repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/view/fragment/setting/ReadPreferenceFragment.kt | 1 | 1301 | package me.ykrank.s1next.view.fragment.setting
import android.content.SharedPreferences
import android.os.Bundle
import com.github.ykrank.androidtools.extension.toast
import me.ykrank.s1next.App.Companion.appComponent
import me.ykrank.s1next.R
import me.ykrank.s1next.data.pref.ReadPreferencesManager
import javax.inject.Inject
/**
* An Activity includes download settings that allow users
* to modify download features and behaviors such as cache
* size and avatars/images download strategy.
*/
class ReadPreferenceFragment : BasePreferenceFragment() {
@Inject
internal lateinit var mReadPreferencesManager: ReadPreferencesManager
override fun onCreatePreferences(bundle: Bundle?, s: String?) {
appComponent.inject(this)
addPreferencesFromResource(R.xml.preference_read)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key == getString(R.string.pref_key_thread_padding)) {
val threadPadding = sharedPreferences.getString(key, null)?.toIntOrNull()
if (threadPadding == null || threadPadding <= 0) {
activity?.toast(R.string.format_error)
}
}
}
companion object {
val TAG = ReadPreferenceFragment::class.java.name
}
} | apache-2.0 | 8c9a2402f35656a2475589d6dfd71a6e | 32.384615 | 95 | 0.72867 | 4.564912 | false | false | false | false |
BjoernPetersen/JMusicBot | src/main/kotlin/net/bjoernpetersen/musicbot/api/module/InstanceStopper.kt | 1 | 4544 | package net.bjoernpetersen.musicbot.api.module
import com.google.inject.ConfigurationException
import com.google.inject.Injector
import com.google.inject.ProvisionException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import net.bjoernpetersen.musicbot.api.plugin.management.PluginFinder
import net.bjoernpetersen.musicbot.spi.loader.ResourceCache
import net.bjoernpetersen.musicbot.spi.loader.SongLoader
import net.bjoernpetersen.musicbot.spi.player.Player
import kotlin.reflect.KClass
private const val CUSTOM_STOPPER_CAPACITY = 32
/**
* Can be used to gracefully shut down an instance of the bot.
*
* In addition to the default set of interfaces, any number of closeable interfaces can be
* registered via [register]. For each of those interfaces, the instance will be loaded from
* the given [injector] and closed.
*
* @param injector an injector to look up all relevant MusicBot instances
*/
class InstanceStopper(private val injector: Injector) {
private val logger = KotlinLogging.logger { }
private var stopped = false
private val additionalBefore: MutableSet<Stopper<*>> = HashSet(CUSTOM_STOPPER_CAPACITY)
private val additionalAfter: MutableSet<Stopper<*>> = HashSet(CUSTOM_STOPPER_CAPACITY)
private suspend fun <T> unstopped(action: suspend () -> T): T {
if (stopped) throw IllegalStateException("stop() has already been called")
return action()
}
private fun <T : Any> KClass<T>.lookup(): T = try {
injector.getInstance(this.java)
} catch (e: ConfigurationException) {
logger.error(e) { "Could not find ${this.qualifiedName}" }
throw IllegalStateException(e)
} catch (e: ProvisionException) {
logger.error(e) { "Could not provide instance of ${this.qualifiedName}" }
throw IllegalStateException(e)
}
private suspend fun <T : Any> KClass<T>.withLookup(action: suspend (T) -> Unit) {
val instance = try {
this.lookup()
} catch (e: IllegalStateException) {
// The lookup method already logged the exception
return
}
action(instance)
}
/**
* Registers an additional [type] to look up via the [injector] and close either before or after
* the instances of all default MusicBot interfaces.
*
* @param type the type for which to look up the implementation and close when [stop] is called
* @param before whether to close the instance before the rest; default: `true`
* @param close will be called to close the instance
*/
fun <T : Any> register(
type: Class<T>,
before: Boolean = true,
close: suspend (T) -> Unit
) = runBlocking<Unit> {
unstopped {
@Suppress("TooGenericExceptionCaught")
val instance = try {
injector.getInstance(type)
} catch (e: RuntimeException) {
throw IllegalArgumentException(e)
}
val set = if (before) additionalBefore else additionalAfter
set.add(Stopper(instance, close))
}
}
private suspend fun close(stopper: Stopper<*>) {
close(stopper) { it() }
}
@Suppress("TooGenericExceptionCaught")
private suspend fun <T : Any> close(instance: T, closer: suspend (T) -> Unit) {
try {
closer(instance)
} catch (e: InterruptedException) {
logger.error(e) { "Interrupted while closing ${instance::class.qualifiedName}" }
throw e
} catch (e: Throwable) {
logger.error(e) { "Could not close ${instance::class.qualifiedName}" }
}
}
/**
* Stops all registered instances.
*/
suspend fun stop(): Unit = unstopped {
withContext(Dispatchers.Default) {
additionalBefore.forEach { close(it) }
Player::class.withLookup { close(it) { it.close() } }
ResourceCache::class.withLookup { close(it) { it.close() } }
SongLoader::class.withLookup { close(it) { it.close() } }
PluginFinder::class.withLookup { finder ->
finder.allPlugins().forEach { close(it) { it.close() } }
}
additionalAfter.forEach { close(it) }
}
stopped = true
}
}
private data class Stopper<T : Any>(
private val instance: T,
private val close: suspend (T) -> Unit
) {
suspend operator fun invoke() = close(instance)
}
| mit | f0912bd7f22531e2c12b038fbdfc53d5 | 34.224806 | 100 | 0.646347 | 4.407371 | false | false | false | false |
jraska/github-client | feature/about/src/main/java/com/jraska/github/client/about/AboutActivity.kt | 1 | 1959 | package com.jraska.github.client.about
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.airbnb.epoxy.EpoxyModel
import com.airbnb.epoxy.SimpleEpoxyAdapter
import com.jraska.github.client.core.android.viewModel
internal class AboutActivity : AppCompatActivity() {
private val viewModel: AboutViewModel by lazy { viewModel(AboutViewModel::class.java) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
setSupportActionBar(findViewById(R.id.toolbar))
val spansCount = 2
val epoxyAdapter = SimpleEpoxyAdapter()
epoxyAdapter.spanCount = spansCount
epoxyAdapter.addModels(createModels())
val layoutManager = GridLayoutManager(this, spansCount)
layoutManager.spanSizeLookup = epoxyAdapter.spanSizeLookup
val aboutRecycler = findViewById<RecyclerView>(R.id.about_recycler)
aboutRecycler.layoutManager = layoutManager
aboutRecycler.adapter = epoxyAdapter
}
private fun createModels(): List<EpoxyModel<*>> {
return listOf(
DescriptionModel(viewModel::onProjectDescriptionClick),
VersionInfoModel(),
IconModel(viewModel::onGithubClick, R.drawable.ic_github_about_48dp, R.string.about_github_description),
IconModel(viewModel::onWebClick, R.drawable.ic_web_48dp, R.string.about_web_description),
IconModel(viewModel::onMediumClick, R.drawable.ic_medium_48dp, R.string.about_medium_description),
IconModel(viewModel::onTwitterClick, R.drawable.ic_twitter_logo_blue_48dp, R.string.about_twitter_description)
)
}
companion object {
fun start(inActivity: Activity) {
val intent = Intent(inActivity, AboutActivity::class.java)
inActivity.startActivity(intent)
}
}
}
| apache-2.0 | fe5f355256ea3211ea63ecd1a3935cb3 | 36.673077 | 116 | 0.774885 | 4.305495 | false | false | false | false |
nickbutcher/plaid | designernews/src/main/java/io/plaidapp/designernews/dagger/StoryModule.kt | 1 | 3331 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.dagger
import androidx.lifecycle.ViewModelProvider
import dagger.Module
import dagger.Provides
import io.plaidapp.core.dagger.scope.FeatureScope
import io.plaidapp.core.data.CoroutinesDispatcherProvider
import io.plaidapp.designernews.data.api.DesignerNewsService
import io.plaidapp.designernews.data.comments.CommentsRemoteDataSource
import io.plaidapp.designernews.data.comments.CommentsRepository
import io.plaidapp.designernews.data.users.UserRemoteDataSource
import io.plaidapp.designernews.data.users.UserRepository
import io.plaidapp.designernews.domain.GetCommentsWithRepliesAndUsersUseCase
import io.plaidapp.designernews.domain.GetStoryUseCase
import io.plaidapp.designernews.domain.PostReplyUseCase
import io.plaidapp.designernews.domain.PostStoryCommentUseCase
import io.plaidapp.designernews.ui.DesignerNewsViewModelFactory
import io.plaidapp.designernews.ui.login.LoginViewModel
import io.plaidapp.designernews.ui.story.StoryActivity
import io.plaidapp.designernews.ui.story.StoryViewModel
import io.plaidapp.designernews.ui.story.StoryViewModelFactory
/**
* Dagger module for [StoryActivity].
*/
@Module
class StoryModule(private val storyId: Long, private val activity: StoryActivity) {
@Provides
fun provideLoginViewModel(
factory: DesignerNewsViewModelFactory
): LoginViewModel =
ViewModelProvider(activity, factory).get(LoginViewModel::class.java)
@Provides
fun provideStoryViewModel(
factory: StoryViewModelFactory
): StoryViewModel =
ViewModelProvider(activity, factory).get(StoryViewModel::class.java)
@Provides
fun provideStoryViewModelFactory(
getStoryUseCase: GetStoryUseCase,
postStoryCommentUseCase: PostStoryCommentUseCase,
postReplyUseCase: PostReplyUseCase,
commentsWithRepliesAndUsersUseCase: GetCommentsWithRepliesAndUsersUseCase,
coroutinesDispatcherProvider: CoroutinesDispatcherProvider
): StoryViewModelFactory =
StoryViewModelFactory(
storyId,
getStoryUseCase,
postStoryCommentUseCase,
postReplyUseCase,
commentsWithRepliesAndUsersUseCase,
coroutinesDispatcherProvider
)
@Provides
@FeatureScope
fun provideUserRepository(dataSource: UserRemoteDataSource): UserRepository =
UserRepository(dataSource)
@Provides
@FeatureScope
fun provideCommentsRemoteDataSource(service: DesignerNewsService): CommentsRemoteDataSource =
CommentsRemoteDataSource(service)
@Provides
@FeatureScope
fun provideCommentsRepository(dataSource: CommentsRemoteDataSource): CommentsRepository =
CommentsRepository(dataSource)
}
| apache-2.0 | 0922aa2e160ca2f156ddb4457e50365a | 36.852273 | 97 | 0.781747 | 4.986527 | false | false | false | false |
nickbutcher/plaid | core/src/main/java/io/plaidapp/core/ui/filter/FilterAdapter.kt | 1 | 3948 | /*
* Copyright 2018 Google LLC.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.ui.filter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import io.plaidapp.core.R
import io.plaidapp.core.ui.filter.FilterHolderInfo.Companion.FILTER_DISABLED
import io.plaidapp.core.ui.filter.FilterHolderInfo.Companion.FILTER_ENABLED
import io.plaidapp.core.ui.filter.FilterHolderInfo.Companion.HIGHLIGHT
import io.plaidapp.core.ui.recyclerview.FilterSwipeDismissListener
private val sourceUiModelDiff = object : DiffUtil.ItemCallback<SourceUiModel>() {
override fun areItemsTheSame(oldItem: SourceUiModel, newItem: SourceUiModel): Boolean {
return oldItem.key == newItem.key
}
override fun areContentsTheSame(oldItem: SourceUiModel, newItem: SourceUiModel): Boolean {
return oldItem == newItem
}
override fun getChangePayload(oldItem: SourceUiModel, newItem: SourceUiModel): Any? {
if (!oldItem.active && newItem.active) {
// filter enabled
return FILTER_ENABLED
}
if (oldItem.active && !newItem.active) {
// filter disabled
return FILTER_DISABLED
}
return null
}
}
/**
* Adapter for showing the list of data sources used as filters for the home grid.
*/
class FilterAdapter : ListAdapter<SourceUiModel, FilterViewHolder>(sourceUiModelDiff), FilterSwipeDismissListener {
init {
setHasStableIds(true)
}
fun highlightPositions(positions: List<Int>) {
positions.forEach {
notifyItemChanged(it, HIGHLIGHT)
}
}
override fun onCreateViewHolder(viewGroup: ViewGroup, viewType: Int): FilterViewHolder {
val holder = FilterViewHolder(
LayoutInflater.from(viewGroup.context)
.inflate(R.layout.filter_item, viewGroup, false)
)
holder.itemView.setOnClickListener {
val position = holder.adapterPosition
val uiModel = getItem(position)
uiModel.onSourceClicked(uiModel)
}
return holder
}
override fun onBindViewHolder(holder: FilterViewHolder, position: Int) {
val filter = getItem(position)
holder.bind(filter)
}
override fun onBindViewHolder(
holder: FilterViewHolder,
position: Int,
partialChangePayloads: List<Any>
) {
if (!partialChangePayloads.isEmpty()) {
// if we're doing a partial re-bind i.e. an item is enabling/disabling or being
// highlighted then data hasn't changed. Just set state based on the payload
val filterEnabled = partialChangePayloads.contains(FILTER_ENABLED)
val filterDisabled = partialChangePayloads.contains(FILTER_DISABLED)
if (filterEnabled || filterDisabled) {
holder.enableFilter(filterEnabled)
// icon is handled by the animator
}
// nothing to do for highlight
} else {
onBindViewHolder(holder, position)
}
}
override fun getItemId(position: Int): Long {
return getItem(position).id.hashCode().toLong()
}
override fun onItemDismiss(position: Int) {
val uiModel = getItem(position)
uiModel.onSourceDismissed(uiModel)
}
}
| apache-2.0 | ffeba2e7d1c8c1201ef2bec14f83aa38 | 34.25 | 115 | 0.678065 | 4.739496 | false | false | false | false |
donald-w/Anki-Android | AnkiDroid/src/main/java/com/ichi2/utils/DatabaseChangeDecorator.kt | 1 | 3548 | /*
Copyright (c) 2020 David Allison <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.utils
import android.content.ContentValues
import android.database.SQLException
import androidx.sqlite.db.SupportSQLiteDatabase
import androidx.sqlite.db.SupportSQLiteStatement
import java.util.*
/** Detects any database modifications and notifies the sync status of the application */
class DatabaseChangeDecorator(val wrapped: SupportSQLiteDatabase) : SupportSQLiteDatabase by wrapped {
private fun markDataAsChanged() {
SyncStatus.markDataAsChanged()
}
private fun needsComplexCheck(): Boolean {
// if we're marked in memory, we can assume no changes - this class only sets the mark.
return !SyncStatus.hasBeenMarkedAsChangedInMemory()
}
private fun checkForChanges(sql: String) {
if (!needsComplexCheck()) {
return
}
val lower = sql.lowercase(Locale.ROOT)
val upper = sql.uppercase(Locale.ROOT)
for (modString in MOD_SQLS) {
if (startsWithIgnoreCase(lower, upper, modString)) {
markDataAsChanged()
break
}
}
}
private fun startsWithIgnoreCase(lowerHaystack: String, upperHaystack: String, needle: String): Boolean {
// Needs to do both according to https://stackoverflow.com/a/38947571
return lowerHaystack.startsWith(needle) || upperHaystack.startsWith(needle.uppercase(Locale.ROOT))
}
override fun compileStatement(sql: String): SupportSQLiteStatement {
val supportSQLiteStatement = wrapped.compileStatement(sql)
checkForChanges(sql) // technically a little hasty - as the statement hasn't been executed.
return supportSQLiteStatement
}
@Throws(SQLException::class)
override fun insert(table: String, conflictAlgorithm: Int, values: ContentValues): Long {
val insert = wrapped.insert(table, conflictAlgorithm, values)
markDataAsChanged()
return insert
}
override fun delete(table: String, whereClause: String, whereArgs: Array<Any>): Int {
val delete = wrapped.delete(table, whereClause, whereArgs)
markDataAsChanged()
return delete
}
override fun update(table: String, conflictAlgorithm: Int, values: ContentValues, whereClause: String?, whereArgs: Array<Any>?): Int {
val update = wrapped.update(table, conflictAlgorithm, values, whereClause, whereArgs)
markDataAsChanged()
return update
}
@Throws(SQLException::class)
override fun execSQL(sql: String) {
wrapped.execSQL(sql)
checkForChanges(sql)
}
@Throws(SQLException::class)
override fun execSQL(sql: String, bindArgs: Array<Any>) {
wrapped.execSQL(sql, bindArgs)
checkForChanges(sql)
}
companion object {
private val MOD_SQLS = arrayOf("insert", "update", "delete")
}
}
| gpl-3.0 | a0f313e1c86918bbb5b7142bc4443d91 | 36.744681 | 138 | 0.700958 | 4.650066 | false | false | false | false |
congwiny/KotlinBasic | src/main/kotlin/com/congwiny/basic/BasicTypes.kt | 1 | 7255 | package com.congwiny.basic
import java.lang.IllegalArgumentException
/**
* Created by congwiny on 2017/6/9.
*/
/**
* 基本类型
* 在Kotlin中,所有东西都是对象,在这个意义上讲,我们可以在任何变量上调用成员函数和属性
* */
/***
* 内置数字类型 6种
* Type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8
* 都是x2
* 注意:在Kotlin中字符不是数字
* */
/**
* 十进制:123 (Long类型用大写)
* 十六进制:0x0F
* 二进制: ob0001001
*
* 注意:Kotlin不支持八进制
* 浮点数
* 默认Double类型:123.4 123.5e10
* Float用f或者F标记: 123.5f
* */
/**
* kotlin支持 "==="
* == (equals) 用于比较判断两者相等
*
===用于严格比较判断两者严格相等
===严格比较,要求进行比较的操作数必须类型一致,不一致时返回flase。
* **/
fun main(args: Array<String>) {
val a: Int = 10000
println(a === a) // 输出“true”
print(a == a) // 输出“true”
val boxedA: Int = a
val anotherBoxedA: Int = a
println(boxedA === anotherBoxedA) // !!!输出“true”!!!
println(boxedA == anotherBoxedA)// !!!输出“true”!!!
val boxedB: Int? = a
val anotherBoxedB: Int? = a
print(boxedB == anotherBoxedB) // !!!输出“true”!!!
print(boxedB === anotherBoxedB) // !!!输出“false”!!!
//显示转换
val c: Byte = 1
// val i:Int = c //错误,较小的类型不能隐式转换为较大的类型
//可以显示转换来拓宽数字
val i: Int = c.toInt()
/**
* 每个数字类型⽀持如下的转换:
c/i.toByte(): Byte
c/i.toShort(): Short
c/i.toInt(): Int
c/i.toLong(): Long
c/i.toFloat(): Float
c/i.toDouble(): Double
c/i.toChar(): Char
*/
//运算时,类型会从上下文推断出来,隐士转换
val l = 1L + 3 //Long +Int -->Long
//运算
/***
* 这是完整的位运算列表(只⽤于 Int 和 Long ):
显式转换
———————
运算
shl(bits) ‒ 有符号左移 (Java 的 << )
shr(bits) ‒ 有符号右移 (Java 的 >> )
ushr(bits) ‒ ⽆符号右移 (Java 的 >>> )
and(bits) ‒ 位与
or(bits) ‒ 位或
xor(bits) ‒ 位异或
inv() ‒ 位⾮
*/
val x = (1 shl 2) and 0x000FF000
//字符
//字符用Char类型表示,他们不能直接当做数字
fun check(c: Char) {
// if(c==1){//错误,类型不兼容
//}
/***
* 字符字面值用单引号括起来
*
* 特殊字符可以⽤反斜杠转义。⽀持这⼏个转义序列:\t 、\b 、\n 、\r 、\' 、\" 、\\ 和 \$ 。
* 编码其他字符要⽤Unicode 转义序列语法:'\uFF00'
*/
if (c == '1') {
}
}
/**
* 布尔。布尔用Boolean类型表示,它有两个值:true和false
* 若需要可空引用,布尔会被装箱
*
* 内置的布尔运算有:
|| ‒ 短路逻辑或
&& ‒ 短路逻辑与
! - 逻辑⾮
*/
//数组--------------------------------------------------------
/**
* 数组在 Kotlin 中使⽤ Array 类来表⽰,
* 它定义了 get 和 set 函数(按照运算符重载约定这会转变为 [] )和 size 属性,
* 以及⼀些其他有⽤的成员函数:
* val size: Int
operator fun get(index: Int): T
operator fun set(index: Int, value: T): Unit
operator fun iterator(): Iterator<T>
*/
// arrayOf() 来创建⼀个数组并传递元素值给它
val arr = arrayOf(10, 20, 30)
println(arr[1]) //20
//可以⽤于创建⼀个指定⼤⼩、元素都为空的数组。
val arrayOfNulls = arrayOfNulls<String>(9)
arrayOfNulls.iterator().forEach { print(it) }
println()
/**
* 另⼀个选项是⽤接受数组⼤⼩和⼀个函数参数的⼯⼚函数,
* ⽤作参数的函数能够返回 给定索引的每个元素初始值:
*/
// 创建⼀个 Array<String> 初始化为 ["0", "1", "4", "9", "16"]
val asc = Array(5, { i -> (i * i).toString() })
asc.iterator().forEach { print(it) }
/**
* 注意: 与 Java 不同的是,Kotlin 中数组是不型变的(invariant)。
* 这意味着 Kotlin 不让我们把 Array<String> 赋值给 Array<Any> ,
* 以防⽌可能的运⾏时失败(但是你可以使⽤ Array<out Any> , 参⻅类型投影)。
*
* Kotlin 也有⽆装箱开销的专⻔的类来表⽰原⽣类型数组: ByteArray 、ShortArray 、IntArray 等等。
* 这些类和 Array 并没有继承关系,但它们有同样的⽅法属性集。
* 它们也都有相应的⼯⼚⽅法:
val x: IntArray = intArrayOf(1, 2, 3)
x[0] = x[1] + x[2]
*/
//字符串--------------------------------------------
/**
* 字符串⽤ String 类型表⽰。字符串是不可变的。
* 字符串的元素⸺字符可以使⽤索引运算符访问: s[i] 。
* 可以⽤ for 循环迭代字符串:
*/
val str = "abcdefg"
for (c in str){
println(c)
}
/**
* Kotlin 有两种类型的字符串字⾯值:
* 转义字符串 ->包含转义字符,转义采用传统的反斜杠方式
*
* 原生字符串 ->可以包含换行和任意文本。使用三个引号(""")分界符括起来,
* 内部没有转义并且可以包含换⾏和任何其他字符
*/
val s = "Hello world!\n"
val text = """
for (c in "foo")
print(c)
"""
println(text)
//你可以通过 trimMargin() 函数去除前导空格:
val text2 = """
|Tell me and I forget.
|Teach me and I remember.
|Involve me and I learn.
|(Benjamin Franklin)
""".trimMargin()
//默认 | ⽤作边界前缀,
// 但你可以选择其他字符并作为参数传⼊,⽐如 trimMargin(">") 。
println(text2)
/**
* 字符串模板
* 字符串可以包含模板表达式 ,即⼀些⼩段代码,会求值并把结果合并到字符串中。
* 模板表达式以美元符( $ )开头,由⼀个简单的名字构成:
*
* 原⽣字符串和转义字符串内部都⽀持模板。
*/
val i1 = 10
val s1 = "i = $i1" // 求值结果为 "i = 10"
//或者⽤花括号扩起来的任意表达式:
val s2 = "abc"
val str1 = "$s2.length is ${s2.length}" // 求值结果为 "abc.length is 3"
//如果你需要在原⽣字符串中表⽰字⾯值 $ 字符(它不⽀持反斜杠转义),
// 你可以⽤下列语法:
val price = """
${'$'}9.99
"""
println(price)
}
//显示把字符转换为Int数字
//当需要可空引⽤时,像数字、字符会被装箱。装箱操作不会保留同⼀性【个人认为是值相等+类型相等】
fun decimalDigitValue(c: Char): Int {
if (c !in '0'..'9')
throw IllegalArgumentException("Out of range")
return c.toInt() - "0".toInt() //显示转换为数字
} | apache-2.0 | 3487e0b2ba178f9f1325d5405b2cf253 | 20.497835 | 72 | 0.504935 | 2.255793 | false | false | false | false |
izmajlowiczl/Expensive | app/src/main/java/pl/expensive/transaction/list/TransactionsActivity.kt | 1 | 4031 | package pl.expensive.transaction.list
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.animation.OvershootInterpolator
import kotlinx.android.synthetic.main.activity_transactions.*
import org.threeten.bp.YearMonth
import pl.expensive.*
import pl.expensive.storage.TransactionDbo
sealed class ViewState {
class Wallets(val adapterData: MutableList<Any>,
val title: CharSequence) : ViewState()
class Empty(val title: CharSequence) : ViewState()
}
class TransactionsActivity : AppCompatActivity(), TransactionListFragment.TransactionListCallbacks {
private val transactionsModel by lazy { Injector.app().transactionsModel() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_transactions)
Injector.app().inject(this)
setSupportActionBar(toolbar)
// Animate FAB only once
startContentAnimation(shouldAnimateFab = savedInstanceState == null)
transactionsModel.showWallets(update)
}
override fun onResume() {
super.onResume()
transactionsFragment().attachCallbacks(this)
}
override fun onPause() {
super.onPause()
transactionsFragment().detachCallbacks()
}
private val update: (ViewState) -> Unit = {
when (it) {
is ViewState.Wallets -> {
transactionsFragment().showTransactions(it.adapterData)
}
is ViewState.Empty -> {
transactionsFragment().showEmpty()
}
}
}
private fun startContentAnimation(shouldAnimateFab: Boolean) {
val createWithdrawalAction: (View) -> Unit = {
startNewTransactionCreatorScreen()
}
with(vCreateTransactionFab) {
if (shouldAnimateFab) {
translationY = 2 * resources.getDimension(R.dimen.fab_size) // Hide below screen
animate() // Pop up from bottom
.translationY(0f)
.setInterpolator(OvershootInterpolator(1f))
.setStartDelay(300)
.setDuration(longAnim().toLong())
.withEndAction {
setOnClickListener(createWithdrawalAction)
}
.start()
} else {
show(true)
setOnClickListener(createWithdrawalAction)
}
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_transactions, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_search -> {
return true
}
else -> return super.onOptionsItemSelected(item)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 666 && resultCode == Activity.RESULT_OK) {
if (data != null && data.hasExtra("message")) {
// Display new transactions including new/updated one
transactionsModel.showWallets(update)
toast(data.getStringExtra("message"))
}
}
}
override fun onTransactionSelected(transaction: TransactionDbo) {
[email protected](transaction)
}
override fun onMonthSelected(month: YearMonth) {
startMonthOverviewScreen(month)
}
private fun transactionsFragment(): TransactionListFragment =
supportFragmentManager.findFragmentById(R.id.vTransactionsListContainer) as TransactionListFragment
}
| gpl-3.0 | 1840657260611336bc3348464d20fd5e | 32.591667 | 111 | 0.632845 | 5.248698 | false | false | false | false |
thanksmister/androidthings-mqtt-alarm-panel | app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/ui/activities/SupportActivity.kt | 1 | 3373 | /*
* Copyright (c) 2018. ThanksMister LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.thanksmister.iot.mqtt.alarmpanel.ui.activities
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.ActionBar
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.Toast
import com.thanksmister.iot.mqtt.alarmpanel.BaseActivity
import com.thanksmister.iot.mqtt.alarmpanel.R
import com.thanksmister.iot.mqtt.alarmpanel.ui.fragments.*
import kotlinx.android.synthetic.main.activity_settings.*
import timber.log.Timber
class SupportActivity : BaseActivity() {
private var actionBar: ActionBar? = null
private val inactivityHandler: Handler = Handler()
private val inactivityCallback = Runnable {
Toast.makeText(this@SupportActivity, getString(R.string.toast_screen_timeout), Toast.LENGTH_LONG).show()
finish()
}
override fun getLayoutId(): Int {
return R.layout.activity_support
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setSupportActionBar(toolbar)
if (supportActionBar != null) {
supportActionBar!!.show()
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
supportActionBar!!.setTitle(R.string.menu_item_help)
actionBar = supportActionBar
}
stopDisconnectTimer()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
override fun onResume() {
super.onResume()
inactivityHandler.postDelayed(inactivityCallback, 300000)
}
override fun onDestroy() {
super.onDestroy()
inactivityHandler.removeCallbacks(inactivityCallback)
}
override fun onUserInteraction() {
inactivityHandler.removeCallbacks(inactivityCallback)
inactivityHandler.postDelayed(inactivityCallback, 300000)
}
/**
* We should close this view if we have no more user activity.
*/
override fun showScreenSaver(manuallySet: Boolean) {
//na-da
}
companion object {
fun createStartIntent(context: Context): Intent {
return Intent(context, SupportActivity::class.java)
}
}
} | apache-2.0 | db59c62245276f184e6f7df9469513b7 | 30.830189 | 112 | 0.716276 | 4.449868 | false | false | false | false |
thanksmister/androidthings-mqtt-alarm-panel | app/src/main/java/com/thanksmister/iot/mqtt/alarmpanel/ui/views/AlarmTriggeredView.kt | 1 | 2152 | /*
* <!--
* ~ Copyright (c) 2017. ThanksMister LLC
* ~
* ~ Licensed under the Apache License, Version 2.0 (the "License");
* ~ you may not use this file except in compliance with the License.
* ~ You may obtain a copy of the License at
* ~
* ~ http://www.apache.org/licenses/LICENSE-2.0
* ~
* ~ Unless required by applicable law or agreed to in writing, software distributed
* ~ under the License is distributed on an "AS IS" BASIS,
* ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* ~ See the License for the specific language governing permissions and
* ~ limitations under the License.
* -->
*/
package com.thanksmister.iot.mqtt.alarmpanel.ui.views
import android.content.Context
import android.os.Handler
import android.text.TextUtils
import android.util.AttributeSet
class AlarmTriggeredView : BaseAlarmView {
var listener: ViewListener? = null
interface ViewListener {
fun onComplete()
fun onError()
}
constructor(context: Context) : super(context) {}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {}
override fun reset() {
codeComplete = false
enteredCode = ""
}
override fun onCancel() {
// na-da
}
override fun addPinCode(code: String) {
if (codeComplete)
return
enteredCode += code
if (enteredCode.length == MAX_CODE_LENGTH) {
codeComplete = true
validateCode(enteredCode)
}
}
override fun removePinCode() {
if (codeComplete) {
return
}
if (!TextUtils.isEmpty(enteredCode)) {
enteredCode = enteredCode.substring(0, enteredCode.length - 1)
}
}
private fun validateCode(validateCode: String) {
val codeInt = validateCode.toInt()
if (codeInt == currentCode) {
if (listener != null) {
listener!!.onComplete()
}
} else {
if (listener != null) {
listener!!.onError()
}
}
reset()
}
} | apache-2.0 | 814e9cc3c8e15cf7c1e60e6a21d1bc57 | 24.630952 | 87 | 0.595725 | 4.244576 | false | false | false | false |
AndroidX/androidx | compose/integration-tests/docs-snippets/src/main/java/androidx/compose/integration/tutorial/Tutorial.kt | 3 | 17155 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// Ignore lint warnings in documentation snippets
@file:Suppress("unused", "UNUSED_PARAMETER")
package androidx.compose.integration.tutorial
import android.content.res.Configuration
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.integration.tutorial.Lesson2_Layouts.Snippet4.MessageCard
import androidx.compose.integration.tutorial.Lesson2_Layouts.Snippet1.Message
import androidx.compose.integration.tutorial.Lesson4_ListsAnimations.Snippet1.Conversation
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
/**
* This file lets DevRel track changes to snippets present in
* https://developer.android.com/jetpack/compose/tutorial
*
* No action required if it's modified.
*/
private object Lesson1_ComposableFunctions {
object Snippet1 {
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
Text("Hello world!")
}
}
}
}
object Snippet2 {
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MessageCard("Android")
}
}
}
@Composable
fun MessageCard(name: String) {
Text(text = "Hello $name!")
}
}
object Snippet3 {
@Composable
fun MessageCard(name: String) {
Text(text = "Hello $name!")
}
@Preview
@Composable
fun PreviewMessageCard() {
MessageCard("Android")
}
}
}
private object Lesson2_Layouts {
object Snippet1 {
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MessageCard(Message("Android", "Jetpack Compose"))
}
}
}
data class Message(val author: String, val body: String)
@Composable
fun MessageCard(msg: Message) {
Text(text = msg.author)
Text(text = msg.body)
}
@Preview
@Composable
fun PreviewMessageCard() {
MessageCard(
msg = Message("Colleague", "Hey, take a look at Jetpack Compose, it's great!")
)
}
}
object Snippet2 {
@Composable
fun MessageCard(msg: Message) {
Column {
Text(text = msg.author)
Text(text = msg.body)
}
}
}
object Snippet3 {
@Composable
fun MessageCard(msg: Message) {
Row {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = "Contact profile picture",
)
Column {
Text(text = msg.author)
Text(text = msg.body)
}
}
}
}
object Snippet4 {
@Composable
fun MessageCard(msg: Message) {
// Add padding around our message
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = "Contact profile picture",
modifier = Modifier
// Set image size to 40 dp
.size(40.dp)
// Clip image to be shaped as a circle
.clip(CircleShape)
)
// Add a horizontal space between the image and the column
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(text = msg.author)
// Add a vertical space between the author and message texts
Spacer(modifier = Modifier.height(4.dp))
Text(text = msg.body)
}
}
}
}
}
private object Lesson3_MaterialDesign {
object Snippet1 {
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTutorialTheme {
MessageCard(Message("Android", "Jetpack Compose"))
}
}
}
}
@Preview
@Composable
fun PreviewMessageCard() {
ComposeTutorialTheme {
MessageCard(
msg = Message("Colleague", "Hey, take a look at Jetpack Compose, it's great!")
)
}
}
}
object Snippet2 {
@Composable
fun MessageCard(msg: Message) {
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = null,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.border(1.5.dp, MaterialTheme.colors.secondary, CircleShape)
)
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(
text = msg.author,
color = MaterialTheme.colors.secondaryVariant
)
Spacer(modifier = Modifier.height(4.dp))
Text(text = msg.body)
}
}
}
}
object Snippet3 {
@Composable
fun MessageCard(msg: Message) {
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = null,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.border(1.5.dp, MaterialTheme.colors.secondary, CircleShape)
)
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(
text = msg.author,
color = MaterialTheme.colors.secondaryVariant,
style = MaterialTheme.typography.subtitle2
)
Spacer(modifier = Modifier.height(4.dp))
Text(
text = msg.body,
style = MaterialTheme.typography.body2
)
}
}
}
}
object Snippet4 {
@Composable
fun MessageCard(msg: Message) {
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = null,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.border(1.5.dp, MaterialTheme.colors.secondary, CircleShape)
)
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(
text = msg.author,
color = MaterialTheme.colors.secondaryVariant,
style = MaterialTheme.typography.subtitle2
)
Spacer(modifier = Modifier.height(4.dp))
Surface(shape = MaterialTheme.shapes.medium, elevation = 1.dp) {
Text(
text = msg.body,
modifier = Modifier.padding(all = 4.dp),
style = MaterialTheme.typography.body2
)
}
}
}
}
object Snippet5 {
@Preview(name = "Light Mode")
@Preview(
uiMode = Configuration.UI_MODE_NIGHT_YES,
showBackground = true,
name = "Dark Mode"
)
@Composable
fun PreviewMessageCard() {
ComposeTutorialTheme {
MessageCard(
msg = Message("Colleague", "Take a look at Jetpack Compose, it's great!")
)
}
}
}
}
}
private object Lesson4_ListsAnimations {
object Snippet1 {
// import androidx.compose.foundation.lazy.items
@Composable
fun Conversation(messages: List<Message>) {
LazyColumn {
items(messages) { message ->
MessageCard(message)
}
}
}
@Preview
@Composable
fun PreviewConversation() {
ComposeTutorialTheme {
val messages = List(15) {
Message("Colleague", "Hey, take a look at Jetpack Compose, it's great!")
}
Conversation(messages)
}
}
}
object Snippet2 {
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeTutorialTheme {
val messages = List(15) {
Message(
"Colleague",
"Hey, take a look at Jetpack Compose, it's great!\n" +
"It's the Android's modern toolkit for building native UI." +
"It simplifies and accelerates UI development on Android." +
"Quickly bring your app to life with less code, powerful " +
"tools, and intuitive Kotlin APIs"
)
}
Conversation(messages)
}
}
}
}
@Composable
fun MessageCard(msg: Message) {
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = null,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.border(1.5.dp, MaterialTheme.colors.secondaryVariant, CircleShape)
)
Spacer(modifier = Modifier.width(8.dp))
// We keep track if the message is expanded or not in this
// variable
var isExpanded by remember { mutableStateOf(false) }
// We toggle the isExpanded variable when we click on this Column
Column(modifier = Modifier.clickable { isExpanded = !isExpanded }) {
Text(
text = msg.author,
color = MaterialTheme.colors.secondaryVariant,
style = MaterialTheme.typography.subtitle2
)
Spacer(modifier = Modifier.height(4.dp))
Surface(
shape = MaterialTheme.shapes.medium,
elevation = 1.dp,
) {
Text(
text = msg.body,
modifier = Modifier.padding(all = 4.dp),
// If the message is expanded, we display all its content
// otherwise we only display the first line
maxLines = if (isExpanded) Int.MAX_VALUE else 1,
style = MaterialTheme.typography.body2
)
}
}
}
}
}
object Snippet4 {
@Composable
fun MessageCard(msg: Message) {
Row(modifier = Modifier.padding(all = 8.dp)) {
Image(
painter = painterResource(R.drawable.profile_picture),
contentDescription = null,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.border(1.5.dp, MaterialTheme.colors.secondaryVariant, CircleShape)
)
Spacer(modifier = Modifier.width(8.dp))
// We keep track if the message is expanded or not in this
// variable
var isExpanded by remember { mutableStateOf(false) }
// surfaceColor will be updated gradually from one color to the other
val surfaceColor: Color by animateColorAsState(
if (isExpanded) MaterialTheme.colors.primary else MaterialTheme.colors.surface,
)
// We toggle the isExpanded variable when we click on this Column
Column(modifier = Modifier.clickable { isExpanded = !isExpanded }) {
Text(
text = msg.author,
color = MaterialTheme.colors.secondaryVariant,
style = MaterialTheme.typography.subtitle2
)
Spacer(modifier = Modifier.height(4.dp))
Surface(
shape = MaterialTheme.shapes.medium,
elevation = 1.dp,
// surfaceColor color will be changing gradually from primary to surface
color = surfaceColor,
// animateContentSize will change the Surface size gradually
modifier = Modifier.animateContentSize().padding(1.dp)
) {
Text(
text = msg.body,
modifier = Modifier.padding(all = 4.dp),
// If the message is expanded, we display all its content
// otherwise we only display the first line
maxLines = if (isExpanded) Int.MAX_VALUE else 1,
style = MaterialTheme.typography.body2
)
}
}
}
}
}
}
// ========================
// Fakes below
// ========================
@Composable
private fun ComposeTutorialTheme(content: @Composable () -> Unit) = MaterialTheme(content = content)
private object R {
object drawable {
const val profile_picture = 1
}
}
@Repeatable
@Retention(AnnotationRetention.SOURCE)
private annotation class Preview(
val name: String = "",
val uiMode: Int = 0,
val showBackground: Boolean = true
)
| apache-2.0 | dad7757b5c7a0e4658f25e5497054e5d | 33.656566 | 100 | 0.510114 | 5.569805 | false | false | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/features/playlist/RecyclerViewPlaylistDetailViewModel.kt | 1 | 4586 | package taiwan.no1.app.ssfm.features.playlist
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.view.View
import com.devrapid.kotlinknifer.glideListener
import com.devrapid.kotlinknifer.palette
import com.devrapid.kotlinknifer.toTimeString
import com.hwangjr.rxbus.RxBus
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.trello.rxlifecycle2.LifecycleProvider
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.features.base.BaseViewModel
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.MUSICPLAYER_STATE_CHANGED
import taiwan.no1.app.ssfm.misc.constants.RxBusTag.VIEWMODEL_TRACK_CLICK
import taiwan.no1.app.ssfm.misc.extension.changeState
import taiwan.no1.app.ssfm.misc.extension.gAlphaIntColor
import taiwan.no1.app.ssfm.misc.extension.gColor
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.MusicPlayerHelper
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playMusic
import taiwan.no1.app.ssfm.misc.utilies.devices.helper.music.playerHelper
import taiwan.no1.app.ssfm.models.entities.PlaylistItemEntity
import taiwan.no1.app.ssfm.models.usecases.AddPlaylistItemCase
import weian.cheng.mediaplayerwithexoplayer.MusicPlayerState
/**
*
* @author jieyi
* @since 11/14/17
*/
class RecyclerViewPlaylistDetailViewModel(private val addPlaylistItemCase: AddPlaylistItemCase,
private var item: PlaylistItemEntity,
private var index: Int) : BaseViewModel() {
val rank by lazy { ObservableField<String>() }
val artistName by lazy { ObservableField<String>() }
val trackName by lazy { ObservableField<String>() }
val thumbnail by lazy { ObservableField<String>() }
val duration by lazy { ObservableField<String>() }
val layoutBackground by lazy { ObservableField<Drawable>() }
val showBackground by lazy { ObservableBoolean() }
val isPlaying by lazy { ObservableBoolean() }
val glideCallback = glideListener<Bitmap> {
onResourceReady = { resource, _, _, _, _ ->
showBackground.set(true)
resource.palette(24).let {
val start = gAlphaIntColor(it.vibrantSwatch?.rgb ?: gColor(R.color.colorSimilarPrimaryDark), 0.45f)
val darkColor = gAlphaIntColor(it.darkVibrantSwatch?.rgb ?: gColor(R.color.colorPrimaryDark), 0.45f)
val background = GradientDrawable(GradientDrawable.Orientation.TL_BR, intArrayOf(start, darkColor))
layoutBackground.set(background)
}
false
}
}
private var clickedIndex = -1
init {
refreshView()
}
//region Lifecycle
override fun <E> onAttach(lifecycleProvider: LifecycleProvider<E>) {
super.onAttach(lifecycleProvider)
RxBus.get().register(this)
}
override fun onDetach() {
RxBus.get().unregister(this)
}
//endregion
fun setPlaylistItem(item: PlaylistItemEntity, index: Int) {
this.item = item
this.index = index
refreshView()
}
/**
* @param view
*
* @event_to [taiwan.no1.app.ssfm.features.playlist.PlaylistDetailFragment.addToPlaylist]
*/
fun trackOnClick(view: View) {
item.let {
// Copy a same object. There are some variables need to modify only.
val playlistEntity = it.copy(id = 0)
lifecycleProvider.playMusic(addPlaylistItemCase, playlistEntity, index)
}
}
@Subscribe(tags = [(Tag(VIEWMODEL_TRACK_CLICK))])
fun changeToStopIcon(uri: String) = isPlaying.set(uri == item.trackUri)
@Subscribe(tags = [Tag(VIEWMODEL_TRACK_CLICK)])
fun notifyClickIndex(index: Integer) {
clickedIndex = index.toInt()
}
/**
* @param state
*
* @event_from [MusicPlayerHelper.setPlayerListener]
*/
@Subscribe(tags = [(Tag(MUSICPLAYER_STATE_CHANGED))])
fun playerStateChanged(state: MusicPlayerState) = isPlaying.changeState(state, index, clickedIndex)
private fun refreshView() {
item.let {
isPlaying.set(playerHelper.isCurrentUri(it.trackUri) && playerHelper.isPlaying)
rank.set(index.toString())
artistName.set(it.artistName)
trackName.set(it.trackName)
duration.set(it.duration.toTimeString())
thumbnail.set(it.coverUrl)
}
}
} | apache-2.0 | 73313f9a1ca1abcbbfa340facab72b23 | 36.598361 | 116 | 0.694287 | 4.314205 | false | false | false | false |
oleksiyp/mockk | mockk/js/src/main/kotlin/io/mockk/impl/JsMockKGateway.kt | 1 | 4551 | package io.mockk.impl
import io.mockk.MockKException
import io.mockk.MockKGateway
import io.mockk.MockKGateway.*
import io.mockk.Ordering
import io.mockk.impl.eval.EveryBlockEvaluator
import io.mockk.impl.eval.ExcludeBlockEvaluator
import io.mockk.impl.eval.VerifyBlockEvaluator
import io.mockk.impl.instantiation.*
import io.mockk.impl.log.JsConsoleLogger
import io.mockk.impl.log.Logger
import io.mockk.impl.log.SafeToString
import io.mockk.impl.recording.*
import io.mockk.impl.recording.states.*
import io.mockk.impl.stub.CommonClearer
import io.mockk.impl.stub.StubGatewayAccess
import io.mockk.impl.stub.StubRepository
import io.mockk.impl.verify.*
import kotlin.reflect.KClass
class JsMockKGateway : MockKGateway {
val safeToString = SafeToString({ commonCallRecorder })
val instanceFactoryRegistryIntrnl = CommonInstanceFactoryRegistry()
override val instanceFactoryRegistry: InstanceFactoryRegistry = instanceFactoryRegistryIntrnl
val stubRepo = StubRepository(safeToString)
val instantiator = JsInstantiator(instanceFactoryRegistryIntrnl)
val anyValueGenerator = AnyValueGenerator()
val signatureValueGenerator = JsSignatureValueGenerator()
override val mockFactory: MockFactory = JsMockFactory(
stubRepo,
instantiator,
StubGatewayAccess({ callRecorder }, anyValueGenerator, stubRepo, safeToString)
)
override val clearer = CommonClearer(stubRepo, safeToString)
override val staticMockFactory: StaticMockFactory
get() = throw UnsupportedOperationException("Static mocks are not supported in JS version")
override val objectMockFactory: ObjectMockFactory
get() = throw UnsupportedOperationException("Object mocks are not supported in JS version")
override val constructorMockFactory: ConstructorMockFactory
get() = throw UnsupportedOperationException("Constructor mocks are not supported in JS version")
override val mockTypeChecker = CommonMockTypeChecker(stubRepo) { false }
override fun verifier(params: VerificationParameters): CallVerifier {
val ordering = params.ordering
val verifier = when (ordering) {
Ordering.UNORDERED -> UnorderedCallVerifier(stubRepo, safeToString)
Ordering.ALL -> AllCallsCallVerifier(stubRepo, safeToString)
Ordering.ORDERED -> OrderedCallVerifier(stubRepo, safeToString)
Ordering.SEQUENCE -> SequenceCallVerifier(stubRepo, safeToString)
}
return if (params.timeout > 0) {
throw UnsupportedOperationException("verification with timeout is not supported for JS")
} else {
verifier
}
}
val callRecorderFactories = CallRecorderFactories(
{ SignatureMatcherDetector(safeToString) { ChainedCallDetector(safeToString) } },
{ CallRoundBuilder(safeToString) },
::ChildHinter,
this::verifier,
{ PermanentMocker(stubRepo, safeToString) },
::VerificationCallSorter,
::AnsweringState,
::StubbingState,
::VerifyingState,
::ExclusionState,
::StubbingAwaitingAnswerState,
::SafeLoggingState
)
override val verificationAcknowledger = CommonVerificationAcknowledger(stubRepo, safeToString)
val commonCallRecorder: CommonCallRecorder = CommonCallRecorder(
stubRepo,
instantiator,
signatureValueGenerator,
mockFactory,
anyValueGenerator,
safeToString,
callRecorderFactories,
{ recorder -> callRecorderFactories.answeringState(recorder) },
verificationAcknowledger
)
override val callRecorder: CallRecorder = commonCallRecorder
override val stubber: Stubber = EveryBlockEvaluator({ callRecorder }, ::AutoHinter)
override val verifier: Verifier = VerifyBlockEvaluator({ callRecorder }, stubRepo, ::AutoHinter)
override val excluder: Excluder = ExcludeBlockEvaluator({ callRecorder }, stubRepo, ::AutoHinter)
override val mockInitializer: MockInitializer
get() = throw MockKException("MockK annotations are not supported in JS")
companion object {
private var log: Logger
init {
Logger.loggerFactory = { cls: KClass<*> -> JsConsoleLogger(cls) }
log = Logger<JsMockKGateway>()
log.trace {
"Starting JavaScript MockK implementation. "
}
}
val defaultImplementation = JsMockKGateway()
val defaultImplementationBuilder = { defaultImplementation }
}
}
| apache-2.0 | 0e52937201a102125124ce0737d49083 | 35.701613 | 104 | 0.721819 | 5.15402 | false | false | false | false |
actions-on-google/appactions-common-biis-kotlin | app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailViewModel.kt | 1 | 4128 | /*
* Copyright (C) 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.android.architecture.blueprints.todoapp.taskdetail
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import androidx.lifecycle.switchMap
import androidx.lifecycle.viewModelScope
import com.example.android.architecture.blueprints.todoapp.Event
import com.example.android.architecture.blueprints.todoapp.R
import com.example.android.architecture.blueprints.todoapp.data.Result
import com.example.android.architecture.blueprints.todoapp.data.Result.Success
import com.example.android.architecture.blueprints.todoapp.data.Task
import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository
import kotlinx.coroutines.launch
/**
* ViewModel for the Details screen.
*/
class TaskDetailViewModel(
private val tasksRepository: TasksRepository
) : ViewModel() {
private val _taskId = MutableLiveData<String>()
private val _task = _taskId.switchMap { taskId ->
tasksRepository.observeTask(taskId).map { computeResult(it) }
}
val task: LiveData<Task?> = _task
val isDataAvailable: LiveData<Boolean> = _task.map { it != null }
private val _dataLoading = MutableLiveData<Boolean>()
val dataLoading: LiveData<Boolean> = _dataLoading
private val _editTaskEvent = MutableLiveData<Event<Unit>>()
val editTaskEvent: LiveData<Event<Unit>> = _editTaskEvent
private val _deleteTaskEvent = MutableLiveData<Event<Unit>>()
val deleteTaskEvent: LiveData<Event<Unit>> = _deleteTaskEvent
private val _snackbarText = MutableLiveData<Event<Int>>()
val snackbarText: LiveData<Event<Int>> = _snackbarText
// This LiveData depends on another so we can use a transformation.
val completed: LiveData<Boolean> = _task.map { input: Task? ->
input?.isCompleted ?: false
}
fun deleteTask() = viewModelScope.launch {
_taskId.value?.let {
tasksRepository.deleteTask(it)
_deleteTaskEvent.value = Event(Unit)
}
}
fun editTask() {
_editTaskEvent.value = Event(Unit)
}
fun setCompleted(completed: Boolean) = viewModelScope.launch {
val task = _task.value ?: return@launch
if (completed) {
tasksRepository.completeTask(task)
showSnackbarMessage(R.string.task_marked_complete)
} else {
tasksRepository.activateTask(task)
showSnackbarMessage(R.string.task_marked_active)
}
}
fun start(taskId: String?) {
// If we're already loading or already loaded, return (might be a config change)
if (_dataLoading.value == true || taskId == _taskId.value) {
return
}
// Trigger the load
_taskId.value = taskId
}
private fun computeResult(taskResult: Result<Task>): Task? {
return if (taskResult is Success) {
taskResult.data
} else {
showSnackbarMessage(R.string.loading_tasks_error)
null
}
}
fun refresh() {
// Refresh the repository and the task will be updated automatically.
_task.value?.let {
_dataLoading.value = true
viewModelScope.launch {
tasksRepository.refreshTask(it.id)
_dataLoading.value = false
}
}
}
private fun showSnackbarMessage(@StringRes message: Int) {
_snackbarText.value = Event(message)
}
}
| apache-2.0 | 504806ca098e031db795614b2583f2c6 | 33.4 | 88 | 0.686773 | 4.496732 | false | false | false | false |
dropbox/Store | app/src/main/java/com/dropbox/android/sample/ui/stream/StreamFragment.kt | 1 | 3714 | package com.dropbox.android.sample.ui.stream
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.dropbox.android.external.store4.Fetcher
import com.dropbox.android.external.store4.MemoryPolicy
import com.dropbox.android.external.store4.StoreBuilder
import com.dropbox.android.external.store4.StoreRequest
import com.dropbox.android.external.store4.fresh
import com.dropbox.android.external.store4.get
import com.dropbox.android.sample.R
import kotlin.coroutines.CoroutineContext
import kotlin.time.ExperimentalTime
import kotlin.time.seconds
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flattenMerge
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.launch
@ExperimentalTime
class StreamFragment : Fragment(), CoroutineScope {
private val get_1: Button get() = requireView().findViewById(R.id.get_1)
private val get_2: Button get() = requireView().findViewById(R.id.get_2)
private val fresh_1: Button get() = requireView().findViewById(R.id.fresh_1)
private val fresh_2: Button get() = requireView().findViewById(R.id.fresh_2)
private val stream_1: TextView get() = requireView().findViewById(R.id.stream_1)
private val stream_2: TextView get() = requireView().findViewById(R.id.stream_2)
private val stream: TextView get() = requireView().findViewById(R.id.stream)
override val coroutineContext: CoroutineContext = Job() + Dispatchers.Main
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_stream, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
var counter = 0
val store = StoreBuilder
.from(
Fetcher.of { key: Int ->
(key * 1000 + counter++).also { delay(1_000) }
}
)
.cachePolicy(
MemoryPolicy
.builder<Any, Any>()
.setExpireAfterWrite(10.seconds)
.build()
)
.build()
get_1.onClick {
store.get(1)
}
fresh_1.onClick {
store.fresh(1)
}
get_2.onClick {
store.get(2)
}
fresh_2.onClick {
store.fresh(2)
}
launch {
store.stream(StoreRequest.cached(1, refresh = false)).collect {
stream_1.text = "Stream 1 $it"
}
}
launch {
store.stream(StoreRequest.cached(2, refresh = false)).collect {
stream_2.text = "Stream 2 $it"
}
}
launch {
flowOf(
store.stream(StoreRequest.cached(1, refresh = false)),
store.stream(StoreRequest.cached(2, refresh = false))
)
.flattenMerge()
.collect {
stream.text = "Stream $it"
}
}
}
fun View.onClick(f: suspend () -> Unit) {
setOnClickListener {
launch {
f()
}
}
}
override fun onDestroy() {
super.onDestroy()
coroutineContext.cancel()
}
}
| apache-2.0 | 7fb74f0ed9d49d20e5e8e876842d4f7e | 28.47619 | 84 | 0.61874 | 4.431981 | false | false | false | false |
pedroSG94/rtmp-rtsp-stream-client-java | encoder/src/main/java/com/pedro/encoder/input/gl/render/MainRender.kt | 1 | 5740 | package com.pedro.encoder.input.gl.render
import android.content.Context
import android.graphics.SurfaceTexture
import android.os.Build
import android.view.Surface
import androidx.annotation.RequiresApi
import com.pedro.encoder.input.gl.FilterAction
import com.pedro.encoder.input.gl.render.filters.BaseFilterRender
/**
* Created by pedro on 20/3/22.
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
class MainRender {
private val cameraRender = CameraRender()
private val screenRender = ScreenRender()
private var width = 0
private var height = 0
private var previewWidth = 0
private var previewHeight = 0
private var context: Context? = null
private var filterRenders: MutableList<BaseFilterRender> = ArrayList()
fun initGl(context: Context, encoderWidth: Int, encoderHeight: Int, previewWidth: Int, previewHeight: Int) {
this.context = context
width = encoderWidth
height = encoderHeight
this.previewWidth = previewWidth
this.previewHeight = previewHeight
cameraRender.initGl(width, height, context, previewWidth, previewHeight)
screenRender.setStreamSize(encoderWidth, encoderHeight)
screenRender.setTexId(cameraRender.texId)
screenRender.initGl(context)
}
fun drawOffScreen() {
cameraRender.draw()
for (baseFilterRender in filterRenders) baseFilterRender.draw()
}
fun drawScreen(width: Int, height: Int, keepAspectRatio: Boolean, mode: Int, rotation: Int,
flipStreamVertical: Boolean, flipStreamHorizontal: Boolean) {
screenRender.draw(width, height, keepAspectRatio, mode, rotation, flipStreamVertical,
flipStreamHorizontal)
}
fun drawScreenEncoder(width: Int, height: Int, isPortrait: Boolean, rotation: Int,
flipStreamVertical: Boolean, flipStreamHorizontal: Boolean) {
screenRender.drawEncoder(width, height, isPortrait, rotation, flipStreamVertical,
flipStreamHorizontal)
}
fun drawScreenPreview(width: Int, height: Int, isPortrait: Boolean, keepAspectRatio: Boolean,
mode: Int, rotation: Int, flipStreamVertical: Boolean, flipStreamHorizontal: Boolean) {
screenRender.drawPreview(width, height, isPortrait, keepAspectRatio, mode, rotation,
flipStreamVertical, flipStreamHorizontal)
}
fun release() {
cameraRender.release()
for (baseFilterRender in filterRenders) baseFilterRender.release()
filterRenders.clear()
screenRender.release()
}
private fun setFilter(position: Int, baseFilterRender: BaseFilterRender) {
val id = filterRenders[position].previousTexId
val renderHandler = filterRenders[position].renderHandler
filterRenders[position].release()
filterRenders[position] = baseFilterRender
filterRenders[position].previousTexId = id
filterRenders[position].initGl(width, height, context, previewWidth, previewHeight)
filterRenders[position].renderHandler = renderHandler
}
private fun addFilter(baseFilterRender: BaseFilterRender) {
filterRenders.add(baseFilterRender)
baseFilterRender.initGl(width, height, context, previewWidth, previewHeight)
baseFilterRender.initFBOLink()
reOrderFilters()
}
private fun addFilter(position: Int, baseFilterRender: BaseFilterRender) {
filterRenders.add(position, baseFilterRender)
baseFilterRender.initGl(width, height, context, previewWidth, previewHeight)
baseFilterRender.initFBOLink()
reOrderFilters()
}
private fun clearFilters() {
for (baseFilterRender in filterRenders) {
baseFilterRender.release()
}
filterRenders.clear()
reOrderFilters()
}
private fun removeFilter(position: Int) {
filterRenders.removeAt(position).release()
reOrderFilters()
}
private fun removeFilter(baseFilterRender: BaseFilterRender) {
baseFilterRender.release()
filterRenders.remove(baseFilterRender)
reOrderFilters()
}
private fun reOrderFilters() {
for (i in filterRenders.indices) {
val texId = if (i == 0) cameraRender.texId else filterRenders[i - 1].texId
filterRenders[i].previousTexId = texId
}
val texId = if (filterRenders.isEmpty()) {
cameraRender.texId
} else {
filterRenders[filterRenders.size - 1].texId
}
screenRender.setTexId(texId)
}
fun setFilterAction(filterAction: FilterAction?, position: Int, baseFilterRender: BaseFilterRender) {
when (filterAction) {
FilterAction.SET -> if (filterRenders.size > 0) {
setFilter(position, baseFilterRender)
} else {
addFilter(baseFilterRender)
}
FilterAction.SET_INDEX -> setFilter(position, baseFilterRender)
FilterAction.ADD -> addFilter(baseFilterRender)
FilterAction.ADD_INDEX -> addFilter(position, baseFilterRender)
FilterAction.CLEAR -> clearFilters()
FilterAction.REMOVE -> removeFilter(baseFilterRender)
FilterAction.REMOVE_INDEX -> removeFilter(position)
else -> {}
}
}
fun filtersCount(): Int {
return filterRenders.size
}
fun setPreviewSize(previewWidth: Int, previewHeight: Int) {
for (i in filterRenders.indices) {
filterRenders[i].setPreviewSize(previewWidth, previewHeight)
}
}
fun enableAA(AAEnabled: Boolean) {
screenRender.isAAEnabled = AAEnabled
}
fun isAAEnabled(): Boolean {
return screenRender.isAAEnabled
}
fun updateFrame() {
cameraRender.updateTexImage()
}
fun getSurfaceTexture(): SurfaceTexture {
return cameraRender.surfaceTexture
}
fun getSurface(): Surface {
return cameraRender.surface
}
fun setCameraRotation(rotation: Int) {
cameraRender.setRotation(rotation)
}
fun setCameraFlip(isFlipHorizontal: Boolean, isFlipVertical: Boolean) {
cameraRender.setFlip(isFlipHorizontal, isFlipVertical)
}
}
| apache-2.0 | cf110e67a2d6b0d81577d644fa866ff1 | 31.429379 | 110 | 0.738676 | 4.153401 | false | false | false | false |
inorichi/tachiyomi-extensions | multisrc/src/main/java/eu/kanade/tachiyomi/multisrc/weebreader/WeebreaderGenerator.kt | 1 | 710 | package eu.kanade.tachiyomi.multisrc.weebreader
import generator.ThemeSourceData.SingleLang
import generator.ThemeSourceGenerator
class WeebreaderGenerator : ThemeSourceGenerator {
override val themePkg = "weebreader"
override val themeClass = "Weebreader"
override val baseVersionCode: Int = 1
override val sources = listOf(
SingleLang("Arang Scans", "https://arangscans.com", "en", overrideVersionCode = 10),
SingleLang("NANI? Scans", "https://naniscans.com", "en", overrideVersionCode = 6, className = "NaniScans"),
)
companion object {
@JvmStatic
fun main(args: Array<String>) {
WeebreaderGenerator().createAll()
}
}
}
| apache-2.0 | a4f48e530d3e2372722bbfb9af758fef | 27.4 | 115 | 0.684507 | 4.152047 | false | false | false | false |
SiimKinks/sqlitemagic | sqlitemagic-tests/app/src/androidTest/kotlin/com/siimkinks/sqlitemagic/model/insert/Inserts.kt | 1 | 1634 | package com.siimkinks.sqlitemagic.model.insert
import com.google.common.truth.Truth.assertThat
import com.siimkinks.sqlitemagic.Select
import com.siimkinks.sqlitemagic.model.TestModel
import com.siimkinks.sqlitemagic.model.TestModelWithUniqueColumn
import com.siimkinks.sqlitemagic.model.TestUtil.assertTableCount
import com.siimkinks.sqlitemagic.model.insertNewRandom
import java.util.concurrent.atomic.AtomicInteger
fun <T> assertInsertSuccess(): (TestModel<T>, T, Long) -> Unit = { model, testVal, id ->
assertTableCount(1L, model.table)
assertThat(id).isNotEqualTo(-1)
val dbVal = Select.from(model.table).queryDeep().takeFirst().execute()
assertThat(dbVal).isNotNull()
assertThat(model.valsAreEqual(testVal, dbVal!!)).isTrue()
}
fun <T> assertEarlyUnsubscribeFromInsertRollbackedAllValues(): (TestModel<T>, List<T>, AtomicInteger) -> Unit = { model, _, eventsCount ->
val countInDb = Select
.from(model.table)
.count()
.execute()
assertThat(countInDb).isEqualTo(0L)
assertThat(eventsCount.get()).isEqualTo(0)
}
fun <T> assertEarlyUnsubscribeFromInsertStoppedAnyFurtherWork(): (TestModel<T>, List<T>, AtomicInteger) -> Unit = { model, _, eventsCount ->
val countInDb = Select
.from(model.table)
.count()
.execute()
assertThat(countInDb).isGreaterThan(0L)
assertThat(countInDb).isLessThan(500)
assertThat(eventsCount.get()).isEqualTo(0)
}
fun <T> newFailingByUniqueConstraint(): (TestModel<T>) -> T = {
val model = it as TestModelWithUniqueColumn
val (v1) = insertNewRandom(model)
val newRandom = model.newRandom()
(model).transferUniqueVal(v1, newRandom)
}
| apache-2.0 | e7f79fbae9c54d11458182d6d5af0882 | 37 | 140 | 0.749082 | 3.817757 | false | true | false | false |
ZieIony/Carbon | carbon/src/main/java/carbon/widget/MenuStrip.kt | 1 | 12776 | package carbon.widget
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.drawable.Drawable
import android.os.Parcel
import android.os.Parcelable
import android.util.AttributeSet
import android.view.Gravity
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import androidx.core.view.MenuItemCompat
import carbon.Carbon
import carbon.R
import carbon.component.LayoutComponent
import carbon.databinding.CarbonMenustripItemBinding
import carbon.databinding.CarbonMenustripItemCheckableBinding
import carbon.databinding.CarbonMenustripToolsItemBinding
import carbon.databinding.CarbonMenustripToolsItemCheckableBinding
import carbon.drawable.CheckedState
import carbon.drawable.ColorStateListFactory
import carbon.recycler.DividerItemDecoration
import carbon.recycler.RowArrayAdapter
import carbon.recycler.RowFactory
import carbon.view.SelectionMode
import java.io.Serializable
open class MenuStrip : RecyclerView {
open class Item : Serializable {
var id = 0
var icon: Drawable? = null
var title: CharSequence? = null
var iconTintList: ColorStateList? = null
var groupId = 0
var isEnabled = true
var isVisible = true
constructor()
constructor(id: Int, icon: Drawable, text: CharSequence) {
this.id = id
this.icon = icon
this.title = text
}
constructor(menuItem: MenuItem) {
id = menuItem.itemId
try { // breaks preview
this.icon = menuItem.icon
} catch (e: Exception) {
}
this.title = menuItem.title
iconTintList = MenuItemCompat.getIconTintList(menuItem)
groupId = menuItem.groupId
isEnabled = menuItem.isEnabled
isVisible = menuItem.isVisible
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Item
if (id != other.id) return false
if (title != other.title) return false
if (groupId != other.groupId) return false
return true
}
override fun hashCode(): Int {
var result = id
result = 31 * result + (title?.hashCode() ?: 0)
result = 31 * result + groupId
return result
}
}
open class CheckableItem : Item {
var isChecked: Boolean = false
constructor()
constructor(id: Int, icon: Drawable, text: CharSequence) : super(id, icon, text)
constructor(menuItem: MenuItem) : super(menuItem) {
isChecked = menuItem.isChecked
}
}
class ItemComponent(val parent: ViewGroup) : LayoutComponent<Item>(parent, R.layout.carbon_menustrip_item) {
private val binding = CarbonMenustripItemBinding.bind(view)
override fun bind(data: Item) {
with(binding) {
root.id = data.id
root.isEnabled = data.isEnabled
carbonIcon.setImageDrawable(data.icon)
carbonIcon.setTintList(data.iconTintList
?: ColorStateListFactory.makeIcon(parent.context))
carbonText.text = data.title
carbonText.textColor = data.iconTintList
?: ColorStateListFactory.makePrimaryText(parent.context)
}
}
}
class CheckableItemComponent(val parent: ViewGroup) : LayoutComponent<CheckableItem>(parent, R.layout.carbon_menustrip_item_checkable) {
private val binding = CarbonMenustripItemCheckableBinding.bind(view)
override fun bind(data: CheckableItem) {
with(binding) {
root.id = data.id
root.isEnabled = data.isEnabled
carbonCheckBox.isChecked = data.isChecked
carbonCheckBox.setTintList(data.iconTintList
?: ColorStateListFactory.makeIcon(parent.context))
carbonCheckBox.text = data.title.toString()
carbonCheckBox.setTextColor(data.iconTintList
?: ColorStateListFactory.makePrimaryText(parent.context))
carbonCheckBox.setOnCheckedChangeListener { _, isChecked -> data.isChecked = isChecked == CheckedState.CHECKED }
}
}
}
class ToolItemComponent(val parent: ViewGroup) : LayoutComponent<Item>(parent, R.layout.carbon_menustrip_tools_item) {
private val binding = CarbonMenustripToolsItemBinding.bind(view)
override fun bind(data: Item) {
with(binding) {
root.id = data.id
root.isEnabled = data.isEnabled
try {
root.tooltipText = data.title
} catch (e: java.lang.Exception) {
}
carbonIcon.setImageDrawable(data.icon)
carbonIcon.setTintList(data.iconTintList
?: ColorStateListFactory.makeIcon(parent.context))
}
}
}
class CheckableToolItemComponent(val parent: ViewGroup) : LayoutComponent<CheckableItem>(parent, R.layout.carbon_menustrip_tools_item_checkable) {
private val binding = CarbonMenustripToolsItemCheckableBinding.bind(view)
override fun bind(data: CheckableItem) {
with(binding) {
root.id = data.id
root.isEnabled = data.isEnabled
try {
root.tooltipText = data.title
} catch (e: java.lang.Exception) {
}
carbonCheckBox.isChecked = data.isChecked
carbonCheckBox.setTintList(data.iconTintList
?: ColorStateListFactory.makeIcon(parent.context))
carbonCheckBox.setOnCheckedChangeListener { _, isChecked -> data.isChecked = isChecked == CheckedState.CHECKED }
}
}
}
@Deprecated("Use itemFactory instead")
var itemLayoutId: Int = 0
open fun <ItemType : Item> putFactory(type: Class<ItemType>, factory: RowFactory<ItemType>) {
adapter.putFactory(type, factory)
}
private lateinit var _itemFactory: RowFactory<Item>
var itemFactory: RowFactory<Item>
get() = _itemFactory
set(value) {
adapter.putFactory(Item::class.java, value)
_itemFactory = value
}
private lateinit var _checkableItemFactory: RowFactory<CheckableItem>
var checkableItemFactory: RowFactory<CheckableItem>
get() = _checkableItemFactory
set(value) {
adapter.putFactory(CheckableItem::class.java, value)
_checkableItemFactory = value
}
private lateinit var _orientation: carbon.view.Orientation
var orientation: carbon.view.Orientation
get() = _orientation
set(value) {
_orientation = value
initItems()
}
var adapter: RowArrayAdapter<Item> = RowArrayAdapter()
var selectionMode: SelectionMode
get() = adapter.selectionMode
set(value) {
adapter.selectionMode = value
}
private var _onItemClickedListener: OnItemClickedListener<Item>? = null
var onItemClickedListener
get() = _onItemClickedListener
set(value) {
_onItemClickedListener = value
initItems()
}
private var items: Array<Item>? = null
var menuItems: Array<Item>?
get() = items
set(value) {
this.items = value
initItems()
}
var selectedItems: List<Item>
get() = adapter.selectedItems
set(value) {
adapter.selectedItems = value
initItems()
}
var selectedIndices: List<Int>
get() = adapter.selectedIndices
set(value) {
adapter.selectedIndices = value
initItems()
}
constructor(context: Context) : super(context, null, R.attr.carbon_menuStripStyle) {
initMenuStrip(null, R.attr.carbon_menuStripStyle)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs, R.attr.carbon_menuStripStyle) {
initMenuStrip(attrs, R.attr.carbon_menuStripStyle)
}
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
initMenuStrip(attrs, defStyleAttr)
}
private fun initMenuStrip(attrs: AttributeSet?, defStyleAttr: Int) {
val a = context.obtainStyledAttributes(attrs, R.styleable.MenuStrip, defStyleAttr, R.style.carbon_MenuStrip)
orientation = carbon.view.Orientation.values()[a.getInt(R.styleable.MenuStrip_android_orientation, carbon.view.Orientation.VERTICAL.ordinal)]
checkableItemFactory = RowFactory { CheckableItemComponent(this) }
itemFactory = RowFactory { ItemComponent(this) }
selectionMode = SelectionMode.values()[a.getInt(R.styleable.MenuStrip_carbon_selectionMode, SelectionMode.NONE.ordinal)]
val menuId = a.getResourceId(R.styleable.MenuStrip_carbon_menu, 0)
if (menuId != 0)
setMenu(menuId)
a.recycle()
}
fun setMenu(resId: Int) = setMenu(Carbon.getMenu(context, resId))
fun setMenu(menu: Menu) {
items = (0 until menu.size()).map {
val item = menu.getItem(it)
if (item.isCheckable || item.isChecked) CheckableItem(item) else Item(item)
}.toTypedArray()
initItems()
}
fun getItem(id: Int) = items?.find { it.id == id }
private fun initItems() {
initAdapter()
refresh()
}
private fun initAdapter() {
val vertical = orientation == carbon.view.Orientation.VERTICAL
layoutManager = LinearLayoutManager(context, if (vertical) LinearLayoutManager.VERTICAL else LinearLayoutManager.HORIZONTAL, false, Gravity.CENTER)
adapter.setOnItemClickedListener(onItemClickedListener)
setAdapter(adapter)
}
fun refresh() {
items?.let {
adapter.items = it.filter { it.isVisible }.toTypedArray()
}
}
override fun setDivider(divider: Drawable?, height: Int): DividerItemDecoration? {
val decoration = super.setDivider(divider, height)
decoration.setDrawBefore { i ->
val items = this.items
items != null && i > 0 && (items[i].groupId != items[i - 1].groupId)
}
return decoration
}
public override fun onSaveInstanceState(): Parcelable? {
//begin boilerplate code that allows parent classes to save state
val superState = super.onSaveInstanceState()
val ss = SavedState(superState)
//end
ss.selectedIndices = ArrayList(selectedIndices)
return ss
}
public override fun onRestoreInstanceState(state: Parcelable) {
//begin boilerplate code so parent classes can restore state
if (state !is SavedState) {
super.onRestoreInstanceState(state)
return
}
super.onRestoreInstanceState(state.superState)
//end
selectedIndices = state.selectedIndices
}
private open class SavedState : Parcelable {
lateinit var selectedIndices: ArrayList<Int>
var superState: Parcelable? = null
constructor() {
superState = null
}
constructor(superState: Parcelable?) {
this.superState = if (superState !== EMPTY_STATE) superState else null
}
private constructor(parcel: Parcel) {
val superState = parcel.readParcelable<Parcelable>(BottomNavigationView::class.java.classLoader)
this.superState = superState ?: EMPTY_STATE
this.selectedIndices = parcel.readSerializable() as ArrayList<Int>
}
override fun describeContents(): Int = 0
override fun writeToParcel(out: Parcel, flags: Int) {
out.writeParcelable(superState, flags)
out.writeSerializable(this.selectedIndices)
}
companion object {
val EMPTY_STATE: SavedState = object : MenuStrip.SavedState() {
}
//required field that makes Parcelables from a Parcel
@JvmField
val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(`in`: Parcel): SavedState {
return SavedState(`in`)
}
override fun newArray(size: Int): Array<SavedState?> {
return arrayOfNulls(size)
}
}
}
}
}
| apache-2.0 | 020401837d481d1a6cc85ef32fe8f1c9 | 33.252011 | 155 | 0.62226 | 4.911957 | false | false | false | false |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/tutionfees/TuitionFeeManager.kt | 1 | 2450 | package de.tum.`in`.tumcampusapp.component.tumui.tutionfees
import android.content.Context
import de.tum.`in`.tumcampusapp.api.tumonline.CacheControl
import de.tum.`in`.tumcampusapp.api.tumonline.TUMOnlineClient
import de.tum.`in`.tumcampusapp.component.notifications.NotificationScheduler
import de.tum.`in`.tumcampusapp.component.notifications.ProvidesNotifications
import de.tum.`in`.tumcampusapp.component.notifications.persistence.NotificationType
import de.tum.`in`.tumcampusapp.component.tumui.tutionfees.model.Tuition
import de.tum.`in`.tumcampusapp.component.ui.overview.card.Card
import de.tum.`in`.tumcampusapp.component.ui.overview.card.ProvidesCard
import de.tum.`in`.tumcampusapp.utils.Utils
import java.io.IOException
import java.util.*
/**
* Tuition manager, handles tuition card
*/
class TuitionFeeManager(private val context: Context) : ProvidesCard, ProvidesNotifications {
override fun getCards(cacheControl: CacheControl): List<Card> {
val results = ArrayList<Card>()
val tuition = loadTuition(cacheControl) ?: return results
val card = TuitionFeesCard(context, tuition)
card.getIfShowOnStart()?.let { results.add(it) }
return results
}
override fun hasNotificationsEnabled(): Boolean {
return Utils.getSettingBool(context, "card_tuition_fee_phone", true)
}
fun loadTuition(cacheControl: CacheControl): Tuition? {
try {
val response = TUMOnlineClient
.getInstance(context)
.getTuitionFeesStatus(cacheControl)
.execute()
if (!response.isSuccessful) {
return null
}
val tuitionList = response.body()
if (tuitionList == null || tuitionList.tuitions.isEmpty()) {
return null
}
val tuition = tuitionList.tuitions[0]
if (!tuition.isPaid && hasNotificationsEnabled()) {
scheduleNotificationAlarm(tuition)
}
return tuition
} catch (e: IOException) {
Utils.log(e)
return null
}
}
private fun scheduleNotificationAlarm(tuition: Tuition) {
val notificationTime = TuitionNotificationScheduler.getNextNotificationTime(tuition)
val scheduler = NotificationScheduler(context)
scheduler.scheduleAlarm(NotificationType.TUITION_FEES, notificationTime)
}
}
| gpl-3.0 | 211a0b90f51cc6addde5b473c3f17b04 | 36.692308 | 93 | 0.68 | 4.43038 | false | false | false | false |
HabitRPG/habitica-android | wearos/src/main/java/com/habitrpg/wearos/habitica/ui/viewmodels/LoginViewModel.kt | 1 | 6874 | package com.habitrpg.wearos.habitica.ui.viewmodels
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import androidx.activity.result.ActivityResultLauncher
import androidx.core.content.edit
import androidx.lifecycle.viewModelScope
import com.google.android.gms.auth.GoogleAuthException
import com.google.android.gms.auth.GoogleAuthUtil
import com.google.android.gms.auth.GooglePlayServicesAvailabilityException
import com.google.android.gms.auth.UserRecoverableAuthException
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.GoogleApiAvailability
import com.google.android.gms.common.GooglePlayServicesUtil
import com.google.android.gms.common.Scopes
import com.google.android.gms.common.UserRecoverableException
import com.google.android.gms.common.api.ApiException
import com.google.android.gms.tasks.Task
import com.habitrpg.common.habitica.helpers.KeyHelper
import com.habitrpg.common.habitica.models.auth.UserAuth
import com.habitrpg.common.habitica.models.auth.UserAuthResponse
import com.habitrpg.common.habitica.models.auth.UserAuthSocial
import com.habitrpg.common.habitica.models.auth.UserAuthSocialTokens
import com.habitrpg.wearos.habitica.data.ApiClient
import com.habitrpg.wearos.habitica.data.repositories.TaskRepository
import com.habitrpg.wearos.habitica.data.repositories.UserRepository
import com.habitrpg.wearos.habitica.managers.AppStateManager
import com.habitrpg.wearos.habitica.util.ExceptionHandlerBuilder
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.IOException
import javax.inject.Inject
@HiltViewModel
class LoginViewModel @Inject constructor(userRepository: UserRepository,
taskRepository: TaskRepository,
exceptionBuilder: ExceptionHandlerBuilder,
private val keyHelper: KeyHelper?,
val sharedPreferences: SharedPreferences,
val apiClient: ApiClient, appStateManager: AppStateManager
) : BaseViewModel(userRepository, taskRepository, exceptionBuilder, appStateManager) {
lateinit var onLoginCompleted: () -> Unit
fun handleGoogleLogin(
activity: Activity,
pickAccountResult: ActivityResultLauncher<Intent>
) {
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestEmail()
.build()
val client = GoogleSignIn.getClient(activity, gso)
pickAccountResult.launch(client.signInIntent)
}
fun handleGoogleLoginResult(
activity: Activity,
task: Task<GoogleSignInAccount>,
recoverFromPlayServicesErrorResult: ActivityResultLauncher<Intent>?,
) {
viewModelScope.launch(exceptionBuilder.userFacing(this)) {
val account = async {
try {
return@async task.getResult(
ApiException::class.java
)
} catch (e: IOException) {
return@async null
} catch (e: GoogleAuthException) {
if (recoverFromPlayServicesErrorResult != null) {
handleGoogleAuthException(e, activity, recoverFromPlayServicesErrorResult)
}
return@async null
} catch (e: UserRecoverableException) {
return@async null
}
}.await()
val scopesString = Scopes.PROFILE + " " + Scopes.EMAIL
val scopes = "oauth2:$scopesString"
val token = withContext(Dispatchers.IO) {
account?.account?.let { GoogleAuthUtil.getToken(activity, it, scopes) }
}
val auth = UserAuthSocial()
auth.network = "google"
auth.authResponse = UserAuthSocialTokens()
auth.authResponse?.client_id = account?.email
auth.authResponse?.access_token = token
val response = apiClient.loginSocial(auth)
handleAuthResponse(response.responseData)
}
}
private fun handleGoogleAuthException(
e: Exception,
activity: Activity,
recoverFromPlayServicesErrorResult: ActivityResultLauncher<Intent>
) {
if (e is GooglePlayServicesAvailabilityException) {
GoogleApiAvailability.getInstance()
GooglePlayServicesUtil.showErrorDialogFragment(
e.connectionStatusCode,
activity,
null,
REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR
) {
}
return
} else if (e is UserRecoverableAuthException) {
// Unable to authenticate, such as when the user has not yet granted
// the app access to the account, but the user can fix this.
// Forward the user to an activity in Google Play services.
val intent = e.intent
recoverFromPlayServicesErrorResult.launch(intent)
return
}
}
private suspend fun handleAuthResponse(userAuthResponse: UserAuthResponse?) {
if (userAuthResponse == null) return
try {
saveTokens(userAuthResponse.apiToken, userAuthResponse.id)
} catch (e: Exception) {
return
}
val user = userRepository.retrieveUser(true)
taskRepository.retrieveTasks(user?.tasksOrder, true)
onLoginCompleted()
}
@Throws(Exception::class)
private fun saveTokens(api: String, user: String) {
this.apiClient.updateAuthenticationCredentials(user, api)
sharedPreferences.edit {
putString("UserID", user)
val encryptedKey =
try {
keyHelper?.encrypt(api)
} catch (e: Exception) {
null
}
if ((encryptedKey?.length ?: 0) > 5) {
putString(user, encryptedKey)
} else {
// Something might have gone wrong with encryption, so fall back to this.
putString("APIToken", api)
}
}
}
fun login(username: String, password: String, onResult: (Boolean) -> Unit) {
viewModelScope.launch(exceptionBuilder.userFacing(this)) {
val response = apiClient.loginLocal(UserAuth(username, password)).responseData
handleAuthResponse(response)
onResult(response?.id != null)
}.invokeOnCompletion {
onResult(it == null)
}
}
companion object {
private const val REQUEST_CODE_RECOVER_FROM_PLAY_SERVICES_ERROR = 1001
}
}
| gpl-3.0 | 3e033a0822cd62bb0a4024022b929cd8 | 39.916667 | 98 | 0.671079 | 5.043287 | false | false | false | false |
qklabs/qksms | android-smsmms/src/main/java/com/klinker/android/send_message/Settings.kt | 3 | 1068 | /*
* Copyright 2013 Jacob Klinker
*
* 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.klinker.android.send_message
/**
* Class to house all of the settings that can be used to send a message
*/
class Settings @JvmOverloads constructor(
// MMS options
var mmsc: String? = "",
var proxy: String? = "",
var port: String? = "0",
var agent: String? = "",
var userProfileUrl: String? = "",
var uaProfTagName: String? = "",
// SMS options
var stripUnicode: Boolean = false)
| gpl-3.0 | 0ea94967f09f030d2fd53fae88ad2cd0 | 32.375 | 75 | 0.668539 | 4.139535 | false | false | false | false |
InsertKoinIO/koin | examples/androidx-samples/src/main/java/org/koin/sample/androidx/mvp/MVPActivity.kt | 1 | 2100 | package org.koin.sample.androidx.mvp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.mvp_activity.*
import org.koin.android.ext.android.get
import org.koin.android.ext.android.getKoin
import org.koin.android.ext.android.inject
import org.koin.android.scope.AndroidScopeComponent
import org.koin.androidx.scope.ScopeActivity
import org.koin.androidx.scope.activityRetainedScope
import org.koin.androidx.scope.activityScope
import org.koin.androidx.scope.createActivityRetainedScope
import org.koin.core.parameter.parametersOf
import org.koin.core.scope.Scope
import org.koin.sample.android.R
import org.koin.sample.androidx.components.ID
import org.koin.sample.androidx.components.mvp.FactoryPresenter
import org.koin.sample.androidx.components.mvp.ScopedPresenter
import org.koin.sample.androidx.mvvm.MVVMActivity
import org.koin.sample.androidx.utils.navigateTo
class MVPActivity : AppCompatActivity(R.layout.mvp_activity), AndroidScopeComponent {
override val scope: Scope by activityScope()
// Inject presenter as Factory
val factoryPresenter: FactoryPresenter by inject { parametersOf(ID) }
// Inject presenter from MVPActivity's scope
val scopedPresenter: ScopedPresenter by inject { parametersOf(ID) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
assert(factoryPresenter.id == scopedPresenter.id)
assert(factoryPresenter.service == scopedPresenter.service)
assert(get<FactoryPresenter> { parametersOf(ID) } != factoryPresenter)
assert(scope.get<ScopedPresenter>() == scopedPresenter)
title = "Android MVP"
mvp_button.setOnClickListener {
navigateTo<MVVMActivity>(isRoot = true, extras =
mapOf(
"vm1" to "value to stateViewModel",
"id" to "vm1"
)
)
}
val my_int = 42
getKoin().setProperty("my_int", my_int)
assert(my_int == getKoin().getProperty<Int>("my_int"))
}
} | apache-2.0 | 454d0cfc1d41159970d934541c4b6834 | 35.224138 | 85 | 0.730476 | 4.216867 | false | false | false | false |
NerdNumber9/TachiyomiEH | app/src/main/java/exh/ui/migration/manga/design/MigrationSourceHolder.kt | 1 | 1316 | package exh.ui.migration.manga.design
import android.view.View
import eu.davidea.flexibleadapter.FlexibleAdapter
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.ui.base.holder.BaseFlexibleViewHolder
import eu.kanade.tachiyomi.util.getRound
import kotlinx.android.synthetic.main.eh_source_item.*
import android.graphics.Paint.STRIKE_THRU_TEXT_FLAG
class MigrationSourceHolder(view: View, val adapter: FlexibleAdapter<MigrationSourceItem>):
BaseFlexibleViewHolder(view, adapter) {
init {
setDragHandleView(reorder)
}
fun bind(source: HttpSource, sourceEnabled: Boolean) {
// Set capitalized title.
title.text = source.name.capitalize()
// Update circle letter image.
itemView.post {
image.setImageDrawable(image.getRound(source.name.take(1).toUpperCase(),false))
}
if(sourceEnabled) {
title.alpha = 1.0f
image.alpha = 1.0f
title.paintFlags = title.paintFlags and STRIKE_THRU_TEXT_FLAG.inv()
} else {
title.alpha = DISABLED_ALPHA
image.alpha = DISABLED_ALPHA
title.paintFlags = title.paintFlags or STRIKE_THRU_TEXT_FLAG
}
}
companion object {
private const val DISABLED_ALPHA = 0.3f
}
} | apache-2.0 | af3959d73b869aa351fcb92a5dde9788 | 31.925 | 91 | 0.680091 | 4.245161 | false | false | false | false |
haozileung/test | src/main/kotlin/com/haozileung/infra/web/BaseServlet.kt | 1 | 3368 | package com.haozileung.infra.web;
import com.alibaba.fastjson.JSON
import com.google.common.base.Strings
import com.google.inject.Injector
import org.beetl.ext.servlet.ServletGroupTemplate
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.PrintWriter
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
abstract class BaseServlet : HttpServlet() {
private final val logger: Logger = LoggerFactory.getLogger(BaseServlet::class.java);
override fun init() {
(Initializer.instance as Injector).injectMembers(this);
}
fun renderView(code: Int, view: String, req: HttpServletRequest, resp: HttpServletResponse) {
resp.contentType = "text/html;charset=utf-8";
resp.status = code;
if (!Strings.isNullOrEmpty(view)) {
try {
ServletGroupTemplate.instance().render(view, req, resp);
} catch (e: Exception) {
logger.error(e.message, e);
try {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
} catch (e1: IOException) {
logger.error(e1.message, e1);
}
}
}
}
fun renderJSON(code: Int, data: Any?, resp: HttpServletResponse) {
resp.contentType = "application/json;charset=utf-8";
resp.status = code;
try {
var pr: PrintWriter = resp.writer;
pr.print(JSON.toJSONString(data));
pr.flush();
} catch (e: IOException) {
logger.error(e.message, e);
}
}
fun render(result: Any?, req: HttpServletRequest, resp: HttpServletResponse) {
if (result != null) {
if (result is String) {
if (result.startsWith("redirect:")) {
val v = result.replace("redirect:", "");
try {
resp.sendRedirect(v);
} catch (e: IOException) {
logger.error(e.message, e);
}
}
renderView(resp.status, result, req, resp);
} else {
renderJSON(resp.status, result, resp);
}
}
}
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
val obj: Any = get(req, resp);
render(obj, req, resp);
}
override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
val obj: Any = get(req, resp);
render(obj, req, resp);
}
override fun doPut(req: HttpServletRequest, resp: HttpServletResponse) {
val obj: Any = get(req, resp);
render(obj, req, resp);
}
override fun doDelete(req: HttpServletRequest, resp: HttpServletResponse) {
val obj: Any = get(req, resp);
render(obj, req, resp);
}
open fun get(req: HttpServletRequest, resp: HttpServletResponse): Any {
return Any();
}
open fun post(req: HttpServletRequest, resp: HttpServletResponse): Any {
return Any();
}
open fun put(req: HttpServletRequest, resp: HttpServletResponse): Any {
return Any();
}
open fun delete(req: HttpServletRequest, resp: HttpServletResponse): Any {
return Any();
}
} | mit | eeb09399bbbe79fa6d16ccd1550eeedd | 30.783019 | 97 | 0.585214 | 4.431579 | false | false | false | false |
Heiner1/AndroidAPS | app/src/test/java/info/nightscout/androidaps/plugins/constraints/versionChecker/AllowedVersionsTest.kt | 1 | 3914 | package info.nightscout.androidaps.plugins.constraints.versionChecker
import org.joda.time.LocalDate
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
class AllowedVersionsTest {
fun generateSupportedVersions(): String =
JSONArray()
// Android API versions
.put(JSONObject().apply {
put("minAndroid", 1) // 1.0
put("maxAndroid", 23) // 6.0.1
})
.put(JSONObject().apply {
put("minAndroid", 24) // 7.0
put("maxAndroid", 25) // 7.1.2
put("supported", "2.6.2")
})
.put(JSONObject().apply {
put("minAndroid", 26) // 8.0
put("maxAndroid", 27) // 8.1
put("supported", "2.8.2")
})
.put(JSONObject().apply {
put("minAndroid", 28) // 9.0
put("maxAndroid", 99)
put("supported", "2.8.2")
})
// Version time limitation
.put(JSONObject().apply {
put("endDate", "2021-11-07")
put("version", "2.9.0-beta1")
})
.put(JSONObject().apply {
put("endDate", "2021-11-07")
put("version", "3.0-beta1")
})
.toString()
@Test
fun generateSupportedVersionsTest() {
val definition = generateSupportedVersions()
assertNull(AllowedVersions().findByApi(definition, 0))
assertFalse(AllowedVersions().findByApi(definition, 1)?.has("supported") ?: true)
assertFalse(AllowedVersions().findByApi(definition, 23)?.has("supported") ?: true)
assertEquals("2.6.2", AllowedVersions().findByApi(definition, 24)?.getString("supported"))
assertEquals("2.6.2", AllowedVersions().findByApi(definition, 25)?.getString("supported"))
assertEquals("2.8.2", AllowedVersions().findByApi(definition, 26)?.getString("supported"))
assertEquals("2.8.2", AllowedVersions().findByApi(definition, 27)?.getString("supported"))
assertEquals("2.8.2", AllowedVersions().findByApi(definition, 28)?.getString("supported"))
}
@Test
fun findByVersionTest() {
//val definition = AllowedVersions().generateSupportedVersions()
val definition =
"[{\"minAndroid\":1,\"maxAndroid\":23},{\"minAndroid\":24,\"maxAndroid\":25,\"supported\":\"2.6.2\"},{\"minAndroid\":26,\"maxAndroid\":27,\"supported\":\"2.8.2\"},{\"minAndroid\":28,\"maxAndroid\":99,\"supported\":\"2.8.2\"},{\"endDate\":\"2021-11-07\",\"version\":\"2.9.0-beta1\"},{\"endDate\":\"2021-11-02\",\"version\":\"3.0-beta1\"},{\"endDate\":\"2021-11-04\",\"version\":\"3.0-beta2\"},{\"endDate\":\"2021-11-10\",\"version\":\"3.0-beta3\"},{\"endDate\":\"2021-11-14\",\"version\":\"3.0-beta4\"}\n" +
" ,{\"endDate\":\"2021-11-16\",\"version\":\"3.0-beta5\"}\n" +
"]"
assertNull(AllowedVersions().findByVersion(definition, "2.6.0"))
assertTrue(AllowedVersions().findByVersion(definition, "2.9.0-beta1")?.has("endDate") ?: false)
assertEquals("2021-11-07", AllowedVersions().findByVersion(definition, "2.9.0-beta1")?.getString("endDate"))
}
@Test
fun endDateToMilliseconds() {
val definition = generateSupportedVersions()
val endDate = AllowedVersions().endDateToMilliseconds(AllowedVersions().findByVersion(definition, "2.9.0-beta1")?.getString("endDate") ?: "1000/01/01")
val dateTime = LocalDate(endDate)
assertEquals(2021, dateTime.year)
assertEquals(11, dateTime.monthOfYear)
assertEquals(7, dateTime.dayOfMonth)
assertNull(AllowedVersions().endDateToMilliseconds("abdef"))
}
} | agpl-3.0 | b83f001e6da84abe7730864eba5cd198 | 46.168675 | 518 | 0.585335 | 4.150583 | false | true | false | false |
treelzebub/zinepress | app/src/main/java/net/treelzebub/zinepress/db/articles/DbArticle.kt | 1 | 716 | package net.treelzebub.zinepress.db.articles
import android.database.Cursor
import net.treelzebub.zinepress.net.api.model.PocketArticle
/**
* Created by Tre Murillo on 1/24/16
*/
class DbArticle : IArticle {
var i = 0 // 0 is _ID
override val id: Long
override val date: Long
override val title: String
override val originalUrl: String
constructor(c: Cursor) {
id = c.getLong(++i)
date = c.getLong(++i)
title = c.getString(++i)
originalUrl = c.getString(++i)
}
constructor(a: PocketArticle) {
id = a.id
date = a.date
title = a.title
originalUrl = a.originalUrl
}
}
| gpl-2.0 | 517c2637256d5326acbaeaf0f70bad8e | 22.866667 | 59 | 0.579609 | 3.912568 | false | false | false | false |
Saketme/JRAW | lib/src/main/kotlin/net/dean/jraw/tree/AbstractCommentNode.kt | 2 | 10988 | package net.dean.jraw.tree
import net.dean.jraw.Endpoint
import net.dean.jraw.JrawUtils
import net.dean.jraw.RedditClient
import net.dean.jraw.databind.Enveloped
import net.dean.jraw.http.LogAdapter
import net.dean.jraw.models.*
import net.dean.jraw.models.internal.GenericJsonResponse
import net.dean.jraw.references.CommentsRequest
import net.dean.jraw.tree.CommentNode.Companion.NO_LIMIT
/**
* This class is the base implementation for all CommentNodes
*/
abstract class AbstractCommentNode<out T : PublicContribution<*>> protected constructor(
override val depth: Int,
override var moreChildren: MoreChildren?,
override val subject: T,
override val settings: CommentTreeSettings
) : CommentNode<T> {
override val replies: MutableList<CommentNode<Comment>> = mutableListOf()
/**
* Initializes [moreChildren] and [replies].
*/
protected fun initReplies(replies: List<NestedIdentifiable>) {
val (comments, allMoreChildren) = replies.partition { it is Comment }
if (allMoreChildren.size > 1)
throw IllegalStateException("More than 1 MoreChildren object found")
this.moreChildren = if (allMoreChildren.isNotEmpty()) allMoreChildren[0] as MoreChildren else null
for (reply in comments) {
this.replies.add(ReplyCommentNode(
depth = this.depth + 1,
comment = reply as Comment,
settings = settings,
parent = this
))
}
}
override fun hasMoreChildren(): Boolean = moreChildren != null
/** */
override fun iterator(): Iterator<CommentNode<Comment>> = replies.iterator()
override fun totalSize(): Int {
// walkTree() goes through this node and all child nodes, but we only care about child nodes
return walkTree().count() - 1
}
override fun visualize(out: LogAdapter) {
val relativeRootDepth = depth
for (node in walkTree(TreeTraversalOrder.PRE_ORDER)) {
val subj = node.subject
val indent = " ".repeat(node.depth - relativeRootDepth)
// Use the submission URL if it's not a self post, otherwise just use the comment/submission body
val body = if (subj is Submission && !subj.isSelfPost) subj.url else subj.body?.replace("\n", "\\n")
out.writeln(indent + "${subj.author} (${subj.score}↑): $body")
}
}
override fun walkTree(order: TreeTraversalOrder): Sequence<CommentNode<*>> =
TreeTraverser.traverse(this, order)
override fun loadMore(reddit: RedditClient): FakeRootCommentNode<T> {
if (moreChildren == null)
throw IllegalStateException("No more children")
val fakeRoot = FakeRootCommentNode(
depth = this.depth,
settings = this.settings,
subject = this.subject
)
attach(requestMore(reddit), fakeRoot)
return fakeRoot
}
override fun replaceMore(reddit: RedditClient): List<ReplyCommentNode> {
if (!hasMoreChildren()) return listOf()
val moreExpanded = requestMore(reddit)
// if not all children were loaded, MoreChildren will be attached later
this.moreChildren = null
return attach(moreExpanded)
}
/**
* Fetches up to [MORE_CHILDREN_LIMIT] Comments/MoreChildren from the API. The objects that are returned are listed
* as if they had been visited in pre-order traversal.
*/
private fun requestMore(reddit: RedditClient): List<NestedIdentifiable> {
if (!hasMoreChildren()) throw IllegalStateException("This node has no more children")
val more = moreChildren!!
if (more.isThreadContinuation)
return continueThread(reddit)
// Make sure we are only making one request to this endpoint at a time, as noted by the docs:
// "**NOTE**: you may only make one request at a time to this API endpoint. Higher concurrency will result in an
// error being returned."
return synchronized(moreChildrenLock) {
val json: GenericJsonResponse = reddit.request {
it.endpoint(Endpoint.GET_MORECHILDREN)
.query(mapOf(
"api_type" to "json",
"children" to more.childrenIds.take(MORE_CHILDREN_LIMIT).joinToString(","),
"link_id" to KindConstants.SUBMISSION + '_' + settings.submissionId,
"sort" to settings.sort.name.toLowerCase()
))
}.deserialize()
// IDs that weren't included in the request
val leftoverIds = more.childrenIds.drop(MORE_CHILDREN_LIMIT)
// The "things" node is an array of either comments or morechildren
val things = json.json?.data?.get("things") as? List<*> ?:
throw IllegalArgumentException("Unexpected JSON response")
// Transform every element to either a Comment or a MoreChildren
val adapter = JrawUtils.adapter<NestedIdentifiable>(Enveloped::class.java)
val redditObjects = things.map { adapter.fromJsonValue(it)!! } as MutableList<NestedIdentifiable>
// Sometimes the reddit API will send us another MoreChildren object for the same root node. Since we can't
// have more than one MoreChildren for a single CommentNode, we have to combine the two
val newRootMoreIndex = if (leftoverIds.isEmpty()) {
// If we don't have any leftover IDs then there is nothing to do
-1
} else {
// Try to find a MoreChildren that has the same parent as this.moreChildren
redditObjects.indexOfFirst {
it is MoreChildren && it.parentFullName == more.parentFullName
}
}
// If we found an additional root MoreChildren, replace it with the data we already have
if (newRootMoreIndex >= 0) {
val newRootMore = redditObjects[newRootMoreIndex] as MoreChildren
redditObjects[newRootMoreIndex] = MoreChildren.create(
/*fullName = */newRootMore.fullName,
/*id = */newRootMore.id,
/*parentFullName = */newRootMore.parentFullName,
/*childrenIds = */leftoverIds + newRootMore.childrenIds
)
}
/*return*/ redditObjects
}
}
/**
* Attaches a list of Comments and MoreChildren to a given root node. Returns all new direct children.
*/
private fun attach(children: List<NestedIdentifiable>, root: AbstractCommentNode<T> = this): List<ReplyCommentNode> {
val newDirectChildren: MutableList<ReplyCommentNode> = ArrayList()
var currentRoot: AbstractCommentNode<*> = root
// Children are listed in pre-order traversal
for (child in children) {
while (child.parentFullName != currentRoot.subject.fullName) {
currentRoot = currentRoot.parent as AbstractCommentNode<*>
if (currentRoot.depth < root.depth)
throw IllegalStateException("Failed to properly create tree")
}
when (child) {
is Comment -> {
val newNode = ReplyCommentNode(
comment = child,
depth = currentRoot.depth + 1,
parent = currentRoot,
settings = this.settings
)
// Sometimes same nodes are added more than once. Instead of not processing the duplicates we remove
// the old ones in order to not break the traversal algorithm
currentRoot.replies.removeIf { it.subject == newNode.subject }
currentRoot.replies.add(newNode)
if (currentRoot.subject.fullName == root.subject.fullName)
newDirectChildren.add(newNode)
// Assume the next comment is the child of the new node
currentRoot = newNode
}
is MoreChildren -> currentRoot.moreChildren = child
else -> throw IllegalArgumentException("Expected Comment or MoreChildren, got " + child.javaClass)
}
}
return newDirectChildren
}
/**
* Requests more comments from a MoreChildren that is a thread continuation.
*
* @see MoreChildren.isThreadContinuation
*/
private fun continueThread(reddit: RedditClient): List<NestedIdentifiable> {
// Request a whole new comment tree with this comment as the root node instead of the actual submission
val root = reddit
.submission(settings.submissionId)
.comments(CommentsRequest(focus = subject.id, sort = settings.sort))
return root
.walkTree(TreeTraversalOrder.PRE_ORDER)
// When we specify `focus` in CommentsRequest, reddit only returns that comment and its children. The
// submission is technically the "root" of the whole tree, but its only child will be a node for the
// "focus" comment. We only care about the children of the focus comment, so drop the first node
// (submission node) and the second node (focus comment)
.drop(2)
// Map everything to the subject
.map { it.subject as NestedIdentifiable }
.toList()
}
override fun loadFully(reddit: RedditClient, depthLimit: Int, requestLimit: Int) {
var requests = 0
if (depthLimit < NO_LIMIT || requestLimit < NO_LIMIT)
throw IllegalArgumentException("Expecting a number greater than or equal to -1, got " + if (requestLimit < NO_LIMIT) requestLimit else depthLimit)
// Load this node's comments first
while (hasMoreChildren()) {
replaceMore(reddit)
if (++requests > requestLimit && depthLimit != NO_LIMIT)
return
}
// Load the children's comments next
for (node in walkTree(TreeTraversalOrder.BREADTH_FIRST)) {
// Travel breadth first so we can accurately compare depths
if (depthLimit != NO_LIMIT && node.depth > depthLimit)
return
while (node.hasMoreChildren()) {
node.replaceMore(reddit)
if (++requests > requestLimit && depthLimit != NO_LIMIT)
return
}
}
}
override fun toString(): String {
return "AbstractCommentNode(depth=$depth, body=${subject.body}, replies=List[${replies.size}])"
}
/** */
companion object {
/** The upper limit to how many more comments can be requested at one time. Equal to 100. */
const val MORE_CHILDREN_LIMIT = 100
private val moreChildrenLock = Any()
}
}
| mit | 880760c7fa3935d2553ed681aa5876df | 41.581395 | 158 | 0.613417 | 4.93531 | false | false | false | false |
abigpotostew/easypolitics | db/src/main/kotlin/bz/stewart/bracken/db/database/TimedTransaction.kt | 1 | 1472 | package bz.stewart.bracken.db.database
import bz.stewart.bracken.db.database.mongo.CollectionWriter
import java.util.*
/**
* Created by stew on 3/30/17.
*/
class TimedTransaction<T : DbItem,D : Database<T>>(private val capture: Transaction<T, D>): Transaction<T, D>{
var startTime: Date? = null
var startExecution: Date? = null
var endExecution: Date? = null
var endTime: Date? = null
var aborted = false
override fun setWriter(writer: CollectionWriter<T, D>) {
capture.setWriter(writer)
}
override fun beginTransaction() {
startTime = now()
capture.beginTransaction()
}
override fun execute() {
startExecution = now()
capture.execute()
endExecution = now()
}
override fun endTransaction() {
capture.endTransaction()
endTime = now()
}
fun now():Date{
return Date()
}
fun formatTimes(start:Date,end:Date):String{
val diff = end.time - start.time
if(diff<1000){
return "$diff milliseconds"
}
return "${diff/1000} seconds"
}
override fun abort(msg: String) {
capture.abort()
aborted = true
if(endExecution==null){
endExecution = now()
}
}
override fun toString(): String {
val se = startExecution ?: now()
val ee = endExecution ?: now()
val et = endTime ?: now()
return "Execution time ${formatTimes(se,ee)}. Total time ${formatTimes(startTime!!,et)}"
}
} | apache-2.0 | a472c35e30191d8facb317f9d8e8fe23 | 22.380952 | 110 | 0.618207 | 3.98916 | false | false | false | false |
Maccimo/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/DesktopLayout.kt | 2 | 5514 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplacePutWithAssignment", "ReplaceGetOrSet")
package com.intellij.openapi.wm.impl
import com.intellij.configurationStore.serialize
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.wm.RegisterToolWindowTask
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.WindowInfo
import com.intellij.util.xmlb.XmlSerializer
import org.jdom.Element
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.NonNls
@Internal
class DesktopLayout(private val idToInfo: MutableMap<String, WindowInfoImpl> = HashMap()) {
companion object {
@NonNls const val TAG = "layout"
}
constructor(descriptors: List<WindowInfoImpl>) : this(descriptors.associateByTo(HashMap()) { it.id!! })
/**
* @param anchor anchor of the stripe.
* @return maximum ordinal number in the specified stripe. Returns `-1` if there is no tool window with the specified anchor.
*/
internal fun getMaxOrder(anchor: ToolWindowAnchor): Int {
return idToInfo.values.asSequence().filter { anchor == it.anchor }.maxOfOrNull { it.order } ?: -1
}
fun copy(): DesktopLayout {
val map = HashMap<String, WindowInfoImpl>(idToInfo.size)
for (entry in idToInfo) {
map.put(entry.key, entry.value.copy())
}
return DesktopLayout(map)
}
internal fun create(task: RegisterToolWindowTask, isNewUi: Boolean): WindowInfoImpl {
val info = WindowInfoImpl()
info.id = task.id
info.isFromPersistentSettings = false
if (isNewUi) {
info.isShowStripeButton = false
}
else {
info.isSplit = task.sideTool
}
info.anchor = task.anchor
task.contentFactory?.anchor?.let {
info.anchor = it
}
return info
}
fun getInfo(id: String) = idToInfo.get(id)
internal fun addInfo(id: String, info: WindowInfoImpl) {
val old = idToInfo.put(id, info)
LOG.assertTrue(old == null)
}
/**
* Sets new `anchor` and `id` for the specified tool window.
* Also, the method properly updates order of all other tool windows.
*/
fun setAnchor(info: WindowInfoImpl,
newAnchor: ToolWindowAnchor,
suppliedNewOrder: Int): List<WindowInfoImpl> {
var newOrder = suppliedNewOrder
val affected = ArrayList<WindowInfoImpl>()
// if order isn't defined then the window will be the last in the stripe
if (newOrder == -1) {
newOrder = getMaxOrder(newAnchor) + 1
}
else {
// shift order to the right in the target stripe
for (otherInfo in idToInfo.values) {
if (otherInfo !== info && otherInfo.anchor == newAnchor && otherInfo.order != -1 && otherInfo.order >= newOrder) {
otherInfo.order++
affected.add(otherInfo)
}
}
}
info.order = newOrder
info.anchor = newAnchor
return affected
}
fun readExternal(layoutElement: Element, isNewUi: Boolean, isFromPersistentSettings: Boolean = true) {
val infoBinding = XmlSerializer.getBeanBinding(WindowInfoImpl::class.java)
val list = mutableListOf<WindowInfoImpl>()
for (element in layoutElement.getChildren(WindowInfoImpl.TAG)) {
val info = WindowInfoImpl()
info.isFromPersistentSettings = isFromPersistentSettings
infoBinding.deserializeInto(info, element)
info.normalizeAfterRead()
val id = info.id
if (id == null) {
LOG.warn("Skip invalid window info (no id): ${JDOMUtil.writeElement(element)}")
continue
}
if (info.isSplit && isNewUi) {
info.isSplit = false
}
idToInfo.put(id, info)
list.add(info)
}
normalizeOrder(list)
for (info in list) {
info.resetModificationCount()
}
}
val stateModificationCount: Long
get() {
if (idToInfo.isEmpty()) {
return 0
}
var result = 0L
for (info in idToInfo.values) {
result += info.modificationCount
}
return result
}
fun writeExternal(tagName: String): Element? {
if (idToInfo.isEmpty()) {
return null
}
var state: Element? = null
for (info in getSortedList()) {
val child = serialize(info) ?: continue
if (state == null) {
state = Element(tagName)
}
state.addContent(child)
}
return state
}
internal fun getSortedList(): List<WindowInfoImpl> = idToInfo.values.sortedWith(windowInfoComparator)
}
private val LOG = logger<DesktopLayout>()
private fun getAnchorWeight(anchor: ToolWindowAnchor): Int {
return when (anchor) {
ToolWindowAnchor.TOP -> 1
ToolWindowAnchor.LEFT -> 2
ToolWindowAnchor.BOTTOM -> 3
ToolWindowAnchor.RIGHT -> 4
else -> 0
}
}
internal val windowInfoComparator: Comparator<WindowInfo> = Comparator { o1, o2 ->
val weightDiff = getAnchorWeight(o1.anchor) - getAnchorWeight(o2.anchor)
if (weightDiff != 0) weightDiff else o1.order - o2.order
}
/**
* Normalizes order of windows in the array. Order of first window will be `0`.
*/
private fun normalizeOrder(list: MutableList<WindowInfoImpl>) {
list.sortWith(windowInfoComparator)
var order = 0
var lastAnchor = ToolWindowAnchor.TOP
for (info in list) {
if (info.order == -1) {
continue
}
if (lastAnchor != info.anchor) {
lastAnchor = info.anchor
order = 0
}
info.order = order++
}
} | apache-2.0 | 2ddd743c462d4a090707132295e1710d | 27.57513 | 127 | 0.672833 | 4.18997 | false | false | false | false |
Jakeler/UT61E-Toolkit | Application/src/main/java/jk/ut61eTool/Temperature.kt | 1 | 2308 | package jk.ut61eTool
import android.util.Log
import java.io.InputStreamReader
data class Temperature(
val id: Int,
val name: String,
val celsius: Double,
)
object TemperatureReader {
const val basePath = "/sys/class/thermal/thermal_zone"
private fun runShellForOutput(cmd: Array<String>): List<String> {
var lines: List<String>
Runtime.getRuntime().exec(cmd).let { process ->
process.waitFor()
lines = InputStreamReader(process.inputStream).use { it.readLines() }
process.destroy()
}
Log.d("TemperatureReader", "runShellForOutput: ${lines.joinToString(";")}")
return lines
}
fun getSensorCount(): Int {
val cmd = arrayOf("sh", "-c", "echo $basePath* | wc -w")
runShellForOutput(cmd).let {
return it[0].trim().toInt()
}
}
fun getAllTemps(count: Int = getSensorCount()): List<Temperature> {
val dirs = (0 until count).joinToString(separator = " "){ i ->
"$basePath$i"
}
val cmd = arrayOf("sh", "-c", "for dir in $dirs; do echo $(cat \$dir/type) $(cat \$dir/temp); done ")
runShellForOutput(cmd).let {
return it.mapIndexed(::lineToTemp)
}
}
fun getTempByID(id: Int): Temperature {
val dir = "$basePath$id"
runShellForOutput(arrayOf("sh", "-c", "echo $(cat $dir/type) $(cat $dir/temp)")).let {
return lineToTemp(id, it[0])
}
}
private fun lineToTemp(index: Int, s: String): Temperature {
val tokens = s.split(" ")
if (tokens.size < 2) {
return Temperature(index, "NOT FOUND", Double.NaN)
}
val name = tokens[0]
val value = tokens[1].toDouble()
return Temperature(index, name, when {
(value > -40 && value < 85) -> value // Industrial temp range, already valid temp
(value > -1000 && value < 1000) -> value/10 // range 100-1000
(value > -10_000 && value < 10_000) -> value/100 // range 1_000-10_000
(value > -100_000 && value < 100_000) -> value/1000 // range 10_000-100_000
(value > -1_000_000 && value < 1_000_000) -> value/10000 // range 100_000-1_000_000
else -> Double.NaN
})
}
}
| apache-2.0 | f6a40c39a79dfb073be94a11c0b8b317 | 33.969697 | 109 | 0.557626 | 3.722581 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/grammar/tree/ExpSinop.kt | 1 | 2440 | package com.bajdcc.LALR1.grammar.tree
import com.bajdcc.LALR1.grammar.codegen.ICodegen
import com.bajdcc.LALR1.grammar.error.SemanticException.SemanticError
import com.bajdcc.LALR1.grammar.runtime.RuntimeInst
import com.bajdcc.LALR1.grammar.semantic.ISemanticRecorder
import com.bajdcc.LALR1.grammar.tree.closure.IClosureScope
import com.bajdcc.LALR1.grammar.type.TokenTools
import com.bajdcc.util.lexer.token.OperatorType
import com.bajdcc.util.lexer.token.Token
import com.bajdcc.util.lexer.token.TokenType
/**
* 【语义分析】一元表达式
*
* @author bajdcc
*/
class ExpSinop(var token: Token,
var operand: IExp) : IExp {
override fun isConstant(): Boolean {
return operand.isConstant()
}
override fun isEnumerable(): Boolean {
return operand.isEnumerable()
}
override fun simplify(recorder: ISemanticRecorder): IExp {
if (!isConstant()) {
return this
}
if (operand is ExpValue) {
if (token.type === TokenType.OPERATOR) {
if (TokenTools.sinop(recorder, this)) {
return operand
}
}
}
return this
}
override fun analysis(recorder: ISemanticRecorder) {
val type = token.obj as OperatorType?
if (type === OperatorType.PLUS_PLUS || type === OperatorType.MINUS_MINUS) {
if (operand !is ExpValue) {
recorder.add(SemanticError.INVALID_OPERATOR, token)
}
} else {
operand.analysis(recorder)
}
}
override fun genCode(codegen: ICodegen) {
operand.genCode(codegen)
codegen.genCode(TokenTools.op2ins(token))
val type = token.obj as OperatorType?
if (type == OperatorType.PLUS_PLUS || type == OperatorType.MINUS_MINUS) {
val value = operand as ExpValue?
codegen.genCode(RuntimeInst.ipush,
codegen.genDataRef(value!!.token.obj!!))
codegen.genCode(RuntimeInst.icopy)
}
}
override fun toString(): String {
return print(StringBuilder())
}
override fun print(prefix: StringBuilder): String {
return "( " + token.toRealString() + " " + operand.print(prefix) + " )"
}
override fun addClosure(scope: IClosureScope) {
operand.addClosure(scope)
}
override fun setYield() {
operand.setYield()
}
}
| mit | bbe25cc0eb4ee5d917bf59ec64054fea | 28.851852 | 83 | 0.622002 | 4.197917 | false | false | false | false |
omaraa/ImageSURF | src/test/kotlin/imagesurf/BatchApplyImageSurfTest.kt | 1 | 2981 | package imagesurf
import ij.ImagePlus
import imagesurf.util.ProgressListener
import org.junit.Test
import org.scijava.Context
import org.scijava.app.StatusService
import org.scijava.app.event.StatusEvent
import org.scijava.log.StderrLogService
import org.scijava.plugin.PluginInfo
import java.io.File
import java.nio.file.Files
import org.assertj.core.api.Assertions.assertThat
class BatchApplyImageSurfTest {
@Test
fun `classifies pixels accurately`() {
val classifierFile = File(javaClass.getResource("/batch-apply/ImageSURF.classifier").file)
val imageFolder = File(javaClass.getResource("/batch-apply/input").file)
val outputFolder = Files.createTempDirectory("imagesurf-" + System.nanoTime()).toFile()
val expectedOutputFolder = File(javaClass.getResource("/batch-apply/output").file)
val outputFiles = BatchApplyImageSurf.batchApplyImageSurf(classifierFile, outputFolder, imageFolder, null, 500, DUMMY_PROGRESS_LISTENER, DUMMY_LOG_SERVICE, DUMMY_STATUS_SERVICE)
outputFiles.forEach {
val actual = ImagePlus(it.absolutePath).processor.pixels as ByteArray
val expected = ImagePlus(File(expectedOutputFolder, it.name).absolutePath).processor.pixels as ByteArray
actual.zip(expected) { actual, expected -> actual to expected}
.filter {(actual, expected) -> actual != expected}
.let { different ->
assertThat(different.size).isEqualTo(0)
}
}
}
companion object {
val DUMMY_PROGRESS_LISTENER = object : ProgressListener {
override fun onProgress(current: Int, max: Int, message: String) {
println("$current/$max: $message")
}
}
val DUMMY_LOG_SERVICE = StderrLogService()
val DUMMY_STATUS_SERVICE = object : StatusService {
override fun getInfo(): PluginInfo<*> {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun getContext(): Context = context()
override fun getPriority(): Double = Double.MAX_VALUE
override fun setInfo(p0: PluginInfo<*>?) {}
override fun setPriority(p0: Double) {}
override fun context(): Context {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun warn(p0: String?) { }
override fun clearStatus() { }
override fun getStatusMessage(p0: String?, p1: StatusEvent?): String = ""
override fun showStatus(p0: String?) {}
override fun showStatus(p0: Int, p1: Int, p2: String?) {}
override fun showStatus(p0: Int, p1: Int, p2: String?, p3: Boolean) {}
override fun showProgress(p0: Int, p1: Int) {}
}
}
} | gpl-3.0 | 04809aa5de4dea050478cabc9bb3e951 | 35.365854 | 185 | 0.634015 | 4.607419 | false | false | false | false |
nearbydelta/KoreanAnalyzer | hannanum/src/test/kotlin/kr/bydelta/koala/test/tests.kt | 1 | 18066 | package kr.bydelta.koala.test
import kaist.cilab.jhannanum.common.communication.PlainSentence
import kaist.cilab.jhannanum.common.communication.Sentence
import kaist.cilab.jhannanum.common.workflow.Workflow
import kaist.cilab.jhannanum.plugin.major.morphanalyzer.impl.ChartMorphAnalyzer
import kaist.cilab.jhannanum.plugin.major.postagger.impl.HMMTagger
import kaist.cilab.jhannanum.plugin.supplement.MorphemeProcessor.UnknownMorphProcessor.UnknownProcessor
import kaist.cilab.jhannanum.plugin.supplement.PlainTextProcessor.InformalSentenceFilter.InformalSentenceFilter
import kaist.cilab.jhannanum.plugin.supplement.PlainTextProcessor.SentenceSegmentor.SentenceSegmentor
import kaist.cilab.parser.berkeleyadaptation.BerkeleyParserWrapper
import kaist.cilab.parser.berkeleyadaptation.Configuration
import kaist.cilab.parser.berkeleyadaptation.HanNanumMorphAnalWrapper
import kaist.cilab.parser.corpusconverter.sejong2treebank.sejongtree.NonterminalNode
import kaist.cilab.parser.corpusconverter.sejong2treebank.sejongtree.ParseTree
import kaist.cilab.parser.dependency.DNode
import kaist.cilab.parser.psg2dg.Converter
import kr.bydelta.koala.*
import kr.bydelta.koala.data.DepEdge
import kr.bydelta.koala.data.SyntaxTree
import kr.bydelta.koala.hnn.*
import kr.bydelta.koala.proc.CanParseDependency
import kr.bydelta.koala.proc.CanParseSyntax
import org.amshove.kluent.`should be equal to`
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.File
object HNNDictTest : Spek(DictSpek(Dictionary, getTagger = { Tagger() }))
val splitterFlow by lazy {
synchronized(Configuration.hanBaseDir) {
Configuration.hanBaseDir = "./hnnModels"
val workflow = Workflow()
val basePath = "./hnnModels"
workflow.appendPlainTextProcessor(SentenceSegmentor(),
basePath + File.separator + "conf" + File.separator + "SentenceSegment.json")
workflow.activateWorkflow(true)
println("SplitterFlow initialized")
workflow
}
}
object HNNSpliterTest : Spek(SplitterSpek(
getSplitter = { SentenceSplitter() },
originalSplitCounter = {
synchronized(splitterFlow) {
splitterFlow.analyze(it)
var count = 0
var isEnded = false
while (!isEnded) {
val sent = splitterFlow.getResultOfSentence(PlainSentence(0, 0, false))
isEnded = sent.isEndOfDocument
count += 1
}
count
}
}
))
object HNNTagConversionTest : Spek(TagConversionSpek(
from = { it.toSejongPOS() },
to = { it.fromSejongPOS() },
getMapping = {
when (it) {
POS.NNG ->
listOf(Conversion("ncpa", toTagger = false),
Conversion("ncps", toTagger = false),
Conversion("ncn"),
Conversion("ncr", toTagger = false))
POS.NNP ->
listOf(Conversion("nqpa", toTagger = false),
Conversion("nqpb", toTagger = false),
Conversion("nqpc", toTagger = false),
Conversion("nqq"))
POS.NNB -> listOf(Conversion("nbn"), Conversion("nbs", toTagger = false))
POS.NNM -> listOf(Conversion("nbu"))
POS.NR -> listOf(Conversion("nnc"), Conversion("nno", toTagger = false))
POS.NP -> listOf(Conversion("npd"), Conversion("npp", toTagger = false))
POS.VV -> listOf(Conversion("pvg"), Conversion("pvd", toTagger = false))
POS.VA -> listOf(Conversion("paa"), Conversion("pad", toTagger = false))
POS.VX -> listOf(Conversion("px"))
POS.VCP -> listOf(Conversion("jp"))
POS.VCN -> listOf(Conversion("paa", toSejong = false))
POS.MM -> listOf(Conversion("mma"), Conversion("mmd", toTagger = false))
POS.MAG -> listOf(Conversion("mag"), Conversion("mad", toTagger = false))
POS.IC -> listOf(Conversion("ii"))
POS.JKS -> listOf(Conversion("jcs"))
POS.JKC -> listOf(Conversion("jcc"))
POS.JKG -> listOf(Conversion("jcm"))
POS.JKO -> listOf(Conversion("jco"))
POS.JKB -> listOf(Conversion("jca"))
POS.JKV -> listOf(Conversion("jcv"))
POS.JKQ -> listOf(Conversion("jcr"))
POS.JC -> listOf(Conversion("jct"), Conversion("jcj", toTagger = false))
POS.JX -> listOf(Conversion("jxf"), Conversion("jxc", toTagger = false))
POS.EC ->
listOf(Conversion("ecc"),
Conversion("ecs", toTagger = false),
Conversion("ecx", toTagger = false))
POS.XPN -> listOf(Conversion("xp"))
POS.XPV -> listOf(Conversion("xp", toSejong = false))
POS.XSN ->
listOf(Conversion("xsnx"),
Conversion("xsnu", toTagger = false),
Conversion("xsna", toTagger = false),
Conversion("xsnca", toTagger = false),
Conversion("xsncc", toTagger = false),
Conversion("xsns", toTagger = false),
Conversion("xsnp", toTagger = false))
POS.XSV ->
listOf(Conversion("xsvn"),
Conversion("xsvv", toTagger = false),
Conversion("xsva", toTagger = false))
POS.XSA ->
listOf(Conversion("xsmn"), Conversion("xsms", toTagger = false))
POS.XSM ->
listOf(Conversion("xsas"), Conversion("xsam", toTagger = false))
POS.XSO, POS.XR, POS.NF, POS.NV, POS.NA -> emptyList()
POS.SS -> listOf(Conversion("sl"), Conversion("sr", toTagger = false))
POS.SO -> listOf(Conversion("sd"))
POS.SW -> listOf(Conversion("sy"), Conversion("su", toTagger = false))
POS.SL -> listOf(Conversion("f"))
POS.SH -> listOf(Conversion("f", toSejong = false))
POS.SN -> listOf(Conversion("nnc", toSejong = false))
else -> listOf(Conversion(it.toString().toLowerCase()))
}
}
))
val taggerWorkflow by lazy {
synchronized(Configuration.hanBaseDir) {
Configuration.hanBaseDir = "./hnnModels"
val workflow = Workflow()
val basePath = "./hnnModels"
workflow.appendPlainTextProcessor(SentenceSegmentor(),
basePath + File.separator + "conf" + File.separator + "SentenceSegment.json")
workflow.appendPlainTextProcessor(InformalSentenceFilter(),
basePath + File.separator + "conf" + File.separator + "InformalSentenceFilter.json")
workflow.setMorphAnalyzer(ChartMorphAnalyzer(),
basePath + File.separator + "conf" + File.separator + "ChartMorphAnalyzer.json", "./hnnModels/")
workflow.appendMorphemeProcessor(UnknownProcessor(),
basePath + File.separator + "conf" + File.separator + "UnknownMorphProcessor.json")
workflow.setPosTagger(HMMTagger(),
basePath + File.separator + "conf" + File.separator + "HmmPosTagger.json", "./hnnModels/")
workflow.activateWorkflow(true)
workflow
}
}
object HNNTaggerTest : Spek(TaggerSpek(
getTagger = { Tagger() },
isSentenceSplitterImplemented = false,
tagSentByOrig = {
synchronized(taggerWorkflow) {
taggerWorkflow.analyze(it)
val original = mutableListOf<Sentence>()
var isEnded = false
while (!isEnded) {
val sent = taggerWorkflow.getResultOfSentence(Sentence(0, 0, false))
isEnded = sent.isEndOfDocument
original.add(sent)
}
val tag = original.flatMap { s -> s.eojeols.toList() }
.joinToString(" ") { e ->
e.morphemes.zip(e.tags).joinToString("+") { pair -> "${pair.first}/${pair.second}" }
}
val surface = original.flatMap { s -> s.plainEojeols.toList() }.joinToString(" ")
surface to tag
}
},
tagParaByOrig = {
synchronized(taggerWorkflow) {
taggerWorkflow.analyze(it)
val original = mutableListOf<Sentence>()
var isEnded = false
while (!isEnded) {
val sent = taggerWorkflow.getResultOfSentence(Sentence(0, 0, false))
isEnded = sent.isEndOfDocument
original.add(sent)
}
original.map { s -> s.eojeols.joinToString(" ") { m -> m.morphemes.joinToString("+") } }
}
}
))
val parser by lazy {
Configuration.parserModel = "./hnnModels/models/parser/KorGrammar_BerkF_ORIG"
Configuration.hanBaseDir = "./hnnModels/"
BerkeleyParserWrapper(Configuration.parserModel)
}
fun SyntaxTree.getDFSString(buffer: StringBuffer, depth: Int = 0): StringBuffer {
buffer.append("\n")
buffer.append("| ".repeat(depth))
buffer.append("${this.originalLabel}")
if (this.terminal != null) {
buffer.append("(")
buffer.append(this.terminal!!.joinToString("+") { it.originalTag!! })
buffer.append(")")
} else {
for (child in this) {
child.getDFSString(buffer, depth + 1)
}
}
return buffer
}
fun NonterminalNode.getDFSString(buffer: StringBuffer, depth: Int = 0): StringBuffer {
buffer.append("\n")
buffer.append("| ".repeat(depth))
buffer.append(this.phraseTag.split("-")[0])
if (this in this.tree.prePreTerminalNodes) {
buffer.append("(")
buffer.append(this.myTerminals!!.joinToString("+") { it.pos })
buffer.append(")")
} else {
for (child in this.children) {
(child as NonterminalNode).getDFSString(buffer, depth + 1)
}
}
return buffer
}
object HNNSyntaxParserTest : Spek(ParserSpek<Sentence, CanParseSyntax<Sentence>>(
getParser = { Parser() },
parseSentByKoala = { sent, parser ->
if (sent.any { it in "+()" }) {
// '+()'가 포함된 어절의 분석결과는 한나눔이 오류를 발생시킴 (+가 누락되거나, ()가 제대로 처리되지 않음)
// 따라서 비교 과정에서 무시함
emptyList()
} else {
val result = parser.analyze(sent)
result.map { s ->
// 한나눔 파서의 원본 문장 변형 정도가 심하므로, 원본 문장은 확인하지 않음
"" to s.getSyntaxTree()!!.getDFSString(StringBuffer()).toString()
}
}
},
parseSentByOrig = {
if (it.any { ch -> ch in "+()" }) {
// '+()'가 포함된 어절의 분석결과는 한나눔이 오류를 발생시킴 (+가 누락되거나, ()가 제대로 처리되지 않음)
// 따라서 비교 과정에서 무시함
emptyList()
} else {
synchronized(taggerWorkflow) {
taggerWorkflow.analyze(it)
val tagged = mutableListOf<Sentence>()
var isEnded = false
while (!isEnded) {
val sent = taggerWorkflow.getResultOfSentence(Sentence(0, 0, false))
isEnded = sent.isEndOfDocument
tagged.add(sent)
}
val conv = Converter()
val trees =
tagged.map { s ->
val surface = s.plainEojeols.joinToString(" ")
.replace("(", "-LRB-").replace(")", "-RRB-")
val exp = conv.StringforDepformat(Converter.functionTagReForm(parser.parse(surface)))
val tree = ParseTree(surface, exp, 0, true)
conv.convert(tree) // 한나눔 코드가 의존구문분석을 위한 분석 과정에서 Tree를 변경하고 있음
tree
}
trees.map {
// 한나눔 파서의 원본 문장 변형 정도가 심하므로, 원본 문장은 확인하지 않음
"" to (it.head as NonterminalNode).getDFSString(StringBuffer()).toString()
}
}
}
}
))
fun DepEdge.getOriginalString() = "${this.originalLabel}(${this.governor?.id ?: -1}, ${this.dependent.id})"
fun DNode.getOriginalString() =
"${this.correspondingPhrase.phraseTag.split("-")[0]}_${this.getdType()}(${this.head?.wordIdx
?: -1}, ${this.wordIdx})"
object HNNDepParserTest : Spek(ParserSpek<Sentence, CanParseDependency<Sentence>>(
getParser = { Parser() },
parseSentByKoala = { sent, parser ->
if (sent.any { it in "+()" }) {
// '+()'가 포함된 어절의 분석결과는 한나눔이 오류를 발생시킴 (+가 누락되거나, ()가 제대로 처리되지 않음)
// 따라서 비교 과정에서 무시함
emptyList()
} else {
val result = parser.analyze(sent)
result.map { s ->
val deps = s.getDependencies()
val depString = deps!!.asSequence().map { it.getOriginalString() }.sorted().joinToString() ?: ""
// 한나눔 파서의 원본 문장 변형 정도가 심하므로, 원본 문장은 확인하지 않음
"" to depString
}
}
},
parseSentByOrig = { sent ->
if (sent.any { it in "+()" }) {
// '+()'가 포함된 어절의 분석결과는 한나눔이 오류를 발생시킴 (+가 누락되거나, ()가 제대로 처리되지 않음)
// 따라서 비교 과정에서 무시함
emptyList()
} else {
synchronized(taggerWorkflow) {
taggerWorkflow.analyze(sent)
val tagged = mutableListOf<Sentence>()
var isEnded = false
while (!isEnded) {
val s = taggerWorkflow.getResultOfSentence(Sentence(0, 0, false))
isEnded = s.isEndOfDocument
tagged.add(s)
}
val conv = Converter()
val trees =
tagged.map { s ->
val surface = s.plainEojeols.joinToString(" ")
.replace("(", "-LRB-").replace(")", "-RRB-")
val exp = conv.StringforDepformat(Converter.functionTagReForm(parser.parse(surface)))
val tree = ParseTree(surface, exp, 0, true)
conv.convert(tree)
}
trees.map { t ->
// 한나눔 파서의 원본 문장 변형 정도가 심하므로, 원본 문장은 확인하지 않음
"" to t.nodeList.map { it.getOriginalString() }.sorted().joinToString()
}
}
}
}
))
object HNNOriginalWrapperTest : Spek({
defaultTimeout = 300000L // 5 minutes
val tagger = Tagger()
describe("MorphemeAnalyzerWrap") {
it("should provide exactly same result with HanNanumMorphemeAnalyzerWrap") {
Examples.exampleSequence().forEach { pair ->
val sent = pair.second
tagger.tagParagraphOriginal(sent).forEach { s ->
Configuration.hanBaseDir = "./hnnModels/"
println("MorphAnalWrap")
val original = HanNanumMorphAnalWrapper.getInstance().getAnalysisResult(s.plainEojeols.joinToString(" "))
val reproduced = MorphemeAnalyzerWrap.getAnalysisResult(s)
reproduced.zip(original).forEach {
if ('+' !in it.first.origEojeol) {
// '+'가 포함된 어절의 분석결과는 한나눔이 오류임 (+가 누락됨)
it.first.toString() `should be equal to` it.second.toString()
}
}
}
}
}
}
describe("BerkeleyParserWrap") {
it("should provide exactly same result with BerkeleyParserWrapper") {
Configuration.parserModel = "./hnnModels/models/parser/KorGrammar_BerkF_ORIG"
Configuration.hanBaseDir = "./hnnModels/"
val parser = BerkeleyParserWrapper(Configuration.parserModel)
val wrap = BerkeleyParserWrap()
Examples.exampleSequence().forEach { pair ->
val sent = pair.second
tagger.tagParagraphOriginal(sent).forEach { s ->
println("ParserWrap")
val original = parser.parse(s.plainEojeols.joinToString(" "))
val reproduced = wrap.parseForced(s)
if ('+' !in reproduced) {
// '+'가 포함된 어절의 분석결과는 한나눔이 오류임 (+가 누락됨)
original `should be equal to` reproduced
}
}
}
}
}
})
| gpl-3.0 | 0d27273620c4d04b3e9a762c1319804b | 42.067332 | 125 | 0.528836 | 4.173514 | false | false | false | false |
ingokegel/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/snapshot/SnapshotHashEnumeratorService.kt | 7 | 3636 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.util.indexing.snapshot
import com.intellij.openapi.components.Service
import com.intellij.openapi.components.service
import com.intellij.openapi.components.serviceIfCreated
import com.intellij.openapi.diagnostic.logger
import com.intellij.util.hash.ContentHashEnumerator
import com.intellij.util.indexing.ID
import com.intellij.util.indexing.IndexInfrastructure
import com.intellij.util.io.IOUtil
import java.io.Closeable
import java.io.IOException
import java.util.concurrent.locks.Lock
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
@Service
internal class SnapshotHashEnumeratorService : Closeable {
companion object {
private val LOG = logger<SnapshotHashEnumeratorService>()
@JvmStatic
fun getInstance(): SnapshotHashEnumeratorService = service()
@JvmStatic
fun closeIfCreated() {
serviceIfCreated<SnapshotHashEnumeratorService>()?.close()
}
}
private enum class State { OPEN, OPEN_AND_CLEAN, CLOSED }
interface HashEnumeratorHandle {
@Throws(IOException::class)
fun enumerateHash(digest: ByteArray): Int
fun release()
}
private inner class HashEnumeratorHandleImpl(private val requestorIndexId: ID<*, *>): HashEnumeratorHandle {
override fun enumerateHash(digest: ByteArray): Int = contentHashEnumerator!!.enumerate(digest)
override fun release() {
lock.withLock {
handles.remove(this)
LOG.assertTrue(state != State.CLOSED, "handle is released for closed enumerator")
}
}
override fun equals(other: Any?): Boolean {
return other is HashEnumeratorHandleImpl && other.requestorIndexId == requestorIndexId
}
override fun hashCode(): Int {
return requestorIndexId.hashCode()
}
override fun toString(): String {
return "handle for ${requestorIndexId.name}"
}
}
@Volatile
private var state: State = State.CLOSED
@Volatile
private var contentHashEnumerator: ContentHashEnumerator? = null
private val handles: MutableSet<HashEnumeratorHandle> = HashSet()
private val lock: Lock = ReentrantLock()
@Throws(IOException::class)
fun initialize(): Boolean {
lock.withLock {
if (state == State.CLOSED) {
val hashEnumeratorFile = IndexInfrastructure.getPersistentIndexRoot().resolve("textContentHashes")
state = State.OPEN
contentHashEnumerator =
IOUtil.openCleanOrResetBroken({ ContentHashEnumerator(hashEnumeratorFile) },
{
IOUtil.deleteAllFilesStartingWith(hashEnumeratorFile)
state = State.OPEN_AND_CLEAN
})!!
}
LOG.assertTrue(state != State.CLOSED)
return state == State.OPEN
}
}
@Throws(IOException::class)
override fun close() {
lock.withLock {
if (state == State.OPEN) {
contentHashEnumerator!!.close()
state = State.CLOSED
LOG.assertTrue(handles.isEmpty(), "enumerator handles are still held: $handles")
handles.clear()
}
}
}
fun flush() {
lock.withLock {
if (state == State.OPEN) {
contentHashEnumerator!!.force()
}
}
}
fun createHashEnumeratorHandle(requestorIndexId: ID<*, *>): HashEnumeratorHandle {
val handle = HashEnumeratorHandleImpl(requestorIndexId)
lock.withLock {
handles.add(handle)
}
return handle
}
}
| apache-2.0 | c871e32401e5ddbdc7a47407661a7797 | 29.049587 | 140 | 0.682343 | 4.637755 | false | false | false | false |
ChristopherGittner/OSMBugs | app/src/main/java/org/gittner/osmbugs/osmnotes/OsmNotesParser.kt | 1 | 2527 | package org.gittner.osmbugs.osmnotes
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.gittner.osmbugs.osmnotes.OsmNote.OsmNoteComment
import org.joda.time.format.DateTimeFormat
import org.osmdroid.util.GeoPoint
import org.w3c.dom.Element
import org.w3c.dom.NodeList
import org.xml.sax.InputSource
import java.io.StringReader
import java.util.*
import javax.xml.parsers.DocumentBuilderFactory
// Parser for Keepright bug lists retrieved from points.php
class OsmNotesParser {
suspend fun parse(data: String): ArrayList<OsmNote> = withContext(Dispatchers.Default) {
val bugs: ArrayList<OsmNote> = ArrayList()
val doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(InputSource(StringReader(data)))
doc.documentElement.normalize()
val formatter = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss zzz")
val nList = doc.getElementsByTagName("note")
for (i in 0 until nList.length) {
val note = nList.item(i) as Element
val lat = note.getAttribute("lat").toDouble()
val lon = note.getAttribute("lon").toDouble()
val state = if (note.getElementsByTagName("status").item(0).textContent == "open") OsmNote.STATE.OPEN else OsmNote.STATE.CLOSED
val id = note.getElementsByTagName("id").item(0).textContent.toLong()
val nListComments = note.getElementsByTagName("comment")
val date = formatter.parseDateTime(note.getElementsByTagName("date").item(0).textContent)
val comments = ArrayList<OsmNoteComment>()
for (n in 0 until nListComments.length) {
val text = ((nListComments.item(n) as Element).getElementsByTagName("text").item(0).textContent)
val creationDate = formatter.parseDateTime((nListComments.item(n) as Element).getElementsByTagName("date").item(0).textContent)
val element: NodeList = (nListComments.item(n) as Element).getElementsByTagName("user")
val username = if (element.length != 0) element.item(0).textContent else null
comments.add(OsmNoteComment(text, creationDate, username ?: ""))
}
// The first comment is the Bugs main Info (Description, date and user)
val firstComment = comments[0]
comments.removeAt(0)
bugs.add(OsmNote(GeoPoint(lat, lon), id, firstComment.Comment, firstComment.User!!, date, state, comments))
}
bugs
}
} | mit | 5687236b619146e4668fc90b89fcb320 | 40.442623 | 143 | 0.684211 | 4.45679 | false | false | false | false |
Major-/Vicis | modern/src/main/kotlin/rs/emulate/modern/codec/ChecksumTable.kt | 1 | 2737 | package rs.emulate.modern.codec
import io.netty.buffer.ByteBuf
import io.netty.buffer.Unpooled
import org.bouncycastle.crypto.params.RSAKeyParameters
import org.bouncycastle.jcajce.provider.digest.Whirlpool
import rs.emulate.util.crypto.rsa.rsaEncrypt
class ChecksumTable {
val size: Int
get() = entries.size
private val entries = mutableListOf<Entry>()
fun getEntries(): List<Entry> {
return entries.toList()
}
fun addEntry(): Entry {
val size = entries.size
check(size < 255) /* not 256, as (255, 255) can't be a reference table */
val entry = Entry(size)
entries += entry
return entry
}
fun removeLastEntry() {
val size = entries.size
check(size > 0)
entries.removeAt(size - 1)
}
operator fun contains(id: Int): Boolean {
return id >= 0 && id < entries.size
}
operator fun get(id: Int): Entry = entries[id]
/* returns an immutable buffer */
fun write() = write(false, null)
/* returns an immutable buffer */
fun write(whirlpool: Boolean) = write(whirlpool, null)
/* returns an immutable buffer */
fun write(whirlpool: Boolean, privateKey: RSAKeyParameters?): ByteBuf {
val buf = Unpooled.buffer()
if (whirlpool) {
buf.writeByte(entries.size)
}
for (entry in entries) {
buf.writeInt(entry.checksum)
buf.writeInt(entry.version)
if (whirlpool) {
buf.writeBytes(entry.whirlpoolDigest!!.slice())
}
}
if (whirlpool) {
val bytes = ByteArray(buf.writerIndex())
buf.getBytes(0, bytes)
val digest = Whirlpool.Digest()
digest.update(bytes)
var temp = Unpooled.buffer(rs.emulate.util.crypto.digest.Whirlpool.DIGEST_LENGTH + 1)
temp.writeByte(1)
temp.writeBytes(digest.digest())
if (privateKey != null) {
temp = temp.rsaEncrypt(privateKey)
}
buf.writeBytes(temp)
temp.release()
}
return buf.asReadOnly()
}
class Entry(val id: Int) {
var checksum: Int = 0
var version: Int = 0
var whirlpoolDigest: ByteBuf? = null
set(value) {
field = value?.let(ByteBuf::asReadOnly)
}
}
}
fun ByteBuf.readChecksumTable(): ChecksumTable {
require(readableBytes() % 8 == 0) { "Checksum table length should be a multiple of 8" }
val table = ChecksumTable()
while (isReadable) {
val entry = table.addEntry()
entry.checksum = readInt()
entry.version = readInt()
}
return table
}
| isc | 80f4c274e146c4ca03ba49e1c5720f77 | 24.579439 | 97 | 0.580563 | 4.310236 | false | false | false | false |
Anizoptera/BacKT_WebServer | src/main/kotlin/azadev/backt/webserver/http/HttpRequestHandler.kt | 1 | 3601 | package azadev.backt.webserver.http
import azadev.backt.webserver.WebServer
import azadev.backt.webserver.callref.CallReferences
import azadev.backt.webserver.intercept.InterceptOn
import azadev.backt.webserver.routing.RouteDataToParams
import azadev.backt.webserver.routing.filterRoutes
import azadev.logging.logDebug
import azadev.logging.logError
import io.netty.buffer.Unpooled
import io.netty.channel.*
import io.netty.handler.codec.http.*
import io.netty.util.ReferenceCountUtil
import java.io.File
import java.net.InetSocketAddress
class HttpRequestHandler(
val server: WebServer
) : ChannelInboundHandlerAdapter()
{
override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
msg as? FullHttpRequest ?: return super.channelRead(ctx, msg)
server.logDebug("Request: ${msg.method()} ${msg.uri()}")
val request = Request(msg, ctx.channel().remoteAddress() as? InetSocketAddress)
val response = Response()
val routes = filterRoutes(server.routes, request)
if (!runRoutes(InterceptOn.PRE_REQUEST, routes, request, response))
return writeResponse(ctx, msg, request, response, routes)
// Looking for routes with a specific path (not ANY).
// If there are no routings with a specific path, then assume that it is 404.
if (routes.find { !it.routeData.url.isAny } != null)
runRoutes(InterceptOn.PRE_EXECUTION, routes, request, response)
&& runRoutes(InterceptOn.EXECUTION, routes, request, response)
&& runRoutes(InterceptOn.POST_EXECUTION, routes, request, response)
else {
// TODO: Return an allowed-methods response (405)
response.setStatus(HttpResponseStatus.NOT_FOUND)
}
writeResponse(ctx, msg, request, response, routes)
}
private fun runRoutes(interceptOn: InterceptOn, routes: List<RouteDataToParams>, request: Request, response: Response): Boolean {
for ((route, params) in routes)
try {
if (route.interceptOn === interceptOn && !route.interceptor.intercept(server, request, response, params))
return false
}
catch(e: Throwable) {
response.setStatus(HttpResponseStatus.INTERNAL_SERVER_ERROR)
server.exceptionHandler?.invoke(CallReferences(request, response, params), e, interceptOn)
?: server.logError("Exception during $interceptOn stage", e)
return false
}
return true
}
private fun writeResponse(ctx: ChannelHandlerContext, msg: Any, request: Request, response: Response, routes: List<RouteDataToParams>) {
if (response.status.code() / 100 == 4 || response.status.code() / 100 == 5)
runRoutes(InterceptOn.ERROR, routes, request, response)
if (response.filePathToSend != null) {
// http://netty.io/4.1/xref/io/netty/example/http/file/HttpStaticFileServerHandler.html
val file = File(response.filePathToSend)
val fileLength = file.length()
val httpResponse = DefaultHttpResponse(HttpVersion.HTTP_1_1, response.status)
httpResponse.headers().add(response.headers)
ctx.write(httpResponse)
ctx.writeAndFlush(DefaultFileRegion(file, 0, fileLength), ctx.newProgressivePromise())
.addListener(ChannelFutureListener.CLOSE)
}
else {
val bufferToSend = response.dataToSend
val buf = when (bufferToSend) {
null -> Unpooled.buffer(0)
else -> Unpooled.copiedBuffer(bufferToSend.toString(), Charsets.UTF_8)
}
val httpResponse = DefaultFullHttpResponse(HttpVersion.HTTP_1_1, response.status, buf)
httpResponse.headers().add(response.headers)
ctx.writeAndFlush(httpResponse)
.addListener(ChannelFutureListener.CLOSE)
}
runRoutes(InterceptOn.POST_REQUEST, routes, request, response)
ReferenceCountUtil.release(msg)
}
}
| mit | 61d948898e900bad1b6fc9f17c161957 | 35.373737 | 137 | 0.752846 | 3.78654 | false | false | false | false |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/quest/subquest/usecase/SaveSubQuestNameUseCase.kt | 1 | 985 | package io.ipoli.android.quest.subquest.usecase
import io.ipoli.android.common.UseCase
import io.ipoli.android.quest.Quest
import io.ipoli.android.quest.data.persistence.QuestRepository
/**
* Created by Venelin Valkov <[email protected]>
* on 03/31/2018.
*/
class SaveSubQuestNameUseCase(private val questRepository: QuestRepository) :
UseCase<SaveSubQuestNameUseCase.Params, Quest> {
override fun execute(parameters: Params): Quest {
val newName = parameters.newName
val subQuestIndex = parameters.index
val quest = questRepository.findById(parameters.questId)
requireNotNull(quest)
val sqs = quest!!.subQuests.toMutableList()
sqs[subQuestIndex] = sqs[subQuestIndex].copy(
name = newName
)
return questRepository.save(
quest.copy(
subQuests = sqs
)
)
}
data class Params(val newName: String, val questId: String, val index: Int)
} | gpl-3.0 | eaef7e8c22402a967243b376f800cdbd | 25.648649 | 79 | 0.674112 | 4.264069 | false | false | false | false |
JavaEden/Orchid-Core | languageExtensions/OrchidAsciidoc/src/main/kotlin/com/eden/orchid/languages/asciidoc/AsciiDoctorCompiler.kt | 2 | 3465 | package com.eden.orchid.languages.asciidoc
import com.caseyjbrooks.clog.Clog
import com.eden.orchid.api.OrchidContext
import com.eden.orchid.api.compilers.OrchidCompiler
import com.eden.orchid.api.options.annotations.Archetype
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.options.annotations.Option
import com.eden.orchid.api.options.annotations.StringDefault
import com.eden.orchid.api.options.archetypes.ConfigArchetype
import com.eden.orchid.api.resources.resource.FileResource
import com.eden.orchid.api.resources.resource.OrchidResource
import com.eden.orchid.languages.asciidoc.extensions.AsciidocIncludeProcessor
import org.asciidoctor.Asciidoctor
import org.asciidoctor.Options
import org.asciidoctor.SafeMode
import org.asciidoctor.jruby.internal.JRubyAsciidoctor
import org.asciidoctor.log.LogHandler
import org.asciidoctor.log.LogRecord
import org.asciidoctor.log.Severity
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.io.StringReader
import javax.inject.Inject
import javax.inject.Named
import javax.inject.Provider
import javax.inject.Singleton
@Singleton
@Archetype(value = ConfigArchetype::class, key = "services.compilers.adoc")
class AsciiDoctorCompiler
@Inject
constructor(
@Named("src") private val resourcesDir: String,
includeProcessor: AsciidocIncludeProcessor
) : OrchidCompiler(800), LogHandler {
private val asciidoctor: Asciidoctor = Asciidoctor.Factory.create()
@Option
@Description("Customize the security level Asciidoctor will run under. One of [UNSAFE, SAFE, SERVER, SECURE]")
@StringDefault("SAFE")
lateinit var safeMode: SafeMode
// register Asciidoctor instance, once during entire Orchid lifetime
init {
asciidoctor.registerLogHandler(this)
asciidoctor.javaExtensionRegistry().apply {
includeProcessor(includeProcessor)
}
}
override fun compile(os: OutputStream, resource: OrchidResource?, extension: String, input: String, data: MutableMap<String, Any>?) {
val reader = StringReader(input)
val writer = OutputStreamWriter(os)
val options = Options()
options.setSafe(safeMode)
// files can be included relative to the default resources directory
if(resource is FileResource) {
// file resources set their base dir to the file's own base dir, so relative includes are resolved properly
options.setBaseDir(resource.file.absoluteFile.parentFile.absolutePath)
}
else {
// otherwise, use the default resources dir
options.setBaseDir(resourcesDir)
}
asciidoctor.convert(reader, writer, options)
writer.close()
}
override fun getOutputExtension(): String {
return "html"
}
override fun getSourceExtensions(): Array<String> {
return arrayOf("ad", "adoc", "asciidoc", "asciidoctor")
}
override fun log(logRecord: LogRecord?) {
if (logRecord == null) return
when (logRecord.severity) {
Severity.DEBUG -> Clog.d(logRecord.message)
Severity.INFO -> Clog.i(logRecord.message)
Severity.WARN -> Clog.w(logRecord.message)
Severity.ERROR -> Clog.e(logRecord.message)
Severity.FATAL -> Clog.e(logRecord.message)
Severity.UNKNOWN -> Clog.d(logRecord.message)
else -> Clog.d(logRecord.message)
}
}
}
| mit | 7a4f70864fa5adddc0f1fead232e5360 | 35.473684 | 137 | 0.724675 | 4.220463 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/utils.kt | 2 | 1566 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.nj2k
import org.jetbrains.kotlin.lexer.KtKeywordToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.util.capitalizeDecapitalize.decapitalizeAsciiOnly
fun <T> List<T>.replace(element: T, replacer: T): List<T> {
val mutableList = toMutableList()
val index = indexOf(element)
mutableList[index] = replacer
return mutableList
}
internal inline fun <T> List<T>.mutate(mutate: MutableList<T>.() -> Unit): List<T> {
val mutableList = toMutableList()
mutate(mutableList)
return mutableList
}
fun String.asGetterName(): String? =
takeIf { JvmAbi.isGetterName(it) }
?.removePrefix("get")
?.takeIf {
it.isNotEmpty() && it.first().isUpperCase()
|| it.startsWith("is") && it.length > 2 && it[2].isUpperCase()
}?.decapitalizeAsciiOnly()
?.escaped()
fun String.asSetterName(): String? =
takeIf { JvmAbi.isSetterName(it) }
?.removePrefix("set")
?.takeIf { it.isNotEmpty() && it.first().isUpperCase() }
?.decapitalizeAsciiOnly()
?.escaped()
fun String.canBeGetterOrSetterName(): Boolean =
asGetterName() != null || asSetterName() != null
private val KEYWORDS = KtTokens.KEYWORDS.types.map { (it as KtKeywordToken).value }.toSet()
fun String.escaped() =
if (this in KEYWORDS || '$' in this) "`$this`"
else this
| apache-2.0 | 8e9e561001919a2f600d8186cbdf3dd9 | 33.043478 | 120 | 0.669221 | 4.015385 | false | false | false | false |
waynepiekarski/XPlaneMonitor | app/src/main/java/net/waynepiekarski/xplanemonitor/GraphView.kt | 1 | 5753 | // ---------------------------------------------------------------------
//
// XPlaneMonitor
//
// Copyright (C) 2017-2018 Wayne Piekarski
// [email protected] http://tinmith.net/wayne
//
// 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 net.waynepiekarski.xplanemonitor
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.util.AttributeSet
import android.view.View
class GraphView(context: Context, attrs: AttributeSet) : View(context, attrs) {
private val foreground = Paint()
private val background = Paint()
private val leader = Paint()
private var mMax: Double = -1.0
private var step: Int = 0
private var stepNext: Int = 0
private var stepPrev: Int = 0
private lateinit var current: DoubleArray
private lateinit var prev: DoubleArray
private lateinit var bitmap: Bitmap
private lateinit var canvas: Canvas
private val palette = intArrayOf(Color.RED, Color.GREEN, Color.BLUE, Color.CYAN, Color.MAGENTA, Color.YELLOW)
private val paint = Array(palette.size, { _ -> Paint() })
init {
foreground.color = Color.LTGRAY
background.color = Color.BLACK
leader.color = Color.DKGRAY
for (i in palette.indices) {
paint[i].color = palette[i]
}
resetLimits()
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
val parentWidth = View.MeasureSpec.getSize(widthMeasureSpec)
val parentHeight = View.MeasureSpec.getSize(heightMeasureSpec)
this.setMeasuredDimension(parentWidth, parentHeight)
}
private fun clearBitmap() {
if (::canvas.isInitialized) {
canvas.drawColor(background.color)
canvas.drawRect(0f, 0f, (canvas.width - 1).toFloat(), 0f, foreground)
canvas.drawRect((canvas.width - 1).toFloat(), 0f, (canvas.width - 1).toFloat(), (canvas.height - 1).toFloat(), foreground)
canvas.drawRect((canvas.width - 1).toFloat(), (canvas.height - 1).toFloat(), 0f, (canvas.height - 1).toFloat(), foreground)
canvas.drawRect(0f, (canvas.height - 1).toFloat(), 0f, 0f, foreground)
}
}
override fun onDraw(liveCanvas: Canvas) {
if (!::bitmap.isInitialized || bitmap.width != liveCanvas.width || bitmap.height != liveCanvas.height) {
bitmap = Bitmap.createBitmap(liveCanvas.width, liveCanvas.height, Bitmap.Config.ARGB_8888)
canvas = Canvas(bitmap)
clearBitmap()
}
super.onDraw(canvas)
// Clear out pixels on the current column before we draw here
canvas.drawLine(step.toFloat(), 0f, step.toFloat(), canvas.height.toFloat(), background)
canvas.drawLine(stepNext.toFloat(), 0f, stepNext.toFloat(), canvas.height.toFloat(), leader)
// Plot the latest data at the current column
if (::current.isInitialized) {
for (i in current.indices) {
val x1 = stepPrev
val y1 = (canvas.height / 2.0 + prev[i] / mMax * canvas.height / 2.0).toInt()
val x2 = step
val y2 = (canvas.height / 2.0 + current[i] / mMax * canvas.height / 2.0).toInt()
// Only draw if there is no wrap-around
if (x2 > x1)
canvas.drawLine(x1.toFloat(), y1.toFloat(), x2.toFloat(), y2.toFloat(), paint[i])
}
}
liveCanvas.drawBitmap(bitmap, 0f, 0f, foreground)
step += 1
if (step > canvas.width)
step = 0
stepNext += 1
if (stepNext > canvas.width)
stepNext = 0
stepPrev += 1
if (stepPrev > canvas.width)
stepPrev = 0
// Save the current values as previous values for the next run
val temp = prev
prev = current
current = temp
}
fun setValues(arg: FloatArray) {
assert(min(arg.size, palette.size) == current.size) {"Mismatch between incoming length " + current.size + " with existing " + arg.size }
for (i in 0 until min(arg.size, palette.size))
current[i] = arg[i].toDouble()
invalidate()
}
fun set1Value(arg: Double) {
assert(1 == current.size) { "Mismatch between incoming length " + current.size + " with existing 1" }
current[0] = arg
invalidate()
}
fun resetLimits(max: Double = 1.0, size: Int = 1) {
step = 0
stepNext = step + 1
stepPrev = step - 1
mMax = 1.0
var length = size
if (length > palette.size)
length = palette.size
if (!::current.isInitialized || length != current.size) {
current = DoubleArray(length)
prev = DoubleArray(length)
}
clearBitmap()
mMax = max
invalidate()
}
companion object {
fun min(a: Int, b: Int): Int {
return if (a < b)
a
else
b
}
}
}
| gpl-3.0 | a6c3fe5617652297adf00f0e305618be | 34.512346 | 144 | 0.597427 | 4.236377 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/util/GHEnterpriseServerMetadataLoader.kt | 8 | 2074 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.util
import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask
import com.intellij.collaboration.util.ProgressIndicatorsProvider
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.util.Disposer
import org.jetbrains.annotations.CalledInAny
import org.jetbrains.plugins.github.api.GithubApiRequest
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.api.data.GHEnterpriseServerMeta
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
@Service
class GHEnterpriseServerMetadataLoader : Disposable {
private val apiRequestExecutor = GithubApiRequestExecutor.Factory.getInstance().create()
private val serverMetadataRequests = ConcurrentHashMap<GithubServerPath, CompletableFuture<GHEnterpriseServerMeta>>()
private val indicatorProvider = ProgressIndicatorsProvider().also {
Disposer.register(this, it)
}
@CalledInAny
fun loadMetadata(server: GithubServerPath): CompletableFuture<GHEnterpriseServerMeta> {
require(!server.isGithubDotCom) { "Cannot retrieve server metadata from github.com" }
return serverMetadataRequests.getOrPut(server) {
ProgressManager.getInstance().submitIOTask(indicatorProvider) {
val metaUrl = server.toApiUrl() + "/meta"
apiRequestExecutor.execute(it, GithubApiRequest.Get.json<GHEnterpriseServerMeta>(metaUrl))
}
}
}
@CalledInAny
internal fun findRequestByEndpointUrl(url: String): CompletableFuture<GHEnterpriseServerMeta>? {
for ((server, request) in serverMetadataRequests) {
val serverUrl = server.toUrl()
if (url.startsWith(serverUrl)) return request
}
return null
}
override fun dispose() {}
} | apache-2.0 | d5ac4642046f36cc4af8523f591afa23 | 42.229167 | 140 | 0.802314 | 4.789838 | false | false | false | false |
GunoH/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/GHPRMetadataPanelFactory.kt | 2 | 5852 | // 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.github.pullrequest.ui.details
import com.intellij.collaboration.util.CollectionDelta
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.ui.components.panels.Wrapper
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import net.miginfocom.layout.CC
import net.miginfocom.layout.LC
import net.miginfocom.swing.MigLayout
import org.jetbrains.plugins.github.api.data.GHLabel
import org.jetbrains.plugins.github.api.data.GHUser
import org.jetbrains.plugins.github.api.data.pullrequest.GHPullRequestRequestedReviewer
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.ui.avatars.GHAvatarIconsProvider
import org.jetbrains.plugins.github.ui.component.LabeledListPanelHandle
import org.jetbrains.plugins.github.ui.util.GHUIUtil
import java.util.concurrent.CompletableFuture
import javax.swing.JComponent
import javax.swing.JLabel
import javax.swing.JPanel
import javax.swing.SwingConstants
class GHPRMetadataPanelFactory(private val model: GHPRMetadataModel,
private val avatarIconsProvider: GHAvatarIconsProvider) {
private val panel = JPanel(null)
fun create(): JComponent {
val reviewersHandle = ReviewersListPanelHandle()
val assigneesHandle = AssigneesListPanelHandle()
val labelsHandle = LabelsListPanelHandle()
return panel.apply {
isOpaque = false
layout = MigLayout(LC()
.fillX()
.gridGap("0", "0")
.insets("0", "0", "0", "0"))
addListPanel(this, reviewersHandle)
addListPanel(this, assigneesHandle)
addListPanel(this, labelsHandle)
}
}
private inner class ReviewersListPanelHandle
: LabeledListPanelHandle<GHPullRequestRequestedReviewer>(model,
GithubBundle.message("pull.request.no.reviewers"),
"${GithubBundle.message("pull.request.reviewers")}:") {
override fun getItems(): List<GHPullRequestRequestedReviewer> = model.reviewers
override fun getItemComponent(item: GHPullRequestRequestedReviewer) = createUserLabel(item)
override fun showEditPopup(parentComponent: JComponent): CompletableFuture<CollectionDelta<GHPullRequestRequestedReviewer>> {
return GHUIUtil
.showChooserPopup(GithubBundle.message("pull.request.reviewers"), parentComponent,
GHUIUtil.SelectionListCellRenderer.PRReviewers(avatarIconsProvider),
model.reviewers, model.loadPotentialReviewers())
}
override fun adjust(indicator: ProgressIndicator, delta: CollectionDelta<GHPullRequestRequestedReviewer>) =
model.adjustReviewers(indicator, delta)
}
private inner class AssigneesListPanelHandle
: LabeledListPanelHandle<GHUser>(model,
GithubBundle.message("pull.request.unassigned"),
"${GithubBundle.message("pull.request.assignees")}:") {
override fun getItems(): List<GHUser> = model.assignees
override fun getItemComponent(item: GHUser) = createUserLabel(item)
override fun showEditPopup(parentComponent: JComponent): CompletableFuture<CollectionDelta<GHUser>> = GHUIUtil
.showChooserPopup(GithubBundle.message("pull.request.assignees"), parentComponent,
GHUIUtil.SelectionListCellRenderer.Users(avatarIconsProvider),
model.assignees, model.loadPotentialAssignees())
override fun adjust(indicator: ProgressIndicator, delta: CollectionDelta<GHUser>) =
model.adjustAssignees(indicator, delta)
}
private fun createUserLabel(user: GHPullRequestRequestedReviewer) = JLabel(user.shortName,
avatarIconsProvider.getIcon(user.avatarUrl,
GHUIUtil.AVATAR_SIZE),
SwingConstants.LEFT).apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP / 2, UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP / 2)
}
private inner class LabelsListPanelHandle
: LabeledListPanelHandle<GHLabel>(model,
GithubBundle.message("pull.request.no.labels"),
"${GithubBundle.message("pull.request.labels")}:") {
override fun getItems(): List<GHLabel> = model.labels
override fun getItemComponent(item: GHLabel) = createLabelLabel(item)
override fun showEditPopup(parentComponent: JComponent): CompletableFuture<CollectionDelta<GHLabel>> =
GHUIUtil.showChooserPopup(GithubBundle.message("pull.request.labels"), parentComponent,
GHUIUtil.SelectionListCellRenderer.Labels(),
model.labels, model.loadAssignableLabels())
override fun adjust(indicator: ProgressIndicator, delta: CollectionDelta<GHLabel>) =
model.adjustLabels(indicator, delta)
}
private fun createLabelLabel(label: GHLabel) = Wrapper(GHUIUtil.createIssueLabelLabel(label)).apply {
border = JBUI.Borders.empty(UIUtil.DEFAULT_VGAP + 1, UIUtil.DEFAULT_HGAP / 2, UIUtil.DEFAULT_VGAP + 2, UIUtil.DEFAULT_HGAP / 2)
}
companion object {
private fun addListPanel(panel: JPanel, handle: LabeledListPanelHandle<*>) {
panel.add(handle.label, CC().alignY("top").width(":${handle.preferredLabelWidth}:"))
panel.add(handle.panel, CC().minWidth("0").growX().pushX().wrap())
}
}
} | apache-2.0 | 2d9d28964c1db8db08c30528eca4e664 | 46.97541 | 131 | 0.674983 | 5.115385 | false | false | false | false |
tginsberg/advent-2016-kotlin | src/main/kotlin/com/ginsberg/advent2016/Day21.kt | 1 | 3855 | /*
* Copyright (c) 2016 by Todd Ginsberg
*/
package com.ginsberg.advent2016
/**
* Advent of Code - Day 21: December 21, 2016
*
* From http://adventofcode.com/2016/day/21
*
*/
class Day21(val instructions: List<String>) {
companion object {
private val SWAP_POSITION = Regex("""^swap position (\d+) with position (\d+)$""")
private val SWAP_LETTERS = Regex("""^swap letter (\S) with letter (\S)$""")
private val ROTATE_SHIFT = Regex("""^rotate (left|right) (\d+) step(s?)$""")
private val ROTATE_LETTER = Regex("""^rotate based on position of letter (\S)$""")
private val REVERSE = Regex("""^reverse positions (\d+) through (\d+)$""")
private val MOVE = Regex("""^move position (\d+) to position (\d+)$""")
private val RIGHT_SHIFT = listOf(1,2,3,4,6,7,8,9)
private val LEFT_SHIFT = listOf(9,1,6,2,7,3,8,4)
}
fun solvePart1(word: String): String =
instructions.fold(word){ carry, next -> mutate(carry, next, true)}
fun solvePart2(word: String): String =
instructions.reversed().fold(word){ carry, next -> mutate(carry, next, false)}
fun mutate(input: String, instruction: String, forward: Boolean): String =
when {
SWAP_POSITION.matches(instruction) -> {
val (x, y) = SWAP_POSITION.matchEntire(instruction)!!.destructured
swapPosition(input, x.toInt(), y.toInt())
}
SWAP_LETTERS.matches(instruction) -> {
val (x, y) = SWAP_LETTERS.matchEntire(instruction)!!.destructured
swapLetters(input, x[0], y[0])
}
ROTATE_SHIFT.matches(instruction) -> {
val (dir, x) = ROTATE_SHIFT.matchEntire(instruction)!!.destructured
if(forward) rotateShift(input, dir, x.toInt())
else rotateShift(input, if(dir == "left") "right" else "left", x.toInt())
}
ROTATE_LETTER.matches(instruction) -> {
val (x) = ROTATE_LETTER.matchEntire(instruction)!!.destructured
rotateLetter(input, x[0], forward)
}
REVERSE.matches(instruction) -> {
val (x, y) = REVERSE.matchEntire(instruction)!!.destructured
reverse(input, x.toInt(), y.toInt())
}
MOVE.matches(instruction) -> {
val (x, y) = MOVE.matchEntire(instruction)!!.destructured
if(forward) move(input, x.toInt(), y.toInt())
else move(input, y.toInt(), x.toInt())
}
else -> input
}
fun swapPosition(input: String, x: Int, y: Int): String {
val arr = input.toCharArray()
val tmp = input[x]
arr[x] = arr[y]
arr[y] = tmp
return arr.joinToString("")
}
fun swapLetters(input: String, x: Char, y: Char): String =
input.map { if(it == x) y else if(it == y) x else it }.joinToString("")
fun rotateShift(input: String, direction: String, steps: Int): String {
val sm = steps % input.length
return if (direction == "left") input.drop(sm) + input.take(sm)
else input.drop(input.length - sm).take(sm) + input.take(input.length - sm)
}
fun rotateLetter(input: String, ch: Char, forward: Boolean): String {
val idx = input.indexOf(ch)
return if(forward) rotateShift(input, "right", RIGHT_SHIFT[idx])
else rotateShift(input, "left", LEFT_SHIFT[idx])
}
fun reverse(input: String, x: Int, y: Int): String =
input.substring(0, x) + input.drop(x).take(y-x+1).reversed() + input.drop(y+1)
fun move(input: String, x: Int, y: Int): String {
val ch = input[x]
val unX = input.substring(0, x) + input.substring(x+1)
return unX.substring(0, y) + ch + unX.substring(y)
}
}
| mit | 2858f1e7edb9e27d63ed5d14fa781325 | 39.578947 | 90 | 0.566018 | 3.783121 | false | false | false | false |
GunoH/intellij-community | platform/build-scripts/src/org/jetbrains/intellij/build/impl/projectStructureMapping/DistributionFileEntry.kt | 2 | 2421 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.intellij.build.impl.projectStructureMapping
import org.jetbrains.intellij.build.impl.ProjectLibraryData
import java.nio.file.Path
sealed interface DistributionFileEntry {
/**
* Path to a file in IDE distribution
*/
val path: Path
/**
* Type of the element in the project configuration which was copied to [.path]
*/
val type: String
fun changePath(newFile: Path): DistributionFileEntry
}
interface LibraryFileEntry : DistributionFileEntry {
val libraryFile: Path?
val size: Int
}
/**
* Represents a file in module-level library
*/
internal class ModuleLibraryFileEntry(override val path: Path,
@JvmField val moduleName: String,
override val libraryFile: Path?,
override val size: Int) : DistributionFileEntry, LibraryFileEntry {
override val type: String
get() = "module-library-file"
override fun changePath(newFile: Path) = ModuleLibraryFileEntry(newFile, moduleName, libraryFile, size)
}
/**
* Represents test classes of a module
*/
internal class ModuleTestOutputEntry(override val path: Path, @JvmField val moduleName: String) : DistributionFileEntry {
override val type: String
get() = "module-test-output"
override fun changePath(newFile: Path) = ModuleTestOutputEntry(newFile, moduleName)
}
/**
* Represents a project-level library
*/
internal class ProjectLibraryEntry(
override val path: Path,
@JvmField val data: ProjectLibraryData,
override val libraryFile: Path?,
override val size: Int
) : DistributionFileEntry, LibraryFileEntry {
override val type: String
get() = "project-library"
override fun changePath(newFile: Path) = ProjectLibraryEntry(newFile, data, libraryFile, size)
override fun toString() = "ProjectLibraryEntry(data='$data\', libraryFile=$libraryFile, size=$size)"
}
/**
* Represents production classes of a module
*/
class ModuleOutputEntry(
override val path: Path,
@JvmField val moduleName: String,
@JvmField val size: Int,
@JvmField val reason: String? = null
) : DistributionFileEntry {
override val type: String
get() = "module-output"
override fun changePath(newFile: Path) = ModuleOutputEntry(newFile, moduleName, size, reason)
} | apache-2.0 | b367f9b7a9f192d9d804f6b46da55e93 | 29.658228 | 121 | 0.713342 | 4.5 | false | true | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/search/SearchResult.kt | 4 | 1089 | package org.thoughtcrime.securesms.search
import org.thoughtcrime.securesms.database.model.ThreadRecord
import org.thoughtcrime.securesms.recipients.Recipient
/**
* Represents an all-encompassing search result that can contain various result for different
* subcategories.
*/
data class SearchResult(
val query: String,
val contacts: List<Recipient>,
val conversations: List<ThreadRecord>,
val messages: List<MessageResult>
) {
fun size(): Int {
return contacts.size + conversations.size + messages.size
}
val isEmpty: Boolean
get() = size() == 0
fun merge(result: ContactSearchResult): SearchResult {
return this.copy(contacts = result.results, query = result.query)
}
fun merge(result: ThreadSearchResult): SearchResult {
return this.copy(conversations = result.results, query = result.query)
}
fun merge(result: MessageSearchResult): SearchResult {
return this.copy(messages = result.results, query = result.query)
}
companion object {
@JvmField
val EMPTY = SearchResult("", emptyList(), emptyList(), emptyList())
}
}
| gpl-3.0 | 4e1a4dcdd7b19bbf4911bb403d1d3768 | 26.923077 | 93 | 0.730028 | 4.338645 | false | false | false | false |
jk1/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/migLayout/MigLayoutBuilder.kt | 3 | 7876 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui.layout.migLayout
import com.intellij.ui.components.noteComponent
import com.intellij.ui.layout.*
import com.intellij.ui.layout.migLayout.patched.*
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.ui.JBUI
import net.miginfocom.layout.*
import java.awt.Component
import java.awt.Container
import javax.swing.ButtonGroup
import javax.swing.JComponent
import javax.swing.JDialog
import javax.swing.JLabel
internal class MigLayoutBuilder(val spacing: SpacingConfiguration, val isUseMagic: Boolean = true) : LayoutBuilderImpl {
companion object {
private var hRelatedGap = -1
private var vRelatedGap = -1
init {
JBUI.addPropertyChangeListener(JBUI.USER_SCALE_FACTOR_PROPERTY) {
updatePlatformDefaults()
}
}
private fun updatePlatformDefaults() {
if (hRelatedGap != -1 && vRelatedGap != -1) {
PlatformDefaults.setRelatedGap(createUnitValue(hRelatedGap, true), createUnitValue(vRelatedGap, false))
}
}
private fun setRelatedGap(h: Int, v: Int) {
if (hRelatedGap == h && vRelatedGap == v) {
return
}
hRelatedGap = h
vRelatedGap = v
updatePlatformDefaults()
}
}
init {
setRelatedGap(spacing.horizontalGap, spacing.verticalGap)
}
/**
* Map of component to constraints shared among rows (since components are unique)
*/
private val componentConstraints: MutableMap<Component, CC> = ContainerUtil.newIdentityTroveMap()
private val rootRow = MigLayoutRow(parent = null, componentConstraints = componentConstraints, builder = this, indent = 0)
val defaultComponentConstraintCreator = DefaultComponentConstraintCreator(spacing)
// keep in mind - MigLayout always creates one more than need column constraints (i.e. for 2 will be 3)
// it doesn't lead to any issue.
val columnConstraints = AC()
override fun newRow(label: JLabel?, buttonGroup: ButtonGroup?, separated: Boolean): Row {
return rootRow.createChildRow(label = label, buttonGroup = buttonGroup, separated = separated)
}
override fun noteRow(text: String, linkHandler: ((url: String) -> Unit)?) {
val cc = CC()
cc.vertical.gapBefore = gapToBoundSize(if (rootRow.subRows == null) spacing.verticalGap else spacing.largeVerticalGap, false)
cc.vertical.gapAfter = gapToBoundSize(spacing.verticalGap * 2, false)
val row = rootRow.createChildRow(label = null, noGrid = true)
row.apply {
val noteComponent = noteComponent(text, linkHandler)
componentConstraints.put(noteComponent, cc)
noteComponent()
}
}
override fun build(container: Container, layoutConstraints: Array<out LCFlags>) {
val lc = createLayoutConstraints()
lc.gridGapY = gapToBoundSize(spacing.verticalGap, false)
if (layoutConstraints.isEmpty()) {
lc.fillX()
// not fillY because it leads to enormously large cells - we use cc `push` in addition to cc `grow` as a more robust and easy solution
}
else {
lc.apply(layoutConstraints)
}
lc.isVisualPadding = spacing.isCompensateVisualPaddings
lc.hideMode = 3
// if constraint specified only for rows 0 and 1, MigLayout will use constraint 1 for any rows with index 1+ (see LayoutUtil.getIndexSafe - use last element if index > size)
val rowConstraints = AC()
rowConstraints.align(if (isUseMagic) "baseline" else "top")
(container as JComponent).putClientProperty("isVisualPaddingCompensatedOnComponentLevel", false)
var isLayoutInsetsAdjusted = false
container.layout = object : MigLayout(lc, columnConstraints, rowConstraints) {
override fun layoutContainer(parent: Container) {
if (!isLayoutInsetsAdjusted) {
isLayoutInsetsAdjusted = true
var topParent = parent.parent
while (topParent != null) {
if (topParent is JDialog) {
val topBottom = createUnitValue(spacing.dialogTopBottom, false)
val leftRight = createUnitValue(spacing.dialogLeftRight, true)
// since we compensate visual padding, child components should be not clipped, so, we do not use content pane DialogWrapper border (returns null),
// but instead set insets to our content panel (so, child components are not clipped)
lc.insets = arrayOf(topBottom, leftRight, topBottom, leftRight)
break
}
topParent = topParent.parent
}
}
super.layoutContainer(parent)
}
}
val isNoGrid = layoutConstraints.contains(LCFlags.noGrid)
var rowIndex = 0
fun configureComponents(row: MigLayoutRow) {
val lastComponent = row.components.lastOrNull()
for ((index, component) in row.components.withIndex()) {
// MigLayout in any case always creates CC, so, create instance even if it is not required
val cc = componentConstraints.get(component) ?: CC()
if (isNoGrid) {
container.add(component, cc)
continue
}
// we cannot use columnCount as an indicator of whether to use spanX/wrap or not because component can share cell with another component,
// in any case MigLayout is smart enough and unnecessary spanX/wrap doesn't harm
if (component === lastComponent) {
cc.spanX()
cc.wrap()
}
if (row.noGrid) {
if (component === row.components.first()) {
rowConstraints.noGrid(rowIndex)
}
}
else if (component === row.components.first()) {
row.gapAfter?.let {
rowConstraints.gap(it, rowIndex)
}
}
if (index >= row.rightIndex) {
cc.horizontal.gapBefore = BoundSize(null, null, null, true, null)
}
container.add(component, cc)
}
rowIndex++
}
fun processRows(rows: List<MigLayoutRow>) {
for (row in rows) {
configureComponents(row)
row.subRows?.let {
processRows(it)
}
}
}
rootRow.subRows?.let {
configureGapBetweenColumns(it)
processRows(it)
}
// do not hold components
componentConstraints.clear()
}
private fun configureGapBetweenColumns(subRows: List<MigLayoutRow>) {
var startColumnIndexToApplyHorizontalGap = 0
if (subRows.any { it.isLabeledIncludingSubRows }) {
// using columnConstraints instead of component gap allows easy debug (proper painting of debug grid)
columnConstraints.gap("${spacing.labelColumnHorizontalGap}px!", 0)
columnConstraints.grow(0f, 0)
startColumnIndexToApplyHorizontalGap = 1
}
val gapAfter = "${spacing.horizontalGap}px!"
for (i in startColumnIndexToApplyHorizontalGap until rootRow.columnIndexIncludingSubRows) {
columnConstraints.gap(gapAfter, i)
}
}
}
internal fun gapToBoundSize(value: Int, isHorizontal: Boolean): BoundSize {
val unitValue = createUnitValue(value, isHorizontal)
return BoundSize(unitValue, unitValue, null, false, null)
}
fun createLayoutConstraints(): LC {
val lc = LC()
lc.gridGapX = gapToBoundSize(0, true)
lc.insets("0px")
return lc
}
private fun createUnitValue(value: Int, isHorizontal: Boolean): UnitValue {
return UnitValue(value.toFloat(), "px", isHorizontal, UnitValue.STATIC, null)
}
private fun LC.apply(flags: Array<out LCFlags>): LC {
for (flag in flags) {
@Suppress("NON_EXHAUSTIVE_WHEN")
when (flag) {
LCFlags.noGrid -> isNoGrid = true
LCFlags.flowY -> isFlowX = false
LCFlags.fill -> fill()
LCFlags.fillX -> isFillX = true
LCFlags.fillY -> isFillY = true
LCFlags.lcWrap -> wrapAfter = 0
LCFlags.debug -> debug()
}
}
return this
} | apache-2.0 | 26a06bee7df940b68de7dde34f3c3401 | 33.099567 | 177 | 0.678771 | 4.368275 | false | false | false | false |
AsamK/TextSecure | app/src/main/java/org/thoughtcrime/securesms/components/settings/app/notifications/profiles/NotificationProfilesFragment.kt | 1 | 4586 | package org.thoughtcrime.securesms.components.settings.app.notifications.profiles
import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.emoji.EmojiUtil
import org.thoughtcrime.securesms.components.settings.DSLConfiguration
import org.thoughtcrime.securesms.components.settings.DSLSettingsAdapter
import org.thoughtcrime.securesms.components.settings.DSLSettingsFragment
import org.thoughtcrime.securesms.components.settings.DSLSettingsIcon
import org.thoughtcrime.securesms.components.settings.DSLSettingsText
import org.thoughtcrime.securesms.components.settings.NO_TINT
import org.thoughtcrime.securesms.components.settings.app.notifications.profiles.models.NoNotificationProfiles
import org.thoughtcrime.securesms.components.settings.app.notifications.profiles.models.NotificationProfilePreference
import org.thoughtcrime.securesms.components.settings.configure
import org.thoughtcrime.securesms.components.settings.conversation.preferences.LargeIconClickPreference
import org.thoughtcrime.securesms.notifications.profiles.NotificationProfile
import org.thoughtcrime.securesms.notifications.profiles.NotificationProfiles
import org.thoughtcrime.securesms.util.LifecycleDisposable
import org.thoughtcrime.securesms.util.navigation.safeNavigate
/**
* Primary entry point for Notification Profiles. When user has no profiles, shows empty state, otherwise shows
* all current profiles.
*/
class NotificationProfilesFragment : DSLSettingsFragment() {
private val viewModel: NotificationProfilesViewModel by viewModels(
factoryProducer = { NotificationProfilesViewModel.Factory() }
)
private val lifecycleDisposable = LifecycleDisposable()
private var toolbar: Toolbar? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbar = view.findViewById(R.id.toolbar)
lifecycleDisposable.bindTo(viewLifecycleOwner.lifecycle)
}
override fun onDestroyView() {
super.onDestroyView()
toolbar = null
}
override fun bindAdapter(adapter: DSLSettingsAdapter) {
NoNotificationProfiles.register(adapter)
LargeIconClickPreference.register(adapter)
NotificationProfilePreference.register(adapter)
lifecycleDisposable += viewModel.getProfiles()
.subscribe { profiles ->
if (profiles.isEmpty()) {
toolbar?.title = ""
} else {
toolbar?.setTitle(R.string.NotificationsSettingsFragment__notification_profiles)
}
adapter.submitList(getConfiguration(profiles).toMappingModelList())
}
}
private fun getConfiguration(profiles: List<NotificationProfile>): DSLConfiguration {
return configure {
if (profiles.isEmpty()) {
customPref(
NoNotificationProfiles.Model(
onClick = { findNavController().safeNavigate(R.id.action_notificationProfilesFragment_to_editNotificationProfileFragment) }
)
)
} else {
sectionHeaderPref(R.string.NotificationProfilesFragment__profiles)
customPref(
LargeIconClickPreference.Model(
title = DSLSettingsText.from(R.string.NotificationProfilesFragment__new_profile),
icon = DSLSettingsIcon.from(R.drawable.add_to_a_group, NO_TINT),
onClick = { findNavController().safeNavigate(R.id.action_notificationProfilesFragment_to_editNotificationProfileFragment) }
)
)
val activeProfile: NotificationProfile? = NotificationProfiles.getActiveProfile(profiles)
profiles.sortedDescending().forEach { profile ->
customPref(
NotificationProfilePreference.Model(
title = DSLSettingsText.from(profile.name),
summary = if (profile == activeProfile) DSLSettingsText.from(NotificationProfiles.getActiveProfileDescription(requireContext(), profile)) else null,
icon = if (profile.emoji.isNotEmpty()) EmojiUtil.convertToDrawable(requireContext(), profile.emoji)?.let { DSLSettingsIcon.from(it) } else DSLSettingsIcon.from(R.drawable.ic_moon_24, NO_TINT),
color = profile.color,
onClick = {
findNavController().safeNavigate(NotificationProfilesFragmentDirections.actionNotificationProfilesFragmentToNotificationProfileDetailsFragment(profile.id))
}
)
)
}
}
}
}
}
| gpl-3.0 | 8940cd920918f385070f3d928aac9452 | 43.524272 | 206 | 0.760576 | 5.23516 | false | true | false | false |
ktorio/ktor | ktor-utils/common/src/io/ktor/util/CaseInsensitiveMap.kt | 1 | 2381 | /*
* 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.util
/**
* A map with case-insensitive [String] keys
*/
public class CaseInsensitiveMap<Value : Any> : MutableMap<String, Value> {
private val delegate = mutableMapOf<CaseInsensitiveString, Value>()
override val size: Int get() = delegate.size
override fun containsKey(key: String): Boolean = delegate.containsKey(CaseInsensitiveString(key))
override fun containsValue(value: Value): Boolean = delegate.containsValue(value)
override fun get(key: String): Value? = delegate[key.caseInsensitive()]
override fun isEmpty(): Boolean = delegate.isEmpty()
override fun clear() {
delegate.clear()
}
override fun put(key: String, value: Value): Value? = delegate.put(key.caseInsensitive(), value)
override fun putAll(from: Map<out String, Value>) {
from.forEach { (key, value) -> put(key, value) }
}
override fun remove(key: String): Value? = delegate.remove(key.caseInsensitive())
override val keys: MutableSet<String>
get() = DelegatingMutableSet(
delegate.keys,
{ content },
{ caseInsensitive() }
)
override val entries: MutableSet<MutableMap.MutableEntry<String, Value>>
get() = DelegatingMutableSet(
delegate.entries,
{ Entry(key.content, value) },
{ Entry(key.caseInsensitive(), value) }
)
override val values: MutableCollection<Value> get() = delegate.values
override fun equals(other: Any?): Boolean {
if (other == null || other !is CaseInsensitiveMap<*>) return false
return other.delegate == delegate
}
override fun hashCode(): Int = delegate.hashCode()
}
private class Entry<Key, Value>(
override val key: Key,
override var value: Value
) : MutableMap.MutableEntry<Key, Value> {
override fun setValue(newValue: Value): Value {
value = newValue
return value
}
override fun hashCode(): Int = 17 * 31 + key!!.hashCode() + value!!.hashCode()
override fun equals(other: Any?): Boolean {
if (other == null || other !is Map.Entry<*, *>) return false
return other.key == key && other.value == value
}
override fun toString(): String = "$key=$value"
}
| apache-2.0 | 813bb5426a0d52ca2a6d4c4bdb4c78d3 | 29.922078 | 118 | 0.645527 | 4.384899 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/WGL.kt | 4 | 11051 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
import core.windows.*
val WGL = "WGL".nativeClass(Module.OPENGL, prefix = "WGL", binding = GLBinding.delegate("GL.getFunctionProvider()")) {
nativeImport("WindowsLWJGL.h")
javaImport("org.lwjgl.system.windows.*")
documentation = "Native bindings to WGL functionality."
IntConstant(
"UseFontOutlines format.",
"FONT_LINES".."0",
"FONT_POLYGONS".."1"
)
IntConstant(
"SwapLayerBuffers flags.",
"SWAP_MAIN_PLANE"..0x00000001,
"SWAP_OVERLAY1"..0x00000002,
"SWAP_OVERLAY2"..0x00000004,
"SWAP_OVERLAY3"..0x00000008,
"SWAP_OVERLAY4"..0x00000010,
"SWAP_OVERLAY5"..0x00000020,
"SWAP_OVERLAY6"..0x00000040,
"SWAP_OVERLAY7"..0x00000080,
"SWAP_OVERLAY8"..0x00000100,
"SWAP_OVERLAY9"..0x00000200,
"SWAP_OVERLAY10"..0x00000400,
"SWAP_OVERLAY11"..0x00000800,
"SWAP_OVERLAY12"..0x00001000,
"SWAP_OVERLAY13"..0x00002000,
"SWAP_OVERLAY14"..0x00004000,
"SWAP_OVERLAY15"..0x00008000,
"SWAP_UNDERLAY1"..0x00010000,
"SWAP_UNDERLAY2"..0x00020000,
"SWAP_UNDERLAY3"..0x00040000,
"SWAP_UNDERLAY4"..0x00080000,
"SWAP_UNDERLAY5"..0x00100000,
"SWAP_UNDERLAY6"..0x00200000,
"SWAP_UNDERLAY7"..0x00400000,
"SWAP_UNDERLAY8"..0x00800000,
"SWAP_UNDERLAY9"..0x01000000,
"SWAP_UNDERLAY10"..0x02000000,
"SWAP_UNDERLAY11"..0x04000000,
"SWAP_UNDERLAY12"..0x08000000,
"SWAP_UNDERLAY13"..0x10000000,
"SWAP_UNDERLAY14"..0x20000000,
"SWAP_UNDERLAY15"..0x40000000
)
SaveLastError..HGLRC(
"CreateContext",
"""
Creates a new OpenGL rendering context, which is suitable for drawing on the device referenced by device. The rendering context has the same pixel
format as the device context.
""",
HDC("hdc", "handle to a device context for which the function creates a suitable OpenGL rendering context")
)
SaveLastError..HGLRC(
"CreateLayerContext",
"Creates a new OpenGL rendering context for drawing to a specified layer plane on a device context.",
HDC("hdc", "the device context for a new rendering context"),
int(
"layerPlane",
"""
the layer plane to which you want to bind a rendering context. The value 0 identifies the main plane. Positive values of {@code layerPlace} identify
overlay planes, where 1 is the first overlay plane over the main plane, 2 is the second overlay plane over the first overlay plane, and so on.
Negative values identify underlay planes, where 1 is the first underlay plane under the main plane, 2 is the second underlay plane under the first
underlay plane, and so on. The number of overlay and underlay planes is given in the {@code reserved} member of the ##PIXELFORMATDESCRIPTOR
structure.
"""
)
)
SaveLastError..BOOL(
"CopyContext",
"Copies selected groups of rendering states from one OpenGL rendering context to another.",
HGLRC("src", "the source OpenGL rendering context whose state information is to be copied"),
HGLRC("dst", "the destination OpenGL rendering context to which state information is to be copied"),
UINT(
"mask",
"""
which groups of the {@code src} rendering state are to be copied to {@code dst}. It contains the bitwise-OR of the same symbolic names that are
passed to the #PushAttrib() function. You can use #ALL_ATTRIB_BITS to copy all the rendering state information.
"""
)
)
SaveLastError..BOOL(
"DeleteContext",
"Deletes a specified OpenGL rendering context.",
HGLRC("context", "handle to an OpenGL rendering context that the function will delete")
)
SaveLastError..HGLRC(
"GetCurrentContext",
"Obtains a handle to the current OpenGL rendering context of the calling thread.",
void()
)
SaveLastError..HDC(
"GetCurrentDC",
"Obtains a handle to the device context that is associated with the current OpenGL rendering context of the calling thread.",
void()
)
SaveLastError..PROC(
"GetProcAddress",
"Returns the address of an OpenGL extension function for use with the current OpenGL rendering context.",
LPCSTR(
"proc",
"""
points to a null-terminated string that is the name of the extension function. The name of the extension function must be identical to a
corresponding function implemented by OpenGL.
"""
)
)
SaveLastError..BOOL(
"MakeCurrent",
"""
Makes a specified OpenGL rendering context the calling thread's current rendering context. All subsequent OpenGL calls made by the thread are drawn on
the device identified by device. You can also use MakeCurrent to change the calling thread's current rendering context so it's no longer current.
""",
nullable..HDC("hdc", "handle to a device context. Subsequent OpenGL calls made by the calling thread are drawn on the device identified by {@code dc}."),
nullable..HGLRC(
"hglrc",
"""
handle to an OpenGL rendering context that the function sets as the calling thread's rendering context. If {@code context} is #NULL, the function
makes the calling thread's current rendering context no longer current, and releases the device context that is used by the rendering context. In
this case, {@code hdc} is ignored.
"""
)
)
SaveLastError..BOOL(
"ShareLists",
"Enables multiple OpenGL rendering contexts to share a single display-list space.",
HGLRC("hglrc1", "the OpenGL rendering context with which to share display lists."),
HGLRC(
"hglrc2",
"""
the OpenGL rendering context to share display lists with {@code hglrc1}. The {@code hglrc2} parameter should not contain any existing display lists
when {@code wglShareLists} is called.
"""
)
)
/*
WINGDIAPI BOOL WINAPI DescribeLayerPlane(HDC, int, int, UINT, LPLAYERPLANEDESCRIPTOR);
WINGDIAPI int WINAPI SetLayerPaletteEntries(HDC, int, int, int, CONST COLORREF *);
WINGDIAPI int WINAPI GetLayerPaletteEntries(HDC, int, int, int, COLORREF *);
WINGDIAPI BOOL WINAPI RealizeLayerPalette(HDC, int, BOOL);
WINGDIAPI BOOL WINAPI SwapLayerBuffers(HDC, UINT);
// WinVer >= 0x0500
WINGDIAPI DWORD WINAPI SwapMultipleBuffers(UINT, CONST WGLSWAP *);
*/
/*
SaveLastError..NativeName("wglUseFontBitmapsW")..BOOL(
"UseFontBitmaps",
"""
Creates a set of bitmap display lists for use in the current OpenGL rendering context. The set of bitmap display lists is based on the glyphs in the
currently selected font in the device context. You can then use bitmaps to draw characters in an OpenGL image.
Creates count display lists, one for each of a run of count glyphs that begins with the first glyph in the device parameter's selected fonts.
""",
HDC("hdc", "the device context whose currently selected font will be used to form the glyph bitmap display lists in the current OpenGL rendering context"),
DWORD("first", "the first glyph in the run of glyphs that will be used to form glyph bitmap display lists"),
DWORD("count", "the number of glyphs in the run of glyphs that will be used to form glyph bitmap display lists. The function creates count display lists, one for each glyph in the run."),
DWORD("listBase", "the starting display list")
)
SaveLastError..NativeName("wglUseFontOutlinesW")..BOOL(
"UseFontOutlines",
"""
Creates a set of display lists, one for each glyph of the currently selected outline font of a device context, for use with the current rendering
context. The display lists are used to draw 3-D characters of TrueType fonts. Each display list describes a glyph outline in floating-point coordinates.
The run of glyphs begins with thefirstglyph of the font of the specified device context. The em square size of the font, the notional grid size of the
original font outline from which the font is fitted, is mapped to 1.0 in the x- and y-coordinates in the display lists. The extrusion parameter sets how
much depth the font has in the z direction.
The glyphMetrics parameter returns a ##GLYPHMETRICSFLOAT structure that contains information about the placement and orientation of each glyph in
a character cell.
""",
HDC(
"hdc",
"""
the device context with the desired outline font. The outline font of {@code dc} is used to create the display lists in the current rendering
context.
"""
),
DWORD("first", "the first of the set of glyphs that form the font outline display lists"),
AutoSize("glyphMetrics")..DWORD(
"count",
"""
the number of glyphs in the set of glyphs used to form the font outline display lists. The {@code wglUseFontOutlines} function creates count display
lists, one display list for each glyph in a set of glyphs.
"""
),
DWORD("listBase", "the starting display list"),
FLOAT(
"deviation",
"""
the maximum chordal deviation from the original outlines. When deviation is zero, the chordal deviation is equivalent to one design unit of the
original font. The value of deviation must be equal to or greater than 0.
"""
),
FLOAT(
"extrusion",
"""
how much a font is extruded in the negative z direction. The value must be equal to or greater than 0. When extrusion is 0, the display lists are
not extruded.
"""
),
int(
"format",
"""
the format to use in the display lists. When format is #FONT_LINES, the {@code wglUseFontOutlines} function creates fonts with line
segments. When format is #FONT_POLYGONS, {@code wglUseFontOutlines} creates fonts with polygons.
""",
"#FONT_LINES #FONT_POLYGONS"
),
nullable..LPGLYPHMETRICSFLOAT(
"glyphMetrics",
"""
an array of {@code count} ##GLYPHMETRICSFLOAT structures that is to receive the metrics of the glyphs. When {@code glyphMetrics} is #NULL, no
glyph metrics are returned.
"""
)
)
*/
} | bsd-3-clause | 84396a098d8afc3b64a0e9bcd9e25d67 | 42.857143 | 195 | 0.643471 | 4.558993 | false | false | false | false |
fabioCollini/ArchitectureComponentsDemo | core/src/main/java/it/codingjam/github/core/utils/ComponentHolder.kt | 1 | 1493 | package it.codingjam.github.core.utils
interface ComponentHolder {
fun <C : Any> getOrCreate(key: Any, componentClass: Class<C>, componentFactory: () -> C): C
fun remove(key: Any)
fun init(interceptor: (Class<*>, () -> Any) -> Any)
}
inline fun <reified C : Any> ComponentHolder.getOrCreate(noinline componentFactory: () -> C): C =
getOrCreate(C::class.java, C::class.java, componentFactory)
inline fun <reified C : Any> ComponentHolder.get(): C =
getOrCreate(C::class.java, C::class.java) {
throw Exception("Component ${C::class.java.simpleName} not available in ${this::class.java.simpleName}")
}
inline fun <reified C : Any> ComponentHolder.provide(noinline componentFactory: () -> C) {
getOrCreate(C::class.java, C::class.java, componentFactory)
}
class ComponentsMap : ComponentHolder {
private var interceptor: (Class<*>, () -> Any) -> Any = { _, factory -> factory() }
private val moduleComponents = HashMap<Any, Any>()
override fun <C : Any> getOrCreate(key: Any, componentClass: Class<C>, componentFactory: () -> C): C {
@Suppress("UNCHECKED_CAST")
return moduleComponents.getOrPut(key) {
interceptor(componentClass, componentFactory)
} as C
}
override fun init(interceptor: (Class<*>, () -> Any) -> Any) {
this.interceptor = interceptor
moduleComponents.clear()
}
override fun remove(key: Any) {
moduleComponents.remove(key)
}
} | apache-2.0 | 998fcae690638f73c9e2bca4a11910f1 | 33.744186 | 116 | 0.64568 | 4.057065 | false | false | false | false |
Tickaroo/tikxml | processor/src/test/java/com/tickaroo/tikxml/processor/scanning/DefaultAnnotationDetectorTest.kt | 1 | 68599 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, 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.tickaroo.tikxml.processor.scanning
import com.google.common.truth.Truth
import com.google.testing.compile.JavaFileObjects
import com.google.testing.compile.JavaSourceSubjectFactory
import com.google.testing.compile.JavaSourcesSubject
import com.google.testing.compile.JavaSourcesSubjectFactory
import com.tickaroo.tikxml.annotation.Attribute
import com.tickaroo.tikxml.annotation.Element
import com.tickaroo.tikxml.annotation.ElementNameMatcher
import com.tickaroo.tikxml.annotation.GenericAdapter
import com.tickaroo.tikxml.annotation.Path
import com.tickaroo.tikxml.annotation.PropertyElement
import com.tickaroo.tikxml.annotation.TextContent
import com.tickaroo.tikxml.annotation.Xml
import com.tickaroo.tikxml.processor.XmlProcessor
import org.junit.Ignore
import org.junit.Test
import javax.tools.JavaFileObject
/**
*
* @author Hannes Dorfmann
*/
class DefaultAnnotationDetectorTest {
@Test
fun multipleAnnotationOnField1() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleAnnotations1",
"package test;",
"@${Xml::class.qualifiedName}",
"class MultipleAnnotations1 {",
" @${Attribute::class.qualifiedName}",
" @${Element::class.qualifiedName}",
" String aField;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Fields can ONLY be annotated with ONE of the following")
}
@Test
fun multipleAnnotationOnField2() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleAnnotations2",
"package test;",
"@${Xml::class.qualifiedName}",
"class MultipleAnnotations2 {",
" @${Element::class.qualifiedName}",
" @${PropertyElement::class.qualifiedName}",
" String aField;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Fields can ONLY be annotated with ONE of the following")
}
@Test
fun multipleAnnotationOnField3() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleAnnotations3",
"package test;",
"",
"import ${Xml::class.java.canonicalName};",
"import ${Attribute::class.java.canonicalName};",
"import ${Element::class.java.canonicalName};",
"import ${PropertyElement::class.java.canonicalName};",
"",
"@${Xml::class.java.simpleName}",
"class MultipleAnnotations3 {",
" @${PropertyElement::class.java.simpleName}",
" @${Attribute::class.java.simpleName}",
" String aField;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Fields can ONLY be annotated with ONE of the following")
}
@Test
fun multipleAnnotationOnField4() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleAnnotations4",
"package test;",
"",
"import ${Xml::class.java.canonicalName};",
"import ${Attribute::class.java.canonicalName};",
"import ${Element::class.java.canonicalName};",
"import ${PropertyElement::class.java.canonicalName};",
"",
"@${Xml::class.java.simpleName}",
"class MultipleAnnotations4 {",
" @${Attribute::class.java.simpleName}",
" @${PropertyElement::class.java.simpleName}",
" @${Element::class.java.simpleName}",
" String aField;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Fields can ONLY be annotated with ONE of the following")
}
@Test
fun multipleAnnotationOnField5() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleAnnotations4",
"package test;",
"",
"@${Xml::class.qualifiedName}",
"class MultipleAnnotations4 {",
" @${Attribute::class.qualifiedName}",
" @${PropertyElement::class.qualifiedName}",
" @${Element::class.qualifiedName}",
" @${TextContent::class.qualifiedName}",
" String aField;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Fields can ONLY be annotated with ONE of the following")
}
@Test
fun multipleAnnotationOnField6() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleAnnotations4",
"package test;",
"",
"",
"@${Xml::class.qualifiedName}",
"class MultipleAnnotations4 {",
" @${Attribute::class.qualifiedName}",
" @${TextContent::class.qualifiedName}",
" String aField;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Fields can ONLY be annotated with ONE of the following")
}
@Test
fun multipleAnnotationOnField7() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleAnnotations4",
"package test;",
"",
"",
"@${Xml::class.qualifiedName}",
"class MultipleAnnotations4 {",
" @${PropertyElement::class.qualifiedName}",
" @${TextContent::class.qualifiedName}",
" String aField;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Fields can ONLY be annotated with ONE of the following")
}
@Test
fun multipleAnnotationOnField8() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleAnnotations4",
"package test;",
"",
"",
"@${Xml::class.qualifiedName}",
"class MultipleAnnotations4 {",
" @${TextContent::class.qualifiedName}",
" @${Element::class.qualifiedName}",
" String aField;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining("Fields can ONLY be annotated with ONE of the following")
}
@Test
fun genericListTypeForJavaObjectIsAllowed() {
val componentFile = JavaFileObjects.forSourceLines("test.InlineListOnListType",
"package test;",
"",
"import ${Xml::class.java.canonicalName};",
"import ${Element::class.java.canonicalName};",
"",
"@${Xml::class.java.simpleName}",
"class InlineListOnListType {",
" @${Element::class.java.simpleName}",
" java.util.List<Object> aList;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun inlineListOnArrayListType() {
val componentFile = JavaFileObjects.forSourceLines("test.InlineListOnArrayListType",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class InlineListOnArrayListType {",
" @${Element::class.java.canonicalName}",
" java.util.ArrayList<Object> aList;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type java.util.ArrayList used for field 'aList' in test.InlineListOnArrayListType can't be used, because it is not annotated with @${Xml::class.simpleName}. Annotate java.util.ArrayList with @${Xml::class.simpleName}!")
}
@Test
fun inlineListOnLinkedListType() {
val componentFile = JavaFileObjects.forSourceLines("test.InlineListOnLinkedListType",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class InlineListOnLinkedListType {",
" @${Element::class.java.canonicalName}",
" java.util.List<Object> aList;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun polymorphicTypeIsPrivateClass() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicClassIsPrivate",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicClassIsPrivate {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerPrivateClass.class)",
" )",
" Object aField;",
"",
"@${Xml::class.java.canonicalName}",
"private class InnerPrivateClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"@${ElementNameMatcher::class.simpleName} does not allow private classes. test.PolymorphicClassIsPrivate.InnerPrivateClass is a private class!")
}
@Test
fun polymorphicTypeIsProtectedClass() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicClassIsProtected",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicClassIsProtected {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerProtectedClass.class)",
" )",
" Object aField;",
"",
"@${Xml::class.java.canonicalName}",
"protected class InnerProtectedClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"@${ElementNameMatcher::class.simpleName} does not allow protected classes. test.PolymorphicClassIsProtected.InnerProtectedClass is a protected class!")
}
@Test
fun polymorphicTypeHasNoPublicConstructor() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicClassHasNoPublicConstructor",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicClassHasNoPublicConstructor {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass.class)",
" )",
" Object aField;",
"",
"@${Xml::class.java.canonicalName}",
"public class InnerClass {",
" private InnerClass() {}",
"}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Class test.PolymorphicClassHasNoPublicConstructor.InnerClass used in @${ElementNameMatcher::class.simpleName} must provide an public empty (parameter-less) constructor")
}
@Test
fun polymorphicTypeHasNoEmptyConstructor() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicClassHasNoEmptyConstructor",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicClassHasNoEmptyConstructor {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"foo\" , type=InnerClass.class)",
" )",
" Object aField;",
"",
"@${Xml::class.java.canonicalName}",
"public class InnerClass {",
" public InnerClass(int a) {}",
"}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Class test.PolymorphicClassHasNoEmptyConstructor.InnerClass used in @${ElementNameMatcher::class.simpleName} must provide an public empty (parameter-less) constructor")
}
@Test
fun polymorphicTypeIsInterface() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicTypeIsInterface",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicTypeIsInterface {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass.class)",
" )",
" Object aField;",
"",
"public interface InnerClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"@${ElementNameMatcher::class.simpleName} only allows classes. test.PolymorphicTypeIsInterface.InnerClass is a not a class!")
}
@Test
fun polymorphicTypeIsEnum() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicTypeIsEnum",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicTypeIsEnum {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass.class)",
" )",
" Object aField;",
"",
"public enum InnerClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"@${ElementNameMatcher::class.simpleName} only allows classes. test.PolymorphicTypeIsEnum.InnerClass is a not a class!")
}
@Test
fun polymorphicTypeIsNotSubType() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicTypeIsNotSubType",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicTypeIsNotSubType {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass.class)",
" )",
" String aField;",
"",
" @${Xml::class.java.canonicalName}",
" public class InnerClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type test.PolymorphicTypeIsNotSubType.InnerClass must be a sub type of java.lang.String. Otherwise this type cannot be used in @${ElementNameMatcher::class.simpleName} to resolve polymorphis")
}
@Test
fun polymorphicTypeIsSubType() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicTypeIsSubType",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicTypeIsSubType {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass.class)",
" )",
" Object aField;",
"",
"@${Xml::class.java.canonicalName}",
"static class InnerClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun polymorphicEmptyXmlName() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicEmptyXmlName",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicEmptyXmlName {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(name=\"\", type=InnerClass.class)",
" )",
" Object aField;",
"",
"@${Xml::class.java.canonicalName}",
"static class InnerClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun polymorphicBlankXmlName() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicBlankXmlName",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicBlankXmlName {",
" @${Element::class.java.canonicalName}(",
" typesByElement = @${ElementNameMatcher::class.qualifiedName}(type=InnerClass.class)",
" )",
" Object aField;",
"",
"@${Xml::class.java.canonicalName}",
"static class InnerClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun polymorphicElementNameInConflict() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicElementNameInConflict",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicElementNameInConflict {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass2.class),",
" })",
" Object aField;",
"",
"@${Xml::class.java.canonicalName}",
"public class InnerClass1 {}",
"@${Xml::class.java.canonicalName}",
"public class InnerClass2 {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: A @${ElementNameMatcher::class.simpleName} with the name \"foo\" is already mapped to the type test.PolymorphicElementNameInConflict.InnerClass1 to resolve polymorphism. Hence it cannot be mapped to test.PolymorphicElementNameInConflict.InnerClass2 as well.")
}
@Test
fun polymorphicElementNoNamingConflict() {
val componentFile = JavaFileObjects.forSourceLines("test.PolymorphicElementNoNamingConflict",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PolymorphicElementNoNamingConflict {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\", type=InnerClass2.class),",
" })",
" Object aField;",
"}",
"",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 {}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementDeclarationOnPrimitive() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementDeclarationOnPrimitive",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementDeclarationOnPrimitive {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\", type=InnerClass2.class),",
" })",
" int aField;",
"",
"@${Xml::class.java.canonicalName}",
"public class InnerClass1 {}",
"@${Xml::class.java.canonicalName}",
"public class InnerClass2 {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type of field 'aField' in class test.ElementDeclarationOnPrimitive is not a class nor a interface. Only classes or interfaces can be annotated with @${Element::class.simpleName} annotation")
}
@Test
fun elementOnInterfaceWithoutPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementOnInterfaceWithoutPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnInterfaceWithoutPolymorphism {",
" @${Element::class.java.canonicalName}",
" MyInterface aField;",
"",
"public interface MyInterface {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type of field 'aField' in class test.ElementOnInterfaceWithoutPolymorphism is an interface. Hence polymorphism must be resolved by annotating this interface with @${GenericAdapter::class.java.simpleName}")
}
@Test
fun elementOnInterfaceWithPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementOnInterfaceWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnInterfaceWithPolymorphism {",
" MyInterface aField;",
"}",
"",
"@${GenericAdapter::class.java.canonicalName}",
"interface MyInterface {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 implements MyInterface{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 implements MyInterface{}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementOnInterfaceWithoutPolymorphismWrong() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementOnInterfaceWithPolymorphismWrong",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnInterfaceWithPolymorphismWrong {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\", type=InnerClass2.class),",
" })",
" MyInterface aField;",
"",
"public interface MyInterface {}",
"@${Xml::class.java.canonicalName}",
"public class InnerClass1 implements MyInterface{}",
"@${Xml::class.java.canonicalName}",
"public class InnerClass2 {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type of field 'aField' in class test.ElementOnInterfaceWithPolymorphismWrong is an interface. Hence polymorphism must be resolved by annotating this interface with @${GenericAdapter::class.java.simpleName}!")
}
@Test
fun elementOnInterfaceWithPolymorphismWrong() {
val componentFile = JavaFileObjects.forSourceLines("test.elementOnInterfaceWithPolymorphismWrong",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnInterfaceWithPolymorphismWrong {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\", type=InnerClass2.class),",
" })",
" MyInterface aField;",
"",
"@${GenericAdapter::class.java.canonicalName}",
"public interface MyInterface {}",
"@${Xml::class.java.canonicalName}",
"public class InnerClass1 implements MyInterface {}",
"@${Xml::class.java.canonicalName}",
"public class InnerClass2 {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type test.ElementOnInterfaceWithPolymorphismWrong.InnerClass2 must be a sub type of test.ElementOnInterfaceWithPolymorphismWrong.MyInterface. Otherwise this type cannot be used in @${ElementNameMatcher::class.java.simpleName} to resolve polymorphism.")
}
@Test
fun elementOnAbstractClassWithoutPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementOnAbstractClassWithoutPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnAbstractClassWithoutPolymorphism {",
" @${Element::class.java.canonicalName}",
" MyClass aField;",
"",
"@${Xml::class.java.canonicalName}",
"public abstract class MyClass {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type of field 'aField' in class test.ElementOnAbstractClassWithoutPolymorphism is an abstract class. Hence polymorphism must be resolved by annotating this abstract class with @${GenericAdapter::class.simpleName}!")
}
@Test
fun elementOnAbstractClassWithPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementOnAbstractClassWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnInterfaceWithPolymorphism {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\" , type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\" , type=InnerClass2.class),",
" })",
" MyClass aField;",
"}",
"",
"@${GenericAdapter::class.java.canonicalName}",
"abstract class MyClass {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 extends MyClass{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 extends MyClass{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementOnAbstractWithPolymorphismWrong() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementOnAbstractClassWithPolymorphismWrong",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnAbstractClassWithPolymorphismWrong {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\" , type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\" , type=InnerClass2.class),",
" })",
" MyClass aField;",
"",
"}",
"",
"@${GenericAdapter::class.java.canonicalName}",
"abstract class MyClass {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 extends MyClass{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 {}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type test.InnerClass2 must be a sub type of test.MyClass. Otherwise this type cannot be used in @${ElementNameMatcher::class.simpleName} to resolve polymorphism.")
}
@Test
fun elementListAbstractClassWithPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementOnAbstractClassWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnInterfaceWithPolymorphism {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\", type=InnerClass2.class),",
" })",
" java.util.List<MyClass> aField;",
"}",
"",
"abstract class MyClass {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 extends MyClass{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 extends MyClass{}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementListInterfaceWithPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementOnAbstractClassWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementOnInterfaceWithPolymorphism {",
" java.util.List<MyInterface> aField;",
"}",
"",
"@${GenericAdapter::class.java.canonicalName}",
"interface MyInterface {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 implements MyInterface{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 implements MyInterface{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementListRawAbstractClassWithPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListRawAbstractClassWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListRawAbstractClassWithPolymorphism {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\" , type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\" , type=InnerClass2.class),",
" })",
" java.util.List aField;",
"}",
"",
"abstract class MyClass {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 extends MyClass{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 extends MyClass{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementListRawInterfaceWithPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListRawInterfaceWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListRawInterfaceWithPolymorphism {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\", type=InnerClass2.class),",
" })",
" java.util.List aField;",
"}",
"",
"interface MyInterface {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 implements MyInterface{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 implements MyInterface{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
@Ignore
fun elementListWildcardExtendsInterfaceWithPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListWildcardInterfaceWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListWildcardInterfaceWithPolymorphism {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\" , type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\" , type=InnerClass2.class),",
" })",
" java.util.List<? extends MyInterface> aField;",
"",
" public interface MyInterface {}",
"@${Xml::class.java.canonicalName}",
" public class InnerClass1 implements MyInterface{}",
"@${Xml::class.java.canonicalName}",
" public class InnerClass2 implements MyInterface{}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementListWildcardExtendsInterfaceWithPolymorphismWrong() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListWildcardExtendsInterfaceWithPolymorphismWrong",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListWildcardExtendsInterfaceWithPolymorphismWrong {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\", type=InnerClass2.class),",
" })",
" java.util.List<? extends MyInterface> aField;",
"}",
"",
"@${GenericAdapter::class.java.canonicalName}",
"interface MyInterface {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 implements MyInterface{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type test.InnerClass2 must be a sub type of test.MyInterface. Otherwise this type cannot be used in @${ElementNameMatcher::class.simpleName} to resolve polymorphism.")
}
@Test
fun elementListWildcardSuperInterfaceWithPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListWildcardInterfaceWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListWildcardInterfaceWithPolymorphism {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\", type=GrandParent.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\", type=Parent.class),",
" })",
" java.util.List<? super GrandParent> aField;",
"}",
"",
"@${Xml::class.java.canonicalName}",
"class GrandParent {}",
"@${Xml::class.java.canonicalName}",
"class Parent extends GrandParent {}",
"@${Xml::class.java.canonicalName}",
"class Child extends Parent {}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementListWildcardSuperInterfaceWithPolymorphismWrong() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListWildcardSuperInterfaceWithPolymorphismWrong",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListWildcardSuperInterfaceWithPolymorphismWrong {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\" , type=GrandParent.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\" , type=Parent.class),",
" })",
" java.util.List<? super GrandParent> aField;",
"",
"@${Xml::class.java.canonicalName}",
" public class GrandParent {}",
"@${Xml::class.java.canonicalName}",
" public class Parent {}",
"@${Xml::class.java.canonicalName}",
" public class Child extends Parent {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type test.ElementListWildcardSuperInterfaceWithPolymorphismWrong.Parent must be a sub type of test.ElementListWildcardSuperInterfaceWithPolymorphismWrong.GrandParent. Otherwise this type cannot be used in @${ElementNameMatcher::class.simpleName} to resolve polymorphism.")
}
@Test
@Ignore
fun elementListWildcardInterfaceWithoutPolymorphism() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListWildcardInterfaceWithPolymorphism",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListWildcardInterfaceWithPolymorphism {",
" @${Element::class.java.canonicalName}(",
" typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}(name=\"foo\" , type=InnerClass1.class),",
" @${ElementNameMatcher::class.qualifiedName}(name=\"bar\" , type=InnerClass2.class),",
" })",
" java.util.List<?> aField;",
"}",
"",
"interface MyInterface {}",
"@${Xml::class.java.canonicalName}",
"class InnerClass1 implements MyInterface{}",
"@${Xml::class.java.canonicalName}",
"class InnerClass2 {}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun noConflictBetweenAttributeAndPropertyElement() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflict1",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class NameConflict1 {",
" @${PropertyElement::class.java.canonicalName}( name =\"foo\" )",
" int a;",
"",
" @${Attribute::class.java.canonicalName}( name =\"foo\" )",
" int b;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun nameConflict() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflict2",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class NameConflict2 {",
" @${PropertyElement::class.java.canonicalName}( name =\"foo\" )",
" int a;",
"",
" @${Element::class.java.canonicalName}( name =\"foo\" )",
" Other b;",
" @${Xml::class.java.canonicalName}",
" static class Other {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'b' in class test.NameConflict2 is in conflict with field 'a' in class test.NameConflict2. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun nameConflict2() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflict2",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class NameConflict2 {",
" @${Element::class.java.canonicalName}( name =\"foo\" )",
" Other b;",
" @${Xml::class.java.canonicalName}",
" public class Other {}",
"",
" @${PropertyElement::class.java.canonicalName}( name =\"foo\" )",
" int a;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'a' in class test.NameConflict2 is in conflict with field 'b' in class test.NameConflict2. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun nameConflict3() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflict2",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class NameConflict2 {",
" @${Element::class.java.canonicalName}( name =\"foo\" )",
" Other b;",
"",
" @${Element::class.java.canonicalName}( name =\"foo\" )",
" Other a;",
"",
" @${Xml::class.java.canonicalName}",
" public class Other {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'a' in class test.NameConflict2 is in conflict with field 'b' in class test.NameConflict2. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun nameConflict4() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflict2",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class NameConflict2 {",
" @${Element::class.java.canonicalName}( name =\"foo\" )",
" Other a;",
"",
" @${Element::class.java.canonicalName}( name =\"foo\" )",
" Other b;",
"",
" @${Xml::class.java.canonicalName}",
" public class Other {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'b' in class test.NameConflict2 is in conflict with field 'a' in class test.NameConflict2. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun nameConflictInheritance1() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflictInheritance1",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class NameConflictInheritance1 extends Parent {",
" @${Attribute::class.java.canonicalName}( name =\"foo\" )",
" int a;",
"",
"}",
"",
"@${Xml::class.java.canonicalName}",
"class Parent {",
" @${Attribute::class.java.canonicalName}( name =\"foo\" )",
" Other b;",
" class Other {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'b' in class test.Parent has the same xml attribute name 'foo' as the field 'a' in class test.NameConflictInheritance1. You can specify another name via annotations.")
}
@Test
fun nameConflictInheritance2() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflictInheritance2",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class NameConflictInheritance2 extends Parent {",
" @${PropertyElement::class.java.canonicalName}( name =\"foo\" )",
" int a;",
"",
"}",
"",
"@${Xml::class.java.canonicalName}",
"class Parent {",
" @${Element::class.java.canonicalName}( name =\"foo\" )",
" Other b;",
" @${Xml::class.java.canonicalName}",
" class Other {}",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'b' in class test.Parent is in conflict with field 'a' in class test.NameConflictInheritance2. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun attributeNotInConflictWithPropertyElement() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflictInheritance3",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class NameConflictInheritance3 extends Parent {",
" @${Attribute::class.java.canonicalName}( name =\"foo\" )",
" int a;",
"",
"}",
"",
"@${Xml::class.java.canonicalName}",
"class Parent {",
" @${PropertyElement::class.java.canonicalName}( name =\"foo\" )",
" String b;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun nameConflictInheritanceOff() {
val componentFile = JavaFileObjects.forSourceLines("test.NameConflictInheritance3",
"package test;",
"",
"@${Xml::class.java.canonicalName}(inheritance = false)",
"class NameConflictInheritance3 extends Parent {",
" @${Attribute::class.java.canonicalName}( name =\"foo\" )",
" int a;",
"",
"}",
"",
"@${Xml::class.java.canonicalName}",
"class Parent {",
" @${PropertyElement::class.java.canonicalName}( name =\"foo\" )",
" String b;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun textContent() {
val componentFile = JavaFileObjects.forSourceLines("test.TextContent",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class TextContent {",
" @${TextContent::class.qualifiedName}",
" String foo;",
"",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun multipleTextContentInInheritance() {
val componentFile = JavaFileObjects.forSourceLines("test.MultipleTextContentOnInheritance",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class MultipleTextContentOnInheritance extends Parent {",
" @${TextContent::class.qualifiedName}",
" String foo;",
"",
"}",
"",
"@${Xml::class.java.canonicalName}",
"class Parent {",
" @${TextContent::class.qualifiedName}",
" String bar;",
"}")
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun textContentOnNotStringField() {
val componentFile = JavaFileObjects.forSourceLines("test.TextContentOnNotString",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class TextContentOnNotString {",
" @${TextContent::class.qualifiedName}",
" int foo;",
"",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Only type String is supported for @TextContent but field 'foo' in class test.TextContentOnNotString is not of type String")
}
@Test
fun incorrectPathAnnotation() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"\")",
" @${Attribute::class.qualifiedName}",
" int foo;",
"",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The field 'foo' in class test.PathAnnotation annotated with @Path(\"\") has an illegal path: Error in path segment '' (segment index = 0)")
}
@Test
fun incorrectPathAnnotation2() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"asd/\")",
" @${Attribute::class.qualifiedName}",
" int foo;",
"",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The field 'foo' in class test.PathAnnotation annotated with @Path(\"asd/\") has an illegal path: Error in path segment '' (segment index = 1)")
}
@Test
fun incorrectPathAnnotation3() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"asd/foo/\")",
" @${Attribute::class.qualifiedName}",
" int foo;",
"",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The field 'foo' in class test.PathAnnotation annotated with @Path(\"asd/foo/\") has an illegal path: Error in path segment '' (segment index = 2)")
}
@Test
fun incorrectPathAnnotation4() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"asd/f oo\")",
" @${Attribute::class.qualifiedName}",
" int foo;",
"",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The field 'foo' in class test.PathAnnotation annotated with @Path(\"asd/f oo\") has an illegal path: Error in path segment 'f oo' (segment index = 1)")
}
@Test
fun correctPathAnnotation() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"foo/bar\")",
" @${Attribute::class.qualifiedName}",
" int foo;",
"",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun attributeAndPathConflict0() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"foo\")",
" @${Attribute::class.qualifiedName}",
" int bar;",
"",
" @${Element::class.qualifiedName}",
" foo foo;",
"",
" @${Xml::class.java.canonicalName}",
" static class foo {}",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'foo' in class test.PathAnnotation is in conflict with test.PathAnnotation. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun attributeAndPathConflict1() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"foo\")",
" @${Attribute::class.qualifiedName}",
" int bar;",
"",
" @${Element::class.qualifiedName}",
" Foo foo;",
"",
" @${Xml::class.java.canonicalName}",
" static class Foo {}",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'foo' in class test.PathAnnotation is in conflict with test.PathAnnotation. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun attributeAndPathConflict2() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"foo\")",
" @${Attribute::class.qualifiedName}",
" int bar;",
"",
" @${Element::class.qualifiedName}",
" Other foo;",
"",
" @${Xml::class.java.canonicalName}(name=\"foo\")",
" static class Other {}",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'foo' in class test.PathAnnotation is in conflict with test.PathAnnotation. Maybe both have the same xml name 'foo' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun attributeAndPathConflict3() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Element::class.qualifiedName}(name=\"foo\")",
" Other foo;",
"",
" @${Path::class.qualifiedName}(\"foo\")",
" @${Attribute::class.qualifiedName}",
" int bar;",
"",
" @${Xml::class.java.canonicalName}",
" public class Other {}",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Element field 'foo' in class test.PathAnnotation can't have attributes that are accessed from outside of the TypeAdapter that is generated from @${Element::class.simpleName} annotated class! Therefore attribute field 'bar' in class test.PathAnnotation can't be added. Most likely the @${Path::class.simpleName} is in conflict with an @${Element::class.simpleName} annotation.")
}
@Test
fun attributeAndPathConflictWithSubPath() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"asd\")",
" @${Element::class.qualifiedName}",
" Other foo;",
"",
" @${Path::class.qualifiedName}(\"asd/other\")",
" @${Attribute::class.qualifiedName}",
" int bar;",
"",
" @${Xml::class.java.canonicalName}",
" public class Other {}",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Element field 'foo' in class test.PathAnnotation can't have attributes that are accessed from outside of the TypeAdapter that is generated from @${Element::class.simpleName} annotated class! Therefore attribute field 'bar' in class test.PathAnnotation can't be added. Most likely the @${Path::class.simpleName} is in conflict with an @${Element::class.simpleName} annotation.")
}
@Test
fun attributeAndPathConflictWithSubPath2() {
val componentFile = JavaFileObjects.forSourceLines("test.PathAnnotation",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathAnnotation {",
" @${Path::class.qualifiedName}(\"asd/other\")",
" @${Attribute::class.qualifiedName}",
" int bar;",
"",
" @${Path::class.qualifiedName}(\"asd\")",
" @${Element::class.qualifiedName}",
" Other foo;",
"",
" @${Xml::class.java.canonicalName}",
" public class Other {}",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"Conflict: field 'foo' in class test.PathAnnotation is in conflict with test.PathAnnotation. Maybe both have the same xml name 'other' (you can change that via annotations) or @${Path::class.simpleName} is causing this conflict.")
}
@Test
fun elementListWithInterfaceAsGenericType() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListWithInterface",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListWithInterface {",
" @${Element::class.qualifiedName}",
" java.util.List<AnInterface> alist;",
"}",
"",
"@${GenericAdapter::class.java.canonicalName}",
"interface AnInterface{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementListWithAbstractClassAsGenericType() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListWithAbstractClass",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListWithAbstractClass {",
" @${Element::class.qualifiedName}",
" java.util.List<AbstractClass> alist;",
"}",
"",
"@${GenericAdapter::class.java.canonicalName}",
"abstract class AbstractClass{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun elementListWithClassWithoutXmlAnnotationAsGenericType() {
val componentFile = JavaFileObjects.forSourceLines("test.ElementListWithNotAnnotatedClass",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ElementListWithNotAnnotatedClass {",
" @${Element::class.qualifiedName}",
" java.util.List<OtherClass> alist;",
"}",
"",
"class OtherClass{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"The type test.OtherClass used for field 'alist' in test.ElementListWithNotAnnotatedClass can't be used, because it is not annotated with @${Xml::class.java.simpleName}. Annotate test.OtherClass with @${Xml::class.java.simpleName}!")
}
@Test
fun validElementList() {
val componentFile = JavaFileObjects.forSourceLines("test.ValidElementList",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class ValidElementList {",
" @${Element::class.qualifiedName}",
" java.util.List<OtherClass> alist;",
"}",
"",
"@${Xml::class.java.canonicalName}",
"class OtherClass{}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.compilesWithoutError()
}
@Test
fun failOnPathWithTextContent() {
val componentFile = JavaFileObjects.forSourceLines("test.PathOnTextContent",
"package test;",
"",
"@${Xml::class.java.canonicalName}",
"class PathOnTextContent {",
" @${Path::class.qualifiedName}(\"asd\")",
" @${TextContent::class.qualifiedName}",
" String foo;",
"}"
)
Truth.assertAbout<JavaSourcesSubject.SingleSourceAdapter, JavaFileObject>(JavaSourceSubjectFactory.javaSource())
.that(componentFile).processedWith(XmlProcessor())
.failsToCompile()
.withErrorContaining(
"@${Path::class.simpleName} on @${TextContent::class.simpleName} is not allowed. Use @${PropertyElement::class.simpleName} and @${Path::class.simpleName} instead on field 'foo' in class test.PathOnTextContent")
}
/**
* Issue:
* https://github.com/Tickaroo/tikxml/pull/66
*/
@Test
fun testEmptyConstructorOnElementNameMatcher() {
val actionFile = JavaFileObjects.forSourceLines("test.complex.action.Action",
"package test.complex.action;",
"@${Xml::class.java.canonicalName}(name = \"action\")",
"public class Action {",
" @${Attribute::class.qualifiedName}(name =\"action\")",
" public String action;",
"}"
)
val testAction = JavaFileObjects.forSourceLines("test.complex.action.TestAction",
"package test.complex.action;",
"@${Xml::class.java.canonicalName}(name = \"testAction\")",
"public class TestAction {",
"}"
)
val filterA = JavaFileObjects.forSourceLines("test.complex.filter.action.FilterA",
"package test.complex.filter.action;",
"@${Xml::class.java.canonicalName}(name = \"filterA\")",
"public class FilterA {",
"}"
)
val filterB = JavaFileObjects.forSourceLines("test.complex.filter.action.FilterB",
"package test.complex.filter.action;",
"@${Xml::class.java.canonicalName}(name = \"filterB\")",
"public class FilterB {",
" @${Attribute::class.qualifiedName}(name =\"target\")",
" public String target;",
"}"
)
val filterC = JavaFileObjects.forSourceLines("test.complex.filter.action.FilterC",
"package test.complex.filter.action;",
"@${Xml::class.java.canonicalName}(name = \"filterC\")",
"public class FilterC {",
"}"
)
val filterD = JavaFileObjects.forSourceLines("test.complex.filter.action.FilterD",
"package test.complex.filter.action;",
"@${Xml::class.java.canonicalName}(name = \"filterD\")",
"public class FilterD {",
"}"
)
val filterE = JavaFileObjects.forSourceLines("test.complex.filter.action.FilterE",
"package test.complex.filter.action;",
"@${Xml::class.java.canonicalName}(name = \"filterE\")",
"public class FilterE {",
"}"
)
val filterFile = JavaFileObjects.forSourceLines("test.complex.filter.Filter",
"package test.complex.filter;",
"@${Xml::class.java.canonicalName}(name =\"filter\")",
"public class Filter {",
" @${Path::class.qualifiedName}(\"action\")",
" @${Element::class.qualifiedName}( typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}( name = \"filterA\", type= test.complex.filter.action.FilterA.class),",
" @${ElementNameMatcher::class.qualifiedName}( name = \"filterB\", type= test.complex.filter.action.FilterB.class),",
" @${ElementNameMatcher::class.qualifiedName}( name = \"filterC\", type= test.complex.filter.action.FilterC.class),",
" @${ElementNameMatcher::class.qualifiedName}( name = \"filterD\", type= test.complex.filter.action.FilterD.class),",
" @${ElementNameMatcher::class.qualifiedName}( name = \"filterE\", type= test.complex.filter.action.FilterE.class),",
" })",
" public Object action;",
"}")
val eventFile = JavaFileObjects.forSourceLines("test.complex.Event",
"package test.complex;",
"@${Xml::class.java.canonicalName}(name =\"event\")",
"public class Event {",
" @${Path::class.qualifiedName}(\"action\")",
" @${Element::class.qualifiedName}( typesByElement = {",
" @${ElementNameMatcher::class.qualifiedName}( name = \"action\", type= test.complex.action.Action.class),",
" @${ElementNameMatcher::class.qualifiedName}( name = \"testAction\", type= test.complex.action.TestAction.class)",
" })",
" public Object action;",
" @${Element::class.qualifiedName}(name =\"filter\")",
" public test.complex.filter.Filter filter;",
"}"
)
Truth.assertAbout(JavaSourcesSubjectFactory.javaSources())
.that(arrayListOf<JavaFileObject>(
actionFile,
testAction,
filterA,
filterB,
filterC,
filterD,
filterE,
filterFile,
eventFile
))
.processedWith(XmlProcessor())
.compilesWithoutError()
}
} | apache-2.0 | 67b0261ee2b504de4ebc0c6baef2bab3 | 38.402642 | 386 | 0.659485 | 4.95765 | false | true | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/features/distance/DistancesViewModel.kt | 1 | 2282 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets 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.
*/
package de.dreier.mytargets.features.distance
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import de.dreier.mytargets.app.ApplicationInstance
import de.dreier.mytargets.shared.models.Dimension
class DistancesViewModel(app: Application) : AndroidViewModel(app) {
private val unit = MutableLiveData<Dimension.Unit>()
private var distance = MutableLiveData<Dimension?>()
private val dimensionDAO = ApplicationInstance.db.dimensionDAO()
val distances: LiveData<List<Dimension>>
init {
val dbDistances = Transformations.switchMap(unit) { unit ->
dimensionDAO.getAll(unit)
}
distances = Transformations.map(dbDistances) { filteredDistances ->
val distances = mutableSetOf(de.dreier.mytargets.shared.models.Dimension.UNKNOWN)
// Add currently selected distance to list
if (this.distance.value?.unit == unit.value) {
distances.add(this.distance.value!!)
}
distances.addAll(filteredDistances)
distances.toList()
}
}
fun setUnit(unit: Dimension.Unit) {
this.unit.value = unit
}
fun setDistance(distance: Dimension?) {
this.distance.value = distance
}
fun createDistanceFromInput(input: String): Dimension {
return try {
val distanceVal = input.replace("[^0-9]".toRegex(), "").toInt()
Dimension(distanceVal.toFloat(), unit.value)
} catch (e: NumberFormatException) {
// leave distance as it is
this.distance.value ?: Dimension(10f, unit.value!!)
}
}
}
| gpl-2.0 | 44aa47b92dc3503a61e2b32a4b08d6dd | 33.059701 | 93 | 0.686678 | 4.657143 | false | false | false | false |
MarkusAmshove/Kluent | common/src/main/kotlin/org/amshove/kluent/Numerical.kt | 1 | 9245 | package org.amshove.kluent
import org.amshove.kluent.internal.assertEquals
import org.amshove.kluent.internal.assertNotEquals
import org.amshove.kluent.internal.assertTrue
@Deprecated("Use `shouldBeEqualTo`", ReplaceWith("this.shouldBeEqualTo(expected)"))
infix fun Boolean.shouldEqualTo(expected: Boolean) = this.shouldBeEqualTo(expected)
infix fun Boolean.shouldBeEqualTo(expected: Boolean) = this.apply { assertEquals(expected, this) }
@Deprecated("Use `shouldBeEqualTo`", ReplaceWith("this.shouldBeEqualTo(expected)"))
infix fun Byte.shouldEqualTo(expected: Byte) = this.shouldBeEqualTo(expected)
infix fun Byte.shouldBeEqualTo(expected: Byte) = this.apply { assertEquals(expected, this) }
@Deprecated("Use `shouldBeEqualTo`", ReplaceWith("this.shouldBeEqualTo(expected)"))
infix fun Short.shouldEqualTo(expected: Short) = this.shouldBeEqualTo(expected)
infix fun Short.shouldBeEqualTo(expected: Short) = this.apply { assertEquals(expected, this) }
@Deprecated("Use `shouldBeEqualTo`", ReplaceWith("this.shouldBeEqualTo(expected)"))
infix fun Int.shouldEqualTo(expected: Int) = this.shouldBeEqualTo(expected)
infix fun Int.shouldBeEqualTo(expected: Int) = this.apply { assertEquals(expected, this) }
@Deprecated("Use `shouldBeEqualTo`", ReplaceWith("this.shouldBeEqualTo(expected)"))
infix fun Long.shouldEqualTo(expected: Long) = this.shouldBeEqualTo(expected)
infix fun Long.shouldBeEqualTo(expected: Long) = this.apply { assertEquals(expected, this) }
@Deprecated("Use `shouldBeEqualTo`", ReplaceWith("this.shouldBeEqualTo(expected)"))
infix fun Float.shouldEqualTo(expected: Float) = this.shouldBeEqualTo(expected)
infix fun Float.shouldBeEqualTo(expected: Float) = this.apply { assertEquals(expected, this) }
@Deprecated("Use `shouldBeEqualTo`", ReplaceWith("this.shouldBeEqualTo(expected)"))
infix fun Double.shouldEqualTo(expected: Double) = this.shouldBeEqualTo(expected)
infix fun Double.shouldBeEqualTo(expected: Double) = this.apply { assertEquals(expected, this) }
@Deprecated("Use `shouldNotBeEqualTo`", ReplaceWith("this.shouldNotBeEqualTo(expected)"))
infix fun Boolean.shouldNotEqualTo(expected: Boolean) = this.shouldNotBeEqualTo(expected)
infix fun Boolean.shouldNotBeEqualTo(expected: Boolean) = this.apply { assertNotEquals(expected, this) }
@Deprecated("Use `shouldNotBeEqualTo`", ReplaceWith("this.shouldNotBeEqualTo(expected)"))
infix fun Byte.shouldNotEqualTo(expected: Byte) = this.shouldNotBeEqualTo(expected)
infix fun Byte.shouldNotBeEqualTo(expected: Byte) = this.apply { assertNotEquals(expected, this) }
@Deprecated("Use `shouldNotBeEqualTo`", ReplaceWith("this.shouldNotBeEqualTo(expected)"))
infix fun Short.shouldNotEqualTo(expected: Short) = this.shouldNotBeEqualTo(expected)
infix fun Short.shouldNotBeEqualTo(expected: Short) = this.apply { assertNotEquals(expected, this) }
@Deprecated("Use `shouldNotBeEqualTo`", ReplaceWith("this.shouldNotBeEqualTo(expected)"))
infix fun Int.shouldNotEqualTo(expected: Int) = this.shouldNotBeEqualTo(expected)
infix fun Int.shouldNotBeEqualTo(expected: Int) = this.apply { assertNotEquals(expected, this) }
@Deprecated("Use `shouldNotBeEqualTo`", ReplaceWith("this.shouldNotBeEqualTo(expected)"))
infix fun Long.shouldNotEqualTo(expected: Long) = this.shouldNotBeEqualTo(expected)
infix fun Long.shouldNotBeEqualTo(expected: Long) = this.apply { assertNotEquals(expected, this) }
@Deprecated("Use `shouldNotBeEqualTo`", ReplaceWith("this.shouldNotBeEqualTo(expected)"))
infix fun Float.shouldNotEqualTo(expected: Float) = this.shouldNotBeEqualTo(expected)
infix fun Float.shouldNotBeEqualTo(expected: Float) = this.apply { assertNotEquals(expected, this) }
@Deprecated("Use `shouldNotBeEqualTo`", ReplaceWith("this.shouldNotBeEqualTo(expected)"))
infix fun Double.shouldNotEqualTo(expected: Double) = this.shouldNotBeEqualTo(expected)
infix fun Double.shouldNotBeEqualTo(expected: Double) = this.apply { assertNotEquals(expected, this) }
infix fun <T : Comparable<T>> T.shouldBeGreaterThan(expected: T) =
this.apply { assertTrue("Expected $this to be greater than $expected", this > expected) }
infix fun <T : Comparable<T>> T.shouldNotBeGreaterThan(expected: T) =
this.apply { assertTrue("Expected $this to not be greater than $expected", this <= expected) }
infix fun <T : Comparable<T>> T.shouldBeGreaterOrEqualTo(expected: T) =
this.apply { assertTrue("Expected $this to be greater or equal to $expected", this >= expected) }
infix fun <T : Comparable<T>> T.shouldNotBeGreaterOrEqualTo(expected: T) =
this.apply { assertTrue("Expected $this to be not be greater or equal to $expected", this < expected) }
infix fun <T : Comparable<T>> T.shouldBeLessThan(expected: T) =
this.apply { assertTrue("Expected $this to be less than $expected", this < expected) }
infix fun <T : Comparable<T>> T.shouldNotBeLessThan(expected: T) =
this.apply { assertTrue("Expected $this to not be less than $expected", this >= expected) }
infix fun <T : Comparable<T>> T.shouldBeLessOrEqualTo(expected: T) =
this.apply { assertTrue("Expected $this to be less or equal to $expected", this <= expected) }
infix fun <T : Comparable<T>> T.shouldNotBeLessOrEqualTo(expected: T) =
this.apply { assertTrue("Expected $this to not be less or equal to $expected", this > expected) }
fun Byte.shouldBePositive() = this.apply { assertTrue("Expected $this to be positive", this > 0) }
fun Short.shouldBePositive() = this.apply { assertTrue("Expected $this to be positive", this > 0) }
fun Int.shouldBePositive() = this.apply { assertTrue("Expected $this to be positive", this > 0) }
fun Long.shouldBePositive() = this.apply { assertTrue("Expected $this to be positive", this > 0) }
fun Float.shouldBePositive() = this.apply { assertTrue("Expected $this to be positive", this > 0) }
fun Double.shouldBePositive() = this.apply { assertTrue("Expected $this to be positive", this > 0) }
fun Byte.shouldBeNegative() = this.apply { assertTrue("Expected $this to be negative", this < 0) }
fun Short.shouldBeNegative() = this.apply { assertTrue("Expected $this to be negative", this < 0) }
fun Int.shouldBeNegative() = this.apply { assertTrue("Expected $this to be negative", this < 0) }
fun Long.shouldBeNegative() = this.apply { assertTrue("Expected $this to be negative", this < 0) }
fun Float.shouldBeNegative() = this.apply { assertTrue("Expected $this to be negative", this < 0) }
fun Double.shouldBeNegative() = this.apply { assertTrue("Expected $this to be negative", this < 0) }
fun Float.shouldBeNear(expected: Float, delta: Float): Float {
if (isNaN() && expected.isNaN()) return this
return shouldBeInRange(expected - delta, expected + delta)
}
fun Double.shouldBeNear(expected: Double, delta: Double): Double {
if (isNaN() && expected.isNaN()) return this
return shouldBeInRange(expected - delta, expected + delta)
}
fun <T : Comparable<T>> T.shouldBeInRange(lowerBound: T, upperBound: T) = this.apply {
assertTrue(
"Expected $this to be between (and including) $lowerBound and $upperBound",
this >= lowerBound && this <= upperBound
)
}
fun <T : Comparable<T>> T.shouldNotBeInRange(lowerBound: T, upperBound: T) = this.apply {
assertTrue(
"Expected $this to not be between (and including) $lowerBound and $upperBound",
this < lowerBound || this > upperBound
)
}
infix fun Byte.shouldBeInRange(range: IntRange) = this.apply { (this.toInt()).shouldBeInRange(range) }
infix fun Short.shouldBeInRange(range: IntRange) = this.apply { (this.toInt()).shouldBeInRange(range) }
infix fun Int.shouldBeInRange(range: IntRange) = this.apply { this.shouldBeInRange(range.first, range.last) }
infix fun <T : Comparable<T>> T.shouldBeInRange(range: ClosedFloatingPointRange<T>) =
this.assertIsInFloatingRange(range)
infix fun <T : Comparable<T>> T.shouldBeInRange(range: ClosedRange<T>) = this.assertIsInFloatingRange(range)
infix fun Long.shouldBeInRange(range: LongRange) = this.apply { this.shouldBeInRange(range.first, range.last) }
infix fun Byte.shouldNotBeInRange(range: IntRange) = this.apply { (this.toInt()).shouldNotBeInRange(range) }
infix fun Short.shouldNotBeInRange(range: IntRange) = this.apply { (this.toInt()).shouldNotBeInRange(range) }
infix fun Int.shouldNotBeInRange(range: IntRange) = this.apply { this.shouldNotBeInRange(range.first, range.last) }
infix fun <T : Comparable<T>> T.shouldNotBeInRange(range: ClosedFloatingPointRange<T>) =
this.assertIsNotInFloatingRange(range)
infix fun <T : Comparable<T>> T.shouldNotBeInRange(range: ClosedRange<T>) = this.assertIsNotInFloatingRange(range)
infix fun Long.shouldNotBeInRange(range: LongRange) = this.apply { this.shouldNotBeInRange(range.first, range.last) }
private fun <T : Comparable<T>> T.assertIsInFloatingRange(range: ClosedRange<T>): T = this.apply {
assertTrue(
"Expected $this to be between (and including) ${range.start} and ${range.endInclusive}",
range.contains(this)
)
}
private fun <T : Comparable<T>> T.assertIsNotInFloatingRange(range: ClosedRange<T>): T = this.apply {
assertTrue(
"Expected $this to not be between (and including) ${range.start} and ${range.endInclusive}",
!range.contains(this)
)
}
| mit | 9169a03e0b0f00f7d7a2b30cc676ebef | 48.438503 | 117 | 0.751541 | 4.038882 | false | false | false | false |
paplorinc/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/compile/KotlinCompileUtil.kt | 8 | 4012 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.recorder.compile
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.ServiceManager
import com.intellij.testGuiFramework.recorder.actions.PerformScriptAction
import java.io.File
import java.net.URL
import java.nio.file.Paths
import java.util.jar.JarFile
object KotlinCompileUtil {
private val localCompiler: LocalCompiler by lazy { LocalCompiler() }
fun compileAndRun(codeString: String) {
localCompiler.compileAndRunOnPooledThread(ScriptWrapper.wrapScript(codeString),
getAllUrls().map { Paths.get(it.toURI()).toFile().path })
}
private fun getAllUrls(): List<URL> {
if (ServiceManager::class.java.classLoader.javaClass.name.contains("Launcher\$AppClassLoader")) {
//lets substitute jars with a common lib dir to avoid Windows long path error
val urls = ServiceManager::class.java.classLoader.forcedUrls()
val libUrl = urls.first { url ->
(url.file.endsWith("idea.jar") && File(url.path).parentFile.name == "lib")
}.getParentURL()
urls.filter { url -> !url.file.startsWith(libUrl.file) }.plus(libUrl).toSet()
if (!ApplicationManager.getApplication().isUnitTestMode)
urls.plus(ServiceManager::class.java.classLoader.forcedBaseUrls())
return urls.toList()
}
val set = mutableSetOf<URL>()
set.addAll(ServiceManager::class.java.classLoader.forcedUrls())
set.addAll(PerformScriptAction::class.java.classLoader.forcedUrls())
set.addAll(PerformScriptAction::class.java.classLoader.forcedBaseUrls())
if (!ApplicationManager.getApplication().isUnitTestMode)
set.addAll(ServiceManager::class.java.classLoader.forcedBaseUrls())
expandClasspathInJar(set)
return set.toList()
}
private fun expandClasspathInJar(setOfUrls: MutableSet<URL>) {
val classpathUrl = setOfUrls.firstOrNull { Regex("classpath\\d*.jar").containsMatchIn(it.path) || it.path.endsWith("pathing.jar") }
if (classpathUrl != null) {
val classpathFile = Paths.get(classpathUrl.toURI()).toFile()
if (!classpathFile.exists()) return
val classpathLine = JarFile(classpathFile).manifest.mainAttributes.getValue("Class-Path")
val classpathList = classpathLine.split(" ").filter { it.startsWith("file") }.map { URL(it) }
setOfUrls.addAll(classpathList)
setOfUrls.remove(classpathUrl)
}
}
private fun URL.getParentURL() = File(this.file).parentFile.toURI().toURL()!!
private fun ClassLoader.forcedUrls(): List<URL> {
var methodName = "getUrls"
val methodAlternativeName = "getURLs"
if (this.javaClass.methods.any { mtd -> mtd.name == methodAlternativeName }) methodName = methodAlternativeName
val method = this.javaClass.getMethod(methodName)
method.isAccessible
val methodResult = method.invoke(this)
val myList: List<*> = (methodResult as? Array<*>)?.asList() ?: methodResult as List<*>
return myList.filterIsInstance(URL::class.java)
}
private fun ClassLoader.forcedBaseUrls(): List<URL> {
try {
return ((this.javaClass.getMethod("getBaseUrls").invoke(this) as? List<*>)!!
.filterIsInstance(URL::class.java)
.map { if (it.protocol == "jar") URL(it.toString().removeSurrounding("jar:", "!/")) else it })
}
catch (e: NoSuchMethodException) {
return emptyList()
}
}
} | apache-2.0 | 19d0fe034fb02ea6c06d7b9f2ad3a385 | 40.802083 | 135 | 0.712114 | 4.227608 | false | false | false | false |
paplorinc/intellij-community | python/src/com/jetbrains/python/psi/resolve/PyResolveImportUtil.kt | 3 | 13737 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("PyResolveImportUtil")
package com.jetbrains.python.psi.resolve
import com.google.common.base.Preconditions
import com.intellij.facet.FacetManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.FileIndexFacade
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFileSystemItem
import com.intellij.psi.PsiManager
import com.intellij.psi.util.QualifiedName
import com.jetbrains.python.codeInsight.typing.PyTypeShed
import com.jetbrains.python.codeInsight.typing.filterTopPriorityResults
import com.jetbrains.python.codeInsight.userSkeletons.PyUserSkeletonsUtil
import com.jetbrains.python.facet.PythonPathContributingFacet
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.impl.PyBuiltinCache
import com.jetbrains.python.psi.impl.PyImportResolver
import com.jetbrains.python.pyi.PyiFile
import com.jetbrains.python.sdk.PySdkUtil
import com.jetbrains.python.sdk.PythonSdkType
/**
* Python resolve utilities for qualified names.
*
* TODO: Merge with ResolveImportUtil, maybe make these functions the methods of PyQualifiedNameResolveContext.
*
* @author vlan
*/
/**
* Resolves qualified [name] to the list of packages, modules and, sometimes, classes.
*
* This method does not take into account source roots order (see PY-28321 as an example).
* The sole purpose of the method is to support classes that require class resolution until they can be migrated to [resolveQualifiedName].
*
* @see resolveQualifiedName
*/
@Deprecated("This method does not provide proper source root resolution")
fun resolveQualifiedNameWithClasses(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
return resolveQualifiedName(name, context, ::resultsFromRoots)
}
/**
* Resolves a qualified [name] to the list of packages and modules according to the [context].
*
* @see resolveTopLevelMember
*/
fun resolveQualifiedName(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
return resolveQualifiedName(name, context, ::resolveModuleFromRoots)
}
private fun resolveQualifiedName(name: QualifiedName,
context: PyQualifiedNameResolveContext,
resolveFromRoots: (QualifiedName, PyQualifiedNameResolveContext) -> List<PsiElement>): List<PsiElement> {
checkAccess()
if (!context.isValid) {
return emptyList()
}
val relativeDirectory = context.containingDirectory
val relativeResults = resolveWithRelativeLevel(name, context)
val foundRelativeImport = relativeDirectory != null &&
relativeResults.any { isRelativeImportResult(name, relativeDirectory, it, context) }
val cache = findCache(context)
val mayCache = cache != null && !foundRelativeImport
val key = cachePrefix(context).append(name)
if (mayCache) {
val cachedResults = cache?.get(key)
if (cachedResults != null) {
return relativeResults + cachedResults
}
}
val foreignResults = foreignResults(name, context)
val pythonResults = listOf(relativeResults,
// TODO: replace with resolveFromRoots when namespace package magic features PY-16688, PY-23087 are implemented
resultsFromRoots(name, context),
relativeResultsFromSkeletons(name, context)).flatten().distinct()
val allResults = pythonResults + foreignResults
val results = if (name.componentCount > 0) filterTopPriorityResults(pythonResults, context.module) + foreignResults else allResults
if (mayCache) {
cache?.put(key, results)
}
return results
}
/**
* Resolves a qualified [name] to the list of packages and modules with Python semantics according to the [context].
*/
private fun resolveModuleFromRoots(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
val head = name.removeTail(name.componentCount - 1)
val nameNoHead = name.removeHead(1)
return nameNoHead.components.fold(resultsFromRoots(head, context)) { results, component ->
filterTopPriorityResults(results, context.module)
.asSequence()
.filterIsInstance<PsiFileSystemItem>()
.flatMap { resolveModuleAt(QualifiedName.fromComponents(component), it, context).asSequence() }
.toList()
}
}
/**
* Resolves a [name] to the first module member defined at the top-level.
*/
fun resolveTopLevelMember(name: QualifiedName, context : PyQualifiedNameResolveContext): PsiElement? {
checkAccess()
val memberName = name.lastComponent ?: return null
return resolveQualifiedName(name.removeLastComponent(), context)
.asSequence()
.filterIsInstance(PyFile::class.java)
.flatMap { it.multiResolveName(memberName).asSequence() }
.map { it.element }
.firstOrNull()
}
/**
* Resolves a [name] relative to the specified [item].
*/
fun resolveModuleAt(name: QualifiedName, item: PsiFileSystemItem?, context: PyQualifiedNameResolveContext): List<PsiElement> {
checkAccess()
val empty = emptyList<PsiElement>()
if (item == null || !item.isValid) {
return empty
}
return name.components.fold(listOf<PsiElement>(item)) { seekers, component ->
if (component == null) empty
else seekers.flatMap {
val children = ResolveImportUtil.resolveChildren(it, component, context.footholdFile, !context.withMembers,
!context.withPlainDirectories, context.withoutStubs, context.withoutForeign)
PyUtil.filterTopPriorityResults(children.toTypedArray())
}
}
}
/**
* Creates a [PyQualifiedNameResolveContext] from a [foothold] element.
*/
fun fromFoothold(foothold: PsiElement): PyQualifiedNameResolveContext {
val module = ModuleUtilCore.findModuleForPsiElement(foothold.containingFile ?: foothold)
return PyQualifiedNameResolveContextImpl(foothold.manager, module, foothold, PythonSdkType.findPythonSdk(module))
}
/**
* Creates a [PyQualifiedNameResolveContext] from a [module].
*/
fun fromModule(module: Module): PyQualifiedNameResolveContext =
PyQualifiedNameResolveContextImpl(PsiManager.getInstance(module.project), module, null, PythonSdkType.findPythonSdk(module))
/**
* Creates a [PyQualifiedNameResolveContext] from an [sdk].
*/
fun fromSdk(project: Project, sdk: Sdk): PyQualifiedNameResolveContext =
PyQualifiedNameResolveContextImpl(PsiManager.getInstance(project), module = null, foothold = null, sdk = sdk)
private fun cachePrefix(context: PyQualifiedNameResolveContext): QualifiedName {
val results = mutableListOf<String>()
if (context.withoutStubs) {
results.add("without-stubs")
}
if (context.withoutForeign) {
results.add("without-foreign")
}
if (context.withoutRoots) {
results.add("without-roots")
}
return QualifiedName.fromComponents(results)
}
private fun foreignResults(name: QualifiedName, context: PyQualifiedNameResolveContext) =
if (context.withoutForeign)
emptyList()
else
PyImportResolver.EP_NAME.extensionList
.asSequence()
.map { it.resolveImportReference(name, context, !context.withoutRoots) }
.filterNotNull()
.toList()
private fun relativeResultsFromSkeletons(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
val footholdFile = context.footholdFile
if (context.withoutRoots && footholdFile != null) {
val virtualFile = footholdFile.virtualFile
if (virtualFile == null || FileIndexFacade.getInstance(context.project).isInContent(virtualFile)) {
return emptyList()
}
val containingDirectory = context.containingDirectory
if (containingDirectory != null) {
val containingName = QualifiedNameFinder.findCanonicalImportPath(containingDirectory, null)
if (containingName != null && containingName.componentCount > 0) {
val absoluteName = containingName.append(name)
val sdk = PythonSdkType.findPythonSdk(footholdFile) ?: return emptyList()
val skeletonsVirtualFile = PySdkUtil.findSkeletonsDir(sdk) ?: return emptyList()
val skeletonsDir = context.psiManager.findDirectory(skeletonsVirtualFile)
return resolveModuleAt(absoluteName, skeletonsDir, context.copyWithoutForeign())
}
}
}
return emptyList()
}
fun relativeResultsForStubsFromRoots(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
if (context.footholdFile !is PyiFile || context.relativeLevel <= 0) {
return emptyList()
}
val containingDirectory = context.containingDirectory ?: return emptyList()
val containingName = QualifiedNameFinder.findCanonicalImportPath(containingDirectory, null) ?: return emptyList()
if (containingName.componentCount <= 0) {
return emptyList()
}
val absoluteName = containingName.append(name)
return resultsFromRoots(absoluteName, context.copyWithRelative(-1).copyWithRoots())
}
private fun resolveWithRelativeLevel(name: QualifiedName, context : PyQualifiedNameResolveContext): List<PsiElement> {
val footholdFile = context.footholdFile
if (context.relativeLevel >= 0 && footholdFile != null && !PyUserSkeletonsUtil.isUnderUserSkeletonsDirectory(footholdFile)) {
return resolveModuleAt(name, context.containingDirectory, context) + relativeResultsForStubsFromRoots(name, context)
}
return emptyList()
}
/**
* Collects resolve results from all roots available.
*
* The retuning {@code List<PsiElement>} contains all elements {@code name} references
* and does not take into account root order.
*/
private fun resultsFromRoots(name: QualifiedName, context: PyQualifiedNameResolveContext): List<PsiElement> {
if (context.withoutRoots) {
return emptyList()
}
val moduleResults = mutableListOf<PsiElement>()
val sdkResults = mutableListOf<PsiElement>()
val sdk = context.effectiveSdk
val module = context.module
val footholdFile = context.footholdFile
val visitor = RootVisitor { root, module, sdk, isModuleSource ->
val results = if (isModuleSource) moduleResults else sdkResults
val effectiveSdk = sdk ?: context.effectiveSdk
if (!root.isValid ||
root == PyUserSkeletonsUtil.getUserSkeletonsDirectory() ||
effectiveSdk != null && PyTypeShed.isInside(root) && !PyTypeShed.maySearchForStubInRoot(name, root, effectiveSdk)) {
return@RootVisitor true
}
results.addAll(resolveInRoot(name, root, context))
if (isAcceptRootAsTopLevelPackage(context) && name.matchesPrefix(QualifiedName.fromDottedString(root.name))) {
results.addAll(resolveInRoot(name, root.parent, context))
}
return@RootVisitor true
}
when {
context.visitAllModules -> {
ModuleManager.getInstance(context.project).modules.forEach {
RootVisitorHost.visitRoots(it, true, visitor)
}
when {
sdk != null ->
RootVisitorHost.visitSdkRoots(sdk, visitor)
footholdFile != null ->
RootVisitorHost.visitSdkRoots(footholdFile, visitor)
}
}
module != null -> {
val otherSdk = sdk != context.sdk
RootVisitorHost.visitRoots(module, otherSdk, visitor)
if (otherSdk && sdk != null) {
RootVisitorHost.visitSdkRoots(sdk, visitor)
}
}
footholdFile != null -> {
RootVisitorHost.visitRoots(footholdFile, visitor)
}
sdk != null -> {
RootVisitorHost.visitSdkRoots(sdk, visitor)
}
else -> throw IllegalStateException()
}
return moduleResults + sdkResults
}
private fun isAcceptRootAsTopLevelPackage(context: PyQualifiedNameResolveContext): Boolean {
context.module?.let {
FacetManager.getInstance(it).allFacets.forEach {
if (it is PythonPathContributingFacet && it.acceptRootAsTopLevelPackage()) {
return true
}
}
}
return false
}
private fun resolveInRoot(name: QualifiedName, root: VirtualFile, context: PyQualifiedNameResolveContext): List<PsiElement> {
return if (root.isDirectory) resolveModuleAt(name, context.psiManager.findDirectory(root), context) else emptyList()
}
private fun findCache(context: PyQualifiedNameResolveContext): PythonPathCache? {
return when {
context.visitAllModules -> null
context.module != null ->
if (context.effectiveSdk != context.sdk) null else PythonModulePathCache.getInstance(context.module)
context.footholdFile != null -> {
val sdk = PyBuiltinCache.findSdkForNonModuleFile(context.footholdFile!!)
if (sdk != null) PythonSdkPathCache.getInstance(context.project, sdk) else null
}
else -> null
}
}
private fun isRelativeImportResult(name: QualifiedName, directory: PsiDirectory, result: PsiElement,
context: PyQualifiedNameResolveContext): Boolean {
if (context.relativeLevel > 0) {
return true
}
else {
val py2 = LanguageLevel.forElement(directory).isPython2
return context.relativeLevel == 0 && py2 && PyUtil.isPackage(directory, false, null) &&
result is PsiFileSystemItem && name != QualifiedNameFinder.findShortestImportableQName(result)
}
}
private fun checkAccess() {
Preconditions.checkState(ApplicationManager.getApplication().isReadAccessAllowed, "This method requires read access")
}
| apache-2.0 | a6272c65ae9401efd0553a5dd5b74665 | 39.049563 | 140 | 0.742156 | 4.47897 | false | false | false | false |
paplorinc/intellij-community | java/java-impl/src/com/intellij/lang/java/actions/ChangeMethodParameters.kt | 2 | 3041 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.java.actions
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.lang.jvm.actions.ChangeParametersRequest
import com.intellij.lang.jvm.actions.ExpectedParameter
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.*
internal class ChangeMethodParameters(target: PsiMethod, override val request: ChangeParametersRequest) : CreateTargetAction<PsiMethod>(
target, request) {
override fun getText(): String {
val helper = JvmPsiConversionHelper.getInstance(target.project)
val parametersString = request.expectedParameters.joinToString(", ", "(", ")") {
val psiType = helper.convertType(it.expectedTypes.first().theType)
val name = it.semanticNames.first()
"${psiType.presentableText} $name"
}
val shortenParameterString = StringUtil.shortenTextWithEllipsis(parametersString, 30, 5)
return QuickFixBundle.message("change.method.parameters.text", shortenParameterString)
}
override fun getFamilyName(): String = QuickFixBundle.message("change.method.parameters.family")
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
val factory = PsiElementFactory.getInstance(project)
val helper = JvmPsiConversionHelper.getInstance(target.project)
tailrec fun updateParameters(currentParameters: List<PsiParameter>, expectedParameters: List<ExpectedParameter>) {
val currentHead = currentParameters.firstOrNull()
val expectedHead = expectedParameters.firstOrNull()
if (expectedHead == null) {
currentParameters.forEach(PsiParameter::delete)
return
}
if (expectedHead is ChangeParametersRequest.ExistingParameterWrapper) {
if (expectedHead.existingParameter == currentHead)
return updateParameters(currentParameters.subList(1, currentParameters.size),
expectedParameters.subList(1, expectedParameters.size))
else
throw UnsupportedOperationException("processing of existing params in different order is not implemented yet")
}
val name = expectedHead.semanticNames.first()
val psiType = helper.convertType(expectedHead.expectedTypes.first().theType)
val newParameter = factory.createParameter(name, psiType)
for (annotationRequest in expectedHead.expectedAnnotations) {
addAnnotationToModifierList(newParameter.modifierList!!, annotationRequest)
}
if (currentHead == null)
target.parameterList.add(newParameter)
else
target.parameterList.addBefore(newParameter, currentHead)
updateParameters(currentParameters, expectedParameters.subList(1, expectedParameters.size))
}
updateParameters(target.parameterList.parameters.toList(), request.expectedParameters)
}
} | apache-2.0 | 2df0ec7fb81a746cc6ae882c869b2a79 | 41.25 | 140 | 0.752384 | 5.252159 | false | false | false | false |
nibarius/opera-park-android | app/src/main/java/se/barsk/park/fcm/Notification.kt | 1 | 2312 | package se.barsk.park.fcm
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.TaskStackBuilder
import android.content.Context
import android.content.Intent
import androidx.core.app.NotificationCompat
import androidx.core.content.ContextCompat
import org.json.JSONObject
import se.barsk.park.R
import se.barsk.park.mainui.ParkActivity
/**
* Base class for notifications.
*/
abstract class Notification(protected val context: Context, protected val data: JSONObject) {
protected abstract val id: String
protected abstract val timeout: Long
abstract fun show()
protected fun makeNotification(title: String, text: String) {
val mBuilder = NotificationCompat.Builder(context, id)
.setSmallIcon(R.mipmap.notif_icon)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setContentTitle(title)
.setContentText(text)
.setAutoCancel(true)
.setTimeoutAfter(timeout)
// Creates an explicit intent for an Activity in your app
val resultIntent = Intent(context, ParkActivity::class.java)
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your app to the Home screen.
val stackBuilder = TaskStackBuilder.create(context)
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ParkActivity::class.java)
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent)
val resultPendingIntent = stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
)
mBuilder.setContentIntent(resultPendingIntent)
val mNotificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
// mNotificationId is a unique integer your app uses to identify the
// notification. For example, to cancel the notification, you can pass its ID
// number to NotificationManager.cancel().
mNotificationManager.notify(0, mBuilder.build())
}
} | mit | c6b8e9b83d7c5705b8ef1df3cf36c263 | 41.054545 | 112 | 0.706747 | 5.160714 | false | false | false | false |
neilellis/kontrol | postmortem/src/main/kotlin/Parts.kt | 1 | 1758 | /*
* Copyright 2014 Cazcade Limited (http://cazcade.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @todo document.
* @author <a href="http://uk.linkedin.com/in/neilellis">Neil Ellis</a>
*/
package kontrol.postmortem
import kontrol.api.PostmortemPart
import javax.persistence.Entity as entity
import javax.persistence.Id as id
import javax.persistence.GeneratedValue as generated
public open entity class TextPart(key: String? = null, text: String? = null) : PostmortemPart(key, text) {
public override fun toString(): String {
return v?:"";
}
override fun toHTML(): String {
return "<pre>$v</pre>"
}
}
public entity class LogPart(key: String? = null, text: String? = null) : TextPart(key, text) {
override fun toHTML(): String {
val stringBuilder = StringBuilder("<div>")
var count = 1;
v?.split("\n")?.map { "<div class='row ${when {it.contains("WARN") -> "warning";it.contains("ERROR") -> "error";it.contains("INFO") -> "success" else -> ""}}'><div class='col-md-1'>${count++}</div><div class='col-md-11'>$it</div></div>" }?.appendString(stringBuilder, separator = "")
stringBuilder.append("</div>")
return stringBuilder.toString()
}
} | apache-2.0 | 9d28a075ee1efc5591402598083a3ab2 | 33.490196 | 291 | 0.672924 | 3.855263 | false | false | false | false |
RuneSuite/client | updater-common/src/main/java/org/runestar/client/updater/common/Hooks.kt | 1 | 1400 | package org.runestar.client.updater.common
data class ClassHook(
val `class`: String,
val name: String,
val `super`: String,
val access : Int,
val interfaces: List<String>,
val fields: List<FieldHook>,
val methods: List<MethodHook>,
val constructors: List<ConstructorHook>
) {
val constructorName get() = "_${`class`}_"
val descriptor get() = "L$name;"
}
data class FieldHook(
val field: String,
val owner: String,
val name: String,
val access: Int,
val descriptor: String,
val decoder: Long?
) {
val getterMethod get() = "get${field.capitalize()}"
val setterMethod get() = "set${field.capitalize()}"
val decoderNarrowed: Number? get() = when(decoder) {
null -> null
else -> {
when (descriptor) {
"I" -> decoder.toInt()
"J" -> decoder
else -> error(this)
}
}
}
val encoderNarrowed: Number? get() = decoderNarrowed?.let { invert(it) }
}
data class MethodHook(
val method: String,
val owner: String,
val name: String,
val access: Int,
val parameters: List<String>?,
val descriptor: String,
val finalArgument: Int?
)
data class ConstructorHook(
val access: Int,
val descriptor: String
) | mit | 5ffb2acd834e9a785be779e4a0b66580 | 23.155172 | 76 | 0.552857 | 4.191617 | false | false | false | false |
RuneSuite/client | updater-mapper/src/main/java/org/runestar/client/updater/mapper/std/classes/UrlRequest.kt | 1 | 1516 | package org.runestar.client.updater.mapper.std.classes
import org.runestar.client.updater.mapper.IdentityMapper
import org.runestar.client.updater.mapper.MethodParameters
import org.runestar.client.updater.mapper.and
import org.runestar.client.updater.mapper.predicateOf
import org.runestar.client.updater.mapper.type
import org.runestar.client.updater.mapper.Class2
import org.runestar.client.updater.mapper.Field2
import org.runestar.client.updater.mapper.Method2
import org.objectweb.asm.Type.*
import java.net.URL
class UrlRequest : IdentityMapper.Class() {
override val predicate = predicateOf<Class2> { it.superType == Any::class.type }
.and { it.instanceFields.any { it.type == URL::class.type } }
class url : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == URL::class.type }
}
class response0 : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == ByteArray::class.type }
}
@MethodParameters()
class getResponse : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == ByteArray::class.type }
}
class isDone0 : IdentityMapper.InstanceField() {
override val predicate = predicateOf<Field2> { it.type == BOOLEAN_TYPE }
}
@MethodParameters()
class isDone : IdentityMapper.InstanceMethod() {
override val predicate = predicateOf<Method2> { it.returnType == BOOLEAN_TYPE }
}
} | mit | 1f777f621e3a623d8505576d509afcf4 | 36.925 | 96 | 0.729551 | 4.211111 | false | false | false | false |
simasch/simon | src/main/java/ch/simas/monitor/boundry/MeasurementController.kt | 1 | 1593 | package ch.simas.monitor.boundry
import ch.simas.monitor.control.MeasurementRepository
import ch.simas.monitor.entity.Measurement
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.util.Collections
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.format.annotation.DateTimeFormat
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController
@RestController
open class MeasurementController(@Autowired val measurementRepository: MeasurementRepository) {
@RequestMapping("/measurements")
fun getMeasurements(
@RequestParam(value = "url", required = true) url: String,
@RequestParam(value = "maxResults", required = false, defaultValue = "20") maxResults: Int,
@RequestParam(value = "dateFrom", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") dateFrom: LocalDate?,
@RequestParam(value = "dateTo", required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") dateTo: LocalDate?): List<Measurement> {
val measurements = measurementRepository.find(
url,
maxResults,
if (dateFrom == null) null else LocalDateTime.of(dateFrom, LocalTime.of(0, 0)),
if (dateTo == null) null else LocalDateTime.of(dateTo, LocalTime.of(23, 59)))
Collections.sort(measurements) { o1, o2 -> o1.timestamp.compareTo(o2.timestamp) }
return measurements
}
}
| apache-2.0 | 5f7407c8445f90f9ef419bfafa24fa32 | 45.852941 | 142 | 0.727558 | 4.449721 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/openapi/editor/toolbar/floating/AbstractFloatingToolbarComponent.kt | 3 | 2869 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.editor.toolbar.floating
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl
import com.intellij.ui.JBColor
import org.jetbrains.annotations.ApiStatus
import java.awt.*
import javax.swing.JComponent
@ApiStatus.Internal
abstract class AbstractFloatingToolbarComponent(
actionGroup: ActionGroup,
override val autoHideable: Boolean,
) : ActionToolbarImpl(ActionPlaces.CONTEXT_TOOLBAR, actionGroup, true),
FloatingToolbarComponent,
TransparentComponent,
Disposable {
private val componentAnimator by lazy { TransparentComponentAnimator(this, this) }
override val component: Component get() = getComponent()
override var opacity: Float = 0.0f
override fun showComponent() {
updateActionsImmediately(true)
isVisible = hasVisibleActions()
}
override fun hideComponent() {
updateActionsImmediately()
isVisible = false
}
override fun addNotify() {
super.addNotify()
updateActionsImmediately(true)
}
override fun scheduleShow() = componentAnimator.scheduleShow()
override fun scheduleHide() = componentAnimator.scheduleHide()
protected fun hideImmediately() = componentAnimator.hideImmediately()
override fun paintComponent(g: Graphics) {
val graphics = g.create()
try {
if (graphics is Graphics2D) {
graphics.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity * BACKGROUND_ALPHA)
graphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
}
graphics.color = BACKGROUND
graphics.fillRoundRect(0, 0, bounds.width, bounds.height, 6, 6)
super.paintComponent(graphics)
}
finally {
graphics.dispose()
}
}
override fun paintChildren(g: Graphics) {
val graphics = g.create()
try {
if (graphics is Graphics2D) {
graphics.composite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity)
}
super.paintChildren(graphics)
}
finally {
graphics.dispose()
}
}
fun init(targetComponent: JComponent) {
setTargetComponent(targetComponent)
setMinimumButtonSize(Dimension(22, 22))
setSkipWindowAdjustments(true)
setReservePlaceAutoPopupIcon(false)
isOpaque = false
layoutPolicy = NOWRAP_LAYOUT_POLICY
}
override fun dispose() = Unit
init {
componentAnimator.scheduleHide()
}
companion object {
private const val BACKGROUND_ALPHA = 0.75f
private val BACKGROUND = JBColor.namedColor("Toolbar.Floating.background", JBColor(0xEDEDED, 0x454A4D))
}
} | apache-2.0 | 9c1a28c6f335dd8c2f1d29ebb0c056b2 | 28.285714 | 140 | 0.739979 | 4.553968 | false | false | false | false |
JetBrains/intellij-community | plugins/hg4idea/src/org/zmlx/hg4idea/provider/commit/HgCommitAndPushExecutor.kt | 1 | 1531 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.zmlx.hg4idea.provider.commit
import com.intellij.dvcs.commit.getCommitAndPushActionName
import com.intellij.dvcs.ui.DvcsBundle
import com.intellij.openapi.util.Key
import com.intellij.openapi.vcs.changes.CommitContext
import com.intellij.openapi.vcs.changes.CommitExecutorWithRichDescription
import com.intellij.openapi.vcs.changes.CommitSession
import com.intellij.vcs.commit.CommitWorkflowHandlerState
import com.intellij.vcs.commit.commitExecutorProperty
import org.jetbrains.annotations.Nls
private val IS_PUSH_AFTER_COMMIT_KEY = Key.create<Boolean>("Hg.Commit.IsPushAfterCommit")
internal var CommitContext.isPushAfterCommit: Boolean by commitExecutorProperty(IS_PUSH_AFTER_COMMIT_KEY)
class HgCommitAndPushExecutor : CommitExecutorWithRichDescription {
@Nls
override fun getActionText(): String = DvcsBundle.message("action.commit.and.push.text")
override fun getText(state: CommitWorkflowHandlerState): String {
return getCommitAndPushActionName(state)
}
override fun useDefaultAction(): Boolean = false
override fun requiresSyncCommitChecks(): Boolean = true
override fun getId(): String = ID
override fun createCommitSession(commitContext: CommitContext): CommitSession {
commitContext.isPushAfterCommit = true
return CommitSession.VCS_COMMIT
}
companion object {
internal const val ID = "Hg.Commit.And.Push.Executor"
}
}
| apache-2.0 | f15cb72f5e222758c2c4c38cd7045203 | 38.25641 | 140 | 0.808622 | 4.229282 | false | false | false | false |
google/iosched | buildSrc/src/main/java/Versions.kt | 1 | 1485 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
object Versions {
val versionName = "7.0.15" // X.Y.Z; X = Major, Y = minor, Z = Patch level
private val versionCodeBase = 70150 // XYYZZM; M = Module (tv, mobile)
val versionCodeMobile = versionCodeBase + 3
const val COMPILE_SDK = 31
const val TARGET_SDK = 30
const val MIN_SDK = 21
const val ANDROID_GRADLE_PLUGIN = "7.2.0"
const val BENCHMARK = "1.1.0-rc02"
const val COMPOSE = "1.1.1"
const val FIREBASE_CRASHLYTICS = "2.3.0"
const val GOOGLE_SERVICES = "4.3.3"
const val HILT_AGP = "2.40.5"
const val KOTLIN = "1.6.10"
const val NAVIGATION = "2.4.1"
const val PROFILE_INSTALLER = "1.2.0-beta01"
// TODO: Remove this once the version for
// "org.threeten:threetenbp:${Versions.threetenbp}:no-tzdb" using java-platform in the
// depconstraints/build.gradle.kts is defined
const val THREETENBP = "1.3.6"
}
| apache-2.0 | b4a0d6264b435806b88c827b9253ef0a | 36.125 | 91 | 0.682155 | 3.453488 | false | false | false | false |
JetBrains/intellij-community | platform/analysis-impl/src/com/intellij/psi/FilePropertyKeyImpl.kt | 1 | 7166 | // 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.psi
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileWithId
import com.intellij.openapi.vfs.newvfs.AttributeInputStream
import com.intellij.openapi.vfs.newvfs.AttributeOutputStream
import com.intellij.openapi.vfs.newvfs.FileAttribute
import com.intellij.util.io.DataInputOutputUtil
import org.jetbrains.annotations.Contract
import org.jetbrains.annotations.VisibleForTesting
import java.io.IOException
import java.util.function.Function
abstract class FilePropertyKeyImpl<T, RAW> protected constructor(name: String,
private val persistentAttribute: FileAttribute) : FilePropertyKey<T> {
@get:VisibleForTesting
val userDataKey: Key<Any?> = Key.create(name)
@Contract("null -> null")
override fun getPersistentValue(virtualFile: VirtualFile?): T? {
if (virtualFile == null) return null
val raw = getRaw(virtualFile, false)
return raw?.let { fromRaw(it) }
}
private fun getRaw(virtualFile: VirtualFile, forceReadPersistence: Boolean): RAW? {
@Suppress("UNCHECKED_CAST")
val memValue = userDataKey[virtualFile] as RAW?
if (memValue != null) {
return if (memValue === NULL_MARKER) null else memValue
}
if (forceReadPersistence || READ_PERSISTENT_VALUE) {
val persisted = readValue(virtualFile)
userDataKey[virtualFile] = persisted ?: NULL_MARKER
return persisted
}
else {
return null
}
}
override fun setPersistentValue(virtualFile: VirtualFile?, newValue: T?): Boolean {
if (virtualFile == null) return false
val oldValue = getRaw(virtualFile, true)
val rawNewValue = newValue?.let { toRaw(it) }
if (keysEqual(oldValue, rawNewValue)) {
return false
}
else {
writeValue(virtualFile, rawNewValue)
userDataKey[virtualFile] = if (newValue == null) NULL_MARKER else rawNewValue
return true
}
}
protected fun keysEqual(k1: RAW?, k2: RAW?): Boolean = (k1 == k2)
protected fun readValue(virtualFile: VirtualFile): RAW? {
if (virtualFile !is VirtualFileWithId) {
LOG.debug("Only VirtualFileWithId can have persistent attributes: $virtualFile")
return null
}
try {
persistentAttribute.readFileAttribute(virtualFile).use { stream ->
if (stream != null && stream.available() > 0) {
return readValue(stream)
}
}
}
catch (e: IOException) {
LOG.error(e)
}
return null
}
protected fun writeValue(virtualFile: VirtualFile, newValue: RAW?) {
if (virtualFile !is VirtualFileWithId) {
LOG.debug("Only VirtualFileWithId can have persistent attributes: $virtualFile")
return
}
try {
persistentAttribute.writeFileAttribute(virtualFile).use { stream -> writeValue(stream, newValue) }
}
catch (e: IOException) {
LOG.error(e)
}
}
@Throws(IOException::class)
protected abstract fun readValue(stream: AttributeInputStream): RAW?
@Throws(IOException::class)
protected abstract fun writeValue(stream: AttributeOutputStream, newValue: RAW?)
/*
* Note that we can write something meaningful into persistent attribute (e.g. LanguageID="GenericSQL"), then user may remove the plugin,
* and stored value may become meaningless. In this case it is OK to transform non-null into null value
*/
protected abstract fun fromRaw(value: RAW): T?
protected abstract fun toRaw(value: T): RAW
companion object {
@JvmStatic
@get:VisibleForTesting
val READ_PERSISTENT_VALUE: Boolean by lazy(LazyThreadSafetyMode.PUBLICATION) {
Registry.`is`("retrieve.pushed.properties.from.vfs", false) or Registry.`is`("scanning.in.smart.mode", false)
}
@JvmStatic
private val NULL_MARKER by lazy(LazyThreadSafetyMode.PUBLICATION) {
if (Registry.`is`("cache.nulls.for.pushed.properties", false) or Registry.`is`("scanning.in.smart.mode", false)) {
Object()
}
else {
null
}
}
@JvmStatic
private val LOG = Logger.getInstance(FilePropertyKeyImpl::class.java)
@JvmStatic
fun createPersistentStringKey(name: String, persistentAttribute: FileAttribute): FilePropertyKey<String> {
return createPersistentStringKey(name, persistentAttribute, String::toString, String::toString)
}
@JvmStatic
fun <T> createPersistentStringKey(name: String,
persistentAttribute: FileAttribute,
fnToRaw: Function<T, String>,
fnFromRaw: Function<String, T?>): FilePropertyKey<T> {
return FilePropertyStringKey(name, persistentAttribute, fnToRaw, fnFromRaw)
}
@JvmStatic
fun <T : Enum<T>> createPersistentEnumKey(userDataName: String,
persistentDataName: String,
persistentDataVersion: Int,
clazz: Class<T>): FilePropertyKey<T> {
return FilePropertyEnumKey(userDataName, FileAttribute(persistentDataName, persistentDataVersion, true), clazz)
}
}
}
internal class FilePropertyStringKey<T>(name: String, persistentAttribute: FileAttribute,
private val fnToRaw: Function<T, String>,
private val fnFromRaw: Function<String, T?>) : FilePropertyKeyImpl<T, String>(name,
persistentAttribute) {
override fun fromRaw(value: String): T? = fnFromRaw.apply(value)
override fun toRaw(value: T): String = fnToRaw.apply(value)
@Throws(IOException::class)
override fun readValue(stream: AttributeInputStream): String? = stream.readEnumeratedString()
@Throws(IOException::class)
override fun writeValue(stream: AttributeOutputStream, newValue: String?) = stream.writeEnumeratedString(newValue)
}
internal class FilePropertyEnumKey<T : Enum<T>>(name: String,
persistentAttribute: FileAttribute,
private val clazz: Class<T>) : FilePropertyKeyImpl<T, Int>(name, persistentAttribute) {
@Throws(IOException::class)
override fun readValue(stream: AttributeInputStream): Int = DataInputOutputUtil.readINT(stream)
@Throws(IOException::class)
override fun writeValue(stream: AttributeOutputStream, newValue: Int?) {
newValue?.let { DataInputOutputUtil.writeINT(stream, it) }
}
override fun fromRaw(value: Int): T? {
if (value >= 0 && value < clazz.enumConstants.size) {
return clazz.enumConstants[value]
}
else {
return null
}
}
override fun toRaw(value: T): Int = value.ordinal
} | apache-2.0 | d99c9c21e12b0a0934fa2de9baaee3a1 | 37.326203 | 140 | 0.662155 | 4.623226 | false | false | false | false |
burntcookie90/KotMeh | app/src/main/kotlin/io/dwak/meh/view/ImagePagerAdapter.kt | 1 | 1231 | package io.dwak.meh.view
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.support.v4.view.ViewPager
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.squareup.picasso.Picasso
import io.dwak.meh.loadImage
public class ImagePagerAdapter(context : Context) : PagerAdapter(){
private val context : Context;
var imageUrls : List<String>? = null
init {
this.context = context
}
override fun instantiateItem(container : ViewGroup?, position : Int) : Any? {
val imageView = ImageView(context)
if(imageUrls?.get(position) !== null){
context.loadImage(imageUrls?.get(position)!!, imageView)
(container as ViewPager).addView(imageView)
}
else {
val blankView = View(context)
(container as ViewPager).addView(blankView)
}
return imageView
}
override fun destroyItem(container : ViewGroup?, position : Int, o : Any?) = (container as ViewPager).removeView(o as View)
override fun isViewFromObject(view : View?, o : Any?) : Boolean = view === o as View
override fun getCount() : Int = imageUrls?.size() ?: 0
} | apache-2.0 | 9dfc4df56d2dd5186d84b7f5921105b3 | 30.589744 | 127 | 0.675873 | 4.365248 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/rhre3/extras/TestAffineScreen.kt | 2 | 2032 | package io.github.chrislo27.rhre3.extras
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Input
import com.badlogic.gdx.graphics.Texture
import io.github.chrislo27.rhre3.RHRE3Application
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.registry.AssetRegistry
import io.github.chrislo27.toolboks.registry.ScreenRegistry
import io.github.chrislo27.toolboks.util.gdxutils.fillRect
class TestAffineScreen(main: RHRE3Application) : ToolboksScreen<RHRE3Application, TestAffineScreen>(main) {
override fun render(delta: Float) {
val batch = main.batch
batch.begin()
batch.setColor(0.9f, 0.9f, 0.9f, 1f)
batch.fillRect(0f, 0f, 1280f, 720f)
batch.setColor(1f, 0f, 0f, 1f)
batch.fillRect(512f, 0f, 1f, 720f)
batch.setColor(0f, 0f, 1f, 1f)
batch.fillRect(0f, 512f, 1280f, 1f)
batch.setColor(1f, 1f, 1f, 1f)
val tex: Texture = AssetRegistry["logo_256"]
val width = 48f * -1f
val height = 32f
val x = 504f
val y = 483f
val originX = width / 2f
val originY = height / 2f
val scaleX = 1f
val scaleY = 1f
val rotation = -115.06123352050781f // 115.06123352050781
val flipX = false
val flipY = false
// width * stretchX
// rotation stays the same
// gdx scaleX and scaleY must always be 1
batch.draw(tex, x, y + height, originX, originY, width, height, scaleX, scaleY, rotation, 0, 0, 256, 256, flipX, flipY)
batch.setColor(0f, 1f, 0f, 1f)
batch.fillRect(x + originX - 2f, y + originY - 2f, 4f, 4f)
batch.setColor(1f, 1f, 1f, 1f)
batch.end()
super.render(delta)
}
override fun renderUpdate() {
super.renderUpdate()
if (Gdx.input.isKeyJustPressed(Input.Keys.ESCAPE))
main.screen = ScreenRegistry["info"]
}
override fun tickUpdate() {
}
override fun dispose() {
}
} | gpl-3.0 | 185c0832cb97c629804504329eeb5fac | 30.276923 | 127 | 0.626476 | 3.48542 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/rhmodding/bread/model/brcad/Animation.kt | 2 | 1421 | package rhmodding.bread.model.brcad
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import rhmodding.bread.model.IAnimation
import rhmodding.bread.util.Unknown
class Animation : IAnimation {
@Unknown
var unknown: Short = 0
override val steps: MutableList<AnimationStep> = mutableListOf()
override fun copy(): Animation {
return Animation().also {
it.unknown = unknown
steps.mapTo(it.steps) { it.copy() }
}
}
override fun toString(): String {
return "Animation=[numSteps=${steps.size}, steps=[${steps.joinToString(separator = "\n")}]]"
}
fun getCurrentStep(frameNum: Int): AnimationStep? {
if (steps.isEmpty()) return null
if (steps.size == 1) return steps.first()
val totalFrames = steps.sumBy { it.delay.toInt() }
val frame = frameNum % totalFrames
var currentFrame = 0
return steps.firstOrNull {
val result = frame in currentFrame..(currentFrame + it.delay.toInt())
currentFrame += it.delay.toInt()
result
}
}
fun render(batch: SpriteBatch, sheet: Texture, sprites: List<Sprite>, frameNum: Int, offsetX: Float, offsetY: Float): AnimationStep? {
val step = getCurrentStep(frameNum)
step?.render(batch, sheet, sprites, offsetX, offsetY)
return step
}
} | gpl-3.0 | 91917ae68658197a5d1167e74fa8b2b8 | 29.913043 | 138 | 0.635468 | 4.332317 | false | false | false | false |
allotria/intellij-community | platform/platform-tests/testSrc/com/intellij/internal/statistics/config/EventLogConfigVersionParserTest.kt | 3 | 18793 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistics.config
import com.intellij.internal.statistic.config.bean.EventLogBucketRange
import com.intellij.internal.statistic.config.bean.EventLogSendConfiguration
import com.intellij.internal.statistic.eventLog.EventLogBuildType
import com.intellij.internal.statistic.eventLog.EventLogBuildType.EAP
import com.intellij.internal.statistic.eventLog.EventLogBuildType.RELEASE
import org.junit.Test
class EventLogConfigVersionParserTest : EventLogConfigBaseParserTest() {
private fun doTestNoVersion(versions: String) {
val config = """
{
"productCode": "IU",
"versions": [""" + versions + """]
}"""
doTest(config, notExistingEndpoints = setOf("send", "metadata"))
}
private fun doTestVersion(versions: String, expected: Map<String, String>,
expectedConfig: Map<EventLogBuildType, EventLogSendConfiguration>? = null) {
val buildConfig = expectedConfig ?: mapOf(
EAP to EventLogSendConfiguration(listOf(EventLogBucketRange(0, 256))),
RELEASE to EventLogSendConfiguration(listOf(EventLogBucketRange(0, 256)))
)
val config = """
{
"productCode": "IU",
"versions": [""" + versions + """]
}"""
doTest(config, existingConfig = buildConfig, existingEndpoints = expected)
}
//region Endpoints with invalid versions
@Test
fun `test parse endpoint with no versions`() {
doTestNoVersion("""
{
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with empty version`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with unknown numerical property in version`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"unknown": 2019
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with unknown string property in version`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"unknown": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with from and unknown string property in version`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.1",
"unknown": "2019.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with to and unknown string property in version`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"unknown": "2019.3",
"to": "2020.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with from and to and unknown string property in version`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"unknown": "2019.3",
"from": "2019.1",
"to": "2020.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with from bigger than to in version`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.2",
"to": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with major to bigger than to in version`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2020.1",
"to": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with boolean from version`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": true
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with alphabet from version`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "my.version"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
//endregion
//region Endpoints with [from, ...) version
@Test
fun `test parse endpoint with numerical from version`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": 2019
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with only from and version equal to from`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with only from and version bigger than from`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with only from and major version bigger than from`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2018.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with only from and version smaller than from`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with only from and major version smaller than from`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2020.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
//endregion
//region Endpoints with [.., to) version
@Test
fun `test parse endpoint with only to and version equal to from`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"to": "2019.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with only to and version bigger than from`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"to": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with only to and major version bigger than from`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"to": "2018.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with only to and version smaller than from`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"to": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with only to and major version smaller than from`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"to": "2020.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
//endregion
//region Endpoints with [from, to) version
@Test
fun `test parse simple endpoints from config`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.1",
"to": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with version equal to from and smaller than to`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.2",
"to": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with version equal to from and to`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.2",
"to": "2019.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with version bigger than from and smaller than to`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.1",
"to": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with version bigger than from and bigger than to`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2018.2",
"to": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with major version bigger than from and smaller than to`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2018.3",
"to": "2020.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with major version bigger than from and bigger than to`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2018.2",
"to": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with version smaller than from and to`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.3",
"to": "2020.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
@Test
fun `test parse endpoint with major version smaller than from and to`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"from": "2018.1",
"to": "2018.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
}""")
}
//endregion
//region Endpoints with multiple versions
@Test
fun `test parse endpoint with first version applicable`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.2",
"to": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
},
{
"majorBuildVersionBorders": {
"from": "2019.2",
"to": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 32, "to": 64 }],
"endpoints": {
"send": "https://send/endpoint-last",
"metadata": "https://metadata/endpoint-last"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with last version applicable`() {
val config = mapOf(
RELEASE to EventLogSendConfiguration(listOf(EventLogBucketRange(32, 64)))
)
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2017.1",
"to": "2018.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
},
{
"majorBuildVersionBorders": {
"from": "2019.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 32, "to": 64 }],
"endpoints": {
"send": "https://send/endpoint-last",
"metadata": "https://metadata/endpoint-last"
}
}""", mapOf("send" to "https://send/endpoint-last", "metadata" to "https://metadata/endpoint-last"), config)
}
@Test
fun `test parse endpoint with middle version applicable`() {
val config = mapOf(
RELEASE to EventLogSendConfiguration(listOf(EventLogBucketRange(32, 64)))
)
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2017.1",
"to": "2018.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
},
{
"majorBuildVersionBorders": {
"from": "2019.1",
"to": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 32, "to": 64 }],
"endpoints": {
"send": "https://send/endpoint-middle",
"metadata": "https://metadata/endpoint-middle"
}
},
{
"majorBuildVersionBorders": {
"from": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 32, "to": 64 }],
"endpoints": {
"send": "https://send/endpoint-last",
"metadata": "https://metadata/endpoint-last"
}
}""", mapOf("send" to "https://send/endpoint-middle", "metadata" to "https://metadata/endpoint-middle"), config)
}
@Test
fun `test parse endpoint with no versions applicable`() {
doTestNoVersion("""
{
"majorBuildVersionBorders": {
"to": "2018.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
},
{
"majorBuildVersionBorders": {
"from": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 32, "to": 64 }],
"endpoints": {
"send": "https://send/endpoint-last",
"metadata": "https://metadata/endpoint-last"
}
}""")
}
@Test
fun `test parse endpoint with two versions applicable`() {
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2019.1",
"to": "2019.3"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
},
{
"majorBuildVersionBorders": {
"from": "2019.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 32, "to": 64 }],
"endpoints": {
"send": "https://send/endpoint-last",
"metadata": "https://metadata/endpoint-last"
}
}""", mapOf("send" to "https://send/endpoint", "metadata" to "https://metadata/endpoint/"))
}
@Test
fun `test parse endpoint with two last versions applicable`() {
val config = mapOf(
RELEASE to EventLogSendConfiguration(listOf(EventLogBucketRange(32, 64)))
)
doTestVersion("""
{
"majorBuildVersionBorders": {
"from": "2018.1",
"to": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 0, "to": 256 }],
"endpoints": {
"send": "https://send/endpoint",
"metadata": "https://metadata/endpoint/"
}
},
{
"majorBuildVersionBorders": {
"from": "2019.1"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 32, "to": 64 }],
"endpoints": {
"send": "https://send/endpoint-middle",
"metadata": "https://metadata/endpoint-middle"
}
},
{
"majorBuildVersionBorders": {
"from": "2019.2"
},
"releaseFilters": [{ "releaseType": "ALL", "from": 32, "to": 64 }],
"endpoints": {
"send": "https://send/endpoint-last",
"metadata": "https://metadata/endpoint-last"
}
}""", mapOf("send" to "https://send/endpoint-middle", "metadata" to "https://metadata/endpoint-middle"), config)
}
//endregion
}
| apache-2.0 | 532867cfdb3deddc564ab7149c0d4278 | 25.543785 | 140 | 0.598787 | 3.533183 | false | true | false | false |
OpenASR/idear | src/main/java/org/openasr/idear/nlp/PatternBasedNlpProvider.kt | 2 | 4306 | package org.openasr.idear.nlp
import com.intellij.openapi.actionSystem.IdeActions.*
import org.openasr.idear.actions.ActionRoutines.pauseSpeech
import org.openasr.idear.actions.ActionRoutines.routineAbout
import org.openasr.idear.actions.ActionRoutines.routineCheck
import org.openasr.idear.actions.ActionRoutines.routineExtract
import org.openasr.idear.actions.ActionRoutines.routineFind
import org.openasr.idear.actions.ActionRoutines.routineFocus
import org.openasr.idear.actions.ActionRoutines.routineFollowing
import org.openasr.idear.actions.ActionRoutines.routineGoto
import org.openasr.idear.actions.ActionRoutines.routineHandleBreakpoint
import org.openasr.idear.actions.ActionRoutines.routineOfLine
import org.openasr.idear.actions.ActionRoutines.routineOpen
import org.openasr.idear.actions.ActionRoutines.routinePress
import org.openasr.idear.actions.ActionRoutines.routinePrintln
import org.openasr.idear.actions.ActionRoutines.routinePsvm
import org.openasr.idear.actions.ActionRoutines.routineReleaseKey
import org.openasr.idear.actions.ActionRoutines.routineStep
import org.openasr.idear.actions.ActionRoutines.tellJoke
import org.openasr.idear.actions.WhereAmIAction
import org.openasr.idear.ide.IDEService
import org.openasr.idear.ide.IDEService.invokeAction
import org.openasr.idear.nlp.Commands.DEBUG
import org.openasr.idear.nlp.Commands.EXECUTE
import org.openasr.idear.nlp.Commands.EXPAND
import org.openasr.idear.nlp.Commands.FOCUS
import org.openasr.idear.nlp.Commands.GOTO
import org.openasr.idear.nlp.Commands.HI_IDEA
import org.openasr.idear.nlp.Commands.NAVIGATE
import org.openasr.idear.nlp.Commands.OPEN
import org.openasr.idear.nlp.Commands.PRESS
import org.openasr.idear.nlp.Commands.SHOW_USAGES
import org.openasr.idear.nlp.Commands.SHRINK
import org.openasr.idear.nlp.Commands.WHERE_AM_I
import org.openasr.idear.tts.TTSService
import java.awt.event.KeyEvent.*
class PatternBasedNlpProvider : NlpProvider {
/**
* @param utterance - the command as spoken
*/
override fun processUtterance(utterance: String) {
when {
utterance == HI_IDEA -> TTSService.say("Hi, again!")
utterance.startsWith(OPEN) -> routineOpen(utterance)
utterance.startsWith(NAVIGATE) -> invokeAction("GotoDeclaration")
utterance.startsWith(EXECUTE) -> invokeAction("Run")
utterance == WHERE_AM_I -> WhereAmIAction()
utterance.startsWith(FOCUS) -> routineFocus(utterance)
utterance.startsWith(GOTO) -> routineGoto(utterance)
utterance.startsWith(EXPAND) -> invokeAction(ACTION_EDITOR_SELECT_WORD_AT_CARET)
utterance.startsWith(SHRINK) -> invokeAction(ACTION_EDITOR_UNSELECT_WORD_AT_CARET)
utterance.startsWith(PRESS) -> routinePress(utterance)
utterance.startsWith("release") -> routineReleaseKey(utterance)
utterance.startsWith("following") -> routineFollowing(utterance)
utterance.startsWith("extract this") -> routineExtract(utterance)
utterance.startsWith("inspect code") -> invokeAction("CodeInspection.OnEditor")
utterance.startsWith("speech pause") -> pauseSpeech()
utterance == SHOW_USAGES -> invokeAction("ShowUsages")
// u.startsWith(OKAY_IDEA) -> routineOkIdea()
// u.startsWith(OKAY_GOOGLE) -> fireGoogleSearch()
"break point" in utterance -> routineHandleBreakpoint(utterance)
utterance.startsWith(DEBUG) -> IDEService.type(VK_CONTROL, VK_SHIFT, VK_F9)
utterance.startsWith("step") -> routineStep(utterance)
utterance.startsWith("resume") -> invokeAction("Resume")
utterance.startsWith("tell me a joke") -> tellJoke()
"check" in utterance -> routineCheck(utterance)
"tell me about yourself" in utterance -> routineAbout()
// "add new class" in u -> routineAddNewClass()
"print line" in utterance -> routinePrintln()
// "new string" in u -> routineNewString()
// "enter " in u -> routineEnter(u)
"public static void main" in utterance -> routinePsvm()
utterance.endsWith("of line") -> routineOfLine(utterance)
utterance.startsWith("find in") -> routineFind(utterance)
}
}
} | apache-2.0 | ba631e442bff2473033bb9e39ce94f77 | 53.518987 | 94 | 0.735253 | 3.787159 | false | false | false | false |
allotria/intellij-community | platform/platform-impl/src/com/intellij/ui/GotItTooltip.kt | 1 | 29995 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ui
import com.intellij.icons.AllIcons
import com.intellij.ide.BrowserUtil
import com.intellij.ide.HelpTooltip
import com.intellij.ide.IdeBundle
import com.intellij.ide.IdeEventQueue
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.collectors.fus.ui.GotItUsageCollector
import com.intellij.internal.statistic.collectors.fus.ui.GotItUsageCollectorGroup
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.actionSystem.Shortcut
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.ui.popup.Balloon
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.Disposer
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.HtmlBuilder
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.components.labels.LinkListener
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.Alarm
import com.intellij.util.ui.*
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import java.awt.*
import java.awt.event.ActionListener
import java.awt.event.ComponentAdapter
import java.awt.event.ComponentEvent
import java.awt.event.KeyEvent
import java.io.StringReader
import java.net.URL
import javax.swing.*
import javax.swing.event.AncestorEvent
import javax.swing.text.*
import javax.swing.text.html.HTML
import javax.swing.text.html.HTMLDocument
import javax.swing.text.html.HTMLEditorKit
import javax.swing.text.html.StyleSheet
/**
* id is a unique id for the tooltip that will be used to store the tooltip state in <code>PropertiesComponent</code>
* id has the following format: place.where.used - lowercase words separated with dots.
* GotIt tooltip usage statistics can be properly gathered if its id prefix is registered in plugin.xml (PlatformExtensions.xml)
* with gotItTooltipAllowlist extension point. Prefix can cover a whole class of different gotit tooltips.
* If prefix is shorter than the whole ID then all different tooltip usages will be reported in one category described by the prefix.
*/
class GotItTooltip(@NonNls val id: String, @Nls val text: String, private val parentDisposable: Disposable) : Disposable {
private class ActionContext(val tooltip: GotItTooltip, val pointProvider: (Component) -> Point)
@Nls
private var header : String = ""
@Nls
private var buttonLabel: String = IdeBundle.message("got.it.button.name")
private var shortcut: Shortcut? = null
private var icon: Icon? = null
private var timeout : Int = -1
private var link : LinkLabel<Unit>? = null
private var linkAction : () -> Unit = {}
private var maxWidth = MAX_WIDTH
private var showCloseShortcut = false
private var maxCount = 1
private var position = Balloon.Position.below
private var onBalloonCreated : (Balloon) -> Unit = {}
// Ease the access (remove private or val to var) if fine tuning is needed.
private val savedCount : (String) -> Int = { PropertiesComponent.getInstance().getInt(it, 0) }
private val canShow : (String) -> Boolean = { savedCount(it) < maxCount }
private val gotIt : (String) -> Unit = {
val count = savedCount(it)
if (count in 0 until maxCount) PropertiesComponent.getInstance().setValue(it, (count + 1).toString())
onGotIt()
}
private var onGotIt: () -> Unit = {}
private val alarm = Alarm()
private var balloon : Balloon? = null
private var nextToShow : GotItTooltip? = null // Next tooltip in the global queue
private var pendingRefresh = false
init {
Disposer.register(parentDisposable, this)
}
/**
* Add optional header to the tooltip.
*/
fun withHeader(@Nls header: String) : GotItTooltip {
this.header = header
return this
}
/**
* Add optional shortcut after mandatory description (text).
*/
fun withShortcut(shortcut: Shortcut) : GotItTooltip {
this.shortcut = shortcut
return this
}
/**
* Set alternative button text instead of default "Got It".
*/
fun withButtonLabel(@Nls label: String) : GotItTooltip {
this.buttonLabel = label
return this
}
/**
* Add optional icon on the left of the header or description.
*/
fun withIcon(icon: Icon) : GotItTooltip {
this.icon = icon
return this
}
/**
* Set close timeout. If set then tooltip appears without "Got It" button.
*/
@JvmOverloads
fun withTimeout(timeout: Int = DEFAULT_TIMEOUT) : GotItTooltip {
if (timeout > 0) {
this.timeout = timeout
}
return this
}
/**
* Limit tooltip body width to the given value. By default it's limited to <code>MAX_WIDTH</code> pixels.
*/
fun withMaxWidth(width: Int) : GotItTooltip {
maxWidth = width
return this
}
/**
* Add optional link to the tooltip.
*/
fun withLink(@Nls linkLabel: String, action: () -> Unit) : GotItTooltip {
link = object : LinkLabel<Unit>(linkLabel, null) {
override fun getNormal() : Color = LINK_FOREGROUND
}
linkAction = action
return this
}
/**
* Add optional link to the tooltip. Java version.
*/
fun withLink(@Nls linkLabel: String, action: Runnable) : GotItTooltip {
return withLink(linkLabel) { action.run() }
}
/**
* Add optional browser link to the tooltip. Link is rendered with arrow icon.
*/
fun withBrowserLink(@Nls linkLabel: String, url: URL) : GotItTooltip {
link = object : LinkLabel<Unit>(linkLabel, AllIcons.Ide.External_link_arrow) {
override fun getNormal() : Color = LINK_FOREGROUND
}.apply { horizontalTextPosition = SwingConstants.LEFT }
linkAction = { BrowserUtil.browse(url) }
return this
}
/**
* Set number of times the tooltip is shown.
*/
fun withShowCount(count: Int) : GotItTooltip {
if (count > 0) maxCount = count
return this
}
/**
* Set preferred tooltip position relatively to the owner component
*/
fun withPosition(position: Balloon.Position) : GotItTooltip {
this.position = position
return this
}
/**
* Optionally show close shortcut next to Got It button
*/
fun andShowCloseShortcut() : GotItTooltip {
showCloseShortcut = true
return this
}
/**
* Set notification method that's called when actual <code>Balloon</code> is created.
*/
fun setOnBalloonCreated(callback: (Balloon) -> Unit) : GotItTooltip {
onBalloonCreated = callback
return this
}
/**
* Returns <code>true</code> if this tooltip can be shown at the given properties settings.
*/
fun canShow() : Boolean = canShow("$PROPERTY_PREFIX.$id")
/**
* Show tooltip for the given component and point to the component.
* If the component is showing (see <code>Component.isShowing</code>) and has not empty bounds then
* the tooltip is shown right away.
* If the component is showing but has empty bounds (technically not visible) then tooltip is shown asynchronously
* when component gets resized to not empty bounds.
* If the component is not showing then tooltip is shown asynchronously when component is added to the hierarchy and
* gets not empty bounds.
*/
fun show(component: JComponent, pointProvider: (Component) -> Point) {
if (canShow()) {
if (component.isShowing) {
if (!component.bounds.isEmpty) {
showImpl(component, pointProvider)
}
else {
component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(event: ComponentEvent) {
if (!event.component.bounds.isEmpty) {
showImpl(event.component as JComponent, pointProvider)
}
}
}.also{ Disposer.register(this, Disposable { component.removeComponentListener(it) }) })
}
}
else {
component.addAncestorListener(object : AncestorListenerAdapter() {
override fun ancestorAdded(ancestorEvent: AncestorEvent) {
if (!ancestorEvent.component.bounds.isEmpty) {
showImpl(ancestorEvent.component, pointProvider)
}
else {
ancestorEvent.component.addComponentListener(object : ComponentAdapter() {
override fun componentResized(componentEvent: ComponentEvent) {
if (!componentEvent.component.bounds.isEmpty) {
showImpl(componentEvent.component as JComponent, pointProvider)
}
}
}.also{ Disposer.register(this@GotItTooltip, Disposable { component.removeComponentListener(it) }) })
}
}
override fun ancestorRemoved(ancestorEvent: AncestorEvent) {
balloon?.let {
it.hide(true)
GotItUsageCollector.instance.logClose(id, GotItUsageCollectorGroup.CloseType.AncestorRemoved)
}
balloon = null
}
}.also{ Disposer.register(this, Disposable { component.removeAncestorListener(it) }) })
}
}
}
/**
* Bind the tooltip to action's presentation. Then <code>ActionToolbar</code> starts following ActionButton with
* the tooltip if it can be shown. Term "follow" is used because ActionToolbar updates its content and ActionButton's
* showing status / location may change in time.
*/
fun assignTo(presentation: Presentation, pointProvider: (Component) -> Point) {
presentation.putClientProperty(PRESENTATION_KEY, ActionContext(this, pointProvider))
Disposer.register(this, Disposable { presentation.putClientProperty(PRESENTATION_KEY, null) })
}
private fun showImpl(component: JComponent, pointProvider: (Component) -> Point) {
if (canShow()) {
val balloonProperty = UIUtil.getClientProperty(component, BALLOON_PROPERTY)
if (balloonProperty == null) {
val tracker = object : PositionTracker<Balloon> (component) {
override fun recalculateLocation(balloon: Balloon): RelativePoint? =
if (getComponent().isShowing)
RelativePoint(component, pointProvider(component))
else {
balloon.hide(true)
GotItUsageCollector.instance.logClose(id, GotItUsageCollectorGroup.CloseType.AncestorRemoved)
null
}
}
balloon = createAndShow(tracker).also { UIUtil.putClientProperty(component, BALLOON_PROPERTY, it) }
}
else if (balloonProperty is BalloonImpl && balloonProperty.isVisible) {
balloonProperty.revalidate()
}
}
else {
hideBalloon()
}
}
private fun followToolbarComponent(component: JComponent, toolbar: JComponent, pointProvider: (Component) -> Point) {
if (canShow()) {
component.addComponentListener(object : ComponentAdapter() {
override fun componentMoved(event: ComponentEvent) {
hideOrRepaint(event.component)
}
override fun componentResized(event: ComponentEvent) {
if (balloon == null && !event.component.bounds.isEmpty && event.component.isShowing) {
val tracker = object : PositionTracker<Balloon>(event.component) {
override fun recalculateLocation(balloon: Balloon): RelativePoint = RelativePoint(getComponent(), pointProvider(getComponent()))
}
balloon = createAndShow(tracker)
}
else {
hideOrRepaint(event.component)
}
}
}.also{ Disposer.register(this, Disposable { component.removeComponentListener(it) }) })
toolbar.addAncestorListener(object : AncestorListenerAdapter() {
override fun ancestorRemoved(event: AncestorEvent) {
hideBalloon()
}
override fun ancestorMoved(event: AncestorEvent?) {
hideOrRepaint(component)
}
}.also{ Disposer.register(this, Disposable { component.removeAncestorListener(it) }) })
}
}
private fun createAndShow(tracker: PositionTracker<Balloon>) : Balloon {
val balloon = createBalloon().also {
val dispatcherDisposable = Disposer.newDisposable()
Disposer.register(this, dispatcherDisposable)
it.addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
GotItUsageCollector.instance.logOpen(id, savedCount("$PROPERTY_PREFIX.$id") + 1)
}
override fun onClosed(event: LightweightWindowEvent) {
HelpTooltip.setMasterPopupOpenCondition(tracker.component, null)
UIUtil.putClientProperty(tracker.component as JComponent, BALLOON_PROPERTY, null)
Disposer.dispose(dispatcherDisposable)
if (event.isOk) {
currentlyShown?.nextToShow = null
currentlyShown = null
gotIt("$PROPERTY_PREFIX.$id")
}
else {
pendingRefresh = true
}
}
})
IdeEventQueue.getInstance().addDispatcher(IdeEventQueue.EventDispatcher { e ->
if (e is KeyEvent && KeymapUtil.isEventForAction(e, CLOSE_ACTION_NAME)) {
it.hide(true)
GotItUsageCollector.instance.logClose(id, GotItUsageCollectorGroup.CloseType.EscapeShortcutPressed)
true
}
else false
}, dispatcherDisposable)
HelpTooltip.setMasterPopupOpenCondition(tracker.component) {
it.isDisposed
}
onBalloonCreated(it)
}
when {
currentlyShown == null -> {
balloon.show(tracker, position)
currentlyShown = this
}
currentlyShown!!.pendingRefresh -> {
nextToShow = currentlyShown!!.nextToShow
balloon.show(tracker, position)
currentlyShown = this
}
else -> {
var tooltip = currentlyShown as GotItTooltip
while (tooltip.nextToShow != null) {
tooltip = tooltip.nextToShow as GotItTooltip
}
tooltip.scheduleNext(this) {
if (tracker.component.isShowing && !tracker.component.bounds.isEmpty) {
balloon.show(tracker, position)
currentlyShown = this@GotItTooltip
}
else {
nextToShow?.let{ it.onGotIt() }
}
}
}
}
return balloon
}
private fun scheduleNext(tooltip: GotItTooltip, show: () -> Unit) {
nextToShow = tooltip
onGotIt = show
}
private fun createBalloon() : Balloon {
var button : JButton? = null
val balloon = JBPopupFactory.getInstance().createBalloonBuilder(createContent { button = it }).
setDisposable(this).
setHideOnAction(false).
setHideOnClickOutside(false).
setHideOnFrameResize(false).
setHideOnKeyOutside(false).
setBlockClicksThroughBalloon(true).
setBorderColor(BORDER_COLOR).
setCornerToPointerDistance(ARROW_SHIFT).
setFillColor(BACKGROUND_COLOR).
setPointerSize(JBUI.size(16, 8)).
createBalloon().
also {
it.setAnimationEnabled(false)
}
val collector = GotItUsageCollector.instance
link?.apply{
setListener(LinkListener { _, _ ->
linkAction()
balloon.hide(true)
collector.logClose(id, GotItUsageCollectorGroup.CloseType.LinkClick)
}, null)
}
button?.apply {
addActionListener(ActionListener {
balloon.hide(true)
collector.logClose(id, GotItUsageCollectorGroup.CloseType.ButtonClick)
})
}
if (timeout > 0) {
alarm.cancelAllRequests()
alarm.addRequest({
balloon.hide(true)
collector.logClose(id, GotItUsageCollectorGroup.CloseType.Timeout)
}, timeout)
}
return balloon
}
private fun createContent(buttonSupplier: (JButton) -> Unit) : JComponent {
val panel = JPanel(GridBagLayout())
val gc = GridBag()
val left = if (icon != null) 8 else 0
val column = if (icon != null) 1 else 0
icon?.let { panel.add(JLabel(it), gc.nextLine().next().anchor(GridBagConstraints.BASELINE)) }
if (header.isNotEmpty()) {
if (icon == null) gc.nextLine()
panel.add(JBLabel(HtmlChunk.raw(header).bold().wrapWith(HtmlChunk.font(ColorUtil.toHtmlColor(FOREGROUND_COLOR))).
wrapWith(HtmlChunk.html()).toString()),
gc.setColumn(column).anchor(GridBagConstraints.LINE_START).insetLeft(left))
}
val builder = HtmlBuilder()
builder.append(HtmlChunk.raw(text).wrapWith(HtmlChunk.font(ColorUtil.toHtmlColor(FOREGROUND_COLOR))))
shortcut?.let {
builder.append(HtmlChunk.nbsp()).append(HtmlChunk.nbsp()).
append(HtmlChunk.text(KeymapUtil.getShortcutText(it)).wrapWith(HtmlChunk.font(ColorUtil.toHtmlColor(SHORTCUT_COLOR))))
}
if (icon == null || header.isNotEmpty()) gc.nextLine()
panel.add(LimitedWidthLabel(builder, maxWidth),
gc.setColumn(column).anchor(GridBagConstraints.LINE_START).insets(if (header.isNotEmpty()) 5 else 0, left, 0, 0))
link?.let {
panel.add(it, gc.nextLine().setColumn(column).anchor(GridBagConstraints.LINE_START).insets(5, left, 0, 0))
}
if (timeout <= 0) {
val button = JButton(buttonLabel).apply{
isFocusable = false
isOpaque = false
putClientProperty("gotItButton", true)
}
buttonSupplier(button)
if (showCloseShortcut) {
val buttonPanel = JPanel().apply{ isOpaque = false }
buttonPanel.layout = BoxLayout(buttonPanel, BoxLayout.X_AXIS)
buttonPanel.add(button)
buttonPanel.add(Box.createHorizontalStrut(JBUIScale.scale(UIUtil.DEFAULT_HGAP)))
@Suppress("HardCodedStringLiteral")
val closeShortcut = JLabel(KeymapUtil.getShortcutText(CLOSE_ACTION_NAME)).apply { foreground = SHORTCUT_COLOR }
buttonPanel.add(closeShortcut)
panel.add(buttonPanel, gc.nextLine().setColumn(column).insets(11, left, 0, 0).anchor(GridBagConstraints.LINE_START))
}
else {
panel.add(button, gc.nextLine().setColumn(column).insets(11, left, 0, 0).anchor(GridBagConstraints.LINE_START))
}
}
panel.background = BACKGROUND_COLOR
panel.border = PANEL_MARGINS
return panel
}
override fun dispose() {
hideBalloon()
removeMeFromQueue()
}
private fun removeMeFromQueue() {
if (currentlyShown === this) currentlyShown = nextToShow
else {
var tooltip = currentlyShown
while(tooltip != null) {
if (tooltip.nextToShow === this) {
tooltip.nextToShow = nextToShow
break
}
tooltip = tooltip.nextToShow
}
}
}
private fun hideBalloon() {
balloon?.hide(false)
balloon = null
}
private fun hideOrRepaint(component: Component) {
balloon?.let {
if (component.bounds.isEmpty) {
hideBalloon()
}
else if (it is BalloonImpl && it.isVisible) {
it.revalidate()
}
}
}
companion object {
@JvmField
val ARROW_SHIFT = JBUIScale.scale(20) + Registry.intValue("ide.balloon.shadow.size") + BalloonImpl.ARC.get()
const val PROPERTY_PREFIX = "got.it.tooltip"
private val PRESENTATION_KEY = Key<ActionContext>("$PROPERTY_PREFIX.presentation")
private val BALLOON_PROPERTY = Key<Balloon>("$PROPERTY_PREFIX.balloon")
private const val DEFAULT_TIMEOUT = 5000 // milliseconds
private const val CLOSE_ACTION_NAME = "CloseGotItTooltip"
private val MAX_WIDTH = JBUIScale.scale(280)
private val FOREGROUND_COLOR = JBColor.namedColor("GotItTooltip.foreground", UIUtil.getToolTipForeground())
private val SHORTCUT_COLOR = JBColor.namedColor("GotItTooltip.shortcutForeground", JBUI.CurrentTheme.Tooltip.shortcutForeground())
private val BACKGROUND_COLOR = JBColor.namedColor("GotItTooltip.background", UIUtil.getToolTipBackground())
private val BORDER_COLOR = JBColor.namedColor("GotItTooltip.borderColor", JBUI.CurrentTheme.Tooltip.borderColor())
private val LINK_FOREGROUND = JBColor.namedColor("GotItTooltip.linkForeground", JBUI.CurrentTheme.Link.Foreground.ENABLED)
private val PANEL_MARGINS = JBUI.Borders.empty(7, 4, 9, 9)
private val iconClasses = hashMapOf<String, Class<*>>()
internal fun findIcon(src: String) : Icon? {
val iconClassName = src.split(".")[0]
val iconClass = iconClasses[iconClassName] ?: AllIcons::class.java
return IconLoader.findIcon(src, iconClass)
}
/**
* Register icon class that's used for resolving icons from icon tags.
* parentDisposable should be disposed on plugin removal.
* AllIcons is used by default if corresponding icons class hasn't been registered or found so
* there is not need to explicitly register it.
*/
fun registerIconClass(iconClass: Class<*>, parentDisposable: Disposable) {
iconClasses[iconClass.simpleName] = iconClass
Disposer.register(parentDisposable) {
iconClasses.remove(iconClass.simpleName)
}
}
/**
* Use this method for following an ActionToolbar component.
*/
@JvmStatic
fun followToolbarComponent(presentation: Presentation, component: JComponent, toolbar: JComponent) {
presentation.getClientProperty(PRESENTATION_KEY)?.let {
it.tooltip.followToolbarComponent(component, toolbar, it.pointProvider)
}
}
// Frequently used point providers
@JvmField
val TOP_MIDDLE : (Component) -> Point = { Point(it.width / 2, 0) }
@JvmField
val LEFT_MIDDLE : (Component) -> Point = { Point(0, it.height / 2) }
@JvmField
val RIGHT_MIDDLE : (Component) -> Point = { Point(it.width, it.height / 2) }
@JvmField
val BOTTOM_MIDDLE : (Component) -> Point = { Point(it.width / 2, it.height) }
// Global tooltip queue start element
private var currentlyShown: GotItTooltip? = null
}
}
private class LimitedWidthLabel(htmlBuilder: HtmlBuilder, limit: Int) : JLabel() {
val htmlView : View
init {
var htmlText = htmlBuilder.wrapWith(HtmlChunk.div()).wrapWith(HtmlChunk.html()).toString()
var view = createHTMLView(this, htmlText)
var width = view.getPreferredSpan(View.X_AXIS)
if (width > limit) {
view = createHTMLView(this, htmlBuilder.wrapWith(HtmlChunk.div().attr("width", limit)).wrapWith(HtmlChunk.html()).toString())
width = rows(view).maxOfOrNull { it.getPreferredSpan(View.X_AXIS) } ?: limit.toFloat()
htmlText = htmlBuilder.wrapWith(HtmlChunk.div().attr("width", width.toInt())).wrapWith(HtmlChunk.html()).toString()
view = createHTMLView(this, htmlText)
}
htmlView = view
preferredSize = Dimension(view.getPreferredSpan(View.X_AXIS).toInt(), view.getPreferredSpan(View.Y_AXIS).toInt())
}
override fun paintComponent(g: Graphics) {
val rect = Rectangle(width, height)
JBInsets.removeFrom(rect, insets)
htmlView.paint(g, rect)
}
private fun rows(root: View) : Collection<View> {
return ArrayList<View>().also { visit(root, it) }
}
private fun visit(view: View, collection: MutableCollection<View>) {
val cname : String? = view.javaClass.canonicalName
cname?.let { if (it.contains("ParagraphView.Row")) collection.add(view) }
for (i in 0 until view.viewCount) {
visit(view.getView(i), collection)
}
}
companion object {
val editorKit = GotItEditorKit()
private fun createHTMLView(component: JComponent, html: String) : View {
val document = editorKit.createDocument(component.font, component.foreground)
StringReader(html).use { editorKit.read(it, document, 0) }
val factory = editorKit.viewFactory
return RootView(component, factory, factory.create(document.defaultRootElement))
}
}
private class GotItEditorKit : HTMLEditorKit() {
companion object {
private const val STYLES = "p { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }" +
"body { margin-top: 0; margin-bottom: 0; margin-left: 0; margin-right: 0 }"
}
private val viewFactory = object : HTMLFactory() {
override fun create(elem: Element) : View {
val attr = elem.attributes
if ("icon" == elem.name) {
val src = attr.getAttribute(HTML.Attribute.SRC) as String
val icon = GotItTooltip.findIcon(src)
if (icon != null) {
return GotItIconView(icon, elem)
}
}
return super.create(elem)
}
}
private val style = StyleSheet()
private var initialized = false
override fun getStyleSheet(): StyleSheet {
if (!initialized) {
StringReader(STYLES).use { style.loadRules(it, null) }
style.addStyleSheet(super.getStyleSheet())
initialized = true
}
return style
}
override fun getViewFactory(): ViewFactory = viewFactory
fun createDocument(font: Font, foreground: Color) : Document {
val s = StyleSheet().also {
it.addStyleSheet(styleSheet)
it.addRule(displayPropertiesToCSS(font, foreground))
}
return HTMLDocument(s).also {
it.asynchronousLoadPriority = Int.MAX_VALUE
it.preservesUnknownTags = true
}
}
private fun displayPropertiesToCSS(font: Font?, fg: Color?): String {
val rule = StringBuilder("body {")
font?.let {
rule.append(" font-family: ").append(it.family).append(" ; ").append(" font-size: ").append(it.size).append("pt ;")
if (it.isBold) rule.append(" font-weight: 700 ; ")
if (it.isItalic) rule.append(" font-style: italic ; ")
}
fg?.let {
rule.append(" color: #")
if (it.red < 16) rule.append('0')
rule.append(Integer.toHexString(it.red))
if (it.green < 16) rule.append('0')
rule.append(Integer.toHexString(it.green))
if (it.blue < 16) rule.append('0')
rule.append(Integer.toHexString(it.blue))
rule.append(" ; ")
}
return rule.append(" }").toString()
}
}
private class GotItIconView(private val icon: Icon, elem: Element) : View(elem) {
private val hAlign = (elem.attributes.getAttribute(HTML.Attribute.HALIGN) as String?)?.toFloatOrNull() ?: 0.5f
private val vAlign = (elem.attributes.getAttribute(HTML.Attribute.VALIGN) as String?)?.toFloatOrNull() ?: 0.75f
override fun getPreferredSpan(axis: Int): Float =
(if (axis == X_AXIS) icon.iconWidth else icon.iconHeight).toFloat()
override fun getToolTipText(x: Float, y: Float, allocation: Shape): String? =
if (icon is IconWithToolTip) icon.getToolTip(true) else
element.attributes.getAttribute(HTML.Attribute.ALT) as String?
override fun paint(g: Graphics, allocation: Shape) {
allocation.bounds.let { icon.paintIcon(null, g, it.x, it.y) }
}
override fun modelToView(pos: Int, a: Shape, b: Position.Bias?): Shape {
if (pos in startOffset .. endOffset) {
val rect = a.bounds
if (pos == endOffset) {
rect.x += rect.width
}
rect.width = 0
return rect
}
throw BadLocationException("$pos not in range $startOffset,$endOffset", pos)
}
override fun getAlignment(axis: Int): Float =
if (axis == X_AXIS) hAlign else vAlign
override fun viewToModel(x: Float, y: Float, a: Shape, bias: Array<Position.Bias>): Int {
val alloc = a as Rectangle
if (x < alloc.x + alloc.width / 2f) {
bias[0] = Position.Bias.Forward
return startOffset
}
bias[0] = Position.Bias.Backward
return endOffset
}
}
private class RootView(private val host : JComponent, private val factory: ViewFactory, private val view : View) : View(null) {
private var width : Float = 0.0f
init {
view.parent = this
setSize(view.getPreferredSpan(X_AXIS), view.getPreferredSpan(Y_AXIS))
}
override fun preferenceChanged(child: View?, width: Boolean, height: Boolean) {
host.revalidate()
host.repaint()
}
override fun paint(g: Graphics, allocation: Shape) {
val bounds = allocation.bounds
view.setSize(bounds.width.toFloat(), bounds.height.toFloat())
view.paint(g, bounds)
}
override fun setParent(parent: View) {
throw Error("Can't set parent on root view")
}
override fun setSize(width: Float, height: Float) {
this.width = width
view.setSize(width, height)
}
// Mostly delegation
override fun getAttributes(): AttributeSet? = null
override fun getPreferredSpan(axis: Int): Float = if (axis == X_AXIS) width else view.getPreferredSpan(axis)
override fun getMinimumSpan(axis: Int): Float = view.getMinimumSpan(axis)
override fun getMaximumSpan(axis: Int): Float = Int.MAX_VALUE.toFloat()
override fun getAlignment(axis: Int): Float = view.getAlignment(axis)
override fun getViewCount(): Int = 1
override fun getView(n: Int) = view
override fun modelToView(pos: Int, a: Shape, b: Position.Bias): Shape = view.modelToView(pos, a, b)
override fun modelToView(p0: Int, b0: Position.Bias, p1: Int, b1: Position.Bias, a: Shape): Shape = view.modelToView(p0, b0, p1, b1, a)
override fun viewToModel(x: Float, y: Float, a: Shape, bias: Array<out Position.Bias>): Int = view.viewToModel(x, y, a, bias)
override fun getDocument(): Document = view.document
override fun getStartOffset(): Int = view.startOffset
override fun getEndOffset(): Int = view.endOffset
override fun getElement(): Element = view.element
override fun getContainer(): Container = host
override fun getViewFactory(): ViewFactory = factory
}
} | apache-2.0 | 414de79c1991d1b80598d6b1785f5796 | 34.794749 | 142 | 0.670612 | 4.323292 | false | false | false | false |
genonbeta/TrebleShot | app/src/main/java/org/monora/uprotocol/client/android/database/ClientTypeConverter.kt | 1 | 1923 | /*
* Copyright (C) 2021 Veli Tasalı
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.monora.uprotocol.client.android.database
import android.util.Base64
import androidx.room.TypeConverter
import org.monora.uprotocol.core.protocol.ClientType
import org.spongycastle.cert.X509CertificateHolder
import org.spongycastle.cert.jcajce.JcaX509CertificateConverter
import org.spongycastle.jce.provider.BouncyCastleProvider
import java.security.cert.X509Certificate
class ClientTypeConverter {
private val bouncyCastleProvider = BouncyCastleProvider()
@TypeConverter
fun fromCertificate(value: X509Certificate?): String? {
if (value == null)
return null
return Base64.encodeToString(value.encoded, Base64.DEFAULT)
}
@TypeConverter
fun toCertificate(value: String?): X509Certificate? {
if (value == null)
return null
return JcaX509CertificateConverter().setProvider(bouncyCastleProvider)
.getCertificate(X509CertificateHolder(Base64.decode(value, Base64.DEFAULT)))
}
@TypeConverter
fun fromType(value: ClientType): String = value.protocolValue
@TypeConverter
fun toType(value: String): ClientType = ClientType.from(value)
} | gpl-2.0 | cd3a1f6e10a2530831e0b013cfd9f876 | 35.283019 | 88 | 0.748699 | 4.3386 | false | false | false | false |
stevesea/RPGpad | adventuresmith-core/src/main/kotlin/org/stevesea/adventuresmith/core/dice_roller/ExplodingDiceGenerator.kt | 2 | 5482 | /*
* Copyright (c) 2017 Steve Christensen
*
* This file is part of Adventuresmith.
*
* Adventuresmith 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.
*
* Adventuresmith 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 Adventuresmith. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.stevesea.adventuresmith.core.dice_roller
import mu.KLoggable
import org.stevesea.adventuresmith.core.Generator
import org.stevesea.adventuresmith.core.GeneratorInputDto
import org.stevesea.adventuresmith.core.GeneratorMetaDto
import org.stevesea.adventuresmith.core.InputParamDto
import java.text.NumberFormat
import java.util.Locale
class ExplodingDiceGenerator( val myid: String,
val myname: String,
val diceParser: DiceParser) : Generator, KLoggable {
override val logger = logger()
override fun getId(): String {
return myid
}
override fun generate(locale: Locale, input: Map<String, String>?): String {
val inputMapForContext = getMetadata(locale).mergeInputWithDefaults(input)
val die = (inputMapForContext.getOrElse("y") { "6" }).toString().toInt()
val nDie = (inputMapForContext.getOrElse("x") { "1" }).toString().toInt()
val eGreaterVal = inputMapForContext.getOrElse("eGreater") { "" }.toString()
val eGreater = if (eGreaterVal.isNullOrEmpty()) 0 else eGreaterVal.toInt()
val eEqualVal = inputMapForContext.getOrElse("eEqual") { "" }.toString()
var eEqual = if (eEqualVal.isNullOrEmpty()) 0 else eEqualVal.toInt()
if (eGreater == 0 && eEqual == 0) {
// if neither has been set, use the die #
eEqual = die
}
if (eGreater > 0) {
// if eGreater has been set, only use eGreater (as is displayed by template)
eEqual = 0
}
val collected_rolls : MutableList<List<Int>> = mutableListOf()
var numIters = 0
var numToRoll = nDie
do {
numIters++
val rolls = diceParser.rollN("1d" + die, numToRoll)
collected_rolls.add(rolls)
val matched_rolls = rolls.filter {
(eGreater > 0 && it >= eGreater) || (eEqual > 0 && it == eEqual)
}
numToRoll = matched_rolls.size
logger.debug("Rolled: $rolls. matches: $matched_rolls ($numToRoll)")
if (numIters > 100) {
logger.info("Too many explodes. abandon ship!")
collected_rolls.add(listOf(0))
break
}
} while (matched_rolls.isNotEmpty())
logger.debug(" ... done. Collected rolls: $collected_rolls")
val dStrSb = StringBuilder("${nDie}d$die!")
if (eGreater > 0)
dStrSb.append(">" + eGreater)
else if (eEqual > 0)
dStrSb.append(eEqual)
else if (eGreater == 0 && eEqual == 0)
dStrSb.append(die)
val dStr = dStrSb.toString()
val sum = collected_rolls.map { it -> it.sum() }.sum()
val nf = NumberFormat.getInstance(locale)
val sb = StringBuilder()
sb.append("$dStr: <big><strong>${nf.format(sum)}</strong></big><br/><br/>")
sb.append(collected_rolls.map {
it -> it.map {
it2 -> if ((eGreater > 0 && it2 >= eGreater) || (eEqual > 0 && it2 == eEqual)) "<strong>$it2</strong>" else "$it2"
}.joinToString(", ", "[", "]")
}.joinToString(" + <br/>"))
return sb.toString()
}
override fun getMetadata(locale: Locale): GeneratorMetaDto {
return GeneratorMetaDto(name = myname,
input = GeneratorInputDto(
displayTemplate = "<big>{{x}}d{{y}}!{{#eGreater}}>{{eGreater}}{{/eGreater}}{{^eGreater}}{{#eEqual}}{{eEqual}}{{/eEqual}}{{/eGreater}}{{^eGreater}}{{^eEqual}}{{y}}{{/eEqual}}{{/eGreater}}</big>",
useWizard = false,
params = listOf(
InputParamDto(name = "x", uiName = "X (# of die)", numbersOnly = true, isInt = true, defaultValue = "1",
maxVal = 100, minVal = 1,
helpText = "Enter dice 'XdY'"),
InputParamDto(name = "y", uiName = "Y (# of sides)", numbersOnly = true, isInt = true, defaultValue = "6"),
InputParamDto(name = "eGreater", uiName = ">E", numbersOnly = true, isInt = true, minVal = 2,
nullIfZero = true, defaultValue = "",
helpText = "Explode if greater than or equal to:"),
InputParamDto(name = "eEqual", uiName = "=E", numbersOnly = true, isInt = true,
nullIfZero = true, defaultValue = "",
helpText = "Explode if equal to:")
)
)
)
}
} | gpl-3.0 | 6fa2428de63bbcf6e391da7dc926c223 | 40.537879 | 218 | 0.55965 | 4.051737 | false | false | false | false |
mtransitapps/mtransit-for-android | src/main/java/org/mtransit/android/ui/schedule/day/ScheduleDayFragment.kt | 1 | 4809 | @file:JvmName("ScheduleDayFragment") // ANALYTICS
package org.mtransit.android.ui.schedule.day
import android.os.Bundle
import android.view.View
import androidx.core.os.bundleOf
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import dagger.hilt.android.AndroidEntryPoint
import org.mtransit.android.R
import org.mtransit.android.commons.MTLog
import org.mtransit.android.commons.ThreadSafeDateFormatter
import org.mtransit.android.databinding.FragmentScheduleDayBinding
import org.mtransit.android.ui.fragment.MTFragmentX
import org.mtransit.android.ui.view.common.isVisible
import org.mtransit.android.util.UITimeUtils
import java.util.Locale
@AndroidEntryPoint
class ScheduleDayFragment : MTFragmentX(R.layout.fragment_schedule_day), MTLog.Loggable {
companion object {
private val LOG_TAG = ScheduleDayFragment::class.java.simpleName
@JvmStatic
fun newInstance(uuid: String, authority: String, dayStartsAtInMs: Long): ScheduleDayFragment {
return ScheduleDayFragment().apply {
arguments = bundleOf(
ScheduleDayViewModel.EXTRA_POI_UUID to uuid,
ScheduleDayViewModel.EXTRA_AUTHORITY to authority,
ScheduleDayViewModel.EXTRA_DAY_START_AT_IN_MS to dayStartsAtInMs,
)
}
}
}
private var theLogTag: String = LOG_TAG
override fun getLogTag(): String = this.theLogTag
private val viewModel by viewModels<ScheduleDayViewModel>()
private var binding: FragmentScheduleDayBinding? = null
private val adapter: ScheduleDayAdapter by lazy {
ScheduleDayAdapter()
}
private var timeChangedReceiverEnabled = false
private val timeChangedReceiver = UITimeUtils.TimeChangedReceiver { adapter.onTimeChanged() }
private val dayDateFormat by lazy { ThreadSafeDateFormatter("EEEE, MMM d, yyyy", Locale.getDefault()) }
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding = FragmentScheduleDayBinding.bind(view).apply {
list.adapter = adapter
}
viewModel.yearMonthDay.observe(viewLifecycleOwner, { yearMonthDay ->
theLogTag = yearMonthDay?.let { "$LOG_TAG-$it" } ?: LOG_TAG
adapter.setYearMonthDay(yearMonthDay)
})
viewModel.dayStartsAtInMs.observe(viewLifecycleOwner, { dayStartsAtInMs ->
dayStartsAtInMs?.let {
binding?.dayDate?.text = getDayDateString(it)
adapter.setDayStartsAt(it)
}
})
viewModel.timestamps.observe(viewLifecycleOwner, { timestamps ->
adapter.setTimes(timestamps)
binding?.apply {
if (timestamps != null && viewModel.scrolledToNow.value != true) {
adapter.getScrollToNowPosition()?.let {
list.scrollToPosition(it)
}
viewModel.setScrolledToNow(true)
}
loadingLayout.isVisible = !adapter.isReady()
list.isVisible = adapter.isReady()
}
})
viewModel.rts.observe(viewLifecycleOwner, { rts ->
adapter.setRTS(rts)
})
}
private fun getDayDateString(dayStartsAtInMs: Long): CharSequence {
return when {
UITimeUtils.isYesterday(dayStartsAtInMs) -> getString(R.string.yesterday) + " "
UITimeUtils.isToday(dayStartsAtInMs) -> getString(R.string.today) + " "
UITimeUtils.isTomorrow(dayStartsAtInMs) -> getString(R.string.tomorrow) + " "
else -> ""
} + dayDateFormat.formatThreadSafe(UITimeUtils.getNewCalendar(dayStartsAtInMs).time)
}
override fun onDetach() {
super.onDetach()
disableTimeChangedReceiver()
}
override fun onResume() {
super.onResume()
enableTimeChangedReceiver()
}
override fun onPause() {
super.onPause()
disableTimeChangedReceiver()
}
private fun enableTimeChangedReceiver() {
if (!timeChangedReceiverEnabled) {
activity?.registerReceiver(timeChangedReceiver, UITimeUtils.TIME_CHANGED_INTENT_FILTER)
timeChangedReceiverEnabled = true
adapter.onTimeChanged() // force update to current time before next change
}
}
private fun disableTimeChangedReceiver() {
if (timeChangedReceiverEnabled) {
activity?.unregisterReceiver(timeChangedReceiver)
timeChangedReceiverEnabled = false
adapter.onTimeChanged(-1L) // mark time as not updating anymore
}
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
} | apache-2.0 | c844e927e38e8a80b7dc1c6445199322 | 35.439394 | 107 | 0.659597 | 4.973113 | false | false | false | false |
leafclick/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/changes/GHPRChangesModelImpl.kt | 1 | 3846 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.changes
import com.intellij.icons.AllIcons
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.Change
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNode
import com.intellij.openapi.vcs.changes.ui.ChangesBrowserNodeRenderer
import com.intellij.openapi.vcs.changes.ui.ChangesGroupingPolicyFactory
import com.intellij.openapi.vcs.changes.ui.TreeModelBuilder
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.EventDispatcher
import com.intellij.util.text.DateFormatUtil
import com.intellij.xml.util.XmlStringUtil
import org.jetbrains.plugins.github.api.data.GHCommit
import org.jetbrains.plugins.github.api.data.GHGitActor
import org.jetbrains.plugins.github.pullrequest.ui.SimpleEventListener
import javax.swing.tree.DefaultTreeModel
class GHPRChangesModelImpl(private val project: Project) : GHPRChangesModel {
private val eventDispatcher = EventDispatcher.create(SimpleEventListener::class.java)
private var _commits: Map<GHCommit, List<Change>>? = null
override var commits: Map<GHCommit, List<Change>>?
get() = _commits
set(value) {
_commits = value
_changes = null
eventDispatcher.multicaster.eventOccurred()
}
private var _changes: List<Change>? = null
override var changes: List<Change>?
get() = _changes
set(value) {
_changes = value
_commits = null
eventDispatcher.multicaster.eventOccurred()
}
override fun buildChangesTree(grouping: ChangesGroupingPolicyFactory): DefaultTreeModel {
val builder = MyTreeModelBuilder(project, grouping)
if (changes != null) {
builder.setChanges(changes!!, null)
}
else if (commits != null) {
for ((commit, changes) in commits!!) {
builder.addCommit(commit, changes)
}
}
return builder.build()
}
override fun addStateChangesListener(listener: () -> Unit) {
eventDispatcher.addListener(object : SimpleEventListener {
override fun eventOccurred() {
listener()
}
})
}
private class MyTreeModelBuilder(project: Project, grouping: ChangesGroupingPolicyFactory) : TreeModelBuilder(project, grouping) {
fun addCommit(commit: GHCommit, changes: List<Change>) {
val parentNode = CommitTagBrowserNode(commit)
parentNode.markAsHelperNode()
myModel.insertNodeInto(parentNode, myRoot, myRoot.childCount)
for (change in changes) {
insertChangeNode(change, parentNode, createChangeNode(change, null))
}
}
}
private class CommitTagBrowserNode(val commit: GHCommit) : ChangesBrowserNode<Any>(commit) {
override fun render(renderer: ChangesBrowserNodeRenderer, selected: Boolean, expanded: Boolean, hasFocus: Boolean) {
renderer.icon = AllIcons.Vcs.CommitNode
renderer.append(commit.messageHeadlineHTML, SimpleTextAttributes.REGULAR_ATTRIBUTES)
renderer.append(" by ${commit.author.getName()} " +
"on ${commit.author.getDate()}",
SimpleTextAttributes.GRAYED_ATTRIBUTES)
val tooltip = "commit ${commit.oid}\n" +
"Author: ${commit.author.getName()}\n" +
"Date: ${commit.author.getDate()}\n\n" +
commit.messageHeadlineHTML + "\n\n" +
commit.messageBodyHTML
renderer.toolTipText = XmlStringUtil.escapeString(tooltip)
}
private fun GHGitActor?.getName() = this?.name ?: "unknown"
private fun GHGitActor?.getDate() = this?.date?.let { DateFormatUtil.formatDateTime(it) } ?: "unknown"
override fun getTextPresentation(): String {
return commit.messageHeadlineHTML
}
}
} | apache-2.0 | d58a824f82b8afbaee7db8b8b167d123 | 37.858586 | 140 | 0.713729 | 4.508792 | false | false | false | false |
byoutline/kickmaterial | app/src/main/java/com/byoutline/kickmaterial/features/projectlist/MainActivity.kt | 1 | 2444 | package com.byoutline.kickmaterial.features.projectlist
import android.annotation.TargetApi
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.Menu
import com.byoutline.kickmaterial.R
import com.byoutline.kickmaterial.features.selectcategory.ARG_CATEGORY
import com.byoutline.kickmaterial.features.selectcategory.CategoriesListActivity
import com.byoutline.kickmaterial.features.selectcategory.DataManager
import com.byoutline.kickmaterial.model.Category
import com.byoutline.kickmaterial.utils.AutoHideToolbarActivity
import com.byoutline.secretsauce.activities.showFragment
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
/**
* @author Pawel Karczewski <pawel.karczewski at byoutline.com> on 2015-01-03
*/
class MainActivity : AutoHideToolbarActivity(), HasSupportFragmentInjector {
@Inject
lateinit var dispatchingFragmentInjector: DispatchingAndroidInjector<Fragment>
override fun supportFragmentInjector(): AndroidInjector<Fragment> = dispatchingFragmentInjector
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.add(R.id.container, ProjectsListFragment.newInstance(DataManager.categoryAll))
.commit()
}
}
override fun setToolbarAlpha(alpha: Float) {
toolbar?.background?.alpha = (alpha * 255).toInt()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.main, menu)
return true
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
val categorySelection = requestCode == CategoriesListActivity.DEFAULT_REQUEST_CODE
if (categorySelection && resultCode == CategoriesListActivity.RESULT_CATEGORY_SELECTED) {
val category = data?.getParcelableExtra<Category>(ARG_CATEGORY) ?: return
showFragment(ProjectsListFragment.newInstance(category), true)
setToolbarText(category.nameResId)
}
}
}
| apache-2.0 | dc3a9a703c4aa677273a4181f5d4f315 | 40.423729 | 99 | 0.761457 | 4.937374 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/NameValidators.kt | 2 | 4858 | // 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.core
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.util.getAllAccessibleFunctions
import org.jetbrains.kotlin.idea.util.getAllAccessibleVariables
import org.jetbrains.kotlin.idea.util.getResolutionScope
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.findDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.resolve.descriptorUtil.isExtension
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.ErrorUtils
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.util.*
class CollectingNameValidator @JvmOverloads constructor(
existingNames: Collection<String> = Collections.emptySet(),
private val filter: (String) -> Boolean = { true }
) : (String) -> Boolean {
private val existingNames = HashSet(existingNames)
override fun invoke(name: String): Boolean {
if (name !in existingNames && filter(name)) {
existingNames.add(name)
return true
}
return false
}
fun addName(name: String) {
existingNames.add(name)
}
}
class NewDeclarationNameValidator(
private val visibleDeclarationsContext: KtElement?,
private val checkDeclarationsIn: Sequence<PsiElement>,
private val target: Target,
private val excludedDeclarations: List<KtDeclaration> = emptyList()
) : (String) -> Boolean {
constructor(
container: PsiElement,
anchor: PsiElement?,
target: Target,
excludedDeclarations: List<KtDeclaration> = emptyList()
) : this(
(anchor ?: container).parentsWithSelf.firstIsInstanceOrNull<KtElement>(),
anchor?.siblings() ?: container.allChildren,
target,
excludedDeclarations
)
enum class Target {
VARIABLES,
FUNCTIONS_AND_CLASSES
}
override fun invoke(name: String): Boolean {
val identifier = Name.identifier(name)
if (visibleDeclarationsContext != null) {
val bindingContext = visibleDeclarationsContext.analyze(BodyResolveMode.PARTIAL_FOR_COMPLETION)
val resolutionScope =
visibleDeclarationsContext.getResolutionScope(bindingContext, visibleDeclarationsContext.getResolutionFacade())
if (resolutionScope.hasConflict(identifier)) return false
}
return checkDeclarationsIn.none {
it.findDescendantOfType<KtNamedDeclaration> { it.isConflicting(identifier) } != null
}
}
private fun isExcluded(it: DeclarationDescriptorWithSource) = ErrorUtils.isError(it) || it.source.getPsi() in excludedDeclarations
private fun LexicalScope.hasConflict(name: Name): Boolean {
fun DeclarationDescriptor.isVisible(): Boolean {
return when (this) {
is DeclarationDescriptorWithVisibility -> isVisible(ownerDescriptor)
else -> true
}
}
return when (target) {
Target.VARIABLES ->
getAllAccessibleVariables(name).any { !it.isExtension && it.isVisible() && !isExcluded(it) }
Target.FUNCTIONS_AND_CLASSES ->
getAllAccessibleFunctions(name).any { !it.isExtension && it.isVisible() && !isExcluded(it) } ||
findClassifier(name, NoLookupLocation.FROM_IDE)?.let { it.isVisible() && !isExcluded(it) } ?: false
}
}
private fun KtNamedDeclaration.isConflicting(name: Name): Boolean {
if (this in excludedDeclarations) return false
if (nameAsName != name) return false
if (this is KtCallableDeclaration && receiverTypeReference != null) return false
return when (target) {
Target.VARIABLES -> this is KtVariableDeclaration || this is KtParameter
Target.FUNCTIONS_AND_CLASSES -> this is KtNamedFunction || this is KtClassOrObject || this is KtTypeAlias
}
}
}
| apache-2.0 | 3ae378685cc0326cf9d96a9879afe87a | 41.243478 | 158 | 0.717785 | 4.942014 | false | false | false | false |
craftsmenlabs/gareth-jvm | gareth-core/src/main/kotlin/org/craftsmenlabs/gareth/validator/services/ExperimentExecutor.kt | 1 | 1826 | package org.craftsmenlabs.gareth.validator.services
import org.craftsmenlabs.gareth.validator.client.GlueLineExecutor
import org.craftsmenlabs.gareth.validator.model.ExecutionStatus
import org.craftsmenlabs.gareth.validator.model.ExperimentDTO
import org.craftsmenlabs.gareth.validator.time.TimeService
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
@Service
class ExperimentExecutor @Autowired constructor(private val glueLineExecutor: GlueLineExecutor,
private val dateTimeService: TimeService) {
private val log = LoggerFactory.getLogger(ExperimentExecutor::class.java)
fun executeBaseline(experiment: ExperimentDTO): ExperimentDTO {
val result = glueLineExecutor.executeBaseline(experiment)
val now = dateTimeService.now()
log.info("Executed baseline. Result: " + result.status.name)
val mustAbort = result.status == ExecutionStatus.ERROR
return experiment.copy(status = result.status,
environment = result.environment,
completed = if (mustAbort) dateTimeService.now() else null,
baselineExecuted = if (mustAbort) null else now)
}
fun executeAssume(experiment: ExperimentDTO): ExperimentDTO {
if (experiment.status != ExecutionStatus.RUNNING)
throw IllegalStateException("Can only execute assume when experiment is in state RUNNING, but state is ${experiment.status.name}")
val result = glueLineExecutor.executeAssume(experiment)
val executed = experiment.copy(
completed = dateTimeService.now(),
status = result.status,
environment = result.environment)
return executed
}
}
| gpl-2.0 | df3b682d58fce0b9e73b65c8ef8dbc25 | 44.65 | 142 | 0.715772 | 5.044199 | false | false | false | false |
junerver/CloudNote | app/src/main/java/com/junerver/cloudnote/ui/activity/BaseActivity.kt | 1 | 3957 | package com.junerver.cloudnote.ui.activity
import android.R
import androidx.appcompat.app.AppCompatActivity
import android.app.ProgressDialog
import android.content.Context
import android.os.Bundle
import android.os.Build
import android.view.LayoutInflater
import android.widget.Toast
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.*
import java.lang.Exception
import java.lang.reflect.ParameterizedType
import kotlin.coroutines.CoroutineContext
/**
* Created by Junerver on 2016/8/31.
*/
abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity() , CoroutineScope by MainScope() {
protected lateinit var mContext: Context
private var mProgressDialog: ProgressDialog? = null
protected lateinit var viewBinding: VB
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mContext = this
initContentView()
initData()
initView()
setListeners()
mProgressDialog = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ProgressDialog(this, R.style.Theme_Material_Light_Dialog_Alert)
} else {
ProgressDialog(this, ProgressDialog.THEME_HOLO_LIGHT)
}
mProgressDialog!!.setMessage("请稍等...")
//注册事件总线
// EventBus.getDefault().register(this);
}
/**
* 如果使用绑定布局(layout包裹), 不能使用setContentView
* 否则会修改根布局view的默认tag, 不需要修改tag的请无视
* 使用ViewBinding自动绑定布局, 替代ButterKnife
*/
protected fun initContentView() {
initViewBinding("inflate", LayoutInflater::class.java, layoutInflater)
if (viewBinding != null) {
setContentView(viewBinding!!.root)
}
}
/**
* 反射初始化ViewBinding
* ActivityBaseBinding.inflate()
* ActivityBaseBinding.bind()
* 具体getActualTypeArguments取[0]还是[1]
* 取决于BaseActivity的泛型的第几位, 此方法为VB是[0]
*/
protected fun initViewBinding(name: String?, cls: Class<*>?, obj: Any?) {
val superclass = javaClass.genericSuperclass
if (superclass != null) {
val aClass = (superclass as ParameterizedType).actualTypeArguments[0] as Class<*>
try {
val method = aClass.getDeclaredMethod(name, cls)
method.isAccessible = true
viewBinding = method.invoke(null, obj) as VB
} catch (e: Exception) {
e.printStackTrace()
}
}
}
override fun onStop() {
super.onStop()
//注销事件总线
// EventBus.getDefault().unregister(this);
}
override fun onDestroy() {
super.onDestroy()
// 当 Activity 销毁的时候取消该 Scope 管理的 job。
// 这样在该 Scope 内创建的子 Coroutine 都会被自动的取消。
cancel()
}
/**
* @param msg toast的提示信息
*/
protected fun showShortToast(msg: String?) {
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show()
}
/**
* @param msg toast的提示信息
*/
protected fun showLongToast(msg: String?) {
Toast.makeText(this, msg, Toast.LENGTH_LONG).show()
}
/**
* 打开进度条dialog
*/
fun showProgress() {
if (mProgressDialog != null && !mProgressDialog!!.isShowing) {
mProgressDialog!!.show()
}
}
/**
* 关闭进度条dialog
*/
fun closeProgress() {
if (mProgressDialog != null && mProgressDialog!!.isShowing) {
mProgressDialog!!.dismiss()
}
}
/**
* 视图初始化
*/
protected abstract fun initView()
/**
* 数据初始化
*/
protected abstract fun initData()
/**
* 设置监听器
*/
protected abstract fun setListeners()
} | apache-2.0 | 3e26c21b85866589766d306a12c07f52 | 26.096296 | 101 | 0.619634 | 4.35876 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/fragments/inventory/stable/StableFragment.kt | 1 | 2549 | package com.habitrpg.android.habitica.ui.fragments.inventory.stable
import android.os.Bundle
import androidx.fragment.app.FragmentPagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.ui.fragments.BaseMainFragment
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.helpers.resetViews
class StableFragment : BaseMainFragment() {
private val viewPager: androidx.viewpager.widget.ViewPager? by bindView(R.id.viewPager)
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
this.usesTabLayout = true
this.hidesToolbar = true
super.onCreateView(inflater, container, savedInstanceState)
return inflater.inflate(R.layout.fragment_viewpager, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
resetViews()
viewPager?.currentItem = 0
setViewPagerAdapter()
}
override fun injectFragment(component: UserComponent) {
component.inject(this)
}
private fun setViewPagerAdapter() {
val fragmentManager = childFragmentManager
viewPager?.adapter = object : FragmentPagerAdapter(fragmentManager) {
override fun getItem(position: Int): androidx.fragment.app.Fragment {
val fragment = StableRecyclerFragment()
when (position) {
0 -> {
fragment.itemType = "pets"
}
1 -> {
fragment.itemType = "mounts"
}
}
fragment.user = [email protected]
fragment.itemTypeText = this.getPageTitle(position).toString()
return fragment
}
override fun getCount(): Int {
return 2
}
override fun getPageTitle(position: Int): CharSequence {
return when (position) {
0 -> activity?.getString(R.string.pets)
1 -> activity?.getString(R.string.mounts)
else -> ""
} ?: ""
}
}
tabLayout?.setupWithViewPager(viewPager)
}
}
| gpl-3.0 | f2c3d5294573bea897ab0b7dcb3d488f | 31.679487 | 91 | 0.617889 | 5.343816 | false | false | false | false |
Flank/flank | common/src/main/kotlin/flank/common/Os.kt | 1 | 349 | package flank.common
private val osName = System.getProperty("os.name")?.lowercase() ?: ""
val isMacOS: Boolean by lazy {
val isMacOS = osName.indexOf("mac") >= 0
logLn("isMacOS = $isMacOS ($osName)")
isMacOS
}
val isWindows: Boolean by lazy {
osName.indexOf("win") >= 0
}
val isLinux: Boolean
get() = !isWindows && !isMacOS
| apache-2.0 | c4d78787f13fa1f5a559d431808fdfa7 | 20.8125 | 69 | 0.647564 | 3.49 | false | false | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/adapter/social/ChallengesListViewAdapter.kt | 1 | 5290 | package com.habitrpg.android.habitica.ui.adapter.social
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.social.Challenge
import com.habitrpg.android.habitica.models.social.ChallengeMembership
import com.habitrpg.android.habitica.ui.fragments.social.challenges.ChallengeFilterOptions
import com.habitrpg.android.habitica.ui.helpers.bindView
import com.habitrpg.android.habitica.ui.views.HabiticaEmojiTextView
import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper
import io.reactivex.BackpressureStrategy
import io.reactivex.Flowable
import io.reactivex.subjects.PublishSubject
import io.realm.OrderedRealmCollection
import io.realm.RealmRecyclerViewAdapter
import net.pherth.android.emoji_library.EmojiParser
class ChallengesListViewAdapter(data: OrderedRealmCollection<Challenge>?, autoUpdate: Boolean, private val viewUserChallengesOnly: Boolean, private val userId: String) : RealmRecyclerViewAdapter<Challenge, ChallengesListViewAdapter.ChallengeViewHolder>(data, autoUpdate) {
private var unfilteredData: OrderedRealmCollection<Challenge>? = null
var challengeMemberships: OrderedRealmCollection<ChallengeMembership>? = null
private val openChallengeFragmentEvents = PublishSubject.create<String>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ChallengeViewHolder {
return ChallengeViewHolder(parent.inflate(R.layout.challenge_item), viewUserChallengesOnly)
}
override fun onBindViewHolder(holder: ChallengeViewHolder, position: Int) {
data?.get(position)?.let { challenge ->
holder.bind(challenge, challengeMemberships?.first { challenge.id == it.challengeID } != null)
holder.itemView.setOnClickListener {
if (challenge.isManaged && challenge.isValid) {
challenge.id?.let {
openChallengeFragmentEvents.onNext(it)
}
}
}
}
}
fun updateUnfilteredData(data: OrderedRealmCollection<Challenge>?) {
super.updateData(data)
unfilteredData = data
}
fun filter(filterOptions: ChallengeFilterOptions) {
if (unfilteredData == null) {
return
}
var query = unfilteredData?.where()
if (filterOptions.showByGroups != null && filterOptions.showByGroups.size > 0) {
val groupIds = arrayOfNulls<String>(filterOptions.showByGroups.size)
var index = 0
for (group in filterOptions.showByGroups) {
groupIds[index] = group.id
index += 1
}
query = query?.`in`("groupId", groupIds)
}
if (filterOptions.showOwned != filterOptions.notOwned) {
query = if (filterOptions.showOwned) {
query?.equalTo("leaderId", userId)
} else {
query?.notEqualTo("leaderId", userId)
}
}
query?.let {
this.updateData(it.findAll())
}
}
fun getOpenDetailFragmentFlowable(): Flowable<String> {
return openChallengeFragmentEvents.toFlowable(BackpressureStrategy.DROP)
}
class ChallengeViewHolder internal constructor(itemView: View, private val viewUserChallengesOnly: Boolean) : RecyclerView.ViewHolder(itemView) {
private val challengeName: HabiticaEmojiTextView by bindView(R.id.challenge_name)
private val challengeDescription: TextView by bindView(R.id.challenge_shorttext)
private val participantCount: TextView by bindView(R.id.participantCount)
private val officialChallengeLayout: TextView by bindView(R.id.official_challenge_view)
private val challengeParticipatingTextView: View by bindView(R.id.is_joined_label)
private val gemPrizeTextView: TextView by bindView(R.id.gemPrizeTextView)
private val gemIconView: ImageView by bindView(R.id.gem_icon)
private var challenge: Challenge? = null
init {
gemIconView.setImageBitmap(HabiticaIconsHelper.imageOfGem())
if (!viewUserChallengesOnly) {
challengeName.setTextColor(ContextCompat.getColor(itemView.context, R.color.brand_200))
}
}
fun bind(challenge: Challenge, isParticipating: Boolean) {
this.challenge = challenge
challengeName.text = EmojiParser.parseEmojis(challenge.name?.trim { it <= ' ' })
challengeDescription.text = challenge.summary
officialChallengeLayout.visibility = if (challenge.official) View.VISIBLE else View.GONE
if (viewUserChallengesOnly) {
challengeParticipatingTextView.visibility = View.GONE
} else {
challengeParticipatingTextView.visibility = if (isParticipating) View.VISIBLE else View.GONE
}
participantCount.text = challenge.memberCount.toString()
gemPrizeTextView.text = challenge.prize.toString()
}
}
}
| gpl-3.0 | 1312e5423759622b5b8e0fbf387d56a0 | 41.66129 | 272 | 0.699244 | 4.962477 | false | false | false | false |
Flank/flank | integration_tests/src/test/kotlin/integration/IgnoreFailedIT.kt | 1 | 1685 | package integration
import FlankCommand
import com.google.common.truth.Truth.assertThat
import integration.config.AndroidTest
import org.junit.Test
import org.junit.experimental.categories.Category
import run
import utils.CONFIGS_PATH
import utils.FLANK_JAR_PATH
import utils.androidRunCommands
import utils.asOutputReport
import utils.assertCostMatches
import utils.assertExitCode
import utils.assertTestCountMatches
import utils.findTestDirectoryFromOutput
import utils.firstTestSuiteOverview
import utils.json
import utils.removeUnicode
import utils.toOutputReportFile
class IgnoreFailedIT {
private val name = this::class.java.simpleName
@Category(AndroidTest::class)
@Test
fun `return with exit code 0 for failed tests`() {
val result = FlankCommand(
flankPath = FLANK_JAR_PATH,
ymlPath = "$CONFIGS_PATH/flank_android_ignore_failed.yml",
params = androidRunCommands
).run(
workingDirectory = "./",
testSuite = name
)
assertExitCode(result, 0)
val resOutput = result.output.removeUnicode()
val outputReport = resOutput.findTestDirectoryFromOutput().toOutputReportFile().json().asOutputReport()
assertThat(outputReport.error).isEmpty()
assertThat(outputReport.cost).isNotNull()
outputReport.assertCostMatches()
assertThat(outputReport.testResults.count()).isEqualTo(1)
assertThat(outputReport.weblinks.count()).isEqualTo(1)
val testSuiteOverview = outputReport.firstTestSuiteOverview
testSuiteOverview.assertTestCountMatches(
total = 1,
failures = 1
)
}
}
| apache-2.0 | 6144eafb3a8f31213e996da34aead3be | 28.561404 | 111 | 0.719881 | 4.603825 | false | true | false | false |
firebase/firebase-android-sdk | encoders/protoc-gen-firebase-encoders/src/main/kotlin/com/google/firebase/encoders/proto/codegen/Parsing.kt | 1 | 6237 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.firebase.encoders.proto.codegen
import com.google.common.collect.ImmutableListMultimap
import com.google.common.collect.ImmutableMultimap
import com.google.firebase.encoders.proto.CodeGenConfig
import com.google.firebase.encoders.proto.codegen.UserDefined.Message
import com.google.firebase.encoders.proto.codegen.UserDefined.ProtoEnum
import com.google.protobuf.DescriptorProtos
import com.google.protobuf.DescriptorProtos.FieldDescriptorProto
import com.google.protobuf.DescriptorProtos.FileDescriptorProto
import dagger.Binds
import dagger.Module
import javax.inject.Inject
/** Transforms the protobuf message descriptors into a message graph for later use in codegen. */
interface DescriptorParser {
fun parse(protoFiles: List<FileDescriptorProto>): Collection<UserDefined>
}
/**
* Default [DescriptorParser] implementation.
*
* The parser repackages all input messages into the `vendorPackage` of the provided [config].
* Additionally it only returns messages that are marked for inclusion in [config].
*
* Any extensions that are encountered are added directly to extended messages as fields, so
* extensions are indistinguishable from message's own fields.
*/
class DefaultParser @Inject constructor(private val config: CodeGenConfig) : DescriptorParser {
override fun parse(files: List<FileDescriptorProto>): List<UserDefined> {
val parsedTypes =
files
.asSequence()
.flatMap { file ->
val javaPackage = "${config.vendorPackage}.${file.`package`}"
val parent = Owner.Package(file.`package`, javaPackage, file.name)
parseEnums(parent, file.enumTypeList).plus(parseMessages(parent, file.messageTypeList))
}
.toList()
val extensions = discoverExtensions(files)
for (type in parsedTypes) {
val msgExtensions = extensions[type.protobufFullName]
if (type !is Message || msgExtensions == null) {
continue
}
type.addFields(msgExtensions)
}
resolveReferences(parsedTypes)
return parsedTypes.filter { config.includeList.contains(it.protobufFullName) }
}
private fun resolveReferences(types: Collection<UserDefined>) {
val messageIndex = types.asSequence().map { it.protobufFullName to it }.toMap()
for (userDefined in types) {
if (userDefined !is Message) {
continue
}
for (field in userDefined.fields) {
(field.type as? Unresolved)?.run {
field.type =
messageIndex[this.protobufName]
?: throw IllegalArgumentException(
"Unresolved reference to $protobufName in ${userDefined.protobufFullName}."
)
}
}
}
}
private fun discoverExtensions(
files: List<FileDescriptorProto>
): ImmutableMultimap<String, ProtoField> {
val extensions: ImmutableListMultimap.Builder<String, ProtoField> =
ImmutableListMultimap.builder<String, ProtoField>()
for (file in files) {
for (field in file.extensionList) {
extensions.put(
field.extendee.trimStart('.'),
ProtoField(
field.name,
field.determineType(),
field.number,
field.label == FieldDescriptorProto.Label.LABEL_REPEATED
)
)
}
}
return extensions.build()
}
private fun parseEnums(
parent: Owner,
enums: List<DescriptorProtos.EnumDescriptorProto>
): Sequence<ProtoEnum> {
return enums.asSequence().map { enum ->
ProtoEnum(parent, enum.name, enum.valueList.map { ProtoEnum.Value(it.name, it.number) })
}
}
private fun parseMessages(
parent: Owner,
messages: List<DescriptorProtos.DescriptorProto>
): Sequence<UserDefined> {
return messages.asSequence().flatMap { msg ->
val m =
Message(
owner = parent,
name = msg.name,
fields =
msg.fieldList.map {
ProtoField(
name = it.name,
type = it.determineType(),
number = it.number,
repeated = it.label == FieldDescriptorProto.Label.LABEL_REPEATED
)
}
)
val newParent = Owner.MsgRef(m)
sequenceOf(m)
.plus(parseEnums(newParent, msg.enumTypeList))
.plus(parseMessages(newParent, msg.nestedTypeList))
}
}
}
private fun FieldDescriptorProto.determineType(): ProtobufType {
if (typeName != "") {
return Unresolved(typeName.trimStart('.'))
}
return when (type) {
FieldDescriptorProto.Type.TYPE_INT32 -> Primitive.INT32
FieldDescriptorProto.Type.TYPE_DOUBLE -> Primitive.DOUBLE
FieldDescriptorProto.Type.TYPE_FLOAT -> Primitive.FLOAT
FieldDescriptorProto.Type.TYPE_INT64 -> Primitive.INT64
FieldDescriptorProto.Type.TYPE_UINT64 -> Primitive.INT64
FieldDescriptorProto.Type.TYPE_FIXED64 -> Primitive.FIXED64
FieldDescriptorProto.Type.TYPE_FIXED32 -> Primitive.FIXED32
FieldDescriptorProto.Type.TYPE_BOOL -> Primitive.BOOLEAN
FieldDescriptorProto.Type.TYPE_STRING -> Primitive.STRING
FieldDescriptorProto.Type.TYPE_BYTES -> Primitive.BYTES
FieldDescriptorProto.Type.TYPE_UINT32 -> Primitive.INT32
FieldDescriptorProto.Type.TYPE_SFIXED32 -> Primitive.SFIXED32
FieldDescriptorProto.Type.TYPE_SFIXED64 -> Primitive.SFIXED64
FieldDescriptorProto.Type.TYPE_SINT32 -> Primitive.SINT32
FieldDescriptorProto.Type.TYPE_SINT64 -> Primitive.SINT64
else -> throw IllegalArgumentException("$type is not supported")
}
}
@Module
abstract class ParsingModule {
@Binds abstract fun bindParser(parser: DefaultParser): DescriptorParser
}
| apache-2.0 | e4190f2e4a438959092bbb776fa66e0b | 34.844828 | 97 | 0.698413 | 4.506503 | false | false | false | false |
devjn/GithubSearch | common/src/main/kotlin/com/github/devjn/githubsearch/utils/Utils.kt | 1 | 3290 | package com.github.devjn.githubsearch.utils
import java.text.SimpleDateFormat
import java.util.*
import com.github.devjn.githubsearch.model.db.DataBaseField
import com.github.devjn.githubsearch.database.ISQLiteContentValues
import com.github.devjn.githubsearch.database.ISQLiteCursor
import com.github.devjn.githubsearch.database.ISQLiteDatabase
/**
* Created by @author Jahongir on 30-Apr-17
* [email protected]
* Utils
*/
object Utils {
val TAG = Utils::class.java.simpleName
fun <T : Any, R : Any> whenAllNotNull(vararg options: T?, block: (List<T>) -> R) {
if (options.all { it != null }) {
block(options.filterNotNull())
}
}
fun <T : Any, R : Any> whenAnyNotNull(vararg options: T?, block: (List<T>) -> R) {
if (options.any { it != null }) {
block(options.filterNotNull())
}
}
fun getDateStringInDateFormat(date: Date): String {
val format = SimpleDateFormat("EEEE, MM/dd/yy kk:mm")
return format.format(date)
}
fun getDateStringInTimeFormat(date: Date): String {
val format = SimpleDateFormat("kk:mm")
return format.format(date)
}
fun executeSQLStatement(db: ISQLiteDatabase?, statement: String) {
db!!.execSQL(statement)
}
fun createTableSQL(tableName: String, fields: Array<DataBaseField?>): String {
var statement = "CREATE TABLE IF NOT EXISTS $tableName("
for (i in fields.indices) {
statement += fields[i]!!.fieldName + " " + fields[i]!!.fieldType
if (fields[i]!!.isPrimaryKey) {
statement += " PRIMARY KEY"
}
if (fields[i]!!.isAutoIncrement) {
statement += " AUTOINCREMENT"
}
if (fields[i]!!.isNotNull) {
statement += " NOT NULL"
}
if (i != fields.size - 1) {
statement += ", "
}
}
statement += ");"
return statement
}
fun createClauseWhereFieldEqualsValue(field: DataBaseField, value: Any): String {
val clause = field.fieldName + "=" + value
return clause
}
fun dropTableIfExistsSQL(tableName: String): String {
val statement = "DROP TABLE IF EXISTS $tableName;"
return statement
}
fun insertObject(db: ISQLiteDatabase, tableName: String, values: ISQLiteContentValues) {
db.insert(tableName, null, values)
}
fun deleteObject(db: ISQLiteDatabase, tableName: String, whereClause: String) {
db.delete(tableName, whereClause, null)
}
fun clearObjects(db: ISQLiteDatabase, tableName: String) {
db.delete(tableName, null, null)
}
fun getAllObjects(db: ISQLiteDatabase, tableName: String, fields: Array<DataBaseField>): ISQLiteCursor? {
return getAllObjectsOrderedByParam(db, tableName, fields, null)
}
fun getAllObjectsOrderedByParam(db: ISQLiteDatabase, tableName: String, fields: Array<DataBaseField>, orderedBy: String?): ISQLiteCursor? {
val fieldNames = arrayOfNulls<String>(fields.size)
for (i in fields.indices) {
fieldNames[i] = fields[i].fieldName
}
return db.query(tableName, fieldNames, null, null, null, null, orderedBy)
}
} | apache-2.0 | 17c75582b4b8789b90b91239e5910568 | 31.584158 | 143 | 0.6231 | 4.107366 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/codegen/src/com/intellij/workspaceModel/codegen/model/KtAnnotations.kt | 2 | 1394 | // 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.codegen.deft.model
import com.intellij.workspaceModel.deft.api.annotations.Default
import org.jetbrains.deft.annotations.Abstract
import org.jetbrains.deft.annotations.Open
import kotlin.reflect.KClass
class KtAnnotations {
val list = mutableListOf<KtAnnotation>()
val byName by lazy {
list.associateBy { it.name.text }
}
override fun toString(): String = list.joinToString()
val flags by lazy {
val result = Flags()
list.forEach {
when (it.name.text) {
Open::class.java.simpleName -> result.open = true
Abstract::class.java.simpleName -> result.abstract = true
Default::class.java.simpleName -> result.default = true
}
}
result
}
operator fun get(name: String): List<String>? =
byName[name]?.args?.map { it.text.removeSurrounding("\"") }
operator fun get(c: Class<*>): List<String>? = get(c.simpleName)
data class Flags(
var content: Boolean = false,
var open: Boolean = false,
var abstract: Boolean = false,
var sealed: Boolean = false,
var relation: Boolean = false,
var default: Boolean = false,
)
}
operator fun KtAnnotations?.contains(kClass: KClass<*>): Boolean {
return this != null && kClass.simpleName in byName
} | apache-2.0 | a398c28453d4123054b4e2846142fd00 | 29.326087 | 120 | 0.69297 | 4.04058 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/RemoveUnusedValueFix.kt | 1 | 4018 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.daemon.QuickFixBundle
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import org.jetbrains.kotlin.cfg.pseudocode.getContainingPseudocode
import org.jetbrains.kotlin.cfg.pseudocode.sideEffectFree
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class RemoveUnusedValueFix(expression: KtBinaryExpression) : KotlinQuickFixAction<KtBinaryExpression>(expression) {
enum class RemoveMode {
REMOVE_ALL, KEEP_INITIALIZE, CANCEL
}
private fun showDialog(variable: KtProperty, project: Project, element: KtBinaryExpression, rhs: KtExpression) {
if (isUnitTestMode()) return doRemove(RemoveMode.KEEP_INITIALIZE, element, rhs)
val message = "<html><body>${KotlinBundle.message(
"there.are.possible.side.effects.found.in.expressions.assigned.to.the.variable.0",
variable.name.toString()
)}</body></html>"
ApplicationManager.getApplication().invokeLater {
val exitCode = Messages.showYesNoCancelDialog(
variable.project,
message,
QuickFixBundle.message("side.effects.warning.dialog.title"),
QuickFixBundle.message("side.effect.action.remove"),
QuickFixBundle.message("side.effect.action.transform"),
QuickFixBundle.message("side.effect.action.cancel"),
Messages.getWarningIcon()
)
WriteCommandAction.runWriteCommandAction(project) {
doRemove(RemoveMode.values()[exitCode], element, rhs)
}
}
}
override fun getFamilyName() = KotlinBundle.message("remove.redundant.assignment")
override fun getText() = familyName
private fun doRemove(mode: RemoveMode, element: KtBinaryExpression, rhs: KtExpression) {
when (mode) {
RemoveMode.REMOVE_ALL -> element.delete()
RemoveMode.KEEP_INITIALIZE -> element.replace(rhs)
else -> {
}
}
}
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val lhs = element.left as? KtSimpleNameExpression ?: return
val rhs = element.right ?: return
val variable = lhs.mainReference.resolve() as? KtProperty ?: return
val pseudocode = rhs.getContainingPseudocode(element.analyze(BodyResolveMode.PARTIAL))
val isSideEffectFree = pseudocode?.getElementValue(rhs)?.createdAt?.sideEffectFree ?: false
if (!isSideEffectFree) {
showDialog(variable, project, element, rhs)
} else {
doRemove(RemoveMode.REMOVE_ALL, element, rhs)
}
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val expression = Errors.UNUSED_VALUE.cast(diagnostic).psiElement
if (!KtPsiUtil.isAssignment(expression)) return null
if (expression.left !is KtSimpleNameExpression) return null
return RemoveUnusedValueFix(expression)
}
}
} | apache-2.0 | d898cdcbff0ee75891946ebddee0fec4 | 44.157303 | 158 | 0.709806 | 4.882139 | false | false | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateInfo.kt | 1 | 4612 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.updateSettings.impl
import com.intellij.openapi.application.impl.ApplicationInfoImpl
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.BuildNumber
import com.intellij.openapi.util.BuildRange
import com.intellij.openapi.util.SystemInfo
import org.jdom.Element
import org.jdom.JDOMException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
class UpdatesInfo(node: Element) {
private val products = node.getChildren("product").map(::Product)
operator fun get(code: String): Product? = products.find { code in it.codes }
}
class Product internal constructor(node: Element) {
val name: String = node.getMandatoryAttributeValue("name")
val codes: Set<String> = node.getChildren("code").map { it.value.trim() }.toSet()
val channels: List<UpdateChannel> = node.getChildren("channel").map(::UpdateChannel)
override fun toString(): String = codes.firstOrNull() ?: "-"
}
class UpdateChannel internal constructor(node: Element) {
companion object {
const val LICENSING_EAP: String = "eap"
const val LICENSING_RELEASE: String = "release"
}
val id: String = node.getMandatoryAttributeValue("id")
val status: ChannelStatus = ChannelStatus.fromCode(node.getAttributeValue("status"))
val licensing: String = node.getAttributeValue("licensing", LICENSING_RELEASE)
val evalDays: Int = node.getAttributeValue("evalDays")?.toInt() ?: 30
val url: String? = node.getAttributeValue("url")
val builds: List<BuildInfo> = node.getChildren("build").map(::BuildInfo)
override fun toString(): String = id
}
class BuildInfo internal constructor(node: Element) {
val number: BuildNumber = parseBuildNumber(node.getMandatoryAttributeValue("fullNumber", "number"))
val apiVersion: BuildNumber = BuildNumber.fromStringWithProductCode(node.getAttributeValue("apiVersion"), number.productCode) ?: number
val version: String = node.getAttributeValue("version") ?: ""
val message: String = node.getChild("message")?.value ?: ""
val blogPost: String? = node.getChild("blogPost")?.getAttributeValue("url")
val releaseDate: Date? = parseDate(node.getAttributeValue("releaseDate"))
val target: BuildRange? = BuildRange.fromStrings(node.getAttributeValue("targetSince"), node.getAttributeValue("targetUntil"))
val buttons: List<ButtonInfo> = node.getChildren("button").map(::ButtonInfo)
val patches: List<PatchInfo> = node.getChildren("patch").map(::PatchInfo)
private fun parseBuildNumber(value: String): BuildNumber {
var buildNumber = BuildNumber.fromString(value)
if (buildNumber.productCode.isEmpty()) {
buildNumber = BuildNumber(ApplicationInfoImpl.getShadowInstance().build.productCode, *buildNumber.components)
}
return buildNumber
}
private fun parseDate(value: String?): Date? =
if (value == null) null
else try {
SimpleDateFormat("yyyyMMdd", Locale.US).parse(value) // same as the 'majorReleaseDate' in ApplicationInfo.xml
}
catch (e: ParseException) {
Logger.getInstance(BuildInfo::class.java).info("invalid build release date: ${value}")
null
}
val downloadUrl: String?
get() = buttons.find(ButtonInfo::isDownload)?.url
override fun toString(): String = "${number}/${version}"
}
class ButtonInfo internal constructor(node: Element) {
val name: String = node.getMandatoryAttributeValue("name")
val url: String = node.getMandatoryAttributeValue("url")
val isDownload: Boolean = node.getAttributeValue("download") != null // a button marked with this attribute is hidden when a patch is available
override fun toString(): String = name
}
class PatchInfo internal constructor(node: Element) {
companion object {
val OS_SUFFIX = if (SystemInfo.isWindows) "win" else if (SystemInfo.isMac) "mac" else if (SystemInfo.isUnix) "unix" else "unknown"
}
val fromBuild: BuildNumber = BuildNumber.fromString(node.getMandatoryAttributeValue("fullFrom", "from"))
val size: String? = node.getAttributeValue("size")
val isAvailable: Boolean = node.getAttributeValue("exclusions")?.splitToSequence(",")?.none { it.trim() == OS_SUFFIX } ?: true
}
private fun Element.getMandatoryAttributeValue(attribute: String) =
getAttributeValue(attribute) ?: throw JDOMException("${name}@${attribute} missing")
private fun Element.getMandatoryAttributeValue(attribute: String, fallback: String) =
getAttributeValue(attribute) ?: getMandatoryAttributeValue(fallback) | apache-2.0 | 78b5ebd155b2926ff64b90afceceac8e | 44.673267 | 146 | 0.74935 | 4.417625 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/wizard/ui/setting/DefaultSettingComponent.kt | 1 | 6830 | // 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.tools.projectWizard.wizard.ui.setting
import com.intellij.openapi.ui.ComboBox
import org.jetbrains.kotlin.tools.projectWizard.core.Context
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settingValidator
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.*
import org.jetbrains.kotlin.tools.projectWizard.settings.DisplayableSettingItem
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components.CheckboxComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components.DropDownComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components.PathFieldComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.components.TextFieldComponent
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.label
import org.jetbrains.kotlin.tools.projectWizard.wizard.ui.customPanel
import java.awt.BorderLayout
import java.awt.event.ItemEvent
import java.nio.file.Path
import javax.swing.DefaultComboBoxModel
import javax.swing.JComponent
object DefaultSettingComponent {
@Suppress("UNCHECKED_CAST")
fun <V : Any, T : SettingType<V>> create(
setting: SettingReference<V, T>,
context: Context,
needLabel: Boolean = true
): SettingComponent<V, T> = when (setting.type) {
VersionSettingType::class ->
VersionSettingComponent(
setting as SettingReference<Version, VersionSettingType>,
context
) as SettingComponent<V, T>
BooleanSettingType::class ->
BooleanSettingComponent(
setting as SettingReference<Boolean, BooleanSettingType>,
context,
needLabel
) as SettingComponent<V, T>
DropDownSettingType::class ->
DropdownSettingComponent(
setting as SettingReference<DisplayableSettingItem, DropDownSettingType<DisplayableSettingItem>>,
context,
needLabel
) as SettingComponent<V, T>
StringSettingType::class ->
StringSettingComponent(
setting as SettingReference<String, StringSettingType>,
context,
needLabel
) as SettingComponent<V, T>
PathSettingType::class ->
PathSettingComponent(
setting as SettingReference<Path, PathSettingType>,
context,
needLabel
) as SettingComponent<V, T>
else -> TODO(setting.type.qualifiedName!!)
}
}
fun <V : Any, T : SettingType<V>> SettingReference<V, T>.createSettingComponent(context: Context) =
DefaultSettingComponent.create(this, context, needLabel = false)
class VersionSettingComponent(
reference: SettingReference<Version, VersionSettingType>,
context: Context
) : SettingComponent<Version, VersionSettingType>(reference, context) {
private val settingLabel = label(setting.title)
private val comboBox = ComboBox<Version>().apply {
addItemListener { e ->
if (e?.stateChange == ItemEvent.SELECTED) {
value = e.item as Version
}
}
}
override fun onInit() {
super.onInit()
val values = read { reference.savedOrDefaultValue }?.let(::listOf).orEmpty()
comboBox.model = DefaultComboBoxModel<Version>(values.toTypedArray())
if (values.isNotEmpty()) {
value = values.first()
}
}
override val validationIndicator = null
override val component: JComponent by lazy(LazyThreadSafetyMode.NONE) {
customPanel {
add(
customPanel {
add(settingLabel, BorderLayout.CENTER)
},
BorderLayout.WEST
)
add(comboBox, BorderLayout.CENTER)
}
}
}
class DropdownSettingComponent(
reference: SettingReference<DisplayableSettingItem, DropDownSettingType<DisplayableSettingItem>>,
context: Context,
needLabel: Boolean = true
) : UIComponentDelegatingSettingComponent<DisplayableSettingItem, DropDownSettingType<DisplayableSettingItem>>(
reference,
context
) {
override val uiComponent = DropDownComponent(
context = context,
initialValues = setting.type.values,
description = setting.description,
validator = setting.validator,
filter = { value ->
context.read { setting.type.filter(this, reference, value) }
},
labelText = setting.title.takeIf { needLabel },
onValueUpdate = handleValueUpdate()
).asSubComponent()
override fun shouldBeShow(): Boolean =
uiComponent.valuesCount > 1
}
class BooleanSettingComponent(
reference: SettingReference<Boolean, BooleanSettingType>,
context: Context,
needLabel: Boolean = true
) : UIComponentDelegatingSettingComponent<Boolean, BooleanSettingType>(
reference,
context
) {
override val title: String? = null
override val uiComponent = CheckboxComponent(
context = context,
labelText = setting.title,
description = setting.description,
initialValue = null,
validator = setting.validator,
onValueUpdate = handleValueUpdate()
).asSubComponent()
}
class StringSettingComponent(
reference: SettingReference<String, StringSettingType>,
context: Context,
needLabel: Boolean = true
) : UIComponentDelegatingSettingComponent<String, StringSettingType>(
reference,
context
) {
override val uiComponent = TextFieldComponent(
context = context,
initialValue = null,
description = setting.description,
labelText = setting.title.takeIf { needLabel },
validator = setting.validator,
onValueUpdate = handleValueUpdate()
).asSubComponent()
fun onUserType(action: () -> Unit) {
uiComponent.onUserType(action)
}
}
class PathSettingComponent(
reference: SettingReference<Path, PathSettingType>,
context: Context,
needLabel: Boolean = true
) : UIComponentDelegatingSettingComponent<Path, PathSettingType>(
reference,
context
) {
override val uiComponent = PathFieldComponent(
context = context,
description = setting.description,
labelText = setting.title.takeIf { needLabel },
validator = settingValidator { path -> setting.validator.validate(this, path) },
onValueUpdate = handleValueUpdate()
).asSubComponent()
fun onUserType(action: () -> Unit) {
uiComponent.onUserType(action)
}
} | apache-2.0 | c9451278f5704ae846d44b93c6f46235 | 35.142857 | 158 | 0.680527 | 4.945692 | false | false | false | false |
jwren/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/DataStatus.kt | 4 | 497 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
internal data class DataStatus(
val isSearching: Boolean = false,
val isRefreshingData: Boolean = false,
val isExecutingOperations: Boolean = false
) {
val isBusy = isRefreshingData || isSearching || isExecutingOperations
override fun toString() = "DataStatus(isBusy=$isBusy " +
"[isSearching=$isSearching, isRefreshingData=$isRefreshingData, isExecutingOperations=$isExecutingOperations])"
}
| apache-2.0 | 169684c28ca103764b0535e19e585b36 | 37.230769 | 119 | 0.760563 | 4.872549 | false | false | false | false |
BijoySingh/Quick-Note-Android | base/src/main/java/com/maubis/scarlet/base/note/folder/SelectorFolderRecyclerItem.kt | 1 | 959 | package com.maubis.scarlet.base.note.folder
import android.content.Context
import androidx.core.content.ContextCompat
import com.maubis.scarlet.base.R
import com.maubis.scarlet.base.config.ApplicationBase.Companion.sAppTheme
import com.maubis.scarlet.base.database.room.folder.Folder
import com.maubis.scarlet.base.support.recycler.RecyclerItem
import com.maubis.scarlet.base.support.ui.ColorUtil
import com.maubis.scarlet.base.support.ui.ThemeColorType
class SelectorFolderRecyclerItem(context: Context, val folder: Folder) : RecyclerItem() {
val isLightShaded = ColorUtil.isLightColored(folder.color)
val title = folder.title
val titleColor = sAppTheme.get(ThemeColorType.TERTIARY_TEXT)
val folderColor = folder.color
val iconColor = when (isLightShaded) {
true -> ContextCompat.getColor(context, R.color.dark_secondary_text)
false -> ContextCompat.getColor(context, R.color.light_primary_text)
}
override val type = Type.FOLDER
}
| gpl-3.0 | d87b76685f3164b941657e18814b6f94 | 38.958333 | 89 | 0.803962 | 3.805556 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/tests/testData/parameterInfo/functionCall/NamedParameter4.kt | 3 | 365 | // IGNORE_FIR
open class A(x: Int) {
fun m(a: String = "a", b: String = "b", c: String = "c", d: String = "d") = 1
fun d(x: Int) {
m(b = "x", d = "x", <caret>)
}
}
/*
Text: (<disabled>[b: String = "b"], [d: String = "d"],</disabled><highlight> </highlight>[a: String = "a"], [c: String = "c"]), Disabled: false, Strikeout: false, Green: true
*/ | apache-2.0 | 17dc0d2acfc907d5359b77c338556c14 | 32.272727 | 174 | 0.50411 | 2.683824 | false | false | false | false |
dowenliu-xyz/ketcd | ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/resolver/SimpleEtcdNameResolverFactory.kt | 1 | 1285 | package xyz.dowenliu.ketcd.resolver
import io.grpc.Attributes
import io.grpc.NameResolver
import io.grpc.internal.GrpcUtil
import java.net.URI
/**
* A custom name resolver factory which creates etcd name resolver.
*
* create at 2017/4/8
* @author liufl
* @since 3.1.0
*
* @property uris Pre-configured known Etcd endpoint URIs.
*/
class SimpleEtcdNameResolverFactory(private val uris: List<URI>) : AbstractEtcdNameResolverFactory() {
/**
* Companion object of [SimpleEtcdNameResolverFactory]
*/
companion object {
private const val SCHEME = "etcd"
private const val NAME = "simple"
}
override fun newNameResolver(targetUri: URI?, params: Attributes?): NameResolver? {
val _targetUri = requireNotNull(targetUri)
if (SCHEME != _targetUri.scheme) return null
val targetPath = checkNotNull(_targetUri.path, { "targetPath is null" })
check(targetPath.startsWith("/"),
{ "the path component ($targetPath) of the target ($_targetUri) must start with '/'" })
val name = targetPath.substring(1)
return SimpleEtcdNameResolver(name, GrpcUtil.SHARED_CHANNEL_EXECUTOR, this.uris)
}
override fun getDefaultScheme(): String = SCHEME
override fun name(): String = NAME
} | apache-2.0 | 1f64854d2c502b8ee9abf652fc327d2a | 31.974359 | 103 | 0.68716 | 4.145161 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/rename/automaticRenamer/before/main.kt | 14 | 662 | open class Foo : Throwable()
val foo: Foo = Foo()
val foo1: Foo = Foo()
val foos: List<Foo> = listOf()
val foos1: Array<Foo> = array()
fun main(args: Array<String>) {
val foo: Foo = Foo()
val someVerySpecialFoo: Foo = Foo()
val fooAnother: Foo = Foo()
val anonymous = object : Foo() {
}
val (foo1: Foo, foos: List<Foo>) = Pair(Foo(), listOf<Foo>())
try {
for (foo2: Foo in listOf<Foo>()) {
}
} catch (foo: Foo) {
}
fun local(foo: Foo) {
}
}
fun topLevel(foo: Foo) {
}
fun collectionLikes(foos: List<Array<Foo>>, foos: List<Map<Foo, Foo>>) {
}
class FooImpl : Foo()
object FooObj : Foo() | apache-2.0 | 5196b36b2fafcdb23a204ba8d2c56af6 | 14.785714 | 72 | 0.561934 | 2.942222 | false | false | false | false |
mickele/DBFlow | dbflow-processor/src/main/java/com/raizlabs/android/dbflow/processor/utils/ElementUtility.kt | 1 | 2790 | package com.raizlabs.android.dbflow.processor.utils
import com.raizlabs.android.dbflow.annotation.ColumnIgnore
import com.raizlabs.android.dbflow.processor.ClassNames
import com.raizlabs.android.dbflow.processor.ProcessorManager
import com.squareup.javapoet.ClassName
import java.util.*
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeMirror
/**
* Description:
*/
object ElementUtility {
/**
* @return real full-set of elements, including ones from super-class.
*/
fun getAllElements(element: TypeElement, manager: ProcessorManager): List<Element> {
val elements = ArrayList(manager.elements.getAllMembers(element))
var superMirror: TypeMirror? = null
var typeElement: TypeElement? = element
while (typeElement?.superclass.let { superMirror = it; it != null }) {
typeElement = manager.typeUtils.asElement(superMirror) as TypeElement?
typeElement?.let {
val superElements = manager.elements.getAllMembers(typeElement)
superElements.forEach { if (!elements.contains(it)) elements += it }
}
}
return elements
}
fun isInSamePackage(manager: ProcessorManager, elementToCheck: Element, original: Element): Boolean {
return manager.elements.getPackageOf(elementToCheck).toString() == manager.elements.getPackageOf(original).toString()
}
fun isPackagePrivate(element: Element): Boolean {
return !element.modifiers.contains(Modifier.PUBLIC) && !element.modifiers.contains(Modifier.PRIVATE)
&& !element.modifiers.contains(Modifier.STATIC)
}
fun isValidAllFields(allFields: Boolean, element: Element): Boolean {
return allFields && element.kind.isField &&
!element.modifiers.contains(Modifier.STATIC) &&
!element.modifiers.contains(Modifier.FINAL) &&
element.getAnnotation(ColumnIgnore::class.java) == null &&
element.asType().toString() != ClassNames.MODEL_ADAPTER.toString()
}
fun getClassName(elementClassname: String, manager: ProcessorManager): ClassName? {
val typeElement: TypeElement? = manager.elements.getTypeElement(elementClassname)
return if (typeElement != null) {
ClassName.get(typeElement)
} else {
val names = elementClassname.split(".")
if (names.size > 0) {
// attempt to take last part as class name
val className = names[names.size - 1]
ClassName.get(elementClassname.replace("." + className, ""), className)
} else {
null
}
}
}
}
| mit | 1eb1b398f1fc4be28d961b476ab99842 | 40.641791 | 125 | 0.664158 | 4.728814 | false | false | false | false |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/codegen/kotlin/KotlinTypeSpec.kt | 3 | 3185 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.codegen.kotlin
import androidx.room.compiler.codegen.KTypeSpecBuilder
import androidx.room.compiler.codegen.VisibilityModifier
import androidx.room.compiler.codegen.XAnnotationSpec
import androidx.room.compiler.codegen.XClassName
import androidx.room.compiler.codegen.XFunSpec
import androidx.room.compiler.codegen.XPropertySpec
import androidx.room.compiler.codegen.XTypeName
import androidx.room.compiler.codegen.XTypeSpec
import com.squareup.kotlinpoet.javapoet.KTypeSpec
internal class KotlinTypeSpec(
private val _className: XClassName?,
internal val actual: KTypeSpec
) : KotlinLang(), XTypeSpec {
override val className: XClassName
get() {
checkNotNull(_className) { "Anonymous classes have no name." }
return _className
}
internal class Builder(
private val className: XClassName?,
internal val actual: KTypeSpecBuilder
) : KotlinLang(), XTypeSpec.Builder {
override fun superclass(typeName: XTypeName) = apply {
actual.superclass(typeName.kotlin)
}
override fun addSuperinterface(typeName: XTypeName) = apply {
actual.addSuperinterface(typeName.kotlin)
}
override fun addAnnotation(annotation: XAnnotationSpec) {
check(annotation is KotlinAnnotationSpec)
actual.addAnnotation(annotation.actual)
}
override fun addProperty(propertySpec: XPropertySpec) = apply {
require(propertySpec is KotlinPropertySpec)
actual.addProperty(propertySpec.actual)
}
override fun addFunction(functionSpec: XFunSpec) = apply {
require(functionSpec is KotlinFunSpec)
actual.addFunction(functionSpec.actual)
}
override fun addType(typeSpec: XTypeSpec) = apply {
require(typeSpec is KotlinTypeSpec)
actual.addType(typeSpec.actual)
}
override fun setPrimaryConstructor(functionSpec: XFunSpec) = apply {
require(functionSpec is KotlinFunSpec)
actual.primaryConstructor(functionSpec.actual)
functionSpec.actual.delegateConstructorArguments.forEach {
actual.addSuperclassConstructorParameter(it)
}
}
override fun setVisibility(visibility: VisibilityModifier) {
actual.addModifiers(visibility.toKotlinVisibilityModifier())
}
override fun build(): XTypeSpec {
return KotlinTypeSpec(className, actual.build())
}
}
} | apache-2.0 | de7a75af901c62dce51638e4d3c01916 | 35.204545 | 76 | 0.698587 | 4.984351 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/openapi/module/impl/AutomaticModuleUnloaderImpl.kt | 2 | 6859 | // 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.openapi.module.impl
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.notification.*
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.AutomaticModuleUnloader
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectBundle
import com.intellij.openapi.roots.ui.configuration.ConfigureUnloadedModulesDialog
import com.intellij.openapi.util.NlsContexts
import com.intellij.util.xmlb.annotations.XCollection
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleDependencyItem
import com.intellij.workspaceModel.storage.bridgeEntities.ModuleId
import com.intellij.xml.util.XmlStringUtil
import kotlinx.coroutines.launch
/**
* If some modules were unloaded and new modules appears after loading project configuration, automatically unloads those which
* aren't required for loaded modules.
*/
@State(name = "AutomaticModuleUnloader", storages = [(Storage(StoragePathMacros.WORKSPACE_FILE))])
internal class AutomaticModuleUnloaderImpl(private val project: Project) : SimplePersistentStateComponent<LoadedModulesListStorage>(LoadedModulesListStorage()),
AutomaticModuleUnloader {
override fun processNewModules(currentModules: Set<String>, storage: EntityStorage) {
if (currentModules.isEmpty()) {
return
}
val oldLoaded = state.modules.toHashSet()
// if we don't store list of loaded modules most probably it means that the project wasn't opened on this machine,
// so let's not unload all modules
if (oldLoaded.isEmpty()) {
return
}
val unloadedStorage = UnloadedModulesListStorage.getInstance(project)
val unloadedModules = unloadedStorage.unloadedModuleNames
// if no modules were unloaded by user, automatic unloading shouldn't start
if (unloadedModules.isEmpty()) {
return
}
//no new modules were added, nothing to process
if (currentModules.all { it in oldLoaded || it in unloadedModules }) {
return
}
val oldLoadedWithDependencies = HashSet<String>()
for (name in oldLoaded) {
processTransitiveDependencies(ModuleId(name), storage, unloadedModules, oldLoadedWithDependencies)
}
val toLoad = currentModules.filter { it in oldLoadedWithDependencies && it !in oldLoaded }
val toUnload = currentModules.filter { it !in oldLoadedWithDependencies && it !in unloadedModules}
if (toUnload.isNotEmpty()) {
LOG.info("Old loaded modules: $oldLoaded")
LOG.info("Old unloaded modules: $unloadedModules")
LOG.info("New modules to unload: $toUnload")
}
fireNotifications(toLoad, toUnload)
unloadedStorage.addUnloadedModuleNames(toUnload)
}
private fun processTransitiveDependencies(moduleId: ModuleId, storage: EntityStorage, explicitlyUnloaded: Set<String>,
result: MutableSet<String>) {
if (moduleId.name in explicitlyUnloaded) return
val moduleEntity = storage.resolve(moduleId) ?: return
if (!result.add(moduleEntity.name)) return
moduleEntity.dependencies.forEach {
if (it is ModuleDependencyItem.Exportable.ModuleDependency) {
processTransitiveDependencies(it.module, storage, explicitlyUnloaded, result)
}
}
}
private fun fireNotifications(modulesToLoad: List<String>, modulesToUnload: List<String>) {
if (modulesToLoad.isEmpty() && modulesToUnload.isEmpty()) return
val messages = mutableListOf<String>()
val actions = mutableListOf<NotificationAction>()
if (modulesToUnload.isNotEmpty()) {
val args = arrayOf(modulesToUnload.size, modulesToUnload[0], if (modulesToUnload.size == 2) modulesToUnload[1] else modulesToUnload.size - 1)
messages += ProjectBundle.message("auto.unloaded.notification", *args)
val text = ProjectBundle.message(if (modulesToUnload.isEmpty()) "auto.unloaded.revert.short" else "auto.unloaded.revert.full", *args)
actions += createAction(text) { list -> list.removeAll(modulesToUnload) }
}
if (modulesToLoad.isNotEmpty()) {
val args = arrayOf(modulesToLoad.size, modulesToLoad[0], if (modulesToLoad.size == 2) modulesToLoad[1] else modulesToLoad.size - 1)
messages += ProjectBundle.message("auto.loaded.notification", *args)
val action = ProjectBundle.message(if (modulesToUnload.isEmpty()) "auto.loaded.revert.short" else "auto.loaded.revert.full", *args)
actions += createAction(action) { list -> list.addAll(modulesToLoad) }
}
actions += object : NotificationAction(ProjectBundle.message("configure.unloaded.modules")) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
if (ConfigureUnloadedModulesDialog(project, null).showAndGet()) {
notification.expire()
}
}
}
val content = XmlStringUtil.wrapInHtml(messages.joinToString("<br>"))
NOTIFICATION_GROUP
.createNotification(ProjectBundle.message("modules.added.notification.title"), content, NotificationType.INFORMATION)
.addActions(actions as Collection<AnAction>)
.notify(project)
}
fun createAction(@NlsContexts.NotificationContent text: String, action: (MutableList<String>) -> Unit): NotificationAction = object : NotificationAction(text) {
override fun actionPerformed(e: AnActionEvent, notification: Notification) {
val unloaded = ArrayList<String>()
val moduleManager = ModuleManager.getInstance(project)
moduleManager.unloadedModuleDescriptions.mapTo(unloaded) { it.name }
action(unloaded)
project.coroutineScope.launch {
moduleManager.setUnloadedModules(unloaded)
}
notification.expire()
}
}
override fun setLoadedModules(modules: List<String>) {
val list = state.modules
list.clear()
list.addAll(modules)
// compiler uses module list from disk, ask to save workspace
SaveAndSyncHandler.getInstance().scheduleProjectSave(project, forceSavingAllSettings = true)
}
companion object {
private val LOG = logger<AutomaticModuleUnloaderImpl>()
private val NOTIFICATION_GROUP: NotificationGroup
get() = NotificationGroupManager.getInstance().getNotificationGroup("Automatic Module Unloading")
}
}
class LoadedModulesListStorage : BaseState() {
@get:XCollection(elementName = "module", valueAttributeName = "name", propertyElementName = "loaded-modules")
val modules by list<String>()
} | apache-2.0 | 618b3ce578899bf93391aa19557ee3d5 | 45.040268 | 162 | 0.739466 | 4.837094 | false | false | false | false |
GunoH/intellij-community | platform/platform-api/src/com/intellij/openapi/wm/BannerStartPagePromoter.kt | 3 | 4645 | // 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.openapi.wm
import com.intellij.icons.AllIcons
import com.intellij.openapi.ui.popup.IconButton
import com.intellij.openapi.util.SystemInfo
import com.intellij.ui.InplaceButton
import com.intellij.ui.JBColor
import com.intellij.ui.components.panels.BackgroundRoundedPanel
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.StartupUiUtil
import com.intellij.util.ui.UIUtil
import org.jetbrains.annotations.Nls
import java.awt.Component
import java.awt.Dimension
import java.awt.Font
import java.awt.Rectangle
import java.awt.event.ActionEvent
import javax.swing.*
abstract class BannerStartPagePromoter : StartPagePromoter {
override fun getPromotion(isEmptyState: Boolean): JPanel? {
if (!canCreatePromo(isEmptyState)) return null
val vPanel: JPanel = NonOpaquePanel()
vPanel.layout = BoxLayout(vPanel, BoxLayout.PAGE_AXIS)
vPanel.alignmentY = Component.TOP_ALIGNMENT
val headerPanel: JPanel = NonOpaquePanel()
headerPanel.layout = BoxLayout(headerPanel, BoxLayout.X_AXIS)
headerPanel.alignmentX = Component.LEFT_ALIGNMENT
val header = JLabel(headerLabel)
header.font = StartupUiUtil.getLabelFont().deriveFont(Font.BOLD).deriveFont(StartupUiUtil.getLabelFont().size2D + JBUI.scale(4))
headerPanel.add(header)
headerPanel.add(Box.createHorizontalGlue())
val hPanel: JPanel = BackgroundRoundedPanel(JBUI.scale(16))
closeAction?.let { closeAction ->
val closeIcons = IconButton(null, AllIcons.Actions.Close, AllIcons.Actions.CloseDarkGrey)
val closeButton = InplaceButton(closeIcons) {
closeAction(hPanel)
}
closeButton.maximumSize = Dimension(16, 16)
headerPanel.add(closeButton)
}
vPanel.add(headerPanel)
vPanel.add(rigid(0, 4))
val description = JLabel("<html>${description}</html>").also {
it.alignmentX = Component.LEFT_ALIGNMENT
it.font = JBUI.Fonts.label().deriveFont(JBUI.Fonts.label().size2D + (when {
SystemInfo.isLinux -> JBUIScale.scale(-2)
SystemInfo.isMac -> JBUIScale.scale(-1)
else -> 0
}))
it.foreground = UIUtil.getContextHelpForeground()
}
vPanel.add(description)
val jButton = JButton()
jButton.isOpaque = false
jButton.alignmentX = Component.LEFT_ALIGNMENT
jButton.action = object : AbstractAction(actionLabel) {
override fun actionPerformed(e: ActionEvent?) {
runAction()
}
}
vPanel.add(Box.createVerticalGlue())
vPanel.add(buttonPixelHunting(jButton))
hPanel.background = JBColor.namedColor("WelcomeScreen.SidePanel.background", JBColor(0xF2F2F2, 0x3C3F41))
hPanel.layout = BoxLayout(hPanel, BoxLayout.X_AXIS)
hPanel.border = JBUI.Borders.empty(12, 16, 16, 16)
val picture = JLabel(promoImage)
picture.alignmentY = Component.TOP_ALIGNMENT
hPanel.add(picture)
hPanel.add(rigid(20, 0))
hPanel.add(vPanel)
return hPanel
}
private fun buttonPixelHunting(button: JButton): JPanel {
val buttonSizeWithoutInsets = Dimension(button.preferredSize.width - button.insets.left - button.insets.right,
button.preferredSize.height - button.insets.top - button.insets.bottom)
val buttonPlace = JPanel().apply {
layout = null
maximumSize = buttonSizeWithoutInsets
preferredSize = buttonSizeWithoutInsets
minimumSize = buttonSizeWithoutInsets
isOpaque = false
alignmentX = JPanel.LEFT_ALIGNMENT
}
buttonPlace.add(button)
button.bounds = Rectangle(-button.insets.left, -button.insets.top, button.preferredSize.width, button.preferredSize.height)
return buttonPlace
}
private fun rigid(width: Int, height: Int): Component {
return scaledRigid(JBUI.scale(width), JBUI.scale(height))
}
private fun scaledRigid(width: Int, height: Int): Component {
return (Box.createRigidArea(Dimension(width, height)) as JComponent).apply {
alignmentX = Component.LEFT_ALIGNMENT
alignmentY = Component.TOP_ALIGNMENT
}
}
protected abstract val headerLabel: @Nls String
protected abstract val actionLabel: @Nls String
protected abstract val description: @Nls String
protected abstract val promoImage: Icon
protected open val closeAction: ((promoPanel: JPanel) -> Unit)? = null
protected abstract fun runAction()
protected open fun canCreatePromo(isEmptyState: Boolean): Boolean = isEmptyState
} | apache-2.0 | 5b7649d578ca9af7d152f6f6000eeaf3 | 35.296875 | 132 | 0.731109 | 4.20362 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.