repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
resilience4j/resilience4j | resilience4j-kotlin/src/main/kotlin/io/github/resilience4j/kotlin/retry/FlowRetry.kt | 1 | 1763 | /*
*
* Copyright 2019 authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
*/
package io.github.resilience4j.kotlin.retry
import io.github.resilience4j.retry.Retry
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.retryWhen
fun <T> Flow<T>.retry(retry: Retry): Flow<T> {
val retryContext = retry.asyncContext<T>()
return onEach {
val delayMs = retryContext.onResult(it)
if (delayMs >= 0) {
delay(delayMs)
throw RetryDueToResultException()
}
}.retryWhen { e, _ ->
var shouldRetry = false
if (e is RetryDueToResultException) {
shouldRetry = true
} else {
val delayMs = retryContext.onError(e)
if (delayMs >= 0) {
delay(delayMs)
shouldRetry = true
}
}
shouldRetry
}.onCompletion { e ->
if (e == null)
retryContext.onComplete()
}
}
private class RetryDueToResultException : RuntimeException("Retry due to retryOnResult predicate") | apache-2.0 | 6d5975056b7ea22b06ec444e8f3e10e6 | 27 | 98 | 0.661373 | 4.289538 | false | false | false | false |
evant/binding-collection-adapter | app/src/main/java/me/tatarka/bindingcollectionadapter/sample/FragmentViewPagerView.kt | 1 | 2041 | package me.tatarka.bindingcollectionadapter.sample
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.google.android.material.tabs.TabLayout
import me.tatarka.bindingcollectionadapter.sample.databinding.ViewpagerViewBinding
class FragmentViewPagerView : Fragment() {
private val viewModel: MutableViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel.setCheckable(true)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ViewpagerViewBinding.inflate(inflater, container, false).also {
it.lifecycleOwner = this
it.viewModel = viewModel
it.listeners = PagerListeners(it, viewModel)
it.executePendingBindings()
it.tabs.setupWithViewPager(it.pager)
it.pager.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(it.tabs))
}.root
}
private class PagerListeners(
private val binding: ViewpagerViewBinding,
private val delegate: Listeners
) : Listeners {
override fun onAddItem() {
delegate.onAddItem()
updateTabs()
}
override fun onRemoveItem() {
delegate.onRemoveItem()
updateTabs()
}
private fun updateTabs() {
// We can't use tabs.setTabsFromPagerAdapter() because it will reset the current item to 0.
binding.tabs.removeAllTabs()
val adapter = binding.pager.adapter!!
for (i in 0 until adapter.count) {
binding.tabs.addTab(
binding.tabs.newTab().setText(adapter.getPageTitle(i)),
i == binding.pager.currentItem
)
}
}
}
}
| apache-2.0 | b2eaae9c2b40655c03e0cf1a5a57a688 | 31.396825 | 103 | 0.648212 | 5.141058 | false | false | false | false |
scenerygraphics/scenery | src/main/kotlin/graphics/scenery/backends/ShaderCompiler.kt | 1 | 8641 | package graphics.scenery.backends
import graphics.scenery.utils.LazyLogger
import org.lwjgl.util.shaderc.Shaderc
import picocli.CommandLine
import java.io.File
import java.lang.UnsupportedOperationException
import java.util.concurrent.Callable
import kotlin.system.exitProcess
/**
* Shader compiler class. Can be used as command line utility as well.
*/
@CommandLine.Command(name = "CompileShader", mixinStandardHelpOptions = true, description = ["Compiles GLSL shader code to SPIRV bytecode."])
class ShaderCompiler: AutoCloseable, Callable<ByteArray> {
private val logger by LazyLogger()
protected val compiler = Shaderc.shaderc_compiler_initialize()
@CommandLine.Parameters(index = "0", description = ["The file to compile"])
lateinit var file: File
@CommandLine.Option(names = ["-o", "--output"], description = ["The file to output the bytecode to. By default, .spv will be appended to the input file name."])
lateinit var output: File
@CommandLine.Option(names = ["-O", "--optimise"], description = ["Optimisation level, [S]ize, [P]erformance (use with care!), [0] zero/none (default)."])
var optimise: String = "0"
@CommandLine.Option(names = ["-g", "--debug"], description = ["Generate debug information."])
var debug: Boolean = false
@CommandLine.Option(names = ["-t", "--target"], description = ["Target, Vulkan (default) or OpenGL."])
var target: String = "Vulkan"
@CommandLine.Option(names = ["-e", "--entryPoint"], description = ["Entry point for the shader. Default is main."])
var entryPoint: String = "main"
@CommandLine.Option(names = ["-s", "--strict"], description = ["Strict compilation, treats warnings as errors."])
var strict: Boolean = false
/**
* Optimisation level for shader compilation.
*/
enum class OptimisationLevel {
None,
Performance,
Size
}
/**
* Compiles the [code] given to SPIRV bytecode.
*/
fun compile(
code: String,
type: ShaderType,
target: Shaders.ShaderTarget,
entryPoint: String = "main",
debug: Boolean = false,
warningsAsErrors: Boolean = false,
optimisationLevel: OptimisationLevel = OptimisationLevel.None,
path: String? = null,
baseClass: String? = null
): ByteArray {
val options = Shaderc.shaderc_compile_options_initialize()
logger.debug("Compiling code from $path of $baseClass, debug=$debug, optimisation=$optimisationLevel")
val shaderType = when (type) {
ShaderType.VertexShader -> Shaderc.shaderc_glsl_vertex_shader
ShaderType.FragmentShader -> Shaderc.shaderc_glsl_fragment_shader
ShaderType.GeometryShader -> Shaderc.shaderc_glsl_geometry_shader
ShaderType.TessellationControlShader -> Shaderc.shaderc_glsl_tess_control_shader
ShaderType.TessellationEvaluationShader -> Shaderc.shaderc_glsl_tess_evaluation_shader
ShaderType.ComputeShader -> Shaderc.shaderc_glsl_compute_shader
}
Shaderc.shaderc_compile_options_set_source_language(options, Shaderc.shaderc_source_language_glsl)
var shaderCode = if(target == Shaders.ShaderTarget.Vulkan) {
Shaderc.shaderc_compile_options_set_target_env(options, Shaderc.shaderc_target_env_vulkan, Shaderc.shaderc_env_version_vulkan_1_2)
Shaderc.shaderc_compile_options_set_target_spirv(options, Shaderc.shaderc_spirv_version_1_2)
code
} else {
Shaderc.shaderc_compile_options_set_target_env(options, Shaderc.shaderc_target_env_opengl, Shaderc.shaderc_env_version_opengl_4_5)
val extensionEnd = code.indexOf("\n", code.findLastAnyOf(listOf("#extension", "#version"))?.first ?: 0)
code.substring(0, extensionEnd) + "\n#define OPENGL\n" + code.substring(extensionEnd)
}
val optimisation = when(optimisationLevel) {
OptimisationLevel.None -> Shaderc.shaderc_optimization_level_zero
OptimisationLevel.Performance -> Shaderc.shaderc_optimization_level_performance
OptimisationLevel.Size -> Shaderc.shaderc_optimization_level_size
}
Shaderc.shaderc_compile_options_set_optimization_level(options, optimisation)
if(warningsAsErrors) {
Shaderc.shaderc_compile_options_set_warnings_as_errors(options)
}
if(debug) {
Shaderc.shaderc_compile_options_set_generate_debug_info(options)
val extensionPos = shaderCode.indexOf("\n", shaderCode.indexOf("#version "))
shaderCode = shaderCode.replaceRange(extensionPos, extensionPos + 1, "\n#extension GL_EXT_debug_printf : enable\n")
}
val result = Shaderc.shaderc_compile_into_spv(
compiler,
shaderCode,
shaderType,
path ?: "compile.glsl",
entryPoint,
options
)
Shaderc.shaderc_compile_options_release(options)
if (Shaderc.shaderc_result_get_compilation_status(result) != Shaderc.shaderc_compilation_status_success) {
val log = Shaderc.shaderc_result_get_error_message(result)
logger.error("Error in shader compilation of $path for ${baseClass}: $log")
logger.error("Shader code was: \n${shaderCode.split("\n").mapIndexed { index, s -> "${index+1}\t: $s" }.joinToString("\n")}")
throw ShaderCompilationException("Error compiling shader file $path")
}
val resultLength = Shaderc.shaderc_result_get_length(result)
val resultBytes = Shaderc.shaderc_result_get_bytes(result)
val bytecode = if (resultLength > 0 && resultBytes != null) {
val array = ByteArray(resultLength.toInt())
resultBytes.get(array)
array
} else {
val log = Shaderc.shaderc_result_get_error_message(result)
logger.error("Error in shader linking of $path for ${baseClass}: $log")
throw ShaderCompilationException("Error compiling shader file $path, received zero-length bytecode")
}
logger.debug("Successfully compiled $path into bytecode (${(resultLength/4)} opcodes), with ${Shaderc.shaderc_result_get_num_warnings(result)} warnings and ${Shaderc.shaderc_result_get_num_errors(result)} errors.")
Shaderc.shaderc_result_release(result)
return bytecode
}
/**
* Returns the version info for the shader compiler.
*/
fun versionInfo(): String {
val p = Package.getPackage("org.lwjgl.util.shaderc")
return "shaderc / lwjgl ${p?.specificationVersion} ${p?.implementationVersion}"
}
/**
* Closes this compiler instance, freeing up resouces.
*/
override fun close() {
Shaderc.shaderc_compiler_release(compiler)
}
/**
* Hook function for picocli to be invoked on startup.
*/
override fun call(): ByteArray {
println(versionInfo())
val out = if(!this::output.isInitialized) {
file.resolveSibling(file.name + ".spv")
} else {
output
}
val type = when(file.name.substringAfterLast(".").lowercase()) {
"vert" -> ShaderType.VertexShader
"frag" -> ShaderType.FragmentShader
"geom" -> ShaderType.GeometryShader
"tesc" -> ShaderType.TessellationControlShader
"tese" -> ShaderType.TessellationEvaluationShader
"comp" -> ShaderType.ComputeShader
else -> throw UnsupportedOperationException("Unknown shader type for ${file.name}.")
}
val level = when(optimise.lowercase()) {
"p" -> OptimisationLevel.Performance
"s" -> OptimisationLevel.Size
else -> OptimisationLevel.None
}
val t = when(target.lowercase()) {
"vulkan" -> Shaders.ShaderTarget.Vulkan
"opengl" -> Shaders.ShaderTarget.OpenGL
else -> throw UnsupportedOperationException("Unknown shader target $target.")
}
println("Compiling $file to $out, type $type, optimising for $level, target $t${if(debug) {", with debug information"} else { "" }}")
val bytecode = compile(file.readText(), type, t, entryPoint, debug, strict, level, file.absolutePath, null)
if(!out.exists()) {
out.createNewFile()
} else {
out.writeBytes(bytecode)
}
return bytecode
}
companion object {
@JvmStatic
fun main(args: Array<String>): Unit = exitProcess(CommandLine(ShaderCompiler()).execute(*args))
}
}
| lgpl-3.0 | 7970a838dbda9a2f6ce225aedd56e1a9 | 40.946602 | 222 | 0.646222 | 4.26716 | false | false | false | false |
glodanif/BluetoothChat | app/src/main/kotlin/com/glodanif/bluetoothchat/ui/adapter/DevicesAdapter.kt | 1 | 3076 | package com.glodanif.bluetoothchat.ui.adapter
import android.bluetooth.BluetoothDevice
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.glodanif.bluetoothchat.R
import java.util.*
class DevicesAdapter(private val context: Context) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
private val typeItem = 0
private val typeHeader = 1
var listener: ((BluetoothDevice) -> Unit)? = null
var availableList = LinkedList<BluetoothDevice>()
var pairedList = ArrayList<BluetoothDevice>()
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
if (holder is HeaderViewHolder) {
holder.header.text = context.getString(if (position == 0)
R.string.scan__available_devices else R.string.scan__paired_devices)
holder.emptyMessage.visibility = if (if (position == 0)
availableList.isEmpty() else pairedList.isEmpty()) View.VISIBLE else View.GONE
} else if (holder is DeviceViewHolder) {
val device = if (position >= 1 && position < availableList.size + 1)
availableList[position - 1] else pairedList[position - availableList.size - 2]
holder.name.text = device.name
holder.macAddress.text = device.address
holder.itemView.setOnClickListener { listener?.invoke(device) }
}
}
override fun getItemViewType(position: Int): Int {
return when (position) {
0 -> typeHeader
availableList.size + 1 -> typeHeader
else -> typeItem
}
}
override fun getItemCount(): Int {
return pairedList.size + availableList.size + 2
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
if (viewType == typeItem) {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_paired_device, parent, false)
return DeviceViewHolder(view)
}
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.item_header_devices, parent, false)
return HeaderViewHolder(view)
}
fun addNewFoundDevice(device: BluetoothDevice) {
val exists = availableList.asSequence()
.filter { it.address == device.address }
.any()
if (!exists) {
availableList.addFirst(device)
}
}
class HeaderViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var header: TextView = itemView.findViewById(R.id.tv_header)
var emptyMessage: TextView = itemView.findViewById(R.id.tv_empty_message)
}
class DeviceViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var name: TextView = itemView.findViewById(R.id.tv_name)
var macAddress: TextView = itemView.findViewById(R.id.tv_mac_address)
}
}
| apache-2.0 | b88a147cdec9da8b4b8a46160553d287 | 35.188235 | 102 | 0.659298 | 4.611694 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/src/internal/MainDispatchers.kt | 1 | 4999 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import kotlinx.coroutines.*
import java.util.*
import kotlin.coroutines.*
/**
* Name of the boolean property that enables using of [FastServiceLoader].
*/
private const val FAST_SERVICE_LOADER_PROPERTY_NAME = "kotlinx.coroutines.fast.service.loader"
// Lazy loader for the main dispatcher
internal object MainDispatcherLoader {
private val FAST_SERVICE_LOADER_ENABLED = systemProp(FAST_SERVICE_LOADER_PROPERTY_NAME, true)
@JvmField
val dispatcher: MainCoroutineDispatcher = loadMainDispatcher()
private fun loadMainDispatcher(): MainCoroutineDispatcher {
return try {
val factories = if (FAST_SERVICE_LOADER_ENABLED) {
FastServiceLoader.loadMainDispatcherFactory()
} else {
// We are explicitly using the
// `ServiceLoader.load(MyClass::class.java, MyClass::class.java.classLoader).iterator()`
// form of the ServiceLoader call to enable R8 optimization when compiled on Android.
ServiceLoader.load(
MainDispatcherFactory::class.java,
MainDispatcherFactory::class.java.classLoader
).iterator().asSequence().toList()
}
@Suppress("ConstantConditionIf")
factories.maxByOrNull { it.loadPriority }?.tryCreateDispatcher(factories)
?: createMissingDispatcher()
} catch (e: Throwable) {
// Service loader can throw an exception as well
createMissingDispatcher(e)
}
}
}
/**
* If anything goes wrong while trying to create main dispatcher (class not found,
* initialization failed, etc), then replace the main dispatcher with a special
* stub that throws an error message on any attempt to actually use it.
*
* @suppress internal API
*/
@InternalCoroutinesApi
public fun MainDispatcherFactory.tryCreateDispatcher(factories: List<MainDispatcherFactory>): MainCoroutineDispatcher =
try {
createDispatcher(factories)
} catch (cause: Throwable) {
createMissingDispatcher(cause, hintOnError())
}
/** @suppress */
@InternalCoroutinesApi
public fun MainCoroutineDispatcher.isMissing(): Boolean =
// not checking `this`, as it may be wrapped in a `TestMainDispatcher`, whereas `immediate` never is.
this.immediate is MissingMainCoroutineDispatcher
// R8 optimization hook, not const on purpose to enable R8 optimizations via "assumenosideeffects"
@Suppress("MayBeConstant")
private val SUPPORT_MISSING = true
@Suppress(
"ConstantConditionIf",
"IMPLICIT_NOTHING_TYPE_ARGUMENT_AGAINST_NOT_NOTHING_EXPECTED_TYPE" // KT-47626
)
private fun createMissingDispatcher(cause: Throwable? = null, errorHint: String? = null) =
if (SUPPORT_MISSING) MissingMainCoroutineDispatcher(cause, errorHint) else
cause?.let { throw it } ?: throwMissingMainDispatcherException()
internal fun throwMissingMainDispatcherException(): Nothing {
throw IllegalStateException(
"Module with the Main dispatcher is missing. " +
"Add dependency providing the Main dispatcher, e.g. 'kotlinx-coroutines-android' " +
"and ensure it has the same version as 'kotlinx-coroutines-core'"
)
}
private class MissingMainCoroutineDispatcher(
private val cause: Throwable?,
private val errorHint: String? = null
) : MainCoroutineDispatcher(), Delay {
override val immediate: MainCoroutineDispatcher get() = this
override fun isDispatchNeeded(context: CoroutineContext): Boolean =
missing()
override fun limitedParallelism(parallelism: Int): CoroutineDispatcher =
missing()
override suspend fun delay(time: Long) =
missing()
override fun invokeOnTimeout(timeMillis: Long, block: Runnable, context: CoroutineContext): DisposableHandle =
missing()
override fun dispatch(context: CoroutineContext, block: Runnable) =
missing()
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) =
missing()
private fun missing(): Nothing {
if (cause == null) {
throwMissingMainDispatcherException()
} else {
val message = "Module with the Main dispatcher had failed to initialize" + (errorHint?.let { ". $it" } ?: "")
throw IllegalStateException(message, cause)
}
}
override fun toString(): String = "Dispatchers.Main[missing${if (cause != null) ", cause=$cause" else ""}]"
}
/**
* @suppress
*/
@InternalCoroutinesApi
public object MissingMainCoroutineDispatcherFactory : MainDispatcherFactory {
override val loadPriority: Int
get() = -1
override fun createDispatcher(allFactories: List<MainDispatcherFactory>): MainCoroutineDispatcher {
return MissingMainCoroutineDispatcher(null)
}
}
| apache-2.0 | b738aaeac2629f099c6396ce81290a93 | 35.757353 | 121 | 0.694539 | 4.90098 | false | false | false | false |
paulinabls/hangman | app/src/test/kotlin/com/intive/hangman/engine/KotlintestGameTest_BehaviorSpec.kt | 1 | 1660 | package com.intive.hangman.engine
import com.intive.hangman.TextUtils
import com.winterbe.expekt.should
import io.kotlintest.matchers.shouldBe
import io.kotlintest.matchers.shouldEqual
import io.kotlintest.specs.BehaviorSpec
class KotlintestGameTest_BehaviorSpec : BehaviorSpec() {
init {
val password = "microwave"
//password = Gen.string().nextPrintableString(10) <- generator
Given("new game with password: $password") {
val game = Game(password = password)
When("created") {
Then("has 0 wrong answers") {
game.wrongAnswers.shouldEqual(0)
}
Then("has all letters dashed") {
val length = password.length
game.dashedPassword.should.match(Regex("_{$length}")) //expekt
}
}
When("correct letter suggested") {
for (c in password) {
Then("returns true for letter $c") {
game.suggestLetter(c).shouldBe(true)
}
Then("number of wrong answers did not increase") {
game.wrongAnswers.shouldEqual(0)
}
}
}
When("any wrong letter suggested") {
val alphabetRangeNotIn = TextUtils.createAlphabetRangeNotIn(password)
for (c in alphabetRangeNotIn) {
Then("should return false for letter $c") {
game.suggestLetter(c).should.be.`false`
}
}
}
}
}
} | mit | ed9b5bff0043def2ea93acaff3cfa040 | 31.568627 | 85 | 0.51747 | 5.076453 | false | true | false | false |
anthonycr/Lightning-Browser | app/src/main/java/acr/browser/lightning/database/history/HistoryDatabase.kt | 1 | 5520 | /*
* Copyright 2014 A.C.R. Development
*/
package acr.browser.lightning.database.history
import acr.browser.lightning.database.HistoryEntry
import acr.browser.lightning.database.databaseDelegate
import acr.browser.lightning.extensions.firstOrNullMap
import acr.browser.lightning.extensions.useMap
import android.app.Application
import android.content.ContentValues
import android.database.Cursor
import android.database.DatabaseUtils
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import androidx.annotation.WorkerThread
import io.reactivex.Completable
import io.reactivex.Single
import javax.inject.Inject
import javax.inject.Singleton
/**
* The disk backed download database. See [HistoryRepository] for function documentation.
*/
@Singleton
@WorkerThread
class HistoryDatabase @Inject constructor(
application: Application
) : SQLiteOpenHelper(application, DATABASE_NAME, null, DATABASE_VERSION), HistoryRepository {
private val database: SQLiteDatabase by databaseDelegate()
// Creating Tables
override fun onCreate(db: SQLiteDatabase) {
val createHistoryTable = "CREATE TABLE $TABLE_HISTORY(" +
" $KEY_ID INTEGER PRIMARY KEY," +
" $KEY_URL TEXT," +
" $KEY_TITLE TEXT," +
" $KEY_TIME_VISITED INTEGER" +
")"
db.execSQL(createHistoryTable)
}
// Upgrading database
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
// Drop older table if it exists
db.execSQL("DROP TABLE IF EXISTS $TABLE_HISTORY")
// Create tables again
onCreate(db)
}
override fun deleteHistory(): Completable = Completable.fromAction {
database.run {
delete(TABLE_HISTORY, null, null)
close()
}
}
override fun deleteHistoryEntry(url: String): Completable = Completable.fromAction {
database.delete(TABLE_HISTORY, "$KEY_URL = ?", arrayOf(url))
}
override fun visitHistoryEntry(url: String, title: String?): Completable =
Completable.fromAction {
val values = ContentValues().apply {
put(KEY_TITLE, title ?: "")
put(KEY_TIME_VISITED, System.currentTimeMillis())
}
database.query(
false,
TABLE_HISTORY,
arrayOf(KEY_ID),
"$KEY_URL = ?",
arrayOf(url),
null,
null,
null,
"1"
).use {
if (it.count > 0) {
database.update(TABLE_HISTORY, values, "$KEY_URL = ?", arrayOf(url))
} else {
addHistoryEntry(HistoryEntry(url, title ?: ""))
}
}
}
override fun findHistoryEntriesContaining(query: String): Single<List<HistoryEntry>> =
Single.fromCallable {
val search = "%$query%"
return@fromCallable database.query(
TABLE_HISTORY,
null,
"$KEY_TITLE LIKE ? OR $KEY_URL LIKE ?",
arrayOf(search, search),
null,
null,
"$KEY_TIME_VISITED DESC",
"5"
).useMap { it.bindToHistoryEntry() }
}
override fun lastHundredVisitedHistoryEntries(): Single<List<HistoryEntry>> =
Single.fromCallable {
database.query(
TABLE_HISTORY,
null,
null,
null,
null,
null,
"$KEY_TIME_VISITED DESC",
"100"
).useMap { it.bindToHistoryEntry() }
}
@WorkerThread
private fun addHistoryEntry(item: HistoryEntry) {
database.insert(TABLE_HISTORY, null, item.toContentValues())
}
@WorkerThread
private fun getHistoryEntry(url: String): String? =
database.query(
TABLE_HISTORY,
arrayOf(KEY_ID, KEY_URL, KEY_TITLE),
"$KEY_URL = ?",
arrayOf(url),
null,
null,
null,
"1"
).firstOrNullMap { it.getString(0) }
private fun getAllHistoryEntries(): List<HistoryEntry> {
return database.query(
TABLE_HISTORY,
null,
null,
null,
null,
null,
"$KEY_TIME_VISITED DESC"
).useMap { it.bindToHistoryEntry() }
}
private fun getHistoryEntriesCount(): Long =
DatabaseUtils.queryNumEntries(database, TABLE_HISTORY)
private fun HistoryEntry.toContentValues() = ContentValues().apply {
put(KEY_URL, url)
put(KEY_TITLE, title)
put(KEY_TIME_VISITED, lastTimeVisited)
}
private fun Cursor.bindToHistoryEntry() = HistoryEntry(
url = getString(1),
title = getString(2),
lastTimeVisited = getLong(3)
)
companion object {
// Database version
private const val DATABASE_VERSION = 2
// Database name
private const val DATABASE_NAME = "historyManager"
// HistoryEntry table name
private const val TABLE_HISTORY = "history"
// HistoryEntry table columns names
private const val KEY_ID = "id"
private const val KEY_URL = "url"
private const val KEY_TITLE = "title"
private const val KEY_TIME_VISITED = "time"
}
}
| mpl-2.0 | f42ffdc82658dd387468d408539b1477 | 29 | 93 | 0.578261 | 4.820961 | false | false | false | false |
leafclick/intellij-community | platform/configuration-store-impl/src/schemeManager/SchemeChangeApplicator.kt | 1 | 6457 | // 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.configurationStore.schemeManager
import com.intellij.configurationStore.LazySchemeProcessor
import com.intellij.configurationStore.SchemeContentChangedHandler
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.VirtualFile
import gnu.trove.THashSet
import java.util.function.Function
internal interface SchemeChangeEvent {
fun execute(schemaLoader: Lazy<SchemeLoader<Any, Any>>, schemeManager: SchemeManagerImpl<Any, Any>)
}
internal interface SchemeAddOrUpdateEvent {
val file: VirtualFile
}
private fun findExternalizableSchemeByFileName(fileName: String, schemeManager: SchemeManagerImpl<Any, Any>): Any? {
return schemeManager.schemes.firstOrNull {
fileName == getSchemeFileName(schemeManager, it)
}
}
internal fun <T : Any> getSchemeFileName(schemeManager: SchemeManagerImpl<T, T>, scheme: T): String {
return "${schemeManager.getFileName(scheme)}${schemeManager.schemeExtension}"
}
internal fun <T : Any> readSchemeFromFile(file: VirtualFile, schemeLoader: SchemeLoader<T, T>, schemeManager: SchemeManagerImpl<T, T>): T? {
val fileName = file.name
if (file.isDirectory || !schemeManager.canRead(fileName)) {
return null
}
return catchAndLog({ file.path }) {
schemeLoader.loadScheme(fileName, null, file.contentsToByteArray())
}
}
internal class SchemeChangeApplicator(private val schemeManager: SchemeManagerImpl<Any, Any>) {
fun reload(events: Collection<SchemeChangeEvent>) {
val lazySchemeLoader = lazy { schemeManager.createSchemeLoader() }
doReload(events, lazySchemeLoader)
if (lazySchemeLoader.isInitialized()) {
lazySchemeLoader.value.apply()
}
}
private fun doReload(events: Collection<SchemeChangeEvent>, lazySchemaLoader: Lazy<SchemeLoader<Any, Any>>) {
val oldActiveScheme = schemeManager.activeScheme
var newActiveScheme: Any? = null
val processor = schemeManager.processor
for (event in sortSchemeChangeEvents(events)) {
event.execute(lazySchemaLoader, schemeManager)
if (event !is UpdateScheme) {
continue
}
val file = event.file
if (!file.isValid) {
continue
}
val fileName = file.name
val changedScheme = findExternalizableSchemeByFileName(fileName, schemeManager)
if (callSchemeContentChangedIfSupported(changedScheme, fileName, file, schemeManager)) {
continue
}
if (changedScheme != null) {
lazySchemaLoader.value.removeUpdatedScheme(changedScheme)
processor.onSchemeDeleted(changedScheme)
}
val newScheme = readSchemeFromFile(file, lazySchemaLoader.value, schemeManager)
fun isNewActiveScheme(): Boolean {
if (newActiveScheme != null) {
return false
}
if (oldActiveScheme == null) {
return newScheme != null && schemeManager.currentPendingSchemeName == processor.getSchemeKey(newScheme)
}
else {
// do not set active scheme if currently no active scheme
// must be equals by reference
return changedScheme === oldActiveScheme
}
}
if (isNewActiveScheme()) {
// call onCurrentSchemeSwitched only when all schemes reloaded
newActiveScheme = newScheme
}
}
if (newActiveScheme != null) {
schemeManager.activeScheme = newActiveScheme
processor.onCurrentSchemeSwitched(oldActiveScheme, newActiveScheme, false)
}
}
}
// exposed for test only
internal fun sortSchemeChangeEvents(inputEvents: Collection<SchemeChangeEvent>): Collection<SchemeChangeEvent> {
if (inputEvents.size < 2) {
return inputEvents
}
var isThereSomeRemoveEvent = false
val existingAddOrUpdate = THashSet<String>()
val removedFileNames = THashSet<String>()
val result = ArrayList(inputEvents)
// first, remove any event before RemoveAllSchemes and remove RemoveScheme event if there is any subsequent add/update
for (i in (result.size - 1) downTo 0) {
val event = result.get(i)
if (event is RemoveAllSchemes) {
for (j in (i - 1) downTo 0) {
result.removeAt(j)
}
break
}
else if (event is SchemeAddOrUpdateEvent) {
val fileName = event.file.name
if (removedFileNames.contains(fileName)) {
result.removeAt(i)
}
else {
existingAddOrUpdate.add(fileName)
}
}
else if (event is RemoveScheme) {
if (existingAddOrUpdate.contains(event.fileName)) {
result.removeAt(i)
}
else {
isThereSomeRemoveEvent = true
removedFileNames.add(event.fileName)
}
}
}
fun weight(event: SchemeChangeEvent): Int {
return when (event) {
is SchemeAddOrUpdateEvent -> 1
else -> 0
}
}
if (isThereSomeRemoveEvent) {
// second, move all RemoveScheme to first place, to ensure that SchemeLoader will be not created during processing of RemoveScheme event
// (because RemoveScheme removes schemes from scheme manager directly)
result.sortWith(Comparator { o1, o2 ->
weight(o1) - weight(o2)
})
}
return result
}
private fun callSchemeContentChangedIfSupported(changedScheme: Any?, fileName: String, file: VirtualFile, schemeManager: SchemeManagerImpl<Any, Any>): Boolean {
if (changedScheme == null || schemeManager.processor !is SchemeContentChangedHandler<*> || schemeManager.processor !is LazySchemeProcessor) {
return false
}
// unrealistic case, but who knows
val externalInfo = schemeManager.schemeToInfo.get(changedScheme) ?: return false
catchAndLog({ file.path }) {
val bytes = file.contentsToByteArray()
lazyPreloadScheme(bytes, schemeManager.isOldSchemeNaming) { name, parser ->
val attributeProvider = Function<String, String?> { parser.getAttributeValue(null, it) }
val schemeName = name
?: schemeManager.processor.getSchemeKey(attributeProvider, FileUtilRt.getNameWithoutExtension(fileName))
?: throw nameIsMissed(bytes)
val dataHolder = SchemeDataHolderImpl(schemeManager.processor, bytes, externalInfo)
@Suppress("UNCHECKED_CAST")
(schemeManager.processor as SchemeContentChangedHandler<Any>).schemeContentChanged(changedScheme, schemeName, dataHolder)
}
return true
}
return false
} | apache-2.0 | 52a6da80916b928b004deb909794a7c0 | 33.351064 | 160 | 0.708533 | 4.672214 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/specialBuiltins/emptyStringMap.kt | 5 | 719 | private object EmptyStringMap : Map<String, Nothing> {
override val size: Int get() = 0
override fun isEmpty(): Boolean = true
override fun containsKey(key: String): Boolean = false
override fun containsValue(value: Nothing): Boolean = false
override fun get(key: String): Nothing? = null
override val entries: Set<Map.Entry<String, Nothing>> get() = null!!
override val keys: Set<String> get() = null!!
override val values: Collection<Nothing> get() = null!!
}
fun box(): String {
val n = EmptyStringMap as Map<Any?, Any?>
if (n.get(null) != null) return "fail 1"
if (n.containsKey(null)) return "fail 2"
if (n.containsValue(null)) return "fail 3"
return "OK"
}
| apache-2.0 | f6866327dfae78916669bc59d0141dc4 | 33.238095 | 72 | 0.659249 | 3.784211 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-tests/testSrc/com/intellij/codeInsight/hints/filtering/PatternExtractionTest.kt | 31 | 2714 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.hints.filtering
import junit.framework.TestCase
import org.assertj.core.api.Assertions.assertThat
class PatternExtractionTest : TestCase() {
fun String.assertMatcher(nameMatcher: String, paramsMatcher: String) {
val matcher = MatcherConstructor.extract(this)
if (matcher == null) {
assertThat(nameMatcher).isEmpty()
assertThat(paramsMatcher).isEmpty()
return
}
assertThat(nameMatcher).isEqualTo(matcher.first)
assertThat(paramsMatcher).isEqualTo(matcher.second)
}
fun String.assertError() {
val matcher = MatcherConstructor.extract(this)
assertThat(matcher).isNull()
}
fun `test error when no closing brace`() {
val text = "Test.foo(paramName"
text.assertError()
}
fun `test match all methods from package`() {
val text = "java.lang.*"
text.assertMatcher("java.lang.*", "")
}
fun `test match all methods from class String`() {
val text = "java.lang.String.*"
text.assertMatcher("java.lang.String.*", "")
}
fun `test match all replace methods`() {
val text = "*.replace"
text.assertMatcher("*.replace", "")
}
fun `test match all replace methods with couple params`() {
val text = "*.replace(*, *)"
text.assertMatcher("*.replace", "(*, *)")
}
fun `test match only one replace method with couple params`() {
val text = "java.lang.String.replace(*,*)"
text.assertMatcher("java.lang.String.replace", "(*,*)")
}
fun `test match debug particular method`() {
val text = "org.logger.Log.debug(format,arg)"
text.assertMatcher("org.logger.Log.debug", "(format,arg)")
}
fun `test match method with single param`() {
val text = "class.method(*)"
text.assertMatcher("class.method", "(*)")
}
fun `test match all methods with single param`() {
val text = "*(*)"
text.assertMatcher("*", "(*)")
}
fun `test simplified params matcher`() {
val text = "(*)"
text.assertMatcher("", "(*)")
}
fun `test shit`() {
val text = " foooo (*) "
text.assertMatcher("foooo", "(*)")
}
} | apache-2.0 | 5e252b9377d346b01bdb36c8328d9b95 | 27.578947 | 75 | 0.655122 | 4.075075 | false | true | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/plugins/printer/BuildFilePrinter.kt | 6 | 1897 | // 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.plugins.printer
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildSystemIR
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.render
abstract class BuildFilePrinter {
abstract val indent: Int
private val builder = StringBuilder()
protected var currentIndent = 0
fun nl(lineBreaks: Int = 1) {
+"\n".repeat(lineBreaks)
}
fun nlIndented(lineBreaks: Int = 1) {
nl(lineBreaks)
indent()
}
fun indent() {
+" ".repeat(currentIndent)
}
fun String.print() {
builder.append(this)
}
operator fun @receiver:NonNls String.unaryPlus() {
builder.append(this)
}
fun indented(inner: () -> Unit) {
currentIndent += indent
inner()
currentIndent -= indent
}
inline fun <T> List<T>.list(
prefix: BuildFilePrinter.() -> Unit = {},
separator: BuildFilePrinter.() -> Unit = { +", " },
suffix: BuildFilePrinter.() -> Unit = {},
render: BuildFilePrinter.(T) -> Unit
) {
prefix()
if (isNotEmpty()) {
render(first())
for (i in 1..lastIndex) {
separator()
render(this[i])
}
}
suffix()
}
open fun <T : BuildSystemIR> List<T>.listNl(needFirstIndent: Boolean = true, lineBreaks: Int = 1) {
if (needFirstIndent) indent()
list(separator = { nl(lineBreaks); indent() }) { it.render(this) }
}
fun result(): String = builder.toString()
}
inline fun <P : BuildFilePrinter> P.printBuildFile(builder: P.() -> Unit) =
apply(builder).result() | apache-2.0 | ba38073fc177ea112a6610f48d84d71b | 27.757576 | 158 | 0.604112 | 4.123913 | false | false | false | false |
smmribeiro/intellij-community | plugins/git4idea/src/git4idea/index/actions/GitFileStatusNodeAction.kt | 6 | 1281 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package git4idea.index.actions
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.util.containers.asJBIterable
import git4idea.index.ui.GitFileStatusNode
import git4idea.index.ui.GitStageDataKeys
import java.util.function.Supplier
import javax.swing.Icon
abstract class GitFileStatusNodeAction(text: Supplier<String>, description: Supplier<String>, icon: Icon? = null)
: DumbAwareAction(text, description, icon) {
override fun update(e: AnActionEvent) {
val nodes = e.getData(GitStageDataKeys.GIT_FILE_STATUS_NODES).asJBIterable()
e.presentation.isEnabledAndVisible = e.project != null && nodes.filter(this::matches).isNotEmpty
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val nodes = e.getRequiredData(GitStageDataKeys.GIT_FILE_STATUS_NODES).asJBIterable()
perform(project, nodes.filter(this::matches).toList())
}
abstract fun matches(statusNode: GitFileStatusNode): Boolean
abstract fun perform(project: Project, nodes: List<GitFileStatusNode>)
} | apache-2.0 | e5ed195cfa7dfccf2a8e8ba1f6720692 | 41.733333 | 140 | 0.788447 | 4.227723 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/KotlinTypeArgumentInfoHandler.kt | 1 | 9569 | // 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.parameterInfo
import com.intellij.lang.parameterInfo.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.core.resolveCandidates
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.parents
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.calls.callUtil.getCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.typeUtil.TypeNullability
import org.jetbrains.kotlin.types.typeUtil.isAnyOrNullableAny
import org.jetbrains.kotlin.types.typeUtil.nullability
class KotlinClassConstructorInfoHandler : KotlinTypeArgumentInfoHandlerBase<ClassConstructorDescriptor>() {
override fun fetchTypeParameters(descriptor: ClassConstructorDescriptor): List<TypeParameterDescriptor> = descriptor.typeParameters
override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<ClassConstructorDescriptor>? {
val userType = argumentList.parent as? KtUserType ?: return null
val descriptors = userType.referenceExpression?.resolveMainReferenceToDescriptors()?.mapNotNull { it as? ClassConstructorDescriptor }
return descriptors?.takeIf { it.isNotEmpty() }
}
override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java)
}
class KotlinClassTypeArgumentInfoHandler : KotlinTypeArgumentInfoHandlerBase<ClassDescriptor>() {
override fun fetchTypeParameters(descriptor: ClassDescriptor) = descriptor.typeConstructor.parameters
override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<ClassDescriptor>? {
val userType = argumentList.parent as? KtUserType ?: return null
val descriptors = userType.referenceExpression?.resolveMainReferenceToDescriptors()?.mapNotNull { it as? ClassDescriptor }
return descriptors?.takeIf { it.isNotEmpty() }
}
override fun getArgumentListAllowedParentClasses() = setOf(KtUserType::class.java)
}
class KotlinFunctionTypeArgumentInfoHandler : KotlinTypeArgumentInfoHandlerBase<FunctionDescriptor>() {
override fun fetchTypeParameters(descriptor: FunctionDescriptor) = descriptor.typeParameters
override fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<FunctionDescriptor>? {
val callElement = argumentList.parent as? KtCallElement ?: return null
val bindingContext = argumentList.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val call = callElement.getCall(bindingContext) ?: return null
val candidates = call.resolveCandidates(bindingContext, callElement.getResolutionFacade())
return candidates
.map { it.resultingDescriptor }
.distinctBy { buildPresentation(it.typeParameters, -1).first }
}
override fun getArgumentListAllowedParentClasses() = setOf(KtCallElement::class.java)
}
abstract class KotlinTypeArgumentInfoHandlerBase<TParameterOwner : DeclarationDescriptor> :
ParameterInfoHandlerWithTabActionSupport<KtTypeArgumentList, TParameterOwner, KtTypeProjection> {
protected abstract fun fetchTypeParameters(descriptor: TParameterOwner): List<TypeParameterDescriptor>
protected abstract fun findParameterOwners(argumentList: KtTypeArgumentList): Collection<TParameterOwner>?
override fun getActualParameterDelimiterType() = KtTokens.COMMA
override fun getActualParametersRBraceType() = KtTokens.GT
override fun getArgumentListClass() = KtTypeArgumentList::class.java
override fun getActualParameters(o: KtTypeArgumentList) = o.arguments.toTypedArray()
override fun getArgListStopSearchClasses() =
setOf(KtNamedFunction::class.java, KtVariableDeclaration::class.java, KtClassOrObject::class.java)
override fun showParameterInfo(element: KtTypeArgumentList, context: CreateParameterInfoContext) {
context.showHint(element, element.textRange.startOffset, this)
}
override fun findElementForUpdatingParameterInfo(context: UpdateParameterInfoContext): KtTypeArgumentList? {
val element = context.file.findElementAt(context.offset) ?: return null
val argumentList = element.getParentOfType<KtTypeArgumentList>(true) ?: return null
val argument = element.parents.takeWhile { it != argumentList }.lastOrNull() as? KtTypeProjection
if (argument != null) {
val arguments = getActualParameters(argumentList)
val index = arguments.indexOf(element)
context.setCurrentParameter(index)
context.setHighlightedParameter(element)
}
return argumentList
}
override fun findElementForParameterInfo(context: CreateParameterInfoContext): KtTypeArgumentList? {
val file = context.file as? KtFile ?: return null
val token = file.findElementAt(context.offset) ?: return null
val argumentList = token.getParentOfType<KtTypeArgumentList>(true) ?: return null
val parameterOwners = findParameterOwners(argumentList) ?: return null
context.itemsToShow = parameterOwners.toTypedArray<Any>()
return argumentList
}
override fun updateParameterInfo(argumentList: KtTypeArgumentList, context: UpdateParameterInfoContext) {
if (context.parameterOwner !== argumentList) {
context.removeHint()
}
val offset = context.offset
val parameterIndex = argumentList.allChildren
.takeWhile { it.startOffset < offset }
.count { it.node.elementType == KtTokens.COMMA }
context.setCurrentParameter(parameterIndex)
}
override fun updateUI(itemToShow: TParameterOwner, context: ParameterInfoUIContext) {
if (!updateUIOrFail(itemToShow, context)) {
context.isUIComponentEnabled = false
return
}
}
private fun updateUIOrFail(itemToShow: TParameterOwner, context: ParameterInfoUIContext): Boolean {
val currentIndex = context.currentParameterIndex
if (currentIndex < 0) return false // by some strange reason we are invoked with currentParameterIndex == -1 during initialization
val parameters = fetchTypeParameters(itemToShow)
val (text, currentParameterStart, currentParameterEnd) = buildPresentation(parameters, currentIndex)
context.setupUIComponentPresentation(
text, currentParameterStart, currentParameterEnd,
false/*isDisabled*/, false/*strikeout*/, false/*isDisabledBeforeHighlight*/,
context.defaultParameterColor
)
return true
}
protected fun buildPresentation(
parameters: List<TypeParameterDescriptor>,
currentIndex: Int
): Triple<String, Int, Int> {
var currentParameterStart = -1
var currentParameterEnd = -1
val text = buildString {
var needWhere = false
for ((index, parameter) in parameters.withIndex()) {
if (index > 0) append(", ")
if (index == currentIndex) {
currentParameterStart = length
}
if (parameter.isReified) {
append("reified ")
}
when (parameter.variance) {
Variance.INVARIANT -> {
}
Variance.IN_VARIANCE -> append("in ")
Variance.OUT_VARIANCE -> append("out ")
}
append(parameter.name.asString())
val upperBounds = parameter.upperBounds
if (upperBounds.size == 1) {
val upperBound = upperBounds.single()
if (!upperBound.isAnyOrNullableAny() || upperBound.nullability() == TypeNullability.NOT_NULL) { // skip Any? or Any!
append(" : ").append(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(upperBound))
}
} else if (upperBounds.size > 1) {
needWhere = true
}
if (index == currentIndex) {
currentParameterEnd = length
}
}
if (needWhere) {
append(" where ")
var needComma = false
for (parameter in parameters) {
val upperBounds = parameter.upperBounds
if (upperBounds.size > 1) {
for (upperBound in upperBounds) {
if (needComma) append(", ")
needComma = true
append(parameter.name.asString())
append(" : ")
append(DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(upperBound))
}
}
}
}
}
return Triple(text, currentParameterStart, currentParameterEnd)
}
} | apache-2.0 | ca1f950b260d9102ff5d9006cb5f3660 | 44.571429 | 158 | 0.688996 | 5.609027 | false | false | false | false |
Wreulicke/spring-sandbox | webflux-oauth2/src/main/kotlin/com/github/wreulicke/webflux/oauth2/CheckTokenReactiveAuthenticationManager.kt | 1 | 5427 | package com.github.wreulicke.webflux.oauth2
import com.github.benmanes.caffeine.cache.Caffeine
import org.slf4j.LoggerFactory
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.security.authentication.ReactiveAuthenticationManager
import org.springframework.security.core.Authentication
import org.springframework.security.core.authority.SimpleGrantedAuthority
import org.springframework.security.oauth2.core.OAuth2AccessToken
import org.springframework.security.oauth2.core.OAuth2AuthenticationException
import org.springframework.security.oauth2.server.resource.BearerTokenAuthenticationToken
import org.springframework.security.oauth2.server.resource.BearerTokenError
import org.springframework.util.StringUtils
import org.springframework.web.reactive.function.BodyInserters
import org.springframework.web.reactive.function.client.ClientResponse
import org.springframework.web.reactive.function.client.WebClient
import reactor.core.publisher.Mono
import java.net.URI
import java.nio.charset.StandardCharsets
import java.time.Duration
import java.util.*
class CheckTokenReactiveAuthenticationManager(
val checkToken: URI,
val webClient: WebClient
) : ReactiveAuthenticationManager {
val caches = Caffeine.newBuilder()
.maximumSize(1000)
.expireAfterAccess(Duration.ofMinutes(10))
.build<String, Authentication>()
companion object {
val log = LoggerFactory.getLogger(CheckTokenReactiveAuthenticationManager::class.java)
fun basicHeaderValue(clientId: String, clientSecret: String): String {
var headerValue = "$clientId:"
if (StringUtils.hasText(clientSecret)) {
headerValue += clientSecret
}
return "Basic " + Base64.getEncoder().encodeToString(headerValue.toByteArray(StandardCharsets.UTF_8))
}
}
constructor(introspectionUri: URI, clientId: String, clientSecret: String) : this(introspectionUri, webClient = WebClient.builder()
.defaultHeader(HttpHeaders.AUTHORIZATION, basicHeaderValue(clientId, clientSecret))
.build())
override fun authenticate(authentication: Authentication?): Mono<Authentication> {
return Mono.justOrEmpty(authentication)
.filter(BearerTokenAuthenticationToken::class.java::isInstance)
.cast(BearerTokenAuthenticationToken::class.java)
.map(BearerTokenAuthenticationToken::getToken)
.flatMap(this::authenticate)
}
private fun authenticate(token: String): Mono<Authentication> {
return Mono.justOrEmpty(caches.getIfPresent(token))
.onErrorResume {
checkToken(token)
.flatMap { response ->
response.bodyToMono(java.util.HashMap::class.java)
.map { it as Map<String, Any> }
}
.map { map ->
if (map.containsKey("error")) {
throw OAuth2AuthenticationException(
invalidToken("contains error: " + map.get("error")))
}
val accessToken = OAuth2AccessToken(OAuth2AccessToken.TokenType.BEARER, token, null, null)
val authorities = map.getOrElse("authorities") { emptyList<String>() } as List<String>
val claims = mutableMapOf<String, Any?>()
claims.put("exp", map.get("exp"))
claims.put("client_id", map.get("client_id"))
claims.put("scope", map.get("scope"))
claims.put("active", map.get("active"))
val a = OAuth2IntrospectionAuthenticationToken(accessToken, claims, authorities.map { SimpleGrantedAuthority(it) })
caches.put(token, a)
a
}
.cast(Authentication::class.java)
.onErrorMap(
{ e ->
e !is OAuth2AuthenticationException
},
this::onError)
}
}
fun checkToken(token: String): Mono<ClientResponse> {
var body = this.webClient.post()
.uri(this.checkToken)
.header(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_UTF8_VALUE)
.body(BodyInserters.fromFormData("token", token))
log.info("header: {}", body.header("Authorization"))
return body.exchange()
}
private fun invalidToken(message: String?): BearerTokenError {
return BearerTokenError("invalid_token",
HttpStatus.UNAUTHORIZED, message,
"https://tools.ietf.org/html/rfc7662#section-2.2");
}
private fun onError(e: Throwable): OAuth2AuthenticationException {
log.error("onError", e)
val invalidToken = invalidToken(e.message);
return OAuth2AuthenticationException(invalidToken, e.message);
}
}
| mit | cba133a1877a3221902d624270791ed1 | 45.784483 | 147 | 0.609913 | 5.357354 | false | false | false | false |
Flank/flank | flank-scripts/src/main/kotlin/flank/scripts/data/github/commons/LastWorkflowRunDate.kt | 1 | 1363 | package flank.scripts.data.github.commons
import com.github.kittinunf.result.getOrNull
import flank.scripts.data.github.getGitHubWorkflowRunsSummary
import flank.scripts.data.github.objects.GitHubWorkflowRun
import java.time.Instant
import java.time.format.DateTimeFormatter
suspend fun getLastWorkflowRunDate(
token: String,
workflowName: String? = null,
workflowFileName: String? = null
): String = getGitHubWorkflowRunsSummary(
githubToken = token,
workflow = requireNotNull(
workflowName ?: workflowFileName
) { "** Missing either workflow name or workflow file name. Both can not be null" },
parameters = listOf(
"per_page" to 20,
"page" to 1
)
).getOrNull()
?.run {
workflowRuns
.filter { it.status != "in_progress" }
.filter { it.conclusion != "cancelled" }
.getOrNull(0)
.logRun()
?.createdAt.run { DateTimeFormatter.ISO_INSTANT.format(Instant.parse(this)) }
} ?: run {
println("** No workflow run found for ${workflowName ?: workflowFileName}")
DateTimeFormatter.ISO_INSTANT.format(Instant.now())
}
private fun GitHubWorkflowRun?.logRun() = this?.also {
println(
"""
** Last workflow run:
name: ${it.name}
last run: ${it.createdAt}
url: ${it.htmlUrl}
""".trimIndent()
)
}
| apache-2.0 | 960c859cd2cba0ef47172f21ee80690c | 29.977273 | 89 | 0.654439 | 4.155488 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/pipeline/deferred/DeferredPipeline.kt | 1 | 10799 | package de.fabmax.kool.pipeline.deferred
import de.fabmax.kool.KoolContext
import de.fabmax.kool.math.clamp
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.DepthCompareOp
import de.fabmax.kool.pipeline.SingleColorTexture
import de.fabmax.kool.pipeline.ao.AoPipeline
import de.fabmax.kool.pipeline.ibl.EnvironmentMaps
import de.fabmax.kool.scene.*
import de.fabmax.kool.util.*
import kotlin.math.min
import kotlin.math.roundToInt
class DeferredPipeline(val scene: Scene, val cfg: DeferredPipelineConfig) {
var renderResolution = 1f
set(value) {
field = value.clamp(0.1f, 2f)
}
val passes: List<DeferredPasses>
var activePassIndex = 0
private set(value) {
field = value % passes.size
}
val activePass: DeferredPasses
get() = passes[activePassIndex]
val inactivePass: DeferredPasses
get() = passes[(activePassIndex + 1) % passes.size]
val onSwap = mutableListOf<DeferredPassSwapListener>()
val onConfigChange = mutableListOf<(DeferredPipeline) -> Unit>()
val lightingPassShader: PbrSceneShader
val aoPipeline: AoPipeline.DeferredAoPipeline?
val reflections: Reflections?
val bloom: Bloom?
val shadowMaps: List<ShadowMap>
val sceneContent = Group()
val lightingPassContent = Group()
val dynamicPointLights = DeferredPointLights(true)
val staticPointLights = DeferredPointLights(false)
val spotLights: List<DeferredSpotLights>
get() = mutSpotLights
private val mutSpotLights = mutableListOf<DeferredSpotLights>()
val noSsrMap = SingleColorTexture(Color(0f, 0f, 0f, 0f))
val noBloomMap = SingleColorTexture(Color(0f, 0f, 0f, 0f))
private val maxGlobalLights = cfg.maxGlobalLights
private val isAoAvailable = cfg.isWithAmbientOcclusion
private val isSsrAvailable = cfg.isWithScreenSpaceReflections
private val isBloomAvailable = cfg.isWithBloom
var isEnabled = true
set(value) {
field = value
updateEnabled()
}
var isAoEnabled = isAoAvailable
set(value) {
field = value && isAoAvailable
updateEnabled()
}
var aoMapSize: Float
get() = aoPipeline?.mapSize ?: 0f
set(value) { aoPipeline?.mapSize = value }
var isSsrEnabled = isSsrAvailable
set(value) {
field = value && isSsrAvailable
updateEnabled()
}
var reflectionMapSize: Float
get() = reflections?.mapSize ?: 0f
set(value) { reflections?.mapSize = value }
var isBloomEnabled = isBloomAvailable
set(value) {
field = value && isBloomAvailable
updateEnabled()
}
var bloomStrength: Float
get() = bloom?.bloomStrength ?: 0f
set(value) { bloom?.bloomStrength = value }
var bloomScale: Float
get() = bloom?.bloomScale ?: 0f
set(value) { bloom?.bloomScale = value }
var bloomMapSize: Int
get() = bloom?.desiredMapHeight ?: 0
set(value) { bloom?.desiredMapHeight = value }
init {
passes = createPasses()
shadowMaps = cfg.shadowMaps ?: createShadowMapsFromSceneLights()
lightingPassShader = cfg.pbrSceneShader ?:
PbrSceneShader(PbrSceneShader.DeferredPbrConfig().apply {
isScrSpcAmbientOcclusion = cfg.isWithAmbientOcclusion
isScrSpcReflections = cfg.isWithScreenSpaceReflections
maxLights = cfg.maxGlobalLights
shadowMaps += [email protected]
useImageBasedLighting(cfg.environmentMaps)
})
setupLightingPassContent()
if (cfg.isWithAmbientOcclusion) {
aoPipeline = AoPipeline.createDeferred(this)
passes.forEach { it.lightingPass.dependsOn(aoPipeline.denoisePass) }
lightingPassShader.scrSpcAmbientOcclusionMap(aoPipeline.aoMap)
onSwap += aoPipeline
} else {
aoPipeline = null
}
if (cfg.isWithScreenSpaceReflections) {
reflections = Reflections(cfg)
scene.addOffscreenPass(reflections.reflectionPass)
scene.addOffscreenPass(reflections.denoisePass)
passes.forEach { it.lightingPass.dependsOn(reflections.denoisePass) }
lightingPassShader.scrSpcReflectionMap(reflections.denoisePass.colorTexture)
onSwap += reflections
} else {
reflections = null
}
if (cfg.isWithBloom) {
bloom = Bloom(this, cfg)
scene.addOffscreenPass(bloom.thresholdPass)
scene.addOffscreenPass(bloom.blurPass)
onSwap += bloom
} else {
bloom = null
}
// make sure scene content is updated from scene.onUpdate, although sceneContent group is not a direct child of scene
scene.onUpdate += { ev ->
sceneContent.update(ev)
lightingPassContent.update(ev)
}
scene.onRenderScene += this::onRenderScene
scene.onDispose += { ctx ->
noSsrMap.dispose()
noBloomMap.dispose()
// dispose inactive deferred pass (active one is auto-disposed by scene)
inactivePass.let {
it.materialPass.dispose(ctx)
it.lightingPass.dispose(ctx)
}
}
}
fun createDefaultOutputQuad(): Mesh {
val outputShader = DeferredOutputShader(cfg, bloom?.bloomMap)
passes[0].lightingPass.onAfterDraw += { outputShader.setDeferredInput(passes[0]) }
passes[1].lightingPass.onAfterDraw += { outputShader.setDeferredInput(passes[1]) }
onConfigChange += {
outputShader.bloomMap(if (isBloomEnabled) bloom?.bloomMap else noBloomMap)
}
return textureMesh {
isFrustumChecked = false
generate {
rect {
mirrorTexCoordsY()
}
}
shader = outputShader
}
}
private fun createPasses(): List<DeferredPasses> {
val matPass0 = MaterialPass(this, "0")
val lightPass0 = PbrLightingPass(this, "0", matPass0)
val matPass1 = MaterialPass(this, "1")
val lightPass1 = PbrLightingPass(this, "1", matPass1)
scene.addOffscreenPass(matPass0)
scene.addOffscreenPass(lightPass0)
scene.addOffscreenPass(matPass1)
scene.addOffscreenPass(lightPass1)
return listOf(DeferredPasses(matPass0, lightPass0), DeferredPasses(matPass1, lightPass1))
}
private fun setupLightingPassContent() {
lightingPassContent.apply {
isFrustumChecked = false
+mesh(listOf(Attribute.POSITIONS, Attribute.TEXTURE_COORDS)) {
isFrustumChecked = false
generate {
rect {
size.set(1f, 1f)
mirrorTexCoordsY()
}
}
shader = lightingPassShader
}
+dynamicPointLights.mesh
+staticPointLights.mesh
}
}
private fun onRenderScene(ctx: KoolContext) {
if (isEnabled) {
swapPasses()
val vpW = (scene.mainRenderPass.viewport.width * renderResolution).roundToInt()
val vpH = (scene.mainRenderPass.viewport.height * renderResolution).roundToInt()
activePass.checkSize(vpW, vpH, ctx)
reflections?.checkSize(vpW, vpH, ctx)
aoPipeline?.checkSize(vpW, vpH, ctx)
bloom?.checkSize(vpW, vpH, ctx)
}
}
private fun swapPasses() {
activePassIndex++
val prev = inactivePass
val current = activePass
prev.isEnabled = false
current.isEnabled = true
lightingPassShader.setMaterialInput(current.materialPass)
dynamicPointLights.lightShader.setMaterialInput(current.materialPass)
staticPointLights.lightShader.setMaterialInput(current.materialPass)
for (i in spotLights.indices) {
spotLights[i].lightShader.setMaterialInput(current.materialPass)
}
for (i in onSwap.indices) {
onSwap[i].onSwap(prev, current)
}
}
fun setBloomBrightnessThresholds(lower: Float, upper: Float) {
bloom?.lowerThreshold = lower
bloom?.upperThreshold = upper
}
fun createSpotLights(maxSpotAngle: Float): DeferredSpotLights {
val lights = DeferredSpotLights(maxSpotAngle)
lightingPassContent += lights.mesh
mutSpotLights += lights
return lights
}
private fun updateEnabled() {
shadowMaps.forEach { it.isShadowMapEnabled = isEnabled }
aoPipeline?.isEnabled = isEnabled && isAoEnabled
passes.forEach { it.isEnabled = isEnabled }
reflections?.isEnabled = isEnabled && isSsrEnabled
lightingPassShader.scrSpcReflectionMap(if (isSsrEnabled) reflections?.reflectionMap else noSsrMap)
bloom?.isEnabled = isEnabled && isBloomEnabled
onConfigChange.forEach { it(this) }
}
private fun createShadowMapsFromSceneLights(): List<ShadowMap> {
val shadows = mutableListOf<ShadowMap>()
for (i in 0 until min(maxGlobalLights, scene.lighting.lights.size)) {
val light = scene.lighting.lights[i]
val shadowMap: ShadowMap? = when (light.type) {
Light.Type.DIRECTIONAL -> CascadedShadowMap(scene, i, drawNode = sceneContent)
Light.Type.SPOT -> SimpleShadowMap(scene, i, drawNode = sceneContent)
Light.Type.POINT -> {
logW { "Point light shadow maps not yet supported" }
null
}
}
shadowMap?.let { shadows += shadowMap }
}
return shadows
}
}
class DeferredPipelineConfig {
var isWithAmbientOcclusion = false
var isWithScreenSpaceReflections = false
var isWithImageBasedLighting = false
var isWithBloom = false
var isWithVignette = false
var isWithChromaticAberration = false
var maxGlobalLights = 4
var baseReflectionStep = 0.1f
var bloomKernelSize = 8
var bloomAvgDownSampling = true
var environmentMaps: EnvironmentMaps? = null
var shadowMaps: List<ShadowMap>? = null
var pbrSceneShader: PbrSceneShader? = null
var outputDepthTest = DepthCompareOp.LESS
fun useShadowMaps(shadowMaps: List<ShadowMap>?) {
this.shadowMaps = shadowMaps
}
fun useImageBasedLighting(environmentMaps: EnvironmentMaps?) {
this.environmentMaps = environmentMaps
isWithImageBasedLighting = environmentMaps != null
}
}
| apache-2.0 | 129dbcc96903c7bb3732e29c93f1c29c | 33.174051 | 125 | 0.631077 | 4.42945 | false | false | false | false |
korotyx/VirtualEntity | src/main/kotlin/com/korotyx/virtualentity/implemention/command/Parameter0.kt | 1 | 2710 | package com.korotyx.virtualentity.implemention.command
import com.korotyx.virtualentity.command.property.ColorSet
import com.korotyx.virtualentity.command.misc.Parameter
import com.korotyx.virtualentity.command.misc.ParameterType
import org.bukkit.command.CommandSender
import org.bukkit.command.ConsoleCommandSender
import org.bukkit.entity.Player
internal class Parameter0(private var param : String, private var type : ParameterType = ParameterType.OPTIONAL,
private var userMode : Boolean = true,
private var consoleMode : Boolean = true) : Parameter
{
companion object
{
val REQUIREMENT_FORMAT : String = ColorSet.PARAM_REQUIREMENT_COLORSET + "<%s>"
val OPTIONAL_FORMAT : String = ColorSet.PARAM_OPTIONAL_COLORSET + "[%s]"
val UNAVAILABLE_FORMAT : String = ColorSet.PARAM_UNAVAILABLE_COLORSET + "{%s}"
}
override fun getParam() : String = param
override fun serParam(param : String) { this.param = param }
override fun getParameterType(): ParameterType = type
override fun setParameterType(type : ParameterType) { this.type = type }
private var permission : String? = null
override fun hasPermission() : Boolean = this.permission != null
override fun getPermission() : String? = this.permission
override fun setUserMode(enable : Boolean) { userMode = enable}
override fun setConsoleMode(enable : Boolean) { consoleMode = enable}
private var childParameter : Parameter? = null
override fun setChild(param : Parameter) { this.childParameter = param }
override fun hasChild() : Boolean = childParameter != null
override fun getChild(): Parameter? = getChild(0)
override fun getChild(index : Int) : Parameter?
{
return if(index <= 0) childParameter
else
{
var param : Parameter? = this.getChild()
for(i in 0..index) param = this.getChild()
return param
}
}
override fun isAllowed(sender : CommandSender) : Boolean = when(sender)
{
is Player -> userMode
is ConsoleCommandSender -> consoleMode
else -> false
}
override fun length() : Int
{
var i = 0
var p : Parameter? = this
while(p != null)
{
p = p.getChild()
i++
}
return i
}
override fun getParameterLabel() : String = when(type)
{
ParameterType.REQUIREMENT -> String.format(REQUIREMENT_FORMAT, this.param)
ParameterType.OPTIONAL -> String.format(OPTIONAL_FORMAT, this.param)
ParameterType.UNAVAILABLE -> String.format(UNAVAILABLE_FORMAT, this.param)
}
} | mit | 52475815458f29aec4b14eaf57f35f65 | 35.146667 | 112 | 0.654244 | 4.554622 | false | false | false | false |
ingokegel/intellij-community | platform/lang-impl/src/com/intellij/analysis/problemsView/toolWindow/NodeComparator.kt | 10 | 1768 | // 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.analysis.problemsView.toolWindow
import com.intellij.openapi.util.text.StringUtil.naturalCompare
data class NodeComparator(
private val sortFoldersFirst: Boolean,
private val sortBySeverity: Boolean,
private val sortByName: Boolean)
: Comparator<Node?> {
override fun compare(node1: Node?, node2: Node?): Int {
if (node1 === node2) return 0
if (node1 == null) return +1
if (node2 == null) return -1
if (node1 is ProblemNode && node2 is ProblemNode) return compare(node1, node2)
if (node1 is ProblemNode) return -1 // problem node before other nodes
if (node2 is ProblemNode) return +1
if (sortFoldersFirst && node1 is FileNode && node2 is FileNode) {
if (node1.file.isDirectory && !node2.file.isDirectory) return -1
if (!node1.file.isDirectory && node2.file.isDirectory) return +1
}
return naturalCompare(node1.name, node2.name)
}
private fun compare(node1: ProblemNode, node2: ProblemNode): Int {
if (sortBySeverity) {
val result = node2.severity.compareTo(node1.severity)
if (result != 0) return result
}
return if (sortByName) {
val result = naturalCompare(node1.text, node2.text)
if (result != 0) result else comparePosition(node1, node2)
}
else {
val result = comparePosition(node1, node2)
if (result != 0) result else naturalCompare(node1.text, node2.text)
}
}
private fun comparePosition(node1: ProblemNode, node2: ProblemNode): Int {
val result = node1.line.compareTo(node2.line)
return if (result != 0) result else node1.column.compareTo(node2.column)
}
}
| apache-2.0 | 55a6fd7a018f04cd1ab5a5d82f578f42 | 38.288889 | 140 | 0.699661 | 3.615542 | false | false | false | false |
nsk-mironov/sento | sento-compiler/src/main/kotlin/io/mironov/sento/compiler/reflect/ClassSpec.kt | 1 | 2258 | package io.mironov.sento.compiler.reflect
import io.mironov.sento.compiler.annotations.AnnotationProxy
import io.mironov.sento.compiler.common.Opener
import io.mironov.sento.compiler.common.Types
import org.objectweb.asm.Type
import java.util.ArrayList
import java.util.Arrays
internal data class ClassSpec(
val access: Int,
val type: Type,
val parent: Type,
val interfaces: Collection<Type>,
val annotations: Collection<AnnotationSpec>,
val fields: Collection<FieldSpec>,
val methods: Collection<MethodSpec>,
val opener: Opener
) {
internal class Builder(val access: Int, val type: Type, val parent: Type, val opener: Opener) {
private val interfaces = ArrayList<Type>()
private val annotations = ArrayList<AnnotationSpec>()
private val fields = ArrayList<FieldSpec>()
private val methods = ArrayList<MethodSpec>()
fun interfaces(values: Collection<Type>): Builder = apply {
interfaces.addAll(values)
}
fun annotation(annotation: AnnotationSpec): Builder = apply {
annotations.add(annotation)
}
fun field(field: FieldSpec): Builder = apply {
fields.add(field)
}
fun method(method: MethodSpec): Builder = apply {
methods.add(method)
}
fun build(): ClassSpec {
return ClassSpec(access, type, parent, interfaces, annotations, fields, methods, opener)
}
}
fun getConstructor(vararg args: Type): MethodSpec? {
return getDeclaredMethod("<init>", *args)
}
fun getDeclaredMethod(name: String, descriptor: String): MethodSpec? {
return methods.firstOrNull {
it.name == name && it.type.descriptor == descriptor
}
}
fun getDeclaredMethod(name: String, vararg args: Type): MethodSpec? {
return methods.firstOrNull {
it.name == name && Arrays.equals(it.arguments, args)
}
}
fun getDeclaredField(name: String): FieldSpec? {
return fields.firstOrNull {
it.name == name
}
}
inline fun <reified A : Any> getAnnotation(): A? {
return getAnnotation(A::class.java)
}
fun <A> getAnnotation(annotation: Class<A>): A? {
return AnnotationProxy.create(annotation, annotations.firstOrNull {
it.type == Types.getAnnotationType(annotation)
} ?: return null)
}
}
| apache-2.0 | 473ab55f4519ad3cf6f48415636fa7b7 | 27.948718 | 97 | 0.691763 | 4.212687 | false | false | false | false |
siosio/intellij-community | platform/lang-impl/src/com/intellij/application/options/editor/EditorAppearanceConfigurable.kt | 1 | 7614 | // 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.application.options.editor
import com.intellij.codeInsight.actions.ReaderModeSettingsListener.Companion.createReaderModeComment
import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings
import com.intellij.codeInsight.documentation.render.DocRenderManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.ui.LafManager
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.application.ApplicationBundle
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.extensions.BaseExtensionPointName
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.options.BoundCompositeSearchableConfigurable
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.options.UnnamedConfigurable
import com.intellij.openapi.options.ex.ConfigurableWrapper
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.layout.*
import com.intellij.util.PlatformUtils
// @formatter:off
private val model = EditorSettingsExternalizable.getInstance()
private val daemonCodeAnalyzerSettings = DaemonCodeAnalyzerSettings.getInstance()
private val uiSettings = UISettings.instance
private val myCbBlinkCaret get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.caret.blinking.ms"), PropertyBinding(model::isBlinkCaret, model::setBlinkCaret))
private val myCbBlockCursor get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.use.block.caret"), PropertyBinding(model::isBlockCursor, model::setBlockCursor))
private val myCbRightMargin get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.right.margin"), PropertyBinding(model::isRightMarginShown, model::setRightMarginShown))
private val myCbShowLineNumbers get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.show.line.numbers"), PropertyBinding(model::isLineNumbersShown, model::setLineNumbersShown))
private val myCbShowMethodSeparators get() = CheckboxDescriptor(if (PlatformUtils.isDataGrip()) ApplicationBundle.message("checkbox.show.method.separators.DataGrip") else ApplicationBundle.message("checkbox.show.method.separators"), daemonCodeAnalyzerSettings::SHOW_METHOD_SEPARATORS.toBinding())
private val myWhitespacesCheckbox get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.show.whitespaces"), PropertyBinding(model::isWhitespacesShown, model::setWhitespacesShown))
private val myLeadingWhitespacesCheckBox get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.show.leading.whitespaces"), PropertyBinding(model::isLeadingWhitespacesShown, model::setLeadingWhitespacesShown))
private val myInnerWhitespacesCheckBox get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.show.inner.whitespaces"), PropertyBinding(model::isInnerWhitespacesShown, model::setInnerWhitespacesShown))
private val myTrailingWhitespacesCheckBox get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.show.trailing.whitespaces"), PropertyBinding(model::isTrailingWhitespacesShown, model::setTrailingWhitespacesShown))
private val myShowVerticalIndentGuidesCheckBox get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.show.indent.guides"), PropertyBinding(model::isIndentGuidesShown, model::setIndentGuidesShown))
private val myFocusModeCheckBox get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.highlight.only.current.declaration"), PropertyBinding(model::isFocusMode, model::setFocusMode))
private val myCbShowIntentionBulbCheckBox get() = CheckboxDescriptor(ApplicationBundle.message("checkbox.show.intention.bulb"), PropertyBinding(model::isShowIntentionBulb, model::setShowIntentionBulb))
private val myCodeLensCheckBox get() = CheckboxDescriptor(IdeBundle.message("checkbox.show.editor.preview.popup"), uiSettings::showEditorToolTip)
private val myRenderedDocCheckBox get() = CheckboxDescriptor(IdeBundle.message("checkbox.show.rendered.doc.comments"), PropertyBinding(model::isDocCommentRenderingEnabled, model::setDocCommentRenderingEnabled))
// @formatter:on
class EditorAppearanceConfigurable : BoundCompositeSearchableConfigurable<UnnamedConfigurable>(
ApplicationBundle.message("tab.editor.settings.appearance"),
"reference.settingsdialog.IDE.editor.appearance",
"editor.preferences.appearance"
), Configurable.WithEpDependencies {
override fun createPanel(): DialogPanel {
val model = EditorSettingsExternalizable.getInstance()
return panel {
row {
cell(isFullWidth = true) {
val cbBlinkCaret = checkBox(myCbBlinkCaret)
intTextField(model::getBlinkPeriod, model::setBlinkPeriod,
columns = 5,
range = EditorSettingsExternalizable.BLINKING_RANGE.asRange(),
step = 100).enableIf(cbBlinkCaret.selected)
}
}
row {
checkBox(myCbBlockCursor)
}
row {
checkBox(myCbRightMargin)
}
row {
checkBox(myCbShowLineNumbers)
}
row {
checkBox(myCbShowMethodSeparators)
}
row {
val cbWhitespace = checkBox(myWhitespacesCheckbox)
row {
checkBox(myLeadingWhitespacesCheckBox).enableIf(cbWhitespace.selected)
}
row {
checkBox(myInnerWhitespacesCheckBox).enableIf(cbWhitespace.selected)
}
row {
checkBox(myTrailingWhitespacesCheckBox).enableIf(cbWhitespace.selected)
}
}
row {
checkBox(myShowVerticalIndentGuidesCheckBox)
}
if (ApplicationManager.getApplication().isInternal) {
row {
checkBox(myFocusModeCheckBox)
}
}
row {
checkBox(myCbShowIntentionBulbCheckBox)
}
row {
checkBox(myCodeLensCheckBox)
}
fullRow {
checkBox(myRenderedDocCheckBox)
component(createReaderModeComment()).withLargeLeftGap()
}
for (configurable in configurables) {
appendDslConfigurableRow(configurable)
}
}
}
override fun createConfigurables(): List<UnnamedConfigurable> {
return ConfigurableWrapper.createConfigurables(EP_NAME)
}
override fun getDependencies(): Collection<BaseExtensionPointName<*>> {
return listOf(EP_NAME)
}
override fun apply() {
val showEditorTooltip = UISettings.instance.showEditorToolTip
val docRenderingEnabled = EditorSettingsExternalizable.getInstance().isDocCommentRenderingEnabled
super.apply()
EditorOptionsPanel.reinitAllEditors()
if (showEditorTooltip != UISettings.instance.showEditorToolTip) {
LafManager.getInstance().repaintUI()
uiSettings.fireUISettingsChanged()
}
if (docRenderingEnabled != EditorSettingsExternalizable.getInstance().isDocCommentRenderingEnabled) {
DocRenderManager.resetAllEditorsToDefaultState()
}
EditorOptionsPanel.restartDaemons()
ApplicationManager.getApplication().messageBus.syncPublisher(EditorOptionsListener.APPEARANCE_CONFIGURABLE_TOPIC).changesApplied()
}
companion object {
private val EP_NAME = ExtensionPointName.create<EditorAppearanceConfigurableEP>("com.intellij.editorAppearanceConfigurable")
}
}
| apache-2.0 | 6cb5ad360ed12f231fdfcc628b415618 | 53 | 314 | 0.75545 | 5.158537 | false | true | false | false |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/input/link/edit/LinkCommentEditPresenter.kt | 1 | 1339 | package io.github.feelfreelinux.wykopmobilny.ui.modules.input.link.edit
import io.github.feelfreelinux.wykopmobilny.api.WykopImageFile
import io.github.feelfreelinux.wykopmobilny.api.links.LinksApi
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.BaseInputView
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.InputPresenter
import io.github.feelfreelinux.wykopmobilny.utils.intoComposite
class LinkCommentEditPresenter(
val schedulers: Schedulers,
val linksApi: LinksApi
) : InputPresenter<BaseInputView>() {
var linkCommentId: Int = -1
private fun editLinkComment() {
view?.showProgressBar = true
linksApi.commentEdit(view?.textBody!!, linkCommentId)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe(
{ view?.exitActivity() },
{
view?.showProgressBar = false
view?.showErrorDialog(it)
})
.intoComposite(compositeObservable)
}
override fun sendWithPhoto(photo: WykopImageFile, containsAdultContent: Boolean) = editLinkComment()
override fun sendWithPhotoUrl(photo: String?, containsAdultContent: Boolean) = editLinkComment()
} | mit | d39b29054381d7695ef8c5a48d1df8b4 | 38.411765 | 104 | 0.716206 | 4.940959 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/codegen/coroutines/controlFlow_while1.kt | 4 | 1340 | /*
* Copyright 2010-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 codegen.coroutines.controlFlow_while1
import kotlin.test.*
import kotlin.coroutines.*
import kotlin.coroutines.intrinsics.*
open class EmptyContinuation(override val context: CoroutineContext = EmptyCoroutineContext) : Continuation<Any?> {
companion object : EmptyContinuation()
override fun resumeWith(result: Result<Any?>) { result.getOrThrow() }
}
suspend fun s1(): Int = suspendCoroutineUninterceptedOrReturn { x ->
println("s1")
x.resume(42)
COROUTINE_SUSPENDED
}
suspend fun s2(): Int = suspendCoroutineUninterceptedOrReturn { x ->
println("s2")
x.resumeWithException(Error("Error"))
COROUTINE_SUSPENDED
}
suspend fun s3(value: Int): Int = suspendCoroutineUninterceptedOrReturn { x ->
println("s3")
x.resume(value)
COROUTINE_SUSPENDED
}
fun f1(): Int {
println("f1")
return 117
}
fun f2(): Int {
println("f2")
return 1
}
fun f3(x: Int, y: Int): Int {
println("f3")
return x + y
}
fun builder(c: suspend () -> Unit) {
c.startCoroutine(EmptyContinuation)
}
@Test fun runTest() {
var result = 0
builder {
while (s3(result) < 3)
++result
}
println(result)
} | apache-2.0 | 9ff819fbd903d9cc4fefebe831db5ad9 | 19.953125 | 115 | 0.670896 | 3.839542 | false | false | false | false |
jwren/intellij-community | platform/platform-impl/src/com/intellij/toolWindow/ToolWindowDefaultLayoutManager.kt | 1 | 5341 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:Suppress("ReplaceGetOrSet")
package com.intellij.toolWindow
import com.intellij.openapi.components.*
import com.intellij.openapi.util.SimpleModificationTracker
import com.intellij.openapi.wm.ToolWindowAnchor
import com.intellij.openapi.wm.ToolWindowContentUiType
import com.intellij.openapi.wm.WindowManager
import com.intellij.openapi.wm.impl.*
import com.intellij.ui.ExperimentalUI
import kotlinx.serialization.Serializable
import java.awt.Rectangle
@Service(Service.Level.APP)
@State(name = "ToolWindowLayout", storages = [Storage(value = "window.state.xml", roamingType = RoamingType.DISABLED)])
internal class ToolWindowDefaultLayoutManager(private val isNewUi: Boolean)
: PersistentStateComponentWithModificationTracker<ToolWindowDefaultLayoutManager.ToolWindowLayoutStorageManagerState> {
companion object {
@JvmStatic
fun getInstance(): ToolWindowDefaultLayoutManager = service()
}
@Volatile
private var state = ToolWindowLayoutStorageManagerState()
private val tracker = SimpleModificationTracker()
// default layout
private var layout = DesktopLayout()
@Suppress("unused")
private constructor() : this(ExperimentalUI.isNewUI())
fun getLayoutCopy() = layout.copy()
fun setLayout(layout: DesktopLayout) {
this.layout = layout.copy()
tracker.incModificationCount()
val list = layout.getSortedList().map(::convertWindowStateToDescriptor)
state = if (ExperimentalUI.isNewUI()) state.copy(v2 = list) else state.copy(v1 = list)
}
override fun getState() = state
override fun getStateModificationCount() = tracker.modificationCount
@Suppress("DuplicatedCode")
override fun noStateLoaded() {
if (!isNewUi) {
(WindowManager.getInstance() as? WindowManagerImpl)?.oldLayout?.let {
setLayout(it)
return
}
}
loadDefaultLayout(isNewUi)
}
private fun loadDefaultLayout(isNewUi: Boolean) {
val provider = service<DefaultToolWindowLayoutProvider>()
val list = if (isNewUi) provider.createV2Layout() else provider.createV1Layout()
layout = convertDescriptorListToLayout(list)
state = if (isNewUi) state.copy(v2 = list) else state.copy(v1 = list)
}
override fun loadState(state: ToolWindowLayoutStorageManagerState) {
this.state = state
val list = if (isNewUi) state.v2 else state.v1
if (list.isEmpty()) {
loadDefaultLayout(isNewUi)
} else {
setLayout(convertDescriptorListToLayout(list))
}
}
@Serializable
data class ToolWindowLayoutStorageManagerState(
val v1: List<ToolWindowDescriptor> = emptyList(),
val v2: List<ToolWindowDescriptor> = emptyList(),
)
}
private fun convertWindowStateToDescriptor(it: WindowInfoImpl): ToolWindowDescriptor {
return ToolWindowDescriptor(
id = it.id!!,
order = it.order,
anchor = when(it.anchor) {
ToolWindowAnchor.TOP -> ToolWindowDescriptor.ToolWindowAnchor.TOP
ToolWindowAnchor.LEFT -> ToolWindowDescriptor.ToolWindowAnchor.LEFT
ToolWindowAnchor.BOTTOM -> ToolWindowDescriptor.ToolWindowAnchor.BOTTOM
ToolWindowAnchor.RIGHT -> ToolWindowDescriptor.ToolWindowAnchor.RIGHT
else -> throw IllegalStateException("Unsupported anchor ${it.anchor}")
},
isAutoHide = it.isAutoHide,
floatingBounds = it.floatingBounds?.let { listOf(it.x, it.y, it.width, it.height) },
isMaximized = it.isMaximized,
isActiveOnStart = it.isActiveOnStart,
isVisible = it.isVisible,
isShowStripeButton = it.isShowStripeButton,
weight = it.weight,
sideWeight = it.sideWeight,
isSplit = it.isSplit,
type = it.type,
internalType = it.type,
contentUiType = when(it.contentUiType) {
ToolWindowContentUiType.TABBED -> ToolWindowDescriptor.ToolWindowContentUiType.TABBED
ToolWindowContentUiType.COMBO -> ToolWindowDescriptor.ToolWindowContentUiType.COMBO
else -> throw IllegalStateException("Unsupported contentUiType ${it.contentUiType}")
},
)
}
@Suppress("DuplicatedCode")
private fun convertDescriptorListToLayout(list: List<ToolWindowDescriptor>): DesktopLayout {
return DesktopLayout(list.map {
WindowInfoImpl().apply {
id = it.id
order = it.order
anchor = when (it.anchor) {
ToolWindowDescriptor.ToolWindowAnchor.TOP -> ToolWindowAnchor.TOP
ToolWindowDescriptor.ToolWindowAnchor.LEFT -> ToolWindowAnchor.LEFT
ToolWindowDescriptor.ToolWindowAnchor.BOTTOM -> ToolWindowAnchor.BOTTOM
ToolWindowDescriptor.ToolWindowAnchor.RIGHT -> ToolWindowAnchor.RIGHT
}
isAutoHide = it.isAutoHide
floatingBounds = it.floatingBounds?.let { Rectangle(it.get(0), it.get(1), it.get(2), it.get(3)) }
isMaximized = it.isMaximized
isActiveOnStart = it.isActiveOnStart
isVisible = it.isVisible
isShowStripeButton = it.isShowStripeButton
weight = it.weight
sideWeight = it.sideWeight
isSplit = it.isSplit
type = it.type
internalType = it.type
contentUiType = when (it.contentUiType) {
ToolWindowDescriptor.ToolWindowContentUiType.TABBED -> ToolWindowContentUiType.TABBED
ToolWindowDescriptor.ToolWindowContentUiType.COMBO -> ToolWindowContentUiType.COMBO
}
}
})
} | apache-2.0 | 15df79edb2c2a2972d198a8c45244a36 | 33.688312 | 121 | 0.737502 | 4.680982 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/unifier/equivalence/controlStructures/doWhileRuntime.kt | 13 | 342 | fun foo(a: Int, b: Int) {
var t = a
<selection>do {
println((t))
t++
} while (t != (a + b))</selection>
var u = a
do {
println(t)
t++
} while (u != a + b)
while (t != a + b) {
println(t)
t++
}
do {
println(t)
t++
} while (t != a + b)
} | apache-2.0 | b33f536b80b672b8b81e21c0b8b333fe | 13.913043 | 38 | 0.339181 | 3.026549 | false | false | false | false |
androidx/androidx | credentials/credentials/src/androidTest/java/androidx/credentials/GetPublicKeyCredentialOptionTest.kt | 3 | 3190 | /*
* 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.credentials
import android.os.Bundle
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.SmallTest
import com.google.common.truth.Truth.assertThat
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@SmallTest
class GetPublicKeyCredentialOptionTest {
@Test
fun constructor_emptyJson_throwsIllegalArgumentException() {
Assert.assertThrows(
"Expected empty Json to throw error",
IllegalArgumentException::class.java
) { GetPublicKeyCredentialOption("") }
}
@Test
fun constructor_success() {
GetPublicKeyCredentialOption(
"{\"hi\":{\"there\":{\"lol\":\"Value\"}}}"
)
}
@Test
fun constructor_setsAllowHybridToTrueByDefault() {
val getPublicKeyCredentialOpt = GetPublicKeyCredentialOption(
"JSON"
)
val allowHybridActual = getPublicKeyCredentialOpt.allowHybrid
assertThat(allowHybridActual).isTrue()
}
@Test
fun constructor_setsAllowHybridFalse() {
val allowHybridExpected = false
val getPublicKeyCredentialOpt = GetPublicKeyCredentialOption(
"JSON", allowHybridExpected
)
val allowHybridActual = getPublicKeyCredentialOpt.allowHybrid
assertThat(allowHybridActual).isEqualTo(allowHybridExpected)
}
@Test
fun getter_requestJson_success() {
val testJsonExpected = "{\"hi\":{\"there\":{\"lol\":\"Value\"}}}"
val createPublicKeyCredentialReq = GetPublicKeyCredentialOption(testJsonExpected)
val testJsonActual = createPublicKeyCredentialReq.requestJson
assertThat(testJsonActual).isEqualTo(testJsonExpected)
}
@Test
fun getter_frameworkProperties_success() {
val requestJsonExpected = "{\"hi\":{\"there\":{\"lol\":\"Value\"}}}"
val allowHybridExpected = false
val expectedData = Bundle()
expectedData.putString(
GetPublicKeyCredentialOption.BUNDLE_KEY_REQUEST_JSON,
requestJsonExpected
)
expectedData.putBoolean(
GetPublicKeyCredentialOption.BUNDLE_KEY_ALLOW_HYBRID,
allowHybridExpected
)
val option = GetPublicKeyCredentialOption(requestJsonExpected, allowHybridExpected)
assertThat(option.type).isEqualTo(PublicKeyCredential.TYPE_PUBLIC_KEY_CREDENTIAL)
assertThat(equals(option.data, expectedData)).isTrue()
assertThat(option.requireSystemProvider).isFalse()
}
} | apache-2.0 | b7b8965ab527079b3acf1962420a4220 | 33.311828 | 91 | 0.697492 | 4.73997 | false | true | false | false |
nimakro/tornadofx | src/test/kotlin/tornadofx/tests/ScopeTest.kt | 1 | 1389 | package tornadofx.tests
import javafx.stage.Stage
import org.junit.Test
import org.testfx.api.FxToolkit
import tornadofx.*
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
import kotlin.test.assertTrue
class ScopeTest {
val primaryStage: Stage = FxToolkit.registerPrimaryStage()
class PersonModel() : ItemViewModel<Person>()
class PersonScope : Scope() {
val model = PersonModel()
}
class C : Controller()
class F : Fragment() {
override val root = label()
override val scope = super.scope as PersonScope
val c : C by inject()
val vm: VM by inject()
}
class VM : ViewModel(), ScopedInstance
@Test
fun instanceCheck() {
val scope1 = PersonScope()
val obj_a = find<C>(scope1)
val obj_a1 = find<C>(scope1)
assertEquals(obj_a, obj_a1)
val scope2 = PersonScope()
val obj_a2 = find<C>(scope2)
assertNotEquals(obj_a, obj_a2)
}
@Test
fun controllerAndViewModelPerScopeInInjectedFragments() {
val scope1 = PersonScope()
val f1 = find<F>(scope1)
val f2 = find<F>(scope1)
assertEquals(f1.c, f2.c)
assertEquals(f1.vm, f2.vm)
val scope2 = PersonScope()
val f3 = find<F>(scope2)
assertNotEquals(f1.c, f3.c)
assertNotEquals(f1.vm, f3.vm)
}
} | apache-2.0 | a364c19b6b41e94bf3ce892014bfda1a | 20.060606 | 62 | 0.61915 | 3.733871 | false | true | false | false |
GunoH/intellij-community | plugins/built-in-help/src/com/jetbrains/builtInHelp/search/HelpSearch.kt | 2 | 3479 | // 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.jetbrains.builtInHelp.search
import com.google.gson.Gson
import com.intellij.openapi.application.ApplicationInfo
import com.intellij.openapi.diagnostic.Logger
import org.apache.commons.compress.utils.IOUtils
import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.index.DirectoryReader
import org.apache.lucene.queryparser.classic.QueryParser
import org.apache.lucene.search.IndexSearcher
import org.apache.lucene.search.Query
import org.apache.lucene.search.TopScoreDocCollector
import org.apache.lucene.search.highlight.Highlighter
import org.apache.lucene.search.highlight.QueryScorer
import org.apache.lucene.search.highlight.Scorer
import org.apache.lucene.store.FSDirectory
import org.jetbrains.annotations.NotNull
import org.jetbrains.annotations.NonNls
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
class HelpSearch {
companion object {
private val resources = arrayOf("_0.cfe", "_0.cfs", "_0.si", "segments_1")
@NonNls
val PREFIX = "/search/"
private val NOT_FOUND = "[]"
private val analyzer: StandardAnalyzer = StandardAnalyzer()
@NotNull
fun search(query: String, maxHits: Int): String {
val indexDir: Path? = Files.createTempDirectory("search-index")
var indexDirectory: FSDirectory? = null
var reader: DirectoryReader? = null
if (indexDir != null)
try {
for (resourceName in resources) {
val input = HelpSearch::class.java.getResourceAsStream(
PREFIX + resourceName)
val fos = FileOutputStream(Paths.get(indexDir.toAbsolutePath().toString(), resourceName).toFile())
IOUtils.copy(input, fos)
fos.flush()
fos.close()
input.close()
}
indexDirectory = FSDirectory.open(indexDir)
reader = DirectoryReader.open(indexDirectory)
ApplicationInfo.getInstance()
val searcher = IndexSearcher(reader)
val collector: TopScoreDocCollector = TopScoreDocCollector.create(maxHits, maxHits)
val q: Query = QueryParser("contents", analyzer).parse(query)
searcher.search(q, collector)
val hits = collector.topDocs().scoreDocs
val scorer: Scorer = QueryScorer(q)
val highlighter = Highlighter(scorer)
val results = ArrayList<HelpSearchResult>()
for (i in hits.indices) {
val doc = searcher.doc(hits[i].doc)
results.add(
HelpSearchResult(i, doc.get("filename"), highlighter.getBestFragment(
analyzer, "contents", doc.get("contents")) + "...",
doc.get("title"), listOf("webhelp")))
}
val searchResults = HelpSearchResults(results)
return if (searchResults.results.isEmpty()) NOT_FOUND else Gson().toJson(searchResults)
}
catch (e: Exception) {
Logger.getInstance(HelpSearch::class.java).error("Error searching help for $query", e)
}
finally {
indexDirectory?.close()
reader?.close()
val tempFiles = indexDir.toFile().listFiles()
tempFiles?.forEach { it.delete() }
Files.delete(indexDir)
}
return NOT_FOUND
}
}
} | apache-2.0 | 0edbfda670f541e3f3dd7a24f3285427 | 35.631579 | 140 | 0.67002 | 4.403797 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/kotlinPsiElementMapping.kt | 2 | 33895 | // 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.uast.kotlin
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.*
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
import org.jetbrains.uast.expressions.UInjectionHost
import org.jetbrains.uast.kotlin.psi.*
import org.jetbrains.uast.psi.UElementWithLocation
import org.jetbrains.uast.util.ClassSet
import org.jetbrains.uast.util.classSetOf
import org.jetbrains.uast.util.emptyClassSet
private val checkCanConvert = Registry.`is`("kotlin.uast.use.psi.type.precheck", true)
fun canConvert(element: PsiElement, targets: Array<out Class<out UElement>>): Boolean {
if (!checkCanConvert) return true
val psiElementClass = element.javaClass
if (targets.any { getPossibleSourceTypes(it).let { psiElementClass in it } })
return true
val ktOriginalCls = (element as? KtLightElementBase)?.kotlinOrigin?.javaClass ?: return false
return targets.any { getPossibleSourceTypes(it).let { ktOriginalCls in it } }
}
fun getPossibleSourceTypes(uastType: Class<out UElement>) =
possibleSourceTypes[uastType] ?: emptyClassSet()
/**
* For every [UElement] subtype states from which [PsiElement] subtypes it can be obtained.
*
* This map is machine generated by `KotlinUastMappingsAccountantOverLargeProjectTest`
*/
@Suppress("DEPRECATION", "RemoveExplicitTypeArguments", "DuplicatedCode")
private val possibleSourceTypes = mapOf<Class<*>, ClassSet<PsiElement>>(
UAnchorOwner::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtClass::class.java,
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtFile::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
KtTypeReference::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UAnnotated::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KtAnnotatedExpression::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDestructuringDeclarationEntry::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtFile::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UAnnotation::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtLightAnnotationForSourceEntry::class.java
),
UAnnotationEx::class.java to classSetOf<PsiElement>(
KtAnnotationEntry::class.java,
KtCallExpression::class.java,
KtLightAnnotationForSourceEntry::class.java
),
UAnnotationMethod::class.java to classSetOf<PsiElement>(
KtLightDeclaration::class.java,
KtParameter::class.java
),
UAnonymousClass::class.java to classSetOf<PsiElement>(
KtLightClass::class.java,
KtObjectDeclaration::class.java
),
UArrayAccessExpression::class.java to classSetOf<PsiElement>(
KtArrayAccessExpression::class.java,
KtBlockStringTemplateEntry::class.java
),
UBinaryExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionWithExpression::class.java
),
UBinaryExpressionWithType::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtIsExpression::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java
),
UBlockExpression::class.java to classSetOf<PsiElement>(
KtBlockExpression::class.java
),
UBreakExpression::class.java to classSetOf<PsiElement>(
KtBreakExpression::class.java
),
UCallExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtStringTemplateExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtWhenConditionWithExpression::class.java,
KtLightPsiArrayInitializerMemberValue::class.java
),
UCallExpressionEx::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtStringTemplateExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtWhenConditionWithExpression::class.java,
KtLightPsiArrayInitializerMemberValue::class.java
),
UCallableReferenceExpression::class.java to classSetOf<PsiElement>(
KtCallableReferenceExpression::class.java
),
UCatchClause::class.java to classSetOf<PsiElement>(
KtCatchClause::class.java
),
UClass::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtFile::class.java,
KtLightClass::class.java,
KtObjectDeclaration::class.java
),
UClassInitializer::class.java to classSetOf<PsiElement>(
),
UClassInitializerEx::class.java to classSetOf<PsiElement>(
),
UClassLiteralExpression::class.java to classSetOf<PsiElement>(
KtClassLiteralExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UComment::class.java to classSetOf<PsiElement>(
PsiComment::class.java
),
UContinueExpression::class.java to classSetOf<PsiElement>(
KtContinueExpression::class.java
),
UDeclaration::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtFile::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
KtTypeReference::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UDeclarationEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UDeclarationsExpression::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtDestructuringDeclaration::class.java,
KtEnumEntry::class.java,
KtFunctionLiteral::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtParameterList::class.java,
KtPrimaryConstructor::class.java,
KtSecondaryConstructor::class.java
),
UDoWhileExpression::class.java to classSetOf<PsiElement>(
KtDoWhileExpression::class.java
),
UElement::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCatchClause::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDestructuringDeclarationEntry::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtFile::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtImportDirective::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightClass::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java,
LeafPsiElement::class.java,
PsiComment::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UElementWithLocation::class.java to classSetOf<PsiElement>(
),
UEnumConstant::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java
),
UEnumConstantEx::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java
),
UExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtArrayAccessExpression::class.java,
KtBinaryExpression::class.java,
KtBinaryExpressionWithTypeRHS::class.java,
KtBlockExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtBreakExpression::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtClass::class.java,
KtClassBody::class.java,
KtClassInitializer::class.java,
KtClassLiteralExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstantExpression::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationCall::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtContinueExpression::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtDestructuringDeclaration::class.java,
KtDoWhileExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtForExpression::class.java,
KtFunctionLiteral::class.java,
KtIfExpression::class.java,
KtIsExpression::class.java,
KtLabelReferenceExpression::class.java,
KtLabeledExpression::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightDeclaration::class.java,
KtLightField::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtNameReferenceExpression::class.java,
KtNamedFunction::class.java,
KtObjectDeclaration::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtParameter::class.java,
KtParameterList::class.java,
KtParenthesizedExpression::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtReturnExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtSecondaryConstructor::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtThrowExpression::class.java,
KtTryExpression::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java,
KtTypeReference::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionIsPattern::class.java,
KtWhenConditionWithExpression::class.java,
KtWhenEntry::class.java,
KtWhenExpression::class.java,
KtWhileExpression::class.java
),
UExpressionList::class.java to classSetOf<PsiElement>(
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtClassBody::class.java,
KtDelegatedSuperTypeEntry::class.java,
KtWhenConditionWithExpression::class.java
),
UField::class.java to classSetOf<PsiElement>(
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtParameter::class.java,
KtProperty::class.java
),
UFieldEx::class.java to classSetOf<PsiElement>(
KtLightFieldForSourceDeclarationSupport::class.java,
KtParameter::class.java,
KtProperty::class.java
),
UFile::class.java to classSetOf<PsiElement>(
FakeFileForLightClass::class.java,
KtFile::class.java
),
UForEachExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtForExpression::class.java
),
UForExpression::class.java to classSetOf<PsiElement>(
),
UIdentifier::class.java to classSetOf<PsiElement>(
LeafPsiElement::class.java
),
UIfExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtIfExpression::class.java
),
UImportStatement::class.java to classSetOf<PsiElement>(
KtImportDirective::class.java
),
UInjectionHost::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UInstanceExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtSuperExpression::class.java,
KtThisExpression::class.java
),
UJumpExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBreakExpression::class.java,
KtContinueExpression::class.java,
KtReturnExpression::class.java
),
ULabeled::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtLabeledExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtSuperExpression::class.java,
KtThisExpression::class.java
),
ULabeledExpression::class.java to classSetOf<PsiElement>(
KtLabeledExpression::class.java
),
ULambdaExpression::class.java to classSetOf<PsiElement>(
KtFunctionLiteral::class.java,
KtLambdaArgument::class.java,
KtLambdaExpression::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtPrimaryConstructor::class.java
),
ULiteralExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtConstantExpression::class.java,
KtEscapeStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtLiteralStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
ULocalVariable::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtProperty::class.java,
UastKotlinPsiVariable::class.java
),
ULocalVariableEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtProperty::class.java,
UastKotlinPsiVariable::class.java
),
ULoopExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtDoWhileExpression::class.java,
KtForExpression::class.java,
KtWhileExpression::class.java
),
UMethod::class.java to classSetOf<PsiElement>(
KtClass::class.java,
KtLightDeclaration::class.java,
KtNamedFunction::class.java,
KtParameter::class.java,
KtPrimaryConstructor::class.java,
KtProperty::class.java,
KtPropertyAccessor::class.java,
KtSecondaryConstructor::class.java,
UastFakeLightMethod::class.java,
UastFakeLightPrimaryConstructor::class.java
),
UMultiResolvable::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtImportDirective::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtObjectLiteralExpression::class.java,
KtPostfixExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UNamedExpression::class.java to classSetOf<PsiElement>(
),
UObjectLiteralExpression::class.java to classSetOf<PsiElement>(
KtObjectLiteralExpression::class.java,
KtSuperTypeCallEntry::class.java
),
UParameter::class.java to classSetOf<PsiElement>(
KtLightParameter::class.java,
KtParameter::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java
),
UParameterEx::class.java to classSetOf<PsiElement>(
KtLightParameter::class.java,
KtParameter::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java
),
UParenthesizedExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtParenthesizedExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UPolyadicExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtLightPsiArrayInitializerMemberValue::class.java,
KtLightPsiLiteral::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionInRange::class.java,
KtWhenConditionWithExpression::class.java
),
UPostfixExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtPostfixExpression::class.java
),
UPrefixExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtPrefixExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UQualifiedReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtDotQualifiedExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallableReferenceExpression::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtLabelReferenceExpression::class.java,
KtNameReferenceExpression::class.java,
KtOperationReferenceExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UResolvable::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtAnnotationEntry::class.java,
KtBlockStringTemplateEntry::class.java,
KtCallExpression::class.java,
KtCallableReferenceExpression::class.java,
KtCollectionLiteralExpression::class.java,
KtConstructorDelegationCall::class.java,
KtDotQualifiedExpression::class.java,
KtEnumEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtImportDirective::class.java,
KtLabelReferenceExpression::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtLightField::class.java,
KtNameReferenceExpression::class.java,
KtObjectLiteralExpression::class.java,
KtOperationReferenceExpression::class.java,
KtPostfixExpression::class.java,
KtSafeQualifiedExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtSuperExpression::class.java,
KtSuperTypeCallEntry::class.java,
KtThisExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UReturnExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtReturnExpression::class.java
),
USimpleNameReferenceExpression::class.java to classSetOf<PsiElement>(
KDocName::class.java,
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtEnumEntrySuperclassReferenceExpression::class.java,
KtLabelReferenceExpression::class.java,
KtNameReferenceExpression::class.java,
KtOperationReferenceExpression::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtStringTemplateExpression::class.java,
KtWhenConditionWithExpression::class.java
),
USuperExpression::class.java to classSetOf<PsiElement>(
KtSuperExpression::class.java
),
USwitchClauseExpression::class.java to classSetOf<PsiElement>(
KtWhenEntry::class.java
),
USwitchClauseExpressionWithBody::class.java to classSetOf<PsiElement>(
KtWhenEntry::class.java
),
USwitchExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtWhenExpression::class.java
),
UThisExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtSimpleNameStringTemplateEntry::class.java,
KtThisExpression::class.java
),
UThrowExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtThrowExpression::class.java
),
UTryExpression::class.java to classSetOf<PsiElement>(
KtBlockStringTemplateEntry::class.java,
KtTryExpression::class.java
),
UTypeReferenceExpression::class.java to classSetOf<PsiElement>(
KtTypeReference::class.java
),
UUnaryExpression::class.java to classSetOf<PsiElement>(
KtAnnotatedExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtPostfixExpression::class.java,
KtPrefixExpression::class.java,
KtWhenConditionWithExpression::class.java
),
UVariable::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UVariableEx::class.java to classSetOf<PsiElement>(
KtDestructuringDeclarationEntry::class.java,
KtEnumEntry::class.java,
KtLightField::class.java,
KtLightFieldForSourceDeclarationSupport::class.java,
KtLightParameter::class.java,
KtParameter::class.java,
KtProperty::class.java,
KtTypeReference::class.java,
UastKotlinPsiParameter::class.java,
UastKotlinPsiParameterBase::class.java,
UastKotlinPsiVariable::class.java
),
UWhileExpression::class.java to classSetOf<PsiElement>(
KtWhileExpression::class.java
),
UYieldExpression::class.java to classSetOf<PsiElement>(
),
UastEmptyExpression::class.java to classSetOf<PsiElement>(
KtBinaryExpression::class.java,
KtBlockStringTemplateEntry::class.java,
KtClass::class.java,
KtEnumEntry::class.java,
KtLightAnnotationForSourceEntry::class.java,
KtObjectDeclaration::class.java,
KtStringTemplateExpression::class.java
),
UnknownKotlinExpression::class.java to classSetOf<PsiElement>(
KtClassInitializer::class.java,
KtConstructorCalleeExpression::class.java,
KtConstructorDelegationReferenceExpression::class.java,
KtLightDeclaration::class.java,
KtParameter::class.java,
KtPropertyAccessor::class.java,
KtScript::class.java,
KtScriptInitializer::class.java,
KtTypeAlias::class.java,
KtTypeParameter::class.java
)
)
| apache-2.0 | 77e2523d7c90ea610352f78eb2c4ee7c | 39.690276 | 120 | 0.702641 | 5.5831 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/parameterInfo/TypeHints.kt | 1 | 6555 | // 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.parameterInfo
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.codeInsight.hints.InlayInfoDetails
import org.jetbrains.kotlin.idea.codeInsight.hints.TextInlayInfoDetail
import org.jetbrains.kotlin.idea.core.util.isMultiLine
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.intentions.SpecifyTypeExplicitlyIntention
import org.jetbrains.kotlin.idea.refactoring.getLineNumber
import org.jetbrains.kotlin.idea.references.resolveMainReferenceToDescriptors
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.sam.SamConstructorDescriptor
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.containsError
import org.jetbrains.kotlin.types.typeUtil.immediateSupertypes
import org.jetbrains.kotlin.types.typeUtil.isEnum
import org.jetbrains.kotlin.types.typeUtil.isUnit
fun providePropertyTypeHint(elem: PsiElement): List<InlayInfoDetails> {
(elem as? KtCallableDeclaration)?.let { property ->
property.nameIdentifier?.let { ident ->
provideTypeHint(property, ident.endOffset)?.let { return listOf(it) }
}
}
return emptyList()
}
fun provideTypeHint(element: KtCallableDeclaration, offset: Int): InlayInfoDetails? {
var type: KotlinType = SpecifyTypeExplicitlyIntention.getTypeForDeclaration(element).unwrap()
if (type.containsError()) return null
val declarationDescriptor = type.constructor.declarationDescriptor
val name = declarationDescriptor?.name
if (name == SpecialNames.NO_NAME_PROVIDED) {
if (element is KtProperty && element.isLocal) {
// for local variables, an anonymous object type is not collapsed to its supertype,
// so showing the supertype will be misleading
return null
}
type = type.immediateSupertypes().singleOrNull() ?: return null
} else if (name?.isSpecial == true) {
return null
}
if (element is KtProperty && element.isLocal && type.isUnit() && element.isMultiLine()) {
val propertyLine = element.getLineNumber()
val equalsTokenLine = element.equalsToken?.getLineNumber() ?: -1
val initializerLine = element.initializer?.getLineNumber() ?: -1
if (propertyLine == equalsTokenLine && propertyLine != initializerLine) {
val indentBeforeProperty = (element.prevSibling as? PsiWhiteSpace)?.text?.substringAfterLast('\n')
val indentBeforeInitializer = (element.initializer?.prevSibling as? PsiWhiteSpace)?.text?.substringAfterLast('\n')
if (indentBeforeProperty == indentBeforeInitializer) {
return null
}
}
}
return if (isUnclearType(type, element)) {
val settings = element.containingKtFile.kotlinCustomSettings
val renderedType = HintsTypeRenderer.getInlayHintsTypeRenderer(element.analyze(), element).renderType(type)
val prefix = buildString {
if (settings.SPACE_BEFORE_TYPE_COLON) {
append(" ")
}
append(":")
if (settings.SPACE_AFTER_TYPE_COLON) {
append(" ")
}
}
val inlayInfo = InlayInfo(
text = "", offset = offset,
isShowOnlyIfExistedBefore = false, isFilterByBlacklist = true, relatesToPrecedingText = true
)
return InlayInfoDetails(inlayInfo, listOf(TextInlayInfoDetail(prefix)) + renderedType)
} else {
null
}
}
private fun isUnclearType(type: KotlinType, element: KtCallableDeclaration): Boolean {
if (element !is KtProperty) return true
val initializer = element.initializer ?: return true
if (initializer is KtConstantExpression || initializer is KtStringTemplateExpression) return false
if (initializer is KtUnaryExpression && initializer.baseExpression is KtConstantExpression) return false
if (isConstructorCall(initializer)) {
return false
}
if (initializer is KtDotQualifiedExpression) {
val selectorExpression = initializer.selectorExpression
if (type.isEnum()) {
// Do not show type for enums if initializer has enum entry with explicit enum name: val p = Enum.ENTRY
val enumEntryDescriptor: DeclarationDescriptor? = selectorExpression?.resolveMainReferenceToDescriptors()?.singleOrNull()
if (enumEntryDescriptor != null && DescriptorUtils.isEnumEntry(enumEntryDescriptor)) {
return false
}
}
if (initializer.receiverExpression.isClassOrPackageReference() && isConstructorCall(selectorExpression)) {
return false
}
}
return true
}
private fun isConstructorCall(initializer: KtExpression?): Boolean {
if (initializer is KtCallExpression) {
val resolvedCall = initializer.resolveToCall(BodyResolveMode.FULL)
val resolvedDescriptor = resolvedCall?.candidateDescriptor
if (resolvedDescriptor is SamConstructorDescriptor) {
return true
}
if (resolvedDescriptor is ConstructorDescriptor &&
(resolvedDescriptor.constructedClass.declaredTypeParameters.isEmpty() || initializer.typeArgumentList != null)
) {
return true
}
return false
}
return false
}
private fun KtExpression.isClassOrPackageReference(): Boolean =
when (this) {
is KtNameReferenceExpression -> this.resolveMainReferenceToDescriptors().singleOrNull()
.let { it is ClassDescriptor || it is PackageViewDescriptor }
is KtDotQualifiedExpression -> this.selectorExpression?.isClassOrPackageReference() ?: false
else -> false
}
| apache-2.0 | 3167c36692675b54bbd02dad0ff87289 | 42.993289 | 158 | 0.720671 | 5.218949 | false | false | false | false |
smmribeiro/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/lang/MarkdownFileViewProvider.kt | 8 | 1967 | // 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.intellij.plugins.markdown.lang
import com.intellij.lang.Language
import com.intellij.lang.LanguageParserDefinitions
import com.intellij.lang.html.HTMLLanguage
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.impl.source.PsiFileImpl
import com.intellij.psi.templateLanguages.TemplateLanguageFileViewProvider
import org.intellij.plugins.markdown.lang.MarkdownElementTypes.MARKDOWN_TEMPLATE_DATA
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownFile
class MarkdownFileViewProvider(manager: PsiManager, virtualFile: VirtualFile, eventSystemEnabled: Boolean)
: MultiplePsiFilesPerDocumentFileViewProvider(manager, virtualFile, eventSystemEnabled), TemplateLanguageFileViewProvider {
private val relevantLanguages = HashSet<Language>()
init {
relevantLanguages.add(baseLanguage)
relevantLanguages.add(templateDataLanguage)
}
override fun createFile(lang: Language): PsiFile? {
if (lang === MarkdownLanguage.INSTANCE) {
return MarkdownFile(this)
}
val parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(lang) ?: return null
val psiFile = parserDefinition.createFile(this)
if (lang === templateDataLanguage && psiFile is PsiFileImpl) {
psiFile.contentElementType = MARKDOWN_TEMPLATE_DATA
}
return psiFile
}
override fun getBaseLanguage(): Language = MarkdownLanguage.INSTANCE
override fun getLanguages(): Set<Language> = relevantLanguages
override fun getTemplateDataLanguage(): Language = HTMLLanguage.INSTANCE
override fun cloneInner(fileCopy: VirtualFile): MultiplePsiFilesPerDocumentFileViewProvider =
MarkdownFileViewProvider(manager, fileCopy, false)
}
| apache-2.0 | 97020c265340b56e7c80249d79487edd | 39.142857 | 140 | 0.807829 | 4.844828 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/scratch/ui/ScratchTopPanel.kt | 6 | 4720 | // 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.scratch.ui
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import org.jetbrains.kotlin.idea.KotlinJvmBundle
import org.jetbrains.kotlin.idea.scratch.ScratchFile
import org.jetbrains.kotlin.idea.scratch.ScratchFileAutoRunner
import org.jetbrains.kotlin.idea.scratch.actions.ClearScratchAction
import org.jetbrains.kotlin.idea.scratch.actions.RunScratchAction
import org.jetbrains.kotlin.idea.scratch.actions.StopScratchAction
import org.jetbrains.kotlin.idea.scratch.output.ScratchOutputHandlerAdapter
class ScratchTopPanel(val scratchFile: ScratchFile) {
private val moduleChooserAction: ModulesComboBoxAction = ModulesComboBoxAction(scratchFile)
val actionsToolbar: ActionToolbar
init {
setupTopPanelUpdateHandlers()
val toolbarGroup = DefaultActionGroup().apply {
add(RunScratchAction())
add(StopScratchAction())
addSeparator()
add(ClearScratchAction())
addSeparator()
add(moduleChooserAction)
add(IsMakeBeforeRunAction())
addSeparator()
add(IsInteractiveCheckboxAction())
addSeparator()
add(IsReplCheckboxAction())
}
actionsToolbar = ActionManager.getInstance().createActionToolbar(ActionPlaces.EDITOR_TOOLBAR, toolbarGroup, true)
}
private fun setupTopPanelUpdateHandlers() {
scratchFile.addModuleListener { _, _ -> updateToolbar() }
val toolbarHandler = createUpdateToolbarHandler()
scratchFile.replScratchExecutor?.addOutputHandler(toolbarHandler)
scratchFile.compilingScratchExecutor?.addOutputHandler(toolbarHandler)
}
private fun createUpdateToolbarHandler(): ScratchOutputHandlerAdapter {
return object : ScratchOutputHandlerAdapter() {
override fun onStart(file: ScratchFile) {
updateToolbar()
}
override fun onFinish(file: ScratchFile) {
updateToolbar()
}
}
}
private fun updateToolbar() {
ApplicationManager.getApplication().invokeLater {
actionsToolbar.updateActionsImmediately()
}
}
private inner class IsMakeBeforeRunAction : SmallBorderCheckboxAction(KotlinJvmBundle.message("scratch.make.before.run.checkbox")) {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isVisible = scratchFile.module != null
e.presentation.description = scratchFile.module?.let { selectedModule ->
KotlinJvmBundle.message("scratch.make.before.run.checkbox.description", selectedModule.name)
}
}
override fun isSelected(e: AnActionEvent): Boolean {
return scratchFile.options.isMakeBeforeRun
}
override fun setSelected(e: AnActionEvent, isMakeBeforeRun: Boolean) {
scratchFile.saveOptions { copy(isMakeBeforeRun = isMakeBeforeRun) }
}
}
private inner class IsInteractiveCheckboxAction : SmallBorderCheckboxAction(
text = KotlinJvmBundle.message("scratch.is.interactive.checkbox"),
description = KotlinJvmBundle.message("scratch.is.interactive.checkbox.description", ScratchFileAutoRunner.AUTO_RUN_DELAY_IN_SECONDS)
) {
override fun isSelected(e: AnActionEvent): Boolean {
return scratchFile.options.isInteractiveMode
}
override fun setSelected(e: AnActionEvent, isInteractiveMode: Boolean) {
scratchFile.saveOptions { copy(isInteractiveMode = isInteractiveMode) }
}
}
private inner class IsReplCheckboxAction : SmallBorderCheckboxAction(
text = KotlinJvmBundle.message("scratch.is.repl.checkbox"),
description = KotlinJvmBundle.message("scratch.is.repl.checkbox.description")
) {
override fun isSelected(e: AnActionEvent): Boolean {
return scratchFile.options.isRepl
}
override fun setSelected(e: AnActionEvent, isRepl: Boolean) {
scratchFile.saveOptions { copy(isRepl = isRepl) }
if (isRepl) {
// TODO start REPL process when checkbox is selected to speed up execution
// Now it is switched off due to KT-18355: REPL process is keep alive if no command is executed
//scratchFile.replScratchExecutor?.start()
} else {
scratchFile.replScratchExecutor?.stop()
}
}
}
}
| apache-2.0 | 5f46e507526c485523e0dde4efb7e18d | 39.34188 | 158 | 0.685169 | 5.285554 | false | false | false | false |
marverenic/Paper | app/src/main/java/com/marverenic/reader/ui/common/article/StreamContinuationViewModel.kt | 1 | 723 | package com.marverenic.reader.ui.common.article
import android.databinding.BaseObservable
import android.databinding.Bindable
import com.marverenic.reader.BR
import com.marverenic.reader.model.Stream
class StreamContinuationViewModel(stream: Stream, val callback: ArticleFetchCallback)
: BaseObservable() {
var stream: Stream = stream
set(value) {
field = value
loading = false
}
var loading: Boolean = false
set(value) {
field = value
notifyPropertyChanged(BR.loadMoreEnabled)
}
val loadMoreEnabled: Boolean
@Bindable get() = !loading
fun loadMore() {
callback(stream)
loading = true
}
} | apache-2.0 | c50ef8fc8119a3b717e68f9a9807a2b7 | 22.354839 | 85 | 0.651452 | 4.72549 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/FileTypeUtil.kt | 1 | 346 | package ch.rmy.android.http_shortcuts.utils
object FileTypeUtil {
const val TYPE_XML = "text/xml"
const val TYPE_JSON = "application/json"
const val TYPE_HTML = "text/html"
const val TYPE_YAML = "text/yaml"
const val TYPE_YAML_ALT = "application/x-yaml"
fun isImage(type: String?) = type?.startsWith("image/") == true
}
| mit | a079becce78da94de886b4dbb7e6efc8 | 30.454545 | 67 | 0.676301 | 3.392157 | false | false | false | false |
sksamuel/ktest | kotest-assertions/kotest-assertions-shared/src/commonMain/kotlin/io/kotest/assertions/show/IterableShow.kt | 1 | 915 | package io.kotest.assertions.show
class IterableShow<T> : Show<Iterable<T>> {
override fun show(a: Iterable<T>): Printed = ListShow<T>().show(a.toList())
}
class ListShow<T> : Show<List<T>> {
private val maxCollectionSnippetSize = 20
override fun show(a: List<T>): Printed {
return if (a.isEmpty()) Printed("[]") else {
val remainingItems = a.size - maxCollectionSnippetSize
val suffix = when {
remainingItems <= 0 -> "]"
else -> "] and $remainingItems more"
}
return a.joinToString(
separator = ", ",
prefix = "[",
postfix = suffix,
limit = maxCollectionSnippetSize
) {
when {
it is Iterable<*> && it.toList() == a && a.size == 1 -> a[0].toString()
else -> recursiveRepr(a, it).value
}
}.printed()
}
}
}
| mit | 216f7e7ff499912aa954465c565f36f0 | 26.727273 | 86 | 0.518033 | 4.084821 | false | false | false | false |
leprosus/kotlin-cli | examples/command.kt | 1 | 1135 | import com.evalab.core.cli.Command
import com.evalab.core.cli.exception.OptionException
fun main(args: Array<String>) {
val command = Command("command", "Command just for testing")
command.addBooleanOption("debug", false, 'd', "Flag of debug mode")
command.addBooleanOption("verbose", false, 'v', "Returns detailed information")
command.addIntegerOption("size", false, 's', "Sets size")
command.addDoubleOption("fraction", false, 'f', "Sets fraction")
command.addStringOption("name", true, 'n', "Sets name")
try {
command.parse(args)
} catch (e: OptionException) {
println(e.message)
println(command.getHelp())
System.exit(2)
}
val debug = command.getBooleanValue("debug", false)
val verbose = command.getBooleanValue("verbose", false)
val size = command.getIntegerValue("size", 0)
val fraction = command.getDoubleValue("fraction", 0.0)
val name = command.getStringValue("name")
println("debug: " + debug)
println("verbose: " + verbose)
println("size: " + size)
println("fraction: " + fraction)
println("name: " + name)
}
| mit | b6d20b397735c7e17ef8de182e3286f1 | 34.46875 | 83 | 0.661674 | 3.834459 | false | false | false | false |
intrigus/jtransc | jtransc-utils/src/com/jtransc/text/captureStdout.kt | 2 | 1702 | /*
* Copyright 2016 Carlos Ballesteros Velasco
*
* 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.jtransc.text
import java.io.ByteArrayOutputStream
import java.io.OutputStream
import java.io.PrintStream
object StdoutRouterStream : OutputStream() {
val defaultRoute = System.out
init {
System.setOut(StdoutRouter)
}
private var os: OutputStream? = null
override fun write(b: Int) {
synchronized(this) {
(os ?: defaultRoute).write(b)
}
}
override fun write(b: ByteArray?, off: Int, len: Int) {
synchronized(this) {
(os ?: defaultRoute).write(b, off, len)
}
}
fun <TOutputStream : OutputStream> routeTemporally(out: TOutputStream, callback: () -> Unit): TOutputStream {
val prev = synchronized(this) { this.os }
synchronized(this) { this.os = out }
try {
callback()
} finally {
synchronized(this) { this.os = prev }
}
return out
}
fun captureThreadSafe(callback: () -> Unit) = routeTemporally(ByteArrayOutputStream(), callback)
}
object StdoutRouter : PrintStream(StdoutRouterStream) {
val os = this.out
}
fun captureStdout(callback: () -> Unit): String {
return StdoutRouterStream.captureThreadSafe(callback).toString()
} | apache-2.0 | 34ae759a178a7340d4576706cdeb1765 | 25.609375 | 110 | 0.718566 | 3.598309 | false | false | false | false |
atlarge-research/opendc-simulator | opendc-model-odc/sc18/src/main/kotlin/com/atlarge/opendc/model/odc/topology/format/sc18/Sc18SetupParser.kt | 1 | 4133 | /*
* MIT License
*
* Copyright (c) 2018 atlarge-research
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.atlarge.opendc.model.odc.topology.format.sc18
import com.atlarge.opendc.model.odc.integration.jpa.schema.Cpu
import com.atlarge.opendc.model.odc.integration.jpa.schema.Datacenter
import com.atlarge.opendc.model.odc.integration.jpa.schema.Path
import com.atlarge.opendc.model.odc.integration.jpa.schema.Rack
import com.atlarge.opendc.model.odc.integration.jpa.schema.RoomType
import com.atlarge.opendc.model.odc.integration.jpa.schema.Section
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import java.io.InputStream
import com.atlarge.opendc.model.odc.integration.jpa.schema.Machine as InternalMachine
import com.atlarge.opendc.model.odc.integration.jpa.schema.Room as InternalRoom
/**
* A parser for the JSON experiment setup files used for the SC18 paper.
*
* @property objectMapper The Jackson [ObjectMapper] to map the setup file.
*/
class Sc18SetupParser(private val objectMapper: ObjectMapper = jacksonObjectMapper()) {
/**
* Parse the given [InputStream] as setup file and convert it into a [Path].
* After the method returns, the input stream is closed.
*
* @param input The [InputStream] to parse as setup file.
* @return The [Path] that has been parsed.
*/
fun parseSetup(input: InputStream): Setup = objectMapper.readValue(input)
/**
* Parse the given [InputStream] as setup file. After the method returns, the input stream
* is closed.
*
* @param input The [InputStream] to parse as setup file.
* @return The [Path] that has been parsed.
*/
fun parse(input: InputStream): Path {
val setup: Setup = parseSetup(input)
val rooms = setup.rooms.map { room ->
val objects = room.objects.map { roomObject ->
when (roomObject) {
is RoomObject.Rack -> {
val machines = roomObject.machines.mapIndexed { position, machine ->
val cpus = machine.cpus.map { id ->
when (id) {
1 -> Cpu(null, "intel", "i7", "v6", "6700k", 4100, 4, 70.0)
2 -> Cpu(null, "intel", "i5", "v6", "6700k", 3500, 2, 50.0)
else -> throw IllegalArgumentException("The cpu id $id is not recognized")
}
}
InternalMachine(null, position, cpus.toSet(), emptySet(), machine.ethernetSpeed)
}
Rack(null, "", 0, 42, machines)
}
}
}
InternalRoom(null, room.type, RoomType.valueOf(room.type), objects)
}
val datacenter = Datacenter(null, rooms)
val sections = listOf(Section(null, datacenter, 0))
return Path(null, sections)
}
}
| mit | 02a977551b7e18cc71e46c2807653ac0 | 45.438202 | 110 | 0.654972 | 4.300728 | false | false | false | false |
wonderkiln/CameraKit-Android | camerakit/src/main/java/com/camerakit/util/CameraSizeCalculator.kt | 2 | 964 | package com.camerakit.util
import com.camerakit.type.CameraSize
import kotlin.math.absoluteValue
class CameraSizeCalculator(private val sizes: Array<CameraSize>) {
fun findClosestSizeContainingTarget(target: CameraSize): CameraSize {
sizes.sort()
var bestSize = sizes.last()
var bestArea = Int.MAX_VALUE
sizes.forEach {
if (it.width >= target.width
&& it.height >= target.height
&& it.area() < bestArea) {
bestSize = it
bestArea = it.area()
}
}
return bestSize
}
fun findClosestSizeMatchingArea(area: Int): CameraSize {
sizes.sort()
var bestSize = sizes.last()
sizes.forEach {
if ((area - it.area()).absoluteValue
< (area - bestSize.area()).absoluteValue) {
bestSize = it
}
}
return bestSize
}
} | mit | ce523ffa571df5b8f4fa66b83f1bccb3 | 23.74359 | 73 | 0.539419 | 4.634615 | false | false | false | false |
Yorxxx/played-next-kotlin | app/src/main/java/com/piticlistudio/playednext/data/repository/datasource/giantbomb/GiantbombGameDatasourceRepositoryImpl.kt | 1 | 2668 | package com.piticlistudio.playednext.data.repository.datasource.giantbomb
import android.arch.persistence.room.EmptyResultSetException
import com.piticlistudio.playednext.data.entity.mapper.datasources.game.GiantbombGameMapper
import com.piticlistudio.playednext.data.repository.datasource.GameDatasourceRepository
import com.piticlistudio.playednext.domain.model.Game
import io.reactivex.Completable
import io.reactivex.Flowable
import javax.inject.Inject
/**
* Remote implementation for retrieving Game instances. This class implements the [GameDatasourceRepository] from
* the data layers as it is the layers responsibility for defining the operations in which data
* store implementation can carry out.
* Created by e-jegi on 3/27/2018.
*/
class GiantbombGameDatasourceRepositoryImpl @Inject constructor(private val service: GiantbombService,
private val mapper: GiantbombGameMapper) : GameDatasourceRepository {
override fun load(id: Int): Flowable<Game> {
return service.fetchGame(id)
.map {
if (!it.error.equals("OK") || it.status_code != 1) {
throw GiantbombServiceException(it.status_code, it.error)
}
if (it.results == null) throw EmptyResultSetException("No results found") else it.results
}
.map { mapper.mapFromDataLayer(it).apply { syncedAt = System.currentTimeMillis() } }
.toFlowable()
}
override fun search(query: String, offset: Int, limit: Int): Flowable<List<Game>> {
var page = 1
if (offset >= limit) {
page = offset / limit + 1
}
return service.searchGames(query = query, page = page, limit = limit)
.map {
if (!it.error.equals("OK") || it.status_code != 1) {
throw GiantbombServiceException(it.status_code, it.error)
}
it.results
}
.map {
mutableListOf<Game>().apply {
it.forEach {
add(mapper.mapFromDataLayer(it).apply { syncedAt = System.currentTimeMillis() })
}
}.toList()
}.toFlowable()
}
override fun save(domainModel: Game): Completable = Completable.error(Throwable("Not allowed"))
}
/**
* Thrown by this repository when an error message and or status code is returned with an error
*/
class GiantbombServiceException(val code: Int, message: String) : RuntimeException(message) | mit | 3d704d492a5bb72b757da2dd8565b15b | 44.237288 | 133 | 0.616942 | 4.931608 | false | false | false | false |
UnderMybrella/Visi | src/main/kotlin/org/abimon/visi/nums/SuperNumberRange.kt | 1 | 5192 | package org.abimon.visi.nums
public class SuperNumberRange(start: SuperNumber, endInclusive: SuperNumber) : SuperNumberProgression(start, endInclusive, SuperLong(1)), ClosedRange<SuperNumber> {
override val start: SuperNumber get() = first
override val endInclusive: SuperNumber get() = last
override fun contains(value: SuperNumber): Boolean = first <= value && value <= last
override fun isEmpty(): Boolean = first > last
override fun equals(other: Any?): Boolean =
other is SuperNumberRange && (isEmpty() && other.isEmpty() ||
first == other.first && last == other.last)
override fun hashCode(): Int =
if (isEmpty()) -1 else ((first * 31) + last).toInt()
override fun toString(): String = "$first..$last"
companion object {
/** An empty range of values of type Int. */
public val EMPTY: SuperNumberRange = SuperNumberRange(SuperLong(1), SuperLong(0))
}
}
public open class SuperNumberProgression
internal constructor
(
start: SuperNumber,
endInclusive: SuperNumber,
/**
* The step of the progression.
*/
public val step: SuperNumber
) : Iterable<SuperNumber> {
init {
if ((step as Number) == 0) throw kotlin.IllegalArgumentException("Step must be non-zero")
}
/**
* The first element in the progression.
*/
public val first: SuperNumber = start
/**
* The last element in the progression.
*/
public val last: SuperNumber = getProgressionLastElement(start, endInclusive, step)
override fun iterator(): SuperNumberIterator = SuperNumberProgressionIterator(first, last, step)
/** Checks if the progression is empty. */
public open fun isEmpty(): Boolean = if (step > 0) first > last else first < last
override fun equals(other: Any?): Boolean =
other is SuperNumberProgression && (isEmpty() && other.isEmpty() ||
first == other.first && last == other.last && step == other.step)
override fun hashCode(): Int =
if (isEmpty()) -1 else (31 * (31 * (first.toLong() xor (first.toLong() ushr 32)) + (last.toLong() xor (last.toLong() ushr 32))) + (step.toLong() xor (step.toLong() ushr 32))).toInt()
override fun toString(): String = if (step > 0) "$first..$last step $step" else "$first downTo $last step ${-step}"
companion object {
/**
* Creates LongProgression within the specified bounds of a closed range.
* The progression starts with the [rangeStart] value and goes toward the [rangeEnd] value not excluding it, with the specified [step].
* In order to go backwards the [step] must be negative.
*/
public fun fromClosedRange(rangeStart: SuperNumber, rangeEnd: SuperNumber, step: SuperNumber): SuperNumberProgression = SuperNumberProgression(rangeStart, rangeEnd, step)
}
}
/** An iterator over a sequence of values of type `Long`. */
public abstract class SuperNumberIterator : Iterator<SuperNumber> {
override final fun next() = nextNumber()
/** Returns the next value in the sequence without boxing. */
public abstract fun nextNumber(): SuperNumber
}
class SuperNumberProgressionIterator(first: SuperNumber, last: SuperNumber, val step: SuperNumber) : SuperNumberIterator() {
private var next = first
private val finalElement = last
private var hasNext: Boolean = if (step > 0) first <= last else first >= last
override fun hasNext(): Boolean = hasNext
override fun nextNumber(): SuperNumber {
val value = next
if (value == finalElement) {
hasNext = false
}
else {
next += step
}
return value
}
}
fun mod(a: SuperNumber, b: SuperNumber): SuperNumber {
val mod = a % b
return if (mod >= 0) mod else mod + b
}
fun differenceModulo(a: SuperNumber, b: SuperNumber, c: SuperNumber): SuperNumber {
return mod(mod(a, c) - mod(b, c), c)
}
/**
* Calculates the final element of a bounded arithmetic progression, i.e. the last element of the progression which is in the range
* from [start] to [end] in case of a positive [step], or from [end] to [start] in case of a negative
* [step].
*
* No validation on passed parameters is performed. The given parameters should satisfy the condition: either
* `step > 0` and `start >= end`, or `step < 0` and`start >= end`.
* @param start first element of the progression
* @param end ending bound for the progression
* @param step increment, or difference of successive elements in the progression
* @return the final element of the progression
* @suppress
*/
fun getProgressionLastElement(start: SuperNumber, end: SuperNumber, step: SuperNumber): SuperNumber {
if (step > 0) {
return end - differenceModulo(end, start, step)
}
else if (step < 0) {
return end + differenceModulo(start, end, -step)
}
else {
throw kotlin.IllegalArgumentException("Step is zero.")
}
}
public infix fun SuperLong.until(to: SuperLong): SuperNumberRange {
if (to <= SuperLong.MIN_VALUE) return SuperNumberRange.EMPTY
return this .. (to - 1)
} | mit | 1a95278f6f0a726115341d4911079d9f | 36.630435 | 194 | 0.657357 | 4.248773 | false | false | false | false |
viniciussoares/esl-pod-client | app/src/main/java/br/com/wakim/eslpodclient/ui/podcastlist/view/PodcastListActivity.kt | 1 | 8404 | package br.com.wakim.eslpodclient.ui.podcastlist.view
import android.os.Bundle
import android.support.design.widget.AppBarLayout
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v4.app.Fragment
import android.view.Menu
import android.view.MenuItem
import br.com.wakim.eslpodclient.R
import br.com.wakim.eslpodclient.android.widget.LoadingFloatingActionButton
import br.com.wakim.eslpodclient.dagger.PodcastPlayerComponent
import br.com.wakim.eslpodclient.dagger.module.PodcastPlayerModule
import br.com.wakim.eslpodclient.ui.podcastlist.downloaded.view.DownloadedListFragment
import br.com.wakim.eslpodclient.ui.podcastlist.favorited.view.FavoritedListFragment
import br.com.wakim.eslpodclient.ui.podcastplayer.view.ListPlayerView
import br.com.wakim.eslpodclient.ui.settings.view.SettingsActivity
import br.com.wakim.eslpodclient.ui.view.BaseActivity
import br.com.wakim.eslpodclient.util.extensions.snack
import br.com.wakim.eslpodclient.util.extensions.startActivity
import butterknife.BindView
import it.sephiroth.android.library.bottomnavigation.BottomNavigation
open class PodcastListActivity : BaseActivity() {
companion object {
const val MINIMUM_THRESHOLD = 5
const val FRAGMENT_TAG = "FRAGMENT"
}
private var podcastPlayerComponent: PodcastPlayerComponent? = null
@BindView(R.id.coordinator_layout)
lateinit var coordinatorLayout: CoordinatorLayout
@BindView(R.id.appbar)
lateinit var appBarLayout: AppBarLayout
@BindView(R.id.player_view)
lateinit var playerView: ListPlayerView
@BindView(R.id.fab_play)
lateinit var playFab: FloatingActionButton
@BindView(R.id.fab_pause)
lateinit var pauseFab: FloatingActionButton
@BindView(R.id.fab_loading)
lateinit var loadingFab: LoadingFloatingActionButton
@BindView(R.id.bottom_navigation)
lateinit var bottomBar: BottomNavigation
var podcastListFragment: PodcastListFragment? = null
var downloadedListFragment: DownloadedListFragment? = null
var favoritedListFragment: FavoritedListFragment? = null
var currentFragment: PodcastListFragment? = null
var savedState = arrayOfNulls<Fragment.SavedState>(3)
var lastSelectedPosition = 0
var lastOffset: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
createActivityComponent()
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_podcastlist)
createPlayerComponent()
restoreFragmentStates(savedInstanceState)
configureAppBarLayout()
configureBottomBar()
addFragmentIfNeeded()
playerView.setControls(playFab, pauseFab, loadingFab)
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
val fragmentManager = supportFragmentManager
podcastListFragment?.let {
if (it.isAdded) {
fragmentManager.putFragment(outState!!, "PODCAST_LIST", it)
}
}
favoritedListFragment?.let {
if (it.isAdded) {
fragmentManager.putFragment(outState!!, "FAVORITED_LIST", it)
}
}
downloadedListFragment?.let {
if (it.isAdded) {
fragmentManager.putFragment(outState!!, "DOWNLOADED_LIST", it)
}
}
}
fun configureAppBarLayout() {
appBarLayout.addOnOffsetChangedListener { appBarLayout, offset ->
currentFragment?.let {
if (offset == 0) {
it.setSwipeRefreshEnabled(true)
} else if (lastOffset == 0 && it.isSwipeRefreshEnabled()) {
it.setSwipeRefreshEnabled(false)
}
}
lastOffset = offset
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.podcast_list_menu, menu)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
if (item?.itemId == R.id.menu_settings) {
startActivity<SettingsActivity>()
return true
}
return super.onOptionsItemSelected(item)
}
fun restoreFragmentStates(savedInstanceState: Bundle?) {
savedInstanceState?.let {
val fragmentManager = supportFragmentManager
podcastListFragment = fragmentManager.getFragment(it, "PODCAST_LIST") as? PodcastListFragment
favoritedListFragment = fragmentManager.getFragment(it, "FAVORITED_LIST") as? FavoritedListFragment
downloadedListFragment = fragmentManager.getFragment(it, "DOWNLOADED_LIST") as? DownloadedListFragment
}
}
fun configureBottomBar() {
bottomBar.setOnMenuItemClickListener(object: BottomNavigation.OnMenuItemSelectionListener {
override fun onMenuItemSelect(id: Int, position: Int) {
when (position) {
0 -> replaceListFragment(PodcastListFragment(), lastSelectedPosition, position)
1 -> replaceFavoritedFragment(FavoritedListFragment(), lastSelectedPosition, position)
2 -> replaceDownloadedFragment(DownloadedListFragment(), lastSelectedPosition, position)
}
lastSelectedPosition = position
}
override fun onMenuItemReselect(p0: Int, p1: Int) { }
})
}
fun addFragmentIfNeeded() {
currentFragment = supportFragmentManager.findFragmentByTag(FRAGMENT_TAG) as PodcastListFragment?
if (currentFragment == null) {
podcastListFragment = PodcastListFragment()
currentFragment = podcastListFragment
supportFragmentManager
.beginTransaction()
.add(R.id.container, podcastListFragment, FRAGMENT_TAG)
.commit()
}
}
fun replaceListFragment(fragment: PodcastListFragment, previousPosition: Int, position: Int) {
podcastListFragment = fragment
replaceFragment(fragment, previousPosition, position)
}
fun replaceFavoritedFragment(fragment: FavoritedListFragment, previousPosition: Int, position: Int) {
favoritedListFragment = favoritedListFragment
replaceFragment(fragment, previousPosition, position)
}
fun replaceDownloadedFragment(fragment: DownloadedListFragment, previousPosition: Int, position: Int) {
downloadedListFragment = fragment
replaceFragment(fragment, previousPosition, position)
}
fun replaceFragment(fragment: PodcastListFragment, previousPosition: Int, position: Int) {
val fragmentManager = supportFragmentManager
val previousFragment = fragmentManager.findFragmentByTag(FRAGMENT_TAG)
val state = savedState[position]
savedState[previousPosition] = fragmentManager.saveFragmentInstanceState(previousFragment)
state?.let {
fragment.setInitialSavedState(state)
}
currentFragment = fragment
fragmentManager
.beginTransaction()
.replace(R.id.container, fragment, FRAGMENT_TAG)
.commit()
}
override fun getSystemService(name: String?): Any? {
if (name == PodcastPlayerComponent::class.java.simpleName) {
return podcastPlayerComponent
}
return super.getSystemService(name)
}
fun createPlayerComponent() {
podcastPlayerComponent = activityComponent + PodcastPlayerModule(playerView)
}
override fun onBackPressed() {
with (playerView) {
if (isExpanded()) {
collapse()
return
}
if (isVisible()) {
hide()
return
}
}
disposePlayerIfNeeded()
super.onBackPressed()
}
override fun finish() {
disposePlayerIfNeeded()
super.finish()
}
open fun disposePlayerIfNeeded() {
if (!playerView.isPlaying()) {
playerView.explicitlyStop()
}
}
override fun showMessage(messageResId: Int): Snackbar = snack(coordinatorLayout, messageResId)
} | apache-2.0 | 847ec4068b65404a84d1acb0fe388cf3 | 32.090551 | 114 | 0.674917 | 5.49281 | false | false | false | false |
VerifAPS/verifaps-lib | smv/src/test/kotlin/edu/kit/iti/formal/smv/parser/TestHelper.kt | 1 | 3603 | package edu.kit.iti.formal.smv.parser
/*-
* #%L
* ProofScriptParser
* %%
* Copyright (C) 2017 Application-oriented Formal Verification
* %%
* 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/gpl-3.0.html>.
* #L%
*/
import edu.kit.iti.formal.smv.SMVFacade
import edu.kit.iti.formal.smv.ast.SMVExpr
import org.antlr.v4.runtime.CharStreams
import java.io.BufferedReader
import java.io.File
import java.io.IOException
import java.io.InputStreamReader
import java.util.*
import java.util.stream.Collectors
/**
* @author Alexander Weigl
* @version 1 (27.04.17)
*/
object TestHelper {
fun getFile(path: String): String {
return getFile(TestHelper::class.java, path)
}
fun getFile(aClass: Class<*>, path: String): String {
return aClass.getResource(path).toExternalForm().substring(5)
}
fun getResourcesAsParameters(folder: String): Iterable<Array<out Any>> {
val files = getResources(folder)
return files.map { f -> arrayOf(f!! as Any) }
}
fun getResources(folder: String): Array<File> {
val f = TestHelper::class.java.classLoader.getResource(folder)
if (f == null) {
System.err.format("Could not find %s%n", folder)
return arrayOf()
}
val file = File(f.file)
return file.listFiles()
}
@Throws(IOException::class)
fun loadLines(filename: String, expectedArgs: Int): Iterable<Array<out Any>> {
//val validExpression = ArrayList<Array<Any>>(4096)
val ve = TestHelper::class.java.getResourceAsStream(filename)
if (ve == null) {
System.err.println("Could not find: $filename")
return arrayListOf()
}
val stream = BufferedReader(InputStreamReader(ve))
return stream.lineSequence()
.filter { !(it.startsWith("#") || it.isEmpty()) }
.map {
it.split(">>>".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
}
.filter {
val b = it.size == expectedArgs;
if (!b)
System.err.println("Line $it has ${it.size} arguments, expected $expectedArgs. SKIPPED%n");
b
}
.asIterable()
}
// println("Found: " + filename + " with " + validExpression.size + " lines!")
// return validExpression
fun asParameters(cases: Array<String>): Collection<Array<out Any>> {
return cases.map { s -> arrayOf(s) }
}
fun getParser(input: String): SMVParser {
return SMVFacade.getParser(CharStreams.fromString(input))
}
@Throws(IOException::class)
fun getParser(f: File): SMVParser {
return SMVFacade.getParser(CharStreams.fromFileName(f.absolutePath))
}
fun toExpr(s: String): SMVExpr {
val v = SMVTransformToAST()
val e = getParser(s).expr().accept(v) as SMVExpr
return getParser(s).expr().accept(v) as SMVExpr
}
}
| gpl-3.0 | aad41910901539528846052815d2bf82 | 31.169643 | 115 | 0.626978 | 4.080408 | false | false | false | false |
yuzumone/bergamio | app/src/main/kotlin/net/yuzumone/bergamio/view/BindingAdapter.kt | 1 | 1080 | package net.yuzumone.bergamio.view
import android.databinding.BindingAdapter
import android.widget.TextView
import net.yuzumone.bergamio.R
import net.yuzumone.bergamio.model.Coupon
import net.yuzumone.bergamio.model.CouponInfo
import net.yuzumone.bergamio.model.HdoInfo
object BindingAdapter {
@BindingAdapter("usage")
@JvmStatic
fun setUsage(view: TextView, usage: Int) {
view.text = view.context.getString(R.string.mb, usage)
}
@BindingAdapter("type_expire")
@JvmStatic
fun setTypeExpire(view: TextView, coupon: Coupon) {
view.text = view.context.getString(R.string.type_expire, coupon.type, coupon.expire)
}
@BindingAdapter("number")
@JvmStatic
fun setNumber(view: TextView, couponInfo: CouponInfo) {
view.text = couponInfo.hdoInfo.joinToString(transform = HdoInfo::number, separator = "\n")
}
@BindingAdapter("total")
@JvmStatic
fun setTotal(view: TextView, couponInfo: CouponInfo) {
view.text = view.context.getString(R.string.mb, couponInfo.coupon.sumBy { it.volume })
}
} | apache-2.0 | e98f7859492c5faab1af597233e38a9a | 29.885714 | 98 | 0.716667 | 3.58804 | false | false | false | false |
GoogleCloudPlatform/kotlin-samples | vision/src/main/quickstart.kt | 1 | 2441 | // Copyright 2018 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.vision
import com.google.cloud.vision.v1.AnnotateImageRequest
import com.google.cloud.vision.v1.Feature
import com.google.cloud.vision.v1.Feature.Type
import com.google.cloud.vision.v1.Image
import com.google.cloud.vision.v1.ImageAnnotatorClient
import com.google.protobuf.ByteString
import java.io.IOException
import java.io.File
fun main(args: Array<String>) {
val imageFileName = if (args.isEmpty()) {
"./resources/doggo.jpg" // Image file path
} else {
args[0] // grab args[0] for file
}
val imageFile = File(imageFileName)
if (!imageFile.exists()) {
throw NoSuchFileException(file = imageFile, reason = "The file you specified does not exist")
}
try {
quickstart(imageFileName)
} catch (e: IOException) {
println("Image annotation failed:")
println(e.message)
}
}
fun quickstart(imageFileName: String) {
// [START vision_quickstart]
// import com.google.cloud.vision.v1.ImageAnnotatorClient
// import java.io.File
val imgProto = ByteString.copyFrom(File(imageFileName).readBytes())
val vision = ImageAnnotatorClient.create()
// Set up the Cloud Vision API request.
val img = Image.newBuilder().setContent(imgProto).build()
val feat = Feature.newBuilder().setType(Type.LABEL_DETECTION).build()
val request = AnnotateImageRequest.newBuilder()
.addFeatures(feat)
.setImage(img)
.build()
// Call the Cloud Vision API and perform label detection on the image.
val result = vision.batchAnnotateImages(arrayListOf(request))
// Print the label annotations for the first response.
result.responsesList[0].labelAnnotationsList.forEach { label ->
println("${label.description} (${(label.score * 100).toInt()}%)")
}
// [END vision_quickstart]
}
| apache-2.0 | c0afe6dc2885dfae12ad8261dc4b3693 | 34.376812 | 101 | 0.702171 | 4.001639 | false | false | false | false |
jitsi/jibri | src/main/kotlin/org/jitsi/jibri/config/JibriConfig.kt | 1 | 6980 | /*
* Copyright @ 2018 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.jitsi.jibri.config
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.exc.InvalidFormatException
import com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException
import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.jitsi.jibri.logger
import org.jivesoftware.smack.ConnectionConfiguration
import java.io.File
data class XmppCredentials(
val domain: String = "",
val port: Int? = null,
val username: String = "",
val password: String = ""
) {
override fun toString(): String {
return "XmppCredentials(domain=$domain, port=$port, username=$username, password=*****)"
}
}
fun com.typesafe.config.Config.toXmppCredentials(): XmppCredentials =
XmppCredentials(
domain = getString("domain"),
port = if (hasPath("port")) getInt("port") else null,
username = getString("username"),
password = getString("password")
)
data class XmppMuc(
val domain: String,
@JsonProperty("room_name")
val roomName: String,
val nickname: String
)
fun com.typesafe.config.Config.toXmppMuc(): XmppMuc =
XmppMuc(
domain = getString("domain"),
roomName = getString("room-name"),
nickname = getString("nickname")
)
data class XmppEnvironmentConfig(
/**
* A user-friendly name for this environment
*/
val name: String,
/**
* A list of xmpp server hosts to which we'll connect
*/
@JsonProperty("xmpp_server_hosts")
val xmppServerHosts: List<String>,
/**
* The base xmpp domain
*/
@JsonProperty("xmpp_domain")
val xmppDomain: String,
/**
* The baseUrl we'll use, if set, to join the call
*/
@JsonProperty("baseUrl")
val baseUrl: String?,
/**
* The login information for the control API
*/
@JsonProperty("control_login")
val controlLogin: XmppCredentials,
/**
* The muc we'll join to announce our presence for
* recording and streaming services
*/
@JsonProperty("control_muc")
val controlMuc: XmppMuc,
/**
* The muc we'll join to announce our presence
* for sip gateway services
* TODO: should this and controlMuc above be
* optional? but somehow require at least one
* to be set?
*/
@JsonProperty("sip_control_muc")
val sipControlMuc: XmppMuc?,
/**
* The login information the selenium web client will use
*/
@JsonProperty("call_login")
val callLogin: XmppCredentials,
/**
* The value we'll strip from the room jid domain to derive
* the call url
*/
@JsonProperty("room_jid_domain_string_to_strip_from_start")
val stripFromRoomDomain: String,
/**
* How long Jibri sessions will be allowed to last before
* they are stopped. A value of 0 allows them to go on
* indefinitely
*/
@JsonProperty("usage_timeout")
val usageTimeoutMins: Int,
/**
* Whether or not we'll automatically trust any
* cert on this XMPP domain
*/
@JsonProperty("always_trust_certs")
val trustAllXmppCerts: Boolean = true,
/**
* The XMPP security mode to use for the XMPP connection
*/
@JsonProperty("security_mode")
@JsonInclude(JsonInclude.Include.NON_NULL)
val securityMode: ConnectionConfiguration.SecurityMode? = null
)
fun com.typesafe.config.Config.toXmppEnvironment(): XmppEnvironmentConfig =
XmppEnvironmentConfig(
name = getString("name"),
xmppServerHosts = getStringList("xmpp-server-hosts"),
xmppDomain = getString("xmpp-domain"),
baseUrl = if (hasPath("base-url")) {
getString("base-url")
} else null,
controlLogin = getConfig("control-login").toXmppCredentials(),
controlMuc = getConfig("control-muc").toXmppMuc(),
sipControlMuc = if (hasPath("sip-control-muc")) {
getConfig("sip-control-muc").toXmppMuc()
} else null,
callLogin = getConfig("call-login").toXmppCredentials(),
stripFromRoomDomain = getString("strip-from-room-domain"),
usageTimeoutMins = getDuration("usage-timeout").toMinutes().toInt(),
trustAllXmppCerts = getBoolean("trust-all-xmpp-certs"),
securityMode = if (hasPath("security-mode")) {
getEnum(ConnectionConfiguration.SecurityMode::class.java, "security-mode")
} else null
)
data class JibriConfig(
@JsonProperty("jibri_id")
val jibriId: String? = null,
@JsonProperty("recording_directory")
val recordingDirectory: String? = null,
/**
* Whether or not Jibri should return to idle state
* after handling (successfully or unsuccessfully)
* a request. A value of 'true' here means that a Jibri
* will NOT return back to the IDLE state and will need
* to be restarted in order to be used again.
*/
@JsonProperty("single_use_mode")
val singleUseMode: Boolean? = null,
/**
* Whether or not pushing stats to statsd
* should be enabled. See [org.jitsi.jibri.statsd.JibriStatsDClient].
*/
@JsonProperty("enable_stats_d")
val enabledStatsD: Boolean? = null,
@JsonProperty("finalize_recording_script_path")
val finalizeRecordingScriptPath: String? = null,
@JsonProperty("xmpp_environments")
val xmppEnvironments: List<XmppEnvironmentConfig>? = null
)
fun loadConfigFromFile(configFile: File): JibriConfig? {
return try {
val config: JibriConfig = jacksonObjectMapper()
.configure(JsonParser.Feature.ALLOW_COMMENTS, true)
.readValue(configFile)
logger.info("Parsed legacy config:\n$config")
config
} catch (e: MissingKotlinParameterException) {
logger.error("A required config parameter was missing: ${e.originalMessage}")
null
} catch (e: UnrecognizedPropertyException) {
logger.error("An unrecognized config parameter was found: ${e.originalMessage}")
null
} catch (e: InvalidFormatException) {
logger.error("A config parameter was incorrectly formatted: ${e.localizedMessage}")
null
}
}
| apache-2.0 | a4f089f35d0325d8d282621eefd5682e | 33.554455 | 96 | 0.673352 | 4.287469 | false | true | false | false |
spinnaker/spinnaker-gradle-project | spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/SpinnakerUIExtensionPlugin.kt | 1 | 2439 | /*
* Copyright 2019 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.gradle.extension
import com.netflix.spinnaker.gradle.extension.Plugins.ASSEMBLE_PLUGIN_TASK_NAME
import com.netflix.spinnaker.gradle.extension.tasks.AssembleUIPluginTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.Exec
import org.gradle.internal.os.OperatingSystem;
/**
* Gradle plugin to support spinnaker UI plugin bundling aspects.
*
* TODO(rz): Need a setup command for scaffolding out all of the various node/rollup/yarn/npm/whatever tool configs
*/
class SpinnakerUIExtensionPlugin : Plugin<Project> {
override fun apply(project: Project) {
// Include JavaPlugin as a hack to get the Zip tasks to actually work. For whatever reason, when the JavaPlugin
// is not applied, Zip tasks fail to bind their configurations, or something.
project.pluginManager.apply(JavaPlugin::class.java)
project.tasks.create(ASSEMBLE_PLUGIN_TASK_NAME, AssembleUIPluginTask::class.java)
// Calling "yarn" on Windows doesn't work, need to use "yarn.cmd"
val yarnCmd = if (OperatingSystem.current().isWindows) "yarn.cmd" else "yarn"
project.tasks.create("yarn", Exec::class.java) {
group = Plugins.GROUP
workingDir = project.projectDir
commandLine = listOf(yarnCmd)
}
project.tasks.create("yarnModules", Exec::class.java) {
group = Plugins.GROUP
workingDir = project.projectDir
commandLine = listOf(yarnCmd, "modules")
}
project.tasks.create("yarnBuild", Exec::class.java) {
group = Plugins.GROUP
workingDir = project.projectDir
commandLine = listOf(yarnCmd, "build")
dependsOn("yarnModules")
}
project.afterEvaluate {
project.tasks.getByName("build") {
dependsOn("yarn", "yarnBuild")
}
}
}
}
| apache-2.0 | 062c8ccdaa24f8eca2c5d4cddf3dc0d8 | 34.347826 | 115 | 0.725297 | 4.038079 | false | false | false | false |
christophpickl/gadsu | src/main/kotlin/at/cpickl/gadsu/service/metainf.kt | 1 | 1890 | package at.cpickl.gadsu.service
import at.cpickl.gadsu.version.Version
import com.github.christophpickl.kpotpourri.common.io.closeSilently
import com.google.inject.Provider
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.DateTimeFormatter
import org.slf4j.LoggerFactory
import java.util.Properties
/**
* Load additionally info at runtime (data provided by build process).
*/
class MetaInfLoader : Provider<MetaInf> {
companion object {
private val PROPERTIES_CLASSPATH = "/gadsu/metainf.properties"
private val PROPKEY_VERSION = "application.version"
private val PROPKEY_BUILT_DATE = "built.date"
// 15.04.2016 19:56
private val DATE_FORMATTER: DateTimeFormatter = DateTimeFormat.forPattern("dd.MM.yyyy HH:mm:ss")
}
private val log = LoggerFactory.getLogger(javaClass)
private var cachedValue: MetaInf? = null
override fun get(): MetaInf {
if (cachedValue != null) {
return cachedValue!!
}
log.debug("load() ... initializing cached value from '{}'", PROPERTIES_CLASSPATH)
val props = Properties()
val inStream = javaClass.getResourceAsStream(PROPERTIES_CLASSPATH)
try {
props.load(inStream)
} finally {
inStream.closeSilently()
}
val version = Version.parse(props.getProperty(PROPKEY_VERSION))
val builtString = props.getProperty(PROPKEY_BUILT_DATE)
val built = if (builtString.equals("@built.date@")) DateTime.now() else DATE_FORMATTER.parseDateTime(builtString)
cachedValue = MetaInf(version, built)
return cachedValue!!
}
}
/**
* Programmatic representation of the metainf.properties file.
*/
data class MetaInf(val applicationVersion: Version, val built: DateTime) {
companion object {} // for extensions only
}
| apache-2.0 | bd5d70ff1d3665ec2070d7b41ae88dad | 32.75 | 121 | 0.694709 | 4.324943 | false | false | false | false |
AlmasB/GroupNet | src/main/kotlin/icurves/diagram/curve/EllipseCurve.kt | 1 | 2240 | package icurves.diagram.curve
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import icurves.diagram.Curve
import icurves.util.Converter
import icurves.util.Label
import javafx.geometry.Point2D
import javafx.scene.shape.Circle
import javafx.scene.shape.Ellipse
import java.util.*
/**
* TODO: curiosity hack
*
* @author Almas Baimagambetov ([email protected])
*/
class EllipseCurve(
label: Label,
var centerX: Double,
var centerY: Double,
var radiusX: Double,
var radiusY: Double) : Curve(label) {
override fun computeShape() = Ellipse(centerX, centerY, radiusX, radiusY)
override fun computePolygon() = Converter.circleToPolygon(CircleCurve(label, centerX, centerY, radiusX))
override fun copyWithNewLabel(newLabel: String): Curve {
val copy = CircleCurve(newLabel, centerX, centerY, radiusX)
// copy.setLabelPositionX(getLabelPositionX())
// copy.setLabelPositionY(getLabelPositionY())
return copy
}
override fun translate(translate: Point2D): Curve {
val copy = CircleCurve(label, centerX + translate.x, centerY + translate.y, radiusX)
// copy.setLabelPositionX(getLabelPositionX() + translate.x)
// copy.setLabelPositionY(getLabelPositionY() + translate.y)
return copy
}
override fun scale(scale: Double, pivot: Point2D): Curve {
val scaled = CircleCurve(label, centerX * scale + (1-scale) * pivot.x, centerY * scale + (1-scale) * pivot.y, radiusX * scale)
// scaled.setLabelPositionX(getLabelPositionX() * scale + (1-scale) * pivot.x)
// scaled.setLabelPositionY(getLabelPositionY() * scale + (1-scale) * pivot.y)
return scaled
}
// override fun equals(other: Any?): Boolean {
// if (other !is EllipseCurve)
// return false
//
// return label == other.label &&
// centerX == other.centerX &&
// centerY == other.centerY &&
// radius == other.radius
// }
//
// override fun hashCode(): Int {
// return Objects.hash(label, centerX, centerY, radius)
// }
override fun toDebugString(): String {
return "$this($centerX, $centerY, r=$radiusX)"
}
} | apache-2.0 | f78700aac4cd957d3518083a64837ac6 | 32.447761 | 134 | 0.654018 | 3.985765 | false | false | false | false |
vanniktech/Emoji | emoji/src/androidMain/kotlin/com/vanniktech/emoji/internal/EmojiSpan.kt | 1 | 3065 | /*
* Copyright (C) 2016 - Niklas Baudy, Ruben Gees, Mario Đanić and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.vanniktech.emoji.internal
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.FontMetricsInt
import android.text.style.DynamicDrawableSpan
import com.vanniktech.emoji.Emoji
import com.vanniktech.emoji.EmojiManager
import kotlin.math.abs
import kotlin.math.roundToInt
internal class EmojiSpan(
private val context: Context,
private val emoji: Emoji,
private val size: Float,
) : DynamicDrawableSpan() {
private val deferredDrawable by lazy(LazyThreadSafetyMode.NONE) {
val drawable = EmojiManager.emojiDrawableProvider().getDrawable(emoji, context)
drawable.setBounds(0, 0, size.toInt(), size.toInt())
drawable
}
override fun getDrawable() = deferredDrawable
override fun getSize(
paint: Paint,
text: CharSequence,
start: Int,
end: Int,
fontMetrics: FontMetricsInt?,
): Int {
if (fontMetrics != null) {
val paintFontMetrics = paint.fontMetrics
val ascent = paintFontMetrics.ascent
val descent = paintFontMetrics.descent
val targetSize = abs(ascent) + abs(descent)
val roundEmojiSize = size.roundToInt()
// Equal size use default font metrics.
if (roundEmojiSize == targetSize.roundToInt()) {
fontMetrics.ascent = ascent.toInt()
fontMetrics.descent = descent.toInt()
fontMetrics.top = paintFontMetrics.top.toInt()
fontMetrics.bottom = paintFontMetrics.bottom.toInt()
} else {
val fontHeight = paintFontMetrics.descent - paintFontMetrics.ascent
val centerY = paintFontMetrics.ascent + fontHeight / 2
fontMetrics.ascent = (centerY - size / 2).toInt()
fontMetrics.top = fontMetrics.ascent
fontMetrics.bottom = (centerY + size / 2).toInt()
fontMetrics.descent = fontMetrics.bottom
}
}
return size.toInt()
}
override fun draw(
canvas: Canvas,
text: CharSequence,
start: Int,
end: Int,
x: Float,
top: Int,
y: Int,
bottom: Int,
paint: Paint,
) {
val drawable = drawable
val paintFontMetrics = paint.fontMetrics
val fontHeight = paintFontMetrics.descent - paintFontMetrics.ascent
val centerY = y + paintFontMetrics.descent - fontHeight / 2
val transitionY = centerY - size / 2
canvas.save()
canvas.translate(x, transitionY)
drawable.draw(canvas)
canvas.restore()
}
}
| apache-2.0 | 984638186703efb9018930709228efbb | 31.585106 | 83 | 0.704212 | 4.289916 | false | false | false | false |
cliffano/swaggy-jenkins | clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/ExtensionClassContainerImpl1map.kt | 1 | 1417 | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.ExtensionClassImpl
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param ioJenkinsBlueoceanServiceEmbeddedRestPipelineImpl
* @param ioJenkinsBlueoceanServiceEmbeddedRestMultiBranchPipelineImpl
* @param propertyClass
*/
data class ExtensionClassContainerImpl1map(
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("io.jenkins.blueocean.service.embedded.rest.PipelineImpl") val ioJenkinsBlueoceanServiceEmbeddedRestPipelineImpl: ExtensionClassImpl? = null,
@field:Valid
@Schema(example = "null", description = "")
@field:JsonProperty("io.jenkins.blueocean.service.embedded.rest.MultiBranchPipelineImpl") val ioJenkinsBlueoceanServiceEmbeddedRestMultiBranchPipelineImpl: ExtensionClassImpl? = null,
@Schema(example = "null", description = "")
@field:JsonProperty("_class") val propertyClass: kotlin.String? = null
) {
}
| mit | d9dc8ca1928ac2ecc580d1792ebcfbf9 | 36.289474 | 187 | 0.810868 | 4.255255 | false | false | false | false |
jghoman/workshop-jb | src/syntax/lambdas.kt | 8 | 844 | package syntax.lambdas
fun apply(f: (Int, Int) -> Int) = f(1, 2)
fun fullSyntacticFormOfFunctionLiterals() {
apply({ x, y -> x + y })
// function type
val sum: (Int, Int) -> Int = { x, y -> x + y }
apply(sum)
// If you need to specify the return type (and the receiver type for extension lambda), you can use the function expression
apply(fun (x: Int, y: Int): Int = x + y)
val sum1 = fun (x: Int, y: Int): Int { return x + y }
apply(sum1)
// one parameter is by default named 'it'
val oneParameter: (Int) -> Int = { it }
oneParameter(1)
val extensionLambda: Int.(Int) -> Int = { x -> this + x }
1.extensionLambda(2) // == 3
}
fun closure(): Int {
var counter = 0
fun increment() {
counter++
}
for (i in 1..10) {
increment()
}
return counter
} | mit | cab78a5915fdbac750ec59239d5dcba0 | 22.472222 | 127 | 0.561611 | 3.296875 | false | false | false | false |
TheFallOfRapture/First-Game-Engine | src/main/kotlin/com/morph/engine/graphics/shaders/Shader.kt | 2 | 4744 | package com.morph.engine.graphics.shaders
import com.morph.engine.graphics.Color
import com.morph.engine.graphics.ShaderResource
import com.morph.engine.math.Matrix4f
import com.morph.engine.math.Vector3f
import com.morph.engine.math.Vector4f
import org.lwjgl.opengl.GL11.GL_FALSE
import org.lwjgl.opengl.GL20.*
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.*
open class Shader<out T : Uniforms>(shaderURL: String, val uniforms: T) {
private var resource: ShaderResource
init {
val oldResource = loadedShaders[shaderURL]
if (oldResource != null) {
this.resource = oldResource
oldResource.addReference()
} else {
this.resource = loadShaderProgram(shaderURL)
loadedShaders[shaderURL] = resource
}
}
fun init() {
uniforms.init(this)
uniforms.defineUniforms(resource.id)
}
fun bind() {
glUseProgram(resource.id)
}
fun unbind() {
glUseProgram(0)
}
fun setUniform3f(name: String, value: Vector3f) {
val location = glGetUniformLocation(resource.id, name)
glUniform3f(location, value.x, value.y, value.z)
}
fun setUniform3f(name: String, value: Color) {
val location = glGetUniformLocation(resource.id, name)
glUniform3f(location, value.red, value.green, value.blue)
}
fun setUniform4f(name: String, value: Vector4f) {
val location = glGetUniformLocation(resource.id, name)
glUniform4f(location, value.x, value.y, value.z, value.w)
}
fun setUniform4f(name: String, value: Color) {
val location = glGetUniformLocation(resource.id, name)
glUniform4f(location, value.red, value.green, value.blue, value.alpha)
}
fun setUniformMatrix4fv(name: String, value: Matrix4f) {
val location = glGetUniformLocation(resource.id, name)
glUniformMatrix4fv(location, false, value.toArray())
}
fun removeReference() {
resource.removeReference()
}
fun setUniform1i(name: String, value: Int) {
val location = glGetUniformLocation(resource.id, name)
glUniform1i(location, value)
}
companion object {
private val loadedShaders = HashMap<String, ShaderResource>()
fun loadShaderProgram(shaderURL: String): ShaderResource {
var shaderProgramID = 0
try {
val vertexShaderID = loadVertexShader(shaderURL + ".vsh")
val fragmentShaderID = loadFragmentShader(shaderURL + ".fsh")
shaderProgramID = glCreateProgram()
glAttachShader(shaderProgramID, vertexShaderID)
glAttachShader(shaderProgramID, fragmentShaderID)
glLinkProgram(shaderProgramID)
if (glGetProgrami(shaderProgramID, GL_LINK_STATUS) == GL_FALSE)
throw RuntimeException("Failed to link shader program: " + glGetProgramInfoLog(shaderProgramID, 1024))
glValidateProgram(shaderProgramID)
if (glGetProgrami(shaderProgramID, GL_VALIDATE_STATUS) == GL_FALSE)
throw RuntimeException("Failed to validate shader program: " + glGetProgramInfoLog(shaderProgramID, 1024))
glDeleteShader(vertexShaderID)
glDeleteShader(fragmentShaderID)
} catch (e: IOException) {
// TODO Auto-generated catch block
e.printStackTrace()
}
return ShaderResource(shaderProgramID)
}
@Throws(IOException::class)
private fun loadShader(filename: String, type: Int): Int {
val shaderSource = StringBuilder()
val reader = BufferedReader(InputStreamReader(Shader::class.java.classLoader.getResourceAsStream(filename)))
reader.useLines {
it.forEach {
shaderSource.append(it).append("\n")
}
}
val shaderID = glCreateShader(type)
glShaderSource(shaderID, shaderSource)
glCompileShader(shaderID)
if (glGetShaderi(shaderID, GL_COMPILE_STATUS) == GL_FALSE)
throw RuntimeException("""Failed to initialize shader of type $type: ${glGetShaderInfoLog(shaderID, 1024)}""")
return shaderID
}
@Throws(IOException::class)
private fun loadVertexShader(filename: String): Int {
return loadShader(filename, GL_VERTEX_SHADER)
}
@Throws(IOException::class)
private fun loadFragmentShader(filename: String): Int {
return loadShader(filename, GL_FRAGMENT_SHADER)
}
}
}
| mit | 8b5c9ca560b966686bd9ceb054ff1bd5 | 32.64539 | 126 | 0.63575 | 4.637341 | false | false | false | false |
collinx/susi_android | app/src/main/java/org/fossasia/susi/ai/helper/SnackbarBehavior.kt | 3 | 1347 | package org.fossasia.susi.ai.helper
import android.content.Context
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.Snackbar
import android.util.AttributeSet
import android.view.View
import android.view.ViewGroup
/**
* <h1>Helper class for snackbar behaviour.</h1>
* Created by rajdeep1008 on 17/10/16.
*/
class SnackbarBehavior
/**
* Instantiates a new Snackbar behavior.
* @param context the context
* *
* @param attrs the attrs
*/
(context: Context, attrs: AttributeSet) : CoordinatorLayout.Behavior<ViewGroup>(context, attrs) {
override fun layoutDependsOn(parent: CoordinatorLayout?, child: ViewGroup?, dependency: View?): Boolean {
return dependency is Snackbar.SnackbarLayout
}
override fun onDependentViewChanged(parent: CoordinatorLayout?, child: ViewGroup?, dependency: View?): Boolean {
val params = child!!.layoutParams as CoordinatorLayout.LayoutParams
params.bottomMargin = parent!!.height - dependency!!.y.toInt()
child.layoutParams = params
return true
}
override fun onDependentViewRemoved(parent: CoordinatorLayout?, child: ViewGroup?, dependency: View?) {
val params = child!!.layoutParams as CoordinatorLayout.LayoutParams
params.bottomMargin = 0
child.layoutParams = params
}
}
| apache-2.0 | 8e5957c57676195f245413a92bfaa028 | 31.853659 | 116 | 0.734224 | 4.742958 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/settings/permissions/permissionoptions/SitePermissionOptionsScreenStore.kt | 1 | 3179 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.settings.permissions.permissionoptions
import mozilla.components.lib.state.Action
import mozilla.components.lib.state.Middleware
import mozilla.components.lib.state.State
import mozilla.components.lib.state.Store
import org.mozilla.focus.settings.permissions.SitePermissionOption
class SitePermissionOptionsScreenStore(
initialState: SitePermissionOptionsScreenState,
middlewares: List<Middleware<SitePermissionOptionsScreenState, SitePermissionOptionsScreenAction>> = emptyList(),
) : Store<SitePermissionOptionsScreenState, SitePermissionOptionsScreenAction>(
initialState,
::sitePermissionOptionsScreenReducer,
middlewares,
) {
init {
dispatch(SitePermissionOptionsScreenAction.InitSitePermissionOptions)
}
}
data class SitePermissionOptionsScreenState(
val sitePermissionOptionList: List<SitePermissionOption> = emptyList(),
val selectedSitePermissionOption: SitePermissionOption? = null,
val sitePermissionLabel: String = "",
val isAndroidPermissionGranted: Boolean = false,
) : State
sealed class SitePermissionOptionsScreenAction : Action {
object InitSitePermissionOptions : SitePermissionOptionsScreenAction()
data class Select(val selectedSitePermissionOption: SitePermissionOption) : SitePermissionOptionsScreenAction()
data class AndroidPermission(val isAndroidPermissionGranted: Boolean) : SitePermissionOptionsScreenAction()
data class UpdateSitePermissionOptions(
val sitePermissionOptionsList: List<SitePermissionOption>,
val selectedSitePermissionOption: SitePermissionOption,
val sitePermissionLabel: String,
val isAndroidPermissionGranted: Boolean,
) : SitePermissionOptionsScreenAction()
}
private fun sitePermissionOptionsScreenReducer(
state: SitePermissionOptionsScreenState,
action: SitePermissionOptionsScreenAction,
): SitePermissionOptionsScreenState {
return when (action) {
is SitePermissionOptionsScreenAction.Select -> {
state.copy(selectedSitePermissionOption = action.selectedSitePermissionOption)
}
is SitePermissionOptionsScreenAction.UpdateSitePermissionOptions -> {
state.copy(
sitePermissionOptionList = action.sitePermissionOptionsList,
selectedSitePermissionOption = action.selectedSitePermissionOption,
sitePermissionLabel = action.sitePermissionLabel,
isAndroidPermissionGranted = action.isAndroidPermissionGranted,
)
}
SitePermissionOptionsScreenAction.InitSitePermissionOptions -> {
throw IllegalStateException(
"You need to add SitePermissionsOptionsMiddleware to your SitePermissionsOptionsScreenStore. ($action)",
)
}
is SitePermissionOptionsScreenAction.AndroidPermission -> {
state.copy(isAndroidPermissionGranted = action.isAndroidPermissionGranted)
}
}
}
| mpl-2.0 | c658aded129d3b54f107b829c1bf3aad | 44.414286 | 120 | 0.763133 | 5.547993 | false | false | false | false |
mozilla-mobile/focus-android | app/src/androidTest/java/org/mozilla/focus/activity/CustomTabTest.kt | 1 | 4453 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
@file:Suppress("DEPRECATION")
package org.mozilla.focus.activity
import androidx.lifecycle.Lifecycle
import androidx.test.core.app.launchActivity
import androidx.test.internal.runner.junit4.AndroidJUnit4ClassRunner
import androidx.test.rule.ActivityTestRule
import okhttp3.mockwebserver.MockWebServer
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mozilla.focus.activity.robots.browserScreen
import org.mozilla.focus.activity.robots.customTab
import org.mozilla.focus.helpers.FeatureSettingsHelper
import org.mozilla.focus.helpers.MockWebServerHelper
import org.mozilla.focus.helpers.TestAssetHelper.getGenericAsset
import org.mozilla.focus.helpers.TestAssetHelper.getGenericTabAsset
import org.mozilla.focus.helpers.TestHelper.createCustomTabIntent
import org.mozilla.focus.helpers.TestHelper.mDevice
import org.mozilla.focus.helpers.TestHelper.waitingTime
import org.mozilla.focus.testAnnotations.SmokeTest
import java.io.IOException
@RunWith(AndroidJUnit4ClassRunner::class)
class CustomTabTest {
private lateinit var webServer: MockWebServer
private val MENU_ITEM_LABEL = "TestItem4223"
private val ACTION_BUTTON_DESCRIPTION = "TestButton"
private val featureSettingsHelper = FeatureSettingsHelper()
@get: Rule
val activityTestRule = ActivityTestRule(
IntentReceiverActivity::class.java,
true,
false,
)
@Before
fun setUp() {
featureSettingsHelper.setCfrForTrackingProtectionEnabled(false)
featureSettingsHelper.setShowStartBrowsingCfrEnabled(false)
webServer = MockWebServer().apply {
dispatcher = MockWebServerHelper.AndroidAssetDispatcher()
start()
}
}
@After
fun tearDown() {
try {
webServer.shutdown()
} catch (e: IOException) {
throw AssertionError("Could not stop web server", e)
}
featureSettingsHelper.resetAllFeatureFlags()
}
@SmokeTest
@Test
fun testCustomTabUI() {
val customTabPage = getGenericAsset(webServer)
val customTabActivity =
launchActivity<IntentReceiverActivity>(
createCustomTabIntent(customTabPage.url, MENU_ITEM_LABEL, ACTION_BUTTON_DESCRIPTION),
)
browserScreen {
progressBar.waitUntilGone(waitingTime)
verifyPageContent(customTabPage.content)
verifyPageURL(customTabPage.url)
}
customTab {
verifyCustomTabActionButton(ACTION_BUTTON_DESCRIPTION)
verifyShareButtonIsDisplayed()
openCustomTabMenu()
verifyTheStandardMenuItems()
verifyCustomMenuItem(MENU_ITEM_LABEL)
// Close the menu and close the tab
mDevice.pressBack()
closeCustomTab()
assertEquals(Lifecycle.State.DESTROYED, customTabActivity.state)
}
}
@SmokeTest
@Test
fun openCustomTabInFocusTest() {
val customTabPage = getGenericTabAsset(webServer, 1)
launchActivity<IntentReceiverActivity>(createCustomTabIntent(customTabPage.url))
customTab {
progressBar.waitUntilGone(waitingTime)
verifyPageURL(customTabPage.url)
openCustomTabMenu()
}.clickOpenInFocusButton {
verifyPageURL(customTabPage.url)
}
}
@SmokeTest
@Test
fun customTabNavigationButtonsTest() {
val firstPage = getGenericTabAsset(webServer, 1)
val secondPage = getGenericTabAsset(webServer, 2)
launchActivity<IntentReceiverActivity>(createCustomTabIntent(firstPage.url))
customTab {
verifyPageContent(firstPage.content)
clickLinkMatchingText("Tab 2")
verifyPageURL(secondPage.url)
}.openCustomTabMenu {
}.pressBack {
progressBar.waitUntilGone(waitingTime)
verifyPageURL(firstPage.url)
}.openMainMenu {
}.pressForward {
verifyPageURL(secondPage.url)
}.openMainMenu {
}.clickReloadButton {
verifyPageContent(secondPage.content)
}
}
}
| mpl-2.0 | dd662b4e83950e40d7c60ccdbedc9b4b | 32.734848 | 101 | 0.69616 | 4.793326 | false | true | false | false |
anton-okolelov/intellij-rust | src/test/kotlin/org/rust/lang/core/resolve/RsNonPhysicalFileResolveTest.kt | 3 | 1537 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.resolve
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiElementVisitor
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiFileFactory
import org.rust.lang.RsLanguage
class RsNonPhysicalFileResolveTest : RsResolveTestBase() {
fun test() {
val code = """
extern crate foo;
use foo;
use std::io;
use self::bar;
use super::baz;
mod not_here;
mod innner {
mod not_there_either;
use super::not_here;
use super::super::super::quux;
}
fn main() {
let h = ::std::collections::Vec::<i32>new();
}
struct S;
trait T: foo::Bar {}
"""
tryResolveEverything(memoryOnlyFile(code))
}
private fun tryResolveEverything(file: PsiFile) {
file.accept(object : PsiElementVisitor() {
override fun visitElement(element: PsiElement?) {
element ?: return
element.reference?.resolve()
element.acceptChildren(this)
}
})
}
private fun memoryOnlyFile(code: String): PsiFile =
PsiFileFactory.getInstance(project).createFileFromText("foo.rs", RsLanguage, code, false, false).apply {
check(this.containingFile.virtualFile == null)
}
}
| mit | e6df7168b0a2f1760b9af9263fcbe29a | 25.050847 | 112 | 0.567339 | 4.685976 | false | true | false | false |
huoguangjin/MultiHighlight | src/main/java/com/github/huoguangjin/multihighlight/ui/ColorPreviewPanel.kt | 1 | 2715 | package com.github.huoguangjin.multihighlight.ui
import com.github.huoguangjin.multihighlight.config.NamedTextAttr
import com.github.huoguangjin.multihighlight.highlight.MultiHighlightManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.ex.EditorMarkupModel
import com.intellij.openapi.editor.markup.HighlighterTargetArea
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.util.ui.UIUtil
import javax.swing.JComponent
/**
* [com.intellij.application.options.colors.SimpleEditorPreview]
*/
class ColorPreviewPanel : PreviewPanel {
private val editor: Editor
init {
val editorFactory = EditorFactory.getInstance()
editor = editorFactory.createViewer(editorFactory.createDocument(""))
editor.settings.apply {
isLineMarkerAreaShown = false
isIndentGuidesShown = false
}
(editor.markupModel as EditorMarkupModel).isErrorStripeVisible = true
}
override val panel: JComponent = editor.component
override fun updateView(textAttrs: List<NamedTextAttr>) {
UIUtil.invokeLaterIfNeeded {
if (editor.isDisposed) {
return@invokeLaterIfNeeded
}
editor.markupModel.removeAllHighlighters()
editor.selectionModel.removeSelection()
val text = textAttrs.joinToString("\n") { it.name }
ApplicationManager.getApplication().runWriteAction {
editor.document.setText(text)
}
textAttrs.forEachIndexed(::highlightLine)
}
}
private fun highlightLine(index: Int, textAttr: NamedTextAttr) {
UIUtil.invokeAndWaitIfNeeded(Runnable {
try {
val markupModel = editor.markupModel
val doc = markupModel.document
val lineStartOffset = doc.getLineStartOffset(index)
val lineEndOffset = doc.getLineEndOffset(index)
// IDEA-53203: add ERASE_MARKER for manually defined attributes
markupModel.addRangeHighlighter(
lineStartOffset, lineEndOffset,
MultiHighlightManager.MULTI_HIGHLIGHT_LAYER, TextAttributes.ERASE_MARKER,
HighlighterTargetArea.EXACT_RANGE
)
markupModel.addRangeHighlighter(
lineStartOffset, lineEndOffset,
MultiHighlightManager.MULTI_HIGHLIGHT_LAYER, textAttr,
HighlighterTargetArea.EXACT_RANGE
)
} catch (e: Exception) {
throw RuntimeException(e)
}
})
}
override fun blinkSelectedColor(textAttr: NamedTextAttr) {
}
private fun stopBlinking() {
}
override fun disposeUIResources() {
EditorFactory.getInstance().releaseEditor(editor)
stopBlinking()
}
}
| gpl-3.0 | c992ffef949c234c7d6fca83136e4912 | 29.505618 | 83 | 0.733702 | 4.763158 | false | false | false | false |
yshrsmz/monotweety | app/src/main/java/net/yslibrary/monotweety/base/EventBus.kt | 1 | 569 | package net.yslibrary.monotweety.base
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import kotlin.reflect.KClass
class EventBus {
private val bus = PublishSubject.create<Event>().toSerialized()
fun emit(event: Event): Unit = bus.onNext(event)
fun <R : Event> on(kClass: KClass<R>): Observable<R> = bus.ofType(kClass.java)
fun <R : Event> on(kClass: KClass<R>, initialValue: R): Observable<R> =
bus.ofType(kClass.java).startWith(initialValue)
fun hasObservers() = bus.hasObservers()
interface Event
}
| apache-2.0 | 25c2b48a8c87ff84ae94a090b89a73ee | 26.095238 | 82 | 0.717047 | 3.870748 | false | false | false | false |
edvin/tornadofx-idea-plugin | src/main/kotlin/no/tornado/tornadofx/idea/actions/NewViewAction.kt | 1 | 6424 | package no.tornado.tornadofx.idea.actions
import com.intellij.ide.fileTemplates.FileTemplate
import com.intellij.ide.fileTemplates.FileTemplateManager
import com.intellij.ide.fileTemplates.FileTemplateUtil
import com.intellij.ide.fileTemplates.actions.CreateFromTemplateActionBase
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.FileEditorManager
//import com.intellij.openapi.project.DumbModePermission
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.MessageType
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.ui.awt.RelativePoint
import com.intellij.util.IncorrectOperationException
import no.tornado.tornadofx.idea.allRoots
import org.apache.velocity.runtime.parser.ParseException
import org.jetbrains.kotlin.psi.KtFile
class NewViewAction : AnAction() {
val log: Logger = Logger.getInstance("#no.tornado.tornadofx.idea.actions.NewViewAction")
override fun actionPerformed(e: AnActionEvent) {
val dialog = NewViewDialog(e.project!!)
dialog.show()
if (dialog.isOK) {
val templateName = dialog.myKindCombo.selectedName
val fileName = dialog.myNameField.text
val rootType = dialog.rootType.text
val viewType = dialog.myTypeCombo.selectedItem as String
val template = FileTemplateManager.getInstance(e.project!!).getInternalTemplate(templateName)
val view = LangDataKeys.IDE_VIEW.getData(e.dataContext)!!
val createdElement = createFileFromTemplate(fileName, template, view.orChooseDirectory!!, rootType, viewType)
if (createdElement != null)
postProcess(createdElement, templateName, rootType, viewType)
}
}
fun postProcess(createdElement: PsiFile, templateName: String, rootType: String, viewType: String) {
// Create FXML companion to the source file
if (templateName == "TornadoFX FXML View") {
val project = createdElement.project
val template = FileTemplateManager.getInstance(project).getInternalTemplate("TornadoFX FXML ViewResource")
// Prefer resources folder as target for FXML file
val resourcesRoot = project.allRoots().find { it.name == "resources" }
val targetDir: PsiDirectory
if (resourcesRoot != null) {
// Split package components into list
val pkgNames = (createdElement as KtFile).packageFqName.asString().split(".")
// Make sure we have created all subfolders
var virtualDirectory: VirtualFile = resourcesRoot
pkgNames.forEach { pkgName ->
val existing = virtualDirectory.findChild(pkgName)
virtualDirectory = existing ?: virtualDirectory.createChildDirectory(null, pkgName)
}
// Convert target to a PSIDirectory
targetDir = PsiManager.getInstance(project).findDirectory(virtualDirectory)!!
} else {
// Revert to creating the FXML file in same dir as the source file
targetDir = createdElement.containingDirectory
}
createFileFromTemplate(createdElement.name.substringBefore(".") + ".fxml", template, targetDir, rootType, viewType)
}
}
fun createFileFromTemplate(name: String, template: FileTemplate, dir: PsiDirectory, rootType: String, viewType: String): PsiFile? {
var file: PsiFile? = null
// val dumbService = DumbService.getInstance(dir.project)
// object : DumbModeTask() {}
// dumbService.queueTask()
// dumbService.completeJustSubmittedTasks()
//DumbService.allowStartingDumbModeInside(DumbModePermission.MAY_START_BACKGROUND, Runnable {
val element: PsiElement
val project = dir.project
try {
val props = FileTemplateManager.getInstance(dir.project).defaultProperties
props["fqRootType"] = rootType
props["rootType"] = rootType.substringAfterLast(".")
props["initType"] = if(hasBuilder(project, rootType)) "builder" else "construct"
props["viewType"] = viewType
element = FileTemplateUtil.createFromTemplate(template, name, props, dir)
val psiFile = element.containingFile
val virtualFile = psiFile.virtualFile
if (virtualFile != null) {
if (template.isLiveTemplateEnabled) {
CreateFromTemplateActionBase.startLiveTemplate(psiFile)
} else {
FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
file = psiFile
}
} catch (e: ParseException) {
Messages.showErrorDialog(project, "Error parsing Velocity template: " + e.message, "Create File from Template")
} catch (e: IncorrectOperationException) {
throw e
} catch (e: Exception) {
log.error(e)
}
//})
return file
}
private fun hasBuilder(project: Project, rootType: String): Boolean {
val builderName = rootType.substringAfterLast(".").toLowerCase()
val layouts = JavaPsiFacade.getInstance(project).findClass("tornadofx.LayoutsKt", GlobalSearchScope.allScope(project))
if (layouts == null) {
val statusBar = WindowManager.getInstance().getStatusBar(project)
JBPopupFactory.getInstance()
.createHtmlTextBalloonBuilder("TornadoFX was not found on your classpath. You must add it to reliably use the TornadoFX plugin.", MessageType.WARNING, null)
.setFadeoutTime(7500)
.createBalloon()
.show(RelativePoint.getCenterOf(statusBar.component), Balloon.Position.atRight)
return true
} else {
return layouts.findMethodsByName(builderName, true).isNotEmpty()
}
}
} | apache-2.0 | 4d350f21455d5531438ae937ec6351b5 | 44.246479 | 176 | 0.674658 | 5.184826 | false | false | false | false |
pyamsoft/home-button | app/src/main/java/com/pyamsoft/homebutton/HomeButton.kt | 1 | 4525 | /*
* Copyright 2020 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.homebutton
import android.app.Application
import android.content.ComponentName
import android.content.pm.PackageManager
import androidx.annotation.CheckResult
import coil.ImageLoader
import com.pyamsoft.homebutton.receiver.BootCompletedReceiver
import com.pyamsoft.pydroid.bootstrap.libraries.OssLibraries
import com.pyamsoft.pydroid.core.requireNotNull
import com.pyamsoft.pydroid.ui.PYDroid
import timber.log.Timber
class HomeButton : Application() {
// Must be lazy since Coil calls getSystemService() internally,
// leading to SO exception
private val lazyImageLoader = lazy(LazyThreadSafetyMode.NONE) { ImageLoader(this) }
// The order that the PYDroid instance and Component instance are created is very specific.
//
// Coil lazy loader must be first, then PYDroid, and then Component
private var pydroid: PYDroid? = null
private var component: HomeButtonComponent? = null
private fun installPYDroid() {
if (pydroid == null) {
val url = "https://github.com/pyamsoft/home-button"
installLogger()
pydroid =
PYDroid.init(
this,
PYDroid.Parameters(
// Must be lazy since Coil calls getSystemService() internally,
// leading to SO exception
lazyImageLoader = lazyImageLoader,
viewSourceUrl = url,
bugReportUrl = "$url/issues",
privacyPolicyUrl = PRIVACY_POLICY_URL,
termsConditionsUrl = TERMS_CONDITIONS_URL,
version = BuildConfig.VERSION_CODE,
logger = createLogger(),
theme = HomeButtonThemeProvider,
debug =
PYDroid.DebugParameters(
enabled = true,
upgradeAvailable = true,
ratingAvailable = false,
),
),
)
} else {
Timber.w("Cannot install PYDroid again")
}
}
private fun installComponent() {
if (component == null) {
val p =
pydroid.requireNotNull { "Must install PYDroid before installing HomeButtonComponent" }
component =
DaggerHomeButtonComponent.factory()
.create(
application = this,
theming = p.modules().theming(),
)
} else {
Timber.w("Cannot install HomeButtonComponent again")
}
}
@CheckResult
private fun componentGraph(): HomeButtonComponent {
return component.requireNotNull { "HomeButtonComponent was not installed, something is wrong." }
}
@CheckResult
private fun fallbackGetSystemService(name: String): Any? {
return if (name == HomeButtonComponent::class.java.name) componentGraph()
else super.getSystemService(name)
}
/** Ensure the BootReceiver is set to state enabled */
private fun ensureBootReceiverEnabled() {
val componentName = ComponentName(this, BootCompletedReceiver::class.java)
packageManager.setComponentEnabledSetting(
componentName,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP,
)
}
override fun onCreate() {
super.onCreate()
installPYDroid()
installComponent()
addLibraries()
ensureBootReceiverEnabled()
}
override fun getSystemService(name: String): Any? {
return pydroid?.getSystemService(name) ?: fallbackGetSystemService(name)
}
companion object {
const val PRIVACY_POLICY_URL = "https://pyamsoft.blogspot.com/p/home-button-privacy-policy.html"
const val TERMS_CONDITIONS_URL =
"https://pyamsoft.blogspot.com/p/home-button-terms-and-conditions.html"
private fun addLibraries() {
// Using pydroid-notify
OssLibraries.usingNotify = true
// Using pydroid-autopsy
OssLibraries.usingAutopsy = true
}
}
}
| apache-2.0 | d5a73c3abdad572f9e51c4322a772d0f | 32.029197 | 100 | 0.660552 | 4.728318 | false | false | false | false |
kibotu/RecyclerViewPresenter | app/src/main/kotlin/net/kibotu/android/recyclerviewpresenter/app/screens/nested/NestedActivity.kt | 1 | 1970 | package net.kibotu.android.recyclerviewpresenter.app.screens.nested
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import net.kibotu.android.recyclerviewpresenter.PresenterAdapter
import net.kibotu.android.recyclerviewpresenter.PresenterViewModel
import net.kibotu.android.recyclerviewpresenter.app.R
class NestedActivity : AppCompatActivity() {
val adapter = PresenterAdapter()
private val list: RecyclerView
get() = findViewById(R.id.list)
private val swipeRefresh: SwipeRefreshLayout
get() = findViewById(R.id.swipeRefresh)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addResultList()
}
private fun addResultList() {
list.layoutManager = LinearLayoutManager(this)
list.setRecycledViewPool(RecyclerView.RecycledViewPool())
list.setHasFixedSize(true)
adapter.registerPresenter(RowPresenter())
adapter.registerPresenter(HorizontalListPresenter())
list.adapter = adapter
addResults(100)
// ignore for now
swipeRefresh.setOnRefreshListener {
swipeRefresh.isRefreshing = false
}
}
private fun addResults(amount: Int) {
val images = (0 until amount).map {
"https://via.placeholder.com/2%02d/300/".format(it)
}
val items: MutableList<PresenterViewModel<*>> = images.map {
PresenterViewModel(Row(it, "$it label"), uuid = it, layout = R.layout.item_icon_with_label)
}.toMutableList()
items.add(0, PresenterViewModel(HorizontalListItems(images.map {
Column(it)
}), R.layout.item_horizontal_list))
adapter.submitList(items)
}
} | apache-2.0 | b11ae945467e3037fbd6ad9793642cda | 29.796875 | 103 | 0.706091 | 4.864198 | false | false | false | false |
danfma/kodando | kodando-store/src/main/kotlin/kodando/store/Store.kt | 1 | 1692 | package kodando.store
import kodando.rxjs.BehaviorSubject
import kodando.rxjs.Subject
import kodando.rxjs.Unsubscribable
import kodando.rxjs.observable.fromArray
import kodando.rxjs.operators.map
import kodando.rxjs.operators.merge
import kodando.rxjs.operators.mergeMap
import kodando.rxjs.operators.scan
import kodando.rxjs.subscribeNext
class Store<T>(
initialState: T,
reducer: Reducer<T>,
effects: Array<out Effect<T>>,
private val actionDispatcher: ActionDispatcher
) : BehaviorSubject<T>(initialState) {
private val subscription: Unsubscribable
init {
val enhancedReducer: Reducer<T> = enhanceReducer(reducer)
val mutationS = Subject<Pair<T, Action>>()
val reactionS = fromArray(effects)
.mergeMap { it.watch(mutationS) }
val actionAndReactionS = actionDispatcher.asObservable().merge(reactionS)
subscription = actionAndReactionS
.map { value to it }
.scan((initialState to Init) as Pair<T, Action>) { (prevState, _), (_, nextAction) ->
val nextState = enhancedReducer(prevState, nextAction)
nextState to nextAction
}
.subscribeNext { mutation ->
this.next(mutation.first)
mutationS.next(mutation)
}
}
constructor(initialState: T, reducer: Reducer<T>, vararg effects: Effect<T>)
: this(initialState, reducer, effects, GlobalActionDispatcher)
fun dispatch(action: Action) {
actionDispatcher.dispatch(action)
}
private fun enhanceReducer(reducer: Reducer<T>): Reducer<T> = { state, action ->
try {
reducer(state, action)
} catch (e: Throwable) {
console.error("Error while processing action", action, "error", e)
state
}
}
}
| mit | c277f92e468edf98e1eba6c575acd342 | 27.2 | 91 | 0.708038 | 4.096852 | false | false | false | false |
CodeIntelligenceTesting/jazzer | agent/src/main/java/com/code_intelligence/jazzer/agent/CoverageIdStrategy.kt | 1 | 9973 | // Copyright 2021 Code Intelligence GmbH
//
// 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.code_intelligence.jazzer.agent
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.channels.FileLock
import java.nio.file.Path
import java.nio.file.StandardOpenOption
import java.util.UUID
/**
* Indicates a fatal failure to generate synchronized coverage IDs.
*/
class CoverageIdException(cause: Throwable? = null) :
RuntimeException("Failed to synchronize coverage IDs", cause)
/**
* [CoverageIdStrategy] provides an abstraction to switch between context specific coverage ID generation.
*
* Coverage (i.e., edge) IDs differ from other kinds of IDs, such as those generated for call sites or cmp
* instructions, in that they should be consecutive, collision-free, and lie in a known, small range.
* This precludes us from generating them simply as hashes of class names.
*/
interface CoverageIdStrategy {
/**
* [withIdForClass] provides the initial coverage ID of the given [className] as parameter to the
* [block] to execute. [block] has to return the number of additionally used IDs.
*/
@Throws(CoverageIdException::class)
fun withIdForClass(className: String, block: (Int) -> Int)
}
/**
* A memory synced strategy for coverage ID generation.
*
* This strategy uses a synchronized block to guard access to a global edge ID counter.
* Even though concurrent fuzzing is not fully supported this strategy enables consistent coverage
* IDs in case of concurrent class loading.
*
* It only prevents races within one VM instance.
*/
class MemSyncCoverageIdStrategy : CoverageIdStrategy {
private var nextEdgeId = 0
@Synchronized
override fun withIdForClass(className: String, block: (Int) -> Int) {
nextEdgeId += block(nextEdgeId)
}
}
/**
* A strategy for coverage ID generation that synchronizes the IDs assigned to a class with other processes via the
* specified [idSyncFile].
* This class takes care of synchronizing the access to the file between multiple processes as long as the general
* contract of [CoverageIdStrategy] is followed.
*/
class FileSyncCoverageIdStrategy(private val idSyncFile: Path) : CoverageIdStrategy {
private val uuid: UUID = UUID.randomUUID()
private var idFileLock: FileLock? = null
private var cachedFirstId: Int? = null
private var cachedClassName: String? = null
private var cachedIdCount: Int? = null
/**
* This method is synchronized to prevent concurrent access to the internal file lock which would result in
* [java.nio.channels.OverlappingFileLockException]. Furthermore, every coverage ID obtained by [obtainFirstId]
* is always committed back again to the sync file by [commitIdCount].
*/
@Synchronized
override fun withIdForClass(className: String, block: (Int) -> Int) {
var actualNumEdgeIds = 0
try {
val firstId = obtainFirstId(className)
actualNumEdgeIds = block(firstId)
} finally {
commitIdCount(actualNumEdgeIds)
}
}
/**
* Obtains a coverage ID for [className] such that all cooperating agent processes will obtain the same ID.
* There are two cases to consider:
* - This agent process is the first to encounter [className], i.e., it does not find a record for that class in
* [idSyncFile]. In this case, a lock on the file is held until the class has been instrumented and a record with
* the required number of coverage IDs has been added.
* - Another agent process has already encountered [className], i.e., there is a record that class in [idSyncFile].
* In this case, the lock on the file is returned immediately and the extracted first coverage ID is returned to
* the caller. The caller is still expected to call [commitIdCount] so that desynchronization can be detected.
*/
private fun obtainFirstId(className: String): Int {
try {
check(idFileLock == null) { "Already holding a lock on the ID file" }
val localIdFile = FileChannel.open(
idSyncFile,
StandardOpenOption.WRITE,
StandardOpenOption.READ
)
// Wait until we have obtained the lock on the sync file. We hold the lock from this point until we have
// finished reading and writing (if necessary) to the file.
val localIdFileLock = localIdFile.lock()
check(localIdFileLock.isValid && !localIdFileLock.isShared)
// Parse the sync file, which consists of lines of the form
// <class name>:<first ID>:<num IDs>
val idInfo = localIdFileLock.channel().readFully()
.lineSequence()
.filterNot { it.isBlank() }
.map { line ->
val parts = line.split(':')
check(parts.size == 4) {
"Expected ID file line to be of the form '<class name>:<first ID>:<num IDs>:<uuid>', got '$line'"
}
val lineClassName = parts[0]
val lineFirstId = parts[1].toInt()
check(lineFirstId >= 0) { "Negative first ID in line: $line" }
val lineIdCount = parts[2].toInt()
check(lineIdCount >= 0) { "Negative ID count in line: $line" }
Triple(lineClassName, lineFirstId, lineIdCount)
}.toList()
cachedClassName = className
val idInfoForClass = idInfo.filter { it.first == className }
return when (idInfoForClass.size) {
0 -> {
// We are the first to encounter this class and thus need to hold the lock until the class has been
// instrumented and we know the required number of coverage IDs.
idFileLock = localIdFileLock
// Compute the next free ID as the maximum over the sums of first ID and ID count, starting at 0 if
// this is the first ID to be assigned. In fact, since this is the only way new lines are added to
// the file, the maximum is always attained by the last line.
val nextFreeId = idInfo.asSequence().map { it.second + it.third }.lastOrNull() ?: 0
cachedFirstId = nextFreeId
nextFreeId
}
1 -> {
// This class has already been instrumented elsewhere, so we just return the first ID and ID count
// reported from there and release the lock right away. The caller is still expected to call
// commitIdCount.
localIdFile.close()
cachedIdCount = idInfoForClass.single().third
idInfoForClass.single().second
}
else -> {
localIdFile.close()
System.err.println(idInfo.joinToString("\n") { "${it.first}:${it.second}:${it.third}" })
throw IllegalStateException("Multiple entries for $className in ID file")
}
}
} catch (e: Exception) {
throw CoverageIdException(e)
}
}
/**
* Records the number of coverage IDs used to instrument the class specified in a previous call to [obtainFirstId].
* If instrumenting the class should fail, this function must still be called. In this case, [idCount] is set to 0.
*/
private fun commitIdCount(idCount: Int) {
val localIdFileLock = idFileLock
try {
check(cachedClassName != null)
if (localIdFileLock == null) {
// We released the lock already in obtainFirstId since the class had already been instrumented
// elsewhere. As we know the expected number of IDs for the current class in this case, check for
// deviations.
check(cachedIdCount != null)
check(idCount == cachedIdCount) {
"$cachedClassName has $idCount edges, but $cachedIdCount edges reserved in ID file"
}
} else {
// We are the first to instrument this class and should record the number of IDs in the sync file.
check(cachedFirstId != null)
localIdFileLock.channel().append("$cachedClassName:$cachedFirstId:$idCount:$uuid\n")
localIdFileLock.channel().force(true)
}
idFileLock = null
cachedFirstId = null
cachedIdCount = null
cachedClassName = null
} catch (e: Exception) {
throw CoverageIdException(e)
} finally {
localIdFileLock?.channel()?.close()
}
}
}
/**
* Reads the [FileChannel] to the end as a UTF-8 string.
*/
fun FileChannel.readFully(): String {
check(size() <= Int.MAX_VALUE)
val buffer = ByteBuffer.allocate(size().toInt())
while (buffer.hasRemaining()) {
when (read(buffer)) {
0 -> throw IllegalStateException("No bytes read")
-1 -> break
}
}
return String(buffer.array())
}
/**
* Appends [string] to the end of the [FileChannel].
*/
fun FileChannel.append(string: String) {
position(size())
write(ByteBuffer.wrap(string.toByteArray()))
}
| apache-2.0 | 8bebec865452aa0d7c1524cbe55de6f2 | 43.923423 | 122 | 0.629099 | 4.655929 | false | false | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/crossing/AddCrossing.kt | 1 | 9261 | package de.westnordost.streetcomplete.quests.crossing
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.*
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.PEDESTRIAN
import de.westnordost.streetcomplete.quests.kerb_height.AddKerbHeightForm
import de.westnordost.streetcomplete.quests.kerb_height.KerbHeight
import de.westnordost.streetcomplete.util.isRightOf
import de.westnordost.streetcomplete.util.normalizeDegrees
class AddCrossing : OsmElementQuestType<KerbHeight> {
private val roadsFilter by lazy { """
ways with
highway ~ trunk|trunk_link|primary|primary_link|secondary|secondary_link|tertiary|tertiary_link|unclassified|residential
and area != yes
and (access !~ private|no or (foot and foot !~ private|no))
""".toElementFilterExpression() }
private val footwaysFilter by lazy { """
ways with
(highway ~ footway|steps or highway ~ path|cycleway and foot ~ designated|yes)
and footway != sidewalk
and area != yes
and access !~ private|no
""".toElementFilterExpression() }
override val commitMessage = "Add whether there is a crossing"
override val wikiLink = "Tag:highway=crossing"
override val icon = R.drawable.ic_quest_pedestrian
override val questTypeAchievements = listOf(PEDESTRIAN)
override fun getTitle(tags: Map<String, String>) = R.string.quest_crossing_title
override fun isApplicableTo(element: Element): Boolean? =
if(element !is Node || element.tags.isNotEmpty()) false else null
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> {
val roadsByNodeId = mapData.ways.asSequence()
.filter { roadsFilter.matches(it) }
.groupByNodeIds()
/* filter out nodes of roads that are the end of a road network (dead end), e.g.
* https://www.openstreetmap.org/node/280046349 or
* https://www.openstreetmap.org/node/56606744 */
roadsByNodeId.removeEndNodes()
/* require all roads at a shared node to either have no sidewalk tagging or all of them to
* have sidewalk tagging: If the sidewalk tagging changes at that point, it may be an
* indicator that this is the transition point between separate sidewalk mapping and
* sidewalk mapping on road-way. F.e.:
* https://www.openstreetmap.org/node/1839120490 */
val anySidewalk = setOf("both","left","right")
roadsByNodeId.values.removeAll { ways ->
if (ways.any { it.tags["sidewalk"] in anySidewalk }) {
!ways.all { it.tags["sidewalk"] in anySidewalk }
} else {
false
}
}
val footwaysByNodeId = mapData.ways.asSequence()
.filter { footwaysFilter.matches(it) }
.groupByNodeIds()
/* filter out nodes of footways that are the end of a footway, e.g.
* https://www.openstreetmap.org/node/1449039062 or
* https://www.openstreetmap.org/node/56606744 */
footwaysByNodeId.removeEndNodes()
/* filter out all nodes that are not shared nodes of both a road and a footway */
roadsByNodeId.keys.retainAll(footwaysByNodeId.keys)
footwaysByNodeId.keys.retainAll(roadsByNodeId.keys)
/* finally, filter out all shared nodes where the footway(s) do not actually cross the road(s).
* There are two situations which both need to be handled:
*
* 1. The shared node is contained in a road way and a footway way and it is not an end
* node of any of the involved ways, e.g.
* https://www.openstreetmap.org/node/8418974983
*
* 2. The road way or the footway way or both actually end on the shared node but are
* connected to another footway / road way which continues the way after
* https://www.openstreetmap.org/node/1641565064
*
* So, for the algorithm, it should be irrelevant to which way(s) the segments around the
* shared node belong, what count are the positions / angles.
*/
footwaysByNodeId.entries.retainAll { (nodeId, footways) ->
val roads = roadsByNodeId.getValue(nodeId)
val neighbouringRoadPositions = roads
.flatMap { it.getNodeIdsNeighbouringNodeId(nodeId) }
.mapNotNull { mapData.getNode(it)?.position }
val neighbouringFootwayPositions = footways
.flatMap { it.getNodeIdsNeighbouringNodeId(nodeId) }
.mapNotNull { mapData.getNode(it)?.position }
/* So, surrounding the shared node X, in the simple case, we have
*
* 1. position A, B neighbouring the shared node position which are part of a road way
* 2. position P, Q neighbouring the shared node position which are part of the footway
*
* The footway crosses the road if P is on one side of the polyline spanned by A,X,B and
* Q is on the other side.
*
* How can a footway that has a shared node with a road not cross the latter?
* Imagine the road at https://www.openstreetmap.org/node/258003112 would continue to
* the south here, then, still none of those footways would actually cross the street
* - only if it continued straight to the north, for example.
*
* The example brings us to the less simple case: What if several roads roads share
* a node at a crossing-candidate position, like it is the case at every T-intersection?
* Also, what if there are more than one footways involved as in the link above?
*
* We look for if there is ANY crossing, so all polylines involved are checked:
* For all roads a car can go through point X, it is checked if not all footways that
* go through X are on the same side of the road-polyline.
* */
val nodePos = mapData.getNode(nodeId)?.position
return@retainAll nodePos != null &&
neighbouringFootwayPositions.anyCrossesAnyOf(neighbouringRoadPositions, nodePos)
}
return footwaysByNodeId.keys
.mapNotNull { mapData.getNode(it) }
.filter { it.tags.isEmpty() }
}
override fun createForm() = AddKerbHeightForm()
override fun applyAnswerTo(answer: KerbHeight, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("kerb", answer.osmValue)
/* So, we don't assume there is a crossing here for kerb=no and kerb=raised.
As most actual crossings will have at least lowered kerbs, this is a good indicator.
When there is no kerb at all, it is likely that this is a situation where the footway
or road drawn in OSM are just virtual, to connect the geometry. In other words, it may be
just e.g. an asphalted area, which does not really classify as a crossing.
*/
if (answer.osmValue in listOf("lowered", "flush")) {
changes.add("highway", "crossing")
}
}
}
/** get the node id(s) neighbouring to the given node id */
private fun Way.getNodeIdsNeighbouringNodeId(nodeId: Long): List<Long> {
val idx = nodeIds.indexOf(nodeId)
if (idx == -1) return emptyList()
val prevNodeId = if (idx > 0) nodeIds[idx - 1] else null
val nextNodeId = if (idx < nodeIds.size - 1) nodeIds[idx + 1] else null
return listOfNotNull(prevNodeId, nextNodeId)
}
private fun MutableMap<Long, MutableList<Way>>.removeEndNodes() {
entries.removeAll { (nodeId, ways) ->
ways.size == 1 && (nodeId == ways[0].nodeIds.first() || nodeId == ways[0].nodeIds.last())
}
}
/** groups the sequence of ways to a map of node id -> list of ways */
private fun Sequence<Way>.groupByNodeIds(): MutableMap<Long, MutableList<Way>> {
val result = mutableMapOf<Long, MutableList<Way>>()
forEach { way ->
way.nodeIds.forEach { nodeId ->
result.getOrPut(nodeId, { mutableListOf() } ).add(way)
}
}
return result
}
/** Returns whether any of the lines spanned by any of the points in this list through the
* vertex point cross any of the lines spanned by any of the points through the vertex point
* from the other list */
private fun List<LatLon>.anyCrossesAnyOf(other: List<LatLon>, vertex: LatLon): Boolean =
(1 until size).any { i -> other.anyAreOnDifferentSidesOf(this[0], vertex, this[i]) }
/** Returns whether any of the points in this list are on different sides of the line spanned
* by p0 and p1 and the line spanned by p1 and p2 */
private fun List<LatLon>.anyAreOnDifferentSidesOf(p0: LatLon, p1: LatLon, p2: LatLon): Boolean =
map { it.isRightOf(p0, p1, p2) }.toSet().size > 1
| gpl-3.0 | caab7aa3f44ca7cd3786492f65383c80 | 48 | 130 | 0.665371 | 4.291474 | false | false | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/fragment/WebFragment.kt | 1 | 4885 | /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.fragment
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebView
import mozilla.components.browser.session.Session
import org.mozilla.focus.R
import org.mozilla.focus.ext.savedWebViewState
import org.mozilla.focus.ext.shouldRequestDesktopSite
import org.mozilla.focus.locale.LocaleAwareFragment
import org.mozilla.focus.locale.LocaleManager
import org.mozilla.focus.utils.AppConstants
import org.mozilla.focus.web.IWebView
import java.util.Locale
/**
* Base implementation for fragments that use an IWebView instance. Based on Android's WebViewFragment.
*/
@Suppress("TooManyFunctions")
abstract class WebFragment : LocaleAwareFragment() {
private var webViewInstance: IWebView? = null
private var isWebViewAvailable: Boolean = false
abstract val session: Session?
/**
* Get the initial URL to load after the view has been created.
*/
abstract val initialUrl: String?
/**
* Inflate a layout for this fragment. The layout needs to contain a view implementing IWebView
* with the id set to "webview".
*/
abstract fun inflateLayout(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View
abstract fun createCallback(): IWebView.Callback
/**
* Adds ability to add methods to onCreateView without override because onCreateView is final.
*/
abstract fun onCreateViewCalled()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflateLayout(inflater, container, savedInstanceState)
val actualWebView = view.findViewById<View>(R.id.webview)
webViewInstance = actualWebView as IWebView
isWebViewAvailable = true
webViewInstance!!.setCallback(createCallback())
session?.let {
webViewInstance!!.setRequestDesktop(it.shouldRequestDesktopSite)
}
if (!AppConstants.isGeckoBuild) {
restoreStateOrLoadUrl()
} else {
loadInitialUrl()
}
onCreateViewCalled()
return view
}
override fun applyLocale() {
val context = context ?: return
val localeManager = LocaleManager.getInstance()
val currentLocale = localeManager.getCurrentLocale(context)
if (!localeManager.isMirroringSystemLocale(context)) {
Locale.setDefault(currentLocale)
val resources = context.resources
val config = resources.configuration
config.setLocale(currentLocale)
@Suppress("DEPRECATION")
context.resources.updateConfiguration(config, null)
}
getWebView()?.updateLocale(currentLocale)
// We create and destroy a new WebView here to force the internal state of WebView to know
// about the new language. See issue #666.
val unneeded = WebView(getContext())
unneeded.destroy()
}
override fun onPause() {
val session = session
if (session != null) {
webViewInstance!!.saveWebViewState(session)
}
webViewInstance!!.onPause()
super.onPause()
}
override fun onResume() {
webViewInstance!!.onResume()
if (AppConstants.isGeckoBuild) {
restoreStateOrLoadUrl()
}
super.onResume()
}
override fun onDestroy() {
if (webViewInstance != null) {
webViewInstance!!.setCallback(null)
webViewInstance!!.destroy()
webViewInstance = null
}
super.onDestroy()
}
override fun onDestroyView() {
isWebViewAvailable = false
super.onDestroyView()
}
protected fun getWebView(): IWebView? {
return if (isWebViewAvailable) webViewInstance else null
}
private fun loadInitialUrl() {
val session = session
if (session == null || session.savedWebViewState == null) {
val url = initialUrl
if (!TextUtils.isEmpty(url)) {
webViewInstance!!.loadUrl(url)
}
}
}
private fun restoreStateOrLoadUrl() {
val session = session
if (session == null || session.savedWebViewState == null) {
val url = initialUrl
if (!TextUtils.isEmpty(url)) {
webViewInstance!!.loadUrl(url)
}
} else {
webViewInstance!!.restoreWebViewState(session)
}
}
}
| mpl-2.0 | 9a72172512923b405685aa554558a32f | 29.72327 | 116 | 0.654452 | 4.89479 | false | false | false | false |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/service/system/v1alpha/ComputationsService.kt | 1 | 8950 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.system.v1alpha
import io.grpc.Status
import io.grpc.StatusException
import java.util.logging.Logger
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.ExperimentalTime
import kotlin.time.TimeMark
import kotlin.time.TimeSource
import kotlinx.coroutines.currentCoroutineContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.isActive
import org.wfanet.measurement.api.v2alpha.DuchyCertificateKey
import org.wfanet.measurement.common.base64UrlDecode
import org.wfanet.measurement.common.base64UrlEncode
import org.wfanet.measurement.common.grpc.grpcRequireNotNull
import org.wfanet.measurement.common.identity.DuchyIdentity
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.identity.duchyIdentityFromContext
import org.wfanet.measurement.internal.kingdom.GetMeasurementByComputationIdRequest
import org.wfanet.measurement.internal.kingdom.Measurement
import org.wfanet.measurement.internal.kingdom.MeasurementsGrpcKt.MeasurementsCoroutineStub
import org.wfanet.measurement.internal.kingdom.StreamMeasurementsRequestKt.filter
import org.wfanet.measurement.internal.kingdom.setMeasurementResultRequest
import org.wfanet.measurement.internal.kingdom.streamMeasurementsRequest
import org.wfanet.measurement.system.v1alpha.Computation
import org.wfanet.measurement.system.v1alpha.ComputationKey
import org.wfanet.measurement.system.v1alpha.ComputationsGrpcKt.ComputationsCoroutineImplBase
import org.wfanet.measurement.system.v1alpha.GetComputationRequest
import org.wfanet.measurement.system.v1alpha.SetComputationResultRequest
import org.wfanet.measurement.system.v1alpha.StreamActiveComputationsContinuationToken
import org.wfanet.measurement.system.v1alpha.StreamActiveComputationsRequest
import org.wfanet.measurement.system.v1alpha.StreamActiveComputationsResponse
import org.wfanet.measurement.system.v1alpha.streamActiveComputationsContinuationToken
import org.wfanet.measurement.system.v1alpha.streamActiveComputationsResponse
@OptIn(ExperimentalTime::class)
class ComputationsService(
private val measurementsClient: MeasurementsCoroutineStub,
private val duchyIdentityProvider: () -> DuchyIdentity = ::duchyIdentityFromContext,
private val streamingTimeout: Duration = 10.minutes,
private val streamingThrottle: Duration = 1.seconds
) : ComputationsCoroutineImplBase() {
override suspend fun getComputation(request: GetComputationRequest): Computation {
val computationKey =
grpcRequireNotNull(ComputationKey.fromName(request.name)) {
"Resource name unspecified or invalid."
}
val internalRequest =
GetMeasurementByComputationIdRequest.newBuilder()
.apply { externalComputationId = apiIdToExternalId(computationKey.computationId) }
.build()
try {
return measurementsClient.getMeasurementByComputationId(internalRequest).toSystemComputation()
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
Status.Code.CANCELLED -> Status.CANCELLED
else -> Status.UNKNOWN
}
.withCause(e)
.asRuntimeException()
}
}
override fun streamActiveComputations(
request: StreamActiveComputationsRequest
): Flow<StreamActiveComputationsResponse> {
val streamingDeadline: TimeMark = TimeSource.Monotonic.markNow() + streamingTimeout
var currentContinuationToken = ContinuationTokenConverter.decode(request.continuationToken)
return flow {
// Continually request measurements from internal service until cancelled or streamingDeadline
// is reached.
//
// TODO(@SanjayVas): Figure out an alternative mechanism (e.g. Spanner change streams) to
// avoid having to poll internal service.
while (currentCoroutineContext().isActive && streamingDeadline.hasNotPassedNow()) {
streamMeasurements(currentContinuationToken)
.catch { cause ->
if (cause !is StatusException) throw cause
throw when (cause.status.code) {
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
Status.Code.CANCELLED -> Status.CANCELLED
else -> Status.UNKNOWN
}
.withCause(cause)
.asRuntimeException()
}
.collect { measurement ->
currentContinuationToken = streamActiveComputationsContinuationToken {
updateTimeSince = measurement.updateTime
lastSeenExternalComputationId = measurement.externalComputationId
}
val response = streamActiveComputationsResponse {
continuationToken = ContinuationTokenConverter.encode(currentContinuationToken)
computation = measurement.toSystemComputation()
}
emit(response)
}
delay(streamingThrottle)
}
}
}
override suspend fun setComputationResult(request: SetComputationResultRequest): Computation {
val computationKey =
grpcRequireNotNull(ComputationKey.fromName(request.name)) {
"Resource name unspecified or invalid."
}
// This assumes that the Certificate resource name is compatible with public API version
// v2alpha.
val aggregatorCertificateKey =
grpcRequireNotNull(DuchyCertificateKey.fromName(request.aggregatorCertificate)) {
"aggregator_certificate unspecified or invalid"
}
val authenticatedDuchy: DuchyIdentity = duchyIdentityProvider()
if (aggregatorCertificateKey.duchyId != authenticatedDuchy.id) {
throw Status.PERMISSION_DENIED.withDescription(
"Aggregator certificate not owned by authenticated Duchy"
)
.asRuntimeException()
}
val internalRequest = setMeasurementResultRequest {
externalComputationId = apiIdToExternalId(computationKey.computationId)
resultPublicKey = request.resultPublicKey
externalAggregatorDuchyId = aggregatorCertificateKey.duchyId
externalAggregatorCertificateId = apiIdToExternalId(aggregatorCertificateKey.certificateId)
encryptedResult = request.encryptedResult
}
try {
return measurementsClient.setMeasurementResult(internalRequest).toSystemComputation()
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
Status.Code.CANCELLED -> Status.CANCELLED
else -> Status.UNKNOWN
}
.withCause(e)
.asRuntimeException()
}
}
private fun streamMeasurements(
continuationToken: StreamActiveComputationsContinuationToken
): Flow<Measurement> {
val request = streamMeasurementsRequest {
filter = filter {
updatedAfter = continuationToken.updateTimeSince
externalComputationIdAfter = continuationToken.lastSeenExternalComputationId
states += STATES_SUBSCRIBED
externalDuchyId = duchyIdentityProvider().id
}
measurementView = Measurement.View.COMPUTATION
}
try {
return measurementsClient.streamMeasurements(request)
} catch (e: StatusException) {
throw when (e.status.code) {
Status.Code.DEADLINE_EXCEEDED -> Status.DEADLINE_EXCEEDED
Status.Code.CANCELLED -> Status.CANCELLED
else -> Status.UNKNOWN
}
.withCause(e)
.asRuntimeException()
}
}
companion object {
private val logger: Logger = Logger.getLogger(this::class.java.name)
}
}
private val STATES_SUBSCRIBED =
listOf(
Measurement.State.PENDING_REQUISITION_PARAMS,
Measurement.State.PENDING_PARTICIPANT_CONFIRMATION,
Measurement.State.PENDING_COMPUTATION,
Measurement.State.FAILED,
Measurement.State.CANCELLED
)
private object ContinuationTokenConverter {
fun encode(token: StreamActiveComputationsContinuationToken): String =
token.toByteArray().base64UrlEncode()
fun decode(token: String): StreamActiveComputationsContinuationToken =
StreamActiveComputationsContinuationToken.parseFrom(token.base64UrlDecode())
}
| apache-2.0 | 2a5a37bf2a15e749203330b072e5950b | 41.822967 | 100 | 0.755642 | 4.963949 | false | false | false | false |
Shoebill/streamer-wrapper | src/main/java/net/gtaun/shoebill/streamer/data/DynamicMapIcon.kt | 1 | 2036 | package net.gtaun.shoebill.streamer.data
import net.gtaun.shoebill.entities.Destroyable
import net.gtaun.shoebill.entities.Player
import net.gtaun.shoebill.constant.MapIconStyle
import net.gtaun.shoebill.data.Color
import net.gtaun.shoebill.data.Location
import net.gtaun.shoebill.streamer.AllOpen
import net.gtaun.shoebill.streamer.Functions
import java.util.*
/**
* Created by marvin on 19.02.16.
* Copyright (c) 2015 Marvin Haschker. All rights reserved.
*/
@AllOpen
class DynamicMapIcon(id: Int, val location: Location, val type: Int, val color: Color, val player: Player?,
val streamDistance: Float, val style: MapIconStyle) : Destroyable {
final var id: Int = id
private set
override fun destroy() {
if (isDestroyed)
return
Functions.destroyDynamicMapIcon(this)
id = -1
removeSelf()
}
override val isDestroyed: Boolean
get() = id == -1
private fun removeSelf() = objects.remove(this)
companion object {
@JvmField val DEFAULT_STREAM_DISTANCE = 200f //From streamer.inc STREAMER_MAP_ICON_SD
@JvmField val DEFAULT_ICON_STYLE = MapIconStyle.LOCAL //From streamer.inc
private var objects = mutableListOf<DynamicMapIcon>()
@JvmStatic fun get(): Set<DynamicMapIcon> = HashSet(objects)
@JvmStatic
operator fun get(id: Int): DynamicMapIcon? = objects.find { it.id == id }
@JvmOverloads
@JvmStatic
fun create(location: Location, type: Int, color: Color, streamDistance: Float = DEFAULT_STREAM_DISTANCE,
style: MapIconStyle = DEFAULT_ICON_STYLE, priority: Int = 0, player: Player? = null,
area: DynamicArea? = null): DynamicMapIcon {
val playerId = player?.id ?: -1
val `object` = Functions.createDynamicMapIcon(location, type, color, playerId, streamDistance, style, area,
priority)
objects.add(`object`)
return `object`
}
}
}
| agpl-3.0 | c86fe57e7e5be2093015554031691214 | 31.31746 | 119 | 0.65275 | 4.14664 | false | false | false | false |
renyuneyun/Easer | app/src/main/java/ryey/easer/core/log/ServiceLog.kt | 1 | 2270 | /*
* Copyright (c) 2016 - 2019 Rui Zhao <[email protected]>
*
* This file is part of Easer.
*
* Easer 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.
*
* Easer 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 Easer. If not, see <http://www.gnu.org/licenses/>.
*/
package ryey.easer.core.log
import android.os.Parcel
import android.os.Parcelable
class ServiceLog : BasicLog {
val serviceName: String
val start: Boolean
constructor(serviceName: String, start: Boolean, extraInfo: String? = null) : super(extraInfo) {
this.serviceName = serviceName
this.start = start
}
override fun equals(other: Any?): Boolean {
if (!super.equals(other))
return false
other as ServiceLog
if (serviceName != other.serviceName)
return false
if (start != other.start)
return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + serviceName.hashCode()
result = 31 * result + start.hashCode()
return result
}
constructor(parcel: Parcel) : super(parcel) {
serviceName = parcel.readString()!!
start = parcel.readByte() > 0
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
super.writeToParcel(parcel, flags)
parcel.writeString(serviceName)
parcel.writeByte(if (start) 1 else 0)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<ServiceLog> {
override fun createFromParcel(parcel: Parcel): ServiceLog {
return ServiceLog(parcel)
}
override fun newArray(size: Int): Array<ServiceLog?> {
return arrayOfNulls(size)
}
}
} | gpl-3.0 | af6569ea7e6287858ca8eae8f5ea523b | 28.493506 | 100 | 0.649339 | 4.373796 | false | false | false | false |
jingcai-wei/android-news | app/src/main/java/com/sky/android/news/data/cache/NewsCache.kt | 1 | 2700 | /*
* Copyright (c) 2021 The sky Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.sky.android.news.data.cache
import com.sky.android.news.data.model.*
/**
* Created by sky on 17-9-21.
*/
class NewsCache(private val mCacheManager: ICacheManager) : INewsCache {
private var mCategoryKey = mCacheManager.buildKey(
NewsCache::class.java.name + ":getCategory()")
override fun getCategory(): CategoryModel? =
mCacheManager.get(mCategoryKey, CategoryModel::class.java)
override fun saveCategory(model: CategoryModel) {
mCacheManager.put(mCategoryKey, model)
}
override fun getHeadLine(tid: String, start: Int, end: Int): HeadLineModel? {
val key = mCacheManager.buildKey("$tid-$start-$end")
val model = mCacheManager.get(key, LinePackageModel::class.java)
if (model != null
&& !isExpired(model.lastTime, 1000 * 60 * 10)) {
// 返回缓存数据
return model.model
}
return null
}
override fun saveHeadLine(tid: String, start: Int, end: Int, model: HeadLineModel) {
mCacheManager.put(
mCacheManager.buildKey("$tid-$start-$end"),
LinePackageModel(System.currentTimeMillis(), model))
}
override fun getDetails(docId: String): DetailsModel? {
val key = mCacheManager.buildKey(docId)
var model = mCacheManager.get(key, DetailsPackageModel::class.java)
if (model != null
&& !isExpired(model.lastTime, 1000 * 60 * 60 * 24)) {
// 返回缓存数据
return model.model
}
return null
}
override fun saveDetails(docId: String, model: DetailsModel) {
mCacheManager.put(
mCacheManager.buildKey(docId),
DetailsPackageModel(System.currentTimeMillis(), model))
}
private fun isExpired(lastTime: Long, timeout: Long): Boolean {
val curTime = System.currentTimeMillis()
// 当前时间-最后时间>=超时时间 || 异常情况: 当前时间 < 最后时间
return curTime - lastTime >= timeout || curTime < lastTime
}
} | apache-2.0 | b570f361773fd7c83bda3580763dcbfb | 31.45679 | 88 | 0.644216 | 4.17806 | false | false | false | false |
FHannes/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/EventDispatcher.kt | 3 | 4764 | /*
* 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
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.keymap.KeymapManager
import com.intellij.openapi.util.SystemInfo
import com.intellij.testGuiFramework.recorder.ui.GuiScriptEditorFrame
import java.awt.Component
import java.awt.Container
import java.awt.KeyboardFocusManager
import java.awt.Point
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.awt.event.MouseEvent.MOUSE_PRESSED
import java.util.*
import javax.swing.JFrame
import javax.swing.KeyStroke
import javax.swing.RootPaneContainer
import javax.swing.SwingUtilities
/**
* @author Sergey Karashevich
*/
object EventDispatcher {
val mainActions by lazy { (ActionManager.getInstance().getAction(IdeActions.GROUP_MAIN_MENU) as ActionGroup).getFlatIdList() }
val LOG = Logger.getInstance(EventDispatcher::class.java)
fun processMouseEvent(me: MouseEvent) {
// if (!(me.clickCount == 1 && me.id == MOUSE_CLICKED && me.button == BUTTON1)) return
if (!(me.id == MOUSE_PRESSED)) return
ScriptGenerator.flushTyping()
var component: Component? = me.component
val mousePoint = me.point
if (component is JFrame)
if (component.title == GuiScriptEditorFrame.GUI_SCRIPT_FRAME_TITLE) return // ignore mouse events from GUI Script Editor Frame
if (component is RootPaneContainer) {
val layeredPane = component.layeredPane
val pt = SwingUtilities.convertPoint(component, mousePoint, layeredPane)
component = layeredPane.findComponentAt(pt)
}
else if (component is Container) {
component = component.findComponentAt(mousePoint)
}
if (component == null) {
component = KeyboardFocusManager.getCurrentKeyboardFocusManager().focusOwner
}
if (component != null) {
val convertedPoint = Point(
me.locationOnScreen.x - component.locationOnScreen.x,
me.locationOnScreen.y - component.locationOnScreen.y)
//get all extended code generators and get with the highest priority
LOG.info("Delegate click from component:${component}")
ScriptGenerator.clickComponent(component, convertedPoint, me)
}
}
fun processKeyBoardEvent(keyEvent: KeyEvent) {
if (keyEvent.component is JFrame && (keyEvent.component as JFrame).title == GuiScriptEditorFrame.GUI_SCRIPT_FRAME_TITLE) return
if (keyEvent.id == KeyEvent.KEY_TYPED)
ScriptGenerator.processTyping(keyEvent.keyChar)
if (SystemInfo.isMac && keyEvent.id == KeyEvent.KEY_PRESSED) {
//we are redirecting native Mac Preferences action as an Intellij action "Show Settings" has been invoked
LOG.info(keyEvent.toString())
val showSettingsId = "ShowSettings"
if (KeymapManager.getInstance().activeKeymap.getActionIds(KeyStroke.getKeyStrokeForEvent(keyEvent)).contains(showSettingsId)) {
val showSettingsAction = ActionManager.getInstance().getAction(showSettingsId)
val actionEvent = AnActionEvent.createFromInputEvent(keyEvent, ActionPlaces.UNKNOWN, showSettingsAction.templatePresentation,
DataContext.EMPTY_CONTEXT)
ScriptGenerator.processKeyActionEvent(showSettingsAction, actionEvent)
}
}
}
fun processActionEvent(anActionTobePerformed: AnAction, anActionEvent: AnActionEvent?) {
val actMgr = ActionManager.getInstance()
if (anActionEvent!!.inputEvent is KeyEvent) ScriptGenerator.processKeyActionEvent(anActionTobePerformed, anActionEvent)
if (mainActions.contains(actMgr.getId(anActionTobePerformed))) ScriptGenerator.processMainMenuActionEvent(anActionTobePerformed,
anActionEvent)
}
private fun ActionGroup.getFlatIdList(): List<String> {
val actMgr = ActionManager.getInstance()
val result = ArrayList<String>()
this.getChildren(null).forEach { anAction ->
if (anAction is ActionGroup) result.addAll(anAction.getFlatIdList())
else result.add(actMgr.getId(anAction))
}
return result
}
} | apache-2.0 | c8bd536d9bffb11441e2d1a7f2adb779 | 40.077586 | 133 | 0.72691 | 4.684366 | false | false | false | false |
clappr/clappr-android | clappr/src/test/kotlin/io/clappr/player/components/MediaOptionTest.kt | 1 | 1135 | package io.clappr.player.components
import io.mockk.every
import io.mockk.mockk
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
class MediaOptionTest {
private lateinit var playback: Playback
@Before
fun setUp() {
playback = mockk()
}
@Test
fun `should create media options json with audio and subtitle`() {
every { playback.selectedAudio } returns "eng"
every { playback.selectedSubtitle } returns "por"
val mediaOptionsJson = playback.buildMediaOptionsJson()
val expectedJson = """{"media_option":[{"name":"por","type":"SUBTITLE"},{"name":"eng","type":"AUDIO"}]}}"""
assertEquals(expectedJson, mediaOptionsJson)
}
@Test
fun `should create media options json only with subtitle`() {
every { playback.selectedAudio } returns null
every { playback.selectedSubtitle } returns "por"
val mediaOptionsJson = playback.buildMediaOptionsJson()
val expectedJson = """{"media_option":[{"name":"por","type":"SUBTITLE"}]}}"""
assertEquals(expectedJson, mediaOptionsJson)
}
} | bsd-3-clause | 2597c89c647555cd70c01852266739ec | 28.128205 | 115 | 0.66696 | 4.576613 | false | true | false | false |
06needhamt/Neuroph-Intellij-Plugin | neuroph-plugin/src/com/thomas/needham/neurophidea/Tuple2.kt | 1 | 1400 | /*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea
/**
* Created by thoma on 29/06/2016.
*/
open class Tuple2<X, Y> {
var valueX: X? = null
var valueY: Y? = null
constructor(x: X?, y: Y?) {
this.valueX = x
this.valueY = y
}
companion object Blank {
@JvmStatic
val BLANK = Tuple2<Any?, Any?>(null, null)
}
} | mit | bceb91ad115e13cd8f6d4f6007452e7f | 32.357143 | 78 | 0.759286 | 3.988604 | false | false | false | false |
dlew/RxBinding | rxbinding-kotlin/src/main/kotlin/com/jakewharton/rxbinding/widget/RxTextView.kt | 3 | 5018 | package com.jakewharton.rxbinding.widget
import android.widget.TextView
import com.jakewharton.rxbinding.internal.Functions
import rx.Observable
import rx.functions.Action1
import rx.functions.Func1
/**
* Create an observable of editor actions on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*/
public inline fun TextView.editorActions(): Observable<Int> = RxTextView.editorActions(this)
/**
* Create an observable of editor actions on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*
* @param handled Function invoked each occurrence to determine the return value of the
* underlying [TextView.OnEditorActionListener].
*/
public inline fun TextView.editorActions(handled: Func1<in Int, Boolean>): Observable<Int> = RxTextView.editorActions(this, handled)
/**
* Create an observable of editor action events on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*/
public inline fun TextView.editorActionEvents(): Observable<TextViewEditorActionEvent> = RxTextView.editorActionEvents(this)
/**
* Create an observable of editor action events on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Warning:* The created observable uses [TextView.OnEditorActionListener] to
* observe actions. Only one observable can be used for a view at a time.
*
* @param handled Function invoked each occurrence to determine the return value of the
* underlying [TextView.OnEditorActionListener].
*/
public inline fun TextView.editorActionEvents(handled: Func1<in TextViewEditorActionEvent, Boolean>): Observable<TextViewEditorActionEvent> = RxTextView.editorActionEvents(this, handled)
/**
* Create an observable of character sequences for text changes on `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
public inline fun TextView.textChanges(): Observable<CharSequence> = RxTextView.textChanges(this)
/**
* Create an observable of text change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
public inline fun TextView.textChangeEvents(): Observable<TextViewTextChangeEvent> = RxTextView.textChangeEvents(this)
/**
* Create an observable of before text change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
public inline fun TextView.beforeTextChangeEvents(): Observable<TextViewBeforeTextChangeEvent> = RxTextView.beforeTextChangeEvents(this)
/**
* Create an observable of after text change events for `view`.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*
* *Note:* A value will be emitted immediately on subscribe.
*/
public inline fun TextView.afterTextChangeEvents(): Observable<TextViewAfterTextChangeEvent> = RxTextView.afterTextChangeEvents(this)
/**
* An action which sets the text property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun TextView.text(): Action1<in CharSequence> = RxTextView.text(this)
/**
* An action which sets the text property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun TextView.textRes(): Action1<in Int> = RxTextView.textRes(this)
/**
* An action which sets the error property of `view` with character sequences.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun TextView.error(): Action1<in CharSequence> = RxTextView.error(this)
/**
* An action which sets the error property of `view` string resource IDs.
*
* *Warning:* The created observable keeps a strong reference to `view`. Unsubscribe
* to free this reference.
*/
public inline fun TextView.errorRes(): Action1<in Int> = RxTextView.errorRes(this)
| apache-2.0 | 48720cc775f722b156833dc97f3c5112 | 37.899225 | 186 | 0.754285 | 4.394046 | false | false | false | false |
yh-kim/gachi-android | Gachi/app/src/main/kotlin/com/pickth/gachi/view/chat/ChatDetailActivity.kt | 1 | 5617 | /*
* Copyright 2017 Yonghoon Kim
*
* 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.pickth.gachi.view.chat
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import com.pickth.commons.extensions.hideKeyboard
import com.pickth.gachi.R
import com.pickth.gachi.base.BaseActivity
import com.pickth.gachi.util.GridSpacingItemDecoration
import com.pickth.gachi.view.chat.adapter.ChatDetailAdapter
import kotlinx.android.synthetic.main.activity_chat_detail.*
import org.jetbrains.anko.toast
import org.json.JSONObject
import java.text.SimpleDateFormat
class ChatDetailActivity: BaseActivity(), ChatDetailContract.View {
private lateinit var mPresenter: ChatDetailPresenter
private lateinit var mAdapter: ChatDetailAdapter
private lateinit var mParticipantAdapter: ParticipantAdapter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_chat_detail)
// val icon = AppCompatResources.getDrawable(this, R.drawable.ic_back)!!
// DrawableCompat.setTint(icon, ContextCompat.getColor(this, R.color.colorWhite))
// actionbar
setSupportActionBar(chat_toolbar)
supportActionBar?.run {
setHomeAsUpIndicator(R.drawable.ic_back)
setDisplayShowTitleEnabled(false)
setDisplayHomeAsUpEnabled(true)
}
// adpater
mAdapter = ChatDetailAdapter()
rv_chat_detail.run {
layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
adapter = mAdapter
}
mParticipantAdapter = ParticipantAdapter()
rv_chat_participant_list.run {
layoutManager = GridLayoutManager(context, 6)
this.adapter = mParticipantAdapter
addItemDecoration(GridSpacingItemDecoration(context,6, 12, false))
}
// presenter
mPresenter = ChatDetailPresenter().apply {
attachView(this@ChatDetailActivity)
setChatDetailAdapterView(mAdapter)
setChatDetailAdapterModel(mAdapter)
setParticipantAdapter(mParticipantAdapter)
getGachiInfo()
}
btn_chat_detail_send.setOnClickListener {
var msg = et_chat_detail_msg.text.toString().trim()
if(msg.length < 1) {
toast("텍스트를 입력해주세요.")
return@setOnClickListener
}
et_chat_detail_msg.text = null
mPresenter.sendMessage(msg)
}
tv_chat_participant.setOnClickListener {
tv_chat_participant.visibility = View.GONE
tv_chat_show.visibility = View.VISIBLE
rv_chat_participant_list.run {
visibility = View.VISIBLE
}
}
tv_chat_show.setOnClickListener {
tv_chat_show.visibility = View.GONE
tv_chat_participant.visibility = View.VISIBLE
rv_chat_participant_list.run {
visibility = View.GONE
}
}
}
override fun getLid(): String = intent.getStringExtra("lid")
override fun scrollToPosition(position: Int) {
if(mPresenter.getItemCount() < 0) return
rv_chat_detail.smoothScrollToPosition(position)
}
override fun bindGachiInfo(responseBody: String) {
val json = JSONObject(responseBody)
Log.d(TAG, "getGachiInfo onResponse, json: ${json}")
// get gachi info
var title = json.getString("detail")
var startDate = json.getString("lead_from").split("T")[0].replace("-",".").trim()
var dday = ((System.currentTimeMillis() - SimpleDateFormat("yyyy.MM.dd").parse(startDate).time) / (1000 * 60 * 60 * 24)).toInt()
// get participant list
var members = json.getJSONArray("member")
for(i in 0..members.length() - 1) {
var member = members.getJSONObject(i)
var memberUid = member.getString("uid")
var memberNickname = member.getString("nickname")
var memberProfile = member.getString("profile_image")
// bind participant
mParticipantAdapter.addItem(Participant(memberUid, memberNickname, memberProfile))
}
// bind view
tv_chat_detail_title.text = title
tv_chat_detail_dday.text = "D - ${if(dday == 0) "day" else dday}"
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when(item?.itemId) {
android.R.id.home -> {
hideKeyboard()
finish()
}
R.id.chat_menu_add -> {
// add
}
}
return super.onOptionsItemSelected(item)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.chat_menu, menu)
return super.onCreateOptionsMenu(menu)
}
} | apache-2.0 | 42de8b84740671c75c5add77d875c621 | 32.321429 | 136 | 0.649634 | 4.6218 | false | false | false | false |
pennlabs/penn-mobile-android | PennMobile/src/main/java/com/pennapps/labs/pennmobile/classes/HomeCellInfo.kt | 1 | 1746 | package com.pennapps.labs.pennmobile.classes
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* Created by Jackie on 2018-03-28. Updated by Marta on 2019-10-20.
*/
class HomeCellInfo {
// Article
@SerializedName("article")
@Expose
var article: Article? = null
// News / Feature / Post
@SerializedName("image_url")
@Expose
val imageUrl: String? = null
@SerializedName("source")
@Expose
val source: String? = null
@SerializedName("title")
@Expose
val title: String? = null
@SerializedName("subtitle")
@Expose
val subtitle: String? = null
@SerializedName("timestamp")
@Expose
val timestamp: String? = null
// News
@SerializedName("article_url")
@Expose
val articleUrl: String? = null
// Dining
@SerializedName("venues")
@Expose
var venues: List<Int>? = null
// Laundry
@SerializedName("room_id")
@Expose
var roomId: Int? = 0
// Courses
@SerializedName("courses")
@Expose
val courses: List<HomeCourse>? = null
@SerializedName("weekday")
@Expose
val weekday: String? = null
// Feature
// Can have source, title, description, timestamp, imageUrl, feature string
@SerializedName("description")
var description: String? = null
@SerializedName("feature")
var featureStr: String? = null
// Post
// Is defined of type 'Post' and has source, imageUrl,
// postUrl, title, subtitle, start/end times, and comments
//NOTE: Only the most recent post from the API will be processed
@SerializedName("time_label")
var post: Post? = null
@SerializedName("test")
val isTest: Boolean? = null
}
| mit | b2ca82cddb07cf581245581f861b485c | 22.28 | 79 | 0.646048 | 4.12766 | false | false | false | false |
SirWellington/alchemy-generator | src/main/java/tech/sirwellington/alchemy/generator/StringGenerators.kt | 1 | 9567 | /*
* Copyright © 2019. Sir Wellington.
* 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 tech.sirwellington.alchemy.generator
import org.apache.commons.lang3.RandomStringUtils
import org.apache.commons.lang3.StringUtils
import org.slf4j.LoggerFactory
import tech.sirwellington.alchemy.annotations.access.NonInstantiable
import tech.sirwellington.alchemy.annotations.arguments.Required
import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern
import tech.sirwellington.alchemy.annotations.designs.patterns.StrategyPattern.Role.CONCRETE_BEHAVIOR
import tech.sirwellington.alchemy.generator.BinaryGenerators.Companion.binary
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.integers
import java.util.UUID
import javax.xml.bind.annotation.adapters.HexBinaryAdapter
/**
* @author SirWellington
*/
@NonInstantiable
@StrategyPattern(role = CONCRETE_BEHAVIOR)
class StringGenerators
@Throws(IllegalAccessException::class)
internal constructor()
{
init
{
throw IllegalAccessException("cannot instantiate this class")
}
companion object
{
private val LOG = LoggerFactory.getLogger(StringGenerators::class.java)
//==============================================================================================
//BASIC STRINGS
//==============================================================================================
/**
* Generates a random string of a random length. Characters can include ASCII, Unicode, or
* International Characters.
*
* @return
*/
@JvmStatic
fun strings(): AlchemyGenerator<String>
{
return AlchemyGenerator {
val size = one(integers(5, 1000))
RandomStringUtils.random(size)
}
}
/**
* Generates a random string of specified length. Characters are included from all sets.
*
* @param length The length of the String, must be at least 1.
*
*
* @return
*/
@JvmStatic
fun strings(length: Int): AlchemyGenerator<String>
{
checkThat(length > 0, "Length must be at least 1")
return AlchemyGenerator { RandomStringUtils.random(length) }
}
/**
* Generates a random hexadecimal string.
*
* @param length The length of the String, must be at least 1.
*
*
* @return
*/
@JvmStatic
fun hexadecimalString(length: Int): AlchemyGenerator<String>
{
checkThat(length > 0, "Length must be at least 1")
val hexBinaryAdapter = HexBinaryAdapter()
val binaryGenerator = binary(length)
return AlchemyGenerator {
val binary = one(binaryGenerator)
val hex = hexBinaryAdapter.marshal(binary)
StringUtils.left(hex, length)
}
}
/**
* Generates a random alphabetic string.
*
* @param length The length of the String, must be at least 1.
*
* @return
*
*
* @throws IllegalArgumentException If `length < 0`
*
*
* @see .alphabeticStrings
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun alphabeticStrings(length: Int): AlchemyGenerator<String>
{
checkThat(length > 0, "length must be > 0")
return AlchemyGenerator { RandomStringUtils.randomAlphabetic(length) }
}
/**
* Generates a random alphabetic string anywhere between `10 - 100` characters. Well suited for the case when
* you don't really care for the size of the string returned.
*
* @return
*
* @see .alphabeticStrings
*/
@JvmStatic
fun alphabeticStrings(): AlchemyGenerator<String>
{
val length = one(integers(10, 100))
return alphabeticStrings(length)
}
/**
* Generates a random alphanumeric string anywhere between `10 - 100` characters. Well suited for the case
* when you don't really care what the size of the string returned.
*
* @return
*
* @see .alphanumericStrings
*/
@JvmStatic
fun alphanumericStrings(): AlchemyGenerator<String>
{
val length = one(integers(10, 100))
return alphabeticStrings(length)
}
/**
*
* @param length The length of the Generated Strings.
*
* @return
*
*
* @throws IllegalArgumentException If `length < 0`
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun alphanumericStrings(length: Int): AlchemyGenerator<String>
{
checkThat(length > 0, "length must be > 0")
return AlchemyGenerator { RandomStringUtils.randomAlphanumeric(length) }
}
/**
* Creates a numeric integer-based String. The sizes of the Strings will vary across instances.
*
*
* Each resulting string will be directly [parsable into an Integer][Integer.parseInt].
*
* @return
*/
@JvmStatic
fun numericStrings(): AlchemyGenerator<String>
{
val length = one(integers(4, 25))
return numericStrings(length)
}
/**
* Creates a numeric integer-based String.
*
*
* For Example:
* <pre>
* String result = numericStrings(5).get();
* //49613
</pre> *
*
* @param length
*
* @return
*
* @throws IllegalArgumentException
*/
@JvmStatic
@Throws(IllegalArgumentException::class)
fun numericStrings(length: Int): AlchemyGenerator<String>
{
checkThat(length > 0, "length must be > 0")
val digits = integers(0, 10)
return AlchemyGenerator {
val builder = StringBuilder()
while (builder.length < length)
{
builder.append(digits.get())
}
builder.toString()
}
}
//==============================================================================================
//UUIDs
//==============================================================================================
/**
* Generates random [UUIDs][UUID].
*/
@JvmField
val uuids = AlchemyGenerator { UUID.randomUUID().toString() }
/**
* Just returns [.uuids]. This exists for consistency.
*
* @return
*/
@JvmStatic
fun uuids(): AlchemyGenerator<String>
{
return uuids
}
//==============================================================================================
//From Fixed targets
//==============================================================================================
/**
* Generates a string value from the specified set.
*
* @param values
*
*
* @return
*/
@JvmStatic
fun stringsFromFixedList(values: List<String>): AlchemyGenerator<String>
{
checkNotNull(values)
checkThat(!values.isEmpty(), "No values specified")
return AlchemyGenerator {
val index = integers(0, values.size).get()
values[index]
}
}
/**
* Generates a string value from the specified set.
*
* @param values
*
*
* @return
*/
@JvmStatic
fun stringsFromFixedList(vararg values: String): AlchemyGenerator<String>
{
checkNotNull(values)
checkThat(values.isNotEmpty(), "No values specified")
return stringsFromFixedList(values.toList())
}
/**
* Takes an existing [Generator][AlchemyGenerator] and transforms its values to a
* String using the [Object.toString] method.
*
* @param <T>
*
* @param generator The backing Alchemy Generator.
*
*
* @return
*
*
* @throws IllegalArgumentException If the Generator is null.
</T> */
@JvmStatic
@Throws(IllegalArgumentException::class)
fun <T> asString(@Required generator: AlchemyGenerator<T>): AlchemyGenerator<String>
{
checkNotNull(generator, "generator missing")
return AlchemyGenerator {
val value = generator.get()
value?.toString() ?: ""
}
}
}
}
| apache-2.0 | e0d3cc0a451fa1f69cb2b849d5338e67 | 28.616099 | 117 | 0.52603 | 5.386261 | false | false | false | false |
matejdro/WearMusicCenter | mobile/src/main/java/com/matejdro/wearmusiccenter/config/buttons/DiskButtonConfigStorage.kt | 1 | 2990 | package com.matejdro.wearmusiccenter.config.buttons
import android.content.Context
import android.os.PersistableBundle
import androidx.annotation.WorkerThread
import com.google.auto.factory.AutoFactory
import com.google.auto.factory.Provided
import com.matejdro.wearmusiccenter.actions.PhoneAction
import com.matejdro.wearmusiccenter.common.buttonconfig.ButtonInfo
import com.matejdro.wearmusiccenter.util.BundleFileSerialization
import timber.log.Timber
import java.io.File
import java.io.IOException
@AutoFactory
class DiskButtonConfigStorage(@Provided private val context: Context, fileSuffix: String) {
private val storageFile = File(context.filesDir, "action_config$fileSuffix")
fun loadButtons(target: ButtonConfig): Boolean {
try {
val configBundle = BundleFileSerialization.readFromFile(storageFile) ?: return false
unpackConfigBundle(configBundle, target)
return true
} catch(e: IOException) {
Timber.e(e, "Config reading error")
return false
} catch(e: RuntimeException) {
// RuntimeException is thrown if marshalling fails
Timber.e(e, "Config reading error")
return false
}
}
@WorkerThread
fun saveButtons(buttons : Collection<Map.Entry<ButtonInfo, PhoneAction>>) : Boolean {
try {
BundleFileSerialization.writeToFile(getConfigBundle(buttons), storageFile)
} catch(e: IOException) {
Timber.e(e, "Config writing error")
return false
}
return true
}
private fun getConfigBundle(buttons : Collection<Map.Entry<ButtonInfo, PhoneAction>>): PersistableBundle {
val configBundle = PersistableBundle()
configBundle.putInt(ConfigConstants.NUM_BUTTONS, buttons.size)
for ((counter, button) in buttons.withIndex()) {
val buttonInfo = button.key
val buttonValue = button.value
val buttonInfoKey = "${ConfigConstants.BUTTON_INFO}.$counter"
configBundle.putPersistableBundle(buttonInfoKey, buttonInfo.serialize())
val buttonActionKey = "${ConfigConstants.BUTTON_ACTION}.$counter"
configBundle.putPersistableBundle(buttonActionKey, buttonValue.serialize())
}
return configBundle
}
private fun unpackConfigBundle(bundle: PersistableBundle, target: ButtonConfig) {
val numButtons = bundle.getInt(ConfigConstants.NUM_BUTTONS, 0)
for (buttonIndex in 0 until numButtons) {
val buttonInfoKey = "${ConfigConstants.BUTTON_INFO}.$buttonIndex"
val buttonInfo = ButtonInfo(bundle.getPersistableBundle(buttonInfoKey)!!)
val buttonActionKey = "${ConfigConstants.BUTTON_ACTION}.$buttonIndex"
val buttonAction = PhoneAction.deserialize<PhoneAction>(context, bundle.getPersistableBundle(buttonActionKey))
target.saveButtonAction(buttonInfo, buttonAction)
}
}
}
| gpl-3.0 | ca002d8f584da3558b1d6904e9dabd23 | 36.375 | 122 | 0.69699 | 4.885621 | false | true | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/views/PageActionOverflowView.kt | 1 | 4356 | package org.wikipedia.views
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.PopupWindow
import androidx.core.view.doOnDetach
import androidx.core.widget.PopupWindowCompat
import com.google.android.material.textview.MaterialTextView
import org.wikipedia.R
import org.wikipedia.auth.AccountUtil
import org.wikipedia.databinding.ItemCustomizeToolbarMenuBinding
import org.wikipedia.databinding.ViewPageActionOverflowBinding
import org.wikipedia.page.PageViewModel
import org.wikipedia.page.action.PageActionItem
import org.wikipedia.page.customize.CustomizeToolbarActivity
import org.wikipedia.page.tabs.Tab
import org.wikipedia.settings.Prefs
class PageActionOverflowView(context: Context) : FrameLayout(context) {
private var binding = ViewPageActionOverflowBinding.inflate(LayoutInflater.from(context), this, true)
private var popupWindowHost: PopupWindow? = null
lateinit var callback: PageActionItem.Callback
init {
binding.overflowForward.setOnClickListener {
dismissPopupWindowHost()
callback.forwardClick()
}
Prefs.customizeToolbarMenuOrder.forEach {
val view = ItemCustomizeToolbarMenuBinding.inflate(LayoutInflater.from(context)).root
val item = PageActionItem.find(it)
view.id = item.viewId
view.text = context.getString(item.titleResId)
view.setCompoundDrawablesRelativeWithIntrinsicBounds(item.iconResId, 0, 0, 0)
view.setOnClickListener {
dismissPopupWindowHost()
item.select(callback)
}
binding.overflowList.addView(view)
}
binding.customizeToolbar.setOnClickListener {
dismissPopupWindowHost()
context.startActivity(CustomizeToolbarActivity.newIntent(context))
}
}
fun show(anchorView: View, callback: PageActionItem.Callback, currentTab: Tab, model: PageViewModel) {
this.callback = callback
popupWindowHost = PopupWindow(this, ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, true)
popupWindowHost?.let {
it.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
PopupWindowCompat.setOverlapAnchor(it, true)
it.showAsDropDown(anchorView, 0, 0, Gravity.END)
}
binding.overflowForward.visibility = if (currentTab.canGoForward()) VISIBLE else GONE
for (i in 1 until binding.overflowList.childCount) {
val view = binding.overflowList.getChildAt(i) as MaterialTextView
val pageActionItem = PageActionItem.find(view.id)
val enabled = model.page != null && (!model.shouldLoadAsMobileWeb || (model.shouldLoadAsMobileWeb && pageActionItem.isAvailableOnMobileWeb))
when (pageActionItem) {
PageActionItem.ADD_TO_WATCHLIST -> {
view.setText(if (model.isWatched) R.string.menu_page_unwatch else R.string.menu_page_watch)
view.setCompoundDrawablesRelativeWithIntrinsicBounds(PageActionItem.watchlistIcon(model.isWatched, model.hasWatchlistExpiry), 0, 0, 0)
view.visibility = if (enabled && AccountUtil.isLoggedIn) VISIBLE else GONE
}
PageActionItem.SAVE -> {
view.setCompoundDrawablesRelativeWithIntrinsicBounds(PageActionItem.readingListIcon(model.isInReadingList), 0, 0, 0)
view.visibility = if (enabled) VISIBLE else GONE
}
PageActionItem.EDIT_ARTICLE -> {
view.setCompoundDrawablesRelativeWithIntrinsicBounds(PageActionItem.editArticleIcon(model.page?.pageProperties?.canEdit != true), 0, 0, 0)
}
else -> {
view.visibility = if (enabled) VISIBLE else GONE
}
}
}
anchorView.doOnDetach {
dismissPopupWindowHost()
}
}
private fun dismissPopupWindowHost() {
popupWindowHost?.let {
it.dismiss()
popupWindowHost = null
}
}
}
| apache-2.0 | cc74183b634bea068e90fea5da572497 | 43 | 158 | 0.684343 | 5.041667 | false | false | false | false |
cossacklabs/themis | docs/examples/android/app/src/main/java/com/cossacklabs/themis/android/example/MainActivitySecureCell.kt | 1 | 1278 | package com.cossacklabs.themis.android.example
import android.os.Bundle
import android.util.Base64
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.cossacklabs.themis.SecureCell
import java.nio.charset.StandardCharsets
class MainActivitySecureCell : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Secure cell
try {
encryptDataForStoring()
} catch (e: Exception) {
e.printStackTrace()
}
}
private fun encryptDataForStoring() {
val charset = StandardCharsets.UTF_8
val pass = "pass"
val message = "hello message"
val sc = SecureCell.SealWithPassphrase(pass, charset)
val protectedData = sc.encrypt(message.toByteArray(charset))
val encodedString = Base64.encodeToString(protectedData, Base64.NO_WRAP)
Log.d("SMC", "encrypted string = $encodedString")
val decodedString = Base64.decode(encodedString, Base64.NO_WRAP)
val unprotected = sc.decrypt(decodedString)
val decryptedData = String(unprotected, charset)
Log.d("SMC", "decrypted data = $decryptedData")
}
}
| apache-2.0 | 24ed44467135225ee43cb8e95a352177 | 34.5 | 80 | 0.690141 | 4.288591 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/search/RecentSearchesFragment.kt | 1 | 8843 | package org.wikipedia.search
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isInvisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.coroutines.*
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.database.AppDatabase
import org.wikipedia.databinding.FragmentSearchRecentBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.mwapi.MwQueryResult
import org.wikipedia.page.Namespace
import org.wikipedia.search.db.RecentSearch
import org.wikipedia.util.FeedbackUtil.setButtonLongPressToast
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.log.L
import org.wikipedia.views.SwipeableItemTouchHelperCallback
import java.util.concurrent.ConcurrentHashMap
class RecentSearchesFragment : Fragment() {
interface Callback {
fun switchToSearch(text: String)
fun onAddLanguageClicked()
fun getLangCode(): String
}
private var _binding: FragmentSearchRecentBinding? = null
private val binding get() = _binding!!
private val namespaceHints = listOf(Namespace.USER, Namespace.PORTAL, Namespace.HELP)
private val namespaceMap = ConcurrentHashMap<String, Map<Namespace, String>>()
private val coroutineExceptionHandler = CoroutineExceptionHandler { _, throwable -> L.e(throwable) }
var callback: Callback? = null
val recentSearchList = mutableListOf<RecentSearch>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentSearchRecentBinding.inflate(inflater, container, false)
binding.recentSearchesDeleteButton.setOnClickListener {
AlertDialog.Builder(requireContext())
.setMessage(getString(R.string.clear_recent_searches_confirm))
.setPositiveButton(getString(R.string.clear_recent_searches_confirm_yes)) { _, _ ->
lifecycleScope.launch(coroutineExceptionHandler) {
withContext(Dispatchers.IO) {
AppDatabase.instance.recentSearchDao().deleteAll()
}
updateList()
}
}
.setNegativeButton(getString(R.string.clear_recent_searches_confirm_no), null)
.create().show()
}
binding.addLanguagesButton.setOnClickListener { onAddLangButtonClick() }
binding.recentSearchesRecycler.layoutManager = LinearLayoutManager(requireActivity())
binding.namespacesRecycler.layoutManager = LinearLayoutManager(requireActivity(), RecyclerView.HORIZONTAL, false)
binding.recentSearchesRecycler.adapter = RecentSearchAdapter()
val touchCallback = SwipeableItemTouchHelperCallback(requireContext())
touchCallback.swipeableEnabled = true
val itemTouchHelper = ItemTouchHelper(touchCallback)
itemTouchHelper.attachToRecyclerView(binding.recentSearchesRecycler)
setButtonLongPressToast(binding.recentSearchesDeleteButton)
return binding.root
}
fun show() {
binding.recentSearchesContainer.visibility = View.VISIBLE
}
fun hide() {
binding.recentSearchesContainer.visibility = View.GONE
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun updateSearchEmptyView(searchesEmpty: Boolean) {
if (searchesEmpty) {
binding.searchEmptyContainer.visibility = View.VISIBLE
if (WikipediaApp.instance.languageState.appLanguageCodes.size == 1) {
binding.addLanguagesButton.visibility = View.VISIBLE
binding.searchEmptyMessage.text = getString(R.string.search_empty_message_multilingual_upgrade)
} else {
binding.addLanguagesButton.visibility = View.GONE
binding.searchEmptyMessage.text = getString(R.string.search_empty_message)
}
} else {
binding.searchEmptyContainer.visibility = View.INVISIBLE
}
}
private fun onAddLangButtonClick() {
callback?.onAddLanguageClicked()
}
fun onLangCodeChanged() {
lifecycleScope.launch(coroutineExceptionHandler) {
updateList()
}
}
suspend fun updateList() {
val searches: List<RecentSearch>
val nsMap: Map<String, MwQueryResult.Namespace>
val langCode = callback?.getLangCode().orEmpty()
if (!namespaceMap.containsKey(langCode)) {
val map = mutableMapOf<Namespace, String>()
namespaceMap[langCode] = map
withContext(Dispatchers.IO) {
nsMap = ServiceFactory.get(WikiSite.forLanguageCode(langCode)).getPageNamespaceWithSiteInfo(null).query?.namespaces.orEmpty()
namespaceHints.forEach {
map[it] = nsMap[it.code().toString()]?.name.orEmpty()
}
}
}
withContext(Dispatchers.IO) {
searches = AppDatabase.instance.recentSearchDao().getRecentSearches()
}
recentSearchList.clear()
recentSearchList.addAll(searches)
binding.namespacesRecycler.adapter = NamespaceAdapter()
binding.recentSearchesRecycler.adapter?.notifyDataSetChanged()
val searchesEmpty = recentSearchList.isEmpty()
binding.searchEmptyContainer.isInvisible = !searchesEmpty
updateSearchEmptyView(searchesEmpty)
binding.recentSearches.isInvisible = searchesEmpty
}
private inner class RecentSearchItemViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener, SwipeableItemTouchHelperCallback.Callback {
private lateinit var recentSearch: RecentSearch
fun bindItem(position: Int) {
recentSearch = recentSearchList[position]
itemView.setOnClickListener(this)
(itemView as TextView).text = recentSearch.text
}
override fun onClick(v: View) {
callback?.switchToSearch((v as TextView).text.toString())
}
override fun onSwipe() {
lifecycleScope.launch(coroutineExceptionHandler) {
withContext(Dispatchers.IO) {
AppDatabase.instance.recentSearchDao().delete(recentSearch)
}
updateList()
}
}
override fun isSwipeable(): Boolean { return true }
}
private inner class RecentSearchAdapter : RecyclerView.Adapter<RecentSearchItemViewHolder>() {
override fun getItemCount(): Int {
return recentSearchList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecentSearchItemViewHolder {
return RecentSearchItemViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_search_recent, parent, false))
}
override fun onBindViewHolder(holder: RecentSearchItemViewHolder, pos: Int) {
holder.bindItem(pos)
}
}
private inner class NamespaceItemViewHolder constructor(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener {
fun bindItem(ns: Namespace?) {
val isHeader = ns == null
itemView.setOnClickListener(this)
(itemView as TextView).text = if (isHeader) getString(R.string.search_namespaces) else namespaceMap[callback?.getLangCode()]?.get(ns).orEmpty() + ":"
itemView.isEnabled = !isHeader
itemView.setTextColor(ResourceUtil.getThemedColor(requireContext(), if (isHeader) R.attr.material_theme_primary_color else R.attr.colorAccent))
}
override fun onClick(v: View) {
callback?.switchToSearch((v as TextView).text.toString())
}
}
private inner class NamespaceAdapter : RecyclerView.Adapter<NamespaceItemViewHolder>() {
override fun getItemCount(): Int {
return namespaceHints.size + 1
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NamespaceItemViewHolder {
return NamespaceItemViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_namespace, parent, false))
}
override fun onBindViewHolder(holder: NamespaceItemViewHolder, pos: Int) {
holder.bindItem(namespaceHints.getOrNull(pos - 1))
}
}
}
| apache-2.0 | ab7ae2dadc21f1b60f9816c694115894 | 40.909953 | 181 | 0.684949 | 5.282557 | false | false | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/context/OnnxMappingContext.kt | 1 | 8073 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.context
import onnx.Onnx
import org.nd4j.linalg.api.buffer.DataType
import org.nd4j.linalg.api.ndarray.INDArray
import org.nd4j.samediff.frameworkimport.context.AbstractMappingContext
import org.nd4j.samediff.frameworkimport.ir.IRAttribute
import org.nd4j.samediff.frameworkimport.ir.IRGraph
import org.nd4j.samediff.frameworkimport.ir.IRNode
import org.nd4j.samediff.frameworkimport.ir.IRTensor
import org.nd4j.samediff.frameworkimport.onnx.convertToOnnxTensor
import org.nd4j.samediff.frameworkimport.onnx.definitions.registry
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRAttr
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRGraph
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRNode
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRTensor
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
import java.lang.IllegalArgumentException
import java.lang.IllegalStateException
class OnnxMappingContext(opDef: Onnx.NodeProto, node: Onnx.NodeProto, graph:
IRGraph<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto,
Onnx.AttributeProto,
Onnx.AttributeProto, Onnx.TensorProto.DataType>, dynamicVariables: MutableMap<String, Onnx.TensorProto>) :
AbstractMappingContext<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.TensorProto,
Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType>(opDef, node, graph,dynamicVariables) {
override fun attrDef(name: String): Onnx.AttributeProto {
val ret = opDef().attributeList.firstOrNull { it.name == name }
return ret!!
}
override fun irAttributeValueForNode(valueName: String): IRAttribute<Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto, Onnx.TensorProto.DataType> {
val attrDef = attrDef(valueName)
var attrValue = node.attributeList.firstOrNull { it.name == valueName }
if(attrValue == null && attrDef.name == "value" && opDef.opType == "Constant")
//allow dummy values
attrValue = Onnx.AttributeProto.newBuilder()
.setName("value").addTensors(Onnx.TensorProto.getDefaultInstance())
.build()
else if(attrValue == null) {
attrValue = Onnx.AttributeProto.newBuilder()
.setName(valueName)
.build()
println("Unable to resolve attribute for name $valueName for node ${nodeName()} for op type ${opName()}")
}
return OnnxIRAttr(inputAttributeDef = attrDef, inputAttributeValue = attrValue!!)
}
override fun tensorInputFor(name: String): IRTensor<Onnx.TensorProto, Onnx.TensorProto.DataType> {
return tensorInputFromInputFrameworkName(name)
}
override fun opName(): String {
return opDef.opType
}
override fun nodeName(): String {
return opDef.name
}
override fun nd4jDataTypeFor(input: IRTensor<Onnx.TensorProto, Onnx.TensorProto.DataType>): DataType {
return input.dataType().nd4jDataType()
}
override fun createIRTensorFromNDArray(ndarray: INDArray): IRTensor<Onnx.TensorProto, Onnx.TensorProto.DataType> {
return OnnxIRTensor(convertToOnnxTensor(ndarray, "tensor"))
}
override fun tensorAttributeFor(name: String): IRTensor<Onnx.TensorProto, Onnx.TensorProto.DataType> {
return irAttributeValueForNode(name).tensorValue()
}
override fun irNode(): IRNode<Onnx.NodeProto, Onnx.TensorProto, Onnx.AttributeProto, Onnx.AttributeProto, Onnx.TensorProto.DataType> {
if(node.opType == "Placeholder")
return OnnxIRNode(node, OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx")["Constant"]!!,graph.opMappingRegistry())
return OnnxIRNode(node, OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx")[node.opType]!!,graph.opMappingRegistry())
}
override fun tensorInputFromInputFrameworkName(name: String): IRTensor<Onnx.TensorProto, Onnx.TensorProto.DataType> {
val castedGraph = graph as OnnxIRGraph
val graphDef = castedGraph.graphDef()
var foundIndex = opDef.inputList.map { input -> input.toString() }.indexOf(name)
//optional or unknown tensors
if(foundIndex < 0 || foundIndex >= node.inputCount) {
println("Node with name ${nodeName()} for opdef with name ${opDef.name} did not contain a tensor with name ${name}, returning empty tensor")
return OnnxIRTensor(Onnx.TensorProto.getDefaultInstance())
}
/**
* Use op definition name as 1 unified reference name in rules for static purposes, but
* look up via index for specific node mappings.
*
* This is equivalent to the tf input position attribute value in the previous tensorflow import.
*/
val graphNode = if(node.opType == "Constant") name else node.getInput(foundIndex)
val attemptedTensor = graphDef.initializerList.firstOrNull { it.name == graphNode }
?: return if(!dynamicVariables.containsKey(graphNode))
OnnxIRTensor(Onnx.TensorProto.getDefaultInstance())
else {
val toConvert = dynamicVariables[graphNode]!!
OnnxIRTensor(toConvert)
}
//no value to be found on placeholder, return default instance
//if no value exists it's an output from another node
//value nodes are the values of attributes that are input nodes in a frozen graph
if(attemptedTensor == null) {
throw IllegalArgumentException("Name $name not found in initializer list.")
}
return OnnxIRTensor(attemptedTensor!!)
}
override fun nodeInputNameForOpDefInputName(name: String): String {
var foundIndex = opDef.inputList.map { input -> input.toString() }.indexOf(name)
if(foundIndex < 0) {
throw IllegalArgumentException("No name ${name} found on op def with name ${opDef.name}")
}
if(foundIndex >= node.inputCount) {
throw IllegalStateException("Node with name $name was found at index $foundIndex but was inconsistent with number of inputs for node ${node.name}")
}
return node.getInput(foundIndex)
}
override fun hasInput(name: String): Boolean {
var foundIndex = opDef.inputList.map { input -> input.toString() }.indexOf(name)
return foundIndex >= 0 && foundIndex < node.inputCount
}
override fun preProcessNode() {
val onnxIRNode = OnnxIRNode(node,opDef, registry())
relevantNodePreProcessingHooks.forEach { hook ->
hook.modifyNode(onnxIRNode,graph as IRGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>)
}
//post processed, we need to update the references in the node
if(relevantNodePreProcessingHooks.isNotEmpty()) {
this.node = onnxIRNode.internalValue()
this.graph.updateNode(onnxIRNode)
}
}
} | apache-2.0 | b24baf0def06d82fa42ed3a25f1081d2 | 46.775148 | 197 | 0.693794 | 4.535393 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/lang/core/macros/proc/RsProcMacroSyntaxFixupTest.kt | 2 | 3203 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.macros.proc
import com.intellij.openapi.util.text.StringUtil
import org.intellij.lang.annotations.Language
import org.rust.*
import org.rust.ide.experiments.RsExperiments
import org.rust.lang.core.macros.MacroExpansionScope
import org.rust.lang.core.psi.ext.RsPossibleMacroCall
import org.rust.lang.core.psi.ext.descendantsOfType
import org.rust.lang.core.psi.ext.expansion
import org.rust.lang.core.psi.ext.isMacroCall
@MinRustcVersion("1.46.0")
@ExpandMacros(MacroExpansionScope.WORKSPACE)
@ProjectDescriptor(WithProcMacroRustProjectDescriptor::class)
@WithExperimentalFeatures(RsExperiments.EVALUATE_BUILD_SCRIPTS, RsExperiments.PROC_MACROS)
class RsProcMacroSyntaxFixupTest : RsTestBase() {
fun `test add semicolon to let stmt`() = checkSyntaxFixup("""
fn main() {
let a = 123
}
""", """
fn main() {
let a = 123;
}
""")
fun `test add semicolon to expr stmt`() = checkSyntaxFixup("""
fn main() {
123
321;
}
""", """
fn main() {
123;
321;
}
""")
fun `test fix dot expr`() = checkSyntaxFixup("""
fn main() {
foo.
}
""", """
fn main() {
foo.__ij__fixup
}
""")
fun `test fix dot expr and add semicolon`() = checkSyntaxFixup("""
fn main() {
foo.
let _ = 1;
}
""", """
fn main() {
foo.__ij__fixup;
let _ = 1;
}
""")
fun `test remove expressions with errors 1`() = checkSyntaxFixup("""
fn main() {
let a = 1;
a + ;
let c = 2;
}
""", """
fn main() {
let a = 1;
__ij__fixup;
let c = 2;
}
""")
fun `test remove expressions with errors 2`() = checkSyntaxFixup("""
fn main() {
let a = 1;
let b = a + ;
let c = 2;
}
""", """
fn main() {
let a = 1;
let b = __ij__fixup;
let c = 2;
}
""")
fun `test remove expressions with errors 3`() = checkSyntaxFixup("""
fn main() {
let a = 1;
let b = a + (a + );
let c = 2;
}
""", """
fn main() {
let a = 1;
let b = a + (__ij__fixup);
let c = 2;
}
""")
private fun checkSyntaxFixup(input: String, @Language("Rust") expectedOutput: String) {
InlineFile("""
|use test_proc_macros::attr_as_is;
|
|#[attr_as_is]
|${input.trimIndent()}
""".trimMargin())
val macro = myFixture.file
.descendantsOfType<RsPossibleMacroCall>()
.single { it.isMacroCall }
val output = macro.expansion?.file?.text
if (!StringUtil.equalsIgnoreWhitespaces(expectedOutput.trimIndent(), output)) {
assertEquals(expectedOutput.trimIndent(), output)
}
}
}
| mit | f41a89d67386aa7d1e2297698ab417cf | 24.220472 | 91 | 0.501717 | 4.16515 | false | true | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/helpers/DataBindingUtils.kt | 1 | 6406 | package com.habitrpg.android.habitica.ui.helpers
import android.content.Context
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.view.View
import android.view.animation.Animation
import android.view.animation.Transformation
import android.widget.ImageView
import android.widget.LinearLayout
import androidx.core.content.res.ResourcesCompat
import coil.imageLoader
import coil.load
import coil.request.ImageRequest
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.setTintWith
import com.habitrpg.android.habitica.helpers.AppConfigManager
import java.util.Collections
import java.util.Date
fun ImageView.loadImage(imageName: String?, imageFormat: String? = null) {
DataBindingUtils.loadImage(this, imageName, imageFormat)
}
object DataBindingUtils {
fun loadImage(view: ImageView?, imageName: String) {
loadImage(view, imageName, null)
}
fun loadImage(view: ImageView?, imageName: String?, imageFormat: String? = null) {
if (view != null && imageName != null && view.visibility == View.VISIBLE) {
val fullname = getFullFilename(imageName, imageFormat)
if (view.tag == fullname) {
return
}
view.tag = fullname
view.load(BASE_IMAGE_URL + fullname)
}
}
fun loadImage(context: Context, imageName: String, imageResult: (Drawable) -> Unit) {
loadImage(context, imageName, null, imageResult)
}
fun loadImage(context: Context, imageName: String, imageFormat: String?, imageResult: (Drawable) -> Unit) {
val request = ImageRequest.Builder(context)
.data(BASE_IMAGE_URL + getFullFilename(imageName, imageFormat))
.target {
imageResult(it)
}
.build()
context.imageLoader.enqueue(request)
}
fun getFullFilename(imageName: String, imageFormat: String? = null): String {
val name = when {
spriteSubstitutions.containsKey(imageName) -> spriteSubstitutions[imageName]
FILENAME_MAP.containsKey(imageName) -> FILENAME_MAP[imageName]
imageName.startsWith("handleless") -> "chair_$imageName"
else -> imageName
}
return name + if (imageFormat == null && FILEFORMAT_MAP.containsKey(imageName)) {
"." + FILEFORMAT_MAP[imageName]
} else {
".${imageFormat ?: "png"}"
}
}
fun setRoundedBackground(view: View, color: Int) {
val drawable = ResourcesCompat.getDrawable(view.resources, R.drawable.layout_rounded_bg, null)
drawable?.setTintWith(color, PorterDuff.Mode.MULTIPLY)
view.background = drawable
}
class LayoutWeightAnimation(internal var view: View, internal var targetWeight: Float) : Animation() {
private var initializeWeight: Float = 0.toFloat()
private var layoutParams: LinearLayout.LayoutParams = view.layoutParams as LinearLayout.LayoutParams
init {
initializeWeight = layoutParams.weight
}
override fun applyTransformation(interpolatedTime: Float, t: Transformation) {
layoutParams.weight = initializeWeight + (targetWeight - initializeWeight) * interpolatedTime
view.requestLayout()
}
override fun willChangeBounds(): Boolean = true
}
const val BASE_IMAGE_URL = "https://habitica-assets.s3.amazonaws.com/mobileApp/images/"
private val FILEFORMAT_MAP: Map<String, String>
private val FILENAME_MAP: Map<String, String>
private var spriteSubstitutions: Map<String, String> = HashMap()
get() {
if (Date().time - (lastSubstitutionCheck?.time ?: 0) > 180000) {
field = AppConfigManager(null).spriteSubstitutions()["generic"] ?: HashMap()
lastSubstitutionCheck = Date()
}
return field
}
private var lastSubstitutionCheck: Date? = null
init {
val tempMap = HashMap<String, String>()
tempMap["head_special_1"] = "gif"
tempMap["broad_armor_special_1"] = "gif"
tempMap["slim_armor_special_1"] = "gif"
tempMap["head_special_0"] = "gif"
tempMap["slim_armor_special_0"] = "gif"
tempMap["broad_armor_special_0"] = "gif"
tempMap["weapon_special_critical"] = "gif"
tempMap["weapon_special_0"] = "gif"
tempMap["shield_special_0"] = "gif"
tempMap["Pet-Wolf-Cerberus"] = "gif"
tempMap["armor_special_ks2019"] = "gif"
tempMap["slim_armor_special_ks2019"] = "gif"
tempMap["broad_armor_special_ks2019"] = "gif"
tempMap["eyewear_special_ks2019"] = "gif"
tempMap["head_special_ks2019"] = "gif"
tempMap["shield_special_ks2019"] = "gif"
tempMap["weapon_special_ks2019"] = "gif"
tempMap["Pet-Gryphon-Gryphatrice"] = "gif"
tempMap["Mount_Head_Gryphon-Gryphatrice"] = "gif"
tempMap["Mount_Body_Gryphon-Gryphatrice"] = "gif"
tempMap["background_clocktower"] = "gif"
tempMap["background_airship"] = "gif"
tempMap["background_steamworks"] = "gif"
tempMap["Pet_HatchingPotion_Veggie"] = "gif"
tempMap["Pet_HatchingPotion_Dessert"] = "gif"
tempMap["Pet-HatchingPotion-Dessert"] = "gif"
tempMap["quest_windup"] = "gif"
tempMap["Pet-HatchingPotion_Windup"] = "gif"
tempMap["Pet_HatchingPotion_Windup"] = "gif"
tempMap["quest_solarSystem"] = "gif"
tempMap["quest_virtualpet"] = "gif"
tempMap["Pet_HatchingPotion_VirtualPet"] = "gif"
FILEFORMAT_MAP = Collections.unmodifiableMap(tempMap)
val tempNameMap = HashMap<String, String>()
tempNameMap["head_special_1"] = "ContributorOnly-Equip-CrystalHelmet"
tempNameMap["armor_special_1"] = "ContributorOnly-Equip-CrystalArmor"
tempNameMap["head_special_0"] = "BackerOnly-Equip-ShadeHelmet"
tempNameMap["armor_special_0"] = "BackerOnly-Equip-ShadeArmor"
tempNameMap["shield_special_0"] = "BackerOnly-Shield-TormentedSkull"
tempNameMap["weapon_special_0"] = "BackerOnly-Weapon-DarkSoulsBlade"
tempNameMap["weapon_special_critical"] = "weapon_special_critical"
tempNameMap["Pet-Wolf-Cerberus"] = "Pet-Wolf-Cerberus"
FILENAME_MAP = Collections.unmodifiableMap(tempNameMap)
}
}
| gpl-3.0 | 1292d923a4803febffadcd302473873f | 40.329032 | 111 | 0.652669 | 4.228383 | false | false | false | false |
petropavel13/2photo-android | TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/views/RetryView.kt | 1 | 1709 | package com.github.petropavel13.twophoto.views
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.TextView
import com.github.petropavel13.twophoto.R
/**
* Created by petropavel on 07/04/15.
*/
class RetryView: LinearLayout {
constructor(ctx: Context): super(ctx) { }
constructor(ctx: Context, attrs: AttributeSet): super(ctx, attrs) { }
constructor(ctx: Context, attrs: AttributeSet, defStyleAttr: Int): super(ctx, attrs, defStyleAttr) { }
constructor(ctx: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int): super(ctx, attrs, defStyleAttr, defStyleRes) { }
var button: ImageButton? = null
var textView: TextView? = null
override fun onFinishInflate() {
super.onFinishInflate()
button = findViewById(R.id.retry_view_refresh_button) as? ImageButton
textView = findViewById(R.id.retry_view_text_view) as? TextView
}
private var _onClickListener: View.OnClickListener? = null
var onRetryListener: View.OnClickListener?
get() = _onClickListener
set(newValue) {
_onClickListener = newValue
button?.setOnClickListener(_onClickListener)
}
var errorText: CharSequence
get() = textView?.getText() ?: ""
set(newValue) {
textView?.setText(newValue)
}
private var _textResource = R.string.retry_view_failed_to_load_content
var errorTextResource: Int
get() = _textResource
set(newValue) {
_textResource = newValue
textView?.setText(_textResource)
}
}
| mit | b6a032d26c0f912c6cf023fa7dd5060d | 27.966102 | 137 | 0.67876 | 4.473822 | false | false | false | false |
nrizzio/Signal-Android | sms-exporter/lib/src/test/java/org/signal/smsexporter/internal/mms/ExportMmsRecipientsUseCaseTest.kt | 1 | 3555 | package org.signal.smsexporter.internal.mms
import android.content.Context
import android.net.Uri
import android.provider.Telephony
import androidx.test.core.app.ApplicationProvider
import com.google.android.mms.pdu_alt.PduHeaders
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.signal.core.util.CursorUtil
import org.signal.smsexporter.TestUtils
@RunWith(RobolectricTestRunner::class)
class ExportMmsRecipientsUseCaseTest {
@Before
fun setUp() {
TestUtils.setUpMmsContentProviderAndResolver()
}
@Test
fun `When I export recipient, then I expect a valid exported recipient`() {
// GIVEN
val address = "+15065550177"
val sender = "+15065550123"
val messageId = 1L
// WHEN
val result = ExportMmsRecipientsUseCase.execute(
ApplicationProvider.getApplicationContext(),
messageId,
address,
sender,
false
)
// THEN
result.either(
onSuccess = {
validateExportedRecipient(address, sender, messageId)
},
onFailure = {
throw it
}
)
}
@Test
fun `Given recipient already exported, When I export recipient with check, then I expect a single exported recipient`() {
// GIVEN
val address = "+15065550177"
val sender = "+15065550123"
val messageId = 1L
ExportMmsRecipientsUseCase.execute(
ApplicationProvider.getApplicationContext(),
messageId,
address,
sender,
false
)
// WHEN
val result = ExportMmsRecipientsUseCase.execute(
ApplicationProvider.getApplicationContext(),
messageId,
address,
sender,
true
)
// THEN
result.either(
onSuccess = {
validateExportedRecipient(address, sender, messageId)
},
onFailure = {
throw it
}
)
}
@Test
fun `Given recipient already exported, When I export recipient with check, then I expect a duplicate exported recipient`() {
// GIVEN
val address = "+15065550177"
val sender = "+15065550123"
val messageId = 1L
ExportMmsRecipientsUseCase.execute(
ApplicationProvider.getApplicationContext(),
messageId,
address,
sender,
false
)
// WHEN
val result = ExportMmsRecipientsUseCase.execute(
ApplicationProvider.getApplicationContext(),
messageId,
address,
sender,
false
)
// THEN
result.either(
onSuccess = {
validateExportedRecipient(address, sender, messageId, expectedRowCount = 2)
},
onFailure = {
throw it
}
)
}
private fun validateExportedRecipient(address: String, sender: String, messageId: Long, expectedRowCount: Int = 1) {
val context: Context = ApplicationProvider.getApplicationContext()
val baseUri: Uri = Telephony.Mms.CONTENT_URI.buildUpon().appendPath(messageId.toString()).appendPath("addr").build()
context.contentResolver.query(
baseUri,
null,
"${Telephony.Mms.Addr.ADDRESS} = ?",
arrayOf(address),
null,
null
)?.use {
it.moveToFirst()
assertEquals(expectedRowCount, it.count)
assertEquals(address, CursorUtil.requireString(it, Telephony.Mms.Addr.ADDRESS))
assertEquals(if (address == sender) PduHeaders.FROM else PduHeaders.TO, CursorUtil.requireInt(it, Telephony.Mms.Addr.TYPE))
} ?: fail("Content Resolver returned a null cursor")
}
}
| gpl-3.0 | f2de6e4bc1f546e6506260df8c12ffb4 | 24.76087 | 129 | 0.673699 | 4.488636 | false | true | false | false |
google/ide-perf | src/main/java/com/google/idea/perf/cvtracer/CachedValueTracerCompletionProvider.kt | 1 | 2780 | /*
* 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.
*/
package com.google.idea.perf.cvtracer
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.CharFilter
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.util.textCompletion.TextCompletionProvider
class CachedValueTracerCompletionProvider : TextCompletionProvider {
override fun applyPrefixMatcher(
result: CompletionResultSet,
prefix: String
): CompletionResultSet {
return result.withPrefixMatcher(prefix)
}
override fun getAdvertisement(): String? = null
override fun getPrefix(text: String, offset: Int): String {
val separators = charArrayOf(' ', '\t')
val lastSeparatorPos = text.lastIndexOfAny(separators, offset - 1)
return text.substring(lastSeparatorPos + 1, offset)
}
override fun fillCompletionVariants(
parameters: CompletionParameters,
prefix: String,
result: CompletionResultSet
) {
val textBeforeCaret = parameters.editor.document.text.substring(0, parameters.offset)
val words = textBeforeCaret.split(' ', '\t').filter(String::isNotBlank)
val normalizedText = words.joinToString(" ")
val command = parseCachedValueTracerCommand(normalizedText)
var tokenIndex = normalizedText.count(Char::isWhitespace)
if (textBeforeCaret.isNotBlank() && textBeforeCaret.last().isWhitespace()) {
++tokenIndex
}
val elements = when (tokenIndex) {
0 -> listOf("clear", "reset", "filter", "clear-filters", "group-by")
1 -> when (command) {
is CachedValueTracerCommand.GroupBy -> listOf("class", "stack-trace")
else -> emptyList()
}
else -> emptyList()
}
result.addAllElements(elements.map(LookupElementBuilder::create))
result.stopHere()
}
override fun acceptChar(c: Char): CharFilter.Result {
return when (c) {
' ', '\t' -> CharFilter.Result.HIDE_LOOKUP
else -> CharFilter.Result.ADD_TO_PREFIX
}
}
}
| apache-2.0 | 68491f11b5a0886e7da1499c27d0994b | 36.066667 | 93 | 0.680935 | 4.719864 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/utils/LayoutUI.kt | 1 | 5030 | /*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 Aleksey Kladov, Evgeny Kurbatsky, Alexey Kudinkin and contributors
Copyright (c) 2016 JetBrains
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package org.elm.utils
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.openapi.vcs.changes.issueLinks.LinkMouseListenerBase
import com.intellij.ui.IdeBorderFactory
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.SimpleTextAttributes
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.UIUtil
import java.awt.BorderLayout
import java.util.regex.Pattern
import javax.swing.BoxLayout
import javax.swing.JComponent
import javax.swing.JPanel
/*
* IntelliJ has a new UI DSL (http://www.jetbrains.org/intellij/sdk/docs/user_interface_components/kotlin_ui_dsl.html)
* but it has been evolving a lot and there are API incompatibilities between 2019.2
* and previous releases. So I've decided to use this simple layout util from intellij-rust
* until we can fully adopt 2019.2 as our minimum IDE version. At which time, this file
* can and should be deleted.
*/
const val HGAP = 30
const val VERTICAL_OFFSET = 2
const val HORIZONTAL_OFFSET = 5
fun layout(block: ElmLayoutUIBuilder.() -> Unit): JPanel {
val panel = JPanel(BorderLayout())
val innerPanel = JPanel().apply {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
}
panel.add(innerPanel, BorderLayout.NORTH)
val builder = ElmLayoutUIBuilderImpl(innerPanel).apply(block)
UIUtil.mergeComponentsWithAnchor(builder.labeledComponents)
return panel
}
interface ElmLayoutUIBuilder {
fun block(text: String, block: ElmLayoutUIBuilder.() -> Unit)
fun row(text: String = "", component: JComponent, toolTip: String = "")
fun noteRow(text: String)
}
private class ElmLayoutUIBuilderImpl(
val panel: JPanel,
val labeledComponents: MutableList<LabeledComponent<*>> = mutableListOf()
) : ElmLayoutUIBuilder {
override fun block(text: String, block: ElmLayoutUIBuilder.() -> Unit) {
val blockPanel = JPanel().apply {
layout = BoxLayout(this, BoxLayout.Y_AXIS)
border = IdeBorderFactory.createTitledBorder(text, false)
}
ElmLayoutUIBuilderImpl(blockPanel, labeledComponents).apply(block)
panel.add(blockPanel)
}
override fun row(text: String, component: JComponent, toolTip: String) {
val labeledComponent = LabeledComponent.create(component, text, BorderLayout.WEST).apply {
(layout as? BorderLayout)?.hgap = HGAP
border = JBUI.Borders.empty(VERTICAL_OFFSET, HORIZONTAL_OFFSET)
toolTipText = toolTip.trimIndent()
}
labeledComponents += labeledComponent
panel.add(labeledComponent)
}
private val HREF_PATTERN =
Pattern.compile("<a(?:\\s+href\\s*=\\s*[\"']([^\"']*)[\"'])?\\s*>([^<]*)</a>")
private val LINK_TEXT_ATTRIBUTES: SimpleTextAttributes
get() = SimpleTextAttributes(SimpleTextAttributes.STYLE_PLAIN, JBUI.CurrentTheme.Link.linkColor())
override fun noteRow(text: String) {
val noteComponent = SimpleColoredComponent()
val matcher = HREF_PATTERN.matcher(text)
if (!matcher.find()) {
noteComponent.append(text)
panel.add(noteComponent)
return
}
var prev = 0
do {
if (matcher.start() != prev) {
noteComponent.append(text.substring(prev, matcher.start()))
}
val linkUrl = matcher.group(1)
noteComponent.append(
matcher.group(2),
LINK_TEXT_ATTRIBUTES,
SimpleColoredComponent.BrowserLauncherTag(linkUrl)
)
prev = matcher.end()
} while (matcher.find())
LinkMouseListenerBase.installSingleTagOn(noteComponent)
if (prev < text.length) {
noteComponent.append(text.substring(prev))
}
panel.add(noteComponent)
}
}
| mit | c780f5e928a96fe9bcfb872377da402b | 35.715328 | 118 | 0.700199 | 4.381533 | false | false | false | false |
pedroSG94/rtmp-rtsp-stream-client-java | app/src/main/java/com/pedro/rtpstreamer/backgroundexample/RtpService.kt | 1 | 5022 | /*
* Copyright (C) 2021 pedroSG94.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pedro.rtpstreamer.backgroundexample
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.app.NotificationCompat
import androidx.lifecycle.MutableLiveData
import com.pedro.rtplibrary.base.Camera2Base
import com.pedro.rtplibrary.rtmp.RtmpCamera2
import com.pedro.rtplibrary.view.OpenGlView
import com.pedro.rtpstreamer.R
/**
* Basic RTMP/RTSP service streaming implementation with camera2
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
class RtpService : Service() {
companion object {
private const val TAG = "RtpService"
private const val channelId = "rtpStreamChannel"
private const val notifyId = 123456
private var notificationManager: NotificationManager? = null
val observer = MutableLiveData<RtpService?>()
}
private var camera2Base: Camera2Base? = null
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
Log.i(TAG, "RTP service started")
return START_STICKY
}
override fun onCreate() {
super.onCreate()
Log.i(TAG, "$TAG create")
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(channelId, channelId, NotificationManager.IMPORTANCE_HIGH)
notificationManager?.createNotificationChannel(channel)
}
keepAliveTrick()
camera2Base = RtmpCamera2(this, true, connectCheckerRtp)
observer.postValue(this)
}
override fun onDestroy() {
super.onDestroy()
Log.i(TAG, "RTP service destroy")
stopRecord()
stopStream()
stopPreview()
observer.postValue(null)
}
private fun keepAliveTrick() {
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
val notification = NotificationCompat.Builder(this, channelId)
.setOngoing(true)
.setContentTitle("")
.setContentText("").build()
startForeground(1, notification)
} else {
startForeground(1, Notification())
}
}
private fun showNotification(text: String) {
val notification = NotificationCompat.Builder(applicationContext, channelId)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("RTP Stream")
.setContentText(text).build()
notificationManager?.notify(notifyId, notification)
}
fun prepare(): Boolean {
return camera2Base?.prepareVideo() ?: false && camera2Base?.prepareAudio() ?: false
}
fun startPreview() {
camera2Base?.startPreview()
}
fun stopPreview() {
camera2Base?.stopPreview()
}
fun switchCamera() {
camera2Base?.switchCamera()
}
fun isStreaming(): Boolean = camera2Base?.isStreaming ?: false
fun isRecording(): Boolean = camera2Base?.isRecording ?: false
fun isOnPreview(): Boolean = camera2Base?.isOnPreview ?: false
fun startStream(endpoint: String) {
camera2Base?.startStream(endpoint)
}
fun stopStream() {
camera2Base?.stopStream()
}
fun startRecord(path: String) {
camera2Base?.startRecord(path) {
Log.i(TAG, "record state: ${it.name}")
}
}
fun stopRecord() {
camera2Base?.stopRecord()
}
fun setView(openGlView: OpenGlView) {
camera2Base?.replaceView(openGlView)
}
fun setView(context: Context) {
camera2Base?.replaceView(context)
}
private val connectCheckerRtp = object : ConnectCheckerRtp {
override fun onConnectionStartedRtp(rtpUrl: String) {
showNotification("Stream connection started")
}
override fun onConnectionSuccessRtp() {
showNotification("Stream started")
Log.e(TAG, "RTP service destroy")
}
override fun onNewBitrateRtp(bitrate: Long) {
}
override fun onConnectionFailedRtp(reason: String) {
showNotification("Stream connection failed")
Log.e(TAG, "RTP service destroy")
}
override fun onDisconnectRtp() {
showNotification("Stream stopped")
}
override fun onAuthErrorRtp() {
showNotification("Stream auth error")
}
override fun onAuthSuccessRtp() {
showNotification("Stream auth success")
}
}
}
| apache-2.0 | 6993093397127622aab08be3470095d6 | 26.442623 | 98 | 0.714058 | 4.263158 | false | false | false | false |
pyamsoft/power-manager | powermanager-base/src/main/java/com/pyamsoft/powermanager/base/states/DozeStateObserver.kt | 1 | 1452 | /*
* Copyright 2017 Peter Kenji Yamanaka
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.powermanager.base.states
import android.os.Build
import android.support.annotation.CheckResult
import com.pyamsoft.powermanager.model.StateObserver
import com.pyamsoft.powermanager.model.States
import timber.log.Timber
import javax.inject.Inject
internal class DozeStateObserver @Inject internal constructor(
private val wrapper: DeviceFunctionWrapper) : StateObserver {
private val isDozeAvailable: Boolean
@CheckResult get() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
override fun enabled(): Boolean {
val enabled = isDozeAvailable && wrapper.state === States.ENABLED
Timber.d("Enabled: %s", enabled)
return enabled
}
override fun unknown(): Boolean {
val unknown = !isDozeAvailable || wrapper.state === States.UNKNOWN
Timber.d("Unknown: %s", unknown)
return unknown
}
}
| apache-2.0 | 794c3743ec06ed57200107b455d24c72 | 32.767442 | 75 | 0.748623 | 4.295858 | false | false | false | false |
google/android-auto-companion-android | trustagent/src/com/google/android/libraries/car/trustagent/PendingCar.kt | 1 | 6918 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.android.libraries.car.trustagent
import android.bluetooth.BluetoothDevice
import android.content.Context
import com.google.android.companionprotos.CapabilitiesExchangeProto.CapabilitiesExchange.OobChannelType
import com.google.android.companionprotos.OperationProto.OperationType
import com.google.android.libraries.car.trustagent.blemessagestream.BluetoothConnectionManager
import com.google.android.libraries.car.trustagent.blemessagestream.MessageStream
import com.google.android.libraries.car.trustagent.blemessagestream.StreamMessage
import com.google.android.libraries.car.trustagent.util.loge
import com.google.android.libraries.car.trustagent.util.logi
import com.google.android.libraries.car.trustagent.util.uuidToBytes
import java.util.UUID
import javax.crypto.SecretKey
/** Represents a car that is ready to be associated (first time) or re-connected with. */
internal interface PendingCar {
/**
* The bluetooth device that this [PendingCar] is connecting to.
*
* Keeping the scan result because it's returned by ConnectionManager callback.
*/
val device: BluetoothDevice
var callback: Callback?
/**
* Initiates connection to connect to a remote device.
*
* Successful connection will invoke [Callback.onConnected].
*
* If the implementation is performing association, [Callback.onAuthStringAvailable] should be
* invoked for out-of-band verification. If not, i.e. reconnection, [Callback.onConnectionFailed]
* should be invoked if the previous session could not be found, and connection will be stopped.
*/
suspend fun connect(advertisedData: ByteArray? = null)
/**
* Stops current connection.
*
* After disconnection, this object should be discarded.
*/
fun disconnect()
/** Propagates callbacks from internal objects to class that exposes external API. */
interface Callback {
/** Invoked when the remote device ID has been received. */
fun onDeviceIdReceived(deviceId: UUID)
/** Invoked for a first-time connection as part of out-of-band user verification. */
fun onAuthStringAvailable(authString: String)
/** Invoked when encryption is established. [car] is ready for exchanging messages. */
fun onConnected(car: Car)
/**
* Invoked when encryption could not be established.
*
* Device will automatically be disconnected. [pendingCar] should be discarded.
*/
fun onConnectionFailed(pendingCar: PendingCar)
}
companion object {
// Internal to expose to the extension methods in this file.
internal const val TAG = "PendingCar"
/** Creates a [PendingCar] to connect to. */
internal fun create(
securityVersion: Int,
context: Context,
isAssociating: Boolean,
stream: MessageStream,
associatedCarManager: AssociatedCarManager,
device: BluetoothDevice,
bluetoothManager: BluetoothConnectionManager,
oobChannelTypes: List<OobChannelType>,
oobData: OobData?
): PendingCar {
if (!isAssociating) {
return when (securityVersion) {
// Version 2/3/4 share the same flow for reconnection.
in 2..4 ->
PendingCarV2Reconnection(stream, associatedCarManager, device, bluetoothManager)
else -> {
// Version 1 is no longer supported.
throw IllegalArgumentException("Unsupported security version: $securityVersion.")
}
}
}
return when (securityVersion) {
2 ->
PendingCarV2Association(context, stream, associatedCarManager, device, bluetoothManager)
3 ->
PendingCarV3Association(
context,
stream,
associatedCarManager,
device,
bluetoothManager,
oobChannelTypes,
oobData
)
4 -> {
PendingCarV4Association(
context,
stream,
associatedCarManager,
device,
bluetoothManager,
oobData
)
}
else -> {
// Version 1 is no longer supported.
throw IllegalArgumentException("Unsupported security version: $securityVersion.")
}
}
}
/**
* Creates an implementation of [BluetoothConnectionManager.ConnectionCallback].
*
* The created callback is intended for PendingCar implementations to listen to connection
* events.
*
* For all connection events, i.e. connected/disconnected/connection failure, the created
* callback always disconnects the PendingCar and invokes
* [PendingCar.Callback.onConnectionFailed], because during connection phase the connection is
* expected to remain unchanged.
*/
internal fun createBluetoothConnectionManagerCallback(
pendingCar: PendingCar
): BluetoothConnectionManager.ConnectionCallback {
return object : BluetoothConnectionManager.ConnectionCallback {
override fun onConnected() {
loge(TAG, "Unexpected gatt callback: onConnected. Disconnecting.")
pendingCar.disconnect()
pendingCar.callback?.onConnectionFailed(pendingCar)
}
override fun onConnectionFailed() {
loge(TAG, "Unexpected gatt callback: onConnectionFailed. Disconnecting.")
pendingCar.disconnect()
pendingCar.callback?.onConnectionFailed(pendingCar)
}
override fun onDisconnected() {
// Mainly rely on disconnect() to clean up the state.
loge(TAG, "Disconnected while attempting to establish connection.")
pendingCar.disconnect()
pendingCar.callback?.onConnectionFailed(pendingCar)
}
}
}
}
}
/**
* Sends device ID and secret key as a message over [messageStream].
*
* Returns the message ID of sent message.
*/
internal fun MessageStream.send(
deviceId: UUID,
secretKey: SecretKey,
): Int {
val payload = uuidToBytes(deviceId) + secretKey.encoded
val messageId =
sendMessage(
StreamMessage(
payload,
operation = OperationType.ENCRYPTION_HANDSHAKE,
isPayloadEncrypted = true,
originalMessageSize = 0,
recipient = null
)
)
logi(PendingCar.TAG, "Sent deviceId and secret key. Message Id: $messageId")
return messageId
}
| apache-2.0 | 6f7710da52d059d5917d126f19ed916a | 34.116751 | 103 | 0.691818 | 4.96626 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/BookcaseFilmViewHolder.kt | 2 | 3057 | package ru.fantlab.android.ui.adapter.viewholder
import android.net.Uri
import android.view.ViewGroup
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import ru.fantlab.android.R
import kotlinx.android.synthetic.main.bookcase_film_row_item.view.*
import ru.fantlab.android.data.dao.model.BookcaseFilm
import ru.fantlab.android.provider.scheme.LinkParserHelper
import ru.fantlab.android.ui.adapter.BookcaseFilmsAdapter
import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter
import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder
class BookcaseFilmViewHolder(itemView: View, adapter: BaseRecyclerAdapter<BookcaseFilm, BookcaseFilmViewHolder>)
: BaseViewHolder<BookcaseFilm>(itemView, adapter) {
override fun bind(bookcase: BookcaseFilm) {
itemView.coverLayout.setUrl(Uri.Builder().scheme(LinkParserHelper.PROTOCOL_HTTPS)
.authority(LinkParserHelper.HOST_DATA)
.appendPath("images")
.appendPath("films")
.appendPath("big")
.appendPath(bookcase.filmId.toString())
.toString())
itemView.filmAutors.text = bookcase.director
itemView.filmName.text = bookcase.name
itemView.workComment.text = if (bookcase.comment.orEmpty().isEmpty()) itemView.context.getString(R.string.bookcase_add_comment) else bookcase.comment
itemView.workComment.setOnClickListener {
if (adapter != null && (adapter as BookcaseFilmsAdapter).itemUpdateListener != null) {
(adapter as BookcaseFilmsAdapter).itemUpdateListener?.onUpdateItemComment(bookcase.filmId, bookcase.comment)
}
}
itemView.workDelete.setOnClickListener {
if (adapter != null && (adapter as BookcaseFilmsAdapter).itemUpdateListener != null) {
(adapter as BookcaseFilmsAdapter).itemUpdateListener?.onDeleteItemFromBookcase(bookcase.filmId)
}
}
}
override fun onClick(v: View) {
super.onClick(v)
if (adapter != null && (adapter as BookcaseFilmsAdapter).itemUpdateListener != null) {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION && position < adapter!!.getItemCount()) {
(adapter as BookcaseFilmsAdapter).itemUpdateListener?.onFilmClicked(adapter?.getItem(position)!!)
}
}
}
interface OnUpdateItemListener {
fun onDeleteItemFromBookcase(itemId: Int)
fun onUpdateItemComment(itemId: Int, itemComment: String?)
fun onFilmClicked(bookcase: BookcaseFilm)
}
companion object {
fun newInstance(
viewGroup: ViewGroup,
adapter: BaseRecyclerAdapter<BookcaseFilm, BookcaseFilmViewHolder>,
isPrivateCase: Boolean
): BookcaseFilmViewHolder =
BookcaseFilmViewHolder(getView(viewGroup, if (isPrivateCase) R.layout.bookcase_film_row_item else R.layout.public_bookcase_film_row_item), adapter)
}
} | gpl-3.0 | 9a54b136f0b7136916a56bfc62d8b07d | 42.070423 | 163 | 0.693817 | 4.754277 | false | false | false | false |
teobaranga/T-Tasks | t-tasks/src/main/java/com/teo/ttasks/data/local/TaskFields.kt | 1 | 2679 | package com.teo.ttasks.data.local
import com.evernote.android.job.util.support.PersistableBundleCompat
import com.teo.ttasks.data.model.Task
import java.util.*
private const val NUM_FIELDS = 5
// TODO: remove this, it's unnecessary
class TaskFields : HashMap<String, String?>(NUM_FIELDS) {
companion object {
private const val KEY_TITLE = "title"
private const val KEY_DUE = "due"
private const val KEY_NOTES = "notes"
private const val KEY_COMPLETED = "completed"
private const val KEY_STATUS = "status"
fun taskFields(block: TaskFields.() -> Unit): TaskFields = TaskFields().apply(block)
/**
* Convert bundle date to TaskFields. This is used when de-serializing task data
* in a job
*/
fun fromBundle(bundle: PersistableBundleCompat): TaskFields? {
val taskFields = taskFields {
if (bundle.containsKey(KEY_TITLE)) {
title = bundle[KEY_TITLE] as String
}
if (bundle.containsKey(KEY_DUE)) {
dueDate = bundle[KEY_DUE] as String
}
if (bundle.containsKey(KEY_NOTES)) {
notes = bundle[KEY_NOTES] as String
}
if (bundle.containsKey(KEY_COMPLETED)) {
completed = bundle[KEY_COMPLETED] as String?
}
if (bundle.containsKey(KEY_STATUS)) {
this[KEY_STATUS] = bundle[KEY_STATUS] as String
}
}
return if (taskFields.isNotEmpty()) taskFields else null
}
}
var title
get() = this[KEY_TITLE]
set(title) {
when {
// Disallow tasks with empty or no title
title == null || title.isBlank() -> remove(KEY_TITLE)
else -> this[KEY_TITLE] = title
}
}
/**
* The task's due date, always in UTC.
*/
var dueDate
get() = this[KEY_DUE]
set(dueDate) {
when (dueDate) {
null -> remove(KEY_DUE)
else -> this[KEY_DUE] = dueDate
}
}
var notes
get() = this[KEY_NOTES]
set(notes) {
when {
notes == null || notes.isBlank() -> remove(KEY_NOTES)
else -> this[KEY_NOTES] = notes
}
}
var completed
get() = this[KEY_COMPLETED]
set(completed) {
this[KEY_COMPLETED] = completed
this[KEY_STATUS] = if (completed == null) Task.STATUS_NEEDS_ACTION else Task.STATUS_COMPLETED
}
}
| apache-2.0 | c4e4a340b30d0e0e5fcb0789f6081b38 | 30.892857 | 105 | 0.520343 | 4.43543 | false | false | false | false |
ohmae/DmsExplorer | mobile/src/main/java/net/mm2d/dmsexplorer/domain/model/MediaServerModel.kt | 1 | 9321 | /*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.domain.model
import android.annotation.SuppressLint
import android.content.Context
import android.os.Handler
import android.os.Looper
import androidx.annotation.IntDef
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import net.mm2d.android.upnp.cds.CdsObject
import net.mm2d.android.upnp.cds.MediaServer
import net.mm2d.dmsexplorer.domain.entity.ContentDirectoryEntity
import net.mm2d.dmsexplorer.domain.entity.ContentEntity
import java.util.*
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class MediaServerModel(
context: Context,
val mediaServer: MediaServer,
private val playbackTargetObserver: (ContentEntity?) -> Unit
) : ExploreListener {
private val handler = Handler(Looper.getMainLooper())
private val historyStack = LinkedList<ContentDirectoryEntity>()
@Volatile
private var exploreListener: ExploreListener = EXPLORE_LISTENER
var path: String? = null
private set
val udn: String
get() = mediaServer.udn
val title: String
get() = mediaServer.friendlyName
val selectedEntity: ContentEntity?
get() {
val entry = historyStack.peekFirst() ?: return null
return entry.selectedEntity
}
fun initialize() {
prepareEntry(ContentDirectoryEntity())
}
fun terminate() {
setExploreListener(null)
for (directory in historyStack) {
directory.terminate()
}
historyStack.clear()
}
fun canDelete(entity: ContentEntity): Boolean {
if (!entity.canDelete()) {
return false
}
if (historyStack.size >= 2) {
val p = historyStack[1].selectedEntity
if (p != null && !p.canDelete()) {
return false
}
}
return mediaServer.hasDestroyObject()
}
@SuppressLint("CheckResult")
fun delete(
entity: ContentEntity,
successCallback: Runnable?,
errorCallback: Runnable?
) {
val doNothing = Runnable { }
val onSuccess = successCallback ?: doNothing
val onError = errorCallback ?: doNothing
val id = (entity.rawEntity as CdsObject).objectId
mediaServer.destroyObject(id)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ integer ->
if (integer == MediaServer.NO_ERROR) {
onSuccess.run()
reload()
return@subscribe
}
onError.run()
}, { onError.run() })
}
fun enterChild(entity: ContentEntity): Boolean {
val directory = historyStack.peekFirst() ?: return false
val child = directory.enterChild(entity) ?: return false
directory.setExploreListener(null)
prepareEntry(child)
updatePlaybackTarget()
return true
}
private fun prepareEntry(directory: ContentDirectoryEntity) {
historyStack.offerFirst(directory)
path = makePath()
directory.setExploreListener(this)
directory.clearState()
directory.startBrowse(mediaServer.browse(directory.parentId))
}
fun exitToParent(): Boolean {
if (historyStack.size < 2) {
return false
}
exploreListener.onStart()
handler.post {
val directory = historyStack.pollFirst() ?: return@post
directory.terminate()
path = makePath()
val parent = historyStack.peekFirst() ?: return@post
parent.setExploreListener(this)
updatePlaybackTarget()
exploreListener.onUpdate(parent.entities)
exploreListener.onComplete()
}
return true
}
fun reload() {
val directory = historyStack.peekFirst() ?: return
directory.clearState()
directory.startBrowse(mediaServer.browse(directory.parentId))
}
fun setExploreListener(listener: ExploreListener?) {
exploreListener = listener ?: EXPLORE_LISTENER
val directory = historyStack.peekFirst() ?: return
exploreListener.onStart()
exploreListener.onUpdate(directory.entities)
if (!directory.isInProgress) {
exploreListener.onComplete()
}
}
fun setSelectedEntity(entity: ContentEntity): Boolean {
val directory = historyStack.peekFirst() ?: return false
directory.selectedEntity = entity
updatePlaybackTarget()
return true
}
private fun updatePlaybackTarget() {
playbackTargetObserver.invoke(selectedEntity)
}
fun selectPreviousEntity(@ScanMode scanMode: Int): Boolean {
val nextEntity = findPrevious(selectedEntity, scanMode) ?: return false
return setSelectedEntity(nextEntity)
}
private fun findPrevious(
current: ContentEntity?,
@ScanMode scanMode: Int
): ContentEntity? {
val directory = historyStack.peekFirst()
if (current == null || directory == null) {
return null
}
val list = directory.entities
when (scanMode) {
SCAN_MODE_SEQUENTIAL -> return findPreviousSequential(current, list)
SCAN_MODE_LOOP -> return findPreviousLoop(current, list)
}
return null
}
private fun findPreviousSequential(
current: ContentEntity,
list: List<ContentEntity>
): ContentEntity? {
val index = list.indexOf(current)
if (index - 1 < 0) {
return null
}
for (i in index - 1 downTo 0) {
val target = list[i]
if (isValidEntity(current, target)) {
return target
}
}
return null
}
private fun findPreviousLoop(
current: ContentEntity,
list: List<ContentEntity>
): ContentEntity? {
val size = list.size
val index = list.indexOf(current)
var i = (size + index - 1) % size
while (i != index) {
val target = list[i]
if (isValidEntity(current, target)) {
return target
}
i = (size + i - 1) % size
}
return null
}
fun selectNextEntity(@ScanMode scanMode: Int): Boolean {
val nextEntity = findNext(selectedEntity, scanMode) ?: return false
return setSelectedEntity(nextEntity)
}
private fun findNext(
current: ContentEntity?,
@ScanMode scanMode: Int
): ContentEntity? {
if (historyStack.isEmpty()) {
return null
}
val list = historyStack.peekFirst().entities
if (current == null) {
return null
}
when (scanMode) {
SCAN_MODE_SEQUENTIAL -> return findNextSequential(current, list)
SCAN_MODE_LOOP -> return findNextLoop(current, list)
}
return null
}
private fun findNextSequential(
current: ContentEntity,
list: List<ContentEntity>
): ContentEntity? {
val size = list.size
val index = list.indexOf(current)
if (index + 1 == size) {
return null
}
for (i in index + 1 until size) {
val target = list[i]
if (isValidEntity(current, target)) {
return target
}
}
return null
}
private fun findNextLoop(
current: ContentEntity,
list: List<ContentEntity>
): ContentEntity? {
val size = list.size
val index = list.indexOf(current)
var i = (index + 1) % size
while (i != index) {
val target = list[i]
if (isValidEntity(current, target)) {
return target
}
i = (i + 1) % size
}
return null
}
private fun isValidEntity(current: ContentEntity, target: ContentEntity): Boolean =
target.type == current.type && target.hasResource() && !target.isProtected
private fun makePath(): String {
val sb = StringBuilder()
for (directory in historyStack) {
if (sb.isNotEmpty() && directory.parentName.isNotEmpty()) {
sb.append(DELIMITER)
}
sb.append(directory.parentName)
}
return sb.toString()
}
fun onUpdateSortSettings() {
historyStack.forEach {
it.onUpdateSortSettings()
}
}
override fun onStart() {
exploreListener.onStart()
}
override fun onUpdate(list: List<ContentEntity>) {
exploreListener.onUpdate(list)
}
override fun onComplete() {
exploreListener.onComplete()
}
@Retention(AnnotationRetention.SOURCE)
@IntDef(SCAN_MODE_SEQUENTIAL, SCAN_MODE_LOOP)
annotation class ScanMode
companion object {
const val SCAN_MODE_SEQUENTIAL = 0
const val SCAN_MODE_LOOP = 1
private const val DELIMITER = " < "
private val EXPLORE_LISTENER = ExploreListenerAdapter()
}
}
| mit | d9dddd772b4f6e05cefb0bc29a8e1501 | 28.539683 | 87 | 0.595916 | 4.725749 | false | false | false | false |
PoweRGbg/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/aps/openAPSSMB/OpenAPSSMBFragment.kt | 3 | 4941 | package info.nightscout.androidaps.plugins.aps.openAPSSMB
import android.annotation.SuppressLint
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import info.nightscout.androidaps.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.logging.L
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateGui
import info.nightscout.androidaps.plugins.aps.openAPSMA.events.EventOpenAPSUpdateResultGui
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.FabricPrivacy
import info.nightscout.androidaps.utils.JSONFormatter
import info.nightscout.androidaps.utils.plusAssign
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import kotlinx.android.synthetic.main.openapsama_fragment.*
import org.json.JSONArray
import org.json.JSONException
import org.slf4j.LoggerFactory
class OpenAPSSMBFragment : Fragment() {
private val log = LoggerFactory.getLogger(L.APS)
private var disposable: CompositeDisposable = CompositeDisposable()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.openapsama_fragment, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
openapsma_run.setOnClickListener {
OpenAPSSMBPlugin.getPlugin().invoke("OpenAPSSMB button", false)
}
}
@Synchronized
override fun onResume() {
super.onResume()
disposable += RxBus
.toObservable(EventOpenAPSUpdateGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateGUI()
}, {
FabricPrivacy.logException(it)
})
disposable += RxBus
.toObservable(EventOpenAPSUpdateResultGui::class.java)
.observeOn(AndroidSchedulers.mainThread())
.subscribe({
updateResultGUI(it.text)
}, {
FabricPrivacy.logException(it)
})
updateGUI()
}
@Synchronized
override fun onPause() {
super.onPause()
disposable.clear()
}
@Synchronized
fun updateGUI() {
if (openapsma_result == null) return
val plugin = OpenAPSSMBPlugin.getPlugin()
plugin.lastAPSResult?.let { lastAPSResult ->
openapsma_result.text = JSONFormatter.format(lastAPSResult.json)
openapsma_request.text = lastAPSResult.toSpanned()
}
plugin.lastDetermineBasalAdapterSMBJS?.let { determineBasalAdapterSMBJS ->
openapsma_glucosestatus.text = JSONFormatter.format(determineBasalAdapterSMBJS.glucoseStatusParam)
openapsma_currenttemp.text = JSONFormatter.format(determineBasalAdapterSMBJS.currentTempParam)
try {
val iobArray = JSONArray(determineBasalAdapterSMBJS.iobDataParam)
openapsma_iobdata.text = TextUtils.concat(String.format(MainApp.gs(R.string.array_of_elements), iobArray.length()) + "\n", JSONFormatter.format(iobArray.getString(0)))
} catch (e: JSONException) {
log.error("Unhandled exception", e)
@SuppressLint("SetTextl18n")
openapsma_iobdata.text = "JSONException see log for details"
}
openapsma_profile.text = JSONFormatter.format(determineBasalAdapterSMBJS.profileParam)
openapsma_mealdata.text = JSONFormatter.format(determineBasalAdapterSMBJS.mealDataParam)
openapsma_scriptdebugdata.text = determineBasalAdapterSMBJS.scriptDebug
plugin.lastAPSResult?.inputConstraints?.let {
openapsma_constraints.text = it.reasons
}
}
if (plugin.lastAPSRun != 0L) {
openapsma_lastrun.text = DateUtil.dateAndTimeFullString(plugin.lastAPSRun)
}
plugin.lastAutosensResult?.let {
openapsma_autosensdata.text = JSONFormatter.format(it.json())
}
}
@Synchronized
private fun updateResultGUI(text: String) {
if (openapsma_result == null) return
openapsma_result.text = text
openapsma_glucosestatus.text = ""
openapsma_currenttemp.text = ""
openapsma_iobdata.text = ""
openapsma_profile.text = ""
openapsma_mealdata.text = ""
openapsma_autosensdata.text = ""
openapsma_scriptdebugdata.text = ""
openapsma_request.text = ""
openapsma_lastrun.text = ""
}
}
| agpl-3.0 | c37f712b683cecd19d6f565ef9540245 | 39.5 | 183 | 0.676381 | 4.80642 | false | false | false | false |
luanalbineli/popularmovies | app/src/main/java/com/themovielist/util/ArrayExtensions.kt | 1 | 372 | package com.themovielist.util
fun <T> IntArray.mapToListNotNull(mapper: (Int) -> T?): List<T>? {
var list: MutableList<T>? = null
this.forEach {
val result = mapper.invoke(it)
if (result != null) {
if (list == null) {
list = mutableListOf()
}
list?.add(result)
}
}
return list
} | apache-2.0 | 6fefdd164b317456d3fa893ca49bc336 | 23.866667 | 66 | 0.505376 | 3.915789 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/persistence/model/StepPersistentWrapper.kt | 1 | 949 | package org.stepic.droid.persistence.model
import android.os.Parcelable
import kotlinx.android.parcel.IgnoredOnParcel
import kotlinx.android.parcel.Parcelize
import org.stepic.droid.util.AppConstants
import org.stepik.android.model.Progressable
import org.stepik.android.model.Step
import org.stepik.android.model.Video
import ru.nobird.android.core.model.Identifiable
@Parcelize
data class StepPersistentWrapper(
val step: Step,
val originalStep: Step = step,
val cachedVideo: Video? = null // maybe more abstract
) : Progressable, Parcelable, Identifiable<Long> {
@IgnoredOnParcel
override val id: Long =
step.id
@IgnoredOnParcel
override val progress: String?
get() = step.progress
@IgnoredOnParcel
val isStepCanHaveQuiz: Boolean =
step.block?.name?.let { name ->
name != AppConstants.TYPE_VIDEO &&
name != AppConstants.TYPE_TEXT
} ?: false
} | apache-2.0 | e15403ec0ec938db30c84ebf2041ea82 | 28.6875 | 57 | 0.714436 | 4.255605 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/ui/custom/AutoCompleteSearchView.kt | 2 | 4882 | package org.stepic.droid.ui.custom
import android.app.Activity
import android.app.SearchManager
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.annotation.DrawableRes
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.SearchView
import androidx.core.widget.ImageViewCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import org.stepic.droid.R
import org.stepic.droid.model.SearchQuery
import org.stepic.droid.model.SearchQuerySource
import org.stepic.droid.ui.adapters.SearchQueriesAdapter
import org.stepic.droid.util.resolveResourceIdAttribute
class AutoCompleteSearchView
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : SearchView(context, attrs, defStyleAttr) {
private val searchQueriesAdapter = SearchQueriesAdapter(context)
private val closeIcon: ImageView = findViewById(androidx.appcompat.R.id.search_close_btn)
private val searchIcon: ImageView = findViewById(androidx.appcompat.R.id.search_mag_icon)
private var focusCallback: FocusCallback? = null
private val colorControlNormal =
AppCompatResources.getColorStateList(context, context.resolveResourceIdAttribute(R.attr.colorControlNormal))
var suggestionsOnTouchListener: OnTouchListener? = null
override fun onAttachedToWindow() {
super.onAttachedToWindow()
searchQueriesAdapter.searchView = this
}
override fun onDetachedFromWindow() {
searchQueriesAdapter.searchView = null
focusCallback = null
searchQueriesAdapter.suggestionClickCallback = null
super.onDetachedFromWindow()
}
init {
maxWidth = 20000
ImageViewCompat.setImageTintList(closeIcon, colorControlNormal)
ImageViewCompat.setImageTintList(searchIcon, colorControlNormal)
}
fun initSuggestions(rootView: ViewGroup) {
val inflater = LayoutInflater.from(context)
val searchQueriesRecyclerView = inflater.inflate(R.layout.search_queries_recycler_view, rootView, false) as RecyclerView
searchQueriesRecyclerView.layoutManager = LinearLayoutManager(context)
searchQueriesRecyclerView.adapter = searchQueriesAdapter
searchQueriesRecyclerView.setOnTouchListener { v, event ->
if (searchQueriesRecyclerView.findChildViewUnder(event.x, event.y) == null) {
if (event.action == MotionEvent.ACTION_UP && isEventInsideView(v, event)) {
[email protected]()
}
} else {
suggestionsOnTouchListener?.onTouch(v, event)
}
false
}
setOnQueryTextFocusChangeListener { _, hasFocus ->
if (hasFocus) {
setConstraint(query.toString())
searchQueriesRecyclerView.layoutManager?.scrollToPosition(0)
searchQueriesRecyclerView.visibility = View.VISIBLE
} else {
searchQueriesRecyclerView.visibility = View.GONE
}
focusCallback?.onFocusChanged(hasFocus)
}
rootView.addView(searchQueriesRecyclerView)
}
fun setFocusCallback(focusCallback: FocusCallback) {
this.focusCallback = focusCallback
}
fun setSuggestionClickCallback(suggestionClickCallback: SuggestionClickCallback) {
searchQueriesAdapter.suggestionClickCallback = suggestionClickCallback
}
fun setCloseIconDrawableRes(@DrawableRes iconRes: Int) {
closeIcon.setImageResource(iconRes)
}
fun setSearchable(activity: Activity) {
val searchManager = activity.getSystemService(Context.SEARCH_SERVICE) as SearchManager
val componentName = activity.componentName
val searchableInfo = searchManager.getSearchableInfo(componentName)
setSearchableInfo(searchableInfo)
}
fun setConstraint(constraint: String) {
searchQueriesAdapter.constraint = constraint
}
fun setSuggestions(suggestions: List<SearchQuery>, source: SearchQuerySource) {
when (source) {
SearchQuerySource.API ->
searchQueriesAdapter.rawAPIItems = suggestions
SearchQuerySource.DB ->
searchQueriesAdapter.rawDBItems = suggestions
}
}
private fun isEventInsideView(v: View, event: MotionEvent): Boolean =
event.x > 0 && event.y > 0 &&
event.x < v.width && event.y < v.height
interface FocusCallback {
fun onFocusChanged(hasFocus: Boolean)
}
interface SuggestionClickCallback {
fun onQueryTextSubmitSuggestion(query: String)
}
} | apache-2.0 | de6130151ce98151a919ad77ddbf3121 | 35.992424 | 128 | 0.720401 | 5.18259 | false | false | false | false |
marius-m/racer_test | core/src/main/java/lt/markmerkk/app/entities/PlayerServerImpl.kt | 1 | 2464 | package lt.markmerkk.app.entities
import lt.markmerkk.app.box2d.Car
import lt.markmerkk.app.screens.GameScreen
import org.slf4j.LoggerFactory
/**
* @author mariusmerkevicius
* @since 2016-10-31
*/
class PlayerServerImpl(
override val id: Int = -1,
override val name: String,
private val car: Car
) : PlayerServer {
override fun updateMovement(movement: Movement) {
// Acceleration
when (movement) {
Movement.FORWARD_START,
Movement.FORWARD_STOP,
Movement.BACKWARD_START,
Movement.BACKWARD_STOP -> {
when (movement) {
Movement.FORWARD_START -> car.accForward()
Movement.BACKWARD_START -> car.accBackward()
else -> car.accStop()
}
}
Movement.LEFT_START,
Movement.LEFT_STOP,
Movement.RIGHT_START,
Movement.RIGHT_STOP -> {
when (movement) {
Movement.LEFT_START -> car.steerLeft()
Movement.RIGHT_START -> car.steerRight()
else -> car.steerNone()
}
}
else -> {
logger.debug("[ERROR] Car unidentified car movement!")
car.accStop()
car.steerNone()
}
}
}
override fun update(deltaTime: Float) {
car.update(deltaTime)
// val newPositionX = GameScreen.PIXELS_PER_METER * car.x - carSprite.width / 2
// val newPositionY = GameScreen.PIXELS_PER_METER * car.y - carSprite.height / 2
// val newAngle = Math.toDegrees(car.angle.toDouble()).toFloat()
// if (newPositionX != carSprite.x ||
// newPositionY != carSprite.y ||
// carSprite.rotation != newAngle) {
// }
//
// carSprite.setPosition(newPositionX, newPositionY)
// carSprite.rotation = newAngle
}
override fun getPositionX(): Float {
return GameScreen.PIXELS_PER_METER * car.positionX()
}
override fun getPositionY(): Float {
return GameScreen.PIXELS_PER_METER * car.positionY()
}
override fun getAngle(): Float {
return Math.toDegrees(car.angle().toDouble()).toFloat()
}
override fun destroy() {
car.destroy()
}
companion object {
val logger = LoggerFactory.getLogger(PlayerServerImpl::class.java)
}
} | apache-2.0 | 2b3fac4276a1aab2592b825232bb2c11 | 29.060976 | 87 | 0.553977 | 4.392157 | false | false | false | false |
ShadwLink/Shadow-Mapper | src/main/java/nl/shadowlink/tools/io/WriteFunctions.kt | 1 | 3732 | package nl.shadowlink.tools.io
import java.io.IOException
import java.io.RandomAccessFile
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.file.Path
import java.util.logging.Level
import java.util.logging.Logger
/**
* @author Shadow-Link
*/
class WriteFunctions(
private var dataOut: RandomAccessFile
) {
constructor(name: String) : this(RandomAccessFile(name, "rw"))
constructor(path: Path) : this(path.toFile().absolutePath)
fun closeFile(): Boolean {
try {
dataOut.close()
} catch (ex: IOException) {
Logger.getLogger(WriteFunctions::class.java.name).log(Level.SEVERE, null, ex)
return false
}
return true
}
fun writeByte(value: Int) {
try {
dataOut.writeByte(value)
} catch (ex: IOException) {
// Nothing we can do about this
}
}
fun write(value: Int) {
var value = value
val bbuf = ByteBuffer.allocate(4)
bbuf.order(ByteOrder.BIG_ENDIAN)
bbuf.putInt(value)
bbuf.order(ByteOrder.LITTLE_ENDIAN)
value = bbuf.getInt(0)
try {
dataOut.writeInt(value)
} catch (ex: IOException) {
value = -1
}
}
fun writeShort(value: Int) {
var value = value
val bbuf = ByteBuffer.allocate(4)
bbuf.order(ByteOrder.BIG_ENDIAN)
bbuf.putInt(value)
bbuf.order(ByteOrder.LITTLE_ENDIAN)
value = bbuf.getShort(2).toInt()
try {
dataOut.writeShort(value)
} catch (ex: IOException) {
value = -1
}
}
fun write(value: Float) {
var value = value
val bbuf = ByteBuffer.allocate(4)
bbuf.order(ByteOrder.BIG_ENDIAN)
bbuf.putFloat(value)
bbuf.order(ByteOrder.LITTLE_ENDIAN)
value = bbuf.getFloat(0)
try {
dataOut.writeFloat(value)
} catch (ex: IOException) {
Logger.getLogger(WriteFunctions::class.java.name).log(Level.SEVERE, null, ex)
}
}
fun writeChar(value: Char): Char {
val letter = '\u0000'
try {
dataOut.writeByte(value.code)
} catch (ex: IOException) {
// Logger.getLogger(loadSAFiles.class.getName()).log(Level.SEVERE, null, ex);
}
return letter
}
fun writeString(value: String) {
for (i in 0 until value.length) {
writeChar(value[i])
}
}
fun writeNullTerminatedString(value: String) {
for (i in 0 until value.length) {
writeChar(value[i])
}
writeByte(0)
}
fun write(vector: Vector3D) {
write(vector.x)
write(vector.y)
write(vector.z)
}
fun write(vector: Vector4D) {
write(vector.x)
write(vector.y)
write(vector.z)
write(vector.w)
}
fun write(array: ByteArray) {
try {
dataOut.write(array)
} catch (ex: IOException) {
Logger.getLogger(WriteFunctions::class.java.name).log(Level.SEVERE, null, ex)
}
}
fun seek(pos: Int) {
try {
dataOut.seek(pos.toLong())
} catch (ex: IOException) {
Logger.getLogger(WriteFunctions::class.java.name).log(Level.SEVERE, null, ex)
}
}
fun gotoEnd() {
try {
dataOut.seek(dataOut.length())
} catch (ex: IOException) {
Logger.getLogger(WriteFunctions::class.java.name).log(Level.SEVERE, null, ex)
}
}
val fileSize: Int
get() = try {
dataOut.length().toInt()
} catch (ex: IOException) {
0
}
} | gpl-2.0 | d806d77bdee26ce87bad12017394bb2a | 24.222973 | 89 | 0.554394 | 3.895616 | false | false | false | false |
UCSoftworks/LeafDb | leafdb-core/src/main/java/com/ucsoftworks/leafdb/dsl/Field.kt | 1 | 2757 | package com.ucsoftworks.leafdb.dsl
/**
* Created by Pasenchuk Victor on 10/08/2017
*/
class Field private constructor(internal val field: String) {
companion object {
private fun getPath(vararg path: String): String {
if (path.isEmpty())
return "$"
return path.joinToString(".", prefix = "$.")
}
}
constructor(vararg path: String) : this("json_extract(doc, '${Field.getPath(*path)}')")
internal constructor(a: Field, operator: String, b: Field) : this("($a $operator $b)")
internal constructor(a: Field, operator: String, b: Number) : this("($a $operator $b)")
internal constructor(b: Number, operator: String, a: Field) : this("($b $operator $a)")
operator fun unaryPlus() = Field("+$field")
operator fun unaryMinus() = Field("-$field")
operator fun plus(field: Field) = Field(this, "+", field)
operator fun minus(field: Field) = Field(this, "-", field)
operator fun times(field: Field) = Field(this, "*", field)
operator fun div(field: Field) = Field(this, "/", field)
operator fun rem(field: Field) = Field(this, "%", field)
operator fun plus(number: Number) = Field(this, "+", number)
operator fun minus(number: Number) = Field(this, "-", number)
operator fun times(number: Number) = Field(this, "*", number)
operator fun div(number: Number) = Field(this, "/", number)
operator fun rem(number: Number) = Field(this, "%", number)
infix fun greaterThan(a: Any?)
= Condition.compareField(this, ComparisonOperator.GREATER_THAN, a)
infix fun greaterThanOrEqual(a: Any?)
= Condition.compareField(this, ComparisonOperator.GREATER_THAN_OR_EQUAL, a)
infix fun lessThan(a: Any?)
= Condition.compareField(this, ComparisonOperator.LESS_THAN, a)
infix fun lessThanOrEqual(a: Any?)
= Condition.compareField(this, ComparisonOperator.LESS_THAN_OR_EQUAL, a)
infix fun notEqual(a: Any?)
= Condition.compareField(this, ComparisonOperator.NOT_EQUAL, a)
infix fun equal(a: Any?)
= Condition.compareField(this, ComparisonOperator.EQUAL, a)
fun isNull() = Condition.isNull(this)
fun isNotNull()
= Condition.isNotNull(this)
infix fun <T : Comparable<T>> between(interval: ClosedRange<T>)
= Condition.between(this, interval.start, interval.endInclusive)
infix fun like(pattern: String)
= Condition.like(this, pattern)
infix fun contains(query: String)
= this.like("%$query%")
infix fun startsWith(query: String)
= this.like("$query%")
infix fun endsWith(query: String)
= this.like("$query%")
override fun toString() = field
}
| lgpl-3.0 | 8322cea8f99b08d4e12af8e3f82e08e3 | 34.805195 | 91 | 0.632572 | 4.060383 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.