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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hellenxu/TipsProject | DroidDailyProject/app/src/main/java/six/ca/droiddailyproject/coordinatorLayout/CoordinatorSample.kt | 1 | 1100 | package six.ca.droiddailyproject.coordinatorLayout
import android.graphics.Color
import android.os.Bundle
import com.google.android.material.appbar.CollapsingToolbarLayout
import androidx.appcompat.app.AppCompatActivity
import six.ca.droiddailyproject.R
/**
* CoordinatorLayout Hello World.
* Created by Xiaolin on 2016-07-11.
*/
class CoordinatorSample : AppCompatActivity(){
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.act_coordinator_nested)
val colBar = findViewById(R.id.colToolbar) as CollapsingToolbarLayout
colBar.title = getString(R.string.app_name)
colBar.setExpandedTitleColor(Color.WHITE)
colBar.setCollapsedTitleTextColor(Color.WHITE)
// val data = ArrayList<String>()
// for(i in 0..30){
// data.add("title: " + i)
// }
// val recylerView = findViewById(R.id.rvDetails) as RecyclerView
// recylerView.layoutManager = LinearLayoutManager(this)
// recylerView.adapter = RVSampleAdapter(this, data)
}
} | apache-2.0 | 4cb20353b45e875a56e3ab881ba86f3e | 31.382353 | 77 | 0.715455 | 4.150943 | false | false | false | false |
ktorio/ktor | ktor-utils/jvm/src/io/ktor/util/CryptoJvm.kt | 1 | 1916 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
@file:kotlin.jvm.JvmMultifileClass
@file:kotlin.jvm.JvmName("CryptoKt")
@file:Suppress("FunctionName")
package io.ktor.util
import kotlinx.coroutines.*
import java.security.*
/**
* Create a digest function with the specified [algorithm] and [salt] provider.
* @param algorithm digest algorithm name
* @param salt a function computing a salt for a particular hash input value
*/
public fun getDigestFunction(algorithm: String, salt: (value: String) -> String): (String) -> ByteArray = { e ->
getDigest(e, algorithm, salt)
}
private fun getDigest(text: String, algorithm: String, salt: (String) -> String): ByteArray =
with(MessageDigest.getInstance(algorithm)) {
update(salt(text).toByteArray())
digest(text.toByteArray())
}
/**
* Compute SHA-1 hash for the specified [bytes]
*/
public actual fun sha1(bytes: ByteArray): ByteArray =
MessageDigest.getInstance("SHA1").digest(bytes)
/**
* Create [Digest] from specified hash [name].
*/
public actual fun Digest(name: String): Digest = DigestImpl(MessageDigest.getInstance(name))
@JvmInline
private value class DigestImpl(val delegate: MessageDigest) : Digest {
override fun plusAssign(bytes: ByteArray) {
delegate.update(bytes)
}
override fun reset() {
delegate.reset()
}
override suspend fun build(): ByteArray = delegate.digest()
}
/**
* Generates a nonce string 16 characters long. Could block if the system's entropy source is empty
*/
public actual fun generateNonce(): String {
val nonce = seedChannel.tryReceive().getOrNull()
if (nonce != null) return nonce
return generateNonceBlocking()
}
private fun generateNonceBlocking(): String {
ensureNonceGeneratorRunning()
return runBlocking {
seedChannel.receive()
}
}
| apache-2.0 | 602e6006060a833d7e413fa9b1097875 | 27.176471 | 118 | 0.708768 | 4.094017 | false | false | false | false |
RedInput/Notification-Blocker | app/src/main/java/com/redinput/notifblock/AppsAdapter.kt | 1 | 2766 | package com.redinput.notifblock
import android.content.Context
import android.content.SharedPreferences
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.preference.PreferenceManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.redinput.notifblock.AppsAdapter.AppsViewHolder
import java.util.*
class AppsAdapter(context: Context, private var apps: List<ApplicationInfo>, checkedListener: OnCheckboxAppChecked) : RecyclerView.Adapter<AppsViewHolder>() {
class AppsViewHolder(itemView: View, var listener: OnCheckboxAppChecked) : RecyclerView.ViewHolder(itemView) {
var icon: ImageView
var name: TextView
var hide: CheckBox
init {
icon = itemView.findViewById(R.id.app_icon)
name = itemView.findViewById(R.id.app_name)
hide = itemView.findViewById(R.id.app_hide)
itemView.setOnClickListener { hide.performClick() }
hide.setOnCheckedChangeListener { buttonView, isChecked -> listener.onCheckboxAppChecked(layoutPosition, isChecked) }
}
}
private val pm: PackageManager
private val mLayoutInflater: LayoutInflater
private val checkedListener: OnCheckboxAppChecked
private val preferences: SharedPreferences
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): AppsViewHolder {
val v = mLayoutInflater.inflate(R.layout.app_recycler_row, parent, false)
return AppsViewHolder(v, checkedListener)
}
override fun onBindViewHolder(holder: AppsViewHolder, position: Int) {
val app = apps[position]
val blocked = HashSet(Arrays.asList(*preferences.getString(Utils.PREF_PACKAGES_BLOCKED, "")!!.split(";").toTypedArray()))
holder.icon.setImageDrawable(app.loadIcon(pm))
holder.name.text = app.loadLabel(pm)
holder.hide.isChecked = blocked.contains(app.packageName)
}
override fun getItemId(position: Int): Long {
return apps[position].packageName.hashCode().toLong()
}
override fun getItemCount(): Int {
return apps.size
}
fun getIem(position: Int): ApplicationInfo {
return apps[position]
}
fun setApps(apps: List<ApplicationInfo>) {
this.apps = apps
notifyDataSetChanged()
}
init {
pm = context.packageManager
mLayoutInflater = LayoutInflater.from(context)
this.checkedListener = checkedListener
preferences = PreferenceManager.getDefaultSharedPreferences(context)
setHasStableIds(true)
}
} | apache-2.0 | 6077086c6764b9a92c06456ee53e6262 | 35.893333 | 158 | 0.723789 | 4.785467 | false | false | false | false |
dahlstrom-g/intellij-community | java/java-impl/src/com/intellij/pom/java/JavaLanguageVersionsCollector.kt | 8 | 3056 | // 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 com.intellij.pom.java
import com.intellij.execution.wsl.WslPath
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.module.LanguageLevelUtil
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.roots.LanguageLevelProjectExtension
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.util.lang.JavaVersion
import java.util.*
class JavaLanguageVersionsCollector : ProjectUsagesCollector() {
private val group = EventLogGroup("java.language", 3)
private val feature = EventFields.Int("feature")
private val minor = EventFields.Int("minor")
private val update = EventFields.Int("update")
private val ea = EventFields.Boolean("ea")
private val wsl = EventFields.Boolean("wsl")
private val moduleJdkVersion = group.registerVarargEvent("MODULE_JDK_VERSION",
feature, minor, update, ea, wsl)
private val moduleLanguageLevel = group.registerEvent("MODULE_LANGUAGE_LEVEL",
EventFields.Int("version"),
EventFields.Boolean("preview"))
override fun getGroup(): EventLogGroup {
return group
}
public override fun getMetrics(project: Project): Set<MetricEvent> {
val sdks = ModuleManager.getInstance(project).modules.mapNotNullTo(HashSet()) {
ModuleRootManager.getInstance(it).sdk
}.filter { it.sdkType is JavaSdk }
val jdkVersions = sdks.mapTo(HashSet()) { sdk ->
JavaVersion.tryParse(sdk.versionString) to (sdk.homePath?.let { WslPath.isWslUncPath(it) } ?: false)
}
val metrics = HashSet<MetricEvent>()
jdkVersions.mapTo(metrics) { (version, isWsl) ->
moduleJdkVersion.metric(
feature with (version?.feature ?: -1),
minor with (version?.minor ?: -1),
update with (version?.update ?: -1),
ea with (version?.ea ?: false),
wsl with isWsl
)
}
val projectExtension = LanguageLevelProjectExtension.getInstance(project)
if (projectExtension != null) {
val projectLanguageLevel = projectExtension.languageLevel
val languageLevels = ModuleManager.getInstance(project).modules.mapTo(EnumSet.noneOf(LanguageLevel::class.java)) {
LanguageLevelUtil.getCustomLanguageLevel(it) ?: projectLanguageLevel
}
languageLevels.mapTo(metrics) {
moduleLanguageLevel.metric(it.toJavaVersion().feature, it.isPreview)
}
}
return metrics
}
override fun requiresReadAccess() = true
}
| apache-2.0 | c5efe973ac35f968505a8a2009f20976 | 42.042254 | 158 | 0.708442 | 4.797488 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/openapi/util/io/fileUtil.kt | 12 | 462 | // 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.openapi.util.io
import java.io.File
val File.systemIndependentPath: String
get() = path.replace(File.separatorChar, '/')
fun endsWithName(path: String, name: String): Boolean {
return path.endsWith(name) && (path.length == name.length || path.getOrNull(path.length - name.length - 1) == '/')
} | apache-2.0 | d5dbc9d68a71de8c4911dcdb0893ac40 | 41.090909 | 140 | 0.731602 | 3.666667 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/typing/DefaultMethodCallTypeCalculator.kt | 1 | 4811 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.typing
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.*
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
import org.jetbrains.plugins.groovy.lang.psi.impl.GrClosureType
import org.jetbrains.plugins.groovy.lang.psi.impl.GrLiteralClassType
import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.getSmartReturnType
import org.jetbrains.plugins.groovy.lang.resolve.api.Argument
import org.jetbrains.plugins.groovy.lang.resolve.api.Arguments
import org.jetbrains.plugins.groovy.lang.resolve.impl.getArguments
class DefaultMethodCallTypeCalculator : GrTypeCalculator<GrMethodCall> {
override fun getType(expression: GrMethodCall): PsiType? {
val results = expression.multiResolve(false)
if (results.isEmpty()) {
return null
}
val arguments = expression.getArguments()
var type: PsiType? = null
for (result in results) {
type = TypesUtil.getLeastUpperBoundNullable(type, getTypeFromResult(result, arguments, expression), expression.manager)
}
return type
}
}
fun getTypeFromResult(result: GroovyResolveResult, arguments: Arguments?, context: GrExpression): PsiType? {
val baseType = getBaseTypeFromResult(result, arguments, context).devoid(context) ?: return null
val substitutor = if (baseType !is GrLiteralClassType && hasGenerics(baseType)) result.substitutor else PsiSubstitutor.EMPTY
return TypesUtil.substituteAndNormalizeType(baseType, substitutor, result.spreadState, context)
}
private fun getBaseTypeFromResult(result: GroovyResolveResult, arguments: Arguments?, context: PsiElement): PsiType? {
return when {
result.isInvokedOnProperty -> getTypeFromPropertyCall(result.element, arguments, context)
result is GroovyMethodResult -> getTypeFromCandidate(result, context)
else -> null
}
}
private fun getTypeFromCandidate(result: GroovyMethodResult, context: PsiElement): PsiType? {
val candidate = result.candidate ?: return null
for (ext in ep.extensions) {
return ext.getType(candidate.receiver, candidate.method, candidate.argumentMapping?.arguments, context) ?: continue
}
return getSmartReturnType(candidate.method)
}
private val ep: ExtensionPointName<GrCallTypeCalculator> = ExtensionPointName.create("org.intellij.groovy.callTypeCalculator")
private fun getTypeFromPropertyCall(element: PsiElement?, arguments: Arguments?, context: PsiElement): PsiType? {
val type = when (element) { // TODO introduce property concept, resolve into it and get its type
is GrField -> element.typeGroovy
is GrMethod -> element.inferredReturnType
is GrAccessorMethod -> element.inferredReturnType
is PsiField -> element.type
is PsiMethod -> element.returnType
else -> null
}
if (type !is GrClosureType) {
return null
}
val argumentTypes = arguments?.map(Argument::type)?.toTypedArray()
return GrClosureSignatureUtil.getReturnType(type.signatures, argumentTypes, context)
}
fun PsiType?.devoid(context: PsiElement): PsiType? {
return if (this == PsiType.VOID && !PsiUtil.isCompileStatic(context)) PsiType.NULL else this
}
private fun hasGenerics(type: PsiType): Boolean {
return !Registry.`is`("groovy.return.type.optimization") || type.accept(GenericsSearcher) == true
}
private object GenericsSearcher : PsiTypeVisitor<Boolean?>() {
override fun visitClassType(classType: PsiClassType): Boolean? {
if (classType.resolve() is PsiTypeParameter) {
return true
}
if (!classType.hasParameters()) {
return null
}
for (parameter in classType.parameters) {
if (parameter.accept(this) == true) return true
}
return null
}
override fun visitArrayType(arrayType: PsiArrayType): Boolean? = arrayType.componentType.accept(this)
override fun visitWildcardType(wildcardType: PsiWildcardType): Boolean? = wildcardType.bound?.accept(this)
}
| apache-2.0 | 55111e25c88e1914ef6dd896adb837ae | 44.386792 | 140 | 0.783413 | 4.34991 | false | false | false | false |
Werb/MoreType | app/src/main/java/com/werb/moretype/click/ItemClickActivity.kt | 1 | 3852 | package com.werb.moretype.click
import android.app.Activity
import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.werb.library.MoreAdapter
import com.werb.library.action.MoreClickListener
import com.werb.library.link.MultiLink
import com.werb.library.link.RegisterItem
import com.werb.moretype.R
import com.werb.moretype.TitleViewHolder
import com.werb.moretype.data.DataServer
import kotlinx.android.synthetic.main.activity_item_click.*
/**
* Created by wanbo on 2017/7/15.
*/
class ItemClickActivity : AppCompatActivity() {
private val adapter = MoreAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_item_click)
toolbar.setNavigationIcon(R.mipmap.ic_close_white_24dp)
toolbar.setNavigationOnClickListener { finish() }
item_click_list.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
item_click_list.adapter = adapter
adapter.apply {
register(RegisterItem(R.layout.item_view_title, TitleViewHolder::class.java))
multiRegister(object : MultiLink<ItemClick>() {
override fun link(data: ItemClick): RegisterItem {
return if (data.click) {
RegisterItem(R.layout.item_view_click_one, ItemClickOneViewHolder::class.java, oneClick)
} else {
RegisterItem(R.layout.item_view_click_two, ItemClickTwoViewHolder::class.java, twoClick)
}
}
})
}
adapter.loadData(DataServer.getItemClickData())
}
private val oneClick = object : MoreClickListener() {
override fun onItemClick(view: View, position: Int) {
when (view.id) {
R.id.icon -> {
val url = view.tag as String
Toast.makeText(view.context, "click icon in Activity icon url is " + url, Toast.LENGTH_SHORT).show()
}
R.id.button -> {
Toast.makeText(view.context, "click button in Activity position is " + position.toString(), Toast.LENGTH_SHORT).show()
}
}
}
override fun onItemTouch(view: View, event: MotionEvent, position: Int): Boolean {
Toast.makeText(this@ItemClickActivity, "111", Toast.LENGTH_SHORT).show()
return true
}
override fun onItemLongClick(view: View, position: Int): Boolean {
return false
}
}
private val twoClick = object : MoreClickListener() {
override fun onItemClick(view: View, position: Int) {
when (view.id) {
R.id.icon -> {
val url = view.tag as String
Toast.makeText(view.context, "click icon in Activity icon url is " + url, Toast.LENGTH_SHORT).show()
}
}
}
override fun onItemLongClick(view: View, position: Int): Boolean {
when (view.id) {
R.id.button -> {
AlertDialog.Builder(view.context)
.setTitle("Button click in Activity position is " + position.toString())
.setPositiveButton("sure", { _: DialogInterface, _: Int -> })
.show()
}
}
return true
}
}
companion object {
fun startActivity(activity: Activity) {
activity.startActivity(Intent(activity, ItemClickActivity::class.java))
}
}
} | apache-2.0 | 707029c293e0583de289a0fa64fa312d | 35.009346 | 138 | 0.604102 | 4.629808 | false | false | false | false |
google/intellij-community | platform/workspaceModel/storage/tests/testSrc/com/intellij/workspaceModel/storage/AbstractEntitiesTest.kt | 5 | 6083 | // 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.workspaceModel.storage
import com.intellij.testFramework.UsefulTestCase.assertOneElement
import com.intellij.workspaceModel.storage.entities.test.api.LeftEntity
import com.intellij.workspaceModel.storage.entities.test.api.MiddleEntity
import com.intellij.workspaceModel.storage.entities.test.api.addLeftEntity
import com.intellij.workspaceModel.storage.entities.test.api.addMiddleEntity
import com.intellij.workspaceModel.storage.entities.test.api.modifyEntity
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class AbstractEntitiesTest {
@Test
fun `simple adding`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
builder.addLeftEntity(sequenceOf(middleEntity))
val storage = builder.toSnapshot()
val leftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
assertOneElement(leftEntity.children.toList())
}
@Test
fun `modifying left entity`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity("first")
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherMiddleEntity = builder.addMiddleEntity("second")
builder.modifyEntity(leftEntity) {
}
builder.modifyEntity(leftEntity) {
this.children = listOf(anotherMiddleEntity)
}
val storage = builder.toSnapshot()
val actualLeftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
val actualChild = assertOneElement(actualLeftEntity.children.toList())
assertEquals(anotherMiddleEntity, actualChild)
assertEquals(anotherMiddleEntity.property, (actualChild as MiddleEntity).property)
}
@Test
fun `modifying abstract entity`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherMiddleEntity = builder.addMiddleEntity()
builder.modifyEntity(leftEntity) {
this.children = listOf(anotherMiddleEntity)
}
val storage = builder.toSnapshot()
val actualLeftEntity = assertOneElement(storage.entities(LeftEntity::class.java).toList())
val actualChild = assertOneElement(actualLeftEntity.children.toList())
assertEquals(anotherMiddleEntity, actualChild)
assertEquals(anotherMiddleEntity.property, (actualChild as MiddleEntity).property)
}
@Test
fun `children replace in addDiff`() {
val builder = MutableEntityStorage.create()
val middleEntity = builder.addMiddleEntity()
val leftEntity = builder.addLeftEntity(sequenceOf(middleEntity))
val anotherBuilder = MutableEntityStorage.from(builder)
val anotherMiddleEntity = anotherBuilder.addMiddleEntity("Another")
anotherBuilder.modifyEntity(leftEntity) {
this.children = listOf(middleEntity, anotherMiddleEntity)
}
val initialMiddleEntity = builder.addMiddleEntity("Initial")
builder.modifyEntity(leftEntity) {
this.children = listOf(middleEntity, initialMiddleEntity)
}
builder.addDiff(anotherBuilder)
val actualLeftEntity = assertOneElement(builder.entities(LeftEntity::class.java).toList())
val children = actualLeftEntity.children.toList() as List<MiddleEntity>
assertEquals(2, children.size)
assertTrue(children.any { it.property == "Another" })
assertTrue(children.none { it.property == "Initial" })
}
@Test
fun `keep children ordering when making storage`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val storage = builder.toSnapshot()
val children = storage.entities(LeftEntity::class.java).single().children.toList()
assertEquals(middleEntity1, children[0])
assertEquals(middleEntity2, children[1])
}
@Test
fun `keep children ordering when making storage 2`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("Two")
val middleEntity2 = builder.addMiddleEntity("One")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val anotherBuilder = makeBuilder(builder) {
addLeftEntity(sequenceOf(middleEntity2, middleEntity1))
}
builder.addDiff(anotherBuilder)
val storage = builder.toSnapshot()
val children = storage.entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity2, children[0])
assertEquals(middleEntity1, children[1])
}
@Test
fun `keep children ordering after rbs 1`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity1, middleEntity2))
val target = MutableEntityStorage.create()
target.replaceBySource({ true }, builder)
val children = target.toSnapshot().entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity1.property, (children[0] as MiddleEntity).property)
assertEquals(middleEntity2.property, (children[1] as MiddleEntity).property)
}
@Test
fun `keep children ordering after rbs 2`() {
val builder = MutableEntityStorage.create()
val middleEntity1 = builder.addMiddleEntity("One")
val middleEntity2 = builder.addMiddleEntity("Two")
builder.addLeftEntity(sequenceOf(middleEntity2, middleEntity1))
val target = MutableEntityStorage.create()
target.replaceBySource({ true }, builder)
val children = target.toSnapshot().entities(LeftEntity::class.java).last().children.toList()
assertEquals(middleEntity2.property, (children[0] as MiddleEntity).property)
assertEquals(middleEntity1.property, (children[1] as MiddleEntity).property)
}
}
| apache-2.0 | f9829fa10026c463c59706d61297b1b9 | 36.782609 | 140 | 0.755713 | 4.885944 | false | true | false | false |
Bugfry/exercism | exercism/kotlin/nucleotide-count/src/main/kotlin/DNA.kt | 2 | 519 | private val legalNucleotides = "ACGT"
class DNA(val dna: String) {
init {
if (!dna.all { it in legalNucleotides }) {
throw IllegalArgumentException("Illegal character in DNA sequence")
}
}
fun count(nucleotide: Char): Int =
if (nucleotide in legalNucleotides) {
dna.count { it == nucleotide }
} else {
throw IllegalArgumentException("Illegal nucleotide character.")
}
val nucleotideCounts: Map<Char, Int>
get() = legalNucleotides.map { it to count(it) }.toMap()
}
| mit | 6884366e3061cac9bc2e23bef97cdec5 | 23.714286 | 73 | 0.657033 | 3.305732 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/IntelliJKotlinNewProjectWizard.kt | 1 | 3854 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.tools.projectWizard
import com.intellij.ide.JavaUiBundle
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logAddSampleCodeChanged
import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkChanged
import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.INTELLIJ
import com.intellij.ide.projectWizard.generators.AssetsNewProjectWizardStep
import com.intellij.ide.starters.local.StandardAssetsProvider
import com.intellij.ide.wizard.AbstractNewProjectWizardStep
import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.name
import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.path
import com.intellij.ide.wizard.NewProjectWizardStep
import com.intellij.ide.wizard.NewProjectWizardStep.Companion.ADD_SAMPLE_CODE_PROPERTY_NAME
import com.intellij.ide.wizard.chain
import com.intellij.openapi.module.StdModuleTypes
import com.intellij.openapi.observable.util.bindBooleanStorage
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkTypeId
import com.intellij.openapi.projectRoots.impl.DependentSdkType
import com.intellij.openapi.roots.ui.configuration.sdkComboBox
import com.intellij.ui.UIBundle.*
import com.intellij.ui.dsl.builder.*
import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType
internal class IntelliJKotlinNewProjectWizard : BuildSystemKotlinNewProjectWizard {
override val name = INTELLIJ
override val ordinal = 0
override fun createStep(parent: KotlinNewProjectWizard.Step) = Step(parent).chain(::AssetsStep)
class Step(parent: KotlinNewProjectWizard.Step) :
AbstractNewProjectWizardStep(parent),
BuildSystemKotlinNewProjectWizardData by parent {
private val sdkProperty = propertyGraph.property<Sdk?>(null)
private val addSampleCodeProperty = propertyGraph.property(true)
.bindBooleanStorage(ADD_SAMPLE_CODE_PROPERTY_NAME)
private val sdk by sdkProperty
private val addSampleCode by addSampleCodeProperty
override fun setupUI(builder: Panel) {
with(builder) {
row(JavaUiBundle.message("label.project.wizard.new.project.jdk")) {
val sdkTypeFilter = { it: SdkTypeId -> it is JavaSdkType && it !is DependentSdkType }
sdkComboBox(context, sdkProperty, StdModuleTypes.JAVA.id, sdkTypeFilter)
.columns(COLUMNS_MEDIUM)
.whenItemSelectedFromUi { logSdkChanged(sdk) }
}
row {
checkBox(message("label.project.wizard.new.project.add.sample.code"))
.bindSelected(addSampleCodeProperty)
.whenStateChangedFromUi { logAddSampleCodeChanged(it) }
}.topGap(TopGap.SMALL)
kmpWizardLink(context)
}
}
override fun setupProject(project: Project) =
KotlinNewProjectWizard.generateProject(
project = project,
projectPath = "$path/$name",
projectName = name,
sdk = sdk,
buildSystemType = BuildSystemType.Jps,
addSampleCode = addSampleCode
)
}
private class AssetsStep(parent: NewProjectWizardStep) : AssetsNewProjectWizardStep(parent) {
override fun setupAssets(project: Project) {
outputDirectory = "$path/$name"
addAssets(StandardAssetsProvider().getIntelliJIgnoreAssets())
}
}
} | apache-2.0 | d7cbe7f56aee12e68377b5530064301e | 46.012195 | 158 | 0.723664 | 5.187079 | false | false | false | false |
spacecowboy/Feeder | app/src/main/java/com/nononsenseapps/feeder/model/opml/OpmlParser.kt | 1 | 3627 | package com.nononsenseapps.feeder.model.opml
import com.nononsenseapps.feeder.db.room.Feed
import com.nononsenseapps.feeder.model.OPMLParserToDatabase
import com.nononsenseapps.feeder.util.sloppyLinkToStrictURL
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.Stack
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.ccil.cowan.tagsoup.Parser
import org.xml.sax.Attributes
import org.xml.sax.ContentHandler
import org.xml.sax.InputSource
import org.xml.sax.Locator
import org.xml.sax.SAXException
class OpmlParser(val opmlToDb: OPMLParserToDatabase) : ContentHandler {
val parser: Parser = Parser()
val tagStack: Stack<String> = Stack()
var isFeedTag = false
var ignoring = 0
var feeds: MutableList<Feed> = mutableListOf()
init {
parser.contentHandler = this
}
@Throws(IOException::class, SAXException::class)
suspend fun parseFile(path: String) {
// Open file
val file = File(path)
file.inputStream().use {
parseInputStream(it)
}
}
@Throws(IOException::class, SAXException::class)
suspend fun parseInputStream(inputStream: InputStream) = withContext(Dispatchers.IO) {
feeds = mutableListOf()
tagStack.clear()
isFeedTag = false
ignoring = 0
parser.parse(InputSource(inputStream))
for (feed in feeds) {
opmlToDb.saveFeed(feed)
}
}
override fun endElement(uri: String?, localName: String?, qName: String?) {
if ("outline" == localName) {
when {
ignoring > 0 -> ignoring--
isFeedTag -> isFeedTag = false
else -> tagStack.pop()
}
}
}
override fun processingInstruction(target: String?, data: String?) {
}
override fun startPrefixMapping(prefix: String?, uri: String?) {
}
override fun ignorableWhitespace(ch: CharArray?, start: Int, length: Int) {
}
override fun characters(ch: CharArray?, start: Int, length: Int) {
}
override fun endDocument() {
}
override fun startElement(uri: String?, localName: String?, qName: String?, atts: Attributes?) {
if ("outline" == localName) {
when {
// Nesting not allowed
ignoring > 0 || isFeedTag -> ignoring++
outlineIsFeed(atts) -> {
isFeedTag = true
val feedTitle = unescape(
atts?.getValue("title") ?: atts?.getValue("text")
?: ""
)
val feed = Feed(
title = feedTitle,
customTitle = feedTitle,
tag = if (tagStack.isNotEmpty()) tagStack.peek() else "",
url = sloppyLinkToStrictURL(atts?.getValue("xmlurl") ?: "")
)
feeds.add(feed)
}
else -> tagStack.push(
unescape(
atts?.getValue("title")
?: atts?.getValue("text")
?: ""
)
)
}
}
}
private fun outlineIsFeed(atts: Attributes?): Boolean =
atts?.getValue("xmlurl") != null
override fun skippedEntity(name: String?) {
}
override fun setDocumentLocator(locator: Locator?) {
}
override fun endPrefixMapping(prefix: String?) {
}
override fun startDocument() {
}
}
| gpl-3.0 | 65d7723c49905bad2410485c36ee28dc | 28.016 | 100 | 0.563 | 4.620382 | false | false | false | false |
chrislo27/RhythmHeavenRemixEditor2 | core/src/main/kotlin/io/github/chrislo27/toolboks/ui/ImageLabel.kt | 2 | 3252 | package io.github.chrislo27.toolboks.ui
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.g2d.SpriteBatch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.graphics.glutils.ShapeRenderer
import com.badlogic.gdx.math.Vector2
import io.github.chrislo27.toolboks.ToolboksScreen
import io.github.chrislo27.toolboks.util.gdxutils.fillRect
/**
* A standard image label.
*/
open class ImageLabel<S : ToolboksScreen<*, *>>
: Label<S>, Palettable {
constructor(palette: UIPalette, parent: UIElement<S>, stage: Stage<S>)
: super(palette, parent, stage)
enum class ImageRendering {
/**
* Draws the region at the full bounds of this element.
*/
RENDER_FULL,
/**
* Maintains the UI element's original aspect ratio, attempting to maximize space but not oversize.
*/
ASPECT_RATIO,
/**
* Maintains the REGION's aspect ratio, oversizing if necessary,
*/
IMAGE_ASPECT_RATIO
}
override var background = false
var image: TextureRegion? = null
var tint: Color = Color(1f, 1f, 1f, 1f)
var renderType: ImageRendering = ImageRendering.ASPECT_RATIO
var rotation: Float = 0f
var rotationPoint = Vector2(0.5f, 0.5f)
override fun render(screen: S, batch: SpriteBatch,
shapeRenderer: ShapeRenderer) {
if (background) {
val old = batch.packedColor
batch.color = palette.backColor
batch.fillRect(location.realX, location.realY, location.realWidth, location.realHeight)
batch.packedColor = old
}
val image = this.image ?: return
val old = batch.packedColor
batch.color = tint
when (renderType) {
ImageLabel.ImageRendering.RENDER_FULL -> {
batch.draw(image,
location.realX, location.realY,
rotationPoint.x * location.realWidth, rotationPoint.y * location.realHeight,
location.realWidth, location.realHeight,
1f, 1f,
rotation)
}
ImageLabel.ImageRendering.ASPECT_RATIO, ImageRendering.IMAGE_ASPECT_RATIO -> {
val aspectWidth = location.realWidth / image.regionWidth
val aspectHeight = location.realHeight / image.regionHeight
val aspectRatio = if (renderType == ImageRendering.ASPECT_RATIO) Math.min(aspectWidth, aspectHeight) else Math.max(aspectWidth, aspectHeight)
val x: Float
val y: Float
val w: Float
val h: Float
w = image.regionWidth * aspectRatio
h = image.regionHeight * aspectRatio
x = location.realWidth / 2 - (w / 2)
y = location.realHeight / 2 - (h / 2)
batch.draw(image, location.realX + x, location.realY + y,
rotationPoint.x * w, rotationPoint.y * h,
w, h,
1f, 1f,
rotation)
}
}
batch.packedColor = old
}
}
| gpl-3.0 | cf28d8372ba762e0aecbccec99207a64 | 33.595745 | 157 | 0.576876 | 4.639087 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/data/base/repository/delegate/ListRepositoryDelegate.kt | 1 | 1780 | package org.stepik.android.data.base.repository.delegate
import io.reactivex.Completable
import io.reactivex.Single
import org.stepik.android.domain.base.DataSourceType
import ru.nobird.app.core.model.Identifiable
import ru.nobird.android.domain.rx.doCompletableOnSuccess
import ru.nobird.android.domain.rx.requireSize
class ListRepositoryDelegate<ID, Item : Identifiable<ID>>(
private val remoteSource: (List<ID>) -> Single<List<Item>>,
private val cacheSource: (List<ID>) -> Single<List<Item>>,
private val saveAction: (List<Item>) -> Completable
) {
fun get(ids: List<ID>, sourceType: DataSourceType, allowFallback: Boolean = false): Single<List<Item>> {
if (ids.isEmpty()) return Single.just(emptyList())
val remote = remoteSource(ids)
.doCompletableOnSuccess(saveAction)
val cache = cacheSource(ids)
return when (sourceType) {
DataSourceType.REMOTE ->
if (allowFallback) {
remote.onErrorResumeNext(cache.requireSize(ids.size))
} else {
remote
}
DataSourceType.CACHE ->
if (allowFallback) {
cache.flatMap { cachedItems ->
val newIds = (ids.toList() - cachedItems.map { it.id })
remoteSource(newIds)
.doCompletableOnSuccess(saveAction)
.map { remoteItems -> (cachedItems + remoteItems) }
}
} else {
cache
}
else ->
throw IllegalArgumentException("Unsupported sourceType = $sourceType")
}.map { items -> items.sortedBy { ids.indexOf(it.id) } }
}
} | apache-2.0 | b9a3d87956f3b1cee021b0e4f506e68c | 36.893617 | 108 | 0.581461 | 4.823848 | false | false | false | false |
theunknownxy/mcdocs | src/main/kotlin/de/theunknownxy/mcdocs/gui/widget/ScrollWidget.kt | 1 | 5875 | package de.theunknownxy.mcdocs.gui.widget
import de.theunknownxy.mcdocs.gui.base.*
import de.theunknownxy.mcdocs.gui.base.Range
import de.theunknownxy.mcdocs.gui.event.MouseButton
import de.theunknownxy.mcdocs.utils.GuiUtils
import net.minecraft.client.Minecraft
import net.minecraft.util.ResourceLocation
import org.lwjgl.opengl.GL11
public class ScrollWidget(root: Root?, val child: ScrollChild) : Widget(root) {
companion object {
val SCROLLER_IMAGE = ResourceLocation("mcdocs:textures/gui/controls.png")
val SCROLLER_TIP_HEIGHT = 5
val SCROLLER_BAR_WIDTH = 9
val SCROLLER_MIDDLE_HEIGHT = 1
val SCROLLBUTTON_HEIGHT = 8
val SCROLLER_DESCRIPTION = BorderImageDescription(
Rectangle(
0f, 0f,
SCROLLER_BAR_WIDTH.toFloat(),
(SCROLLER_TIP_HEIGHT * 2 + SCROLLER_MIDDLE_HEIGHT).toFloat()),
SCROLLER_TIP_HEIGHT, 0, SCROLLER_TIP_HEIGHT, 0)
val SCROLLBUTTON_STEP = 50f
}
private var position = 0f
private var drag_last: Point? = null
/**
* Returns the area occupied by the scrollbar.
*/
private fun scrollbarArea(): Rectangle {
return Rectangle(x + width - SCROLLER_BAR_WIDTH, y, SCROLLER_BAR_WIDTH.toFloat(), height)
}
/**
* Returns the position and length of the visible view
*/
private fun contentRange(): Range {
return Range(position, position + height)
}
/**
* Returns the position and length of the scrollbar in screen coordinates.
*
* @note child mustn't be null
*/
private fun scrollerRangeScreen(): Range {
val scrollbararea = scrollbarArea()
val range = contentRange()
val startrel = range.start / child.getHeight()
val stoprel = range.stop / child.getHeight()
return Range(startrel * scrollbararea.height + SCROLLBUTTON_HEIGHT, stoprel * scrollbararea.height - SCROLLBUTTON_HEIGHT)
}
/**
* Returns the area occupied by the scroller.
*/
private fun scrollerArea(): Rectangle {
val scrollerrange = scrollerRangeScreen()
return Rectangle(x + width - SCROLLER_BAR_WIDTH, y + scrollerrange.start, SCROLLER_BAR_WIDTH.toFloat(), Math.max(scrollerrange.distance(), 2 * SCROLLER_TIP_HEIGHT.toFloat()))
}
/**
* Fix the scroller between the top and the bottom
*/
private fun fixScrollerPosition() {
var range = contentRange()
range.moveStop(Math.min(child.getHeight(), range.stop))
range.moveStart(Math.max(0f, range.start))
position = range.start
}
/**
* Returns the width of the child
*/
public fun childWidth(): Float {
return width - SCROLLER_BAR_WIDTH
}
override final fun draw() {
// Update mouse position in child
val root = root
if (root != null) {
child.mouse_pos = Point(root.mouse_pos.x - x, root.mouse_pos.y - y + position)
}
val child = child
// Setup depth buffer to hide elements outside the widget area
GL11.glClear(GL11.GL_DEPTH_BUFFER_BIT)
GL11.glDepthFunc(GL11.GL_ALWAYS)
GL11.glColorMask(false, false, false, false)
GuiUtils.drawColoredRect(x.toInt(), y.toInt(), (x + width).toInt(), (y + height).toInt(), 0x000000FF, 100.toDouble())
GL11.glColorMask(true, true, true, true)
GL11.glDepthFunc(GL11.GL_GREATER)
// Draw content
GL11.glPushMatrix()
GL11.glTranslatef(x, y - position, 0f)
child.draw()
GL11.glPopMatrix()
if (child.getHeight() > height) {
// Draw the scrollbar if the content is larger than the view
drawScrollbar()
}
GL11.glDepthFunc(GL11.GL_LEQUAL)
}
private fun drawScrollbar() {
GL11.glColor3f(1f, 1f, 1f)
Minecraft.getMinecraft().getTextureManager().bindTexture(SCROLLER_IMAGE)
val barleft = scrollbarArea().x.toInt()
// Draw scroller
GuiUtils.drawBox(scrollerArea(), 0.toDouble(), SCROLLER_DESCRIPTION)
// Draw Buttons
root!!.gui.drawTexturedModalRect(barleft, y.toInt(), 0, 11, SCROLLER_BAR_WIDTH, SCROLLBUTTON_HEIGHT)
root!!.gui.drawTexturedModalRect(barleft, (y + height - SCROLLBUTTON_HEIGHT).toInt(), 0, 19, SCROLLER_BAR_WIDTH, SCROLLBUTTON_HEIGHT)
}
override final fun onMouseClick(pos: Point, button: MouseButton): Widget? {
val scrollbar_area = scrollbarArea()
drag_last = null
if (Rectangle(scrollbar_area.x, scrollbar_area.y, scrollbar_area.width, SCROLLBUTTON_HEIGHT.toFloat()).contains(pos)) {
// Up button
position -= SCROLLBUTTON_STEP
} else if (Rectangle(scrollbar_area.x, scrollbar_area.y2() - SCROLLBUTTON_HEIGHT, scrollbar_area.width, SCROLLBUTTON_HEIGHT.toFloat()).contains(pos)) {
// Down button
position += SCROLLBUTTON_STEP
} else if (scrollerArea().contains(pos)) {
drag_last = pos
} else {
val mp = pos
mp.x -= this.x
mp.y -= this.y
mp.y += position
child.onMouseClick(mp, button)
}
fixScrollerPosition()
return this
}
override fun onUpdate() {
super.onUpdate()
fixScrollerPosition()
}
override fun onMouseClickMove(pos: Point) {
val drag_last = drag_last
if (drag_last != null) {
position += (pos.y - drag_last.y) / height * child.getHeight()
this.drag_last = pos
fixScrollerPosition()
}
}
override fun onMouseScroll(pos: Point, wheel: Int) {
position -= wheel * 0.3f
fixScrollerPosition()
}
override fun onAreaChanged() {
child.width = childWidth()
}
} | mit | 8fddd64d716ee5beb8befddf2b4d0396 | 32.386364 | 182 | 0.615149 | 4.114146 | false | false | false | false |
allotria/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/frame/XThreadsFramesView.kt | 3 | 17360 | // 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.xdebugger.impl.frame
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.NonProportionalOnePixelSplitter
import com.intellij.openapi.util.Disposer
import com.intellij.ui.ListSpeedSearch
import com.intellij.ui.PopupHandler
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.SpeedSearchComparator
import com.intellij.util.ui.JBUI
import com.intellij.util.ui.TextTransferable
import com.intellij.util.ui.UIUtil
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.frame.XExecutionStack
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.frame.XSuspendContext
import com.intellij.xdebugger.impl.XDebugSessionImpl
import com.intellij.xdebugger.impl.actions.XDebuggerActions
import java.awt.BorderLayout
import java.awt.Component
import java.awt.Dimension
import java.awt.Rectangle
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.JPanel
import javax.swing.JScrollPane
class XThreadsFramesView(val project: Project) : XDebugView() {
private val myPauseDisposables = SequentialDisposables(this)
private val myThreadsList = XDebuggerThreadsList.createDefault()
private val myFramesList = XDebuggerFramesList(project)
private val mySplitter: NonProportionalOnePixelSplitter
private var myListenersEnabled = false
private var myFramesManager: FramesManager
private var myThreadsContainer: ThreadsContainer
val threads: XDebuggerThreadsList get() = myThreadsList
val frames: XDebuggerFramesList get() = myFramesList
private var myAlreadyPaused = false
private val myFramesPresentationCache = mutableMapOf<Any, String>()
val mainPanel = JPanel(BorderLayout())
val defaultFocusedComponent: JComponent = myFramesList
companion object {
private const val splitterProportionKey = "XThreadsFramesViewSplitterKey"
private const val splitterProportionDefaultValue = 0.5f
private val Disposable.isAlive get() = !Disposer.isDisposed(this)
private val Disposable.isNotAlive get() = !isAlive
private fun Disposable.onTermination(disposable: Disposable) = Disposer.register(this, disposable)
private fun Disposable.onTermination(action: () -> Unit) = Disposer.register(this, Disposable { action() })
private fun Component.toScrollPane(): JScrollPane {
return ScrollPaneFactory.createScrollPane(this)
}
private fun <T> T.withSpeedSearch(
shouldMatchFromTheBeginning: Boolean = false,
shouldMatchCamelCase: Boolean = true,
converter: ((Any?) -> String?)? = null
): T where T : JList<*> {
val search = if (converter != null) ListSpeedSearch(this, converter) else ListSpeedSearch(this)
search.comparator = SpeedSearchComparator(shouldMatchFromTheBeginning, shouldMatchCamelCase)
return this
}
}
private fun XDebuggerFramesList.withSpeedSearch(
shouldMatchFromTheBeginning: Boolean = false,
shouldMatchCamelCase: Boolean = true
): XDebuggerFramesList {
val coloredStringBuilder = TextTransferable.ColoredStringBuilder()
fun getPresentation(element: Any?): String? {
element ?: return null
return myFramesPresentationCache.getOrPut(element) {
when (element) {
is XStackFrame -> {
element.customizePresentation(coloredStringBuilder)
val value = coloredStringBuilder.builder.toString()
coloredStringBuilder.builder.clear()
value
}
else -> toString()
}
}
}
return withSpeedSearch(shouldMatchFromTheBeginning, shouldMatchCamelCase, ::getPresentation)
}
fun setThreadsVisible(visible: Boolean) {
if (mySplitter.firstComponent.isVisible == visible) return
mySplitter.firstComponent.isVisible = visible
mySplitter.revalidate()
mySplitter.repaint()
}
init {
val disposable = myPauseDisposables.next()
myFramesManager = FramesManager(myFramesList, disposable)
myThreadsContainer = ThreadsContainer(myThreadsList, null, disposable)
myPauseDisposables.terminateCurrent()
mySplitter = NonProportionalOnePixelSplitter(false, splitterProportionKey, splitterProportionDefaultValue, this, project).apply {
firstComponent = myThreadsList.withSpeedSearch().toScrollPane().apply {
minimumSize = Dimension(JBUI.scale(26), 0)
}
secondComponent = myFramesList.withSpeedSearch().toScrollPane()
}
mainPanel.add(mySplitter, BorderLayout.CENTER)
myThreadsList.addListSelectionListener { e ->
if (e.valueIsAdjusting || !myListenersEnabled) return@addListSelectionListener
val stack = myThreadsList.selectedValue?.stack ?: return@addListSelectionListener
val session = getSession(e) ?: return@addListSelectionListener
stack.setActive(session)
}
myThreadsList.addMouseListener(object : PopupHandler() {
override fun invokePopup(comp: Component, x: Int, y: Int) {
val actionManager = ActionManager.getInstance()
val group = actionManager.getAction(XDebuggerActions.THREADS_TREE_POPUP_GROUP) as? ActionGroup ?: return
actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, group).component.show(comp, x, y)
}
})
myThreadsList.addMouseListener(object : MouseAdapter() {
// not mousePressed here, otherwise click in unfocused frames list transfers focus to the new opened editor
override fun mouseReleased(e: MouseEvent) {
if (!myListenersEnabled) return
val i = myThreadsList.locationToIndex(e.point)
if (i == -1 || !myThreadsList.isSelectedIndex(i)) return
val session = getSession(e) ?: return
val stack = myThreadsList.selectedValue?.stack ?: return
stack.setActive(session)
}
})
myFramesList.addListSelectionListener {
if (it.valueIsAdjusting || !myListenersEnabled) return@addListSelectionListener
val session = getSession(it) ?: return@addListSelectionListener
val stack = myThreadsList.selectedValue?.stack ?: return@addListSelectionListener
val frame = myFramesList.selectedValue as? XStackFrame ?: return@addListSelectionListener
session.setCurrentStackFrame(stack, frame)
}
myFramesList.addMouseListener(object : PopupHandler() {
override fun invokePopup(comp: Component, x: Int, y: Int) {
val actionManager = ActionManager.getInstance()
val group = actionManager.getAction(XDebuggerActions.FRAMES_TREE_POPUP_GROUP) as ActionGroup
actionManager.createActionPopupMenu(ActionPlaces.UNKNOWN, group).component.show(comp, x, y)
}
})
myFramesList.addMouseListener(object : MouseAdapter() {
// not mousePressed here, otherwise click in unfocused frames list transfers focus to the new opened editor
override fun mouseReleased(e: MouseEvent) {
if (!myListenersEnabled) return
val i = myFramesList.locationToIndex(e.point)
if (i == -1 || !myFramesList.isSelectedIndex(i)) return
val session = getSession(e) ?: return
val stack = myThreadsList.selectedValue?.stack ?: return
val frame = myFramesList.selectedValue as? XStackFrame ?: return
session.setCurrentStackFrame(stack, frame)
}
})
}
fun saveUiState() {
if (mySplitter.width < mySplitter.minimumSize.width) return
mySplitter.saveProportion()
}
override fun processSessionEvent(event: SessionEvent, session: XDebugSession) {
if (event == SessionEvent.BEFORE_RESUME) {
return
}
val suspendContext = session.suspendContext
if (suspendContext == null) {
UIUtil.invokeLaterIfNeeded { myAlreadyPaused = false }
requestClear()
return
}
UIUtil.invokeLaterIfNeeded {
if (!myAlreadyPaused && event == SessionEvent.PAUSED) {
myAlreadyPaused = true
// clear immediately
cancelClear()
clear()
start(session)
return@invokeLaterIfNeeded
}
if (event == SessionEvent.FRAME_CHANGED) {
val currentExecutionStack = (session as XDebugSessionImpl).currentExecutionStack
val currentStackFrame = session.getCurrentStackFrame()
var selectedStack = threads.selectedValue?.stack
if (selectedStack != currentExecutionStack) {
val newSelectedItemIndex = threads.model.items.indexOfFirst { it.stack == currentExecutionStack }
if (newSelectedItemIndex != -1) {
threads.selectedIndex = newSelectedItemIndex;
myFramesManager.refresh();
selectedStack = threads.selectedValue?.stack;
}
}
if (selectedStack != currentExecutionStack)
return@invokeLaterIfNeeded;
val selectedFrame = frames.selectedValue
if (selectedFrame != currentStackFrame) {
frames.setSelectedValue(currentStackFrame, true);
}
}
if (event == SessionEvent.SETTINGS_CHANGED) {
myFramesManager.refresh()
}
}
}
fun start(session: XDebugSession) {
val suspendContext = session.suspendContext ?: return
val disposable = nextDisposable()
myFramesManager = FramesManager(myFramesList, disposable)
val activeStack = suspendContext.activeExecutionStack
activeStack?.setActive(session)
myThreadsContainer = ThreadsContainer(myThreadsList, activeStack, disposable)
myThreadsContainer.start(suspendContext)
}
private fun XExecutionStack.setActive(session: XDebugSession) {
myFramesManager.setActive(this)
val currentFrame = myFramesManager.tryGetCurrentFrame(this) ?: return
session.setCurrentStackFrame(this, currentFrame)
}
private fun nextDisposable(): Disposable {
val disposable = myPauseDisposables.next()
disposable.onTermination {
myListenersEnabled = false
}
myListenersEnabled = true
return disposable
}
override fun clear() {
myPauseDisposables.terminateCurrent()
myThreadsList.clear()
myFramesList.clear()
myFramesPresentationCache.clear()
}
override fun dispose() = Unit
private class FramesContainer(
private val myDisposable: Disposable,
private val myFramesList: XDebuggerFramesList,
private val myExecutionStack: XExecutionStack
) : XStackFrameContainerEx {
private var isActive = false
private var isProcessed = false
private var isStarted = false
private var mySelectedValue: Any? = null
private var myVisibleRectangle: Rectangle? = null
private val myItems = mutableListOf<Any?>()
val currentFrame: XStackFrame?
get() = myFramesList.selectedValue as? XStackFrame
fun startIfNeeded() {
UIUtil.invokeLaterIfNeeded {
if (isStarted)
return@invokeLaterIfNeeded
isStarted = true
myItems.add(null) // loading
myExecutionStack.computeStackFrames(0, this)
}
}
fun setActive(activeDisposable: Disposable) {
startIfNeeded()
isActive = true
activeDisposable.onTermination {
isActive = false
myVisibleRectangle = myFramesList.visibleRect
mySelectedValue = if (myFramesList.isSelectionEmpty) null else myFramesList.selectedValue
}
updateView()
}
private fun updateView() {
if (!isActive) return
myFramesList.model.replaceAll(myItems)
if (mySelectedValue != null) {
myFramesList.setSelectedValue(mySelectedValue, true)
}
else if (myFramesList.model.items.isNotEmpty()) {
myFramesList.selectedIndex = 0
mySelectedValue = myFramesList.selectedValue
}
val visibleRectangle = myVisibleRectangle
if (visibleRectangle != null)
myFramesList.scrollRectToVisible(visibleRectangle)
myFramesList.repaint()
}
override fun errorOccurred(errorMessage: String) {
addStackFramesInternal(mutableListOf(errorMessage), null, true)
}
override fun addStackFrames(stackFrames: MutableList<out XStackFrame>, toSelect: XStackFrame?, last: Boolean) {
addStackFramesInternal(stackFrames, toSelect, last)
}
override fun addStackFrames(stackFrames: MutableList<out XStackFrame>, last: Boolean) {
addStackFrames(stackFrames, null, last)
}
private fun addStackFramesInternal(stackFrames: MutableList<*>, toSelect: XStackFrame?, last: Boolean) {
invokeIfNeeded {
val insertIndex = myItems.size - 1
if (stackFrames.isNotEmpty()) {
myItems.addAll(insertIndex, stackFrames)
}
if (last) {
// remove loading
myItems.removeAt(myItems.size - 1)
isProcessed = true
}
if (toSelect != null && myItems.contains(toSelect)) {
mySelectedValue = toSelect
}
updateView()
}
}
private fun invokeIfNeeded(action: () -> Unit) {
UIUtil.invokeLaterIfNeeded {
if (isProcessed || myDisposable.isNotAlive)
return@invokeLaterIfNeeded
action()
}
}
}
private class FramesManager(private val myFramesList: XDebuggerFramesList, private val disposable: Disposable) {
private val myMap = mutableMapOf<StackInfo, FramesContainer>()
private val myActiveStackDisposables = SequentialDisposables(disposable)
private var myActiveStack: XExecutionStack? = null
private fun XExecutionStack.getContainer(): FramesContainer {
return myMap.getOrPut(StackInfo.from(this)) {
FramesContainer(disposable, myFramesList, this)
}
}
fun setActive(stack: XExecutionStack) {
val disposable = myActiveStackDisposables.next()
myActiveStack = stack
stack.getContainer().setActive(disposable)
}
fun tryGetCurrentFrame(stack: XExecutionStack): XStackFrame? {
return stack.getContainer().currentFrame
}
fun refresh() {
myMap.clear()
setActive(myActiveStack ?: return)
}
}
private class ThreadsContainer(
private val myThreadsList: XDebuggerThreadsList,
private val myActiveStack: XExecutionStack?,
private val myDisposable: Disposable
) : XSuspendContext.XExecutionStackContainer {
private var isProcessed = false
private var isStarted = false
companion object {
private val loading = listOf(StackInfo.loading)
}
fun start(suspendContext: XSuspendContext) {
UIUtil.invokeLaterIfNeeded {
if (isStarted) return@invokeLaterIfNeeded
if (myActiveStack != null) {
myThreadsList.model.replaceAll(listOf(StackInfo.from(myActiveStack), StackInfo.loading))
} else {
myThreadsList.model.replaceAll(loading)
}
myThreadsList.selectedIndex = 0
suspendContext.computeExecutionStacks(this)
isStarted = true
}
}
override fun errorOccurred(errorMessage: String) {
invokeIfNeeded {
val model = myThreadsList.model
// remove loading
model.remove(model.size - 1)
model.add(listOf(StackInfo.error(errorMessage)))
isProcessed = true
}
}
override fun addExecutionStack(executionStacks: MutableList<out XExecutionStack>, last: Boolean) {
invokeIfNeeded {
val model = myThreadsList.model
val insertIndex = model.size - 1
val threads = getThreadsList(executionStacks)
if (threads.any()) {
model.addAll(insertIndex, threads)
}
if (last) {
// remove loading
model.remove(model.size - 1)
isProcessed = true
}
myThreadsList.repaint()
}
}
fun addExecutionStack(executionStack: XExecutionStack, last: Boolean) {
addExecutionStack(mutableListOf(executionStack), last)
}
private fun getThreadsList(executionStacks: MutableList<out XExecutionStack>): List<StackInfo> {
var sequence = executionStacks.asSequence()
if (myActiveStack != null) {
sequence = sequence.filter { it != myActiveStack }
}
return sequence.map { StackInfo.from(it) }.toList()
}
private fun invokeIfNeeded(action: () -> Unit) {
UIUtil.invokeLaterIfNeeded {
if (isProcessed || myDisposable.isNotAlive) {
return@invokeLaterIfNeeded
}
action()
}
}
}
private class SequentialDisposables(parent: Disposable? = null) : Disposable {
private var myCurrentDisposable: Disposable? = null
init {
parent?.onTermination(this)
}
fun next(): Disposable {
val newDisposable = Disposer.newDisposable()
Disposer.register(this, newDisposable)
myCurrentDisposable?.disposeIfNeeded()
myCurrentDisposable = newDisposable
return newDisposable
}
fun terminateCurrent() {
myCurrentDisposable?.disposeIfNeeded()
myCurrentDisposable = null
}
private fun Disposable.disposeIfNeeded() {
if (this.isAlive)
Disposer.dispose(this)
}
override fun dispose() = terminateCurrent()
}
}
| apache-2.0 | 24b8180529549d26c011cb31fa0c0c9c | 31.693032 | 140 | 0.704781 | 4.977064 | false | false | false | false |
lapis-mc/minecraft-versioning | src/main/kotlin/com/lapismc/minecraft/versioning/Version.kt | 1 | 2868 | package com.lapismc.minecraft.versioning
/**
* Complete information about a version of the game and its dependencies.
* @param stub Basic information about the version.
* @param assetIndex Summary of assets needed for the game and where to find them.
* @param downloads Logical downloads for items such as the client and server.
* @param libraries Packages the game depends on to run.
* @param launcher Information needed for the launcher to start the game.
*/
class Version(stub: VersionStub, val assetIndex: AssetIndex, val downloads: List<Resource>,
val libraries: List<Library>, val launcher: LauncherInfo) {
/**
* Unique name of the version.
*/
val id = stub.id
/**
* Type of version (release, snapshot, etc.).
*/
val type = stub.type
/**
* Last date and time the version was updated.
* May be newer than the release time.
*/
val updateTime = stub.updateTime
/**
* Date and time the version was first released.
*/
val releaseTime = stub.releaseTime
/**
* Location of where to get additional information for the version.
*/
val url = stub.url
/**
* Retrieves a list of libraries needed to run the game on the current system.
* @return List of required libraries.
*/
fun getApplicableLibraries() = libraries.filter { it.isApplicable() }
/**
* Creates a string representation of the version.
* @return Version and type as a string.
*/
override fun toString(): String {
return "Version($id $type)"
}
/**
* Constructs information for a single version of the game.
* @param assetIndex Summary of assets needed for the game and where to find them.
* @param launcher Information needed for the launcher to start the game.
*/
class Builder(private val stub: VersionStub, private val assetIndex: AssetIndex,
private val launcher: LauncherInfo) {
private val downloads = ArrayList<Resource>()
private val libraries = ArrayList<Library>()
/**
* Adds a download for the version.
* @param download Download to add.
* @return Builder for chaining methods.
*/
fun addDownload(download: Resource): Builder {
downloads.add(download)
return this
}
/**
* Adds a library that the version depends on.
* @return Builder for chaining methods.
*/
fun addLibrary(library: Library): Builder {
libraries.add(library)
return this
}
/**
* Constructs the version.
* @return Constructed version information.
*/
fun build(): Version {
return Version(stub, assetIndex, downloads.toList(), libraries.toList(), launcher)
}
}
} | mit | 29ae574f2ef6fab6fb6a65e5963afc33 | 30.877778 | 94 | 0.624826 | 4.812081 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/refactoring/rename/inplace/TemplateInlayUtil.kt | 2 | 15798 | // 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.refactoring.rename.inplace
import com.intellij.codeInsight.hints.InlayPresentationFactory
import com.intellij.codeInsight.hints.presentation.*
import com.intellij.codeInsight.template.impl.TemplateState
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.FusInputEvent
import com.intellij.lang.LangBundle
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.actionSystem.ex.ActionUtil
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.ColorKey
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.keymap.KeymapUtil
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.DialogPanel
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.Disposer
import com.intellij.psi.PsiNamedElement
import com.intellij.refactoring.RefactoringBundle
import com.intellij.refactoring.rename.RenameInplacePopupUsagesCollector
import com.intellij.refactoring.rename.RenamePsiElementProcessor
import com.intellij.refactoring.rename.impl.TextOptions
import com.intellij.refactoring.rename.impl.isEmpty
import com.intellij.refactoring.util.TextOccurrencesUtil
import com.intellij.ui.layout.*
import com.intellij.ui.popup.PopupFactoryImpl
import com.intellij.util.ui.JBEmptyBorder
import com.intellij.util.ui.JBInsets
import org.jetbrains.annotations.ApiStatus
import java.awt.*
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import javax.swing.JLabel
import javax.swing.LayoutFocusTraversalPolicy
@ApiStatus.Experimental
object TemplateInlayUtil {
@JvmStatic
fun createNavigatableButton(templateState: TemplateState,
inEditorOffset: Int,
presentation: SelectableInlayPresentation,
templateElement: VirtualTemplateElement): Inlay<PresentationRenderer>? {
val renderer = PresentationRenderer(presentation)
val inlay = templateState.editor.inlayModel.addInlineElement(inEditorOffset, true, renderer) ?: return null
VirtualTemplateElement.installOnTemplate(templateState, templateElement)
presentation.addListener(object : PresentationListener {
override fun contentChanged(area: Rectangle) {
inlay.repaint()
}
override fun sizeChanged(previous: Dimension, current: Dimension) {
inlay.repaint()
}
})
Disposer.register(templateState, inlay)
return inlay
}
open class SelectableTemplateElement(val presentation: SelectableInlayPresentation) : VirtualTemplateElement {
override fun onSelect(templateState: TemplateState) {
presentation.isSelected = true
templateState.focusCurrentHighlighter(false)
}
}
@JvmStatic
fun createNavigatableButtonWithPopup(templateState: TemplateState,
inEditorOffset: Int,
presentation: SelectableInlayPresentation,
panel: DialogPanel,
templateElement: SelectableTemplateElement = SelectableTemplateElement(presentation),
logStatisticsOnHide: () -> Unit = {}): Inlay<PresentationRenderer>? {
val editor = templateState.editor
val inlay = createNavigatableButton(templateState, inEditorOffset, presentation, templateElement) ?: return null
fun showPopup() {
try {
editor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, inlay.visualPosition)
panel.border = JBEmptyBorder(JBInsets.create(Insets(8, 12, 4, 12)))
val popup = JBPopupFactory.getInstance()
.createComponentPopupBuilder(panel, panel.preferredFocusedComponent)
.setRequestFocus(true)
.addListener(object : JBPopupListener {
override fun onClosed(event: LightweightWindowEvent) {
presentation.isSelected = false
templateState.focusCurrentHighlighter(true)
logStatisticsOnHide.invoke()
}
})
.createPopup()
DumbAwareAction.create {
popup.cancel()
templateState.nextTab()
logStatisticsOnHide.invoke()
}.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts(IdeActions.ACTION_EDITOR_ENTER), panel)
popup.showInBestPositionFor(editor)
}
finally {
editor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, null)
}
}
presentation.addSelectionListener(object : SelectableInlayPresentation.SelectionListener {
override fun selectionChanged(isSelected: Boolean) {
if (isSelected) showPopup()
}
})
return inlay
}
@JvmStatic
fun createSettingsPresentation(editor: EditorImpl, onClick: (MouseEvent) -> Unit = {}): SelectableInlayPresentation {
val factory = PresentationFactory(editor)
fun button(background: Color?): InlayPresentation {
val button = factory.container(
presentation = factory.icon(AllIcons.Actions.InlayGear),
padding = InlayPresentationFactory.Padding(4, 4, 4, 4),
roundedCorners = InlayPresentationFactory.RoundedCorners(6, 6),
background = background
)
return factory.container(button, padding = InlayPresentationFactory.Padding(3, 6, 0, 0))
}
val colorsScheme = editor.colorsScheme
var hovered = button(colorsScheme.getColor(INLINE_REFACTORING_SETTINGS_HOVERED))
val shortcut = KeymapUtil.getPrimaryShortcut("SelectVirtualTemplateElement")
if (shortcut != null) {
val tooltip = RefactoringBundle.message("refactoring.extract.method.inplace.options.tooltip", KeymapUtil.getShortcutText(shortcut))
hovered = factory.withTooltip(tooltip, hovered)
}
return object : SelectableInlayButton(editor,
default = button(colorsScheme.getColor(INLINE_REFACTORING_SETTINGS_DEFAULT)),
active = button(colorsScheme.getColor(INLINE_REFACTORING_SETTINGS_FOCUSED)),
hovered) {
override fun mouseClicked(event: MouseEvent, translated: Point) {
super.mouseClicked(event, translated)
onClick(event)
}
}
}
@JvmStatic
fun createRenameSettingsInlay(templateState: TemplateState,
offset: Int,
elementToRename: PsiNamedElement,
restart: Runnable): Inlay<PresentationRenderer>? {
val processor = RenamePsiElementProcessor.forElement(elementToRename)
val initOptions = TextOptions(
commentStringOccurrences = processor.isToSearchInComments(elementToRename),
textOccurrences = if (TextOccurrencesUtil.isSearchTextOccurrencesEnabled(elementToRename)) {
processor.isToSearchForTextOccurrences(elementToRename)
}
else {
null
}
)
return createRenameSettingsInlay(templateState, offset, initOptions) { (commentStringOccurrences, textOccurrences) ->
if (commentStringOccurrences != null) {
processor.setToSearchInComments(elementToRename, commentStringOccurrences)
}
if (textOccurrences != null) {
processor.setToSearchForTextOccurrences(elementToRename, textOccurrences)
}
restart.run()
}
}
internal fun createRenameSettingsInlay(
templateState: TemplateState,
offset: Int,
initOptions: TextOptions,
optionsListener: (TextOptions) -> Unit,
): Inlay<PresentationRenderer>? {
if (initOptions.isEmpty) {
return null
}
val editor = templateState.editor as EditorImpl
val factory = PresentationFactory(editor)
val colorsScheme = editor.colorsScheme
fun button(presentation: InlayPresentation, second: Boolean) = factory.container(
presentation = presentation,
padding = InlayPresentationFactory.Padding(if (second) 0 else 4, 4, 4, 4)
)
var tooltip = LangBundle.message("inlay.rename.tooltip.header")
val commentStringPresentation = initOptions.commentStringOccurrences?.let { commentStringOccurrences ->
tooltip += LangBundle.message("inlay.rename.tooltip.comments.strings")
BiStatePresentation(
first = { factory.icon(AllIcons.Actions.InlayRenameInCommentsActive) },
second = { factory.icon(AllIcons.Actions.InlayRenameInComments) },
initiallyFirstEnabled = commentStringOccurrences,
)
}
val textPresentation = initOptions.textOccurrences?.let { textOccurrences ->
tooltip += LangBundle.message("inlay.rename.tooltip.non.code")
BiStatePresentation(
first = { factory.icon(AllIcons.Actions.InlayRenameInNoCodeFilesActive) },
second = { factory.icon(AllIcons.Actions.InlayRenameInNoCodeFiles) },
initiallyFirstEnabled = textOccurrences,
)
}
val buttonsPresentation = if (commentStringPresentation != null && textPresentation != null) {
factory.seq(
button(commentStringPresentation, false),
button(textPresentation, true)
)
}
else {
val presentation = commentStringPresentation
?: textPresentation
?: error("at least one option should be not null")
button(presentation, false)
}
val shortcut = KeymapUtil.getPrimaryShortcut("SelectVirtualTemplateElement")
if (shortcut != null) {
tooltip += LangBundle.message("inlay.rename.tooltip.tab.advertisement", KeymapUtil.getShortcutText(shortcut))
}
fun withBackground(bgKey: ColorKey) = factory.container(
presentation = buttonsPresentation,
roundedCorners = InlayPresentationFactory.RoundedCorners(3, 3),
background = colorsScheme.getColor(bgKey),
padding = InlayPresentationFactory.Padding(4, 0, 0, 0),
)
val presentation = object : SelectableInlayButton(editor,
withBackground(INLINE_REFACTORING_SETTINGS_DEFAULT),
withBackground(INLINE_REFACTORING_SETTINGS_FOCUSED),
factory.withTooltip(tooltip, withBackground(INLINE_REFACTORING_SETTINGS_HOVERED))) {
override fun mouseClicked(event: MouseEvent, translated: Point) {
super.mouseClicked(event, translated)
logStatisticsOnShow(editor, event)
}
}
val templateElement = object : SelectableTemplateElement(presentation) {
override fun onSelect(templateState: TemplateState) {
super.onSelect(templateState)
logStatisticsOnShow(editor)
}
}
var currentOptions: TextOptions = initOptions
val panel = renamePanel(editor, initOptions) { newOptions ->
currentOptions = newOptions
newOptions.commentStringOccurrences?.let {
commentStringPresentation?.state = BiStatePresentation.State(it)
}
newOptions.textOccurrences?.let {
textPresentation?.state = BiStatePresentation.State(it)
}
optionsListener.invoke(newOptions)
}
return createNavigatableButtonWithPopup(templateState, offset, presentation, panel, templateElement) {
logStatisticsOnHide(editor, initOptions, currentOptions)
}
}
private fun logStatisticsOnShow(editor: Editor, mouseEvent: MouseEvent? = null) {
val showEvent = mouseEvent
?: KeyEvent(editor.component, KeyEvent.KEY_PRESSED, System.currentTimeMillis(), 0, KeyEvent.VK_TAB, KeyEvent.VK_TAB.toChar())
RenameInplacePopupUsagesCollector.show.log(editor.project,
EventFields.InputEvent.with(FusInputEvent(showEvent, javaClass.simpleName)))
}
private fun logStatisticsOnHide(editor: EditorImpl, initOptions: TextOptions, newOptions: TextOptions) {
RenameInplacePopupUsagesCollector.hide.log(
editor.project,
RenameInplacePopupUsagesCollector.searchInCommentsOnHide.with(newOptions.commentStringOccurrences ?: false),
RenameInplacePopupUsagesCollector.searchInTextOccurrencesOnHide.with(newOptions.textOccurrences ?: false)
)
RenameInplacePopupUsagesCollector.settingsChanged.log(
editor.project,
RenameInplacePopupUsagesCollector.changedOnHide.with(initOptions != newOptions)
)
}
private fun renamePanel(
editor: Editor,
initOptions: TextOptions,
optionsListener: (TextOptions) -> Unit,
): DialogPanel {
val renameAction = ActionManager.getInstance().getAction(IdeActions.ACTION_RENAME)
var (commentsStringsOccurrences, textOccurrences) = initOptions // model
val panel = panel {
row(LangBundle.message("inlay.rename.also.rename.options.title")) {
commentsStringsOccurrences?.let {
row {
cell {
checkBox(
text = RefactoringBundle.message("comments.and.strings"),
isSelected = it,
actionListener = { _, cb ->
commentsStringsOccurrences = cb.isSelected
optionsListener(TextOptions(commentStringOccurrences = commentsStringsOccurrences, textOccurrences = textOccurrences))
}
).focused()
component(JLabel(AllIcons.Actions.InlayRenameInComments))
}
}
}
textOccurrences?.let {
row {
cell {
val cb = checkBox(
text = RefactoringBundle.message("text.occurrences"),
isSelected = it,
actionListener = { _, cb ->
textOccurrences = cb.isSelected
optionsListener(TextOptions(commentStringOccurrences = commentsStringsOccurrences, textOccurrences = textOccurrences))
}
)
if (commentsStringsOccurrences == null) {
cb.focused()
}
component(JLabel(AllIcons.Actions.InlayRenameInNoCodeFiles))
}
}
}
}
row {
cell {
link(LangBundle.message("inlay.rename.link.label.more.options"), null) {
doRename(editor, renameAction, null)
}.component.isFocusable = true
comment(KeymapUtil.getFirstKeyboardShortcutText(renameAction))
}
}
}
DumbAwareAction.create {
doRename(editor, renameAction, it)
}.registerCustomShortcutSet(KeymapUtil.getActiveKeymapShortcuts(IdeActions.ACTION_RENAME), panel)
panel.isFocusCycleRoot = true
panel.focusTraversalPolicy = LayoutFocusTraversalPolicy()
return panel
}
private fun doRename(editor: Editor, renameAction: AnAction, anActionEvent: AnActionEvent?) {
RenameInplacePopupUsagesCollector.openRenameDialog.log(editor.project, RenameInplacePopupUsagesCollector.linkUsed.with(anActionEvent == null))
val event = AnActionEvent(null,
DataManager.getInstance().getDataContext(editor.component),
anActionEvent?.place ?: ActionPlaces.UNKNOWN, renameAction.templatePresentation.clone(),
ActionManager.getInstance(), 0)
if (ActionUtil.lastUpdateAndCheckDumb(renameAction, event, true)) {
ActionUtil.performActionDumbAware(renameAction, event)
}
}
}
| apache-2.0 | 36b213246a8a84a7b7e2f13ec06d1c8d | 43.128492 | 146 | 0.690087 | 5.594193 | false | true | false | false |
Szewek/FL | src/main/java/szewek/fl/network/FLNetUtilClient.kt | 1 | 1157 | package szewek.fl.network
import net.minecraft.client.Minecraft
import net.minecraft.client.network.NetHandlerPlayClient
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.network.INetHandler
import net.minecraft.network.NetHandlerPlayServer
import net.minecraft.util.IThreadListener
import net.minecraft.util.Tuple
import net.minecraftforge.fml.common.network.internal.FMLProxyPacket
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
@SideOnly(Side.CLIENT)
class FLNetUtilClient private constructor() : FLNetUtil {
override fun preprocess(p: FMLProxyPacket, s: Side): Tuple<IThreadListener, EntityPlayer>? {
if (s == Side.CLIENT) {
val mc = Minecraft.getMinecraft()
return Tuple(mc, mc.player)
}
return FLNetUtilServer.THIS.preprocess(p, s)
}
override fun decode(msg: FLNetMsg, p: EntityPlayer, s: Side) = if (s == Side.CLIENT)
msg.climsg(p)
else
msg.srvmsg(p)
override fun check(h: INetHandler) = when (h) {
is NetHandlerPlayClient -> Side.CLIENT
is NetHandlerPlayServer -> Side.SERVER
else -> null
}
companion object {
val THIS = FLNetUtilClient()
}
}
| mit | 6ad299f3377f927cab5c97af053fa146 | 28.666667 | 93 | 0.776145 | 3.363372 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/common/test/channels/BasicOperationsTest.kt | 1 | 5502 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.channels
import kotlinx.coroutines.*
import kotlin.test.*
class BasicOperationsTest : TestBase() {
@Test
fun testSimpleSendReceive() = runTest {
// Parametrized common test :(
TestChannelKind.values().forEach { kind -> testSendReceive(kind, 20) }
}
@Test
fun testTrySendToFullChannel() = runTest {
TestChannelKind.values().forEach { kind -> testTrySendToFullChannel(kind) }
}
@Test
fun testTrySendAfterClose() = runTest {
TestChannelKind.values().forEach { kind -> testTrySend(kind) }
}
@Test
fun testSendAfterClose() = runTest {
TestChannelKind.values().forEach { kind -> testSendAfterClose(kind) }
}
@Test
fun testReceiveCatching() = runTest {
TestChannelKind.values().forEach { kind -> testReceiveCatching(kind) }
}
@Test
fun testInvokeOnClose() = TestChannelKind.values().forEach { kind ->
reset()
val channel = kind.create<Int>()
channel.invokeOnClose {
if (it is AssertionError) {
expect(3)
}
}
expect(1)
channel.trySend(42)
expect(2)
channel.close(AssertionError())
finish(4)
}
@Test
fun testInvokeOnClosed() = TestChannelKind.values().forEach { kind ->
reset()
expect(1)
val channel = kind.create<Int>()
channel.close()
channel.invokeOnClose { expect(2) }
assertFailsWith<IllegalStateException> { channel.invokeOnClose { expect(3) } }
finish(3)
}
@Test
fun testMultipleInvokeOnClose() = TestChannelKind.values().forEach { kind ->
reset()
val channel = kind.create<Int>()
channel.invokeOnClose { expect(3) }
expect(1)
assertFailsWith<IllegalStateException> { channel.invokeOnClose { expect(4) } }
expect(2)
channel.close()
finish(4)
}
@Test
fun testIterator() = runTest {
TestChannelKind.values().forEach { kind ->
val channel = kind.create<Int>()
val iterator = channel.iterator()
assertFailsWith<IllegalStateException> { iterator.next() }
channel.close()
assertFailsWith<IllegalStateException> { iterator.next() }
assertFalse(iterator.hasNext())
}
}
@Suppress("ReplaceAssertBooleanWithAssertEquality")
private suspend fun testReceiveCatching(kind: TestChannelKind) = coroutineScope {
reset()
val channel = kind.create<Int>()
launch {
expect(2)
channel.send(1)
}
expect(1)
val result = channel.receiveCatching()
assertEquals(1, result.getOrThrow())
assertEquals(1, result.getOrNull())
assertTrue(ChannelResult.success(1) == result)
expect(3)
launch {
expect(4)
channel.close()
}
val closed = channel.receiveCatching()
expect(5)
assertNull(closed.getOrNull())
assertTrue(closed.isClosed)
assertNull(closed.exceptionOrNull())
assertTrue(ChannelResult.closed<Int>(closed.exceptionOrNull()) == closed)
finish(6)
}
private suspend fun testTrySend(kind: TestChannelKind) = coroutineScope {
val channel = kind.create<Int>()
val d = async { channel.send(42) }
yield()
channel.close()
assertTrue(channel.isClosedForSend)
channel.trySend(2)
.onSuccess { expectUnreached() }
.onClosed {
assertTrue { it is ClosedSendChannelException}
if (!kind.isConflated) {
assertEquals(42, channel.receive())
}
}
d.await()
}
private suspend fun testTrySendToFullChannel(kind: TestChannelKind) = coroutineScope {
if (kind.isConflated || kind.capacity == Int.MAX_VALUE) return@coroutineScope
val channel = kind.create<Int>()
// Make it full
repeat(11) {
channel.trySend(42)
}
channel.trySend(1)
.onSuccess { expectUnreached() }
.onFailure { assertNull(it) }
.onClosed {
expectUnreached()
}
}
/**
* [ClosedSendChannelException] should not be eaten.
* See [https://github.com/Kotlin/kotlinx.coroutines/issues/957]
*/
private suspend fun testSendAfterClose(kind: TestChannelKind) {
assertFailsWith<ClosedSendChannelException> {
coroutineScope {
val channel = kind.create<Int>()
channel.close()
launch {
channel.send(1)
}
}
}
}
private suspend fun testSendReceive(kind: TestChannelKind, iterations: Int) = coroutineScope {
val channel = kind.create<Int>()
launch {
repeat(iterations) { channel.send(it) }
channel.close()
}
var expected = 0
for (x in channel) {
if (!kind.isConflated) {
assertEquals(expected++, x)
} else {
assertTrue(x >= expected)
expected = x + 1
}
}
if (!kind.isConflated) {
assertEquals(iterations, expected)
}
}
}
| apache-2.0 | 03e3b1ba8a349f07081e22c09eb4034d | 28.580645 | 102 | 0.567612 | 4.674596 | false | true | false | false |
Polidea/Polithings | numpad/src/main/java/com/polidea/androidthings/driver/numpad/domain/Column.kt | 1 | 817 | package com.polidea.androidthings.driver.numpad.domain
import com.google.android.things.pio.Gpio
import com.polidea.androidthings.driver.numpad.hardware.GpioFactory
internal open class Column(gpioId: String,
open val id: Id,
gpioFactory: GpioFactory) : AutoCloseable {
val gpio: Gpio = gpioFactory.openGpio(gpioId).apply {
setDirection(Gpio.DIRECTION_OUT_INITIALLY_LOW)
value = true
}
open var state: Boolean = false
set(value) { gpio.value = !value}
override fun close() {
gpio.close()
}
enum class Id { C1, C2, C3 }
}
internal open class ColumnFactory(val gpioFactory: GpioFactory = GpioFactory()) {
open fun create(gpioId: String, id: Column.Id)
= Column(gpioId, id, gpioFactory)
}
| mit | a1d50ff08f9691b110bf026263237b03 | 25.354839 | 81 | 0.646267 | 3.730594 | false | false | false | false |
LivingDoc/livingdoc | livingdoc-results/src/main/kotlin/org/livingdoc/results/examples/scenarios/ScenarioResult.kt | 2 | 5110 | package org.livingdoc.results.examples.scenarios
import org.livingdoc.repositories.model.scenario.Scenario
import org.livingdoc.results.Status
import org.livingdoc.results.TestDataResult
data class ScenarioResult private constructor(
val steps: List<StepResult>,
override val status: Status,
val fixtureSource: Class<*>?,
val scenario: Scenario
) : TestDataResult<Scenario> {
/**
* A not threadsafe builder class for [ScenarioResult] objects
*/
class Builder {
private lateinit var status: Status
private var steps = mutableListOf<StepResult>()
private var fixtureSource: Class<*>? = null
private var scenario: Scenario? = null
private var finalized = false
private fun checkFinalized() {
if (this.finalized)
throw IllegalStateException(
"This ScenarioResult.Builder has already been finalized and can't be altered anymore."
)
}
/**
* Sets or overrides the status for the built [ScenarioResult]
*
* @param status Can be any [Status] except [Status.Unknown]
*/
fun withStatus(status: Status): Builder {
checkFinalized()
this.status = status
return this
}
/**
* Sets the [StepResult] for a step in the given [Scenario]
*
* @param step A successfully built [StepResult]
*/
fun withStep(step: StepResult): Builder {
checkFinalized()
steps.add(step)
when (step.status) {
is Status.Failed -> {
status = Status.Failed(step.status.reason)
}
is Status.Exception -> {
status = Status.Exception(step.status.exception)
}
}
return this
}
/**
* Sets or overrides the [fixtureSource] that defines the implementation of Fixture.
* This value is optional.
*/
fun withFixtureSource(fixtureSource: Class<*>): Builder {
checkFinalized()
this.fixtureSource = fixtureSource
return this
}
/**
* Sets or overrides the [Scenario] that the built [ScenarioResult] refers to
*/
fun withScenario(scenario: Scenario): Builder {
checkFinalized()
this.scenario = scenario
return this
}
/**
* Marks all steps that have no result yet with [Status.Skipped]
*/
fun withUnassignedSkipped(): Builder {
checkFinalized()
this.scenario!!.steps.forEach {
withStep(
StepResult.Builder()
.withValue(it.value)
.withStatus(Status.Skipped)
.build()
)
}
return this
}
/**
* Build an immutable [ScenarioResult]
*
* WARNING: The builder will be finalized and can not be altered after calling this function
*
* @returns A new [ScenarioResult] with the data from this builder
* @throws IllegalStateException If the builder is missing data to build a [ScenarioResult]
*/
fun build(): ScenarioResult {
// Finalize this builder. No further changes are allowed
this.finalized = true
val scenario =
this.scenario ?: throw IllegalStateException("Cannot build ScenarioResult without a scenario")
// Check status
if (!this::status.isInitialized) {
throw IllegalStateException("Cannot build ScenarioResult with unknown status")
}
val status = this.status
val steps = if (status is Status.Manual || status is Status.Disabled)
scenario.steps.map {
StepResult.Builder()
.withStatus(this.status)
.withValue(it.value)
.build()
}.toMutableList()
else
this.steps
// Do all scenario steps have a valid result?
if (steps.size != scenario.steps.size) {
throw IllegalStateException(
"Cannot build ScenarioResult. The number of step results (${steps.size})" +
" does not match the expected number (${scenario.steps.size})"
)
}
scenario.steps.forEach { step ->
if (steps.none {
it.value == step.value && it.status != Status.Unknown
}) {
throw IllegalStateException("Not all scenario steps are contained in the result")
}
}
// Build result
return ScenarioResult(
steps,
status,
fixtureSource,
scenario
)
}
}
}
| apache-2.0 | 4873e044ca16f1f0bef820b4afebdf1f | 32.84106 | 110 | 0.52681 | 5.584699 | false | false | false | false |
zdary/intellij-community | platform/lang-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/LegacyBridgeProjectLifecycleListener.kt | 1 | 4143 | // 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.workspaceModel.ide.impl.legacyBridge
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.components.ServiceDescriptor
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.impl.ExternalModuleListStorage
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectServiceContainerCustomizer
import com.intellij.openapi.roots.ProjectRootManager
import com.intellij.openapi.roots.impl.ModifiableModelCommitterService
import com.intellij.openapi.roots.impl.libraries.ProjectLibraryTable
import com.intellij.serviceContainer.ComponentManagerImpl
import com.intellij.workspaceModel.ide.WorkspaceModel
import com.intellij.workspaceModel.ide.WorkspaceModelTopics
import com.intellij.workspaceModel.ide.impl.WorkspaceModelImpl
import com.intellij.workspaceModel.ide.impl.WorkspaceModelInitialTestContent
import com.intellij.workspaceModel.ide.impl.jps.serialization.JpsProjectModelSynchronizer
import com.intellij.workspaceModel.ide.impl.legacyBridge.facet.FacetEntityChangeListener
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.ProjectLibraryTableBridgeImpl
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.ModuleManagerComponentBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModifiableModelCommitterServiceBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.project.ProjectRootManagerBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.RootsChangeWatcher
import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.VirtualFileUrlWatcher
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
class LegacyBridgeProjectLifecycleListener : ProjectServiceContainerCustomizer {
companion object {
private val LOG = logger<LegacyBridgeProjectLifecycleListener>()
fun enabled(project: Project) = ModuleManager.getInstance(project) is ModuleManagerComponentBridge
}
override fun serviceRegistered(project: Project) {
val enabled = WorkspaceModel.isEnabled || WorkspaceModelInitialTestContent.peek() != null
if (!enabled) {
LOG.info("Using legacy project model to open project")
return
}
LOG.info("Using workspace model to open project")
val pluginDescriptor = PluginManagerCore.getPlugin(PluginManagerCore.CORE_ID)
?: error("Could not find plugin by id: ${PluginManagerCore.CORE_ID}")
val container = project as ComponentManagerImpl
container.registerComponent(JpsProjectModelSynchronizer::class.java, JpsProjectModelSynchronizer::class.java, pluginDescriptor, false)
container.registerComponent(RootsChangeWatcher::class.java, RootsChangeWatcher::class.java, pluginDescriptor, false)
container.registerComponent(VirtualFileUrlWatcher::class.java, VirtualFileUrlWatcher::class.java, pluginDescriptor, false)
container.registerComponent(ModuleManager::class.java, ModuleManagerComponentBridge::class.java, pluginDescriptor, true)
container.registerService(ProjectRootManager::class.java, ProjectRootManagerBridge::class.java, pluginDescriptor, override = true,
preloadMode = ServiceDescriptor.PreloadMode.AWAIT)
container.unregisterComponent(ExternalModuleListStorage::class.java)
container.registerService(WorkspaceModel::class.java, WorkspaceModelImpl::class.java, pluginDescriptor, false)
container.registerService(ProjectLibraryTable::class.java, ProjectLibraryTableBridgeImpl::class.java, pluginDescriptor, true)
container.registerService(ModifiableModelCommitterService::class.java, ModifiableModelCommitterServiceBridge::class.java, pluginDescriptor, true)
container.registerService(WorkspaceModelTopics::class.java, WorkspaceModelTopics::class.java, pluginDescriptor, false)
container.registerService(FacetEntityChangeListener::class.java, FacetEntityChangeListener::class.java, pluginDescriptor, false)
}
} | apache-2.0 | 1a3e9c5fd518e8e6c65a7ab23bdc16b0 | 61.787879 | 149 | 0.838523 | 5.133829 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-tests/src/test/kotlin/test/entities/Data_03_Builder_Select.kt | 1 | 5998 | /**
* <slate_header>
* url: www.slatekit.com
* git: www.github.com/code-helix/slatekit
* org: www.codehelix.co
* author: Kishore Reddy
* copyright: 2016 CodeHelix Solutions Inc.
* license: refer to website and/or github
* about: A tool-kit, utility library and server-backend
* mantra: Simplicity above all else
* </slate_header>
*/
package test.entities
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import slatekit.common.data.*
import slatekit.common.data.BuildMode
import slatekit.data.sql.Builders
import slatekit.data.sql.vendors.MySqlDialect
import slatekit.entities.*
import slatekit.query.*
import test.setup.User5
class Data_03_Builder_Select {
private lateinit var entities:Entities
private val lookup = mapOf(
"id" to DataType.DTLong,
"email" to DataType.DTString,
"active" to DataType.DTBool,
"level" to DataType.DTInt,
"category" to DataType.DTString
)
private fun builder(): Select = Builders.Select(MySqlDialect,"user", { name -> lookup[name]!! }, { name -> name })
@Before
fun setup(){
entities = EntitySetup.realDb()
entities.register<Long, User5>(EntityLongId() , vendor = Vendor.MySql) { repo -> UserService(repo) }
}
@Test
fun can_build_empty(){
val cmd = builder().build(BuildMode.Sql)
Assert.assertEquals("select * from `user`;", cmd.sql)
Assert.assertEquals(0, cmd.values.size)
}
@Test fun can_build_count() {
val builder = builder().agg(MySqlDialect.aggr.count, Const.All).where("id", Op.Eq, 2L)
ensure(builder = builder,
expectSqlRaw = "select count(*) from `user` where `id` = 2;",
expectSqlPrep = "select count(*) from `user` where `id` = ?;",
expectPairs = listOf(Value("email", DataType.DTLong, 2L))
)
}
@Test fun can_build_filter_1_of_id() {
val builder = builder().where("id", Op.Eq, 2L)
ensure(builder = builder,
expectSqlRaw = "select * from `user` where `id` = 2;",
expectSqlPrep = "select * from `user` where `id` = ?;",
expectPairs = listOf(Value("email", DataType.DTLong, 2L))
)
}
@Test fun can_build_filter_1_of_type_string() {
val builder = builder().where("email", Op.Eq, "[email protected]")
ensure(builder = builder,
expectSqlRaw = "select * from `user` where `email` = '[email protected]';",
expectSqlPrep = "select * from `user` where `email` = ?;",
expectPairs = listOf(Value("email", DataType.DTString, "[email protected]"))
)
}
@Test fun can_build_filter_1_of_type_int() {
val builder = builder().where("level", Op.Gte, 2)
ensure(builder = builder,
expectSqlRaw = "select * from `user` where `level` >= 2;",
expectSqlPrep = "select * from `user` where `level` >= ?;",
expectPairs = listOf(Value("email", DataType.DTInt, 2))
)
}
@Test fun can_build_filter_1_of_type_bool() {
val builder = builder().where("active", Op.IsNot, false)
ensure(builder = builder,
expectSqlRaw = "select * from `user` where `active` is not 0;",
expectSqlPrep = "select * from `user` where `active` is not ?;",
expectPairs = listOf(Value("email", DataType.DTBool, false))
)
}
@Test fun can_build_filter_multiple_conditions() {
val builder = builder()
.where("active", Op.IsNot, false)
.and("category", Op.Eq, "action")
.and("level", Op.Gte, 2)
ensure(builder = builder,
expectSqlRaw = "select * from `user` where ((`active` is not 0 and `category` = 'action') and `level` >= 2);",
expectSqlPrep = "select * from `user` where ((`active` is not ? and `category` = ?) and `level` >= ?);",
expectPairs = listOf(
Value("active" , DataType.DTBool, false),
Value("category", DataType.DTString, "action"),
Value("level" , DataType.DTInt, 2)
)
)
}
@Test fun can_build_filter_1_with_from_order_limit() {
val builder = builder()
.from("users")
.where("level", Op.Eq, 1)
.orderBy("id", Order.Dsc)
.limit(2)
ensure(builder = builder,
expectSqlRaw = "select * from `users` where `level` = 1 order by `id` desc limit 2;",
expectSqlPrep = "select * from `users` where `level` = ? order by `id` desc limit ?;",
expectPairs = listOf(
Value("level", DataType.DTInt, 1),
Value("", DataType.DTInt, 2)
)
)
}
@Test fun can_build_filter_in() {
val builder = builder().where("id", Op.In, listOf(1L, 2L, 3L))
ensure(builder = builder,
expectSqlRaw = "select * from `user` where `id` in (1,2,3);",
expectSqlPrep = "select * from `user` where `id` in (?,?,?);",
expectPairs = listOf(
Value("id", DataType.DTLong, 1L),
Value("id", DataType.DTLong, 2L),
Value("id", DataType.DTLong, 3L)
)
)
}
fun ensure(builder:Select, expectSqlRaw:String, expectSqlPrep:String, expectPairs:Values){
val cmd1 = builder.build(BuildMode.Sql)
val cmd2 = builder.build(BuildMode.Prep)
Assert.assertEquals(expectSqlRaw, cmd1.sql)
Assert.assertEquals(expectSqlPrep, cmd2.sql)
expectPairs.forEachIndexed { ndx, pair ->
val actual = cmd2.pairs[ndx]
Assert.assertEquals(pair.value, actual.value)
Assert.assertEquals(pair.tpe, actual.tpe)
}
}
}
| apache-2.0 | 6f0b849948c2d489971916482b8b52e6 | 35.13253 | 127 | 0.553351 | 3.874677 | false | true | false | false |
leafclick/intellij-community | java/java-tests/testSrc/com/intellij/java/codeInsight/daemon/LightJava11HighlightingTest.kt | 1 | 1431 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.java.codeInsight.daemon
import com.intellij.JavaTestUtil
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction
import com.intellij.psi.CommonClassNames
import com.intellij.psi.PsiClass
import com.intellij.testFramework.fixtures.LightJavaCodeInsightFixtureTestCase
import org.assertj.core.api.Assertions.assertThat
class LightJava11HighlightingTest : LightJavaCodeInsightFixtureTestCase() {
override fun getProjectDescriptor() = JAVA_11
override fun getBasePath() = JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/daemonCodeAnalyzer/advHighlighting11"
fun testMixedVarAndExplicitTypesInLambdaDeclaration() = doTest()
fun testGotoDeclarationOnLambdaVarParameter() {
myFixture.configureByFile(getTestName(false) + ".java")
val offset = myFixture.editor.caretModel.offset
val elements = GotoDeclarationAction.findAllTargetElements(myFixture.project, myFixture.editor, offset)
assertThat(elements).hasSize(1)
val element = elements[0]
assertThat(element).isInstanceOf(PsiClass::class.java)
assertEquals(CommonClassNames.JAVA_LANG_STRING, (element as PsiClass).qualifiedName)
}
private fun doTest() {
myFixture.configureByFile(getTestName(false) + ".java")
myFixture.checkHighlighting()
}
} | apache-2.0 | b8cbbe4ec25d54f86f2547b9bf38907e | 45.193548 | 140 | 0.806429 | 4.834459 | false | true | false | false |
leafclick/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/hprof/visitors/HistogramVisitor.kt | 1 | 4302 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.diagnostic.hprof.visitors
import com.intellij.diagnostic.hprof.classstore.ClassDefinition
import com.intellij.diagnostic.hprof.classstore.ClassStore
import com.intellij.diagnostic.hprof.histogram.Histogram
import com.intellij.diagnostic.hprof.histogram.HistogramEntry
import com.intellij.diagnostic.hprof.parser.*
import java.nio.ByteBuffer
class HistogramVisitor(private val classStore: ClassStore) : HProfVisitor() {
private var completed = false
private var instanceCount = 0L
private var classToHistogramEntryInternal = HashMap<ClassDefinition, InternalHistogramEntry>()
override fun preVisit() {
assert(!completed)
disableAll()
enable(HeapDumpRecordType.InstanceDump)
enable(HeapDumpRecordType.ObjectArrayDump)
enable(HeapDumpRecordType.PrimitiveArrayDump)
enable(HeapDumpRecordType.ClassDump)
}
override fun visitPrimitiveArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, numberOfElements: Long, elementType: Type) {
instanceCount++
val classDefinition = classStore.getClassForPrimitiveArray(elementType)!!
classToHistogramEntryInternal.getOrPut(classDefinition) {
InternalHistogramEntry(classDefinition)
}.addInstance(numberOfElements * elementType.size + ClassDefinition.ARRAY_PREAMBLE_SIZE)
}
override fun visitClassDump(classId: Long,
stackTraceSerialNumber: Long,
superClassId: Long,
classloaderClassId: Long,
instanceSize: Long,
constants: Array<ConstantPoolEntry>,
staticFields: Array<StaticFieldEntry>,
instanceFields: Array<InstanceFieldEntry>) {
instanceCount++
val classDefinition = classStore.classClass
classToHistogramEntryInternal.getOrPut(classDefinition) {
InternalHistogramEntry(classDefinition)
}.addInstance(classDefinition.instanceSize.toLong() + ClassDefinition.OBJECT_PREAMBLE_SIZE)
}
override fun visitObjectArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, arrayClassObjectId: Long, objects: LongArray) {
instanceCount++
val classDefinition = classStore[arrayClassObjectId]
classToHistogramEntryInternal.getOrPut(classDefinition) {
InternalHistogramEntry(classDefinition)
}.addInstance(objects.size.toLong() * visitorContext.idSize + ClassDefinition.ARRAY_PREAMBLE_SIZE)
}
override fun visitInstanceDump(objectId: Long, stackTraceSerialNumber: Long, classObjectId: Long, bytes: ByteBuffer) {
instanceCount++
val classDefinition = classStore[classObjectId]
classToHistogramEntryInternal.getOrPut(classDefinition) {
InternalHistogramEntry(classDefinition)
}.addInstance(classDefinition.instanceSize.toLong() + ClassDefinition.OBJECT_PREAMBLE_SIZE)
}
override fun postVisit() {
completed = true
}
fun createHistogram(): Histogram {
assert(completed)
val result = ArrayList<HistogramEntry>(classToHistogramEntryInternal.size)
classToHistogramEntryInternal.forEach { (_, internalEntry) ->
result.add(internalEntry.asHistogramEntry())
}
result.sortByDescending { e -> e.totalInstances }
return Histogram(result, instanceCount)
}
class InternalHistogramEntry(private val classDefinition: ClassDefinition) {
private var totalInstances = 0L
private var totalBytes = 0L
fun addInstance(sizeInBytes: Long) {
totalInstances++
totalBytes += sizeInBytes
}
fun asHistogramEntry(): HistogramEntry {
return HistogramEntry(classDefinition, totalInstances, totalBytes)
}
}
}
| apache-2.0 | bf5d618e546a1f14aad4dc3a678b1c23 | 38.46789 | 134 | 0.738261 | 4.922197 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/ForConversion.kt | 1 | 14752 | // 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.nj2k.conversions
import com.intellij.psi.*
import com.intellij.util.IncorrectOperationException
import org.jetbrains.kotlin.j2k.ReferenceSearcher
import org.jetbrains.kotlin.j2k.hasWriteAccesses
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.nj2k.*
import org.jetbrains.kotlin.nj2k.symbols.deepestFqName
import org.jetbrains.kotlin.nj2k.tree.*
import org.jetbrains.kotlin.nj2k.types.JKJavaArrayType
import org.jetbrains.kotlin.nj2k.types.JKJavaPrimitiveType
import org.jetbrains.kotlin.nj2k.types.JKNoType
import org.jetbrains.kotlin.utils.NumberWithRadix
import org.jetbrains.kotlin.utils.extractRadix
import kotlin.math.abs
class ForConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) {
private val referenceSearcher: ReferenceSearcher
get() = context.converter.converterServices.oldServices.referenceSearcher
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKJavaForLoopStatement) return recurse(element)
convertToForeach(element)?.also { return recurse(it.withFormattingFrom(element)) }
convertToWhile(element)?.also { return recurse(it.withFormattingFrom(element)) }
return recurse(element)
}
private fun convertToWhile(loopStatement: JKJavaForLoopStatement): JKStatement? {
val whileBody = createWhileBody(loopStatement)
val condition =
if (loopStatement.condition !is JKStubExpression) loopStatement::condition.detached()
else JKLiteralExpression("true", JKLiteralExpression.LiteralType.BOOLEAN)
val whileStatement = JKWhileStatement(condition, whileBody)
if (loopStatement.initializers.isEmpty()
|| loopStatement.initializers.singleOrNull() is JKEmptyStatement
) return whileStatement
val convertedFromForLoopSyntheticWhileStatement =
JKKtConvertedFromForLoopSyntheticWhileStatement(
loopStatement::initializers.detached(),
whileStatement
)
val notNeedParentBlock = loopStatement.parent is JKBlock
|| loopStatement.parent is JKLabeledExpression && loopStatement.parent?.parent is JKBlock
return when {
loopStatement.hasNameConflict() ->
JKExpressionStatement(
runExpression(
convertedFromForLoopSyntheticWhileStatement,
symbolProvider
)
)
!notNeedParentBlock -> blockStatement(convertedFromForLoopSyntheticWhileStatement)
else -> convertedFromForLoopSyntheticWhileStatement
}
}
private fun createWhileBody(loopStatement: JKJavaForLoopStatement): JKStatement {
if (loopStatement.updaters.singleOrNull() is JKEmptyStatement) return loopStatement::body.detached()
val continueStatementConverter = object : RecursiveApplicableConversionBase(context) {
override fun applyToElement(element: JKTreeElement): JKTreeElement {
if (element !is JKContinueStatement) return recurse(element)
val elementPsi = element.psi<PsiContinueStatement>()!!
if (elementPsi.findContinuedStatement()?.toContinuedLoop() != loopStatement.psi<PsiForStatement>()) return recurse(element)
val statements = loopStatement.updaters.map { it.copyTreeAndDetach() } + element.copyTreeAndDetach()
return if (element.parent is JKBlock)
JKBlockStatementWithoutBrackets(statements)
else JKBlockStatement(JKBlockImpl(statements))
}
}
val body = continueStatementConverter.applyToElement(loopStatement::body.detached())
if (body is JKBlockStatement) {
val hasNameConflict = loopStatement.initializers.any { initializer ->
initializer is JKDeclarationStatement && initializer.declaredStatements.any { loopVar ->
loopVar is JKLocalVariable && body.statements.any { statement ->
statement is JKDeclarationStatement && statement.declaredStatements.any {
it is JKLocalVariable && it.name.value == loopVar.name.value
}
}
}
}
val statements =
if (hasNameConflict) {
listOf(JKExpressionStatement(runExpression(body, symbolProvider))) + loopStatement::updaters.detached()
} else {
body.block::statements.detached() + loopStatement::updaters.detached()
}
return JKBlockStatement(JKBlockImpl(statements))
} else {
val statements =
listOf(body as JKStatement) + loopStatement::updaters.detached()
return JKBlockStatement(JKBlockImpl(statements))
}
}
private fun convertToForeach(loopStatement: JKJavaForLoopStatement): JKForInStatement? {
val initializer = loopStatement.initializers.singleOrNull() ?: return null
val loopVar = (initializer as? JKDeclarationStatement)?.declaredStatements?.singleOrNull() as? JKLocalVariable ?: return null
val loopVarPsi = loopVar.psi<PsiLocalVariable>() ?: return null
val condition = loopStatement.condition as? JKBinaryExpression ?: return null
if (!loopVarPsi.hasWriteAccesses(referenceSearcher, loopStatement.body.psi())
&& !loopVarPsi.hasWriteAccesses(referenceSearcher, loopStatement.condition.psi())
) {
val left = condition.left as? JKFieldAccessExpression ?: return null
if (condition.right.psi<PsiExpression>()?.type in listOf(PsiType.DOUBLE, PsiType.FLOAT, PsiType.CHAR)) return null
if (left.identifier.target != loopVar) return null
val operationType =
(loopStatement.updaters.singleOrNull() as? JKExpressionStatement)?.expression?.isVariableIncrementOrDecrement(loopVar)
val reversed = when (operationType?.token?.text) {
"++" -> false
"--" -> true
else -> return null
}
val operatorToken =
((condition.operator as? JKKtOperatorImpl)?.token as? JKKtSingleValueOperatorToken)?.psiToken
val inclusive = when (operatorToken) {
KtTokens.LT -> if (reversed) return null else false
KtTokens.LTEQ -> if (reversed) return null else true
KtTokens.GT -> if (reversed) false else return null
KtTokens.GTEQ -> if (reversed) true else return null
KtTokens.EXCLEQ -> false
else -> return null
}
val start = loopVar::initializer.detached()
val right = condition::right.detached().parenthesizeIfBinaryExpression()
val range = forIterationRange(start, right, reversed, inclusive)
val explicitType =
if (context.converter.settings.specifyLocalVariableTypeByDefault)
JKJavaPrimitiveType.INT
else JKNoType
val loopVarDeclaration =
JKForLoopVariable(
JKTypeElement(explicitType),
loopVar::name.detached(),
JKStubExpression()
)
return JKForInStatement(
loopVarDeclaration,
range,
loopStatement::body.detached()
)
}
return null
}
private fun PsiStatement.toContinuedLoop(): PsiLoopStatement? {
return when (this) {
is PsiLoopStatement -> this
is PsiLabeledStatement -> statement?.toContinuedLoop()
else -> null
}
}
private fun forIterationRange(
start: JKExpression,
bound: JKExpression,
reversed: Boolean,
inclusiveComparison: Boolean
): JKExpression {
indicesIterationRange(start, bound, reversed, inclusiveComparison)?.also { return it }
return when {
reversed -> downToExpression(
start,
convertBound(bound, if (inclusiveComparison) 0 else +1),
context
)
bound !is JKLiteralExpression && !inclusiveComparison ->
untilToExpression(
start,
convertBound(bound, 0),
context
)
else -> JKBinaryExpression(
start,
convertBound(bound, if (inclusiveComparison) 0 else -1),
JKKtOperatorImpl(
JKOperatorToken.RANGE,
typeFactory.types.nullableAny //todo range type
)
)
}
}
private fun convertBound(bound: JKExpression, correction: Int): JKExpression {
if (correction == 0) return bound
if (bound is JKLiteralExpression && bound.type == JKLiteralExpression.LiteralType.INT) {
val correctedLiteral = addCorrectionToIntLiteral(bound.literal, correction)
if (correctedLiteral != null) {
return JKLiteralExpression(correctedLiteral, bound.type)
}
}
val sign = if (correction > 0) JKOperatorToken.PLUS else JKOperatorToken.MINUS
return JKBinaryExpression(
bound,
JKLiteralExpression(abs(correction).toString(), JKLiteralExpression.LiteralType.INT),
JKKtOperatorImpl(
sign,
typeFactory.types.int
)
)
}
private fun addCorrectionToIntLiteral(intLiteral: String, correction: Int): String? {
require(!intLiteral.startsWith("-")) { "This function does not work with signed literals, but $intLiteral was supplied" }
val numberWithRadix = extractRadix(intLiteral)
val value = numberWithRadix.number.toIntOrNull(numberWithRadix.radix) ?: return null
val fixedValue = (value + correction).toString(numberWithRadix.radix)
return "${numberWithRadix.radixPrefix}${fixedValue}"
}
private val NumberWithRadix.radixPrefix: String
get() = when (radix) {
2 -> "0b"
10 -> ""
16 -> "0x"
else -> error("Invalid radix for $this")
}
private fun indicesIterationRange(
start: JKExpression,
bound: JKExpression,
reversed: Boolean,
inclusiveComparison: Boolean
): JKExpression? {
val collectionSizeExpression =
if (reversed) {
if (!inclusiveComparison) return null
if ((bound as? JKLiteralExpression)?.literal?.toIntOrNull() != 0) return null
if (start !is JKBinaryExpression) return null
if (start.operator.token.text != "-") return null
if ((start.right as? JKLiteralExpression)?.literal?.toIntOrNull() != 1) return null
start.left
} else {
if (inclusiveComparison) return null
if ((start as? JKLiteralExpression)?.literal?.toIntOrNull() != 0) return null
bound
} as? JKQualifiedExpression ?: return null
val indices = indicesByCollectionSize(collectionSizeExpression)
?: indicesByArrayLength(collectionSizeExpression)
?: return null
return if (reversed) {
JKQualifiedExpression(
indices,
JKCallExpressionImpl(
symbolProvider.provideMethodSymbol("kotlin.collections.reversed"),
JKArgumentList()
)
)
} else indices
}
private fun indicesByCollectionSize(javaSizeCall: JKQualifiedExpression): JKQualifiedExpression? {
val methodCall = javaSizeCall.selector as? JKCallExpression ?: return null
return if (methodCall.identifier.deepestFqName() == "java.util.Collection.size"
&& methodCall.arguments.arguments.isEmpty()
) toIndicesCall(javaSizeCall) else null
}
private fun indicesByArrayLength(javaSizeCall: JKQualifiedExpression): JKQualifiedExpression? {
val methodCall = javaSizeCall.selector as? JKFieldAccessExpression ?: return null
val receiverType = javaSizeCall.receiver.calculateType(typeFactory)
if (methodCall.identifier.name == "length" && receiverType is JKJavaArrayType) {
return toIndicesCall(javaSizeCall)
}
return null
}
private fun toIndicesCall(javaSizeCall: JKQualifiedExpression): JKQualifiedExpression? {
if (javaSizeCall.psi == null) return null
val selector = JKFieldAccessExpression(
symbolProvider.provideFieldSymbol("kotlin.collections.indices")
)
return JKQualifiedExpression(javaSizeCall::receiver.detached(), selector)
}
private fun JKJavaForLoopStatement.hasNameConflict(): Boolean {
val names = initializers.flatMap { it.declaredVariableNames() }
if (names.isEmpty()) return false
val factory = PsiElementFactory.getInstance(context.project)
for (name in names) {
val refExpr = try {
factory.createExpressionFromText(name, psi) as? PsiReferenceExpression ?: return true
} catch (e: IncorrectOperationException) {
return true
}
if (refExpr.resolve() != null) return true
}
return (parent as? JKBlock)
?.statements
?.takeLastWhile { it != this }
?.any {
it.declaredVariableNames().any { it in names }
} == true
}
private fun JKStatement.declaredVariableNames(): Collection<String> =
when (this) {
is JKDeclarationStatement ->
declaredStatements.filterIsInstance<JKVariable>().map { it.name.value }
is JKJavaForLoopStatement -> initializers.flatMap { it.declaredVariableNames() }
else -> emptyList()
}
private fun JKExpression.isVariableIncrementOrDecrement(variable: JKLocalVariable): JKOperator? {
val pair = when (this) {
is JKPostfixExpression -> operator to expression
is JKPrefixExpression -> operator to expression
else -> return null
}
if ((pair.second as? JKFieldAccessExpression)?.identifier?.target != variable) return null
return pair.first
}
} | apache-2.0 | 1656211610c352fc553cb29dc71c3ec2 | 42.26393 | 158 | 0.628999 | 5.568894 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/ui/DocumentationToolWindowUpdater.kt | 1 | 3342 | // 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 com.intellij.lang.documentation.ide.ui
import com.intellij.ide.DataManager
import com.intellij.ide.IdeEventQueue
import com.intellij.lang.documentation.ide.actions.documentationTargets
import com.intellij.lang.documentation.ide.impl.DocumentationBrowser
import com.intellij.lang.documentation.impl.documentationRequest
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.impl.Utils
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.readAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.wm.IdeFocusManager
import com.intellij.util.ui.EDT
import com.intellij.util.ui.update.Activatable
import kotlinx.coroutines.*
import java.lang.Runnable
import kotlin.coroutines.resume
internal class DocumentationToolWindowUpdater(
private val project: Project,
private val browser: DocumentationBrowser,
) : Activatable {
private val cs = CoroutineScope(CoroutineName("DocumentationPreviewToolWindowUI"))
override fun showNotify() {
toggleAutoUpdate(true)
}
override fun hideNotify() {
toggleAutoUpdate(false)
}
private var paused: Boolean = false
fun pause(): Disposable {
EDT.assertIsEdt()
paused = true
cs.coroutineContext.cancelChildren()
return Disposable {
EDT.assertIsEdt()
paused = false
}
}
private val autoUpdateRequest = Runnable(::requestAutoUpdate)
private var autoUpdateDisposable: Disposable? = null
private fun toggleAutoUpdate(state: Boolean) {
if (state) {
if (autoUpdateDisposable != null) {
return
}
val disposable = Disposer.newDisposable("documentation auto updater")
IdeEventQueue.getInstance().addActivityListener(autoUpdateRequest, disposable)
autoUpdateDisposable = disposable
}
else {
autoUpdateDisposable?.let(Disposer::dispose)
autoUpdateDisposable = null
}
}
private fun requestAutoUpdate() {
cs.coroutineContext.cancelChildren()
if (paused) {
return
}
cs.launch {
delay(DEFAULT_UI_RESPONSE_TIMEOUT)
autoUpdate()
}
}
private suspend fun autoUpdate() {
val dataContext = focusDataContext()
if (dataContext.getData(CommonDataKeys.PROJECT) != project) {
return
}
val request = readAction {
documentationTargets(dataContext).singleOrNull()?.documentationRequest()
}
if (request != null) {
browser.resetBrowser(request)
}
}
private suspend fun focusDataContext(): DataContext = suspendCancellableCoroutine {
IdeFocusManager.getGlobalInstance().doWhenFocusSettlesDown({
@Suppress("DEPRECATION")
val dataContextFromFocusedComponent = DataManager.getInstance().dataContext
val uiSnapshot = Utils.wrapToAsyncDataContext(dataContextFromFocusedComponent)
val asyncDataContext = AnActionEvent.getInjectedDataContext(uiSnapshot)
it.resume(asyncDataContext)
}, ModalityState.any())
}
}
| apache-2.0 | de0b945794f050e532a9ee838b53fc3a | 31.446602 | 158 | 0.757032 | 4.808633 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/refIndex/tests/test/org/jetbrains/kotlin/idea/search/refIndex/AbstractFindUsagesWithCompilerReferenceIndexTest.kt | 1 | 1606 | // 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.search.refIndex
import com.intellij.pom.java.LanguageLevel
import com.intellij.psi.PsiElement
import com.intellij.testFramework.IdeaTestUtil
import com.intellij.testFramework.builders.JavaModuleFixtureBuilder
import org.jetbrains.kotlin.findUsages.AbstractFindUsagesTest
import org.jetbrains.kotlin.findUsages.AbstractFindUsagesTest.Companion.FindUsageTestType
import org.jetbrains.kotlin.findUsages.KotlinFindUsageConfigurator
import org.jetbrains.kotlin.test.TestMetadataUtil
import java.io.File
abstract class AbstractFindUsagesWithCompilerReferenceIndexTest : KotlinCompilerReferenceTestBase() {
override fun tuneFixture(moduleBuilder: JavaModuleFixtureBuilder<*>) {
super.tuneFixture(moduleBuilder)
moduleBuilder.setLanguageLevel(LanguageLevel.JDK_1_8)
moduleBuilder.addJdk(IdeaTestUtil.getMockJdk18Path().path)
}
override fun getTestDataPath(): String = File(TestMetadataUtil.getTestDataPath(javaClass)).path
protected fun doTest(path: String): Unit = AbstractFindUsagesTest.doFindUsageTest<PsiElement>(
path,
configurator = KotlinFindUsageConfigurator.fromFixture(myFixture),
executionWrapper = { findUsageTest ->
findUsageTest(FindUsageTestType.DEFAULT)
installCompiler()
rebuildProject()
findUsageTest(FindUsageTestType.CRI)
},
testType = FindUsageTestType.CRI,
)
}
| apache-2.0 | c6f8740a32d6b23ed568445752a0820b | 43.611111 | 158 | 0.779577 | 5.01875 | false | true | false | false |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/Settings.kt | 1 | 2016 | package de.fabmax.kool.demo
import de.fabmax.kool.KeyValueStorage
import de.fabmax.kool.KoolContext
import de.fabmax.kool.modules.ui2.MutableStateValue
import de.fabmax.kool.modules.ui2.Sizes
import de.fabmax.kool.util.logD
/**
* Object containing all demo related global settings.
*/
object Settings {
val defaultUiSizes = mapOf(
"Small" to UiSizeSetting("Small", Sizes.small),
"Medium" to UiSizeSetting("Medium", Sizes.medium),
"Large" to UiSizeSetting("Large", Sizes.large),
)
val defaultUiSize = UiSizeSetting("Large", Sizes.large)
private var settingsStore: KeyValueStorage? = null
private val settings = mutableListOf<MutableStateSettings<*>>()
val isFullscreen = MutableStateSettings("koolDemo.isFullscreen", false) { it.toBoolean() }
val showHiddenDemos = MutableStateSettings("koolDemo.showHiddenDemos", false) { it.toBoolean() }
val showDebugOverlay = MutableStateSettings("koolDemo.showDebugOverlay", true) { it.toBoolean() }
val showMenuOnStartup = MutableStateSettings("koolDemo.showMenuOnStartup", true) { it.toBoolean() }
val uiSize = MutableStateSettings("koolDemo.uiSize", defaultUiSize) {
defaultUiSizes[it] ?: defaultUiSize
}
val selectedDemo = MutableStateSettings("koolDemo.selectedDemo", Demos.defaultDemo) { it }
fun loadSettings(ctx: KoolContext) {
settingsStore = ctx.assetMgr.storage
settings.forEach { it.load() }
}
class MutableStateSettings<T>(val key: String, initValue: T, val parser: (String) -> T)
: MutableStateValue<T>(initValue)
{
init {
settings += this
onChange {
settingsStore?.storeString(key, "$it")
logD { "Stored $key: $it" }
}
}
fun load() {
settingsStore?.loadString(key)?.let { set(parser(it)) }
}
}
data class UiSizeSetting(val name: String, val sizes: Sizes) {
override fun toString(): String = name
}
} | apache-2.0 | 5bd5a99ef2c0c0bd486e1d0e17c25934 | 33.186441 | 103 | 0.665675 | 4.156701 | false | false | false | false |
yeungeek/AndroidRoad | AVSample/app/src/main/java/com/yeungeek/avsample/activities/media/MediaPlayerActivity.kt | 1 | 2755 | package com.yeungeek.avsample.activities.media
import android.media.MediaPlayer
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.yeungeek.avsample.databinding.ActivityMediaPlayerBinding
class MediaPlayerActivity : AppCompatActivity(), SurfaceHolder.Callback, View.OnClickListener {
private lateinit var binding: ActivityMediaPlayerBinding
private lateinit var surfaceHolder: SurfaceHolder
private lateinit var mediaPlayer: MediaPlayer
private var isStop: Boolean = true
/**
* 1. create media player
* 2. set datasource
* 3. prepare/prepareAysnc
* 4. start
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMediaPlayerBinding.inflate(layoutInflater)
setContentView(binding.root)
init()
}
private fun init() {
surfaceHolder = binding.mediaPlayerSurface.holder
surfaceHolder.addCallback(this)
mediaPlayer = MediaPlayer()
mediaPlayer.setDataSource("https://c1.monidai.com/20220119/IY2u9Sy7/index.m3u8")
mediaPlayer.setOnPreparedListener {
Log.d("DEBUG", "##### prepared ")
mediaPlayer.start()
}
binding.mediaPlayerPauseBtn.setOnClickListener(this)
binding.mediaPlayerStartBtn.setOnClickListener(this)
binding.mediaPlayerStopBtn.setOnClickListener(this)
}
override fun surfaceCreated(holder: SurfaceHolder) {
var surface = holder.surface
mediaPlayer.setSurface(surface)
mediaPlayer.prepareAsync()
}
override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
}
override fun surfaceDestroyed(holder: SurfaceHolder) {
}
override fun onDestroy() {
super.onDestroy()
release()
}
override fun onClick(v: View?) {
when (v?.id) {
binding.mediaPlayerPauseBtn.id -> {
mediaPlayer.pause()
isStop = false
}
binding.mediaPlayerStartBtn.id -> {
Log.d("DEBUG", "##### media player status: $isStop")
if (isStop)
mediaPlayer.prepareAsync()
else
mediaPlayer.start()
isStop = false
}
binding.mediaPlayerStopBtn.id -> {
mediaPlayer.stop()
isStop = true
}
}
}
private fun release() {
if (null != mediaPlayer && mediaPlayer.isPlaying) {
mediaPlayer.stop()
mediaPlayer.release()
}
}
} | apache-2.0 | 9d9015d220151e2b1fc1606c9c27ae4e | 28.010526 | 95 | 0.627223 | 5.055046 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/types/Countries.kt | 1 | 16724 | package slatekit.common.types
import slatekit.results.Outcome
import slatekit.results.builders.Outcomes
interface CountryLookup {
val supported:List<Country>
/**
* Finds the Country with matching iso2 representation
* @param iso2: 2 char country code in ISO format e.g. us
*/
fun parse(iso2: String?): Outcome<Country> {
val cleaned = iso2?.trim()
return when {
cleaned.isNullOrEmpty() -> Outcomes.invalid("Country code not supplied")
cleaned.length < 2 -> Outcomes.invalid("Country code invalid, must be at least 2 chars")
else -> {
val found = find(cleaned)
when (found) {
null -> Outcomes.invalid("Country code $cleaned is invalid")
else -> Outcomes.success(found)
}
}
}
}
/**
* get the countries by list of iso codes
* @param iso2Codes: List of 2 char ISO country codes to filter against
* @return
*/
fun filter(iso2Codes: List<String>): List<Country> {
val countries = supported
val filtered = iso2Codes.map { code -> countries.find { country -> country.iso2 == code } }
val matched = filtered.filterNotNull()
return matched
}
/**
* get the country with matching 2 char ISO country code
*/
fun find(iso2: String?): Country? {
return when (iso2) {
null -> null
else -> supported.firstOrNull { it.iso2 == iso2.toUpperCase() }
}
}
}
object Countries : CountryLookup {
/**
* Supported country codes ( minimal list for now with expected length of phone chars)
*/
override val supported = listOf(
Country("United States" , "US", "USA", "1" , 10, "^[0-9]{10}", "1234567890", "ic_flag_USA"),
Country("Australia" , "AU", "AUS", "61" , 10, "^[0-9]{10}", "1234567890", "ic_flag_AUS"),
Country("Canada" , "CA", "CAN", "1" , 10, "^[0-9]{10}", "1234567890", "ic_flag_CAN"),
Country("France" , "FR", "FRA", "33" , 10, "^[0-9]{10}", "1234567890", "ic_flag_FRA"),
Country("Germany" , "DE", "DEU", "49" , 10, "^[0-9]{10}", "1234567890", "ic_flag_DEU"),
Country("Greece" , "GR", "GRC", "30" , 10, "^[0-9]{10}", "1234567890", "ic_flag_GRC"),
Country("Greenland" , "GL", "GRL", "299" , 10, "^[0-9]{10}", "1234567890", "ic_flag_GRL"),
Country("Iceland" , "IS", "ISL", "354" , 10, "^[0-9]{10}", "1234567890", "ic_flag_ISL"),
Country("India" , "IN", "IND", "91" , 10, "^[0-9]{10}", "1234567890", "ic_flag_IND"),
Country("Ireland" , "IE", "IRL", "353" , 10, "^[0-9]{10}", "1234567890", "ic_flag_IRL"),
Country("Israel" , "IL", "ISR", "972" , 10, "^[0-9]{10}", "1234567890", "ic_flag_ISR"),
Country("Italy" , "IT", "ITA", "39" , 10, "^[0-9]{10}", "1234567890", "ic_flag_ITA"),
Country("Mexico" , "MX", "MEX", "52" , 10, "^[0-9]{10}", "1234567890", "ic_flag_MEX"),
Country("Netherlands" , "NL", "NLD", "31" , 10, "^[0-9]{10}", "1234567890", "ic_flag_NLD"),
Country("New Zealand" , "NZ", "NZL", "64" , 10, "^[0-9]{10}", "1234567890", "ic_flag_NZL"),
Country("Norway" , "NO", "NOR", "47" , 10, "^[0-9]{10}", "1234567890", "ic_flag_NOR"),
Country("Poland" , "PL", "POL", "48" , 10, "^[0-9]{10}", "1234567890", "ic_flag_POL"),
Country("Portugal" , "PT", "PRT", "351" , 10, "^[0-9]{10}", "1234567890", "ic_flag_PRT"),
Country("Puerto Rico" , "PR", "PRI", "1-787", 10, "^[0-9]{10}", "1234567890", "ic_flag_PRI"),
Country("South Africa" , "ZA", "ZAF", "27" , 10, "^[0-9]{10}", "1234567890", "ic_flag_ZAF"),
Country("Sweden" , "SE", "SWE", "46" , 10, "^[0-9]{10}", "1234567890", "ic_flag_SWE"),
Country("Switzerland" , "CH", "CHE", "41" , 10, "^[0-9]{10}", "1234567890", "ic_flag_CHE"),
Country("U.S. Virgin Islands", "VI", "VIR", "1-340", 10, "^[0-9]{10}", "1234567890", "ic_flag_VIR"),
Country("United Kingdom" , "GB", "GBR", "44" , 10, "^[0-9]{10}", "1234567890", "ic_flag_GBR")
)
/*
val all = listOf(
Country("AF", "AFG", "93", "Afghanistan"),
Country("AL", "ALB", "355", "Albania"),
Country("DZ", "DZA", "213", "Algeria"),
Country("AS", "ASM", "1-684", "American Samoa"),
Country("AD", "AND", "376", "Andorra"),
Country("AO", "AGO", "244", "Angola"),
Country("AI", "AIA", "1-264", "Anguilla"),
Country("AQ", "ATA", "672", "Antarctica"),
Country("AG", "ATG", "1-268", "Antigua and Barbuda"),
Country("AR", "ARG", "54", "Argentina"),
Country("AM", "ARM", "374", "Armenia"),
Country("AW", "ABW", "297", "Aruba"),
Country("AU", "AUS", "61", "Australia"),
Country("AT", "AUT", "43", "Austria"),
Country("AZ", "AZE", "994", "Azerbaijan"),
Country("BS", "BHS", "1-242", "Bahamas"),
Country("BH", "BHR", "973", "Bahrain"),
Country("BD", "BGD", "880", "Bangladesh"),
Country("BB", "BRB", "1-246", "Barbados"),
Country("BY", "BLR", "375", "Belarus"),
Country("BE", "BEL", "32", "Belgium"),
Country("BZ", "BLZ", "501", "Belize"),
Country("BJ", "BEN", "229", "Benin"),
Country("BM", "BMU", "1-441", "Bermuda"),
Country("BT", "BTN", "975", "Bhutan"),
Country("BO", "BOL", "591", "Bolivia"),
Country("BA", "BIH", "387", "Bosnia and Herzegovina"),
Country("BW", "BWA", "267", "Botswana"),
Country("BR", "BRA", "55", "Brazil"),
Country("IO", "IOT", "246", "British Indian Ocean Territory"),
Country("VG", "VGB", "1-284", "British Virgin Islands"),
Country("BN", "BRN", "673", "Brunei"),
Country("BG", "BGR", "359", "Bulgaria"),
Country("BF", "BFA", "226", "Burkina Faso"),
Country("BI", "BDI", "257", "Burundi"),
Country("KH", "KHM", "855", "Cambodia"),
Country("CM", "CMR", "237", "Cameroon"),
Country("CA", "CAN", "1", "Canada"),
Country("CV", "CPV", "238", "Cape Verde"),
Country("KY", "CYM", "1-345", "Cayman Islands"),
Country("CF", "CAF", "236", "Central African Republic"),
Country("TD", "TCD", "235", "Chad"),
Country("CL", "CHL", "56", "Chile"),
Country("CN", "CHN", "86", "China"),
Country("CX", "CXR", "61", "Christmas Island"),
Country("CC", "CCK", "61", "Cocos Islands"),
Country("CO", "COL", "57", "Colombia"),
Country("KM", "COM", "269", "Comoros"),
Country("CK", "COK", "682", "Cook Islands"),
Country("CR", "CRI", "506", "Costa Rica"),
Country("HR", "HRV", "385", "Croatia"),
Country("CU", "CUB", "53", "Cuba"),
Country("CW", "CUW", "599", "Curacao"),
Country("CY", "CYP", "357", "Cyprus"),
Country("CZ", "CZE", "420", "Czech Republic"),
Country("CD", "COD", "243", "Democratic Republic of the Congo"),
Country("DK", "DNK", "45", "Denmark"),
Country("DJ", "DJI", "253", "Djibouti"),
Country("DM", "DMA", "1-767", "Dominica"),
Country("DO", "DOM", "1-809", "Dominican Republic"),
Country("TL", "TLS", "670", "East Timor"),
Country("EC", "ECU", "593", "Ecuador"),
Country("EG", "EGY", "20", "Egypt"),
Country("SV", "SLV", "503", "El Salvador"),
Country("GQ", "GNQ", "240", "Equatorial Guinea"),
Country("ER", "ERI", "291", "Eritrea"),
Country("EE", "EST", "372", "Estonia"),
Country("ET", "ETH", "251", "Ethiopia"),
Country("FK", "FLK", "500", "Falkland Islands"),
Country("FO", "FRO", "298", "Faroe Islands"),
Country("FJ", "FJI", "679", "Fiji"),
Country("FI", "FIN", "358", "Finland"),
Country("FR", "FRA", "33", "France"),
Country("PF", "PYF", "689", "French Polynesia"),
Country("GA", "GAB", "241", "Gabon"),
Country("GM", "GMB", "220", "Gambia"),
Country("GE", "GEO", "995", "Georgia"),
Country("DE", "DEU", "49", "Germany"),
Country("GH", "GHA", "233", "Ghana"),
Country("GI", "GIB", "350", "Gibraltar"),
Country("GR", "GRC", "30", "Greece"),
Country("GL", "GRL", "299", "Greenland"),
Country("GD", "GRD", "1-473", "Grenada"),
Country("GU", "GUM", "1-671", "Guam"),
Country("GT", "GTM", "502", "Guatemala"),
Country("GG", "GGY", "44-1481", "Guernsey"),
Country("GN", "GIN", "224", "Guinea"),
Country("GW", "GNB", "245", "Guinea-Bissau"),
Country("GY", "GUY", "592", "Guyana"),
Country("HT", "HTI", "509", "Haiti"),
Country("HN", "HND", "504", "Honduras"),
Country("HK", "HKG", "852", "Hong Kong"),
Country("HU", "HUN", "36", "Hungary"),
Country("IS", "ISL", "354", "Iceland"),
Country("IN", "IND", "91", "India"),
Country("ID", "IDN", "62", "Indonesia"),
Country("IR", "IRN", "98", "Iran"),
Country("IQ", "IRQ", "964", "Iraq"),
Country("IE", "IRL", "353", "Ireland"),
Country("IM", "IMN", "44-1624", "Isle of Man"),
Country("IL", "ISR", "972", "Israel"),
Country("IT", "ITA", "39", "Italy"),
Country("CI", "CIV", "225", "Ivory Coast"),
Country("JM", "JAM", "1-876", "Jamaica"),
Country("JP", "JPN", "81", "Japan"),
Country("JE", "JEY", "44-1534", "Jersey"),
Country("JO", "JOR", "962", "Jordan"),
Country("KZ", "KAZ", "7", "Kazakhstan"),
Country("KE", "KEN", "254", "Kenya"),
Country("KI", "KIR", "686", "Kiribati"),
Country("XK", "XKX", "383", "Kosovo"),
Country("KW", "KWT", "965", "Kuwait"),
Country("KG", "KGZ", "996", "Kyrgyzstan"),
Country("LA", "LAO", "856", "Laos"),
Country("LV", "LVA", "371", "Latvia"),
Country("LB", "LBN", "961", "Lebanon"),
Country("LS", "LSO", "266", "Lesotho"),
Country("LR", "LBR", "231", "Liberia"),
Country("LY", "LBY", "218", "Libya"),
Country("LI", "LIE", "423", "Liechtenstein"),
Country("LT", "LTU", "370", "Lithuania"),
Country("LU", "LUX", "352", "Luxembourg"),
Country("MO", "MAC", "853", "Macau"),
Country("MK", "MKD", "389", "Macedonia"),
Country("MG", "MDG", "261", "Madagascar"),
Country("MW", "MWI", "265", "Malawi"),
Country("MY", "MYS", "60", "Malaysia"),
Country("MV", "MDV", "960", "Maldives"),
Country("ML", "MLI", "223", "Mali"),
Country("MT", "MLT", "356", "Malta"),
Country("MH", "MHL", "692", "Marshall Islands"),
Country("MR", "MRT", "222", "Mauritania"),
Country("MU", "MUS", "230", "Mauritius"),
Country("YT", "MYT", "262", "Mayotte"),
Country("MX", "MEX", "52", "Mexico"),
Country("FM", "FSM", "691", "Micronesia"),
Country("MD", "MDA", "373", "Moldova"),
Country("MC", "MCO", "377", "Monaco"),
Country("MN", "MNG", "976", "Mongolia"),
Country("ME", "MNE", "382", "Montenegro"),
Country("MS", "MSR", "1-664", "Montserrat"),
Country("MA", "MAR", "212", "Morocco"),
Country("MZ", "MOZ", "258", "Mozambique"),
Country("MM", "MMR", "95", "Myanmar"),
Country("NA", "NAM", "264", "Namibia"),
Country("NR", "NRU", "674", "Nauru"),
Country("NP", "NPL", "977", "Nepal"),
Country("NL", "NLD", "31", "Netherlands"),
Country("AN", "ANT", "599", "Netherlands Antilles"),
Country("NC", "NCL", "687", "New Caledonia"),
Country("NZ", "NZL", "64", "New Zealand"),
Country("NI", "NIC", "505", "Nicaragua"),
Country("NE", "NER", "227", "Niger"),
Country("NG", "NGA", "234", "Nigeria"),
Country("NU", "NIU", "683", "Niue"),
Country("KP", "PRK", "850", "North Korea"),
Country("MP", "MNP", "1-670", "Northern Mariana Islands"),
Country("NO", "NOR", "47", "Norway"),
Country("OM", "OMN", "968", "Oman"),
Country("PK", "PAK", "92", "Pakistan"),
Country("PW", "PLW", "680", "Palau"),
Country("PS", "PSE", "970", "Palestine"),
Country("PA", "PAN", "507", "Panama"),
Country("PG", "PNG", "675", "Papua New Guinea"),
Country("PY", "PRY", "595", "Paraguay"),
Country("PE", "PER", "51", "Peru"),
Country("PH", "PHL", "63", "Philippines"),
Country("PN", "PCN", "64", "Pitcairn"),
Country("PL", "POL", "48", "Poland"),
Country("PT", "PRT", "351", "Portugal"),
Country("PR", "PRI", "1-787", "Puerto Rico"),
Country("QA", "QAT", "974", "Qatar"),
Country("CG", "COG", "242", "Republic of the Congo"),
Country("RE", "REU", "262", "Reunion"),
Country("RO", "ROU", "40", "Romania"),
Country("RU", "RUS", "7", "Russia"),
Country("RW", "RWA", "250", "Rwanda"),
Country("BL", "BLM", "590", "Saint Barthelemy"),
Country("SH", "SHN", "290", "Saint Helena"),
Country("KN", "KNA", "1-869", "Saint Kitts and Nevis"),
Country("LC", "LCA", "1-758", "Saint Lucia"),
Country("MF", "MAF", "590", "Saint Martin"),
Country("PM", "SPM", "508", "Saint Pierre and Miquelon"),
Country("VC", "VCT", "1-784", "Saint Vincent and the Grenadines"),
Country("WS", "WSM", "685", "Samoa"),
Country("SM", "SMR", "378", "San Marino"),
Country("ST", "STP", "239", "Sao Tome and Principe"),
Country("SA", "SAU", "966", "Saudi Arabia"),
Country("SN", "SEN", "221", "Senegal"),
Country("RS", "SRB", "381", "Serbia"),
Country("SC", "SYC", "248", "Seychelles"),
Country("SL", "SLE", "232", "Sierra Leone"),
Country("SG", "SGP", "65", "Singapore"),
Country("SX", "SXM", "1-721", "Sint Maarten"),
Country("SK", "SVK", "421", "Slovakia"),
Country("SI", "SVN", "386", "Slovenia"),
Country("SB", "SLB", "677", "Solomon Islands"),
Country("SO", "SOM", "252", "Somalia"),
Country("ZA", "ZAF", "27", "South Africa"),
Country("KR", "KOR", "82", "South Korea"),
Country("SS", "SSD", "211", "South Sudan"),
Country("ES", "ESP", "34", "Spain"),
Country("LK", "LKA", "94", "Sri Lanka"),
Country("SD", "SDN", "249", "Sudan"),
Country("SR", "SUR", "597", "Suriname"),
Country("SJ", "SJM", "47", "Svalbard and Jan Mayen"),
Country("SZ", "SWZ", "268", "Swaziland"),
Country("SE", "SWE", "46", "Sweden"),
Country("CH", "CHE", "41", "Switzerland"),
Country("SY", "SYR", "963", "Syria"),
Country("TW", "TWN", "886", "Taiwan"),
Country("TJ", "TJK", "992", "Tajikistan"),
Country("TZ", "TZA", "255", "Tanzania"),
Country("TH", "THA", "66", "Thailand"),
Country("TG", "TGO", "228", "Togo"),
Country("TK", "TKL", "690", "Tokelau"),
Country("TO", "TON", "676", "Tonga"),
Country("TT", "TTO", "1-868", "Trinidad and Tobago"),
Country("TN", "TUN", "216", "Tunisia"),
Country("TR", "TUR", "90", "Turkey"),
Country("TM", "TKM", "993", "Turkmenistan"),
Country("TC", "TCA", "1-649", "Turks and Caicos Islands"),
Country("TV", "TUV", "688", "Tuvalu"),
Country("VI", "VIR", "1-340", "U.S. Virgin Islands"),
Country("UG", "UGA", "256", "Uganda"),
Country("UA", "UKR", "380", "Ukraine"),
Country("AE", "ARE", "971", "United Arab Emirates"),
Country("GB", "GBR", "44", "United Kingdom"),
Country("US", "USA", "1", "United States"),
Country("UY", "URY", "598", "Uruguay"),
Country("UZ", "UZB", "998", "Uzbekistan"),
Country("VU", "VUT", "678", "Vanuatu"),
Country("VA", "VAT", "379", "Vatican"),
Country("VE", "VEN", "58", "Venezuela"),
Country("VN", "VNM", "84", "Vietnam"),
Country("WF", "WLF", "681", "Wallis and Futuna"),
Country("EH", "ESH", "212", "Western Sahara"),
Country("YE", "YEM", "967", "Yemen"),
Country("ZM", "ZMB", "260", "Zambia"),
Country("ZW", "ZWE", "263", "Zimbabwe")
)
*/
/**
* country usa - used for defaults
*
* @return
*/
val usa = supported.find { it.iso2 == "US" }!!
}
| apache-2.0 | 6dc250c96f624c425f0e70b8a3f6ddbb | 48.47929 | 113 | 0.474767 | 2.97686 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/typeAliases/compoundWithDeprecatedArgumentsAndConstructor.kt | 4 | 475 | // "Replace with 'New<T, U>'" "false"
// ACTION: Convert to block body
// ACTION: Introduce import alias
// ACTION: Remove explicit type specification
@Deprecated("Use New", replaceWith = ReplaceWith("New<T, U>"))
class Old<T, U>
@Deprecated("Use New1", replaceWith = ReplaceWith("New1"))
class Old1
@Deprecated("Use New2", replaceWith = ReplaceWith("New2"))
class Old2
typealias OOO = Old<Old1, Old2>
class New<T, U>
class New1
class New2
fun foo(): <caret>OOO? = null | apache-2.0 | 0dd8ac199fe9a97a3ffac11f15b49c6a | 21.666667 | 62 | 0.703158 | 3.209459 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/infra/network/response/BookmarkRssXml.kt | 1 | 961 | /*
* Copyright (c) 2017. Rei Matsushita
*
* 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 me.rei_m.hbfavmaterial.infra.network.response
import org.simpleframework.xml.ElementList
import org.simpleframework.xml.Root
@Root(name = "rdf:RDF", strict = false)
class BookmarkRssXml {
@set:ElementList(inline = true, required = false)
@get:ElementList(inline = true, required = false)
var list: MutableList<BookmarkRssItemXml> = arrayListOf()
}
| apache-2.0 | 68ab09a6721b24796fd002c3d6fa6d23 | 39.041667 | 112 | 0.752341 | 4.004167 | false | false | false | false |
rei-m/HBFav_material | app/src/main/kotlin/me/rei_m/hbfavmaterial/viewmodel/widget/fragment/BookmarkedUsersFragmentViewModel.kt | 1 | 4483 | /*
* Copyright (c) 2017. Rei Matsushita
*
* 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 me.rei_m.hbfavmaterial.viewmodel.widget.fragment
import android.arch.lifecycle.ViewModel
import android.arch.lifecycle.ViewModelProvider
import android.databinding.Observable
import android.databinding.ObservableArrayList
import android.databinding.ObservableBoolean
import android.databinding.ObservableField
import android.view.View
import android.widget.AdapterView
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.subjects.PublishSubject
import me.rei_m.hbfavmaterial.constant.BookmarkCommentFilter
import me.rei_m.hbfavmaterial.model.BookmarkModel
import me.rei_m.hbfavmaterial.model.entity.BookmarkUser
class BookmarkedUsersFragmentViewModel(private val bookmarkModel: BookmarkModel,
private val articleUrl: String,
bookmarkCommentFilter: BookmarkCommentFilter) : ViewModel() {
val bookmarkUserList: ObservableArrayList<BookmarkUser> = ObservableArrayList()
val isVisibleEmpty: ObservableBoolean = ObservableBoolean(false)
val isVisibleProgress: ObservableBoolean = ObservableBoolean(false)
val isRefreshing: ObservableBoolean = ObservableBoolean(false)
val bookmarkCommentFilter: ObservableField<BookmarkCommentFilter> = ObservableField(bookmarkCommentFilter)
val isVisibleError: ObservableBoolean = ObservableBoolean(false)
private val onItemClickEventSubject = PublishSubject.create<String>()
val onItemClickEvent: io.reactivex.Observable<String> = onItemClickEventSubject
val onRaiseRefreshErrorEvent = bookmarkModel.isRaisedRefreshError
private val disposable: CompositeDisposable = CompositeDisposable()
private val bookmarkCommentFilterChangedCallback = object : Observable.OnPropertyChangedCallback() {
override fun onPropertyChanged(sender: Observable?, propertyId: Int) {
bookmarkModel.getUserList(articleUrl, [email protected]())
}
}
init {
disposable.addAll(bookmarkModel.bookmarkUserList.subscribe {
if (it.isEmpty()) {
bookmarkUserList.clear()
} else {
bookmarkUserList.addAll(it)
}
isVisibleEmpty.set(bookmarkUserList.isEmpty())
}, bookmarkModel.isLoading.subscribe {
isVisibleProgress.set(it)
}, bookmarkModel.isRefreshing.subscribe {
isRefreshing.set(it)
}, bookmarkModel.isRaisedGetError.subscribe {
isVisibleError.set(it)
})
this.bookmarkCommentFilter.addOnPropertyChangedCallback(bookmarkCommentFilterChangedCallback)
bookmarkModel.getUserList(articleUrl, this.bookmarkCommentFilter.get())
}
override fun onCleared() {
bookmarkCommentFilter.removeOnPropertyChangedCallback(bookmarkCommentFilterChangedCallback)
disposable.dispose()
super.onCleared()
}
@Suppress("UNUSED_PARAMETER")
fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
onItemClickEventSubject.onNext(bookmarkUserList[position].creator)
}
fun onRefresh() {
bookmarkModel.refreshUserList(articleUrl, bookmarkCommentFilter.get())
}
class Factory(private val bookmarkModel: BookmarkModel,
private val articleUrl: String,
var bookmarkCommentFilter: BookmarkCommentFilter = BookmarkCommentFilter.ALL) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(BookmarkedUsersFragmentViewModel::class.java)) {
return BookmarkedUsersFragmentViewModel(bookmarkModel, articleUrl, bookmarkCommentFilter) as T
}
throw IllegalArgumentException("Unknown class name")
}
}
}
| apache-2.0 | fbe3f144d43a772487cf5678c17f2685 | 41.292453 | 125 | 0.732991 | 5.231039 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/frontend-api/src/org/jetbrains/kotlin/idea/frontend/api/symbols/markers/KtSymbolWithVisibility.kt | 2 | 835 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.frontend.api.symbols.markers
interface KtSymbolWithVisibility {
val visibility: KtSymbolVisibility
}
sealed class KtSymbolVisibility {
object PUBLIC : KtSymbolVisibility()
object PRIVATE : KtSymbolVisibility()
object PRIVATE_TO_THIS : KtSymbolVisibility()
object PROTECTED : KtSymbolVisibility()
object INTERNAL : KtSymbolVisibility()
object UNKNOWN : KtSymbolVisibility()
object LOCAL : KtSymbolVisibility()
}
fun KtSymbolVisibility.isPrivateOrPrivateToThis(): Boolean =
this == KtSymbolVisibility.PRIVATE || this == KtSymbolVisibility.PRIVATE_TO_THIS | apache-2.0 | 8023839b708d343e0aedb46ae24095f9 | 35.347826 | 115 | 0.768862 | 4.744318 | false | false | false | false |
ThePreviousOne/Untitled | app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaImpl.kt | 1 | 1093 | package eu.kanade.tachiyomi.data.database.models
class MangaImpl : Manga {
override var id: Long? = null
override var source: String = "TEST"
override lateinit var url: String
override lateinit var title: String
override var artist: String? = null
override var author: String? = null
override var description: String? = null
override var genre: String? = null
override var status: Int = 0
override var thumbnail_url: String? = null
override var favorite: Boolean = false
override var last_update: Long = 0
override var initialized: Boolean = false
override var viewer: Int = 0
override var chapter_flags: Int = 0
@Transient override var unread: Int = 0
@Transient override var category: Int = 0
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || javaClass != other.javaClass) return false
val manga = other as Manga
return url == manga.url
}
override fun hashCode(): Int {
return url.hashCode()
}
}
| gpl-3.0 | f265c0cd909333b97a311044d1698912 | 19.622642 | 71 | 0.647758 | 4.516529 | false | false | false | false |
PaleoCrafter/VanillaImmersion | src/main/kotlin/de/mineformers/vanillaimmersion/immersion/CraftingHandler.kt | 1 | 8074 | package de.mineformers.vanillaimmersion.immersion
import de.mineformers.vanillaimmersion.client.CraftingDragHandler
import de.mineformers.vanillaimmersion.tileentity.CraftingTableLogic
import de.mineformers.vanillaimmersion.tileentity.CraftingTableLogic.Companion.Slot
import de.mineformers.vanillaimmersion.util.blockPos
import de.mineformers.vanillaimmersion.util.equal
import de.mineformers.vanillaimmersion.util.insertOrDrop
import de.mineformers.vanillaimmersion.util.minus
import de.mineformers.vanillaimmersion.util.times
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.stats.StatList
import net.minecraft.util.EnumActionResult
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Vec3d
import net.minecraft.world.World
import net.minecraftforge.event.entity.player.PlayerInteractEvent
import net.minecraftforge.fml.common.Loader
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent
/**
* Handles crafting operations.
*/
object CraftingHandler {
/**
* Handles right clicks on the crafting table's top surface.
*/
@SubscribeEvent
fun onRightClick(event: PlayerInteractEvent.RightClickBlock) {
if (event.face != EnumFacing.UP || event.hand != EnumHand.MAIN_HAND)
return
val tile = event.world.getTileEntity(event.pos) as? CraftingTableLogic ?: return
val hitVec = event.hitVec - event.pos
val (x, y) = getLocalPos(tile, hitVec)
if (x in 0..7 && y in 0..7) {
if (event.world.isRemote)
CraftingDragHandler.onStartDragging()
event.cancellationResult = EnumActionResult.SUCCESS
event.isCanceled = true
} else if (!event.entityPlayer.isSneaking && x in 9..11 && y in 6..8 && Loader.isModLoaded("jei")) {
if (event.world.isRemote)
CraftingDragHandler.openRecipeGui()
event.cancellationResult = EnumActionResult.SUCCESS
event.isCanceled = true
}
}
/**
* Handles left clicks on the crafting table's top surface.
*/
@SubscribeEvent
fun onLeftClick(event: PlayerInteractEvent.LeftClickBlock) {
if (event.face != EnumFacing.UP)
return
val tile = event.world.getTileEntity(event.pos) as? CraftingTableLogic ?: return
val hitVec = event.hitVec - event.pos
// Prevent Vanilla behaviour if ours was successful
if (handleClick(event.world, event.pos, event.entityPlayer, hitVec)) {
event.cancellationResult = EnumActionResult.SUCCESS
event.isCanceled = true
}
}
fun getLocalPos(tile: CraftingTableLogic, hitVec: Vec3d): Pair<Int, Int> {
// Rotate the hit vector of the game's ray tracing result to be able to ignore the block's rotation
// Then, convert the vector to the "local" position on the table's face in the [0;15] (i.e. pixel)
// coordinate space
val facing = tile.facing
val angle = -Math.toRadians(180.0 - facing.horizontalAngle).toFloat()
val rot = (-16 * ((hitVec - Vec3d(0.5, 0.0, 0.5)).rotateYaw(angle) - Vec3d(0.5, 0.0, 0.5))).blockPos
// The crafting grid starts at (3|4)
val x = rot.x - 3
val y = rot.z - 4
return Pair(x, y)
}
/**
* Handles a left click on the crafting table grid and drops the appropriate item.
*/
fun handleClick(world: World, pos: BlockPos, player: EntityPlayer, hitVec: Vec3d): Boolean {
val tile = world.getTileEntity(pos) as? CraftingTableLogic ?: return false
// Get the pixel position on the grid that was clicked
val (x, y) = getLocalPos(tile, hitVec)
// The grid covers a 11x7 pixel area (including the output)
if (x !in 0..11 || y !in 0..7)
return false
val (slotX, modX) = Pair(x / 3, x % 3)
val (slotY, modY) = Pair(y / 3, y % 3)
// Don't allow the 1 pixel gap between the individual crafting slots to be clicked
if (modX == 2 || modY == 2)
return true
// The "slots" right above and below the output don't exist
if (slotX == 3 && slotY % 2 == 0)
return true
// Special case for the output
if (slotX == 3 && slotY == 1) {
val result = tile[Slot.OUTPUT].copy()
tile.takeCraftingResult(player, tile[Slot.OUTPUT], false)
// If the player is sneaking, try to extract as many crafting results from the table as possible
if (player.isSneaking && !world.isRemote) {
while (!result.isEmpty && result.equal(tile[Slot.OUTPUT])) {
tile.takeCraftingResult(player, tile[Slot.OUTPUT], false)
}
}
return true
}
val slot = Slot.values()[slotX + slotY * 3 + 1]
val existing = tile[slot]
// Try to remove the item in the hovered slot
if (!existing.isEmpty && !world.isRemote) {
player.insertOrDrop(existing.copy())
tile[slot] = ItemStack.EMPTY
tile.craft(player)
player.addStat(StatList.CRAFTING_TABLE_INTERACTION)
}
return true
}
/**
* Performs the actual distribution of items across the crafting table once the dragging process has ended.
*/
fun performDrag(table: CraftingTableLogic, player: EntityPlayer, slots: List<Int>) {
val stack = player.getHeldItem(EnumHand.MAIN_HAND)
if (stack.isEmpty)
return
// Calculate the amount of consumed items
val consumed = slots.fold(0) { acc, slot ->
// Gather the consumed amount for the current slot and add it to the crafting table
val amount = splitDrag(table, player, stack, slots, slot)
if (amount < 0) {
acc
} else {
val copy = stack.copy()
copy.count = amount
val remaining = table.inventory.insertItem(slot + 1, copy, false).count
acc + (amount - remaining)
}
}
// Consume the items
stack.shrink(consumed)
// Try crafting with the added items
table.craft(player)
}
/**
* Splits the given stack across a set of slots and calculates the amount for the requested slot.
*/
fun splitDrag(table: CraftingTableLogic, player: EntityPlayer,
dragStack: ItemStack, slots: List<Int>, slot: Int): Int {
// First, seek out all slots that the stack may actually be inserted into
val viableSlots = table.inventory.contents.drop(1).withIndex().filter {
(it.value.isEmpty || dragStack.equal(it.value)) && slots.contains(it.index)
}.map { it.index }
// Calculate the amount available for dragging across the table
val draggedSize = dragStack.count
// If there are less items than slots to distribute across and the requested slot was only dragged across when
// all items were consumed or if it isn't even a viable slot, mark it as "not receiving items"
if ((draggedSize < viableSlots.size && slots.indexOf(slot) >= draggedSize) || !viableSlots.contains(slot))
return -1
val stack = table.inventory.getStackInSlot(slot + 1)
val maxAmount =
if (!player.isSneaking) {
// Not Sneaking = Only insert one item
1
} else {
// The maximum amount is the dragged size divided by the number of slots
// If there are less items in the stack than slots, the maximum amount is 1
draggedSize / Math.min(draggedSize, viableSlots.size)
}
// The amount to be inserted into the slot is either the maximum amount or
// what remains to be filled into the slot
return if (stack.isEmpty) maxAmount else Math.min(stack.maxStackSize - stack.count, maxAmount)
}
}
| mit | 44d3719a9c1668e0f0c9939d16d8617e | 44.359551 | 118 | 0.635497 | 4.354908 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/DropdownField.kt | 1 | 1506 | package alraune
import pieces100.*
import vgrechka.*
class DropdownField(
val title: String,
val values: List<TitledValue_killme>,
val initial: String)
: FormField<String>, Retupd.With, Retupd.Helpers<DropdownField> {
private var _name by notNull<String>()
var _value by notNull<String>()
private var used = false
override val retupd = Retupd<String>()
override fun use(source: FieldSource) {
used = true
_value = when (source) {
is FieldSource.Initial -> initial
is FieldSource.Post -> (values.find {it.value == Al.getControlValue(_name)} ?: bitch()).value
is FieldSource.DB -> retupd.retrieve(source.entity)
}
}
override fun name() = _name
override fun setName(name: String) {_name = name}
override fun error() = null
override fun value(): String = _value
override fun debug_shitIntoBogusRequestModel_asIfItCameFromClient(model: BogusRequestModel) {
model.controlNameToValue.put(_name, value())
}
override fun used() = used
override fun update(entity: Any) = retupd.update(entity, _value)
override fun isOnlyForAdmin() = false
fun debug_set(value: String) {_value = value}
fun compose(): Renderable {
val titledValues = values
return TextControlBuilder()
.begin(title, _name, ValidationResult(value()))
.select(titledValues)
.compose()
}
fun set(x: String) {_value = x}
}
| apache-2.0 | 1ac0908cea0b3bdce4be122504a2036e | 24.1 | 105 | 0.632802 | 4.07027 | false | false | false | false |
androidx/androidx | tv/tv-foundation/src/androidTest/java/androidx/tv/foundation/lazy/list/LazyListAnimateItemPlacementTest.kt | 3 | 42679 | /*
* 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.tv.foundation.lazy.list
import androidx.compose.animation.core.FiniteAnimationSpec
import androidx.compose.animation.core.LinearEasing
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.requiredHeight
import androidx.compose.foundation.layout.requiredHeightIn
import androidx.compose.foundation.layout.requiredWidth
import androidx.compose.foundation.layout.requiredWidthIn
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalLayoutDirection
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.SemanticsNodeInteraction
import androidx.compose.ui.test.assertHeightIsEqualTo
import androidx.compose.ui.test.assertIsNotDisplayed
import androidx.compose.ui.test.assertWidthIsEqualTo
import androidx.compose.ui.test.getBoundsInRoot
import androidx.compose.ui.test.getUnclippedBoundsInRoot
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.height
import androidx.compose.ui.unit.width
import androidx.test.filters.LargeTest
import androidx.tv.foundation.PivotOffsets
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import kotlinx.coroutines.runBlocking
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import kotlin.math.roundToInt
@LargeTest
@RunWith(Parameterized::class)
@OptIn(ExperimentalFoundationApi::class)
class LazyListAnimateItemPlacementTest(private val config: Config) {
private val isVertical: Boolean get() = config.isVertical
private val reverseLayout: Boolean get() = config.reverseLayout
@get:Rule
val rule = createComposeRule()
private val itemSize: Int = 50
private var itemSizeDp: Dp = Dp.Infinity
private val itemSize2: Int = 30
private var itemSize2Dp: Dp = Dp.Infinity
private val itemSize3: Int = 20
private var itemSize3Dp: Dp = Dp.Infinity
private val containerSize: Int = itemSize * 5
private var containerSizeDp: Dp = Dp.Infinity
private val spacing: Int = 10
private var spacingDp: Dp = Dp.Infinity
private val itemSizePlusSpacing = itemSize + spacing
private var itemSizePlusSpacingDp = Dp.Infinity
private lateinit var state: TvLazyListState
@Before
fun before() {
rule.mainClock.autoAdvance = false
with(rule.density) {
itemSizeDp = itemSize.toDp()
itemSize2Dp = itemSize2.toDp()
itemSize3Dp = itemSize3.toDp()
containerSizeDp = containerSize.toDp()
spacingDp = spacing.toDp()
itemSizePlusSpacingDp = itemSizePlusSpacing.toDp()
}
}
@Test
fun reorderTwoItems() {
var list by mutableStateOf(listOf(0, 1))
rule.setContent {
LazyList {
items(list, key = { it }) {
Item(it)
}
}
}
assertPositions(0 to 0, 1 to itemSize)
rule.runOnIdle {
list = listOf(1, 0)
}
onAnimationFrame { fraction ->
assertPositions(
0 to 0 + (itemSize * fraction).roundToInt(),
1 to itemSize - (itemSize * fraction).roundToInt(),
fraction = fraction
)
}
}
@Test
fun reorderTwoItems_layoutInfoHasFinalPositions() {
var list by mutableStateOf(listOf(0, 1))
rule.setContent {
LazyList {
items(list, key = { it }) {
Item(it)
}
}
}
assertLayoutInfoPositions(0 to 0, 1 to itemSize)
rule.runOnIdle {
list = listOf(1, 0)
}
onAnimationFrame {
// fraction doesn't affect the offsets in layout info
assertLayoutInfoPositions(1 to 0, 0 to itemSize)
}
}
@Test
fun reorderFirstAndLastItems() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4))
rule.setContent {
LazyList {
items(list, key = { it }) {
Item(it)
}
}
}
assertPositions(
0 to 0,
1 to itemSize,
2 to itemSize * 2,
3 to itemSize * 3,
4 to itemSize * 4,
)
rule.runOnIdle {
list = listOf(4, 1, 2, 3, 0)
}
onAnimationFrame { fraction ->
assertPositions(
0 to 0 + (itemSize * 4 * fraction).roundToInt(),
1 to itemSize,
2 to itemSize * 2,
3 to itemSize * 3,
4 to itemSize * 4 - (itemSize * 4 * fraction).roundToInt(),
fraction = fraction
)
}
}
@Test
fun moveFirstItemToEndCausingAllItemsToAnimate() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4))
rule.setContent {
LazyList {
items(list, key = { it }) {
Item(it)
}
}
}
assertPositions(
0 to 0,
1 to itemSize,
2 to itemSize * 2,
3 to itemSize * 3,
4 to itemSize * 4,
)
rule.runOnIdle {
list = listOf(1, 2, 3, 4, 0)
}
onAnimationFrame { fraction ->
assertPositions(
0 to 0 + (itemSize * 4 * fraction).roundToInt(),
1 to itemSize - (itemSize * fraction).roundToInt(),
2 to itemSize * 2 - (itemSize * fraction).roundToInt(),
3 to itemSize * 3 - (itemSize * fraction).roundToInt(),
4 to itemSize * 4 - (itemSize * fraction).roundToInt(),
fraction = fraction
)
}
}
@Test
fun itemSizeChangeAnimatesNextItems() {
var size by mutableStateOf(itemSizeDp)
rule.setContent {
LazyList(
minSize = itemSizeDp * 5,
maxSize = itemSizeDp * 5
) {
items(listOf(0, 1, 2, 3), key = { it }) {
Item(it, size = if (it == 1) size else itemSizeDp)
}
}
}
rule.runOnIdle {
size = itemSizeDp * 2
}
rule.mainClock.advanceTimeByFrame()
rule.onNodeWithTag("1")
.assertMainAxisSizeIsEqualTo(size)
onAnimationFrame { fraction ->
if (!reverseLayout) {
assertPositions(
0 to 0,
1 to itemSize,
2 to itemSize * 2 + (itemSize * fraction).roundToInt(),
3 to itemSize * 3 + (itemSize * fraction).roundToInt(),
fraction = fraction,
autoReverse = false
)
} else {
assertPositions(
3 to itemSize - (itemSize * fraction).roundToInt(),
2 to itemSize * 2 - (itemSize * fraction).roundToInt(),
1 to itemSize * 3 - (itemSize * fraction).roundToInt(),
0 to itemSize * 4,
fraction = fraction,
autoReverse = false
)
}
}
}
@Test
fun onlyItemsWithModifierAnimates() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4))
rule.setContent {
LazyList {
items(list, key = { it }) {
Item(it, animSpec = if (it == 1 || it == 3) AnimSpec else null)
}
}
}
rule.runOnIdle {
list = listOf(1, 2, 3, 4, 0)
}
onAnimationFrame { fraction ->
assertPositions(
0 to itemSize * 4,
1 to itemSize - (itemSize * fraction).roundToInt(),
2 to itemSize,
3 to itemSize * 3 - (itemSize * fraction).roundToInt(),
4 to itemSize * 3,
fraction = fraction
)
}
}
@Test
fun animationsWithDifferentDurations() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4))
rule.setContent {
LazyList {
items(list, key = { it }) {
val duration = if (it == 1 || it == 3) Duration * 2 else Duration
Item(it, animSpec = tween(duration.toInt(), easing = LinearEasing))
}
}
}
rule.runOnIdle {
list = listOf(1, 2, 3, 4, 0)
}
onAnimationFrame(duration = Duration * 2) { fraction ->
val shorterAnimFraction = (fraction * 2).coerceAtMost(1f)
assertPositions(
0 to 0 + (itemSize * 4 * shorterAnimFraction).roundToInt(),
1 to itemSize - (itemSize * fraction).roundToInt(),
2 to itemSize * 2 - (itemSize * shorterAnimFraction).roundToInt(),
3 to itemSize * 3 - (itemSize * fraction).roundToInt(),
4 to itemSize * 4 - (itemSize * shorterAnimFraction).roundToInt(),
fraction = fraction
)
}
}
@Test
fun multipleChildrenPerItem() {
var list by mutableStateOf(listOf(0, 2))
rule.setContent {
LazyList {
items(list, key = { it }) {
Item(it)
Item(it + 1)
}
}
}
assertPositions(
0 to 0,
1 to itemSize,
2 to itemSize * 2,
3 to itemSize * 3,
)
rule.runOnIdle {
list = listOf(2, 0)
}
onAnimationFrame { fraction ->
assertPositions(
0 to 0 + (itemSize * 2 * fraction).roundToInt(),
1 to itemSize + (itemSize * 2 * fraction).roundToInt(),
2 to itemSize * 2 - (itemSize * 2 * fraction).roundToInt(),
3 to itemSize * 3 - (itemSize * 2 * fraction).roundToInt(),
fraction = fraction
)
}
}
@Test
fun multipleChildrenPerItemSomeDoNotAnimate() {
var list by mutableStateOf(listOf(0, 2))
rule.setContent {
LazyList {
items(list, key = { it }) {
Item(it)
Item(it + 1, animSpec = null)
}
}
}
rule.runOnIdle {
list = listOf(2, 0)
}
onAnimationFrame { fraction ->
assertPositions(
0 to 0 + (itemSize * 2 * fraction).roundToInt(),
1 to itemSize * 3,
2 to itemSize * 2 - (itemSize * 2 * fraction).roundToInt(),
3 to itemSize,
fraction = fraction
)
}
}
@Test
fun animateArrangementChange() {
var arrangement by mutableStateOf(Arrangement.Center)
rule.setContent {
LazyList(
arrangement = arrangement,
minSize = itemSizeDp * 5,
maxSize = itemSizeDp * 5
) {
items(listOf(1, 2, 3), key = { it }) {
Item(it)
}
}
}
assertPositions(
1 to itemSize,
2 to itemSize * 2,
3 to itemSize * 3,
)
rule.runOnIdle {
arrangement = Arrangement.SpaceBetween
}
rule.mainClock.advanceTimeByFrame()
onAnimationFrame { fraction ->
assertPositions(
1 to itemSize - (itemSize * fraction).roundToInt(),
2 to itemSize * 2,
3 to itemSize * 3 + (itemSize * fraction).roundToInt(),
fraction = fraction
)
}
}
@Test
fun moveItemToTheBottomOutsideOfBounds() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5))
rule.setContent {
LazyList(maxSize = itemSizeDp * 3) {
items(list, key = { it }) {
Item(it)
}
}
}
assertPositions(
0 to 0,
1 to itemSize,
2 to itemSize * 2
)
rule.runOnIdle {
list = listOf(0, 4, 2, 3, 1, 5)
}
onAnimationFrame { fraction ->
val item1Offset = itemSize + (itemSize * 3 * fraction).roundToInt()
val item4Offset = itemSize * 4 - (itemSize * 3 * fraction).roundToInt()
val expected = mutableListOf<Pair<Any, Int>>().apply {
add(0 to 0)
if (item1Offset < itemSize * 3) {
add(1 to item1Offset)
} else {
rule.onNodeWithTag("1").assertIsNotDisplayed()
}
add(2 to itemSize * 2)
if (item4Offset < itemSize * 3) {
add(4 to item4Offset)
} else {
rule.onNodeWithTag("4").assertIsNotDisplayed()
}
}
assertPositions(
expected = expected.toTypedArray(),
fraction = fraction
)
}
}
@Test
fun moveItemToTheTopOutsideOfBounds() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5))
rule.setContent {
LazyList(maxSize = itemSizeDp * 3f, startIndex = 3) {
items(list, key = { it }) {
Item(it)
}
}
}
assertPositions(
3 to 0,
4 to itemSize,
5 to itemSize * 2
)
rule.runOnIdle {
list = listOf(2, 4, 0, 3, 1, 5)
}
onAnimationFrame { fraction ->
val item1Offset = itemSize * -2 + (itemSize * 3 * fraction).roundToInt()
val item4Offset = itemSize - (itemSize * 3 * fraction).roundToInt()
val expected = mutableListOf<Pair<Any, Int>>().apply {
if (item4Offset > -itemSize) {
add(4 to item4Offset)
} else {
rule.onNodeWithTag("4").assertIsNotDisplayed()
}
add(3 to 0)
if (item1Offset > -itemSize) {
add(1 to item1Offset)
} else {
rule.onNodeWithTag("1").assertIsNotDisplayed()
}
add(5 to itemSize * 2)
}
assertPositions(
expected = expected.toTypedArray(),
fraction = fraction
)
}
}
@Test
fun moveFirstItemToEndCausingAllItemsToAnimate_withSpacing() {
var list by mutableStateOf(listOf(0, 1, 2, 3))
rule.setContent {
LazyList(arrangement = Arrangement.spacedBy(spacingDp)) {
items(list, key = { it }) {
Item(it)
}
}
}
rule.runOnIdle {
list = listOf(1, 2, 3, 0)
}
onAnimationFrame { fraction ->
assertPositions(
0 to 0 + (itemSizePlusSpacing * 3 * fraction).roundToInt(),
1 to itemSizePlusSpacing - (itemSizePlusSpacing * fraction).roundToInt(),
2 to itemSizePlusSpacing * 2 - (itemSizePlusSpacing * fraction).roundToInt(),
3 to itemSizePlusSpacing * 3 - (itemSizePlusSpacing * fraction).roundToInt(),
fraction = fraction
)
}
}
@Test
fun moveItemToTheBottomOutsideOfBounds_withSpacing() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5))
rule.setContent {
LazyList(
maxSize = itemSizeDp * 3 + spacingDp * 2,
arrangement = Arrangement.spacedBy(spacingDp)
) {
items(list, key = { it }) {
Item(it)
}
}
}
assertPositions(
0 to 0,
1 to itemSizePlusSpacing,
2 to itemSizePlusSpacing * 2
)
rule.runOnIdle {
list = listOf(0, 4, 2, 3, 1, 5)
}
onAnimationFrame { fraction ->
val item1Offset =
itemSizePlusSpacing + (itemSizePlusSpacing * 3 * fraction).roundToInt()
val item4Offset =
itemSizePlusSpacing * 4 - (itemSizePlusSpacing * 3 * fraction).roundToInt()
val screenSize = itemSize * 3 + spacing * 2
val expected = mutableListOf<Pair<Any, Int>>().apply {
add(0 to 0)
if (item1Offset < screenSize) {
add(1 to item1Offset)
} else {
rule.onNodeWithTag("1").assertIsNotDisplayed()
}
add(2 to itemSizePlusSpacing * 2)
if (item4Offset < screenSize) {
add(4 to item4Offset)
} else {
rule.onNodeWithTag("4").assertIsNotDisplayed()
}
}
assertPositions(
expected = expected.toTypedArray(),
fraction = fraction
)
}
}
@Test
fun moveItemToTheTopOutsideOfBounds_withSpacing() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5, 6, 7))
rule.setContent {
LazyList(
maxSize = itemSizeDp * 3 + spacingDp * 2,
startIndex = 3,
arrangement = Arrangement.spacedBy(spacingDp)
) {
items(list, key = { it }) {
Item(it)
}
}
}
assertPositions(
3 to 0,
4 to itemSizePlusSpacing,
5 to itemSizePlusSpacing * 2
)
rule.runOnIdle {
list = listOf(2, 4, 0, 3, 1, 5, 6, 7)
}
onAnimationFrame { fraction ->
val item1Offset =
itemSizePlusSpacing * -2 + (itemSizePlusSpacing * 3 * fraction).roundToInt()
val item4Offset =
(itemSizePlusSpacing - itemSizePlusSpacing * 3 * fraction).roundToInt()
val expected = mutableListOf<Pair<Any, Int>>().apply {
if (item4Offset > -itemSize) {
add(4 to item4Offset)
} else {
rule.onNodeWithTag("4").assertIsNotDisplayed()
}
add(3 to 0)
if (item1Offset > -itemSize) {
add(1 to item1Offset)
} else {
rule.onNodeWithTag("1").assertIsNotDisplayed()
}
add(5 to itemSizePlusSpacing * 2)
}
assertPositions(
expected = expected.toTypedArray(),
fraction = fraction
)
}
}
@Test
fun moveItemToTheTopOutsideOfBounds_differentSizes() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5))
rule.setContent {
LazyList(maxSize = itemSize2Dp + itemSize3Dp + itemSizeDp, startIndex = 3) {
items(list, key = { it }) {
val size =
if (it == 3) itemSize2Dp else if (it == 1) itemSize3Dp else itemSizeDp
Item(it, size = size)
}
}
}
val item3Size = itemSize2
val item4Size = itemSize
assertPositions(
3 to 0,
4 to item3Size,
5 to item3Size + item4Size
)
rule.runOnIdle {
// swap 4 and 1
list = listOf(0, 4, 2, 3, 1, 5)
}
onAnimationFrame { fraction ->
rule.onNodeWithTag("2").assertDoesNotExist()
// item 2 was between 1 and 3 but we don't compose it and don't know the real size,
// so we use an average size.
val item2Size = (itemSize + itemSize2 + itemSize3) / 3
val item1Size = itemSize3 /* the real size of the item 1 */
val startItem1Offset = -item1Size - item2Size
val item1Offset =
startItem1Offset + ((itemSize2 - startItem1Offset) * fraction).roundToInt()
val endItem4Offset = -item4Size - item2Size
val item4Offset = item3Size - ((item3Size - endItem4Offset) * fraction).roundToInt()
val expected = mutableListOf<Pair<Any, Int>>().apply {
if (item4Offset > -item4Size) {
add(4 to item4Offset)
} else {
rule.onNodeWithTag("4").assertIsNotDisplayed()
}
add(3 to 0)
if (item1Offset > -item1Size) {
add(1 to item1Offset)
} else {
rule.onNodeWithTag("1").assertIsNotDisplayed()
}
add(5 to item3Size + item4Size - ((item4Size - item1Size) * fraction).roundToInt())
}
assertPositions(
expected = expected.toTypedArray(),
fraction = fraction
)
}
}
@Test
fun moveItemToTheBottomOutsideOfBounds_differentSizes() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4, 5))
val listSize = itemSize2 + itemSize3 + itemSize - 1
val listSizeDp = with(rule.density) { listSize.toDp() }
rule.setContent {
LazyList(maxSize = listSizeDp) {
items(list, key = { it }) {
val size =
if (it == 0) itemSize2Dp else if (it == 4) itemSize3Dp else itemSizeDp
Item(it, size = size)
}
}
}
val item0Size = itemSize2
val item1Size = itemSize
assertPositions(
0 to 0,
1 to item0Size,
2 to item0Size + item1Size
)
rule.runOnIdle {
list = listOf(0, 4, 2, 3, 1, 5)
}
onAnimationFrame { fraction ->
val item2Size = itemSize
val item4Size = itemSize3
// item 3 was between 2 and 4 but we don't compose it and don't know the real size,
// so we use an average size.
val item3Size = (itemSize + itemSize2 + itemSize3) / 3
val startItem4Offset = item0Size + item1Size + item2Size + item3Size
val endItem1Offset = item0Size + item4Size + item2Size + item3Size
val item1Offset =
item0Size + ((endItem1Offset - item0Size) * fraction).roundToInt()
val item4Offset =
startItem4Offset - ((startItem4Offset - item0Size) * fraction).roundToInt()
val expected = mutableListOf<Pair<Any, Int>>().apply {
add(0 to 0)
if (item1Offset < listSize) {
add(1 to item1Offset)
} else {
rule.onNodeWithTag("1").assertIsNotDisplayed()
}
add(2 to item0Size + item1Size - ((item1Size - item4Size) * fraction).roundToInt())
if (item4Offset < listSize) {
add(4 to item4Offset)
} else {
rule.onNodeWithTag("4").assertIsNotDisplayed()
}
}
assertPositions(
expected = expected.toTypedArray(),
fraction = fraction
)
}
}
@Test
fun animateAlignmentChange() {
var alignment by mutableStateOf(CrossAxisAlignment.End)
rule.setContent {
LazyList(
crossAxisAlignment = alignment,
crossAxisSize = itemSizeDp
) {
items(listOf(1, 2, 3), key = { it }) {
val crossAxisSize =
if (it == 1) itemSizeDp else if (it == 2) itemSize2Dp else itemSize3Dp
Item(it, crossAxisSize = crossAxisSize)
}
}
}
val item2Start = itemSize - itemSize2
val item3Start = itemSize - itemSize3
assertPositions(
1 to 0,
2 to itemSize,
3 to itemSize * 2,
crossAxis = listOf(
1 to 0,
2 to item2Start,
3 to item3Start,
)
)
rule.runOnIdle {
alignment = CrossAxisAlignment.Center
}
rule.mainClock.advanceTimeByFrame()
val item2End = itemSize / 2 - itemSize2 / 2
val item3End = itemSize / 2 - itemSize3 / 2
onAnimationFrame { fraction ->
assertPositions(
1 to 0,
2 to itemSize,
3 to itemSize * 2,
crossAxis = listOf(
1 to 0,
2 to item2Start + ((item2End - item2Start) * fraction).roundToInt(),
3 to item3Start + ((item3End - item3Start) * fraction).roundToInt(),
),
fraction = fraction
)
}
}
@Test
fun animateAlignmentChange_multipleChildrenPerItem() {
var alignment by mutableStateOf(CrossAxisAlignment.Start)
rule.setContent {
LazyList(
crossAxisAlignment = alignment,
crossAxisSize = itemSizeDp * 2
) {
items(1) {
listOf(1, 2, 3).forEach {
val crossAxisSize =
if (it == 1) itemSizeDp else if (it == 2) itemSize2Dp else itemSize3Dp
Item(it, crossAxisSize = crossAxisSize)
}
}
}
}
rule.runOnIdle {
alignment = CrossAxisAlignment.End
}
rule.mainClock.advanceTimeByFrame()
val containerSize = itemSize * 2
onAnimationFrame { fraction ->
assertPositions(
1 to 0,
2 to itemSize,
3 to itemSize * 2,
crossAxis = listOf(
1 to ((containerSize - itemSize) * fraction).roundToInt(),
2 to ((containerSize - itemSize2) * fraction).roundToInt(),
3 to ((containerSize - itemSize3) * fraction).roundToInt()
),
fraction = fraction
)
}
}
@Test
fun animateAlignmentChange_rtl() {
// this test is not applicable to LazyRow
assumeTrue(isVertical)
var alignment by mutableStateOf(CrossAxisAlignment.End)
rule.setContent {
CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) {
LazyList(
crossAxisAlignment = alignment,
crossAxisSize = itemSizeDp
) {
items(listOf(1, 2, 3), key = { it }) {
val crossAxisSize =
if (it == 1) itemSizeDp else if (it == 2) itemSize2Dp else itemSize3Dp
Item(it, crossAxisSize = crossAxisSize)
}
}
}
}
assertPositions(
1 to 0,
2 to itemSize,
3 to itemSize * 2,
crossAxis = listOf(
1 to 0,
2 to 0,
3 to 0,
)
)
rule.runOnIdle {
alignment = CrossAxisAlignment.Center
}
rule.mainClock.advanceTimeByFrame()
onAnimationFrame { fraction ->
assertPositions(
1 to 0,
2 to itemSize,
3 to itemSize * 2,
crossAxis = listOf(
1 to 0,
2 to ((itemSize / 2 - itemSize2 / 2) * fraction).roundToInt(),
3 to ((itemSize / 2 - itemSize3 / 2) * fraction).roundToInt(),
),
fraction = fraction
)
}
}
@Test
fun moveItemToEndCausingNextItemsToAnimate_withContentPadding() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4))
val rawStartPadding = 8
val rawEndPadding = 12
val (startPaddingDp, endPaddingDp) = with(rule.density) {
rawStartPadding.toDp() to rawEndPadding.toDp()
}
rule.setContent {
LazyList(startPadding = startPaddingDp, endPadding = endPaddingDp) {
items(list, key = { it }) {
Item(it)
}
}
}
val startPadding = if (reverseLayout) rawEndPadding else rawStartPadding
assertPositions(
0 to startPadding,
1 to startPadding + itemSize,
2 to startPadding + itemSize * 2,
3 to startPadding + itemSize * 3,
4 to startPadding + itemSize * 4,
)
rule.runOnIdle {
list = listOf(0, 2, 3, 4, 1)
}
onAnimationFrame { fraction ->
assertPositions(
0 to startPadding,
1 to startPadding + itemSize + (itemSize * 3 * fraction).roundToInt(),
2 to startPadding + itemSize * 2 - (itemSize * fraction).roundToInt(),
3 to startPadding + itemSize * 3 - (itemSize * fraction).roundToInt(),
4 to startPadding + itemSize * 4 - (itemSize * fraction).roundToInt(),
fraction = fraction
)
}
}
@Test
fun reorderFirstAndLastItems_noNewLayoutInfoProduced() {
var list by mutableStateOf(listOf(0, 1, 2, 3, 4))
var measurePasses = 0
rule.setContent {
LazyList {
items(list, key = { it }) {
Item(it)
}
}
LaunchedEffect(Unit) {
snapshotFlow { state.layoutInfo }
.collect {
measurePasses++
}
}
}
rule.runOnIdle {
list = listOf(4, 1, 2, 3, 0)
}
var startMeasurePasses = Int.MIN_VALUE
onAnimationFrame { fraction ->
if (fraction == 0f) {
startMeasurePasses = measurePasses
}
}
rule.mainClock.advanceTimeByFrame()
// new layoutInfo is produced on every remeasure of Lazy lists.
// but we want to avoid remeasuring and only do relayout on each animation frame.
// two extra measures are possible as we switch inProgress flag.
assertThat(measurePasses).isAtMost(startMeasurePasses + 2)
}
@Test
fun noAnimationWhenScrollOtherPosition() {
rule.setContent {
LazyList(maxSize = itemSizeDp * 3) {
items(listOf(0, 1, 2, 3, 4, 5, 6, 7), key = { it }) {
Item(it)
}
}
}
rule.runOnIdle {
runBlocking {
state.scrollToItem(0, itemSize / 2)
}
}
onAnimationFrame { fraction ->
assertPositions(
0 to -itemSize / 2,
1 to itemSize / 2,
2 to itemSize * 3 / 2,
3 to itemSize * 5 / 2,
fraction = fraction
)
}
}
@Test
fun itemWithSpecsIsMovingOut() {
var list by mutableStateOf(listOf(0, 1, 2, 3))
rule.setContent {
LazyList(maxSize = itemSizeDp * 2) {
items(list, key = { it }) {
Item(it, animSpec = if (it == 1) AnimSpec else null)
}
}
}
rule.runOnIdle {
list = listOf(0, 2, 3, 1)
}
onAnimationFrame { fraction ->
val listSize = itemSize * 2
val item1Offset = itemSize + (itemSize * 2f * fraction).roundToInt()
val expected = mutableListOf<Pair<Any, Int>>().apply {
add(0 to 0)
if (item1Offset < listSize) {
add(1 to item1Offset)
} else {
rule.onNodeWithTag("1").assertIsNotDisplayed()
}
}
assertPositions(
expected = expected.toTypedArray(),
fraction = fraction
)
}
}
private fun assertPositions(
vararg expected: Pair<Any, Int>,
crossAxis: List<Pair<Any, Int>>? = null,
fraction: Float? = null,
autoReverse: Boolean = reverseLayout
) {
with(rule.density) {
val actual = expected.map {
val actualOffset = rule.onNodeWithTag(it.first.toString())
.getUnclippedBoundsInRoot().let { bounds ->
val offset = if (isVertical) bounds.top else bounds.left
if (offset == Dp.Unspecified) Int.MIN_VALUE else offset.roundToPx()
}
it.first to actualOffset
}
val subject = if (fraction == null) {
assertThat(actual)
} else {
assertWithMessage("Fraction=$fraction").that(actual)
}
subject.isEqualTo(
listOf(*expected).let { list ->
if (!autoReverse) {
list
} else {
val containerBounds = rule.onNodeWithTag(ContainerTag).getBoundsInRoot()
val mainAxisSize =
if (isVertical) containerBounds.height else containerBounds.width
val mainAxisSizePx = with(rule.density) { mainAxisSize.roundToPx() }
list.map {
val itemSize = rule.onNodeWithTag(it.first.toString())
.getUnclippedBoundsInRoot().let { bounds ->
(if (isVertical) bounds.height else bounds.width).roundToPx()
}
it.first to (mainAxisSizePx - itemSize - it.second)
}
}
}
)
if (crossAxis != null) {
val actualCross = expected.map {
val actualOffset = rule.onNodeWithTag(it.first.toString())
.getUnclippedBoundsInRoot().let { bounds ->
val offset = if (isVertical) bounds.left else bounds.top
if (offset == Dp.Unspecified) Int.MIN_VALUE else offset.roundToPx()
}
it.first to actualOffset
}
assertWithMessage(
"CrossAxis" + if (fraction != null) "for fraction=$fraction" else ""
)
.that(actualCross)
.isEqualTo(crossAxis)
}
}
}
private fun assertLayoutInfoPositions(vararg offsets: Pair<Any, Int>) {
rule.runOnIdle {
assertThat(visibleItemsOffsets).isEqualTo(listOf(*offsets))
}
}
private val visibleItemsOffsets: List<Pair<Any, Int>>
get() = state.layoutInfo.visibleItemsInfo.map {
it.key to it.offset
}
private fun onAnimationFrame(duration: Long = Duration, onFrame: (fraction: Float) -> Unit) {
require(duration.mod(FrameDuration) == 0L)
rule.waitForIdle()
rule.mainClock.advanceTimeByFrame()
var expectedTime = rule.mainClock.currentTime
for (i in 0..duration step FrameDuration) {
onFrame(i / duration.toFloat())
rule.mainClock.advanceTimeBy(FrameDuration)
expectedTime += FrameDuration
assertThat(expectedTime).isEqualTo(rule.mainClock.currentTime)
rule.waitForIdle()
}
}
@Composable
private fun LazyList(
arrangement: Arrangement.HorizontalOrVertical? = null,
minSize: Dp = 0.dp,
maxSize: Dp = containerSizeDp,
startIndex: Int = 0,
crossAxisSize: Dp = Dp.Unspecified,
crossAxisAlignment: CrossAxisAlignment = CrossAxisAlignment.Start,
startPadding: Dp = 0.dp,
endPadding: Dp = 0.dp,
content: TvLazyListScope.() -> Unit
) {
state = rememberTvLazyListState(startIndex)
if (isVertical) {
val verticalArrangement =
arrangement ?: if (!reverseLayout) Arrangement.Top else Arrangement.Bottom
val horizontalAlignment = if (crossAxisAlignment == CrossAxisAlignment.Start) {
Alignment.Start
} else if (crossAxisAlignment == CrossAxisAlignment.Center) {
Alignment.CenterHorizontally
} else {
Alignment.End
}
TvLazyColumn(
state = state,
modifier = Modifier
.requiredHeightIn(min = minSize, max = maxSize)
.then(
if (crossAxisSize != Dp.Unspecified) {
Modifier.requiredWidth(crossAxisSize)
} else {
Modifier.fillMaxWidth()
}
)
.testTag(ContainerTag),
verticalArrangement = verticalArrangement,
horizontalAlignment = horizontalAlignment,
reverseLayout = reverseLayout,
contentPadding = PaddingValues(top = startPadding, bottom = endPadding),
pivotOffsets = PivotOffsets(parentFraction = 0f),
content = content
)
} else {
val horizontalArrangement =
arrangement ?: if (!reverseLayout) Arrangement.Start else Arrangement.End
val verticalAlignment = if (crossAxisAlignment == CrossAxisAlignment.Start) {
Alignment.Top
} else if (crossAxisAlignment == CrossAxisAlignment.Center) {
Alignment.CenterVertically
} else {
Alignment.Bottom
}
TvLazyRow(
state = state,
modifier = Modifier
.requiredWidthIn(min = minSize, max = maxSize)
.then(
if (crossAxisSize != Dp.Unspecified) {
Modifier.requiredHeight(crossAxisSize)
} else {
Modifier.fillMaxHeight()
}
)
.testTag(ContainerTag),
horizontalArrangement = horizontalArrangement,
verticalAlignment = verticalAlignment,
reverseLayout = reverseLayout,
contentPadding = PaddingValues(start = startPadding, end = endPadding),
pivotOffsets = PivotOffsets(parentFraction = 0f),
content = content
)
}
}
@Composable
private fun TvLazyListItemScope.Item(
tag: Int,
size: Dp = itemSizeDp,
crossAxisSize: Dp = size,
animSpec: FiniteAnimationSpec<IntOffset>? = AnimSpec
) {
Box(
Modifier
.then(
if (isVertical) {
Modifier.requiredHeight(size).requiredWidth(crossAxisSize)
} else {
Modifier.requiredWidth(size).requiredHeight(crossAxisSize)
}
)
.testTag(tag.toString())
.then(
if (animSpec != null) {
Modifier.animateItemPlacement(animSpec)
} else {
Modifier
}
)
)
}
private fun SemanticsNodeInteraction.assertMainAxisSizeIsEqualTo(
expected: Dp
): SemanticsNodeInteraction {
return if (isVertical) assertHeightIsEqualTo(expected) else assertWidthIsEqualTo(expected)
}
companion object {
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun params() = arrayOf(
Config(isVertical = true, reverseLayout = false),
Config(isVertical = false, reverseLayout = false),
Config(isVertical = true, reverseLayout = true),
Config(isVertical = false, reverseLayout = true),
)
class Config(
val isVertical: Boolean,
val reverseLayout: Boolean
) {
override fun toString() =
(if (isVertical) "LazyColumn" else "LazyRow") +
(if (reverseLayout) "(reverse)" else "")
}
}
}
private val FrameDuration = 16L
private val Duration = 400L
private val AnimSpec = tween<IntOffset>(Duration.toInt(), easing = LinearEasing)
private val ContainerTag = "container"
private enum class CrossAxisAlignment {
Start,
End,
Center
}
| apache-2.0 | 883e2acfc732be059a7f7637357935eb | 32.899126 | 99 | 0.508002 | 5.127839 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/conversation/AttachmentButtonCenterHelper.kt | 1 | 1210 | package org.thoughtcrime.securesms.conversation
import androidx.core.view.doOnNextLayout
import androidx.recyclerview.widget.RecyclerView
import org.signal.core.util.DimensionUnit
/**
* Adds necessary padding to each side of the given RecyclerView in order to ensure that
* if all buttons can fit in the visible real-estate on screen, they are centered.
*/
class AttachmentButtonCenterHelper(private val recyclerView: RecyclerView) : RecyclerView.AdapterDataObserver() {
private val itemWidth: Float = DimensionUnit.DP.toPixels(88f)
private val defaultPadding: Float = DimensionUnit.DP.toPixels(16f)
override fun onChanged() {
val itemCount = recyclerView.adapter?.itemCount ?: return
val requiredSpace = itemWidth * itemCount
recyclerView.doOnNextLayout {
if (it.measuredWidth >= requiredSpace) {
val extraSpace = it.measuredWidth - requiredSpace
val availablePadding = extraSpace / 2f
it.post {
it.setPadding(availablePadding.toInt(), it.paddingTop, availablePadding.toInt(), it.paddingBottom)
}
} else {
it.setPadding(defaultPadding.toInt(), it.paddingTop, defaultPadding.toInt(), it.paddingBottom)
}
}
}
}
| gpl-3.0 | db99df915b71ae0ff6c3b70919cea1da | 36.8125 | 113 | 0.73719 | 4.618321 | false | false | false | false |
androidx/androidx | test/integration-tests/junit-gtest-test/src/androidTest/java/androidx/test/ext/junitgtesttest/GtestRunnerTest.kt | 3 | 3599 | /*
* 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.test.ext.junitgtesttest
import androidx.test.ext.junitgtest.GtestRunner
import androidx.test.ext.junitgtest.TargetLibrary
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.Description
import org.junit.runner.RunWith
import org.junit.runner.notification.Failure
import org.junit.runner.notification.RunListener
import org.junit.runner.notification.RunNotifier
/**
* Tests the GtestRunner
*
* These specific tests would be more appropriate to put in junit-gtest itself, and have an
* integration test app run the tests more like an actual app consuming the library would (basically
* the [NativeTests] class), but due to b/236913987 it is currently difficult or impossible to
* make the test libraries ('apptest') available to the tests without including them in the release
* AAR.
*/
class GtestRunnerTest {
private val runListener = CountingRunListener()
private val runNotifier = RunNotifier().apply {
addListener(runListener)
}
companion object {
private val runner = GtestRunner(NativeTests::class.java)
}
@Test
fun runsTheTest() {
runner.run(runNotifier)
assertThat(runListener.failures).hasSize(2)
val adderFailure = runListener.failures[0]
assertThat(adderFailure.message.normalizeWhitespace()).contains(
"""
Expected equality of these values:
42
add(42, 1)
Which is: 43
""".normalizeWhitespace()
)
val uncaughtExceptionFailure = runListener.failures[1]
assertThat(uncaughtExceptionFailure.message.normalizeWhitespace()).contains(
"""
unknown file:-1
Unknown C++ exception thrown in the test body.
""".normalizeWhitespace()
)
}
@Test
fun reportsAllResults() {
runner.run(runNotifier)
assertThat(runListener.descriptions.map { it.displayName }).isEqualTo(
listOf(
"adder_pass(androidx.test.ext.junitgtesttest.GtestRunnerTest\$NativeTests)",
"foo_fail(androidx.test.ext.junitgtesttest.GtestRunnerTest\$NativeTests)",
"JUnitNotifyingListener_handles_null_file_names(androidx.test.ext.junitgtesttest." +
"GtestRunnerTest\$NativeTests)"
)
)
}
fun String.normalizeWhitespace(): String {
return replace("\\s+".toRegex(), " ").trim()
}
class CountingRunListener : RunListener() {
val failures = mutableListOf<Failure>()
val descriptions = mutableListOf<Description>()
override fun testFailure(failure: Failure) {
failures.add(failure)
}
override fun testFinished(description: Description) {
descriptions.add(description)
}
}
@RunWith(GtestRunner::class)
@TargetLibrary(libraryName = "apptest")
class NativeTests
} | apache-2.0 | 575c3c47469c4afe26252a0f75fa5fd3 | 33.951456 | 100 | 0.675188 | 4.515684 | false | true | false | false |
pokk/SSFM | app/src/main/kotlin/taiwan/no1/app/ssfm/features/chart/ChartIndexFragment.kt | 1 | 6385 | package taiwan.no1.app.ssfm.features.chart
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.StaggeredGridLayoutManager
import android.widget.GridLayout.VERTICAL
import com.devrapid.kotlinknifer.recyclerview.WrapContentLinearLayoutManager
import com.devrapid.kotlinknifer.recyclerview.itemdecorator.GridSpacingItemDecorator
import com.devrapid.kotlinknifer.recyclerview.itemdecorator.HorizontalItemDecorator
import com.devrapid.kotlinknifer.scaledDrawable
import org.jetbrains.anko.bundleOf
import taiwan.no1.app.ssfm.R
import taiwan.no1.app.ssfm.databinding.FragmentChartIndexBinding
import taiwan.no1.app.ssfm.features.base.AdvancedFragment
import taiwan.no1.app.ssfm.features.search.RecyclerViewSearchArtistChartViewModel
import taiwan.no1.app.ssfm.misc.extension.gContext
import taiwan.no1.app.ssfm.misc.extension.recyclerview.ArtistAdapter
import taiwan.no1.app.ssfm.misc.extension.recyclerview.DataInfo
import taiwan.no1.app.ssfm.misc.extension.recyclerview.RVCustomScrollCallback
import taiwan.no1.app.ssfm.misc.extension.recyclerview.RankAdapter
import taiwan.no1.app.ssfm.misc.extension.recyclerview.TagAdapter
import taiwan.no1.app.ssfm.misc.extension.recyclerview.firstFetch
import taiwan.no1.app.ssfm.misc.extension.recyclerview.keepAllLastItemPosition
import taiwan.no1.app.ssfm.misc.extension.recyclerview.refreshAndChangeList
import taiwan.no1.app.ssfm.misc.extension.recyclerview.restoreAllLastItemPosition
import taiwan.no1.app.ssfm.misc.widgets.recyclerviews.adapters.BaseDataBindingAdapter
import taiwan.no1.app.ssfm.models.entities.lastfm.BaseEntity
import javax.inject.Inject
/**
* @author jieyi
* @since 8/20/17
*/
class ChartIndexFragment : AdvancedFragment<ChartIndexFragmentViewModel, FragmentChartIndexBinding>() {
//region Static initialization
companion object Factory {
/**
* Use this factory method to create a new instance of this fragment using the provided parameters.
*
* @return A new instance of [android.app.Fragment] ChartIndexFragment.
*/
fun newInstance() = ChartIndexFragment().apply {
arguments = bundleOf()
}
}
//endregion
@Inject override lateinit var viewModel: ChartIndexFragmentViewModel
private val rankInfo by lazy { DataInfo() }
private val artistInfo by lazy { DataInfo(limit = 30) }
private val tagInfo by lazy { DataInfo() }
private var rankRes = mutableListOf<BaseEntity>()
private var artistRes = mutableListOf<BaseEntity>()
private var tagRes = mutableListOf<BaseEntity>()
//region Fragment lifecycle
override fun onResume() {
super.onResume()
binding?.apply {
listOf(Pair(artistInfo, artistLayoutManager),
Pair(rankInfo, rankLayoutManager)).restoreAllLastItemPosition()
}
}
override fun onPause() {
super.onPause()
binding?.apply {
listOf(Triple(artistInfo, rvTopArtists, artistLayoutManager),
Triple(rankInfo, rvTopChart, rankLayoutManager)).keepAllLastItemPosition()
}
}
override fun onDestroyView() {
listOf((binding?.rankAdapter as BaseDataBindingAdapter<*, *>),
(binding?.artistAdapter as BaseDataBindingAdapter<*, *>),
(binding?.tagAdapter as BaseDataBindingAdapter<*, *>)).forEach { it.detachAll() }
super.onDestroyView()
}
//endregion
//region Base fragment implement
override fun rendered(savedInstanceState: Bundle?) {
binding?.apply {
rankLayoutManager = WrapContentLinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
artistLayoutManager = WrapContentLinearLayoutManager(activity, LinearLayoutManager.HORIZONTAL, false)
tagLayoutManager = StaggeredGridLayoutManager(3, VERTICAL)
rankAdapter = RankAdapter(this@ChartIndexFragment, R.layout.item_rank_type_1, rankRes) { holder, item, _ ->
if (null == holder.binding.avm)
holder.binding.avm = RecyclerViewChartRankChartViewModel(item)
else
holder.binding.avm?.setChartItem(item)
}
artistAdapter = ArtistAdapter(this@ChartIndexFragment,
R.layout.item_artist_type_1,
artistRes) { holder, item, _ ->
if (null == holder.binding.avm)
holder.binding.avm = RecyclerViewSearchArtistChartViewModel(item)
else
holder.binding.avm?.setArtistItem(item)
val sd = gContext().scaledDrawable(R.drawable.ic_feature, 0.5f, 0.5f)
holder.binding.tvPlayCount.setCompoundDrawables(sd, null, null, null)
}
tagAdapter = TagAdapter(this@ChartIndexFragment, R.layout.item_tag_type_1, tagRes) { holder, item, _ ->
if (null == holder.binding.avm)
holder.binding.avm = RecyclerViewChartTagViewModel(item)
else
holder.binding.avm?.setTagItem(item)
}
rankDecoration = HorizontalItemDecorator(20)
artistDecoration = HorizontalItemDecorator(20)
tagDecoration = GridSpacingItemDecorator(3, 20, false)
artistLoadmore = RVCustomScrollCallback(binding?.artistAdapter as ArtistAdapter, artistInfo,
artistRes, viewModel::fetchArtistList)
}
// First time showing this fragment.
rankInfo.firstFetch { info ->
viewModel.fetchRankList {
rankRes.refreshAndChangeList(it, 1, binding?.rankAdapter as RankAdapter, info)
}
}
artistInfo.firstFetch {
viewModel.fetchArtistList(it.page, it.limit) { resList, total ->
artistRes.refreshAndChangeList(resList, total, binding?.artistAdapter as ArtistAdapter, it)
}
}
tagInfo.firstFetch {
viewModel.fetchTrackList(it.page, it.limit) { resList, total ->
tagRes.refreshAndChangeList(resList, total, binding?.tagAdapter as TagAdapter, it)
}
}
}
override fun provideInflateView(): Int = R.layout.fragment_chart_index
//endregion
} | apache-2.0 | b11621926ac0c64452ccbaffb06b8e1a | 45.275362 | 119 | 0.681754 | 4.626812 | false | false | false | false |
nrizzio/Signal-Android | spinner/lib/src/main/java/org/signal/spinner/SpinnerServer.kt | 1 | 15690 | package org.signal.spinner
import android.app.Application
import android.database.Cursor
import androidx.sqlite.db.SupportSQLiteDatabase
import com.github.jknack.handlebars.Handlebars
import com.github.jknack.handlebars.Template
import com.github.jknack.handlebars.helper.ConditionalHelpers
import fi.iki.elonen.NanoHTTPD
import org.signal.core.util.ExceptionUtil
import org.signal.core.util.logging.Log
import org.signal.spinner.Spinner.DatabaseConfig
import java.lang.IllegalArgumentException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.Queue
import java.util.concurrent.ConcurrentLinkedQueue
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.min
/**
* The workhorse of this lib. Handles all of our our web routing and response generation.
*
* In general, you add routes in [serve], and then build a response by creating a handlebars template (in the assets folder) and then passing in a data class
* to [renderTemplate].
*/
internal class SpinnerServer(
private val application: Application,
deviceInfo: Map<String, String>,
private val databases: Map<String, DatabaseConfig>,
private val plugins: Map<String, Plugin>
) : NanoHTTPD(5000) {
companion object {
private val TAG = Log.tag(SpinnerServer::class.java)
}
private val deviceInfo: Map<String, String> = deviceInfo.filterKeys { !it.startsWith(Spinner.KEY_PREFIX) }
private val environment: String = deviceInfo[Spinner.KEY_ENVIRONMENT] ?: "UNKNOWN"
private val handlebars: Handlebars = Handlebars(AssetTemplateLoader(application)).apply {
registerHelper("eq", ConditionalHelpers.eq)
registerHelper("neq", ConditionalHelpers.neq)
}
private val recentSql: MutableMap<String, Queue<QueryItem>> = mutableMapOf()
private val dateFormat = SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS zzz", Locale.US)
override fun serve(session: IHTTPSession): Response {
if (session.method == Method.POST) {
// Needed to populate session.parameters
session.parseBody(mutableMapOf())
}
val dbParam: String = session.queryParam("db") ?: session.parameters["db"]?.toString() ?: databases.keys.first()
val dbConfig: DatabaseConfig = databases[dbParam] ?: return internalError(IllegalArgumentException("Invalid db param!"))
try {
return when {
session.method == Method.GET && session.uri == "/css/main.css" -> newFileResponse("css/main.css", "text/css")
session.method == Method.GET && session.uri == "/js/main.js" -> newFileResponse("js/main.js", "text/javascript")
session.method == Method.GET && session.uri == "/" -> getIndex(dbParam, dbConfig.db)
session.method == Method.GET && session.uri == "/browse" -> getBrowse(dbParam, dbConfig.db)
session.method == Method.POST && session.uri == "/browse" -> postBrowse(dbParam, dbConfig, session)
session.method == Method.GET && session.uri == "/query" -> getQuery(dbParam, dbConfig.db)
session.method == Method.POST && session.uri == "/query" -> postQuery(dbParam, dbConfig, session)
session.method == Method.GET && session.uri == "/recent" -> getRecent(dbParam, dbConfig.db)
else -> {
val plugin = plugins[session.uri]
if (plugin != null && session.method == Method.GET) {
getPlugin(dbParam, plugin)
} else {
newFixedLengthResponse(Response.Status.NOT_FOUND, MIME_HTML, "Not found")
}
}
}
} catch (t: Throwable) {
Log.e(TAG, t)
return internalError(t)
}
}
fun onSql(dbName: String, sql: String) {
val commands: Queue<QueryItem> = recentSql[dbName] ?: ConcurrentLinkedQueue()
commands += QueryItem(System.currentTimeMillis(), sql)
if (commands.size > 500) {
commands.remove()
}
recentSql[dbName] = commands
}
private fun getIndex(dbName: String, db: SupportSQLiteDatabase): Response {
return renderTemplate(
"overview",
OverviewPageModel(
environment = environment,
deviceInfo = deviceInfo,
database = dbName,
databases = databases.keys.toList(),
plugins = plugins.values.toList(),
tables = db.getTables().use { it.toTableInfo() },
indices = db.getIndexes().use { it.toIndexInfo() },
triggers = db.getTriggers().use { it.toTriggerInfo() },
queryResult = db.getTables().use { it.toQueryResult() }
)
)
}
private fun getBrowse(dbName: String, db: SupportSQLiteDatabase): Response {
return renderTemplate(
"browse",
BrowsePageModel(
environment = environment,
deviceInfo = deviceInfo,
database = dbName,
databases = databases.keys.toList(),
plugins = plugins.values.toList(),
tableNames = db.getTableNames()
)
)
}
private fun postBrowse(dbName: String, dbConfig: DatabaseConfig, session: IHTTPSession): Response {
val table: String = session.parameters["table"]?.get(0).toString()
val pageSize: Int = session.parameters["pageSize"]?.get(0)?.toInt() ?: 1000
var pageIndex: Int = session.parameters["pageIndex"]?.get(0)?.toInt() ?: 0
val action: String? = session.parameters["action"]?.get(0)
val rowCount = dbConfig.db.getTableRowCount(table)
val pageCount = ceil(rowCount.toFloat() / pageSize.toFloat()).toInt()
when (action) {
"first" -> pageIndex = 0
"next" -> pageIndex = min(pageIndex + 1, pageCount - 1)
"previous" -> pageIndex = max(pageIndex - 1, 0)
"last" -> pageIndex = pageCount - 1
}
val query = "select * from $table limit $pageSize offset ${pageSize * pageIndex}"
val queryResult = dbConfig.db.query(query).use { it.toQueryResult(columnTransformers = dbConfig.columnTransformers) }
return renderTemplate(
"browse",
BrowsePageModel(
environment = environment,
deviceInfo = deviceInfo,
database = dbName,
databases = databases.keys.toList(),
plugins = plugins.values.toList(),
tableNames = dbConfig.db.getTableNames(),
table = table,
queryResult = queryResult,
pagingData = PagingData(
rowCount = rowCount,
pageSize = pageSize,
pageIndex = pageIndex,
pageCount = pageCount,
startRow = pageSize * pageIndex,
endRow = min(pageSize * (pageIndex + 1), rowCount)
)
)
)
}
private fun getQuery(dbName: String, db: SupportSQLiteDatabase): Response {
return renderTemplate(
"query",
QueryPageModel(
environment = environment,
deviceInfo = deviceInfo,
database = dbName,
databases = databases.keys.toList(),
plugins = plugins.values.toList(),
query = ""
)
)
}
private fun getRecent(dbName: String, db: SupportSQLiteDatabase): Response {
val queries: List<RecentQuery>? = recentSql[dbName]
?.map { it ->
RecentQuery(
formattedTime = dateFormat.format(Date(it.time)),
query = it.query
)
}
return renderTemplate(
"recent",
RecentPageModel(
environment = environment,
deviceInfo = deviceInfo,
database = dbName,
databases = databases.keys.toList(),
plugins = plugins.values.toList(),
recentSql = queries?.reversed()
)
)
}
private fun postQuery(dbName: String, dbConfig: DatabaseConfig, session: IHTTPSession): Response {
val action: String = session.parameters["action"]?.get(0).toString()
val rawQuery: String = session.parameters["query"]?.get(0).toString()
val query = if (action == "analyze") "EXPLAIN QUERY PLAN $rawQuery" else rawQuery
val startTime = System.currentTimeMillis()
return renderTemplate(
"query",
QueryPageModel(
environment = environment,
deviceInfo = deviceInfo,
database = dbName,
databases = databases.keys.toList(),
plugins = plugins.values.toList(),
query = rawQuery,
queryResult = dbConfig.db.query(query).use { it.toQueryResult(queryStartTime = startTime, columnTransformers = dbConfig.columnTransformers) }
)
)
}
private fun getPlugin(dbName: String, plugin: Plugin): Response {
return renderTemplate(
"plugin",
PluginPageModel(
environment = environment,
deviceInfo = deviceInfo,
database = dbName,
databases = databases.keys.toList(),
plugins = plugins.values.toList(),
activePlugin = plugin,
pluginResult = plugin.get()
)
)
}
private fun internalError(throwable: Throwable): Response {
val stackTrace = ExceptionUtil.convertThrowableToString(throwable)
.split("\n")
.map { it.trim() }
.mapIndexed { index, s -> if (index == 0) s else " $s" }
.joinToString("<br />")
return renderTemplate("error", stackTrace)
}
private fun renderTemplate(assetName: String, model: Any): Response {
val template: Template = handlebars.compile(assetName)
val output: String = template.apply(model)
return newFixedLengthResponse(output)
}
private fun newFileResponse(assetPath: String, mimeType: String): Response {
return newChunkedResponse(
Response.Status.OK,
mimeType,
application.assets.open(assetPath)
)
}
private fun Cursor.toQueryResult(queryStartTime: Long = 0, columnTransformers: List<ColumnTransformer> = emptyList()): QueryResult {
val numColumns = this.columnCount
val columns = mutableListOf<String>()
val transformers = mutableListOf<ColumnTransformer>()
for (i in 0 until numColumns) {
val columnName = getColumnName(i)
val customTransformer: ColumnTransformer? = columnTransformers.find { it.matches(null, columnName) }
columns += if (customTransformer != null) {
"$columnName *"
} else {
columnName
}
transformers += customTransformer ?: DefaultColumnTransformer
}
var timeOfFirstRow = 0L
val rows = mutableListOf<List<String>>()
while (moveToNext()) {
if (timeOfFirstRow == 0L) {
timeOfFirstRow = System.currentTimeMillis()
}
val row = mutableListOf<String>()
for (i in 0 until numColumns) {
val columnName: String = getColumnName(i)
try {
row += transformers[i].transform(null, columnName, this)
} catch (e: Exception) {
row += "*Failed to Transform*\n\n${DefaultColumnTransformer.transform(null, columnName, this)}"
}
}
rows += row
}
if (timeOfFirstRow == 0L) {
timeOfFirstRow = System.currentTimeMillis()
}
return QueryResult(
columns = columns,
rows = rows,
timeToFirstRow = max(timeOfFirstRow - queryStartTime, 0),
timeToReadRows = max(System.currentTimeMillis() - timeOfFirstRow, 0)
)
}
private fun Cursor.toTableInfo(): List<TableInfo> {
val tables = mutableListOf<TableInfo>()
while (moveToNext()) {
val name = getString(getColumnIndexOrThrow("name"))
tables += TableInfo(
name = name ?: "null",
sql = getString(getColumnIndexOrThrow("sql"))?.formatAsSqlCreationStatement(name) ?: "null"
)
}
return tables
}
private fun Cursor.toIndexInfo(): List<IndexInfo> {
val indices = mutableListOf<IndexInfo>()
while (moveToNext()) {
indices += IndexInfo(
name = getString(getColumnIndexOrThrow("name")) ?: "null",
sql = getString(getColumnIndexOrThrow("sql")) ?: "null"
)
}
return indices
}
private fun Cursor.toTriggerInfo(): List<TriggerInfo> {
val indices = mutableListOf<TriggerInfo>()
while (moveToNext()) {
indices += TriggerInfo(
name = getString(getColumnIndexOrThrow("name")) ?: "null",
sql = getString(getColumnIndexOrThrow("sql")) ?: "null"
)
}
return indices
}
/** Takes a SQL table creation statement and formats it using HTML */
private fun String.formatAsSqlCreationStatement(name: String): String {
val fields = substring(indexOf("(") + 1, this.length - 1).split(",")
val fieldStrings = fields.map { s -> " ${s.trim()},<br>" }.toMutableList()
if (fieldStrings.isNotEmpty()) {
fieldStrings[fieldStrings.lastIndex] = " ${fields.last().trim()}<br>"
}
return "CREATE TABLE $name (<br/>" +
fieldStrings.joinToString("") +
")"
}
private fun IHTTPSession.queryParam(name: String): String? {
if (queryParameterString == null) {
return null
}
val params: Map<String, String> = queryParameterString
.split("&")
.mapNotNull { part ->
val parts = part.split("=")
if (parts.size == 2) {
parts[0] to parts[1]
} else {
null
}
}
.toMap()
return params[name]
}
interface PrefixPageData {
val environment: String
val deviceInfo: Map<String, String>
val database: String
val databases: List<String>
val plugins: List<Plugin>
}
data class OverviewPageModel(
override val environment: String,
override val deviceInfo: Map<String, String>,
override val database: String,
override val databases: List<String>,
override val plugins: List<Plugin>,
val tables: List<TableInfo>,
val indices: List<IndexInfo>,
val triggers: List<TriggerInfo>,
val queryResult: QueryResult? = null
) : PrefixPageData
data class BrowsePageModel(
override val environment: String,
override val deviceInfo: Map<String, String>,
override val database: String,
override val databases: List<String>,
override val plugins: List<Plugin>,
val tableNames: List<String>,
val table: String? = null,
val queryResult: QueryResult? = null,
val pagingData: PagingData? = null,
) : PrefixPageData
data class QueryPageModel(
override val environment: String,
override val deviceInfo: Map<String, String>,
override val database: String,
override val databases: List<String>,
override val plugins: List<Plugin>,
val query: String = "",
val queryResult: QueryResult? = null
) : PrefixPageData
data class RecentPageModel(
override val environment: String,
override val deviceInfo: Map<String, String>,
override val database: String,
override val databases: List<String>,
override val plugins: List<Plugin>,
val recentSql: List<RecentQuery>?
) : PrefixPageData
data class PluginPageModel(
override val environment: String,
override val deviceInfo: Map<String, String>,
override val database: String,
override val databases: List<String>,
override val plugins: List<Plugin>,
val activePlugin: Plugin,
val pluginResult: PluginResult
) : PrefixPageData
data class QueryResult(
val columns: List<String>,
val rows: List<List<String>>,
val rowCount: Int = rows.size,
val timeToFirstRow: Long,
val timeToReadRows: Long,
)
data class TableInfo(
val name: String,
val sql: String
)
data class IndexInfo(
val name: String,
val sql: String
)
data class TriggerInfo(
val name: String,
val sql: String
)
data class PagingData(
val rowCount: Int,
val pageSize: Int,
val pageIndex: Int,
val pageCount: Int,
val firstPage: Boolean = pageIndex == 0,
val lastPage: Boolean = pageIndex == pageCount - 1,
val startRow: Int,
val endRow: Int
)
data class QueryItem(
val time: Long,
val query: String
)
data class RecentQuery(
val formattedTime: String,
val query: String
)
}
| gpl-3.0 | 0aec5dda9b20896f507b4897611d2322 | 30.890244 | 157 | 0.653856 | 4.363181 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/options/BoundCompositeConfigurable.kt | 2 | 2139 | // 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.openapi.options
import com.intellij.openapi.util.NlsContexts
import com.intellij.ui.dsl.builder.AlignX
import com.intellij.ui.dsl.builder.Panel
abstract class BoundCompositeConfigurable<T : UnnamedConfigurable>(
@NlsContexts.ConfigurableName displayName: String,
helpTopic: String? = null
) : BoundConfigurable(displayName, helpTopic) {
abstract fun createConfigurables(): List<T>
private val lazyConfigurables: Lazy<List<T>> = lazy { createConfigurables() }
val configurables get() = lazyConfigurables.value
private val plainConfigurables get() = lazyConfigurables.value.filter { it !is UiDslConfigurable && it !is UiDslUnnamedConfigurable }
override fun isModified(): Boolean {
return super.isModified() || plainConfigurables.any { it.isModified }
}
override fun reset() {
super.reset()
for (configurable in plainConfigurables) {
configurable.reset()
}
}
override fun apply() {
super.apply()
for (configurable in plainConfigurables) {
configurable.apply()
}
}
override fun disposeUIResources() {
super.disposeUIResources()
if (lazyConfigurables.isInitialized()) {
for (configurable in configurables) {
configurable.disposeUIResources()
}
}
}
protected fun Panel.appendDslConfigurable(configurable: UnnamedConfigurable) {
if (configurable is UiDslUnnamedConfigurable) {
val builder = this
with(configurable) {
builder.createContent()
}
}
else {
val panel = configurable.createComponent()
if (panel != null) {
row {
cell(panel)
.align(AlignX.FILL)
}
}
}
}
}
abstract class BoundCompositeSearchableConfigurable<T : UnnamedConfigurable>(@NlsContexts.ConfigurableName displayName: String, helpTopic: String, private val _id: String = helpTopic)
: BoundCompositeConfigurable<T>(displayName, helpTopic), SearchableConfigurable {
override fun getId(): String = _id
}
| apache-2.0 | 834a62b5887bffe58b0a1b14a1866459 | 30.455882 | 183 | 0.708742 | 4.62987 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/code-insight/inspections-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/inspections/RedundantElvisReturnNullInspection.kt | 3 | 3339 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.inspections
import com.intellij.openapi.util.TextRange
import com.intellij.psi.util.elementType
import org.jetbrains.kotlin.idea.base.psi.safeDeparenthesize
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.*
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtReturnExpression
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.psi.stubs.elements.KtStubElementTypes
class RedundantElvisReturnNullInspection :
AbstractKotlinApplicatorBasedInspection<KtBinaryExpression, RedundantElvisReturnNullInspection.RedundantElvisReturnNullInspectionInput>(
KtBinaryExpression::class
) {
class RedundantElvisReturnNullInspectionInput : KotlinApplicatorInput
override fun getApplicabilityRange() = applicabilityRanges { binaryExpression: KtBinaryExpression ->
val right =
binaryExpression.right?.safeDeparenthesize()?.takeIf { it == binaryExpression.right }
?: return@applicabilityRanges emptyList()
listOf(TextRange(binaryExpression.operationReference.startOffset, right.endOffset).shiftLeft(binaryExpression.startOffset))
}
override fun getInputProvider() = inputProvider { binaryExpression: KtBinaryExpression ->
// Returns null if LHS of the binary expression is not nullable.
if (binaryExpression.left?.getKtType()?.isMarkedNullable != true) return@inputProvider null
return@inputProvider RedundantElvisReturnNullInspectionInput()
}
override fun getApplicator() =
applicator<KtBinaryExpression, RedundantElvisReturnNullInspection.RedundantElvisReturnNullInspectionInput> {
familyName(KotlinBundle.lazyMessage(("remove.redundant.elvis.return.null.text")))
actionName(KotlinBundle.lazyMessage(("inspection.redundant.elvis.return.null.descriptor")))
isApplicableByPsi { binaryExpression ->
// The binary expression must be in a form of "return <left expression> ?: return null".
val returnExpression = binaryExpression.right as? KtReturnExpression ?: return@isApplicableByPsi false
// Returns false if RHS is not "return null".
val deparenthesizedReturnExpression =
returnExpression.returnedExpression?.safeDeparenthesize() ?: return@isApplicableByPsi false
if (deparenthesizedReturnExpression.elementType != KtStubElementTypes.NULL) return@isApplicableByPsi false
val isTargetOfReturn =
binaryExpression == binaryExpression.getStrictParentOfType<KtReturnExpression>()?.returnedExpression?.safeDeparenthesize()
isTargetOfReturn && binaryExpression.operationToken == KtTokens.ELVIS
}
applyTo { binaryExpression, _ ->
val left = binaryExpression.left ?: return@applyTo
binaryExpression.replace(left)
}
}
} | apache-2.0 | 3afd5fe783b0255ed24e13708b7f52c2 | 56.586207 | 142 | 0.746331 | 5.776817 | false | false | false | false |
shogo4405/HaishinKit.java | haishinkit/src/main/java/com/haishinkit/graphics/GlPixelTransform.kt | 1 | 4137 | package com.haishinkit.graphics
import android.content.res.AssetManager
import android.graphics.SurfaceTexture
import android.os.Handler
import android.util.Log
import android.util.Size
import android.view.Surface
import com.haishinkit.codec.util.DefaultFpsController
import com.haishinkit.codec.util.FpsController
import com.haishinkit.codec.util.FpsControllerFactory
import com.haishinkit.graphics.filter.VideoEffect
import com.haishinkit.graphics.gles.GlKernel
import com.haishinkit.graphics.gles.GlTexture
internal class GlPixelTransform(
override var listener: PixelTransform.Listener? = null,
) : PixelTransform, SurfaceTexture.OnFrameAvailableListener {
override var fpsControllerClass: Class<*>? = null
set(value) {
if (field == value) {
return
}
field = value
fpsController = FpsControllerFactory.shared.create(value)
}
override var surface: Surface?
get() = kernel.surface
set(value) {
kernel.surface = value
listener?.onPixelTransformSurfaceChanged(this, value)
}
override var imageOrientation: ImageOrientation
get() = kernel.imageOrientation
set(value) {
kernel.imageOrientation = value
}
override var videoGravity: VideoGravity
get() = kernel.videoGravity
set(value) {
kernel.videoGravity = value
}
override var videoEffect: VideoEffect
get() = kernel.videoEffect
set(value) {
kernel.videoEffect = value
}
override var extent: Size
get() = kernel.extent
set(value) {
kernel.extent = value
}
override var surfaceRotation: Int
get() = kernel.surfaceRotation
set(value) {
kernel.surfaceRotation = value
}
override var resampleFilter: ResampleFilter
get() = kernel.resampleFilter
set(value) {
kernel.resampleFilter = value
}
override var expectedOrientationSynchronize: Boolean
get() = kernel.expectedOrientationSynchronize
set(value) {
kernel.expectedOrientationSynchronize = value
}
override var assetManager: AssetManager?
get() = kernel.assetManager
set(value) {
kernel.assetManager = value
}
var handler: Handler? = null
set(value) {
field?.post { kernel.tearDown() }
value?.post { kernel.setUp() }
field = value
}
private var kernel: GlKernel = GlKernel()
private var fpsController: FpsController = DefaultFpsController.instance
private var texture: GlTexture? = null
set(value) {
field?.release()
field = value
}
override fun createInputSurface(width: Int, height: Int, format: Int) {
if (texture != null && texture?.isValid(width, height) == true) {
texture?.surface?.let {
listener?.onPixelTransformInputSurfaceCreated(this, it)
}
return
}
texture = GlTexture.create(width, height).apply {
setOnFrameAvailableListener(this@GlPixelTransform, handler)
surface?.let {
listener?.onPixelTransformInputSurfaceCreated(this@GlPixelTransform, it)
}
}
}
override fun onFrameAvailable(surfaceTexture: SurfaceTexture) {
if (surface == null) {
return
}
listener?.onPixelTransformImageAvailable(this)
texture?.updateTexImage()
var timestamp = surfaceTexture.timestamp
if (timestamp <= 0L) {
return
}
if (fpsController.advanced(timestamp)) {
timestamp = fpsController.timestamp(timestamp)
texture?.let {
kernel.render(it.id, it.extent, timestamp)
}
}
}
override fun dispose() {
texture = null
listener = null
kernel.tearDown()
}
companion object {
private val TAG = GlPixelTransform::class.java.simpleName
}
}
| bsd-3-clause | f11f8e3a4ef01dccda23406e30b02913 | 30.823077 | 88 | 0.615422 | 4.844262 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/android/intention/redoParcelable/oldField.kt | 14 | 1182 | // INTENTION_CLASS: org.jetbrains.kotlin.android.intention.RedoParcelableAction
import android.os.Parcel
import android.os.Parcelable
class <caret>SomeData(parcel: Parcel) : Parcelable {
var count = 0
init {
oldField = parcel.readInt()
field9 = parcel.readByte() != 0.toByte()
goodArray = parcel.createTypedArray(SuperParcelable)
goodList = parcel.createTypedArrayList(SuperParcelable)
parcelableProperty = parcel.readParcelable(SuperParcelable::class.java.classLoader)
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(oldField)
parcel.writeByte(if (field9) 1 else 0)
parcel.writeTypedArray(goodArray, flags)
parcel.writeTypedList(goodList)
parcel.writeParcelable(parcelableProperty, flags)
}
override fun describeContents(): Int {
return 42
}
companion object CREATOR : Parcelable.Creator<SomeData> {
override fun createFromParcel(parcel: Parcel): SomeData {
return SomeData(parcel)
}
override fun newArray(size: Int): Array<SomeData?> {
return arrayOfNulls(size)
}
}
} | apache-2.0 | 3bf226e0c7d6d3aa6aa7beda39839bd3 | 30.972973 | 91 | 0.675127 | 4.635294 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/model/psi/labels/LinkLabelSymbolReference.kt | 7 | 1987 | package org.intellij.plugins.markdown.model.psi.labels
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.model.Symbol
import com.intellij.model.psi.PsiCompletableReference
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.intellij.plugins.markdown.lang.psi.MarkdownRecursiveElementVisitor
import org.intellij.plugins.markdown.lang.psi.impl.MarkdownLinkLabel
import org.intellij.plugins.markdown.model.psi.MarkdownPsiSymbolReferenceBase
import org.intellij.plugins.markdown.model.psi.labels.LinkLabelSymbol.Companion.isDeclaration
internal class LinkLabelSymbolReference(
element: PsiElement,
rangeInElement: TextRange,
private val text: String,
): MarkdownPsiSymbolReferenceBase(element, rangeInElement), PsiCompletableReference {
override fun resolveReference(): Collection<Symbol> {
val file = element.containingFile
val declarations = file.collectLinkLabels().asSequence().filter { it.isDeclaration }
val matchingDeclarations = declarations.filter { it.text == text }
val symbols = matchingDeclarations.mapNotNull { LinkLabelSymbol.createPointer(it)?.dereference() }
return symbols.toList()
}
override fun getCompletionVariants(): Collection<LookupElement> {
val file = element.containingFile
val labels = file.collectLinkLabels().asSequence()
return labels.map { LookupElementBuilder.create(it) }.toList()
}
companion object {
private fun PsiFile.collectLinkLabels(): List<MarkdownLinkLabel> {
val elements = arrayListOf<MarkdownLinkLabel>()
val visitor = object: MarkdownRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element is MarkdownLinkLabel) {
elements.add(element)
}
super.visitElement(element)
}
}
accept(visitor)
return elements
}
}
}
| apache-2.0 | f760fe3710c808b3a04bcf9afb0b0eb9 | 39.55102 | 102 | 0.767992 | 4.753589 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/savedPatches/SavedPatchesEditorDiffPreview.kt | 5 | 1491 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes.savedPatches
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vcs.changes.ui.SimpleTreeEditorDiffPreview
import com.intellij.openapi.wm.IdeFocusManager
import java.awt.Component
import javax.swing.JComponent
abstract class SavedPatchesEditorDiffPreview(diffProcessor: SavedPatchesDiffPreview, tree: ChangesTree, targetComponent: JComponent,
private val focusMainComponent: (Component?) -> Unit)
: SimpleTreeEditorDiffPreview(diffProcessor, tree, targetComponent, false) {
private var lastFocusOwner: Component? = null
init {
Disposer.register(diffProcessor, Disposable { lastFocusOwner = null })
}
override fun openPreview(requestFocus: Boolean): Boolean {
lastFocusOwner = IdeFocusManager.getInstance(project).focusOwner
return super.openPreview(requestFocus)
}
override fun returnFocusToTree() {
val focusOwner = lastFocusOwner
lastFocusOwner = null
focusMainComponent(focusOwner)
}
override fun updateDiffAction(event: AnActionEvent) {
event.presentation.isVisible = true
event.presentation.isEnabled = changeViewProcessor.iterateAllChanges().any()
}
}
| apache-2.0 | 5eb0d96648ba51c116a2f317f216ad2f | 39.297297 | 132 | 0.777331 | 4.840909 | false | false | false | false |
Unic8/retroauth | retroauth/src/test/java/com/andretietz/retroauth/UtilsTest.kt | 1 | 1865 | package com.andretietz.retroauth
import okhttp3.Request
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import java.util.HashMap
@RunWith(MockitoJUnitRunner::class)
class UtilsTest {
@Test
fun createUniqueIdentifier() {
val map = HashMap<Int, Request>()
var request = Request.Builder()
.url("http://www.google.com/test/request1")
.build()
map[Utils.createUniqueIdentifier(request)] = request
request = Request.Builder()
.method("GET", null)
.url("http://www.google.com/test/request1")
.build()
map[Utils.createUniqueIdentifier(request)] = request
request = Request.Builder()
.url("http://www.google.com/test/request2")
.build()
map[Utils.createUniqueIdentifier(request)] = request
request = Request.Builder()
.method("GET", null)
.url("http://www.google.com/test/request2")
.build()
map[Utils.createUniqueIdentifier(request)] = request
Assert.assertEquals(2, map.size.toLong())
}
@Test
fun check() {
val request1 = Request.Builder()
.method("GET", null)
.header("foo", "bar")
.url("http://www.google.com/test/request2")
.build()
val request2 = Request.Builder()
.method("GET", null)
.header("var", "foo")
.url("http://www.google.com/test/request2")
.build()
val request3 = Request.Builder()
.method("GET", null)
.header("var", "foo")
.tag("fpp")
.url("http://www.google.com/test/request2")
.build()
val id1 = Utils.createUniqueIdentifier(request1)
val id2 = Utils.createUniqueIdentifier(request2)
val id3 = Utils.createUniqueIdentifier(request3)
/** Headers should not effect the id **/
Assert.assertTrue(id1 == id2)
Assert.assertTrue(id2 == id3)
}
}
| apache-2.0 | 49d6b430d4e0e7656597935dc91dfec3 | 24.902778 | 56 | 0.646113 | 3.621359 | false | true | false | false |
smmribeiro/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/inference/TypePositionConstraint.kt | 12 | 1236 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors.inference
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiType
import com.intellij.psi.impl.source.resolve.graphInference.constraints.ConstraintFormula
import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter
class TypePositionConstraint(
private val expectedType: ExpectedType,
private val rightType: PsiType?,
private val context: PsiElement
) : GrConstraintFormula() {
override fun reduce(session: GroovyInferenceSession, constraints: MutableList<in ConstraintFormula>): Boolean {
if (rightType != null) {
for (extension in GrTypeConverter.EP_NAME.extensionList) {
if (!extension.isApplicableTo(expectedType.position)) {
continue
}
val reduced = extension.reduceTypeConstraint(expectedType.type, rightType, expectedType.position, context)
if (reduced != null) {
constraints += reduced
return true
}
}
}
constraints += TypeConstraint(expectedType.type, rightType, context)
return true
}
}
| apache-2.0 | 461631047c601e8a1adf7497d91618b7 | 38.870968 | 140 | 0.739482 | 4.69962 | false | false | false | false |
Drepic26/CouponCodes3 | core/src/main/kotlin/tech/feldman/couponcodes/core/commands/SimpleCommandHandler.kt | 2 | 5485 | /**
* The MIT License
* Copyright (c) 2015 Nicholas Feldman (AngrySoundTech)
* <p/>
* 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:
* <p/>
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* <p/>
* 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 tech.feldman.couponcodes.core.commands
import tech.feldman.couponcodes.api.CouponCodes
import tech.feldman.couponcodes.api.command.CommandHandler
import tech.feldman.couponcodes.api.command.CommandSender
import tech.feldman.couponcodes.core.commands.runnables.*
import tech.feldman.couponcodes.core.util.LocaleHandler
class SimpleCommandHandler : CommandHandler {
override fun handleCommand(command: String, args: Array<String>, sender: CommandSender): Boolean {
if (command.equals("coupon", ignoreCase = true)) {
when (command.toLowerCase()) {
"help" -> help(sender)
"add" -> if (checkPermission(sender, "cc.add"))
CouponCodes.getModTransformer().scheduleRunnable(AddCommand(sender, args))
"time" -> if (checkPermission(sender, "cc.time"))
CouponCodes.getModTransformer().scheduleRunnable(TimeCommand(sender, args))
"uses" -> if (checkPermission(sender, "cc.uses"))
CouponCodes.getModTransformer().scheduleRunnable(UsesCommand(sender, args))
"remove" -> if (checkPermission(sender, "cc.remove"))
CouponCodes.getModTransformer().scheduleRunnable(RemoveCommand(sender, args))
"redeem" -> if (checkPermission(sender, "cc.redeem"))
CouponCodes.getModTransformer().scheduleRunnable(RedeemCommand(sender, args))
"list" -> if (checkPermission(sender, "cc.list"))
CouponCodes.getModTransformer().scheduleRunnable(ListCommand(sender, args))
"info" -> if (checkPermission(sender, "cc.info"))
CouponCodes.getModTransformer().scheduleRunnable(InfoCommand(sender, args))
else -> return false
}
return true
} else
return false
}
private fun checkPermission(sender: CommandSender, node: String): Boolean {
if (sender.hasPermission(node))
return true
else
sender.sendMessage(LocaleHandler.getString("Command.NoPermission"))
return false
}
override fun handleCommand(command: String, sender: CommandSender): Boolean {
if (command.equals("coupon", ignoreCase = true)) {
help(sender)
return true
} else
return false
}
override fun handleCommandEvent(sender: CommandSender, message: String): Boolean {
var message = message
message = trimCommand(message)
val indexOfSpace = message.indexOf(" ")
if (indexOfSpace != -1) {
val command = message.substring(0, indexOfSpace)
val args = message.substring(indexOfSpace + 1).split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
return handleCommand(command, args, sender)
} else {
return handleCommand(message, sender)
}
}
private fun trimCommand(command: String): String {
var command = command
if (command.startsWith("/")) {
if (command.length == 1) {
return ""
} else {
command = command.substring(1)
}
}
return command.trim { it <= ' ' }
}
private fun help(sender: CommandSender) {
sender.sendMessage(LocaleHandler.getString("Command.Help.Header"))
sender.sendMessage(LocaleHandler.getString("Command.Help.Instructions"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddItem"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddEcon"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddRank"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddXp"))
sender.sendMessage(LocaleHandler.getString("Command.Help.AddCmd"))
sender.sendMessage(LocaleHandler.getString("Command.Help.Time"))
sender.sendMessage(LocaleHandler.getString("Command.Help.Uses"))
sender.sendMessage(LocaleHandler.getString("Command.Help.Redeem"))
sender.sendMessage(LocaleHandler.getString("Command.Help.Remove"))
sender.sendMessage(LocaleHandler.getString("Command.Help.List"))
sender.sendMessage(LocaleHandler.getString("Command.Help.Info"))
}
}
| mit | 555fbf2ad746f97d075e12bdbd29f01b | 46.284483 | 125 | 0.664904 | 4.64044 | false | false | false | false |
jbmlaird/DiscogsBrowser | app/src/testShared/bj/vinylbrowser/home/ViewedReleaseFactory.kt | 1 | 669 | package bj.vinylbrowser.home
import bj.vinylbrowser.greendao.ViewedRelease
/**
* Created by Josh Laird on 19/05/2017.
*/
object ViewedReleaseFactory {
@JvmStatic fun buildViewedReleases(number: Int): List<ViewedRelease> {
return (1..number).map { buildViewedRelease(it) }
}
private fun buildViewedRelease(number: Int): ViewedRelease {
val viewedRelease = ViewedRelease()
viewedRelease.style = "techno"
viewedRelease.releaseName = "viewedReleaseName" + number
viewedRelease.artists = "viewedReleaseArtists" + number
viewedRelease.releaseId = "viewedReleaseId" + number
return viewedRelease
}
} | mit | e0824be611863fc81ab696e31ab8ab88 | 30.904762 | 74 | 0.704036 | 4.079268 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/navtab/MoreBottomSheetFragmentUnitTests.kt | 1 | 2907 | package fr.free.nrw.commons.navtab
import android.content.Context
import android.os.Looper
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import fr.free.nrw.commons.TestCommonsApplication
import fr.free.nrw.commons.profile.ProfileActivity
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.Shadows
import org.robolectric.annotation.Config
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
@LooperMode(LooperMode.Mode.PAUSED)
class MoreBottomSheetFragmentUnitTests {
private lateinit var fragment: MoreBottomSheetFragment
private lateinit var context: Context
@Before
fun setUp() {
context = RuntimeEnvironment.application.applicationContext
val activity = Robolectric.buildActivity(ProfileActivity::class.java).create().get()
fragment = MoreBottomSheetFragment()
val fragmentManager: FragmentManager = activity.supportFragmentManager
val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
fragmentTransaction.add(fragment, null)
fragmentTransaction.commit()
}
@Test
@Throws(Exception::class)
fun checkFragmentNotNull() {
Assert.assertNotNull(fragment)
}
@Test
@Throws(Exception::class)
fun testOnAttach() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onAttach(context)
}
@Test
@Throws(Exception::class)
fun testOnLogoutClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onLogoutClicked()
}
@Test
@Throws(Exception::class)
fun testOnFeedbackClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onFeedbackClicked()
}
@Test
@Throws(Exception::class)
fun testOnAboutClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onAboutClicked()
}
@Test
@Throws(Exception::class)
fun testOnTutorialClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onTutorialClicked()
}
@Test
@Throws(Exception::class)
fun testOnSettingsClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onSettingsClicked()
}
@Test
@Throws(Exception::class)
fun testOnProfileClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onProfileClicked()
}
@Test
@Throws(Exception::class)
fun testOnPeerReviewClicked() {
Shadows.shadowOf(Looper.getMainLooper()).idle()
fragment.onPeerReviewClicked()
}
} | apache-2.0 | f6213527b6c5585d4086cf21bd009f0a | 26.695238 | 92 | 0.715858 | 4.789127 | false | true | false | false |
joaomneto/TitanCompanion | src/main/java/pt/joaomneto/titancompanion/LoadAdventureActivity.kt | 1 | 6221 | package pt.joaomneto.titancompanion
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.widget.AdapterView
import android.widget.AdapterView.OnItemLongClickListener
import android.widget.ArrayAdapter
import android.widget.ListView
import pt.joaomneto.titancompanion.adapter.Savegame
import pt.joaomneto.titancompanion.adapter.SavegameListAdapter
import pt.joaomneto.titancompanion.consts.Constants
import pt.joaomneto.titancompanion.consts.FightingFantasyGamebook
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.text.SimpleDateFormat
import java.util.ArrayList
import java.util.Date
class LoadAdventureActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_load_adventure)
val listview = findViewById<ListView>(R.id.adventureListView)
val baseDir = File(filesDir, "ffgbutil")
var fileList: Array<String>? = baseDir.list()
if (fileList == null)
fileList = arrayOf()
val files = ArrayList<Savegame>()
for (string in fileList) {
if (string.startsWith("save")) {
val f = File(baseDir, string)
files.add(Savegame(string, Date(f.lastModified())))
}
}
val adapter = SavegameListAdapter(this, files)
listview.adapter = adapter
listview.onItemClickListener = AdapterView.OnItemClickListener { _, _, position, _ ->
val dir = File(baseDir, files[position].filename)
val f = File(dir, "temp.xml")
if (f.exists())
f.delete()
val initialSavePoints = dir
.listFiles { _, filename -> filename.startsWith("initial") }
?: emptyArray()
val numericSavePoints = dir
.listFiles { _, filename ->
!filename.startsWith("initial") && !filename.startsWith("exception")
}
?: emptyArray()
val savepointFiles = numericSavePoints
.sortedBy { it.lastModified() }
.reversed()
.plus(
initialSavePoints.sortedBy { it.lastModified() }
)
val names = savepointFiles
.map { it.name.dropLast(4) }
.toTypedArray()
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.chooseSavePoint)
builder.setItems(names) { _, which ->
var gamebook: FightingFantasyGamebook? = null
try {
val bufferedReader = BufferedReader(
FileReader(savepointFiles[which])
)
while (bufferedReader.ready()) {
val line = bufferedReader.readLine()
if (line.startsWith("gamebook=")) {
val gbs =
line.split("=".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()[1]
val numbericGbs = gbs.toIntOrNull()
gamebook = if (numbericGbs != null)
FightingFantasyGamebook.values()[numbericGbs]
else
FightingFantasyGamebook.valueOf(gbs)
break
}
}
bufferedReader.close()
val intent = Intent(
this,
Constants
.getRunActivity(this, gamebook!!)
)
intent.putExtra(
ADVENTURE_SAVEGAME_CONTENT,
File(File(File(filesDir, "ffgbutil"), dir.name), savepointFiles[which].name).readText()
)
intent.putExtra(
ADVENTURE_NAME,
dir.name
)
startActivity(intent)
} catch (e: Exception) {
e.printStackTrace()
}
}
val alert = builder.create()
alert.show()
}
listview.onItemLongClickListener = OnItemLongClickListener { _, _, position, _ ->
val builder = AlertDialog.Builder(this)
builder.setTitle(R.string.deleteSavegame)
.setCancelable(false)
.setNegativeButton(
R.string.close
) { dialog, _ -> dialog.cancel() }
builder.setPositiveButton(
R.string.ok
) { _, _ ->
val file = files[position].filename
val f = File(baseDir, file)
if (deleteDirectory(f)) {
files.removeAt(position)
(
listview
.adapter as ArrayAdapter<String>
)
.notifyDataSetChanged()
}
}
val alert = builder.create()
alert.show()
true
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.gamebook_list, menu)
return true
}
companion object {
val ADVENTURE_SAVEGAME_CONTENT = "ADVENTURE_SAVEGAME_CONTENT"
val ADVENTURE_NAME = "ADVENTURE_NAME"
val DATE_FORMAT = SimpleDateFormat("yyyy-MM-dd HH:mm")
fun deleteDirectory(path: File): Boolean {
if (path.exists()) {
val files = path.listFiles()
for (i in files.indices) {
if (files[i].isDirectory) {
deleteDirectory(files[i])
} else {
files[i].delete()
}
}
}
return path.delete()
}
}
}
| lgpl-3.0 | 1adc4b89d1d54062296a67c475eb9633 | 33.561111 | 111 | 0.509082 | 5.515071 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/MigLayoutBuilder.kt | 6 | 12626 | /*
* 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.ui.layout
import com.intellij.codeInspection.SmartHashMap
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.ActionToolbar
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.ToggleAction
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.openapi.ui.OnePixelDivider
import com.intellij.ui.SeparatorComponent
import com.intellij.ui.TextFieldWithHistory
import com.intellij.ui.TextFieldWithHistoryWithBrowseButton
import com.intellij.ui.components.Label
import com.intellij.ui.components.noteComponent
import com.intellij.util.SmartList
import net.miginfocom.layout.*
import net.miginfocom.swing.MigLayout
import java.awt.Component
import java.awt.Container
import javax.swing.*
import javax.swing.text.JTextComponent
/**
* Automatically add `growX` to JTextComponent (see isAddGrowX).
* Automatically add `grow` and `push` to JPanel (see isAddGrowX).
*/
internal class MigLayoutBuilder : LayoutBuilderImpl {
private val rows = SmartList<MigLayoutRow>()
private val componentConstraints: MutableMap<Component, CC> = SmartHashMap()
override fun newRow(label: JLabel?, buttonGroup: ButtonGroup?, separated: Boolean, indented: Boolean): Row {
if (separated) {
val row = MigLayoutRow(componentConstraints, this, noGrid = true, separated = true)
rows.add(row)
row.apply { SeparatorComponent(0, OnePixelDivider.BACKGROUND, null)() }
}
val row = MigLayoutRow(componentConstraints, this, label != null, buttonGroup = buttonGroup, indented = indented)
rows.add(row)
label?.let { row.apply { label() } }
return row
}
override fun noteRow(text: String) {
// add empty row as top gap
newRow()
val row = MigLayoutRow(componentConstraints, this, noGrid = true)
rows.add(row)
row.apply { noteComponent(text)() }
}
override fun build(container: Container, layoutConstraints: Array<out LCFlags>) {
val labeled = rows.firstOrNull({ it.labeled && !it.indented }) != null
var gapTop = -1
val lc = c()
if (layoutConstraints.isEmpty()) {
lc.fillX()
// not fillY because it leads to enormously large cells - we use cc `push` in addition to cc `grow` as a more robust and easy solution
}
else {
lc.apply(layoutConstraints)
}
lc.noVisualPadding()
lc.hideMode = 3
container.layout = MigLayout(lc)
val noGrid = layoutConstraints.contains(LCFlags.noGrid)
for (row in rows) {
val lastComponent = row.components.lastOrNull()
if (lastComponent == null) {
if (row === rows.first()) {
// do not add gap for the first row
continue
}
// https://goo.gl/LDylKm
// gap = 10u where u = 4px
gapTop = VERTICAL_GAP * 3
}
var isSplitRequired = true
for ((index, component) in row.components.withIndex()) {
// MigLayout in any case always creates CC, so, create instance even if it is not required
val cc = componentConstraints.get(component) ?: CC()
if (gapTop != -1) {
cc.vertical.gapBefore = gapToBoundSize(gapTop, false)
gapTop = -1
}
addGrowIfNeed(cc, component)
if (!noGrid) {
if (component === lastComponent) {
isSplitRequired = false
cc.wrap()
}
if (row.noGrid) {
if (component === row.components.first()) {
// rowConstraints.noGrid() doesn't work correctly
cc.spanX()
if (row.separated) {
cc.vertical.gapBefore = gapToBoundSize(VERTICAL_GAP * 3, false)
cc.vertical.gapAfter = gapToBoundSize(VERTICAL_GAP * 2, false)
}
}
}
else {
var isSkippableComponent = true
if (component === row.components.first()) {
if (row.indented) {
cc.horizontal.gapBefore = gapToBoundSize(HORIZONTAL_GAP * 3, true)
}
if (labeled) {
if (row.labeled) {
isSkippableComponent = false
}
else {
cc.skip()
}
}
}
if (isSkippableComponent) {
if (isSplitRequired) {
isSplitRequired = false
cc.split()
}
// do not add gap if next component is gear action button
if (component !== lastComponent && !row.components.get(index + 1).let { it is JLabel && it.icon === AllIcons.General.Gear }) {
cc.horizontal.gapAfter = gapToBoundSize(HORIZONTAL_GAP * 2, true)
}
}
}
if (index >= row.rightIndex) {
cc.horizontal.gapBefore = BoundSize(null, null, null, true, null)
}
}
container.add(component, cc)
}
}
// do not hold components
componentConstraints.clear()
}
}
private fun addGrowIfNeed(cc: CC, component: Component) {
if (component is TextFieldWithHistory || component is TextFieldWithHistoryWithBrowseButton) {
cc.minWidth("350")
cc.growX()
}
else if (component is JTextComponent || component is SeparatorComponent || component is ComponentWithBrowseButton<*>) {
cc.growX()
}
else if (component is JPanel && component.componentCount == 1 &&
(component.getComponent(0) as? JComponent)?.getClientProperty(ActionToolbar.ACTION_TOOLBAR_PROPERTY_KEY) != null) {
cc.grow().push()
}
}
private class MigLayoutRow(private val componentConstraints: MutableMap<Component, CC>,
override val builder: LayoutBuilderImpl,
val labeled: Boolean = false,
val noGrid: Boolean = false,
private val buttonGroup: ButtonGroup? = null,
val separated: Boolean = false,
val indented: Boolean = false) : Row() {
val components = SmartList<Component>()
var rightIndex = Int.MAX_VALUE
private var _subRows: MutableList<Row>? = null
override val subRows: List<Row>
get() = _subRows ?: emptyList()
override var enabled: Boolean = true
get() = field
set(value) {
if (field == value) {
return
}
field = value
for (c in components) {
c.isEnabled = value
}
}
override var visible: Boolean = true
get() = field
set(value) {
if (field == value) {
return
}
field = value
for (c in components) {
c.isVisible = value
}
}
override var subRowsEnabled: Boolean = true
get() = field
set(value) {
if (field == value) {
return
}
field = value
_subRows?.forEach { it.enabled = value }
}
override var subRowsVisible: Boolean = true
get() = field
set(value) {
if (field == value) {
return
}
field = value
_subRows?.forEach { it.visible = value }
}
override operator fun JComponent.invoke(vararg constraints: CCFlags, gapLeft: Int, growPolicy: GrowPolicy?) {
addComponent(this, constraints, gapLeft = gapLeft, growPolicy = growPolicy)
}
private fun addComponent(component: Component, constraints: Array<out CCFlags>, gapLeft: Int, growPolicy: GrowPolicy?) {
if (buttonGroup != null && component is JToggleButton) {
buttonGroup.add(component)
}
createComponentConstraints(constraints, gapLeft = gapLeft, growPolicy = growPolicy)?.let {
componentConstraints.put(component, it)
}
components.add(component)
}
override fun alignRight() {
if (rightIndex != Int.MAX_VALUE) {
throw IllegalStateException("right allowed only once")
}
rightIndex = components.size
}
override fun createRow(label: String?): Row {
val row = builder.newRow(label?.let { Label(it) }, indented = true)
if (_subRows == null) {
_subRows = SmartList()
}
_subRows!!.add(row)
return row
}
}
private fun createComponentConstraints(constraints: Array<out CCFlags>? = null,
gapLeft: Int = 0,
gapAfter: Int = 0,
gapTop: Int = 0,
gapBottom: Int = 0,
split: Int = -1,
growPolicy: GrowPolicy?): CC? {
var _cc = constraints?.create()
fun cc(): CC {
if (_cc == null) {
_cc = CC()
}
return _cc!!
}
if (gapLeft != 0) {
cc().horizontal.gapBefore = gapToBoundSize(gapLeft, true)
}
if (gapAfter != 0) {
cc().horizontal.gapAfter = gapToBoundSize(gapAfter, true)
}
if (gapTop != 0) {
cc().vertical.gapBefore = gapToBoundSize(gapTop, false)
}
if (gapBottom != 0) {
cc().vertical.gapAfter = gapToBoundSize(gapBottom, false)
}
if (split != -1) {
cc().split = split
}
if (growPolicy == GrowPolicy.SHORT_TEXT) {
cc().maxWidth("210")
}
else if (growPolicy == GrowPolicy.MEDIUM_TEXT) {
cc().minWidth("210")
cc().maxWidth("350")
}
return _cc
}
private fun gapToBoundSize(value: Int, isHorizontal: Boolean): BoundSize {
val unitValue = UnitValue(value.toFloat(), "", isHorizontal, UnitValue.STATIC, null)
return BoundSize(unitValue, unitValue, null, false, null)
}
// default values differs to MigLayout - IntelliJ Platform defaults are used
// see com.intellij.uiDesigner.core.AbstractLayout.DEFAULT_HGAP and DEFAULT_VGAP (multiplied by 2 to achieve the same look (it seems in terms of MigLayout gap is both left and right space))
private fun c(insets: String? = "0", gridGapX: Int = HORIZONTAL_GAP * 2, gridGapY: Int = VERTICAL_GAP): LC {
// no setter for gap, so, create string to parse
val lc = LC()
lc.gridGapX = gapToBoundSize(gridGapX, true)
lc.gridGapY = gapToBoundSize(gridGapY, false)
insets?.let {
lc.insets(it)
}
return lc
}
private fun Array<out CCFlags>.create() = if (isEmpty()) null else CC().apply(this)
private fun CC.apply(flags: Array<out CCFlags>): CC {
for (flag in flags) {
when (flag) {
//CCFlags.wrap -> isWrap = true
CCFlags.grow -> grow()
CCFlags.growX -> growX()
CCFlags.growY -> growY()
// If you have more than one component in a cell the alignment keywords will not work since the behavior would be indeterministic.
// You can however accomplish the same thing by setting a gap before and/or after the components.
// That gap may have a minimum size of 0 and a preferred size of a really large value to create a "pushing" gap.
// There is even a keyword for this: "push". So "gapleft push" will be the same as "align right" and work for multi-component cells as well.
//CCFlags.right -> horizontal.gapBefore = BoundSize(null, null, null, true, null)
CCFlags.push -> push()
CCFlags.pushX -> pushX()
CCFlags.pushY -> pushY()
//CCFlags.span -> span()
//CCFlags.spanX -> spanX()
//CCFlags.spanY -> spanY()
//CCFlags.split -> split()
//CCFlags.skip -> skip()
}
}
return this
}
private fun LC.apply(flags: Array<out LCFlags>): LC {
for (flag in flags) {
when (flag) {
LCFlags.noGrid -> isNoGrid = true
LCFlags.flowY -> isFlowX = false
LCFlags.fill -> fill()
LCFlags.fillX -> isFillX = true
LCFlags.fillY -> isFillY = true
LCFlags.lcWrap -> wrapAfter = 0
LCFlags.debug -> debug()
}
}
return this
}
private class DebugMigLayoutAction : ToggleAction(), DumbAware {
private var debugEnabled = false
override fun setSelected(e: AnActionEvent, state: Boolean) {
debugEnabled = state
LayoutUtil.setGlobalDebugMillis(if (debugEnabled) 300 else 0)
}
override fun isSelected(e: AnActionEvent) = debugEnabled
} | apache-2.0 | ea3a36b80c40ff0b6af57d4da0c8911b | 29.948529 | 189 | 0.620624 | 4.316581 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/activity/util/RequestCodes.kt | 2 | 1077 | /*
* Copyright 2018 New Vector 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 im.vector.activity.util
const val FALLBACK_AUTHENTICATION_ACTIVITY_REQUEST_CODE = 314
const val CAPTCHA_CREATION_ACTIVITY_REQUEST_CODE = 316
const val TERMS_CREATION_ACTIVITY_REQUEST_CODE = 317
const val STICKER_PICKER_ACTIVITY_REQUEST_CODE = 12000
const val INTEGRATION_MANAGER_ACTIVITY_REQUEST_CODE = 13000
//const val BATTERY_OPTIMIZATION_FCM_REQUEST_CODE = 14000
const val BATTERY_OPTIMIZATION_FDROID_REQUEST_CODE = 14001
const val TERMS_REQUEST_CODE = 15000
| apache-2.0 | 7515d801d2cf707e16f53edf58ed883c | 32.65625 | 75 | 0.767874 | 3.874101 | false | false | false | false |
solokot/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/jobs/NewPhotoFetcher.kt | 1 | 4937 | package com.simplemobiletools.gallery.pro.jobs
import android.annotation.TargetApi
import android.app.job.JobInfo
import android.app.job.JobInfo.TriggerContentUri
import android.app.job.JobParameters
import android.app.job.JobScheduler
import android.app.job.JobService
import android.content.ComponentName
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.provider.MediaStore
import android.provider.MediaStore.Images
import android.provider.MediaStore.Video
import com.simplemobiletools.commons.extensions.getParentPath
import com.simplemobiletools.commons.extensions.getStringValue
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.gallery.pro.extensions.addPathToDB
import com.simplemobiletools.gallery.pro.extensions.updateDirectoryPath
// based on https://developer.android.com/reference/android/app/job/JobInfo.Builder.html#addTriggerContentUri(android.app.job.JobInfo.TriggerContentUri)
@TargetApi(Build.VERSION_CODES.N)
class NewPhotoFetcher : JobService() {
companion object {
const val PHOTO_VIDEO_CONTENT_JOB = 1
private val MEDIA_URI = Uri.parse("content://${MediaStore.AUTHORITY}/")
private val PHOTO_PATH_SEGMENTS = Images.Media.EXTERNAL_CONTENT_URI.pathSegments
private val VIDEO_PATH_SEGMENTS = Video.Media.EXTERNAL_CONTENT_URI.pathSegments
}
private val mHandler = Handler()
private val mWorker = Runnable {
scheduleJob(this@NewPhotoFetcher)
jobFinished(mRunningParams, false)
}
private var mRunningParams: JobParameters? = null
fun scheduleJob(context: Context) {
val componentName = ComponentName(context, NewPhotoFetcher::class.java)
val photoUri = Images.Media.EXTERNAL_CONTENT_URI
val videoUri = Video.Media.EXTERNAL_CONTENT_URI
JobInfo.Builder(PHOTO_VIDEO_CONTENT_JOB, componentName).apply {
addTriggerContentUri(TriggerContentUri(photoUri, TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS))
addTriggerContentUri(TriggerContentUri(videoUri, TriggerContentUri.FLAG_NOTIFY_FOR_DESCENDANTS))
addTriggerContentUri(TriggerContentUri(MEDIA_URI, 0))
try {
context.getSystemService(JobScheduler::class.java)?.schedule(build())
} catch (ignored: Exception) {
}
}
}
fun isScheduled(context: Context): Boolean {
val jobScheduler = context.getSystemService(JobScheduler::class.java)
val jobs = jobScheduler.allPendingJobs
return jobs.any { it.id == PHOTO_VIDEO_CONTENT_JOB }
}
override fun onStartJob(params: JobParameters): Boolean {
mRunningParams = params
ensureBackgroundThread {
val affectedFolderPaths = HashSet<String>()
if (params.triggeredContentAuthorities != null && params.triggeredContentUris != null) {
val ids = arrayListOf<String>()
for (uri in params.triggeredContentUris!!) {
val path = uri.pathSegments
if (path != null && (path.size == PHOTO_PATH_SEGMENTS.size + 1 || path.size == VIDEO_PATH_SEGMENTS.size + 1)) {
ids.add(path[path.size - 1])
}
}
if (ids.isNotEmpty()) {
val selection = StringBuilder()
for (id in ids) {
if (selection.isNotEmpty()) {
selection.append(" OR ")
}
selection.append("${Images.ImageColumns._ID} = '$id'")
}
var cursor: Cursor? = null
try {
val projection = arrayOf(Images.ImageColumns.DATA)
val uris = arrayListOf(Images.Media.EXTERNAL_CONTENT_URI, Video.Media.EXTERNAL_CONTENT_URI)
uris.forEach {
cursor = contentResolver.query(it, projection, selection.toString(), null, null)
while (cursor!!.moveToNext()) {
val path = cursor!!.getStringValue(Images.ImageColumns.DATA)
affectedFolderPaths.add(path.getParentPath())
addPathToDB(path)
}
}
} catch (ignored: Exception) {
} finally {
cursor?.close()
}
}
}
affectedFolderPaths.forEach {
updateDirectoryPath(it)
}
}
mHandler.post(mWorker)
return true
}
override fun onStopJob(params: JobParameters): Boolean {
mHandler.removeCallbacks(mWorker)
return false
}
}
| gpl-3.0 | f6b71c93d397743c99dbc8f8e6118b05 | 40.838983 | 152 | 0.619202 | 4.996964 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/search/gene/collection/TupleGene.kt | 1 | 11393 | package org.evomaster.core.search.gene.collection
import org.evomaster.core.logging.LoggingUtil
import org.evomaster.core.output.OutputFormat
import org.evomaster.core.problem.util.ParamUtil
import org.evomaster.core.search.gene.*
import org.evomaster.core.search.gene.optional.OptionalGene
import org.evomaster.core.search.gene.root.CompositeFixedGene
import org.evomaster.core.search.gene.string.StringGene
import org.evomaster.core.search.gene.utils.GeneUtils
import org.evomaster.core.search.impact.impactinfocollection.GeneImpact
import org.evomaster.core.search.impact.impactinfocollection.value.TupleGeneImpact
import org.evomaster.core.search.service.Randomness
import org.evomaster.core.search.service.mutator.MutationWeightControl
import org.evomaster.core.search.service.mutator.genemutation.AdditionalGeneMutationInfo
import org.evomaster.core.search.service.mutator.genemutation.SubsetGeneMutationSelectionStrategy
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* A tuple is a fixed-size, ordered list of elements, of possible different types.
* This is needed for example when representing the inputs of function calls in
* GraphQL.
*/
class TupleGene(
/**
* The name of this gene
*/
name: String,
/**
* The actual elements in the array, based on the template. Ie, usually those elements will be clones
* of the templated, and then mutated/randomized
* note that if the list of gene could be updated, its impact needs to be updated
*/
val elements: List<Gene>,
/**
* In some cases, we want to treat an element differently from the other (the last in particular).
* This is for example the case of function calls in GQL when the return type is an object, on
* which we need to select what to retrieve.
* In these cases, such return object will be part of the tuple, as the last element.
*/
val lastElementTreatedSpecially: Boolean = false,
) : CompositeFixedGene(name, elements) {
init {
if (elements.isEmpty()) {
throw IllegalArgumentException("Empty tuple")
}
}
companion object {
val log: Logger = LoggerFactory.getLogger(TupleGene::class.java)
}
override fun isLocallyValid(): Boolean {
return getViewOfChildren().all { it.isLocallyValid() }
}
/*
For GQL, the last element of the Tuple represents a return type gene.
It is a special gene that will be treated with the Boolean selection.
*/
fun getSpecialGene(): Gene? {
if (lastElementTreatedSpecially) {
return elements.last()
}
return null
}
override fun getValueAsPrintableString(
previousGenes: List<Gene>,
mode: GeneUtils.EscapeMode?,
targetFormat: OutputFormat?,
extraCheck: Boolean
): String {
val buffer = StringBuffer()
if (mode == GeneUtils.EscapeMode.GQL_NONE_MODE) {
if (lastElementTreatedSpecially) {
val returnGene = elements.last()
// The return is an optional non-active, we do not print the whole tuple
if ((returnGene.getWrappedGene(OptionalGene::class.java)?.isActive == true) || (returnGene.getWrappedGene(OptionalGene::class.java))==null) {
//need the name for input and return
buffer.append(name)
//printout the inputs. See later if a refactoring is needed
val s = elements.dropLast(1)
//.filter { it !is OptionalGene || it.isActive }
.filter { it.getWrappedGene(OptionalGene::class.java)?.isActive ?: true }
.joinToString(",") {
gqlInputsPrinting(it, targetFormat)
}.replace("\"", "\\\"")
if (s.isNotEmpty()) {
buffer.append("(")
buffer.append(s)
buffer.append(")")
}
//printout the return
buffer.append(
if (returnGene is OptionalGene && returnGene.isActive) {
assert(returnGene.gene is ObjectGene)
returnGene.gene.getValueAsPrintableString(
previousGenes,
GeneUtils.EscapeMode.BOOLEAN_SELECTION_MODE,
targetFormat,
extraCheck = true
)
} else
if (returnGene is ObjectGene) {
returnGene.getValueAsPrintableString(
previousGenes,
GeneUtils.EscapeMode.BOOLEAN_SELECTION_MODE,
targetFormat,
extraCheck = true
)
} else ""
)
}
} else {
//need the name for inputs only
buffer.append(name)
//printout only the inputs, since there is no return (is a primitive type)
val s = elements
//.filter { it !is OptionalGene || it.isActive }
.filter { it.getWrappedGene(OptionalGene::class.java)?.isActive ?: true }
.joinToString(",") {
gqlInputsPrinting(it, targetFormat)
}.replace("\"", "\\\"")
if (s.isNotEmpty()) {
buffer.append("(")
buffer.append(s)
buffer.append(")")
}
}
} else {
"[" + elements.filter { it.isPrintable() }.joinTo(buffer, ", ") {
it.getValueAsPrintableString(
previousGenes,
mode,
targetFormat
)
} + "]"
}
return buffer.toString()
}
private fun gqlInputsPrinting(
it: Gene,
targetFormat: OutputFormat?
) = if (it is EnumGene<*> ||
(it is OptionalGene && it.gene is EnumGene<*>) ||
(it is OptionalGene && it.gene is ArrayGene<*> && it.gene.template is EnumGene<*>) ||
(it is OptionalGene && it.gene is ArrayGene<*> && it.gene.template is OptionalGene && it.gene.template.gene is EnumGene<*>) ||
(it is ArrayGene<*> && it.template is EnumGene<*>) ||
(it is ArrayGene<*> && it.template is OptionalGene && it.template.gene is EnumGene<*>)
) {
val i = it.getValueAsRawString()
"${it.name} : $i"
} else {
if (it is ObjectGene || (it.getWrappedGene(OptionalGene::class.java)?.gene is ObjectGene)) {
val i = it.getValueAsPrintableString(mode = GeneUtils.EscapeMode.GQL_INPUT_MODE)
" $i"
} else {
if (it is ArrayGene<*> || (it is OptionalGene && it.gene is ArrayGene<*>)) {
val i = it.getValueAsPrintableString(mode = GeneUtils.EscapeMode.GQL_INPUT_ARRAY_MODE)
"${it.name} : $i"
} else {
val mode =
if (ParamUtil.getValueGene(it) is StringGene) GeneUtils.EscapeMode.GQL_STR_VALUE else GeneUtils.EscapeMode.GQL_INPUT_MODE
val i = it.getValueAsPrintableString(mode = mode, targetFormat = targetFormat)
"${it.name} : $i"
}
}
}
override fun randomize(randomness: Randomness, tryToForceNewValue: Boolean) {
elements.filter { it.isMutable() }.forEach {
it.randomize(randomness, false)
}
}
override fun copyValueFrom(other: Gene) {
if (other !is TupleGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
assert(elements.size == other.elements.size)
(elements.indices).forEach {
elements[it].copyValueFrom(other.elements[it])
}
}
override fun containsSameValueAs(other: Gene): Boolean {
if (other !is TupleGene) {
throw IllegalArgumentException("Invalid gene type ${other.javaClass}")
}
return this.elements.zip(other.elements) { thisElem, otherElem ->
thisElem.containsSameValueAs(otherElem)
}.all { it }
}
override fun bindValueBasedOn(gene: Gene): Boolean {
if (gene is TupleGene
&& elements.size == gene.elements.size
// binding is applicable only if names of element genes are consistent
&& (elements.indices).all { elements[it].possiblySame(gene.elements[it]) }
) {
var result = true
(elements.indices).forEach {
val r = elements[it].bindValueBasedOn(gene.elements[it])
if (!r)
LoggingUtil.uniqueWarn(log, "cannot bind the element at $it with the name ${elements[it].name}")
result = result && r
}
if (!result)
LoggingUtil.uniqueWarn(
log,
"cannot bind the ${this::class.java.simpleName} with the specified TupleGene gene"
)
return result
}
LoggingUtil.uniqueWarn(log, "cannot bind TupleGene with ${gene::class.java.simpleName}")
return false
}
override fun isMutable(): Boolean {
return elements.any { it.isMutable() }
}
override fun mutationWeight(): Double {
return elements.sumOf { it.mutationWeight() }
}
override fun adaptiveSelectSubsetToMutate(
randomness: Randomness,
internalGenes: List<Gene>,
mwc: MutationWeightControl,
additionalGeneMutationInfo: AdditionalGeneMutationInfo
): List<Pair<Gene, AdditionalGeneMutationInfo?>> {
if (additionalGeneMutationInfo.impact != null
&& additionalGeneMutationInfo.impact is TupleGeneImpact
) {
val impacts = internalGenes.map { additionalGeneMutationInfo.impact.elements.getValue(it.name) }
val selected = mwc.selectSubGene(
internalGenes,
true,
additionalGeneMutationInfo.targets,
individual = null,
impacts = impacts,
evi = additionalGeneMutationInfo.evi
)
val map = selected.map { internalGenes.indexOf(it) }
return map.map {
internalGenes[it] to additionalGeneMutationInfo.copyFoInnerGene(
impact = impacts[it] as? GeneImpact,
gene = internalGenes[it]
)
}
}
throw IllegalArgumentException("impact is null or not TupleGeneImpact, ${additionalGeneMutationInfo.impact}")
}
override fun copyContent(): Gene {
return TupleGene(name, elements.map(Gene::copy), lastElementTreatedSpecially)
}
override fun customShouldApplyShallowMutation(
randomness: Randomness,
selectionStrategy: SubsetGeneMutationSelectionStrategy,
enableAdaptiveGeneMutation: Boolean,
additionalGeneMutationInfo: AdditionalGeneMutationInfo?
): Boolean {
return false
}
} | lgpl-3.0 | b791e9f357642652a706ecc946c6e1a8 | 37.755102 | 159 | 0.57272 | 5.169238 | false | false | false | false |
Yorxxx/played-next-kotlin | app/src/androidTest/java/com/piticlistudio/playednext/data/repository/datasource/room/image/RoomGameImagesServiceTest.kt | 1 | 3389 | package com.piticlistudio.playednext.data.repository.datasource.room.image
import android.arch.core.executor.testing.InstantTaskExecutorRule
import android.arch.persistence.room.Room
import android.database.sqlite.SQLiteConstraintException
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import com.piticlistudio.playednext.data.AppDatabase
import com.piticlistudio.playednext.factory.DomainFactory
import com.piticlistudio.playednext.factory.DomainFactory.Factory.makeRoomGameImage
import junit.framework.Assert
import junit.framework.Assert.*
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class RoomGameImagesServiceTest {
@JvmField
@Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private var database: AppDatabase? = null
@Before
fun setUp() {
database = Room.inMemoryDatabaseBuilder(InstrumentationRegistry.getContext(), AppDatabase::class.java)
.allowMainThreadQueries()
.build()
}
@Test
fun insertShouldStoreData() {
val game = DomainFactory.makeGameCache()
val data = makeRoomGameImage(gameId = game.id)
database?.gamesDao()?.insert(game)
val result = database?.imageRoom()?.insert(data)
Assert.assertNotNull(result)
assertEquals(data.id, result?.toInt())
}
@Test
fun insertShouldAutoGenerateAPrimaryKey() {
val game = DomainFactory.makeGameCache()
val data = makeRoomGameImage(gameId = game.id, id = null)
database?.gamesDao()?.insert(game)
val result = database?.imageRoom()?.insert(data)
Assert.assertNotNull(result)
assertNotNull(result)
assertEquals(1L, result)
}
@Test
fun insertIsNotAllowedIfGameDoesNotExistOnDatabase() {
val data = makeRoomGameImage()
try {
database?.imageRoom()?.insert(data)
} catch (e: Throwable) {
assertNotNull(e)
assertTrue(e is SQLiteConstraintException)
}
}
@Test
fun findShouldReturnsEmptyIfNotFound() {
val observer = database?.imageRoom()?.findForGame(2)?.test()
Assert.assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertValueCount(1)
assertValue { it.isEmpty() }
assertNotComplete()
}
}
@Test
fun findShouldReturnData() {
// Arrange
val game = DomainFactory.makeGameCache()
val data = makeRoomGameImage(gameId = game.id)
val data2 = makeRoomGameImage(gameId = game.id)
val data3 = makeRoomGameImage(gameId = game.id)
database?.gamesDao()?.insert(game)
database?.imageRoom()?.insert(data)
database?.imageRoom()?.insert(data2)
database?.imageRoom()?.insert(data3)
val observer = database?.imageRoom()?.findForGame(game.id)?.test()
Assert.assertNotNull(observer)
observer?.apply {
assertNoErrors()
assertValueCount(1)
assertValue { it.contains(data) && it.contains(data2) && it.contains(data3) && it.size == 3 }
assertNotComplete()
}
}
@After
fun tearDown() {
database?.close()
}
} | mit | c68ece5d7c132bc513acdef0aa5ff105 | 27.728814 | 110 | 0.662437 | 4.65522 | false | true | false | false |
zitmen/thunderstorm-algorithms | src/main/kotlin/cz/cuni/lf1/thunderstorm/datastructures/PhysicalQuantities.kt | 1 | 1135 | package cz.cuni.lf1.thunderstorm.datastructures
public enum class PhysicalUnits {
NANOMETERS,
PIXELS,
PHOTONS,
AD_COUNTS
}
public interface PhysicalQuantity {
public fun getValue(): Double
public fun getUnit(): PhysicalUnits
}
public class Distance private constructor(
private val value: Double,
private val unit: PhysicalUnits)
: PhysicalQuantity {
public override fun getValue() = value
public override fun getUnit() = unit
companion object {
public fun fromNanoMeters(value: Double) = Distance(value, PhysicalUnits.NANOMETERS)
public fun fromPixels(value: Double) = Distance(value, PhysicalUnits.PIXELS)
}
}
public class Intensity private constructor(
private val value: Double,
private val unit: PhysicalUnits)
: PhysicalQuantity {
public override fun getValue() = value
public override fun getUnit() = unit
companion object {
public fun fromPhotons(value: Double) = Intensity(value, PhysicalUnits.PHOTONS)
public fun fromAdCounts(value: Double) = Intensity(value, PhysicalUnits.AD_COUNTS)
}
} | gpl-3.0 | c8932fcba67141c34d8713be8c30b15e | 26.047619 | 92 | 0.702203 | 4.348659 | false | false | false | false |
the4thfloor/Msync | app/src/main/java/eu/the4thfloor/msync/di/OkHttpModule.kt | 1 | 2189 | /*
* Copyright 2017 Ralph Bergmann
*
* 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 eu.the4thfloor.msync.di
import dagger.Module
import dagger.Provides
import eu.the4thfloor.msync.BuildConfig
import eu.the4thfloor.msync.MSyncApp
import eu.the4thfloor.msync.utils.enableLogging
import eu.the4thfloor.msync.utils.enableStetho
import okhttp3.Cache
import okhttp3.CertificatePinner
import okhttp3.OkHttpClient
import java.io.File
import javax.inject.Singleton
@Module
class OkHttpModule {
private val OKHTTP_CLIENT_CACHE_SIZE = 100L * 1024L * 1024L // 100 MiB for images
@Provides
@Singleton
internal fun provideOkHttpClient(app: MSyncApp): OkHttpClient {
val cacheDirectory = File(app.cacheDir.absoluteFile, "http")
val cache = Cache(cacheDirectory, OKHTTP_CLIENT_CACHE_SIZE)
val builder = OkHttpClient.Builder()
builder.cache(cache)
if (BuildConfig.DEBUG) {
builder.enableLogging()
builder.enableStetho()
}
val certificatePinner = CertificatePinner.Builder()
.add("secure.meetup.com", "sha256/dvShW4Mh3UYqIPjIrA7pExa9WkTXG3+g2Bws6R8NYu0=") // CN=f2.shared.global.fastly.net,O=Fastly\, Inc.,L=San Francisco,ST=California,C=US
.add("secure.meetup.com", "sha256/+VZJxHgrOOiVyUxgMRbfoo+GIWrMKd4aellBBHtBcKg=") // CN=GlobalSign CloudSSL CA - SHA256 - G3,O=GlobalSign nv-sa,C=BE
.add("secure.meetup.com", "sha256/K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q=") // CN=GlobalSign Root CA,OU=Root CA,O=GlobalSign nv-sa,C=BE
.build()
builder.certificatePinner(certificatePinner)
return builder.build()
}
}
| apache-2.0 | c637c37670f439389dbb2a3a19e9bd6c | 36.101695 | 177 | 0.723618 | 3.519293 | false | false | false | false |
googlecodelabs/android-compose-codelabs | MigrationCodelab/app/src/main/java/com/google/samples/apps/sunflower/data/PlantRepository.kt | 1 | 1327 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.sunflower.data
/**
* Repository module for handling data operations.
*/
class PlantRepository private constructor(private val plantDao: PlantDao) {
fun getPlants() = plantDao.getPlants()
fun getPlant(plantId: String) = plantDao.getPlant(plantId)
fun getPlantsWithGrowZoneNumber(growZoneNumber: Int) =
plantDao.getPlantsWithGrowZoneNumber(growZoneNumber)
companion object {
// For Singleton instantiation
@Volatile private var instance: PlantRepository? = null
fun getInstance(plantDao: PlantDao) =
instance ?: synchronized(this) {
instance ?: PlantRepository(plantDao).also { instance = it }
}
}
}
| apache-2.0 | caf7b42460414341de4ec1390e944127 | 31.365854 | 76 | 0.708365 | 4.35082 | false | false | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/mailstore/FolderSettingsProvider.kt | 2 | 1781 | package com.fsck.k9.mailstore
import com.fsck.k9.Account
import com.fsck.k9.Preferences
import com.fsck.k9.mail.FolderClass
/**
* Provides imported folder settings if available, otherwise default values.
*/
class FolderSettingsProvider(val preferences: Preferences, val account: Account) {
fun getFolderSettings(folderServerId: String): FolderSettings {
val storage = preferences.storage
val prefix = "${account.uuid}.$folderServerId"
return FolderSettings(
visibleLimit = account.displayCount,
displayClass = storage.getString("$prefix.displayMode", null).toFolderClass(FolderClass.NO_CLASS),
syncClass = storage.getString("$prefix.syncMode", null).toFolderClass(FolderClass.INHERITED),
notifyClass = storage.getString("$prefix.notifyMode", null).toFolderClass(FolderClass.INHERITED),
pushClass = storage.getString("$prefix.pushMode", null).toFolderClass(FolderClass.SECOND_CLASS),
inTopGroup = storage.getBoolean("$prefix.inTopGroup", false),
integrate = storage.getBoolean("$prefix.integrate", false),
).also {
removeImportedFolderSettings(prefix)
}
}
private fun removeImportedFolderSettings(prefix: String) {
val editor = preferences.createStorageEditor()
editor.remove("$prefix.displayMode")
editor.remove("$prefix.syncMode")
editor.remove("$prefix.notifyMode")
editor.remove("$prefix.pushMode")
editor.remove("$prefix.inTopGroup")
editor.remove("$prefix.integrate")
editor.commit()
}
private fun String?.toFolderClass(defaultValue: FolderClass): FolderClass {
return if (this == null) defaultValue else FolderClass.valueOf(this)
}
}
| apache-2.0 | 6b0e0a1b748a0779a88b9044454d14c1 | 39.477273 | 110 | 0.690623 | 4.839674 | false | false | false | false |
commons-app/apps-android-commons | app/src/test/kotlin/fr/free/nrw/commons/quiz/QuizQuestionTest.kt | 6 | 1571 | package fr.free.nrw.commons.quiz
import android.net.Uri
import fr.free.nrw.commons.TestCommonsApplication
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [21], application = TestCommonsApplication::class)
class QuizQuestionTest {
@Mock
private lateinit var quizQuestion: QuizQuestion
private val QUESTION_NUM_SAMPLE_VALUE = 1
private val QUESTION_SAMPLE_VALUE = "Is this picture OK to upload?"
private val QUESTION_URL_SAMPLE_VALUE_ONE = "https://i.imgur.com/0fMYcpM.jpg"
private val QUESTION_URL_SAMPLE_VALUE_TWO = "https://example.com"
private val IS_ANSWER_SAMPLE_VALUE = false
private val ANSWER_MESSAGE_SAMPLE_VALUE = "Continue"
@Before
fun setup() {
MockitoAnnotations.initMocks(this)
quizQuestion = QuizQuestion(
QUESTION_NUM_SAMPLE_VALUE,
QUESTION_SAMPLE_VALUE,
QUESTION_URL_SAMPLE_VALUE_ONE,
IS_ANSWER_SAMPLE_VALUE,
ANSWER_MESSAGE_SAMPLE_VALUE
)
}
@Test
fun testGetUrl() {
assertEquals(quizQuestion.getUrl(), Uri.parse(QUESTION_URL_SAMPLE_VALUE_ONE))
}
@Test
fun testSetUrl() {
quizQuestion.setUrl(QUESTION_URL_SAMPLE_VALUE_TWO)
assertEquals(quizQuestion.getUrl(), Uri.parse(QUESTION_URL_SAMPLE_VALUE_TWO))
}
} | apache-2.0 | f92c47f334d43971d7714f0f92eeb45e | 29.823529 | 85 | 0.711649 | 3.997455 | false | true | false | false |
spinnaker/spinnaker-gradle-project | spinnaker-extensions/src/main/kotlin/com/netflix/spinnaker/gradle/extension/SpinnakerExtensionsBundlerPlugin.kt | 1 | 3452 | /*
* 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.Plugins.BUNDLE_PLUGINS_TASK_NAME
import com.netflix.spinnaker.gradle.extension.Plugins.CHECKSUM_BUNDLE_TASK_NAME
import com.netflix.spinnaker.gradle.extension.Plugins.COLLECT_PLUGIN_ZIPS_TASK_NAME
import com.netflix.spinnaker.gradle.extension.Plugins.RELEASE_BUNDLE_TASK_NAME
import com.netflix.spinnaker.gradle.extension.extensions.SpinnakerBundleExtension
import com.netflix.spinnaker.gradle.extension.tasks.CreatePluginInfoTask
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.plugins.JavaPlugin
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.bundling.Zip
import org.gradle.crypto.checksum.Checksum
import org.gradle.crypto.checksum.ChecksumPlugin
import java.io.File
/**
* Bundles all plugin artifacts into single zip.
*/
class SpinnakerExtensionsBundlerPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.plugins.apply(JavaPlugin::class.java)
project.plugins.apply(ChecksumPlugin::class.java)
project.extensions.create("spinnakerBundle", SpinnakerBundleExtension::class.java)
project.tasks.register(COLLECT_PLUGIN_ZIPS_TASK_NAME, Copy::class.java) {
group = Plugins.GROUP
// Look for assemblePlugin task.
if (project.subprojects.isNotEmpty()) { // Safe guard this in case if project structure is not set correctly.
val assemblePluginTasks: Set<Task> = project.getTasksByName(ASSEMBLE_PLUGIN_TASK_NAME, true)
if (assemblePluginTasks.isNotEmpty()) {
dependsOn(assemblePluginTasks)
}
}
val distributions = project.subprojects
.filter { subproject ->
subproject.plugins.hasPlugin(SpinnakerServiceExtensionPlugin::class.java) ||
subproject.plugins.hasPlugin(SpinnakerUIExtensionPlugin::class.java)
}
.map { subproject -> project.file("${subproject.buildDir}/distributions") }
from(distributions)
.into("${project.buildDir}/zips")
}
project.tasks.register(BUNDLE_PLUGINS_TASK_NAME, Zip::class.java) {
dependsOn(COLLECT_PLUGIN_ZIPS_TASK_NAME)
group = Plugins.GROUP
from("${project.buildDir}/zips")
}
project.tasks.register(CHECKSUM_BUNDLE_TASK_NAME, Checksum::class.java) {
dependsOn(BUNDLE_PLUGINS_TASK_NAME)
group = Plugins.GROUP
files = project.tasks.getByName(BUNDLE_PLUGINS_TASK_NAME).outputs.files
outputDir = File(project.buildDir, "checksums")
algorithm = Checksum.Algorithm.SHA512
}
project.tasks.register(RELEASE_BUNDLE_TASK_NAME, CreatePluginInfoTask::class.java) {
dependsOn(CHECKSUM_BUNDLE_TASK_NAME)
group = Plugins.GROUP
}
}
}
| apache-2.0 | a0fd76b769bd09b3b533c0b5e190888a | 37.355556 | 115 | 0.743627 | 4.02331 | false | false | false | false |
GreenLionSoft/madrid-pollution-android-app | app/src/main/java/com/greenlionsoft/pollution/madrid/dependencies/RealTimeDatabase.kt | 1 | 2439 | package com.greenlionsoft.pollution.madrid.dependencies
import com.google.firebase.database.*
import com.greenlionsoft.domain.entities.PollutionData
import com.greenlionsoft.domain.realtimedatabase.IRealTimeDataBase
import com.greenlionsoft.logx.Logx
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
const val SERVER_TIME = "serverTime"
const val POLLUTION_DATA = "pollutionData"
class RealTimeDatabase : IRealTimeDataBase {
val database: FirebaseDatabase
val serverTimeRef: DatabaseReference
val pollutionDataRef: DatabaseReference
init {
database = FirebaseDatabase.getInstance()
database.setPersistenceEnabled(true)
serverTimeRef = database.getReference(SERVER_TIME)
pollutionDataRef = database.getReference(POLLUTION_DATA)
serverTimeRef.keepSynced(true)
pollutionDataRef.keepSynced(true)
}
override fun getServerTimeSingle(): Single<Long> {
return Single.create<Long> { emitter ->
serverTimeRef.setValue(ServerValue.TIMESTAMP)
serverTimeRef.addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
emitter.onError(p0.toException())
}
override fun onDataChange(p0: DataSnapshot) {
Logx.d("Server Time obtained: ${p0.value as Long}")
emitter.onSuccess(p0.value as Long)
}
})
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
}
override fun savePollutionData(pollutionData: PollutionData) {
database.getReference(POLLUTION_DATA).setValue(pollutionData)
}
override fun getPollutionDataSingle(): Single<PollutionData> {
return Single.create<PollutionData> { emitter ->
database.getReference(POLLUTION_DATA).addListenerForSingleValueEvent(object : ValueEventListener {
override fun onCancelled(p0: DatabaseError) {
emitter.onError(p0.toException())
}
override fun onDataChange(p0: DataSnapshot) {
emitter.onSuccess(p0.getValue(PollutionData::class.java) as PollutionData)
}
})
}.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
}
} | apache-2.0 | fc649fbc1b030de26b186236d2696fb8 | 33.857143 | 110 | 0.680197 | 4.810651 | false | false | false | false |
esafirm/android-image-picker | imagepicker/src/main/java/com/esafirm/imagepicker/features/ImagePickerActivity.kt | 1 | 6241 | package com.esafirm.imagepicker.features
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.PorterDuff
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.ActionBar
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.esafirm.imagepicker.R
import com.esafirm.imagepicker.features.cameraonly.CameraOnlyConfig
import com.esafirm.imagepicker.helper.ConfigUtils
import com.esafirm.imagepicker.helper.ImagePickerUtils
import com.esafirm.imagepicker.helper.IpCrasher
import com.esafirm.imagepicker.helper.LocaleManager
import com.esafirm.imagepicker.helper.ViewUtils
import com.esafirm.imagepicker.model.Image
class ImagePickerActivity : AppCompatActivity(), ImagePickerInteractionListener {
private val cameraModule = ImagePickerComponentsHolder.cameraModule
private var actionBar: ActionBar? = null
private lateinit var imagePickerFragment: ImagePickerFragment
private val config: ImagePickerConfig? by lazy {
intent.extras!!.getParcelable(ImagePickerConfig::class.java.simpleName)
}
private val cameraOnlyConfig: CameraOnlyConfig? by lazy {
intent.extras?.getParcelable(CameraOnlyConfig::class.java.simpleName)
}
private val isCameraOnly by lazy { cameraOnlyConfig != null }
private val startForCameraResult = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result: ActivityResult ->
val resultCode = result.resultCode
if (resultCode == Activity.RESULT_CANCELED) {
cameraModule.removeImage(this)
setResult(RESULT_CANCELED)
finish()
return@registerForActivityResult
}
if (resultCode == Activity.RESULT_OK) {
cameraModule.getImage(this, result.data) { images ->
val resultIntent = ImagePickerUtils.createResultIntent(images)
finishPickImages(resultIntent)
}
}
}
override fun attachBaseContext(newBase: Context) {
super.attachBaseContext(LocaleManager.updateResources(newBase))
}
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setResult(RESULT_CANCELED)
/* This should not happen */
val intent = intent
if (intent == null || intent.extras == null) {
IpCrasher.openIssue()
}
if (isCameraOnly) {
val cameraIntent = cameraModule.getCameraIntent(this, cameraOnlyConfig!!)
startForCameraResult.launch(cameraIntent)
return
}
val currentConfig = config!!
setTheme(currentConfig.theme)
setContentView(R.layout.ef_activity_image_picker)
setupView(currentConfig)
if (savedInstanceState != null) {
// The fragment has been restored.
imagePickerFragment =
supportFragmentManager.findFragmentById(R.id.ef_imagepicker_fragment_placeholder) as ImagePickerFragment
} else {
imagePickerFragment = ImagePickerFragment.newInstance(currentConfig)
val ft = supportFragmentManager.beginTransaction()
ft.replace(R.id.ef_imagepicker_fragment_placeholder, imagePickerFragment)
ft.commit()
}
}
/**
* Create option menus.
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.ef_image_picker_menu_main, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
if (!isCameraOnly) {
menu.findItem(R.id.menu_camera).isVisible = config?.isShowCamera ?: true
menu.findItem(R.id.menu_done).apply {
title = ConfigUtils.getDoneButtonText(this@ImagePickerActivity, config!!)
isVisible = imagePickerFragment.isShowDoneButton
}
}
return super.onPrepareOptionsMenu(menu)
}
/**
* Handle option menu's click event
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == android.R.id.home) {
onBackPressed()
return true
}
if (id == R.id.menu_done) {
imagePickerFragment.onDone()
return true
}
if (id == R.id.menu_camera) {
imagePickerFragment.captureImage()
return true
}
return super.onOptionsItemSelected(item)
}
override fun onBackPressed() {
if (this::imagePickerFragment.isInitialized) {
if (!imagePickerFragment.handleBack()) {
super.onBackPressed()
}
} else {
super.onBackPressed()
}
}
private fun setupView(config: ImagePickerConfig) {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
actionBar = supportActionBar
actionBar?.run {
val arrowDrawable = ViewUtils.getArrowIcon(this@ImagePickerActivity)
val arrowColor = config.arrowColor
if (arrowColor != ImagePickerConfig.NO_COLOR && arrowDrawable != null) {
arrowDrawable.setColorFilter(arrowColor, PorterDuff.Mode.SRC_ATOP)
}
setDisplayHomeAsUpEnabled(true)
setHomeAsUpIndicator(arrowDrawable)
setDisplayShowTitleEnabled(true)
}
}
/* --------------------------------------------------- */
/* > ImagePickerInteractionListener Methods */
/* --------------------------------------------------- */
override fun setTitle(title: String?) {
actionBar?.title = title
invalidateOptionsMenu()
}
override fun cancel() {
finish()
}
override fun selectionChanged(imageList: List<Image>?) {
// Do nothing when the selection changes.
}
override fun finishPickImages(result: Intent?) {
setResult(RESULT_OK, result)
finish()
}
}
| mit | d0cc8dee65ce94f8e48cc4d1dcbe4c5d | 33.291209 | 120 | 0.650056 | 5.187864 | false | true | false | false |
Shingyx/Bixlight | bixlight/src/main/java/com/github/shingyx/bixlight/BixlightService.kt | 1 | 3403 | package com.github.shingyx.bixlight
import android.accessibilityservice.AccessibilityService
import android.content.Intent
import android.hardware.camera2.CameraAccessException
import android.hardware.camera2.CameraManager
import android.os.Build
import android.os.Handler
import android.util.Log
import android.view.accessibility.AccessibilityEvent
private val TAG = BixlightService::class.java.simpleName
private val BIXBY_PACKAGE = if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
"com.samsung.android.app.spage"
} else {
"com.samsung.android.bixby.agent"
}
class BixlightService : AccessibilityService() {
private lateinit var cameraManager: CameraManager
private lateinit var handler: Handler
private lateinit var bixlightPreferences: BixlightPreferences
private lateinit var torchCallback: CameraManager.TorchCallback
private lateinit var cameraId: String
private var torchEnabled: Boolean = false
private var lastRunMillis: Long = 0
override fun onServiceConnected() {
Log.v(TAG, "onServiceConnected")
cameraManager = getSystemService(CameraManager::class.java)!!
handler = Handler()
bixlightPreferences = BixlightPreferences(this)
torchCallback = object : CameraManager.TorchCallback() {
override fun onTorchModeChanged(cameraId: String, enabled: Boolean) {
torchEnabled = enabled
}
}
cameraManager.registerTorchCallback(torchCallback, handler)
Log.v(TAG, "registered torch callback")
hasCameraId()
}
override fun onAccessibilityEvent(event: AccessibilityEvent) {
val activeWindowPackage = getActiveWindowPackage()
Log.v(TAG, "onAccessibilityEvent: [type] ${AccessibilityEvent.eventTypeToString(event.eventType)} [time] ${event.eventTime} [activeWindowPackage] $activeWindowPackage")
val currentMillis = System.currentTimeMillis()
val runTooSoon = currentMillis - lastRunMillis < bixlightPreferences.getSavedMaxRunFrequencyMs()
if (runTooSoon || activeWindowPackage != BIXBY_PACKAGE) {
return
}
if (hasCameraId()) {
Log.v(TAG, "turning torch ${if (torchEnabled) "OFF" else "ON"}")
lastRunMillis = currentMillis
try {
cameraManager.setTorchMode(cameraId, !torchEnabled)
} catch (e: CameraAccessException) {
Log.v(TAG, "failed to toggle torch")
}
}
handler.postDelayed({
performGlobalAction(GLOBAL_ACTION_BACK)
}, 50)
}
override fun onInterrupt() {
Log.v(TAG, "onInterrupt")
}
override fun onUnbind(intent: Intent): Boolean {
Log.v(TAG, "onUnbind")
cameraManager.unregisterTorchCallback(torchCallback)
Log.v(TAG, "unregistered torch callback")
return false
}
private fun getActiveWindowPackage(): String? {
return rootInActiveWindow?.packageName?.toString()
}
private fun hasCameraId(): Boolean {
if (!this::cameraId.isInitialized) {
try {
cameraId = cameraManager.cameraIdList[0] // Usually back camera is at 0 position
} catch (e: CameraAccessException) {
Log.v(TAG, "failed to get camera id")
return false
}
}
return true
}
}
| gpl-3.0 | 6b24f44878b14abd4a5d61b7c494973b | 34.082474 | 176 | 0.669115 | 4.598649 | false | false | false | false |
nebula-plugins/java-source-refactor | rewrite-java/src/test/kotlin/org/openrewrite/java/tree/LabelTest.kt | 1 | 2023 | /**
* Copyright 2016 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 org.openrewrite.java.tree
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.openrewrite.java.JavaParser
import org.openrewrite.java.firstMethodStatement
open class LabelTest : JavaParser() {
@Test
fun labeledWhileLoop() {
val orig = """
|public class A {
| public void test() {
| labeled: while(true) {
| }
| }
|}
""".trimMargin()
val a = parse(orig)
val labeled = a.firstMethodStatement() as J.Label
assertEquals("labeled", labeled.label.simpleName)
assertTrue(labeled.statement is J.WhileLoop)
assertEquals(orig, a.print())
}
@Test
fun nonEmptyLabeledWhileLoop() {
val orig = """
|public class A {
| public void test() {
| outer: while(true) {
| while(true) {
| break outer;
| }
| }
| }
|}
""".trimMargin()
val a = parse(orig)
val labeled = a.firstMethodStatement() as J.Label
assertEquals("outer", labeled.label.simpleName)
assertTrue(labeled.statement is J.WhileLoop)
assertEquals(orig, a.print())
}
}
| apache-2.0 | e800fc58e42d40e576753fcf77e052f9 | 30.123077 | 75 | 0.585764 | 4.397826 | false | true | false | false |
zyyoona7/KExtensions | lib/src/main/java/com/zyyoona7/extensions/dates.kt | 1 | 13973 | package com.zyyoona7.extensions
import android.annotation.SuppressLint
import java.text.DateFormat
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
/**
* Created by zyyoona7 on 2017/8/30.
* 日期转换相关的拓展函数
*/
/*
SimpleDateFormat https://developer.android.com/reference/java/text/SimpleDateFormat.html
匹配格式
Date转换成年
G ---- 公元
y ---- 2017
yy ---- 17
yyy ---- 2017
yyyy ---- 2017
yyyyy ---- 002017
Date转换成月份格式
M ---- 8 (个位数时不以0补齐)
MM ---- 08 (个位数时以0补齐)
MMM ---- 8月
MMMM ---- 八月
L ---- 8 (个位数时不以0补齐)
LL ---- 08 (个位数时以0补齐)
LLL ---- 8月
LLLL ---- 八月
Date转换成星期格式
E/EE/EEE ---- 周几
EEEE ---- 星期几
EEEEE ---- 几
Date转换成周数
w(small) ---- 年中的周数 (个位数时不以0补齐)
ww(small) ---- 年中的周数 (个位数时以0补齐)
W(big) ---- 月份中的周数 (个位数时不以0补齐)
WW(big) ---- 月份中的周数 (个位数时以0补齐)
Date转换成天数
d ---- 1 (日期9月1号)月份中的第几天 (个位数时不以0补齐)
dd ---- 01 (日期9月1号)月份中的第几天 (个位数时以0补齐)
D ---- 244 (日期9月1号)一年当中的第几天
输出当前时间是上午/下午
a ---- 上午
输出当前时间的小时位
H ---- 9 (9:00)Hour in day (0-23) 24时制 (个位数时不以0补齐)
HH ---- 09 (9:00)Hour in day (0-23) 24时制 (个位数时以0补齐)
K ---- 9 (9:00)Hour in am/pm (0-11) 12时制 (个位数时不以0补齐)
KK ---- 09 (9:00)Hour in am/pm (0-11) 12时制 (个位数时以0补齐)
输出当前时间的分钟位
m ---- 4 分钟数(个位数时不以0补齐)
mm ---- 04 分钟数(个位数时以0补齐)
输出当前时间的秒位
s ---- 5 (个位数时不以0补齐)
ss ---- 05 (个位数时以0补齐)
输出当前时间的毫秒位
S ---- 1 保留一位
SS ---- 10 保留两位
SSS ---- 100 保留三位
时区
z ---- GMT+08:00
zzzz ---- 中国标准时间
Z ---- +0800
*/
/**
* 单例默认的日期格式化
*/
internal object DefaultDateFormat {
private const val DEFAULT_DATE_STR = "yyyy-MM-dd HH:mm:ss"
val DEFAULT_FORMAT = ThreadLocal<SimpleDateFormat>().apply { set(SimpleDateFormat(DEFAULT_DATE_STR,Locale.US)) }
}
/**
* 当前时间毫秒值
*/
val currentTimeMills: Long get() = System.currentTimeMillis()
/**
* 当前时间格式化成指定格式的String类型
*/
fun currentTimeString(format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!): String = currentTimeMills.format2DateString(format)
/**
* 当前时间的Date类型
*/
val currentDate: Date get() = Date()
/**
* Date类型格式化成指定格式的String类型
*
* @param format
*/
fun Date.format2String(format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!): String = format.format(this)
/**
* Date类型格式化成指定格式的String类型
*
* @param formatPattern
*/
@SuppressLint("SimpleDateFormat")
fun Date.format2String(formatPattern: String): String = format2String(SimpleDateFormat(formatPattern))
/**
* Long类型格式化成指定格式的String类型的日期
*
* @param formatPattern
*/
fun Long.format2DateString(formatPattern: String): String = Date(this).format2String(formatPattern)
/**
* Long类型格式化成指定格式的String类型的日期
*
* @param format
*/
fun Long.format2DateString(format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!): String = Date(this).format2String(format)
/**
* 解析String类型的日期为Long类型
*
* @param time
* @param format
*/
fun parseDateString2Mills(time: String, format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!): Long {
return try {
format.parse(time).time
} catch (e: ParseException) {
e.printStackTrace()
-1L
}
}
/**
* 解析String类型的日期为Date类型
*
* @param time
* @param format
*/
fun parseString2Date(time: String, format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!): Date {
return try {
format.parse(time)
} catch (e: ParseException) {
e.printStackTrace()
Date()
}
}
/**
* 获取两个日期的时间差
*
* @param otherCalendar 默认值:当前日期
* @param unit 返回值的时间单位 默认值:天
*/
fun Calendar.getTimeSpan(otherCalendar: Calendar = Calendar.getInstance(), unit: TimeUnit): Long =
calculateTimeSpan(Math.abs(this.timeInMillis - otherCalendar.timeInMillis), unit)
/**
* 获取两个日期的时间差
*
* @param otherDate 默认值:当前日期
* @param unit 返回值的时间单位 默认值:天
*/
fun Date.getTimeSpan(otherDate: Date = Date(), unit: TimeUnit = TimeUnit.DAYS): Long =
calculateTimeSpan(Math.abs(this.time - otherDate.time), unit)
/**
* 获取两个日期的时间差
*
* @param otherMills 默认值:当前时间毫秒值
* @param unit 返回值的时间单位 默认值:天
*/
fun Long.getTimeSpan(otherMills: Long = currentTimeMills, unit: TimeUnit = TimeUnit.DAYS): Long =
calculateTimeSpan(Math.abs(this - otherMills), unit)
/**
* 获取两个日期的时间差
* (如果使用当前日期的默认值做比较,DateFormat必须是默认类型,否则需要全部替换掉默认参数)
*
* @param time1 默认值:当前日期
* @param time2
* @param format 默认值:"yyyy-MM-dd HH:mm:ss"格式的format
* @param unit 返回值的时间单位 默认值:天
*/
fun getTimeSpan(time1: String = currentTimeString(), time2: String,
format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!,
unit: TimeUnit = TimeUnit.DAYS): Long =
calculateTimeSpan(Math.abs(parseDateString2Mills(time1, format) -
parseDateString2Mills(time2, format)), unit)
/**
* 计算时间间隔
*
* @param diffMills 时间差值
* @param unit
*/
fun calculateTimeSpan(diffMills: Long, unit: TimeUnit): Long = when (unit) {
TimeUnit.NANOSECONDS -> TimeUnit.MILLISECONDS.toNanos(diffMills)
TimeUnit.MICROSECONDS -> TimeUnit.MILLISECONDS.toMicros(diffMills)
TimeUnit.MILLISECONDS -> TimeUnit.MILLISECONDS.toMillis(diffMills)
TimeUnit.SECONDS -> TimeUnit.MILLISECONDS.toSeconds(diffMills)
TimeUnit.MINUTES -> TimeUnit.MILLISECONDS.toMinutes(diffMills)
TimeUnit.HOURS -> TimeUnit.MILLISECONDS.toHours(diffMills)
else -> TimeUnit.MILLISECONDS.toDays(diffMills)
}
/**
* 将时间戳转换成 xx小时前 的样式(同微博)
*
* @return
*
* 如果小于1秒钟内,显示刚刚
* 如果在1分钟内,显示xx秒前
* 如果在1小时内,显示xx分钟前
* 如果在1小时外的今天内,显示今天15:32
* 如果是昨天的,显示昨天15:32
* 如果是同一年,显示 09-01 15:32
* 其余显示,2017-09-01
*/
fun formatAgoStyleForWeibo(time: String, format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!): String = parseDateString2Mills(time, format).formatAgoStyleForWeibo()
/**
* 将时间戳转换成 xx小时前 的样式(同微信)
*
* @return
*
* 如果小于1秒钟内,显示刚刚
* 如果在1分钟内,显示xx秒前
* 如果在1小时内,显示xx分钟前
* 如果是昨天,显示昨天
* 如果在一个月内,显示xx天前
* 如果在一年内,显示xx月前
* 如果在两年内,显示xx年前
* 其余显示,2017-09-01
*/
fun formatAgoStyleForWeChat(time: String, format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!): String = parseDateString2Mills(time, format).formatAgoStyleForWeChat()
/**
* 将时间戳转换成 xx小时前 的样式(同微博)
*
* @return
*
* 如果小于1秒钟内,显示刚刚
* 如果在1分钟内,显示xx秒前
* 如果在1小时内,显示xx分钟前
* 如果在1小时外的今天内,显示今天15:32
* 如果是昨天的,显示昨天15:32
* 如果是同一年,显示 09-01 15:32
* 其余显示,2017-09-01
*/
fun Date.formatAgoStyleForWeibo(): String = this.time.formatAgoStyleForWeibo()
/**
* 将时间戳转换成 xx小时前 的样式(同微信)
*
* @return
*
* 如果小于1秒钟内,显示刚刚
* 如果在1分钟内,显示xx秒前
* 如果在1小时内,显示xx分钟前
* 如果是昨天,显示昨天
* 如果在一个月内,显示xx天前
* 如果在一年内,显示xx月前
* 如果在两年内,显示xx年前
* 其余显示,2017-09-01
*/
fun Date.formatAgoStyleForWeChat(): String = time.formatAgoStyleForWeChat()
/**
* 将时间戳转换成 xx小时前 的样式(同微博)
*
* @return
*
* 如果小于1秒钟内,显示刚刚
* 如果在1分钟内,显示xx秒前
* 如果在1小时内,显示xx分钟前
* 如果在1小时外的今天内,显示今天15:32
* 如果是昨天的,显示昨天15:32
* 如果是同一年,显示 09-01 15:32
* 其余显示,2017-09-01
*/
fun Long.formatAgoStyleForWeibo(): String {
val now = currentTimeMills
val span = now - this
return when {
span <= TimeUnit.SECONDS.toMillis(1) -> "刚刚"
span <= TimeUnit.MINUTES.toMillis(1) -> String.format("%d秒前", span / TimeUnit.SECONDS.toMillis(1))
span <= TimeUnit.HOURS.toMillis(1) -> String.format("%d分钟前", span / TimeUnit.MINUTES.toMillis(1))
span <= TimeUnit.DAYS.toMillis(1) -> String.format("%d小时前", span / TimeUnit.HOURS.toMillis(1))
span >= TimeUnit.DAYS.toMillis(1) && span <= TimeUnit.DAYS.toMillis(1) * 2 -> String.format("昨天%tR", this)
isSameYear(now) -> String.format("%tm-%td %tR", this, this, this)
else -> String.format("%tF", this)
}
}
/**
* 将时间戳转换成 xx小时前 的样式(同微信)
*
* @return
*
* 如果小于1秒钟内,显示刚刚
* 如果在1分钟内,显示xx秒前
* 如果在1小时内,显示xx分钟前
* 如果是昨天,显示昨天
* 如果在一个月内,显示xx天前
* 如果在一年内,显示xx月前
* 如果在两年内,显示xx年前
* 其余显示,2017-09-01
*/
fun Long.formatAgoStyleForWeChat(): String {
val now = currentTimeMills
val span = now - this
loge("span=$span")
return when {
span <= TimeUnit.SECONDS.toMillis(1) -> "刚刚"
span <= TimeUnit.MINUTES.toMillis(1) -> String.format("%d秒前", span / TimeUnit.SECONDS.toMillis(1))
span <= TimeUnit.HOURS.toMillis(1) -> String.format("%d分钟前", span / TimeUnit.MINUTES.toMillis(1))
span <= TimeUnit.DAYS.toMillis(1) -> String.format("%d小时前", span / TimeUnit.HOURS.toMillis(1))
span >= TimeUnit.DAYS.toMillis(1) && span <= TimeUnit.DAYS.toMillis(1) * 2 -> "昨天"
span <= TimeUnit.DAYS.toMillis(1) * 30 -> String.format("%d天前", span / TimeUnit.DAYS.toMillis(1))
span <= TimeUnit.DAYS.toMillis(1) * 30 * 12 -> String.format("%d月前", span / (TimeUnit.DAYS.toMillis(1) * 30))
span <= TimeUnit.DAYS.toMillis(1) * 30 * 12 * 2 -> String.format("%d年前", span / (TimeUnit.DAYS.toMillis(1) * 30 * 12))
else -> String.format("%tF", this)
}
}
/**
* 判断两个毫秒值是否在同一年
*/
fun Long.isSameYear(otherMills: Long): Boolean {
val cal = Calendar.getInstance()
cal.time = Date(this)
val cal1 = Calendar.getInstance()
cal1.time = Date(otherMills)
return cal[Calendar.YEAR] == cal1[Calendar.YEAR]
}
fun Date.isSameYear(otherDate: Date): Boolean {
val cal = Calendar.getInstance()
cal.time = this
val cal1 = Calendar.getInstance()
cal1.time = otherDate
return cal[Calendar.YEAR] == cal1[Calendar.YEAR]
}
/**
* 日期是否在两个日期之间
*
* @param minCal 最小日期
* @param maxCal 最大日期
*/
fun Date.betweenDates(minCal: Calendar, maxCal: Calendar): Boolean = betweenDates(minCal.time, maxCal.time)
/**
* 日期是否在两个日期之间
*
* @param minDate 最小日期
* @param maxDate 最大日期
*/
fun Date.betweenDates(minDate: Date, maxDate: Date): Boolean =
(this == minDate || this.after(minDate)) // >= minCal
&& this.before(maxDate) // && < maxCal
/**
* 将日期时间设置为0点,00:00:00:0
*/
fun Calendar.ofTimeZero(): Calendar {
return apply {
set(Calendar.HOUR_OF_DAY, 0)
set(Calendar.MINUTE, 0)
set(Calendar.SECOND, 0)
set(Calendar.MILLISECOND, 0)
}
}
/**
* 获取星期的下标
*
* @return 星期日 为1
*/
val Date.dayOfWeek: Int
get() {
val cal = Calendar.getInstance()
cal.time = this
return cal.get(Calendar.DAY_OF_WEEK)
}
/**
* 获取星期的下标
*
* @return 星期日 为1
*/
val Calendar.dayOfWeek: Int
get() = get(Calendar.DAY_OF_WEEK)
/**
* 获取星期的下标
*
* @return 星期日 为1
*/
val Long.dayOfWeek: Int
get() {
val cal = Calendar.getInstance()
cal.timeInMillis = this
return cal.get(Calendar.DAY_OF_WEEK)
}
/**
* 获取星期的下标
*
* @param time
* @param format
* @return 星期日 为1
*/
fun dayOfWeek(time: String, format: DateFormat = DefaultDateFormat.DEFAULT_FORMAT.get()!!): Int {
return parseString2Date(time, format).dayOfWeek
} | apache-2.0 | 24588c24d127b290381590460ce06e63 | 24.907193 | 176 | 0.626332 | 2.815889 | false | false | false | false |
nt-ca-aqe/library-app | library-integration-slack/src/main/kotlin/library/integration/slack/services/error/handling/SlackErrorDecoder.kt | 1 | 1611 | package library.integration.slack.services.error.handling
import feign.FeignException
import feign.Response
import feign.codec.ErrorDecoder
import org.springframework.http.HttpStatus.*
/**
* Custom implementation of Feign Error Decoder.
*/
class SlackErrorDecoder : ErrorDecoder {
override fun decode(methodKey: String, response: Response): Exception {
val statusCode: Int = response.status()
return when {
statusCode == BAD_REQUEST.value() -> SlackInvalidPayloadException(response.status())
statusCode == FORBIDDEN.value() -> SlackChannelProhibitedException(response.status())
statusCode == NOT_FOUND.value() -> SlackChannelNotFoundException(response.status())
statusCode == GONE.value() -> SlackChannelArchivedException(response.status())
statusCode in INTERNAL_SERVER_ERROR.value()..599 -> SlackServerException(response.status())
else -> FeignException.errorStatus(methodKey, response)
}
}
}
data class SlackInvalidPayloadException(val status: Int, val reason: String = "invalid_payload") : RuntimeException()
data class SlackChannelProhibitedException(val status: Int, val reason: String = "action_prohibited") :
RuntimeException()
data class SlackChannelNotFoundException(val status: Int, val reason: String = "channel_not_found") : RuntimeException()
data class SlackChannelArchivedException(val status: Int, val reason: String = "channel_is_archived") :
RuntimeException()
data class SlackServerException(val status: Int, val reason: String = "rollup_error") : RuntimeException()
| apache-2.0 | de43ce3d9604319b61746c6f9d94ccb9 | 41.394737 | 120 | 0.734947 | 4.68314 | false | false | false | false |
bassaer/ChatMessageView | chatmessageview/src/main/kotlin/com/github/bassaer/chatmessageview/util/ChatBot.kt | 1 | 1194 | package com.github.bassaer.chatmessageview.util
import java.util.*
/**
* Chat Bot for demo
* Created by nakayama on 2016/12/03.
*/
object ChatBot {
fun talk(username: String?, message: String): String {
val receive = message.toLowerCase()
when {
receive.contains("hello") -> {
var user = ""
if (username != null) {
user = " " + username
}
return "Hello$user!"
}
receive.contains("hey") -> return "Hey $username!"
receive.startsWith("do ") -> return "Yes, I do."
receive.contains("time") -> return "It's " + TimeUtils.calendarToString(Calendar.getInstance(), null) + "."
receive.contains("today") -> return "It's " + TimeUtils.calendarToString(Calendar.getInstance(), "M/d(E)")
else -> {
var reply = "Lorem ipsum dolor sit amet"
if (receive.length > 7) {
reply += ", consectetur adipiscing elit, " + "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. "
}
return reply
}
}
}
}
| apache-2.0 | 443ad32c81ed7a136b0246c1f15cdcd4 | 34.117647 | 134 | 0.514238 | 4.438662 | false | false | false | false |
maskaravivek/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/FileProcessor.kt | 3 | 7808 | package fr.free.nrw.commons.upload
import android.content.ContentResolver
import android.content.Context
import android.net.Uri
import androidx.exifinterface.media.ExifInterface
import fr.free.nrw.commons.R
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.mwapi.CategoryApi
import fr.free.nrw.commons.mwapi.OkHttpJsonApiClient
import fr.free.nrw.commons.settings.Prefs
import fr.free.nrw.commons.upload.structure.depictions.DepictModel
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
import java.io.File
import java.io.IOException
import java.util.*
import javax.inject.Inject
import javax.inject.Named
/**
* Processing of the image filePath that is about to be uploaded via ShareActivity is done here
*/
private const val DEFAULT_SUGGESTION_RADIUS_IN_METRES = 100
private const val MAX_SUGGESTION_RADIUS_IN_METRES = 1000
private const val RADIUS_STEP_SIZE_IN_METRES = 100
private const val MIN_NEARBY_RESULTS = 5
class FileProcessor @Inject constructor(
private val context: Context,
private val contentResolver: ContentResolver,
private val gpsCategoryModel: GpsCategoryModel,
private val depictsModel: DepictModel,
@param:Named("default_preferences") private val defaultKvStore: JsonKvStore,
private val apiCall: CategoryApi,
private val okHttpJsonApiClient: OkHttpJsonApiClient
) {
private val compositeDisposable = CompositeDisposable()
fun cleanup() {
compositeDisposable.clear()
}
/**
* Processes filePath coordinates, either from EXIF data or user location
*/
fun processFileCoordinates(similarImageInterface: SimilarImageInterface, filePath: String?)
: ImageCoordinates {
val exifInterface: ExifInterface? = try {
ExifInterface(filePath!!)
} catch (e: IOException) {
Timber.e(e)
null
}
// Redact EXIF data as indicated in preferences.
redactExifTags(exifInterface, getExifTagsToRedact())
Timber.d("Calling GPSExtractor")
val originalImageCoordinates = ImageCoordinates(exifInterface)
if (originalImageCoordinates.decimalCoords == null) {
//Find other photos taken around the same time which has gps coordinates
findOtherImages(
File(filePath),
similarImageInterface
)
} else {
prePopulateCategoriesAndDepictionsBy(originalImageCoordinates)
}
return originalImageCoordinates
}
/**
* Gets EXIF Tags from preferences to be redacted.
*
* @return tags to be redacted
*/
fun getExifTagsToRedact(): Set<String> {
val prefManageEXIFTags =
defaultKvStore.getStringSet(Prefs.MANAGED_EXIF_TAGS) ?: emptySet()
val redactTags: Set<String> =
context.resources.getStringArray(R.array.pref_exifTag_values).toSet()
return redactTags - prefManageEXIFTags
}
/**
* Redacts EXIF metadata as indicated in preferences.
*
* @param exifInterface ExifInterface object
* @param redactTags tags to be redacted
*/
fun redactExifTags(exifInterface: ExifInterface?, redactTags: Set<String>) {
compositeDisposable.add(
Observable.fromIterable(redactTags)
.flatMap { Observable.fromArray(*FileMetadataUtils.getTagsFromPref(it)) }
.subscribe(
{ redactTag(exifInterface, it) },
{ Timber.d(it) },
{ save(exifInterface) }
)
)
}
private fun save(exifInterface: ExifInterface?) {
try {
exifInterface?.saveAttributes()
} catch (e: IOException) {
Timber.w("EXIF redaction failed: %s", e.toString())
}
}
private fun redactTag(exifInterface: ExifInterface?, tag: String) {
Timber.d("Checking for tag: %s", tag)
exifInterface?.getAttribute(tag)
?.takeIf { it.isNotEmpty() }
?.let {
exifInterface.setAttribute(tag, null).also {
Timber.d("Exif tag $tag with value $it redacted.")
}
}
}
/**
* Find other images around the same location that were taken within the last 20 sec
*
* @param originalImageCoordinates
* @param fileBeingProcessed
* @param similarImageInterface
*/
private fun findOtherImages(
fileBeingProcessed: File,
similarImageInterface: SimilarImageInterface
) {
val oneHundredAndTwentySeconds = 120 * 1000L
//Time when the original image was created
val timeOfCreation = fileBeingProcessed.lastModified()
LongRange
val timeOfCreationRange =
timeOfCreation - oneHundredAndTwentySeconds..timeOfCreation + oneHundredAndTwentySeconds
fileBeingProcessed.parentFile
.listFiles()
.asSequence()
.filter { it.lastModified() in timeOfCreationRange }
.map { Pair(it, readImageCoordinates(it)) }
.firstOrNull { it.second?.decimalCoords != null }
?.let { fileCoordinatesPair ->
similarImageInterface.showSimilarImageFragment(
fileBeingProcessed.path,
fileCoordinatesPair.first.absolutePath,
fileCoordinatesPair.second
)
}
}
private fun readImageCoordinates(file: File) =
try {
ImageCoordinates(contentResolver.openInputStream(Uri.fromFile(file))!!)
} catch (e: IOException) {
Timber.e(e)
try {
ImageCoordinates(file.absolutePath)
} catch (ex: IOException) {
Timber.e(ex)
null
}
}
/**
* Initiates retrieval of image coordinates or user coordinates, and caching of coordinates. Then
* initiates the calls to MediaWiki API through an instance of CategoryApi.
*
* @param imageCoordinates
*/
fun prePopulateCategoriesAndDepictionsBy(imageCoordinates: ImageCoordinates) {
requireNotNull(imageCoordinates.decimalCoords)
compositeDisposable.add(
apiCall.request(imageCoordinates.decimalCoords)
.subscribeOn(Schedulers.io())
.observeOn(Schedulers.io())
.subscribe(
gpsCategoryModel::setCategoriesFromLocation,
{
Timber.e(it)
gpsCategoryModel.clear()
}
)
)
compositeDisposable.add(
suggestNearbyDepictions(imageCoordinates)
)
}
private val radiiProgressionInMetres =
(DEFAULT_SUGGESTION_RADIUS_IN_METRES..MAX_SUGGESTION_RADIUS_IN_METRES step RADIUS_STEP_SIZE_IN_METRES)
private fun suggestNearbyDepictions(imageCoordinates: ImageCoordinates): Disposable {
return Observable.fromIterable(radiiProgressionInMetres.map { it / 1000.0 })
.concatMap {
Observable.fromCallable {
okHttpJsonApiClient.getNearbyPlaces(
imageCoordinates.latLng,
Locale.getDefault().language,
it,
false
)
}
}
.subscribeOn(Schedulers.io())
.filter { it.size >= MIN_NEARBY_RESULTS }
.take(1)
.subscribe(
{ depictsModel.nearbyPlaces.offer(it) },
{ Timber.e(it) }
)
}
}
| apache-2.0 | 47088d764a8dec5e3dd525444c034618 | 34.652968 | 110 | 0.623207 | 5.005128 | false | false | false | false |
ngageoint/mage-android | mage/src/main/java/mil/nga/giat/mage/compat/server5/login/SignupActivityServer5.kt | 1 | 2756 | package mil.nga.giat.mage.compat.server5.login
import android.os.Bundle
import android.util.Patterns
import android.view.View
import androidx.lifecycle.ViewModelProvider
import dagger.hilt.android.AndroidEntryPoint
import mil.nga.giat.mage.databinding.ActivitySignupBinding
import mil.nga.giat.mage.login.SignupActivity
import mil.nga.giat.mage.login.SignupViewModel
@AndroidEntryPoint
class SignupActivityServer5: SignupActivity() {
protected lateinit var viewModelServer5: SignupViewModelServer5
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.captchaView.visibility = View.GONE
binding.captchaTextLayout.visibility = View.GONE
viewModelServer5 = ViewModelProvider(this).get(SignupViewModelServer5::class.java)
viewModelServer5.signupState.observe(this, { state: SignupViewModel.SignupState -> onSignupState(state) })
viewModelServer5.signupStatus.observe(this, { status: SignupViewModel.SignupStatus? -> onSignup(status) })
}
override fun signup() {
binding.displaynameLayout.error = null
binding.usernameLayout.error = null
binding.emailLayout.error = null
binding.passwordLayout.error = null
binding.confirmpasswordLayout.error = null
val displayName: String = binding.signupDisplayname.text.toString()
val username: String = binding.signupUsername.text.toString()
val email: String = binding.signupEmail.text.toString()
val phone: String = binding.signupPhone.text.toString()
// are the inputs valid?
if (displayName.isEmpty()) {
binding.displaynameLayout.error = "Display name can not be blank"
return
}
if (username.isEmpty()) {
binding.usernameLayout.error = "Username can not be blank"
return
}
if (email.isNotEmpty() && !Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
binding.emailLayout.error = "Please enter a valid email address"
return
}
val password: String = binding.signupPassword.text.toString()
val confirmpassword: String = binding.signupConfirmpassword.text.toString()
if (password.isEmpty()) {
binding.passwordLayout.error = "Password can not be blank"
return
}
if (confirmpassword.isEmpty()) {
binding.confirmpasswordLayout.error = "Enter password again"
return
}
if (password != confirmpassword) {
binding.passwordLayout.error = "Passwords do not match"
binding.confirmpasswordLayout.error = "Passwords do not match"
return
}
hideKeyboard()
viewModelServer5.signup(SignupViewModel.Account(username, displayName, email, phone, password))
}
} | apache-2.0 | ae9a1957bd5f90e653292df9359b672e | 34.805195 | 112 | 0.711901 | 4.360759 | false | false | false | false |
koesie10/AdventOfCode-Solutions-Kotlin | 2016/src/main/kotlin/com/koenv/adventofcode/Day4.kt | 1 | 2420 | package com.koenv.adventofcode
import java.util.*
import java.util.regex.Pattern
import kotlin.comparisons.compareValues
object Day4 {
val ROOM_NAME_PATTERN: Pattern = Pattern.compile("([a-z\\-]*)-(\\d+)\\[([a-z]{5})\\]")
fun getRoomName(input: String): RoomName {
val matcher = ROOM_NAME_PATTERN.matcher(input)
if (!matcher.find()) {
throw IllegalStateException("Invalid room name: $input")
}
return RoomName(
matcher.group(1),
matcher.group(2).toInt(),
matcher.group(3).toCharArray().toList()
)
}
fun getMostCommonLetters(encryptedName: String) = encryptedName.toCharArray()
.filter { it != '-' }
.groupBy { it }
.values
.sortedWith(Comparator { lhs, rhs ->
if (lhs.size == rhs.size) {
return@Comparator compareValues(lhs[0], rhs[0])
}
compareValues(rhs.size, lhs.size)
})
.map { it[0] }
.take(5)
fun isChecksumValid(room: RoomName) = room.mostCommonLetters == getMostCommonLetters(room.encryptedName)
fun getSectorIdSum(input: String) = input.lines()
.filter(String::isNotBlank)
.map { getRoomName(it) }
.filter { isChecksumValid(it) }
.sumBy { it.sectorId }
fun decryptName(room: RoomName) = String(room.encryptedName
.toCharArray()
.map { shiftLetter(it, room.sectorId) }
.toCharArray())
fun shiftLetter(letter: Char, n: Int): Char {
if (letter == '-') {
return ' '
}
var new = letter
for (i in 1..n) {
new = shiftLetter(new)
}
return new
}
fun shiftLetter(letter: Char): Char {
if (letter == 'z') {
return 'a'
}
return letter + 1
}
fun getNorthPoleObjectStorageSectorId(input: String) = input.lines()
.filter(String::isNotBlank)
.map { getRoomName(it) }
.filter { isChecksumValid(it) }
.map { decryptName(it) to it.sectorId }
.find { it.first == "northpole object storage" }!!
.second
data class RoomName(
val encryptedName: String,
val sectorId: Int,
val mostCommonLetters: List<Char>
)
} | mit | 589bf7b640972465c3d82f72242b9311 | 27.482353 | 108 | 0.530579 | 4.158076 | false | false | false | false |
yschimke/oksocial | src/main/kotlin/com/baulsupp/okurl/services/twilio/TwilioAuthInterceptor.kt | 1 | 2794 | package com.baulsupp.okurl.services.twilio
import com.baulsupp.oksocial.output.OutputHandler
import com.baulsupp.okurl.authenticator.AuthInterceptor
import com.baulsupp.okurl.authenticator.BasicCredentials
import com.baulsupp.okurl.authenticator.ValidatedCredentials
import com.baulsupp.okurl.authenticator.basic.BasicAuthServiceDefinition
import com.baulsupp.okurl.completion.ApiCompleter
import com.baulsupp.okurl.completion.BaseUrlCompleter
import com.baulsupp.okurl.completion.CompletionVariableCache
import com.baulsupp.okurl.completion.UrlList
import com.baulsupp.okurl.credentials.CredentialsStore
import com.baulsupp.okurl.credentials.Token
import com.baulsupp.okurl.credentials.TokenValue
import com.baulsupp.okurl.kotlin.query
import com.baulsupp.okurl.secrets.Secrets
import com.baulsupp.okurl.services.twilio.model.Accounts
import okhttp3.Credentials
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
class TwilioAuthInterceptor : AuthInterceptor<BasicCredentials>() {
override val serviceDefinition: BasicAuthServiceDefinition =
BasicAuthServiceDefinition(
"api.twilio.com", "Twilio API", "twilio",
"https://www.twilio.com/docs/api/rest", "https://www.twilio.com/console"
)
override suspend fun intercept(chain: Interceptor.Chain, credentials: BasicCredentials): Response {
var request = chain.request()
request = request.newBuilder()
.addHeader("Authorization", Credentials.basic(credentials.user, credentials.password))
.build()
return chain.proceed(request)
}
override suspend fun authorize(
client: OkHttpClient,
outputHandler: OutputHandler<Response>,
authArguments: List<String>
): BasicCredentials {
val user = Secrets.prompt("Twilio Account SID", "twilio.accountSid", "", false)
val password = Secrets.prompt("Twilio Auth Token", "twilio.authToken", "", true)
return BasicCredentials(user, password)
}
override suspend fun validate(
client: OkHttpClient,
credentials: BasicCredentials
): ValidatedCredentials {
val map = client.query<Accounts>(
"https://api.twilio.com/2010-04-01/Accounts.json",
TokenValue(credentials)
)
return ValidatedCredentials(map.accounts.firstOrNull()?.friendly_name)
}
override suspend fun apiCompleter(
prefix: String,
client: OkHttpClient,
credentialsStore: CredentialsStore,
completionVariableCache: CompletionVariableCache,
tokenSet: Token
): ApiCompleter {
val urlList = UrlList.fromResource(name())
val completer = BaseUrlCompleter(urlList!!, hosts(credentialsStore), completionVariableCache)
completer.withVariable("AccountSid") {
credentialsStore.get(serviceDefinition, tokenSet)?.let { listOf(it.user) }
}
return completer
}
}
| apache-2.0 | 334e9084b451c6d3f0956fc6fedaef3d | 34.367089 | 101 | 0.772727 | 4.595395 | false | false | false | false |
Magneticraft-Team/Magneticraft | src/main/kotlin/com/cout970/magneticraft/systems/computer/DeviceMotherboard.kt | 2 | 4373 | package com.cout970.magneticraft.systems.computer
import com.cout970.magneticraft.api.computer.IDevice
import com.cout970.magneticraft.api.computer.IRW
import com.cout970.magneticraft.api.core.ITileRef
import com.cout970.magneticraft.misc.split
import com.cout970.magneticraft.misc.splitSet
import net.minecraft.util.math.BlockPos
/**
* Created by cout970 on 2016/10/01.
*/
class DeviceMotherboard(val tile: ITileRef, val mb: Motherboard) : IDevice, ITileRef by tile {
var logType = 0
val memStruct = ReadWriteStruct("motherboard_header",
ReadOnlyByte("online") { if (mb.isOnline) 1 else 0 },
ReadWriteByte("signal", { signal(it.toInt()) }, { 0 }),
ReadWriteByte("sleep", { mb.sleep(it.toInt()) }, { 0 }),
ReadOnlyByte("padding") { 0 },
ReadOnlyInt("memSize") { mb.ram.memorySize },
ReadOnlyInt("littleEndian") { if (mb.ram.isLittleEndian) -1 else 0 },
ReadOnlyInt("worldTime") { (getWorldTime() and 0xFFFFFFFF).toInt() },
ReadOnlyInt("cpuTime") { mb.clock },
ReadWriteByte("logType", { logType = it.toInt() }, { logType.toByte() }),
ReadWriteByte("logByte", { logByte(it) }, { 0 }),
LogShort("logShort") { logShort(it) },
LogInt("logInt") { logInt(it) },
ReadOnlyIntArray("devices") { getDevices() },
ReadOnlyInt("*monitor") { 0xFF000000.toInt() },
ReadOnlyInt("*floppy") { 0xFF010000.toInt() },
ReadOnlyInt("*keyboard") { 0xFF020000.toInt() }
)
override fun update() = Unit
fun getDevices(): IntArray {
val buffer = IntArray(16)
repeat(16) {
if (it in mb.deviceMap.keySet()) {
buffer[it] = 0xFF000000.toInt() or (it shl 16)
}
}
return buffer
}
fun signal(id: Int) {
when (id) {
0 -> mb.halt()
1 -> mb.start()
2 -> mb.reset()
}
}
fun logByte(data: Byte) {
when (logType) {
1 -> print("${data.toInt() and 0xFF} ")
2 -> print("0x%02x ".format(data.toInt() and 0xFF))
3 -> print(data.toChar())
else -> {
println("${getComputerPos()}: 0x%02x, %03d, ".format(data.toInt() and 0xFF,
data.toInt() and 0xFF) + data.toChar())
}
}
}
fun logShort(data: Short) {
when (logType) {
1 -> print("$data ")
2 -> print("0x%04x ".format(data))
3 -> print(data.toChar())
else -> {
println("${getComputerPos()}: 0x%04x, %05d".format(data, data))
}
}
}
fun logInt(data: Int) {
when (logType) {
1 -> print("$data ")
2 -> print("0x%08x ".format(data))
3 -> print(data.toChar())
else -> {
println("${getComputerPos()}: 0x%08x, %010d".format(data, data))
}
}
}
fun getWorldTime(): Long {
if (tile == FakeRef) return 0L
return world.totalWorldTime
}
fun getComputerPos(): BlockPos {
if (tile == FakeRef) return BlockPos.ORIGIN
return pos
}
override fun readByte(bus: IRW, addr: Int): Byte {
return memStruct.read(addr)
}
override fun writeByte(bus: IRW, addr: Int, data: Byte) {
memStruct.write(addr, data)
}
class LogInt(val name: String, val log: (Int) -> Unit) : IVariable {
var logInt = 0
override val size = 4
override fun read(addr: Int) = logInt.split(addr)
override fun write(addr: Int, value: Byte) {
logInt = logInt.splitSet(addr, value)
if (addr == 0) log(logInt)
}
override fun toString(): String = "i32 $name;"
}
class LogShort(val name: String, val log: (Short) -> Unit) : IVariable {
var logShort = 0
override val size = 2
override fun read(addr: Int) = logShort.split(addr)
override fun write(addr: Int, value: Byte) {
logShort = logShort.splitSet(addr, value)
if (addr == 0) log(logShort.toShort())
}
override fun toString(): String = "i16 $name;"
}
override fun serialize() = mapOf("logType" to logType)
override fun deserialize(map: Map<String, Any>) {
logType = map["logType"] as Int
}
}
| gpl-2.0 | 38e4203fcd30bcaf47d6c673cf919668 | 29.58042 | 94 | 0.54745 | 3.731229 | false | false | false | false |
spark/photon-tinker-android | mesh/src/main/java/io/particle/mesh/bluetooth/connecting/GattConnector.kt | 1 | 2962 | package io.particle.mesh.bluetooth.connecting
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothGatt
import android.content.Context
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.Observer
import com.snakydesign.livedataextensions.filter
import com.snakydesign.livedataextensions.first
import io.particle.mesh.bluetooth.BLELiveDataCallbacks
import io.particle.mesh.bluetooth.btAdapter
import io.particle.mesh.common.android.SimpleLifecycleOwner
import io.particle.mesh.setup.flow.Scopes
import kotlinx.coroutines.CompletableDeferred
import mu.KotlinLogging
import java.util.concurrent.TimeUnit
private val INITIAL_CONNECTION_TIMEOUT = TimeUnit.SECONDS.toMillis(5)
class GattConnector(private val ctx: Context) {
private val lifecycleOwner = SimpleLifecycleOwner()
private val log = KotlinLogging.logger {}
suspend fun createGattConnection(
device: BluetoothDevice,
scopes: Scopes
): Pair<BluetoothGatt, BLELiveDataCallbacks>? {
lifecycleOwner.setNewState(Lifecycle.State.RESUMED)
this.ctx.btAdapter.cancelDiscovery()
val callbacks = BLELiveDataCallbacks()
val gatt = try {
scopes.withMain(INITIAL_CONNECTION_TIMEOUT) {
log.info { "Creating GATT connection" }
doCreateGattConnection(device, ctx, callbacks)
}
} catch (ex: Exception) {
return null
}
try {
return Pair(gatt, callbacks)
} finally {
lifecycleOwner.setNewState(Lifecycle.State.DESTROYED)
callbacks.connectionStateChangedLD.removeObservers(lifecycleOwner)
}
}
private suspend fun doCreateGattConnection(
device: BluetoothDevice,
ctx: Context,
callbacks: BLELiveDataCallbacks
): BluetoothGatt {
val completable = CompletableDeferred<BluetoothGatt>()
doCreateGattConnection(device, ctx, callbacks) {
completable.complete(it)
}
return completable.await()
}
private fun doCreateGattConnection(
device: BluetoothDevice,
ctx: Context,
liveDataCallbacks: BLELiveDataCallbacks,
callback: (BluetoothGatt) -> Unit
) {
log.info { "About to connect to $device" }
val gattRef = device.connectGatt(ctx.applicationContext, false, liveDataCallbacks)
log.info { "Called connectGatt for $gattRef" }
liveDataCallbacks.connectionStateChangedLD
.filter { it == ConnectionState.CONNECTED }
.first()
.observe(lifecycleOwner, Observer {
log.debug { "Connection state updated to $it" }
if (it == ConnectionState.CONNECTED) {
callback(gattRef)
} else {
log.error { "Connection status not CONNECTED?! it=$it" }
}
})
}
} | apache-2.0 | 9f663115cf6a87ec3f5bfe2a584de5f9 | 32.292135 | 90 | 0.659352 | 5.054608 | false | false | false | false |
mozilla-mobile/focus-android | app/src/main/java/org/mozilla/focus/settings/permissions/SitePermissionOption.kt | 1 | 2186 | /* 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
import org.mozilla.focus.R
sealed class AutoplayOption {
data class AllowAudioVideo(
override val prefKeyId: Int = R.string.pref_key_allow_autoplay_audio_video,
override val titleId: Int = R.string.preference_allow_audio_video_autoplay,
) : SitePermissionOption(prefKeyId = prefKeyId, titleId = titleId)
data class BlockAudioOnly(
override val prefKeyId: Int = R.string.pref_key_block_autoplay_audio_only,
override val titleId: Int = R.string.preference_block_autoplay_audio_only,
override val summaryId: Int = R.string.preference_block_autoplay_audio_only_summary,
) : SitePermissionOption(prefKeyId = prefKeyId, titleId = titleId)
data class BlockAudioVideo(
override val prefKeyId: Int = R.string.pref_key_block_autoplay_audio_video,
override val titleId: Int = R.string.preference_block_autoplay_audio_video,
) : SitePermissionOption(prefKeyId = prefKeyId, titleId = titleId)
}
sealed class SitePermissionOption(open val prefKeyId: Int, open val titleId: Int, open val summaryId: Int? = null) {
data class AskToAllow(
override val prefKeyId: Int = R.string.pref_key_ask_to_allow,
override val titleId: Int = R.string.preference_option_phone_feature_ask_to_allow,
override val summaryId: Int = R.string.preference_block_autoplay_audio_only_summary,
) : SitePermissionOption(prefKeyId = prefKeyId, titleId = titleId)
data class Blocked(
override val prefKeyId: Int = R.string.pref_key_blocked,
override val titleId: Int = R.string.preference_option_phone_feature_blocked,
) : SitePermissionOption(prefKeyId = prefKeyId, titleId = titleId)
data class Allowed(
override val prefKeyId: Int = R.string.pref_key_allowed,
override val titleId: Int = R.string.preference_option_phone_feature_allowed,
) : SitePermissionOption(prefKeyId = prefKeyId, titleId = titleId)
}
| mpl-2.0 | b26de5f84c6a2d0c8e8037b3c53d69a5 | 48.681818 | 116 | 0.724154 | 3.960145 | false | false | false | false |
chat-sdk/chat-sdk-android | chat-sdk-vendor/src/main/java/smartadapter/SmartEndlessScrollAdapterBuilder.kt | 1 | 1940 | package smartadapter
import androidx.annotation.LayoutRes
import io.github.manneohlund.smartrecycleradapter.R
import smartadapter.listener.OnLoadMoreListener
class SmartEndlessScrollAdapterBuilder : SmartAdapterBuilder() {
private var isEndlessScrollEnabled: Boolean = true
private var autoLoadMoreEnabled = false
@LayoutRes
private var loadMoreLayoutResource = R.layout.load_more_view
private var onLoadMoreListener: OnLoadMoreListener? = null
override fun getSmartRecyclerAdapter(): SmartRecyclerAdapter {
return SmartEndlessScrollRecyclerAdapter(items).also {
it.isEndlessScrollEnabled = isEndlessScrollEnabled
it.autoLoadMoreEnabled = autoLoadMoreEnabled
it.loadMoreLayoutResource = loadMoreLayoutResource
it.onLoadMoreListener = onLoadMoreListener
}
}
/**
* @see SmartEndlessScrollRecyclerAdapter.isEndlessScrollEnabled
*/
fun setEndlessScrollEnabled(isEndlessScrollEnabled: Boolean): SmartEndlessScrollAdapterBuilder {
this.isEndlessScrollEnabled = isEndlessScrollEnabled
return this
}
/**
* @see SmartEndlessScrollRecyclerAdapter.autoLoadMoreEnabled
*/
fun setAutoLoadMoreEnabled(autoLoadMoreEnabled: Boolean): SmartEndlessScrollAdapterBuilder {
this.autoLoadMoreEnabled = autoLoadMoreEnabled
return this
}
/**
* @see SmartEndlessScrollRecyclerAdapter.loadMoreLayoutResource
*/
fun setLoadMoreLayoutResource(@LayoutRes loadMoreLayoutResource: Int): SmartEndlessScrollAdapterBuilder {
this.loadMoreLayoutResource = loadMoreLayoutResource
return this
}
/**
* @see SmartEndlessScrollRecyclerAdapter.onLoadMoreListener
*/
fun setOnLoadMoreListener(onLoadMoreListener: OnLoadMoreListener): SmartEndlessScrollAdapterBuilder {
this.onLoadMoreListener = onLoadMoreListener
return this
}
}
| apache-2.0 | 6b6182c918d17ee22dd485c41a268cd0 | 34.272727 | 109 | 0.750515 | 5.68915 | false | false | false | false |
google/horologist | audio-ui/src/debug/java/com/google/android/horologist/audio/ui/VolumeScreenPreview.kt | 1 | 4905 | /*
* 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
*
* 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.android.horologist.audio.ui
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.PreviewParameter
import androidx.compose.ui.tooling.preview.PreviewParameterProvider
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Scaffold
import com.google.android.horologist.audio.AudioOutput
import com.google.android.horologist.audio.VolumeState
import com.google.android.horologist.audio.ui.components.toAudioOutputUi
import com.google.android.horologist.compose.tools.ThemeValues
import com.google.android.horologist.compose.tools.WearLargeRoundDevicePreview
import com.google.android.horologist.compose.tools.WearPreviewDevices
import com.google.android.horologist.compose.tools.WearPreviewFontSizes
import com.google.android.horologist.compose.tools.WearPreviewThemes
import com.google.android.horologist.compose.tools.WearSmallRoundDevicePreview
@WearSmallRoundDevicePreview
@Composable
fun VolumeScreenGuideWithLongText() {
val volume = VolumeState(10, 10)
Box(modifier = Modifier.fillMaxSize()) {
Scaffold(
positionIndicator = {
VolumePositionIndicator(
volumeState = { volume.copy(current = 5) },
autoHide = false
)
}
) {
VolumeScreen(
volume = { volume },
audioOutputUi = AudioOutput.BluetoothHeadset(id = "1", name = "Galaxy Watch 4")
.toAudioOutputUi(),
increaseVolume = { },
decreaseVolume = { },
onAudioOutputClick = {}
)
}
}
}
@WearPreviewDevices
@WearPreviewFontSizes
@Composable
fun VolumeScreenPreview(
@PreviewParameter(AudioOutputProvider::class) audioOutput: AudioOutput
) {
val volume = VolumeState(5, 10)
Scaffold(
positionIndicator = {
VolumePositionIndicator(
volumeState = { volume },
autoHide = false
)
}
) {
VolumeScreen(
volume = { volume },
audioOutputUi = audioOutput.toAudioOutputUi(),
increaseVolume = { },
decreaseVolume = { },
onAudioOutputClick = {}
)
}
}
@WearLargeRoundDevicePreview
@Composable
fun VolumeScreenTheme(
@PreviewParameter(WearPreviewThemes::class) themeValues: ThemeValues
) {
val volume = VolumeState(10, 10)
MaterialTheme(themeValues.colors) {
Box(modifier = Modifier.fillMaxSize()) {
Scaffold(
positionIndicator = {
VolumePositionIndicator(
volumeState = { volume.copy(current = 5) },
autoHide = false
)
}
) {
VolumeScreen(
volume = { volume },
audioOutputUi = AudioOutput.BluetoothHeadset(id = "1", name = "PixelBuds")
.toAudioOutputUi(),
increaseVolume = { },
decreaseVolume = { },
onAudioOutputClick = {}
)
}
}
}
}
@WearPreviewDevices
@WearPreviewFontSizes
@Composable
fun VolumeScreenWithLabel() {
val volume = VolumeState(10, 10)
Box(modifier = Modifier.fillMaxSize()) {
Scaffold(
positionIndicator = {
VolumePositionIndicator(
volumeState = { volume.copy(current = 5) },
autoHide = false
)
}
) {
VolumeWithLabelScreen(
volume = { volume },
increaseVolume = { },
decreaseVolume = { }
)
}
}
}
class AudioOutputProvider : PreviewParameterProvider<AudioOutput> {
override val values = sequenceOf(
AudioOutput.BluetoothHeadset(id = "1", name = "PixelBuds"),
AudioOutput.WatchSpeaker(id = "2", name = "Galaxy Watch 4"),
AudioOutput.BluetoothHeadset(id = "3", name = "Sennheiser Momentum Wireless")
)
}
| apache-2.0 | faa2cfc9cf90d302194b95bfa9d5bfaa | 31.919463 | 95 | 0.619368 | 4.813543 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/common/CommentsMapperTest.kt | 1 | 9534 | package org.wordpress.android.fluxc.common
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.model.CommentModel
import org.wordpress.android.fluxc.model.CommentStatus.APPROVED
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.comments.CommentsMapper
import org.wordpress.android.fluxc.network.rest.wpcom.comment.CommentParent
import org.wordpress.android.fluxc.network.rest.wpcom.comment.CommentWPComRestResponse
import org.wordpress.android.fluxc.persistence.comments.CommentEntityList
import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity
import org.wordpress.android.fluxc.utils.DateTimeUtilsWrapper
import java.util.Date
class CommentsMapperTest {
private val dateTimeUtilsWrapper: DateTimeUtilsWrapper = mock()
private val mapper = CommentsMapper(dateTimeUtilsWrapper)
@Test
fun `xmlrpc dto is converted to entity`() {
val comment = getDefaultComment(false).copy(
authorProfileImageUrl = null,
datePublished = "2021-07-29T21:29:27+00:00"
)
val site = SiteModel().apply {
id = comment.localSiteId
selfHostedSiteId = comment.remoteSiteId
}
val xmlRpcDto = comment.toXmlRpcDto()
whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(comment.publishedTimestamp)
whenever(dateTimeUtilsWrapper.iso8601UTCFromDate(any())).thenReturn(comment.datePublished)
val mappedEntity = mapper.commentXmlRpcDTOToEntity(xmlRpcDto, site)
assertThat(mappedEntity).isEqualTo(comment)
}
@Test
fun `xmlrpc dto list is converted to entity list`() {
val commentList = getDefaultCommentList(false).map { it.copy(id = 0, authorProfileImageUrl = null) }
val site = SiteModel().apply {
id = commentList.first().localSiteId
selfHostedSiteId = commentList.first().remoteSiteId
}
val xmlRpcDtoList = commentList.map { it.toXmlRpcDto() }
whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(commentList.first().publishedTimestamp)
whenever(dateTimeUtilsWrapper.iso8601UTCFromDate(any())).thenReturn(commentList.first().datePublished)
val mappedEntityList = mapper.commentXmlRpcDTOToEntityList(xmlRpcDtoList.toTypedArray(), site)
assertThat(mappedEntityList).isEqualTo(commentList)
}
@Test
fun `dto is converted to entity`() {
val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00")
val site = SiteModel().apply {
id = comment.localSiteId
siteId = comment.remoteSiteId
}
val commentDto = comment.toDto()
whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(comment.publishedTimestamp)
val mappedEntity = mapper.commentDtoToEntity(commentDto, site)
assertThat(mappedEntity).isEqualTo(comment)
}
@Test
fun `entity is converted to model`() {
val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00")
val commentModel = comment.toModel()
val mappedModel = mapper.commentEntityToLegacyModel(comment)
assertModelsEqual(mappedModel, commentModel)
}
@Test
fun `model is converted to entity`() {
val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00")
val commentModel = comment.toModel()
val mappedEntity = mapper.commentLegacyModelToEntity(commentModel)
assertThat(mappedEntity).isEqualTo(comment)
}
@Suppress("ComplexMethod")
private fun assertModelsEqual(mappedModel: CommentModel, commentModel: CommentModel): Boolean {
return mappedModel.id == commentModel.id &&
mappedModel.remoteCommentId == commentModel.remoteCommentId &&
mappedModel.remotePostId == commentModel.remotePostId &&
mappedModel.authorId == commentModel.authorId &&
mappedModel.localSiteId == commentModel.localSiteId &&
mappedModel.remoteSiteId == commentModel.remoteSiteId &&
mappedModel.authorUrl == commentModel.authorUrl &&
mappedModel.authorName == commentModel.authorName &&
mappedModel.authorEmail == commentModel.authorEmail &&
mappedModel.authorProfileImageUrl == commentModel.authorProfileImageUrl &&
mappedModel.postTitle == commentModel.postTitle &&
mappedModel.status == commentModel.status &&
mappedModel.datePublished == commentModel.datePublished &&
mappedModel.publishedTimestamp == commentModel.publishedTimestamp &&
mappedModel.content == commentModel.content &&
mappedModel.url == commentModel.url &&
mappedModel.hasParent == commentModel.hasParent &&
mappedModel.parentId == commentModel.parentId &&
mappedModel.iLike == commentModel.iLike
}
private fun CommentEntity.toDto(): CommentWPComRestResponse {
val entity = this
return CommentWPComRestResponse().apply {
ID = entity.remoteCommentId
URL = entity.url
author = Author().apply {
ID = entity.authorId
URL = entity.authorUrl
avatar_URL = entity.authorProfileImageUrl
email = entity.authorEmail
name = entity.authorName
}
content = entity.content
date = entity.datePublished
i_like = entity.iLike
parent = CommentParent().apply {
ID = entity.parentId
}
post = Post().apply {
type = "post"
title = entity.postTitle
link = "https://public-api.wordpress.com/rest/v1.1/sites/185464053/posts/85"
ID = entity.remotePostId
}
status = entity.status
}
}
private fun CommentEntity.toModel(): CommentModel {
val entity = this
return CommentModel().apply {
id = entity.id.toInt()
remoteCommentId = entity.remoteCommentId
remotePostId = entity.remotePostId
authorId = entity.authorId
localSiteId = entity.localSiteId
remoteSiteId = entity.remoteSiteId
authorUrl = entity.authorUrl
authorName = entity.authorName
authorEmail = entity.authorEmail
authorProfileImageUrl = entity.authorProfileImageUrl
postTitle = entity.postTitle
status = entity.status
datePublished = entity.datePublished
publishedTimestamp = entity.publishedTimestamp
content = entity.content
url = entity.authorProfileImageUrl
hasParent = entity.hasParent
parentId = entity.parentId
iLike = entity.iLike
}
}
private fun CommentEntity.toXmlRpcDto(): HashMap<*, *> {
return hashMapOf<String, Any?>(
"parent" to this.parentId.toString(),
"post_title" to this.postTitle,
"author" to this.authorName,
"link" to this.url,
"date_created_gmt" to Date(),
"comment_id" to this.remoteCommentId.toString(),
"content" to this.content,
"author_url" to this.authorUrl,
"post_id" to this.remotePostId,
"user_id" to this.authorId,
"author_email" to this.authorEmail,
"status" to this.status
)
}
private fun getDefaultComment(allowNulls: Boolean): CommentEntity {
return CommentEntity(
id = 0,
remoteCommentId = 10,
remotePostId = 100,
authorId = 44,
localSiteId = 10_000,
remoteSiteId = 100_000,
authorUrl = if (allowNulls) null else "https://test-debug-site.wordpress.com",
authorName = if (allowNulls) null else "authorname",
authorEmail = if (allowNulls) null else "[email protected]",
authorProfileImageUrl = if (allowNulls) null else "https://gravatar.com/avatar/111222333",
postTitle = if (allowNulls) null else "again",
status = APPROVED.toString(),
datePublished = if (allowNulls) null else "2021-05-12T15:10:40+02:00",
publishedTimestamp = 1_000_000,
content = if (allowNulls) null else "content example",
url = if (allowNulls) null else "https://test-debug-site.wordpress.com/2021/02/25/again/#comment-137",
hasParent = true,
parentId = 1_000L,
iLike = false
)
}
private fun getDefaultCommentList(allowNulls: Boolean): CommentEntityList {
val comment = getDefaultComment(allowNulls)
return listOf(
comment.copy(id = 1, remoteCommentId = 10, datePublished = "2021-07-24T00:51:43+02:00"),
comment.copy(id = 2, remoteCommentId = 20, datePublished = "2021-07-24T00:51:43+02:00"),
comment.copy(id = 3, remoteCommentId = 30, datePublished = "2021-07-24T00:51:43+02:00"),
comment.copy(id = 4, remoteCommentId = 40, datePublished = "2021-07-24T00:51:43+02:00")
)
}
}
| gpl-2.0 | 1709c3826674eec51cf47f8c205c7fed | 42.336364 | 118 | 0.642123 | 4.981191 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/typing/RsEnterInStringLiteralHandler.kt | 8 | 2924 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.typing
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegate.Result
import com.intellij.codeInsight.editorActions.enter.EnterHandlerDelegateAdapter
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.actionSystem.EditorActionHandler
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiFile
import com.intellij.psi.StringEscapesTokenTypes.STRING_LITERAL_ESCAPES
import org.rust.lang.core.psi.RS_RAW_LITERALS
import org.rust.lang.core.psi.RS_STRING_LITERALS
import org.rust.lang.core.psi.RsFile
class RsEnterInStringLiteralHandler : EnterHandlerDelegateAdapter() {
override fun preprocessEnter(
file: PsiFile,
editor: Editor,
caretOffsetRef: Ref<Int>,
caretAdvanceRef: Ref<Int>,
dataContext: DataContext,
originalHandler: EditorActionHandler?
): Result {
if (file !is RsFile) return Result.Continue
val caretOffset = caretOffsetRef.get()
if (!isValidInnerOffset(caretOffset, editor.document.charsSequence)) return Result.Continue
val highlighter = (editor as EditorEx).highlighter
val iterator = highlighter.createIterator(caretOffset)
// Return if we are not inside literal contents (i.e. in prefix, suffix or delimiters)
if (!RsQuoteHandler().isDeepInsideLiteral(iterator, caretOffset)) return Result.Continue
// Return if we are inside escape sequence
if (iterator.tokenType in STRING_LITERAL_ESCAPES) {
// If we are just at the beginning, we don't want to return, but
// we have to determine literal type. Retreating iterator will do.
if (caretOffset == iterator.start) {
iterator.retreat()
} else {
return Result.Continue
}
}
return when (iterator.tokenType) {
in RS_STRING_LITERALS -> {
// In Rust, an unescaped newline inside a string literal is perfectly valid,
// and can be used to format multiline text. So if there is at least one such
// newline, don't try to be smart.
val tokenText = editor.document.immutableCharSequence.subSequence(iterator.start, iterator.end)
if (tokenText.contains(UNESCAPED_NEWLINE)) return Result.Continue
editor.document.insertString(caretOffset, "\\")
caretOffsetRef.set(caretOffset + 1)
Result.DefaultForceIndent
}
in RS_RAW_LITERALS ->
Result.DefaultSkipIndent
else -> Result.Continue
}
}
}
private val UNESCAPED_NEWLINE = """[^\\]\n""".toRegex()
| mit | 6e20073f8b990f856543abfa9d4007e8 | 39.054795 | 111 | 0.676129 | 4.754472 | false | false | false | false |
Aptoide/aptoide-client-v8 | app/src/main/java/cm/aptoide/pt/autoupdate/AutoUpdateModel.kt | 1 | 622 | package cm.aptoide.pt.autoupdate
data class AutoUpdateModel(val versionCode: Int, val uri: String, val md5: String,
val minSdk: String, val packageName: String,
val shouldUpdate: Boolean = false, var status: Status = Status.SUCCESS,
var loading: Boolean = false) {
constructor(status: Status) : this(-1, "", "", "", "", status = status)
constructor(loading: Boolean) : this(-1, "", "", "", "", loading = loading)
fun wasSuccess(): Boolean = status == Status.SUCCESS
}
enum class Status {
ERROR_NETWORK, ERROR_GENERIC, SUCCESS
} | gpl-3.0 | a612d28fe195d5a56c3a9cf01fcd83ff | 33.611111 | 98 | 0.601286 | 4.411348 | false | false | false | false |
KentVu/vietnamese-t9-ime | app/src/main/java/com/vutrankien/t9vietnamese/android/WordListAdapter.kt | 1 | 1940 | package com.vutrankien.t9vietnamese.android
import android.view.LayoutInflater
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import android.widget.TextView
import androidx.cardview.widget.CardView
/**
* Created by user on 2018/03/21.
*/
class WordListAdapter() : RecyclerView.Adapter<WordListAdapter.ViewHolder>() {
private val words = mutableListOf<String>()
internal var selectedWord = 0
override fun getItemCount(): Int = words.size
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.textView.apply {
text = words[position]
isSelected = position == selectedWord
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder =
ViewHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.candidate, parent, false) as CardView
//.also {
//(it.layoutParams as ViewGroup.MarginLayoutParams).apply
//it.layoutParams = ViewGroup.MarginLayoutParams(parent.context) MarginLayoutParamsCompat.also {
// leftMargin = parent.resources.getDimensionPixelOffset(R.dimen.candidate_gap)
//}
)
fun clear() {
words.clear()
notifyDataSetChanged()
}
fun update(cand: Collection<String>) {
words.clear()
words.addAll(cand)
notifyDataSetChanged()
selectedWord = 0
}
fun select(selectedWord: Int) {
val tmp = this.selectedWord
this.selectedWord = selectedWord
notifyItemChanged(tmp)
notifyItemChanged(this.selectedWord)
}
fun findItem(targetWord: String): Int {
return words.indexOf(targetWord)
}
class ViewHolder(cardView: CardView) : RecyclerView.ViewHolder(cardView) {
val textView: TextView = cardView.findViewById(R.id.content)
}
}
| gpl-3.0 | 2fb6843cca13c7bee5dbbef5709a3618 | 28.393939 | 112 | 0.656186 | 4.85 | false | false | false | false |
czyzby/gdx-setup | src/main/kotlin/com/github/czyzby/setup/data/templates/unofficial/squidLibBasic.kt | 1 | 33902 | package com.github.czyzby.setup.data.templates.unofficial
import com.github.czyzby.setup.data.files.CopiedFile
import com.github.czyzby.setup.data.files.path
import com.github.czyzby.setup.data.libs.unofficial.SquidLib
import com.github.czyzby.setup.data.platforms.Assets
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.data.templates.Template
import com.github.czyzby.setup.views.ProjectTemplate
/**
* A (somewhat) simple project using SquidLib extension.
* @author Tommy Ettinger
*/
@ProjectTemplate
class SquidLibBasicTemplate : Template {
override val id = "squidLibBasicTemplate"
override val width = "80 * 11"
override val height = "30 * 22"
override val description: String
get() = "Project template included simple launchers and an `ApplicationAdapter` extension showing usage of [SquidLib](https://github.com/SquidPony/SquidLib) extension."
override fun apply(project: Project) {
super.apply(project)
// Including SquidLib dependency:
SquidLib().initiate(project)
// Adding font:
arrayOf("fnt", "png").forEach {
val fileName = "Inconsolata-LGC-Custom-distance.$it"
project.files.add(CopiedFile(projectName = Assets.ID, path = fileName,
original = path("generator", "templates", "squidLib", fileName)))
}
}
override fun getApplicationListenerContent(project: Project): String = """package ${project.basic.rootPackage};
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import squidpony.FakeLanguageGen;
import squidpony.squidai.DijkstraMap;
import squidpony.squidgrid.gui.gdx.DefaultResources;
import squidpony.squidgrid.gui.gdx.SColor;
import squidpony.squidgrid.gui.gdx.SquidInput;
import squidpony.squidgrid.gui.gdx.SquidLayers;
import squidpony.squidgrid.gui.gdx.SquidMouse;
import squidpony.squidgrid.mapping.DungeonGenerator;
import squidpony.squidgrid.mapping.DungeonUtility;
import squidpony.squidmath.Coord;
import squidpony.squidmath.GreasedRegion;
import squidpony.squidmath.RNG;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The main class of the game, constructed once in each of the platform-specific Launcher classes. Doesn't use any
* platform-specific code.
*/
// If this is an example project in gdx-setup, then squidlib-util and the squidlib (the display module) are always
// dependencies. If you didn't change those dependencies, this class should run out of the box.
//
// This class is useful as a starting point, since it has dungeon generation and some of the trickier parts of input
// handling (using the mouse to get a path for the player) already filled in. You can remove any imports or usages of
// classes that you don't need.
// A main game class that uses LibGDX to display, which is the default for SquidLib, needs to extend ApplicationAdapter
// or something related, like Game. Game adds features that SquidLib doesn't currently use, so ApplicationAdapter is
// perfectly fine for these uses.
public class ${project.basic.mainClass} extends ApplicationAdapter {
SpriteBatch batch;
private RNG rng;
private SquidLayers display;
private DungeonGenerator dungeonGen;
private char[][] decoDungeon, bareDungeon, lineDungeon;
private int[][] colorIndices, bgColorIndices;
/** In number of cells */
private int gridWidth;
/** In number of cells */
private int gridHeight;
/** The pixel width of a cell */
private int cellWidth;
/** The pixel height of a cell */
private int cellHeight;
private SquidInput input;
private Color bgColor;
private Stage stage;
private DijkstraMap playerToCursor;
private Coord cursor, player;
private List<Coord> toCursor;
private ArrayList<Coord> awaitedMoves;
private float secondsWithoutMoves;
private String[] lang;
private int langIndex = 0;
@Override
public void create () {
//These variables, corresponding to the screen's width and height in cells and a cell's width and height in
//pixels, must match the size you specified in the launcher for input to behave.
//This is one of the more common places a mistake can happen.
//In our desktop launcher, we gave these arguments to the configuration:
// configuration.width = 80 * 11;
// configuration.height = 30 * 20;
//Here, config.height refers to the total number of rows to be displayed on the screen.
//We're displaying 24 rows of dungeon, then 6 more rows of text generation to show some tricks with language.
//gridHeight is 24 because that variable will be used for generating the dungeon and handling movement within
//the upper 24 rows. Anything that refers to the full height, which happens rarely and usually for things like
//screen resizes, just uses gridHeight + 6. Next to it is gridWidth, which is 80 because we want 80 grid spaces
//across the whole screen. cellWidth and cellHeight are 11 and 20, and match the multipliers for config.width
//and config.height, but in this case don't strictly need to because we soon use a "Stretchable" font. While
//gridWidth and gridHeight are measured in spaces on the grid, cellWidth and cellHeight are the pixel dimensions
//of an individual cell. The font will look more crisp if the cell dimensions match the config multipliers
//exactly, and the stretchable fonts (technically, distance field fonts) can resize to non-square sizes and
//still retain most of that crispness.
gridWidth = 80;
gridHeight = 24;
cellWidth = 11;
cellHeight = 20;
// gotta have a random number generator. We can seed an RNG with any long we want, or even a String.
rng = new RNG("SquidLib!");
//Some classes in SquidLib need access to a batch to render certain things, so it's a good idea to have one.
batch = new SpriteBatch();
//Here we make sure our Stage, which holds any text-based grids we make, uses our Batch.
stage = new Stage(new StretchViewport(gridWidth * cellWidth, (gridHeight + 6) * cellHeight), batch);
// the font will try to load Inconsolata-LGC (custom) as an embedded bitmap font with a distance field effect.
// this font is covered under the SIL Open Font License (fully free), so there's no reason it can't be used.
display = new SquidLayers(gridWidth, gridHeight + 6, cellWidth, cellHeight,
DefaultResources.getStretchableFont());
// a bit of a hack to increase the text height slightly without changing the size of the cells they're in.
// this causes a tiny bit of overlap between cells, which gets rid of an annoying gap between vertical lines.
// if you use '#' for walls instead of box drawing chars, you don't need this.
display.setTextSize(cellWidth, cellHeight + 1);
// this makes animations very fast, which is good for multi-cell movement but bad for attack animations.
display.setAnimationDuration(0.03f);
//These need to have their positions set before adding any entities if there is an offset involved.
//There is no offset used here, but it's still a good practice here to set positions early on.
display.setPosition(0, 0);
//This uses the seeded RNG we made earlier to build a procedural dungeon using a method that takes rectangular
//sections of pre-drawn dungeon and drops them into place in a tiling pattern. It makes good "ruined" dungeons.
dungeonGen = new DungeonGenerator(gridWidth, gridHeight, rng);
//uncomment this next line to randomly add water to the dungeon in pools.
//dungeonGen.addWater(15);
//decoDungeon is given the dungeon with any decorations we specified. (Here, we didn't, unless you chose to add
//water to the dungeon. In that case, decoDungeon will have different contents than bareDungeon, next.)
decoDungeon = dungeonGen.generate();
//getBareDungeon provides the simplest representation of the generated dungeon -- '#' for walls, '.' for floors.
bareDungeon = dungeonGen.getBareDungeon();
//When we draw, we may want to use a nicer representation of walls. DungeonUtility has lots of useful methods
//for modifying char[][] dungeon grids, and this one takes each '#' and replaces it with a box-drawing character.
lineDungeon = DungeonUtility.hashesToLines(decoDungeon);
//Coord is the type we use as a general 2D point, usually in a dungeon.
//Because we know dungeons won't be incredibly huge, Coord performs best for x and y values less than 256, but
// by default it can also handle some negative x and y values (-3 is the lowest it can efficiently store). You
// can call Coord.expandPool() or Coord.expandPoolTo() if you need larger maps to be just as fast.
cursor = Coord.get(-1, -1);
// here, we need to get a random floor cell to place the player upon, without the possibility of putting him
// inside a wall. There are a few ways to do this in SquidLib. The most straightforward way is to randomly
// choose x and y positions until a floor is found, but particularly on dungeons with few floor cells, this can
// have serious problems -- if it takes too long to find a floor cell, either it needs to be able to figure out
// that random choice isn't working and instead choose the first it finds in simple iteration, or potentially
// keep trying forever on an all-wall map. There are better ways! These involve using a kind of specific storage
// for points or regions, getting that to store only floors, and finding a random cell from that collection of
// floors. The two kinds of such storage used commonly in SquidLib are the "packed data" as short[] produced by
// CoordPacker (which use very little memory, but can be slow, and are treated as unchanging by CoordPacker so
// any change makes a new array), and GreasedRegion objects (which use slightly more memory, tend to be faster
// on almost all operations compared to the same operations with CoordPacker, and default to changing the
// GreasedRegion object when you call a method on it instead of making a new one). Even though CoordPacker
// sometimes has better documentation, GreasedRegion is generally a better choice; it was added to address
// shortcomings in CoordPacker, particularly for speed, and the worst-case scenarios for data in CoordPacker are
// no problem whatsoever for GreasedRegion. CoordPacker is called that because it compresses the information
// for nearby Coords into a smaller amount of memory. GreasedRegion is called that because it encodes regions,
// but is "greasy" both in the fatty-food sense of using more space, and in the "greased lightning" sense of
// being especially fast. Both of them can be seen as storing regions of points in 2D space as "on" and "off."
// Here we fill a GreasedRegion so it stores the cells that contain a floor, the '.' char, as "on."
GreasedRegion placement = new GreasedRegion(bareDungeon, '.');
//player is, here, just a Coord that stores his position. In a real game, you would probably have a class for
//creatures, and possibly a subclass for the player. The singleRandom() method on GreasedRegion finds one Coord
// in that region that is "on," or -1,-1 if there are no such cells. It takes an RNG object as a parameter, and
// if you gave a seed to the RNG constructor, then the cell this chooses will be reliable for testing. If you
// don't seed the RNG, any valid cell should be possible.
player = placement.singleRandom(rng);
//This is used to allow clicks or taps to take the player to the desired area.
toCursor = new ArrayList<Coord>(200);
//When a path is confirmed by clicking, we draw from this List to find which cell is next to move into.
awaitedMoves = new ArrayList<Coord>(200);
//DijkstraMap is the pathfinding swiss-army knife we use here to find a path to the latest cursor position.
//DijkstraMap.Measurement is an enum that determines the possibility or preference to enter diagonals. Here, the
// MANHATTAN value is used, which means 4-way movement only, no diagonals possible. Alternatives are CHEBYSHEV,
// which allows 8 directions of movement at the same cost for all directions, and EUCLIDEAN, which allows 8
// directions, but will prefer orthogonal moves unless diagonal ones are clearly closer "as the crow flies."
playerToCursor = new DijkstraMap(decoDungeon, DijkstraMap.Measurement.MANHATTAN);
//These next two lines mark the player as something we want paths to go to or from, and get the distances to the
// player from all walkable cells in the dungeon.
playerToCursor.setGoal(player);
playerToCursor.scan(null);
//The next three lines set the background color for anything we don't draw on, but also create 2D arrays of the
//same size as decoDungeon that store simple indexes into a common list of colors, using the colors that looks
// up as the colors for the cell with the same x and y.
bgColor = SColor.DARK_SLATE_GRAY;
colorIndices = DungeonUtility.generatePaletteIndices(decoDungeon);
bgColorIndices = DungeonUtility.generateBGPaletteIndices(decoDungeon);
// this creates an array of sentences, where each imitates a different sort of language or mix of languages.
// this serves to demonstrate the large amount of glyphs SquidLib supports.
// there's no need to put much effort into understanding this section yet, and many games won't use the language
// generation code at all. If you want to know what this does, the parameters are:
// minimum words in a sentence, maximum words in a sentence, "mid" punctuation that can be after a word (like a
// comma), "end" punctuation that can be at the end of a sentence, frequency of "mid" punctuation (the chance in
// 1.0 that a word will have something like a comma appended after it), and the limit on how many chars to use.
lang = new String[]
{
FakeLanguageGen.ENGLISH.sentence(5, 10, new String[]{",", ",", ",", ";"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.17, gridWidth - 4),
FakeLanguageGen.GREEK_AUTHENTIC.sentence(5, 11, new String[]{",", ",", ";"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.2, gridWidth - 4),
FakeLanguageGen.GREEK_ROMANIZED.sentence(5, 11, new String[]{",", ",", ";"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.2, gridWidth - 4),
FakeLanguageGen.LOVECRAFT.sentence(3, 9, new String[]{",", ",", ";"},
new String[]{".", ".", "!", "!", "?", "...", "..."}, 0.15, gridWidth - 4),
FakeLanguageGen.FRENCH.sentence(4, 12, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.17, gridWidth - 4),
FakeLanguageGen.RUSSIAN_AUTHENTIC.sentence(6, 13, new String[]{",", ",", ",", ",", ";", " -"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.25, gridWidth - 4),
FakeLanguageGen.RUSSIAN_ROMANIZED.sentence(6, 13, new String[]{",", ",", ",", ",", ";", " -"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.25, gridWidth - 4),
FakeLanguageGen.JAPANESE_ROMANIZED.sentence(5, 13, new String[]{",", ",", ",", ",", ";"},
new String[]{".", ".", ".", "!", "?", "...", "..."}, 0.12, gridWidth - 4),
FakeLanguageGen.SWAHILI.sentence(4, 9, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?"}, 0.12, gridWidth - 4),
FakeLanguageGen.SOMALI.sentence(4, 9, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?"}, 0.12, gridWidth - 4),
FakeLanguageGen.HINDI_ROMANIZED.sentence(4, 9, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?"}, 0.12, gridWidth - 4),
FakeLanguageGen.ARABIC_ROMANIZED.sentence(4, 9, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?"}, 0.12, gridWidth - 4),
FakeLanguageGen.NORSE.addModifiers(FakeLanguageGen.Modifier.SIMPLIFY_NORSE).sentence(4, 9, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?"}, 0.12, gridWidth - 4),
FakeLanguageGen.INUKTITUT.sentence(4, 9, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?"}, 0.12, gridWidth - 4),
FakeLanguageGen.NAHUATL.sentence(4, 9, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?"}, 0.12, gridWidth - 4),
FakeLanguageGen.FANTASY_NAME.sentence(4, 8, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.22, gridWidth - 4),
FakeLanguageGen.FANCY_FANTASY_NAME.sentence(4, 8, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.22, gridWidth - 4),
FakeLanguageGen.GOBLIN.sentence(4, 8, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "?", "...", "..."}, 0.12, gridWidth - 4),
FakeLanguageGen.ELF.sentence(4, 8, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "?", "..."}, 0.22, gridWidth - 4),
FakeLanguageGen.DEMONIC.sentence(4, 8, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "!", "!", "..."}, 0.1, gridWidth - 4),
FakeLanguageGen.INFERNAL.sentence(4, 8, new String[]{",", ",", ",", ";", ";"},
new String[]{".", ".", ".", "?", "?", "..."}, 0.22, gridWidth - 4),
FakeLanguageGen.FRENCH.mix(FakeLanguageGen.JAPANESE_ROMANIZED, 0.65).sentence(5, 9, new String[]{",", ",", ",", ";"},
new String[]{".", ".", ".", "!", "?", "?", "..."}, 0.14, gridWidth - 4),
FakeLanguageGen.ENGLISH.addAccents(0.5, 0.15).sentence(5, 10, new String[]{",", ",", ",", ";"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.17, gridWidth - 4),
// mixAll is useful when mixing many languages; it takes alternating languages and weights for
// the preceding language, and doesn't care what order the pairs are given in (the mix method
// does care, which can be confusing when more than two languages are mixed).
FakeLanguageGen.mixAll(FakeLanguageGen.SWAHILI, 1.0, FakeLanguageGen.JAPANESE_ROMANIZED, 1.0, FakeLanguageGen.FRENCH, 1.0,
FakeLanguageGen.RUSSIAN_ROMANIZED, 1.0, FakeLanguageGen.GREEK_ROMANIZED, 1.0, FakeLanguageGen.ENGLISH, 1.2,
FakeLanguageGen.ELF, 1.0, FakeLanguageGen.LOVECRAFT, 0.75)
.sentence(5, 10, new String[]{",", ",", ",", ";"},
new String[]{".", ".", ".", "!", "?", "..."}, 0.2, gridWidth - 4),
};
// this is a big one.
// SquidInput can be constructed with a KeyHandler (which just processes specific keypresses), a SquidMouse
// (which is given an InputProcessor implementation and can handle multiple kinds of mouse move), or both.
// keyHandler is meant to be able to handle complex, modified key input, typically for games that distinguish
// between, say, 'q' and 'Q' for 'quaff' and 'Quip' or whatever obtuse combination you choose. The
// implementation here handles hjkl keys (also called vi-keys), numpad, arrow keys, and wasd for 4-way movement.
// Shifted letter keys produce capitalized chars when passed to KeyHandler.handle(), but we don't care about
// that so we just use two case statements with the same body, i.e. one for 'A' and one for 'a'.
// You can also set up a series of future moves by clicking within FOV range, using mouseMoved to determine the
// path to the mouse position with a DijkstraMap (called playerToCursor), and using touchUp to actually trigger
// the event when someone clicks.
input = new SquidInput(new SquidInput.KeyHandler() {
@Override
public void handle(char key, boolean alt, boolean ctrl, boolean shift) {
switch (key)
{
case SquidInput.UP_ARROW:
case 'k':
case 'w':
case 'K':
case 'W':
{
//-1 is up on the screen
move(0, -1);
break;
}
case SquidInput.DOWN_ARROW:
case 'j':
case 's':
case 'J':
case 'S':
{
//+1 is down on the screen
move(0, 1);
break;
}
case SquidInput.LEFT_ARROW:
case 'h':
case 'a':
case 'H':
case 'A':
{
move(-1, 0);
break;
}
case SquidInput.RIGHT_ARROW:
case 'l':
case 'd':
case 'L':
case 'D':
{
move(1, 0);
break;
}
case 'Q':
case 'q':
case SquidInput.ESCAPE:
{
Gdx.app.exit();
break;
}
}
}
},
//The second parameter passed to a SquidInput can be a SquidMouse, which takes mouse or touchscreen
//input and converts it to grid coordinates (here, a cell is 12 wide and 24 tall, so clicking at the
// pixel position 15,51 will pass screenX as 1 (since if you divide 15 by 12 and round down you get 1),
// and screenY as 2 (since 51 divided by 24 rounded down is 2)).
new SquidMouse(cellWidth, cellHeight, gridWidth, gridHeight, 0, 0, new InputAdapter() {
// if the user clicks and there are no awaitedMoves queued up, generate toCursor if it
// hasn't been generated already by mouseMoved, then copy it over to awaitedMoves.
@Override
public boolean touchUp(int screenX, int screenY, int pointer, int button) {
if(awaitedMoves.isEmpty()) {
if (toCursor.isEmpty()) {
cursor = Coord.get(screenX, screenY);
//This uses DijkstraMap.findPathPreScannned() to get a path as a List of Coord from the current
// player position to the position the user clicked on. The "PreScanned" part is an optimization
// that's special to DijkstraMap; because the whole map has already been fully analyzed by the
// DijkstraMap.scan() method at the start of the program, and re-calculated whenever the player
// moves, we only need to do a fraction of the work to find the best path with that info.
toCursor = playerToCursor.findPathPreScanned(cursor);
//findPathPreScanned includes the current cell (goal) by default, which is helpful when
// you're finding a path to a monster or loot, and want to bump into it, but here can be
// confusing because you would "move into yourself" as your first move without this.
if(!toCursor.isEmpty())
toCursor = toCursor.subList(1, toCursor.size());
}
awaitedMoves.addAll(toCursor);
}
return true;
}
@Override
public boolean touchDragged(int screenX, int screenY, int pointer) {
return mouseMoved(screenX, screenY);
}
// causes the path to the mouse position to become highlighted (toCursor contains a list of Coords that
// receive highlighting). Uses DijkstraMap.findPathPreScanned() to find the path, which is rather fast.
@Override
public boolean mouseMoved(int screenX, int screenY) {
if(!awaitedMoves.isEmpty())
return false;
if(cursor.x == screenX && cursor.y == screenY) {
return false;
}
cursor = Coord.get(screenX, screenY);
//This uses DijkstraMap.findPathPreScannned() to get a path as a List of Coord from the current
// player position to the position the user clicked on. The "PreScanned" part is an optimization
// that's special to DijkstraMap; because the whole map has already been fully analyzed by the
// DijkstraMap.scan() method at the start of the program, and re-calculated whenever the player
// moves, we only need to do a fraction of the work to find the best path with that info.
toCursor = playerToCursor.findPathPreScanned(cursor);
//findPathPreScanned includes the current cell (goal) by default, which is helpful when
// you're finding a path to a monster or loot, and want to bump into it, but here can be
// confusing because you would "move into yourself" as your first move without this.
if(!toCursor.isEmpty())
toCursor = toCursor.subList(1, toCursor.size());
return false;
}
}));
//Setting the InputProcessor is ABSOLUTELY NEEDED TO HANDLE INPUT
Gdx.input.setInputProcessor(new InputMultiplexer(stage, input));
//You might be able to get by with the next line instead of the above line, but the former is preferred.
//Gdx.input.setInputProcessor(input);
// and then add display, our one visual component, to the list of things that act in Stage.
stage.addActor(display);
}
/**
* Move the player if he isn't bumping into a wall or trying to go off the map somehow.
* In a fully-fledged game, this would not be organized like this, but this is a one-file demo.
* @param xmod
* @param ymod
*/
private void move(int xmod, int ymod) {
int newX = player.x + xmod, newY = player.y + ymod;
if (newX >= 0 && newY >= 0 && newX < gridWidth && newY < gridHeight
&& bareDungeon[newX][newY] != '#') {
// changing the player Coord is all we need to do here, because we re-calculate the distances to the player
// from all other cells only when we need to, that is, when the movement is finished (see render() ).
player = player.translate(xmod, ymod);
}
// loops through the text snippets displayed whenever the player moves
langIndex = (langIndex + 1) % lang.length;
}
/**
* Draws the map, applies any highlighting for the path to the cursor, and then draws the player.
*/
public void putMap()
{
for (int i = 0; i < gridWidth; i++) {
for (int j = 0; j < gridHeight; j++) {
display.put(i, j, lineDungeon[i][j], colorIndices[i][j], bgColorIndices[i][j], 40);
}
}
for (Coord pt : toCursor) {
// use a brighter light to trace the path to the cursor, from 170 max lightness to 0 min.
display.highlight(pt.x, pt.y, 100);
}
//places the player as an '@' at his position in orange.
display.put(player.x, player.y, '@', SColor.SAFETY_ORANGE);
//this helps compatibility with the HTML target, which doesn't support String.format()
char[] spaceArray = new char[gridWidth];
Arrays.fill(spaceArray, ' ');
String spaces = String.valueOf(spaceArray);
for (int i = 0; i < 4; i++) {
display.putString(0, gridHeight + i + 1, spaces, 0, 1);
display.putString(2, gridHeight + i + 1, lang[(langIndex + i) % lang.length], 0, 1);
}
}
@Override
public void render () {
// standard clear the background routine for libGDX
Gdx.gl.glClearColor(bgColor.r / 255.0f, bgColor.g / 255.0f, bgColor.b / 255.0f, 1.0f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
// need to display the map every frame, since we clear the screen to avoid artifacts.
putMap();
// if the user clicked, we have a list of moves to perform.
if(!awaitedMoves.isEmpty()) {
// this doesn't check for input, but instead processes and removes Coords from awaitedMoves.
secondsWithoutMoves += Gdx.graphics.getDeltaTime();
if (secondsWithoutMoves >= 0.1) {
secondsWithoutMoves = 0;
Coord m = awaitedMoves.remove(0);
toCursor.remove(0);
move(m.x - player.x, m.y - player.y);
}
// this only happens if we just removed the last Coord from awaitedMoves, and it's only then that we need to
// re-calculate the distances from all cells to the player. We don't need to calculate this information on
// each part of a many-cell move (just the end), nor do we need to calculate it whenever the mouse moves.
if(awaitedMoves.isEmpty()) {
// the next two lines remove any lingering data needed for earlier paths
playerToCursor.clearGoals();
playerToCursor.resetMap();
// the next line marks the player as a "goal" cell, which seems counter-intuitive, but it works because all
// cells will try to find the distance between themselves and the nearest goal, and once this is found, the
// distances don't change as long as the goals don't change. Since the mouse will move and new paths will be
// found, but the player doesn't move until a cell is clicked, the "goal" is the non-changing cell, so the
// player's position, and the "target" of a pathfinding method like DijkstraMap.findPathPreScanned() is the
// currently-moused-over cell, which we only need to set where the mouse is being handled.
playerToCursor.setGoal(player);
playerToCursor.scan(null);
}
}
// if we are waiting for the player's input and get input, process it.
else if(input.hasNext()) {
input.next();
}
// stage has its own batch and must be explicitly told to draw().
stage.draw();
// certain classes that use scene2d.ui widgets need to be told to act() to process input.
stage.act();
}
@Override
public void resize(int width, int height) {
super.resize(width, height);
//Very important to have the mouse behave correctly if the user fullscreens or resizes the game!
// here, the (float)height / (this.gridHeight + 6) refers to the height of a cell using the full area of the
// window. Since we have 6 rows of generated text but don't want those to be considered by the mouse, we
// give the gridHeight parameter our gridHeight (which includes only the dungeon map), but calculate the cell
// height using the height of the window (height) divided by (gridHeight + 6) to consider the 6 extra rows as
// contributing to that height, even though they aren't part of the grid.
input.getMouse().reinitialize((float) width / this.gridWidth, (float)height / (this.gridHeight + 6), this.gridWidth, this.gridHeight, 0, 0);
}
}"""
}
| unlicense | 878b20849e04e1c7333ac0af03a70533 | 64.574468 | 176 | 0.592708 | 4.525093 | false | false | false | false |
afollestad/material-dialogs | color/src/main/java/com/afollestad/materialdialogs/color/view/ObservableEditText.kt | 2 | 2268 | /**
* Designed and developed by Aidan Follestad (@afollestad)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("MemberVisibilityCanBePrivate", "unused")
package com.afollestad.materialdialogs.color.view
import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import androidx.annotation.StringRes
import androidx.appcompat.widget.AppCompatEditText
typealias TextListener = ((String) -> Unit)?
/** @author Aidan Follestad (@afollestad) */
class ObservableEditText(
context: Context,
attrs: AttributeSet? = null
) : AppCompatEditText(context, attrs) {
private var listener: TextListener = null
private var paused: Boolean = false
val textOrEmpty: String
get() = text?.toString()?.trim() ?: ""
val textLength: Int get() = textOrEmpty.length
override fun onAttachedToWindow() {
super.onAttachedToWindow()
addTextChangedListener(watcher)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
removeTextChangedListener(watcher)
}
fun observe(listener: TextListener) {
this.listener = listener
}
fun updateText(text: CharSequence) {
paused = true
setText(text)
}
fun updateText(@StringRes res: Int) {
paused = true
setText(res)
}
private val watcher = object : TextWatcher {
override fun beforeTextChanged(
s: CharSequence?,
start: Int,
count: Int,
after: Int
) = Unit
override fun onTextChanged(
s: CharSequence,
start: Int,
before: Int,
count: Int
) {
if (!paused) {
listener?.invoke(s.toString())
}
}
override fun afterTextChanged(s: Editable?) {
paused = false
}
}
}
| apache-2.0 | 9ffe68d25174b05ce149fcdf2c236c4b | 24.483146 | 75 | 0.698854 | 4.447059 | false | false | false | false |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/DesignersFragment.kt | 1 | 5401 | package com.boardgamegeek.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentDesignersBinding
import com.boardgamegeek.databinding.RowDesignerBinding
import com.boardgamegeek.entities.PersonEntity
import com.boardgamegeek.extensions.inflate
import com.boardgamegeek.extensions.loadThumbnailInList
import com.boardgamegeek.ui.adapter.AutoUpdatableAdapter
import com.boardgamegeek.ui.viewmodel.DesignersViewModel
import com.boardgamegeek.ui.widget.RecyclerSectionItemDecoration
import kotlin.properties.Delegates
class DesignersFragment : Fragment() {
private var _binding: FragmentDesignersBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<DesignersViewModel>()
private val adapter: DesignersAdapter by lazy { DesignersAdapter(viewModel) }
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentDesignersBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.setHasFixedSize(true)
binding.recyclerView.adapter = adapter
binding.recyclerView.addItemDecoration(
RecyclerSectionItemDecoration(resources.getDimensionPixelSize(R.dimen.recycler_section_header_height), adapter)
)
binding.swipeRefresh.setOnRefreshListener { viewModel.refresh() }
viewModel.designers.observe(viewLifecycleOwner) {
adapter.designers = it
binding.recyclerView.isVisible = adapter.itemCount > 0
binding.emptyTextView.isVisible = adapter.itemCount == 0
binding.progressBar.hide()
binding.swipeRefresh.isRefreshing = false
}
viewModel.progress.observe(viewLifecycleOwner) {
if (it == null) {
binding.horizontalProgressBar.progressContainer.isVisible = false
} else {
binding.horizontalProgressBar.progressContainer.isVisible = it.second > 0
binding.horizontalProgressBar.progressView.max = it.second
binding.horizontalProgressBar.progressView.progress = it.first
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
class DesignersAdapter(private val viewModel: DesignersViewModel) : RecyclerView.Adapter<DesignersAdapter.DesignerViewHolder>(),
AutoUpdatableAdapter, RecyclerSectionItemDecoration.SectionCallback {
var designers: List<PersonEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
autoNotify(oldValue, newValue) { old, new ->
old.id == new.id
}
}
init {
setHasStableIds(true)
}
override fun getItemCount() = designers.size
override fun getItemId(position: Int) = designers.getOrNull(position)?.id?.toLong() ?: RecyclerView.NO_ID
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DesignerViewHolder {
return DesignerViewHolder(parent.inflate(R.layout.row_designer))
}
override fun onBindViewHolder(holder: DesignerViewHolder, position: Int) {
holder.bind(designers.getOrNull(position))
}
override fun isSection(position: Int): Boolean {
if (position == RecyclerView.NO_POSITION) return false
if (designers.isEmpty()) return false
if (position == 0) return true
val thisLetter = viewModel.getSectionHeader(designers.getOrNull(position))
val lastLetter = viewModel.getSectionHeader(designers.getOrNull(position - 1))
return thisLetter != lastLetter
}
override fun getSectionHeader(position: Int): CharSequence {
return when {
position == RecyclerView.NO_POSITION -> "-"
designers.isEmpty() -> "-"
else -> viewModel.getSectionHeader(designers.getOrNull(position))
}
}
inner class DesignerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = RowDesignerBinding.bind(itemView)
fun bind(designer: PersonEntity?) {
designer?.let { d ->
binding.avatarView.loadThumbnailInList(d.thumbnailUrl, R.drawable.person_image_empty)
binding.nameView.text = d.name
binding.countView.text = itemView.context.resources.getQuantityString(R.plurals.games_suffix, d.itemCount, d.itemCount)
binding.whitmoreScoreView.text = itemView.context.getString(R.string.whitmore_score).plus(" ${d.whitmoreScore}")
itemView.setOnClickListener {
PersonActivity.startForDesigner(itemView.context, d.id, d.name)
}
}
}
}
}
}
| gpl-3.0 | 293b43187065e00d82e9212feaff7728 | 41.865079 | 139 | 0.680985 | 5.14381 | false | false | false | false |
BasinMC/Basin | sink/src/main/kotlin/org/basinmc/sink/extension/ExtensionManagerImpl.kt | 1 | 7202 | /*
* Copyright 2019 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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.basinmc.sink.extension
import org.apache.logging.log4j.LogManager
import org.basinmc.faucet.event.EventBus
import org.basinmc.faucet.event.extension.*
import org.basinmc.faucet.extension.Extension.Phase
import org.basinmc.faucet.extension.ExtensionManager
import org.basinmc.faucet.extension.error.ExtensionException
import org.basinmc.sink.util.LifecycleService
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Service
import java.io.IOException
import java.nio.file.Files
import java.nio.file.Path
import java.util.*
import java.util.concurrent.CopyOnWriteArrayList
import java.util.concurrent.locks.ReentrantLock
/**
* @author [Johannes Donath](mailto:[email protected])
* @since 1.0
*/
@Service
class ExtensionManagerImpl @Autowired
constructor(
private val ctx: ApplicationContext,
private val eventBus: EventBus,
@param:Value("\${basin.extension.dir:extensions/}") private val pluginDir: Path) :
LifecycleService(), ExtensionManager {
private val _extensions = CopyOnWriteArrayList<ExtensionImpl>()
override val extensions: List<ExtensionImpl>
get() = this._extensions
// TODO: Given a copy on write list we won't need to sync as long as only one thread writes to this list
private val lock = ReentrantLock()
private val registrations = CopyOnWriteArrayList<Path>() // TODO: Probably won't need CopyOnWrite
/**
* {@inheritDoc}
*/
override fun onStart() {
this.discover()
this.initialize()
super.onStart()
}
/**
* {@inheritDoc}
*/
override fun onStop() {
this.shutdown()
this.clearRegistry()
super.onStop()
}
/**
* Discovers all unregistered extension containers within the configured extension directory.
*/
fun discover() {
this.lock.lock()
try {
if (!Files.exists(this.pluginDir)) {
try {
Files.createDirectories(this.pluginDir)
logger.info("Created an empty extension directory")
} catch (ex: IOException) {
logger.warn("Cannot create extension directory", ex)
}
return
}
Files.list(this.pluginDir)
.filter { p -> p.toString().endsWith(ExtensionManager.CONTAINER_EXTENSION) }
.forEach(this::discover)
} catch (ex: IOException) {
logger.warn("Cannot index extension directory", ex)
} finally {
this.lock.unlock()
}
}
fun discover(path: Path) {
if (this.registrations.contains(path)) {
return
}
logger.debug("Indexing extension at path %s", path)
try {
val extension = ExtensionImpl(path)
val state = this.eventBus.post(ExtensionRegistrationEvent.Pre(extension))
if (state.has(ExtensionRegistrationEvent.State.REGISTER)) {
this.registrations.add(path)
this._extensions += extension
this.eventBus.post(ExtensionRegistrationEvent.Post(extension))
}
} catch (ex: ExtensionException) {
logger.error("Failed to load extension: $path", ex)
}
}
private fun initialize() {
logger.info("Extension system has entered startup")
logger.debug("Performing dependency resolve on new extensions")
this.extensions
.filter { e -> e.phase == Phase.REGISTERED }
.sorted()
.forEach { e ->
val state = this.eventBus.post(ExtensionResolveEvent.Pre(e))
if (!state.has(ExtensionResolveEvent.State.RESOLVE)) {
return@forEach
}
try {
e.resolve()
this.eventBus.post(ExtensionResolveEvent.Post(e))
} catch (ex: Throwable) {
logger.warn("Failed to resolve extension " + e.manifest.identifier + "#" + e
.manifest.version, ex)
}
}
logger.debug("Performing initialization on resolved extensions")
this.extensions
.filter { e -> e.phase == Phase.RESOLVED }
.sorted()
.forEach { e ->
val state = this.eventBus.post(ExtensionLoadEvent.Pre(e))
if (!state.has(ExtensionLoadEvent.State.LOAD)) {
return@forEach
}
try {
e.initialize()
this.eventBus.post(ExtensionLoadEvent.Post(e))
} catch (ex: Throwable) {
logger
.warn("Failed to initialize extension " + e.manifest.identifier + "#" + e
.manifest.version, ex)
e.close() // ensure loader is destroyed
}
}
logger.debug("Performing startup on loaded extensions")
this.extensions
.filter { e -> e.phase == Phase.LOADED }
.sorted()
.forEach { e ->
val state = this.eventBus.post(ExtensionRunEvent.Pre(e))
if (!state.has(ExtensionRunEvent.State.RUN)) {
return@forEach
}
try {
e.start(this.ctx)
this.eventBus.post(ExtensionRunEvent.Post(e))
} catch (ex: Throwable) {
logger
.warn("Failed to start extension " + e.manifest.identifier + "#" + e
.manifest.version, ex)
e.close() // ensure context and loader are destroyed
}
}
logger.info("Extension system startup complete")
}
private fun clearRegistry() {
this.lock.lock()
try {
val extensions = ArrayList(this.extensions)
extensions.forEach { e -> this.eventBus.post(ExtensionRemovalEvent.Pre(e)) }
this._extensions.clear()
this.registrations.clear()
extensions.forEach { e -> this.eventBus.post(ExtensionRemovalEvent.Post(e)) }
} finally {
this.lock.unlock()
}
}
private fun shutdown() {
logger.info("Extension system is shutting down")
logger.debug("Performing clean extension shutdown")
this.extensions
.filter { e -> e.phase == Phase.RUNNING }
.sorted()
.forEach { e ->
this.eventBus.post(ExtensionShutdownEvent.Pre(e))
try {
e.close()
} catch (ex: Throwable) {
logger.warn("Failed to perform graceful shutdown of extension " + e.manifest
.identifier + "#" + e.manifest.version, ex)
}
this.eventBus.post(ExtensionShutdownEvent.Post(e))
}
}
companion object {
private val logger = LogManager.getFormatterLogger(ExtensionManagerImpl::class.java)
}
}
| apache-2.0 | 6252a148206394d2f65ff6bcdda8b1b2 | 30.043103 | 106 | 0.644265 | 4.367495 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/handler/handshake/HandshakeHandler.kt | 1 | 7108 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.handler.handshake
import com.google.common.collect.LinkedHashMultimap
import com.google.common.collect.Multimap
import com.google.gson.Gson
import com.google.gson.JsonObject
import io.netty.handler.codec.CodecException
import org.lanternpowered.api.text.textOf
import org.lanternpowered.api.text.toText
import org.lanternpowered.api.text.translatableTextOf
import org.lanternpowered.server.game.Lantern
import org.lanternpowered.server.network.NetworkContext
import org.lanternpowered.server.network.NetworkSession
import org.lanternpowered.server.network.ProxyType
import org.lanternpowered.server.network.packet.PacketHandler
import org.lanternpowered.server.network.protocol.ProtocolState
import org.lanternpowered.server.network.vanilla.packet.handler.login.LoginStartHandler
import org.lanternpowered.server.network.vanilla.packet.type.handshake.HandshakePacket
import org.lanternpowered.server.profile.LanternGameProfile
import org.lanternpowered.server.profile.LanternProfileProperty
import org.lanternpowered.server.util.UUIDHelper
import org.lanternpowered.server.util.gson.fromJson
import org.spongepowered.api.profile.property.ProfileProperty
import java.net.InetSocketAddress
object HandshakeHandler : PacketHandler<HandshakePacket> {
private const val fmlMarker = "\u0000FML\u0000"
private val gson = Gson()
override fun handle(ctx: NetworkContext, packet: HandshakePacket) {
val nextState = ProtocolState.byId(packet.nextState)
val session = ctx.session
if (nextState == null) {
session.close(translatableTextOf("Unknown protocol state! ($nextState)"))
return
}
session.protocolState = nextState
if (nextState != ProtocolState.Login && nextState != ProtocolState.Status) {
session.close(translatableTextOf("Received a unexpected handshake message! ($nextState)"))
return
}
val proxyType = ctx.game.config.server.proxy.type
var hostname = packet.hostname
val virtualAddress: InetSocketAddress
when (proxyType) {
ProxyType.WATERFALL, ProxyType.BUNGEE_CORD, ProxyType.VELOCITY -> {
var split = hostname.split("\u0000\\|".toRegex(), 2).toTypedArray()
// Check for a fml marker
session.attr(NetworkSession.FML_MARKER).set(split.size == 2 == split[1].contains(fmlMarker))
split = split[0].split("\u0000").toTypedArray()
if (split.size == 3 || split.size == 4) {
virtualAddress = InetSocketAddress(split[1], packet.port)
val uniqueId = UUIDHelper.parseFlatString(split[2])
val properties = if (split.size == 4) {
try {
LanternProfileProperty.createPropertiesMapFromJson(gson.fromJson(split[3]))
} catch (e: Exception) {
session.close(textOf("Invalid ${proxyType.displayName} proxy data format."))
throw CodecException(e)
}
} else {
LinkedHashMultimap.create()
}
session.attr(LoginStartHandler.SPOOFED_GAME_PROFILE).set(LanternGameProfile(uniqueId, null, properties))
} else {
session.close(textOf("Please enable client detail forwarding (also known as \"ip forwarding\") on "
+ "your proxy if you wish to use it on this server, and also make sure that you joined through the proxy."))
return
}
}
ProxyType.LILY_PAD -> {
virtualAddress = try {
val jsonObject = gson.fromJson<JsonObject>(hostname)
val securityKey = ctx.game.config.server.proxy.securityKey
// Validate the security key
if (securityKey.isNotEmpty() && jsonObject["s"].asString != securityKey) {
session.close(textOf("Proxy security key mismatch"))
Lantern.getLogger().warn("Proxy security key mismatch for the player {}", jsonObject["n"].asString)
return
}
val name = jsonObject["n"].asString
val uniqueId = UUIDHelper.parseFlatString(jsonObject["u"].asString)
val properties: Multimap<String, ProfileProperty> = LinkedHashMultimap.create()
if (jsonObject.has("p")) {
val jsonArray = jsonObject.getAsJsonArray("p")
for (property in jsonArray) {
property as JsonObject
val propertyName = property["n"].asString
val propertyValue = property["v"].asString
val propertySignature = if (property.has("s")) property["s"].asString else null
properties.put(propertyName, LanternProfileProperty(propertyName, propertyValue, propertySignature))
}
}
session.attr(LoginStartHandler.SPOOFED_GAME_PROFILE).set(LanternGameProfile(uniqueId, name, properties))
session.attr(NetworkSession.FML_MARKER).set(false)
val port = jsonObject["rP"].asInt
val host = jsonObject["h"].asString
InetSocketAddress(host, port)
} catch (e: Exception) {
session.close(textOf("Invalid ${proxyType.displayName} proxy data format."))
throw CodecException(e)
}
}
ProxyType.NONE -> {
val index = hostname.indexOf(this.fmlMarker)
session.attr(NetworkSession.FML_MARKER).set(index != -1)
if (index != -1) {
hostname = hostname.substring(0, index)
}
virtualAddress = InetSocketAddress(hostname, packet.port)
}
}
session.virtualHost = virtualAddress
session.protocolVersion = packet.protocolVersion
if (nextState == ProtocolState.Login) {
val version = ctx.game.platform.minecraftVersion
if (packet.protocolVersion < version.protocol) {
session.close(translatableTextOf("multiplayer.disconnect.outdated_client", version.name.toText()))
} else if (packet.protocolVersion > version.protocol) {
session.close(translatableTextOf("multiplayer.disconnect.outdated_server", version.name.toText()))
}
}
}
}
| mit | 1c321a02e899214ce02f05a9baade8a9 | 51.264706 | 136 | 0.613112 | 5.077143 | false | false | false | false |
mercadopago/px-android | px-services/src/main/java/com/mercadopago/android/px/internal/core/PlatformInterceptor.kt | 1 | 982 | package com.mercadopago.android.px.internal.core
import android.content.Context
import okhttp3.Interceptor
import okhttp3.Response
import java.io.IOException
class PlatformInterceptor(context: Context) : Interceptor {
private val currentPlatform = getPlatform(context)
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val request = originalRequest.newBuilder()
.header(HEADER_PLATFORM, currentPlatform)
.build()
return chain.proceed(request)
}
private fun getPlatform(context: Context): String {
val packageName = context.applicationInfo.packageName
return if (packageName.contains("com.mercadolibre")) PLATFORM_ML else PLATFORM_MP
}
companion object {
private const val HEADER_PLATFORM = "x-platform"
private const val PLATFORM_MP = "MP"
private const val PLATFORM_ML = "ML"
}
} | mit | 4e260bb4db1318f3febd6ded496b0eba | 31.766667 | 89 | 0.703666 | 4.721154 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/data/api/app/model/AppListWrapper.kt | 1 | 684 | package me.ykrank.s1next.data.api.app.model
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonProperty
/**
* Created by ykrank on 2017/7/22.
*/
@JsonIgnoreProperties(ignoreUnknown = true)
open class AppListWrapper<D> : AppDataWrapper<BaseAppList<D>>()
@JsonIgnoreProperties(ignoreUnknown = true)
class BaseAppList<D> {
@JsonProperty("pageNo")
var pageNo: Int = 0
@JsonProperty("pageSize")
var pageSize: Int = 0
@JsonProperty("totalCount")
var totalCount: Int = 0
@JsonProperty("webpageurl")
var webPageUrl: String? = null
@JsonProperty("list")
var list: ArrayList<D> = arrayListOf()
} | apache-2.0 | 2237d99df6f7621f3cb0a4ab9ba78b80 | 27.541667 | 63 | 0.726608 | 3.886364 | false | false | false | false |
timusus/Shuttle | app/src/main/java/com/simplecity/amp_library/utils/playlists/FavoritesPlaylistManager.kt | 1 | 5750 | package com.simplecity.amp_library.utils.playlists
import android.content.ContentValues
import android.content.Context
import android.provider.MediaStore
import android.support.v4.util.Pair
import com.simplecity.amp_library.R
import com.simplecity.amp_library.data.PlaylistsRepository
import com.simplecity.amp_library.data.SongsRepository
import com.simplecity.amp_library.model.Playlist
import com.simplecity.amp_library.model.Playlist.Type
import com.simplecity.amp_library.model.Song
import com.simplecity.amp_library.utils.LogUtils
import io.reactivex.Completable
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import java.util.Collections
import java.util.concurrent.TimeUnit
import javax.inject.Inject
class FavoritesPlaylistManager @Inject constructor(
private val applicationContext: Context,
private val playlistManager: PlaylistManager,
private val playlistsRepository: PlaylistsRepository,
private val songsRepository: SongsRepository
) {
fun getFavoritesPlaylist(): Single<Playlist?> {
return playlistsRepository.getPlaylists()
.first(Collections.emptyList())
.flatMapObservable { playlists -> Observable.fromIterable(playlists) }
.filter { playlist -> playlist.type == Type.FAVORITES }
.switchIfEmpty(Maybe.fromCallable { createFavoritePlaylist() }.toObservable())
.firstOrError()
.doOnError { throwable -> LogUtils.logException(TAG, "getFavoritesPlaylist failed", throwable) }
}
fun isFavorite(song: Song?): Observable<Boolean> {
return if (song == null) {
Observable.just(false)
} else getFavoritesPlaylist().flatMapObservable { playlist -> songsRepository.getSongs(playlist) }
.map { songs -> songs.contains(song) }
}
fun createFavoritePlaylist(): Playlist? {
val playlist = playlistManager.createPlaylist(applicationContext.getString(R.string.fav_title))
if (playlist != null) {
playlist.canDelete = false
playlist.canRename = false
playlist.type = Playlist.Type.FAVORITES
}
return playlist
}
fun clearFavorites(): Disposable {
return getFavoritesPlaylist()
.flatMapCompletable { playlist ->
Completable.fromAction {
val uri = MediaStore.Audio.Playlists.Members.getContentUri("external", playlist.id)
applicationContext.contentResolver.delete(uri, null, null)
}
}
.subscribeOn(Schedulers.io())
.subscribe(
{ },
{ throwable -> LogUtils.logException(TAG, "clearFavorites error", throwable) }
)
}
fun toggleFavorite(song: Song, isFavorite: (Boolean) -> Unit): Disposable {
return isFavorite(song)
.first(false)
.subscribeOn(Schedulers.io())
.subscribe(
{ favorite ->
if (!favorite) {
addToFavorites(song) { success ->
if (success) {
isFavorite.invoke(true)
}
}
} else {
removeFromFavorites(song) { success ->
if (success) {
isFavorite.invoke(false)
}
}
}
},
{ error -> LogUtils.logException(TAG, "PlaylistManager: Error toggling favorites", error) }
)
}
fun addToFavorites(song: Song, success: (Boolean) -> Unit): Disposable {
return Single.zip<Playlist, Int, Pair<Playlist, Int>>(
getFavoritesPlaylist(),
getFavoritesPlaylist().flatMapObservable<List<Song>> { songsRepository.getSongs(it) }
.first(emptyList())
.map { it.size },
BiFunction { first, second -> Pair(first, second) })
.map { pair ->
val uri = MediaStore.Audio.Playlists.Members.getContentUri("external", pair.first!!.id)
val values = ContentValues()
values.put(MediaStore.Audio.Playlists.Members.AUDIO_ID, song.id)
values.put(MediaStore.Audio.Playlists.Members.PLAY_ORDER, pair.second!! + 1)
val newUri = applicationContext.contentResolver.insert(uri, values)
applicationContext.contentResolver.notifyChange(MediaStore.Audio.Playlists.EXTERNAL_CONTENT_URI, null)
newUri != null
}
.delay(150, TimeUnit.MILLISECONDS)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ success.invoke(it) },
{ throwable -> LogUtils.logException(TAG, "Error adding to playlist", throwable) }
)
}
fun removeFromFavorites(song: Song, callback: (Boolean) -> Unit): Disposable {
return getFavoritesPlaylist()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ playlist -> playlist?.let { playlistManager.removeFromPlaylist(it, song, callback) } },
{ error -> LogUtils.logException(TAG, "PlaylistManager: Error Removing from favorites", error) }
)
}
companion object {
private val TAG = "FavoritesPlaylistManage"
}
} | gpl-3.0 | a3d142ca373bc393e4e712885f14380f | 40.374101 | 118 | 0.612522 | 5.156951 | false | false | false | false |
didi/DoraemonKit | Android/dokit-ft/src/main/java/com/didichuxing/doraemonkit/kit/filemanager/sqlite/dao/EncryptSQLiteDB.kt | 1 | 1435 | package com.didichuxing.doraemonkit.kit.filemanager.sqlite.dao
import android.content.ContentValues
import android.database.Cursor
import com.tencent.wcdb.database.SQLiteDatabase
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/6/24-16:40
* 描 述:
* 修订历史:
* ================================================
*/
class EncryptSQLiteDB(private val database: SQLiteDatabase) : SQLiteDB {
override fun delete(table: String, whereClause: String, whereArgs: Array<String>):Int {
return database.delete(table, whereClause, whereArgs)
}
override fun isOpen(): Boolean {
return database.isOpen
}
override fun close() {
database.close()
}
override fun rawQuery(sql: String, selectionArgs: Array<String>?): Cursor? {
return database.rawQuery(sql, selectionArgs)
}
override fun execSQL(sql: String) {
database.execSQL(sql)
}
override fun insert(table: String, nullColumnHack: String?, values: ContentValues): Long {
return database.insert(table, nullColumnHack, values)
}
override fun update(table: String, values: ContentValues, whereClause: String, whereArgs: Array<String>): Int {
return database.update(table, values, whereClause, whereArgs)
}
override fun getVersion(): Int {
return database.version
}
} | apache-2.0 | 56caae863d3c37f35c326aeeb838162f | 27.367347 | 115 | 0.63067 | 4.381703 | false | false | false | false |
wiltonlazary/kotlin-native | shared/src/library/kotlin/org/jetbrains/kotlin/konan/library/impl/KonanLibraryWriterImpl.kt | 1 | 2745 | /*
* 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 org.jetbrains.kotlin.konan.library.impl
import org.jetbrains.kotlin.konan.library.BitcodeWriter
import org.jetbrains.kotlin.konan.library.KonanLibraryWriter
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.library.KonanLibrary
import org.jetbrains.kotlin.konan.library.KonanLibraryLayout
import org.jetbrains.kotlin.konan.properties.Properties
import org.jetbrains.kotlin.konan.target.KonanTarget
import org.jetbrains.kotlin.library.*
import org.jetbrains.kotlin.library.impl.*
class KonanLibraryLayoutForWriter(
override val libDir: File,
override val target: KonanTarget
) : KonanLibraryLayout, KotlinLibraryLayoutForWriter(libDir)
/**
* Requires non-null [target].
*/
class KonanLibraryWriterImpl(
libDir: File,
moduleName: String,
versions: KotlinLibraryVersioning,
target: KonanTarget,
builtInsPlatform: BuiltInsPlatform,
nopack: Boolean = false,
shortName: String? = null,
val layout: KonanLibraryLayoutForWriter = KonanLibraryLayoutForWriter(libDir, target),
base: BaseWriter = BaseWriterImpl(layout, moduleName, versions, builtInsPlatform, listOf(target.visibleName), nopack, shortName),
bitcode: BitcodeWriter = BitcodeWriterImpl(layout),
metadata: MetadataWriter = MetadataWriterImpl(layout),
ir: IrWriter = IrMonoliticWriterImpl(layout)
) : BaseWriter by base, BitcodeWriter by bitcode, MetadataWriter by metadata, IrWriter by ir, KonanLibraryWriter
fun buildLibrary(
natives: List<String>,
included: List<String>,
linkDependencies: List<KonanLibrary>,
metadata: SerializedMetadata,
ir: SerializedIrModule?,
versions: KotlinLibraryVersioning,
target: KonanTarget,
output: String,
moduleName: String,
nopack: Boolean,
shortName: String?,
manifestProperties: Properties?,
dataFlowGraph: ByteArray?
): KonanLibraryLayout {
val library = KonanLibraryWriterImpl(
File(output),
moduleName,
versions,
target,
BuiltInsPlatform.NATIVE,
nopack,
shortName
)
library.addMetadata(metadata)
if (ir != null) {
library.addIr(ir)
}
natives.forEach {
library.addNativeBitcode(it)
}
included.forEach {
library.addIncludedBinary(it)
}
manifestProperties?.let { library.addManifestAddend(it) }
library.addLinkDependencies(linkDependencies)
dataFlowGraph?.let { library.addDataFlowGraph(it) }
library.commit()
return library.layout
}
| apache-2.0 | a3ca8df7d2f03c2c72084c10d5b76d02 | 30.551724 | 137 | 0.71694 | 4.371019 | false | false | false | false |
hypercube1024/firefly | firefly-common/src/main/kotlin/com/fireflysource/common/coroutine/CommonCoroutinePool.kt | 1 | 6853 | package com.fireflysource.common.coroutine
import com.fireflysource.common.concurrent.ExecutorServiceUtils.shutdownAndAwaitTermination
import com.fireflysource.common.coroutine.CoroutineDispatchers.awaitTerminationTimeout
import com.fireflysource.common.ref.Cleaner
import kotlinx.coroutines.*
import java.util.concurrent.*
import java.util.concurrent.atomic.AtomicInteger
/**
* @author Pengtao Qiu
*/
object CoroutineDispatchers {
val availableProcessors = Runtime.getRuntime().availableProcessors()
val awaitTerminationTimeout =
Integer.getInteger("com.fireflysource.common.coroutine.awaitTerminationTimeout", 5).toLong()
val defaultPoolSize: Int =
Integer.getInteger("com.fireflysource.common.coroutine.defaultPoolSize", availableProcessors)
val defaultPoolKeepAliveTime: Long =
Integer.getInteger("com.fireflysource.common.coroutine.defaultPoolKeepAliveTime", 30).toLong()
val ioBlockingPoolSize: Int = Integer.getInteger(
"com.fireflysource.common.coroutine.ioBlockingPoolSize",
64.coerceAtLeast(availableProcessors)
)
val ioBlockingPoolKeepAliveTime: Long =
Integer.getInteger("com.fireflysource.common.coroutine.ioBlockingPoolKeepAliveTime", 30).toLong()
val ioBlockingThreadPool: ExecutorService by lazy {
val threadId = AtomicInteger()
ThreadPoolExecutor(
availableProcessors, ioBlockingPoolSize,
ioBlockingPoolKeepAliveTime, TimeUnit.SECONDS,
LinkedTransferQueue()
) { runnable -> Thread(runnable, "firefly-io-blocking-pool-" + threadId.getAndIncrement()) }
}
val singleThreadPool: ExecutorService by lazy {
ThreadPoolExecutor(
1, 1, 0, TimeUnit.MILLISECONDS,
LinkedTransferQueue()
) { runnable -> Thread(runnable, "firefly-single-thread-pool") }
}
val computationThreadPool: ExecutorService by lazy {
ForkJoinPool(defaultPoolSize, { pool ->
val worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool)
worker.name = "firefly-computation-pool-" + worker.poolIndex
worker
}, null, true)
}
val computation: CoroutineDispatcher by lazy { computationThreadPool.asCoroutineDispatcher() }
val ioBlocking: CoroutineDispatcher by lazy { ioBlockingThreadPool.asCoroutineDispatcher() }
val singleThread: CoroutineDispatcher by lazy { singleThreadPool.asCoroutineDispatcher() }
val scheduler: ScheduledExecutorService by lazy {
Executors.newScheduledThreadPool(defaultPoolSize) {
Thread(it, "firefly-scheduler-thread")
}
}
fun newSingleThreadExecutor(name: String): ExecutorService {
val executor = ThreadPoolExecutor(
1, 1, 0, TimeUnit.MILLISECONDS,
LinkedTransferQueue()
) { runnable -> Thread(runnable, name) }
return FinalizableExecutorService(executor)
}
fun newFixedThreadExecutor(name: String, poolSize: Int, maxPoolSize: Int = poolSize): ExecutorService {
val executor = ThreadPoolExecutor(
poolSize,
maxPoolSize,
defaultPoolKeepAliveTime, TimeUnit.SECONDS,
LinkedTransferQueue()
) { runnable -> Thread(runnable, name) }
return FinalizableExecutorService(executor)
}
fun newComputationThreadExecutor(name: String, asyncMode: Boolean = true): ExecutorService {
val executor = ForkJoinPool(defaultPoolSize, { pool ->
val worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool)
worker.name = name + "-" + worker.poolIndex
worker
}, null, asyncMode)
return FinalizableExecutorService(executor)
}
fun newSingleThreadDispatcher(name: String): CoroutineDispatcher {
return newSingleThreadExecutor(name).asCoroutineDispatcher()
}
fun newFixedThreadDispatcher(name: String, poolSize: Int, maxPoolSize: Int = poolSize): CoroutineDispatcher {
return newFixedThreadExecutor(name, poolSize, maxPoolSize).asCoroutineDispatcher()
}
fun newComputationThreadDispatcher(name: String, asyncMode: Boolean = true): CoroutineDispatcher {
return newComputationThreadExecutor(name, asyncMode).asCoroutineDispatcher()
}
fun stopAll() {
shutdownAndAwaitTermination(computationThreadPool, awaitTerminationTimeout, TimeUnit.SECONDS)
shutdownAndAwaitTermination(singleThreadPool, awaitTerminationTimeout, TimeUnit.SECONDS)
shutdownAndAwaitTermination(ioBlockingThreadPool, awaitTerminationTimeout, TimeUnit.SECONDS)
shutdownAndAwaitTermination(scheduler, awaitTerminationTimeout, TimeUnit.SECONDS)
}
}
val applicationCleaner: Cleaner = Cleaner.create()
class ExecutorCleanTask(private val executor: ExecutorService) : Runnable {
override fun run() {
if (!executor.isShutdown) {
shutdownAndAwaitTermination(executor, awaitTerminationTimeout, TimeUnit.SECONDS)
}
}
}
class FinalizableExecutorService(private val executor: ExecutorService) : ExecutorService by executor {
init {
applicationCleaner.register(this, ExecutorCleanTask(executor))
}
}
class FinalizableScheduledExecutorService(private val executor: ScheduledExecutorService) :
ScheduledExecutorService by executor {
init {
applicationCleaner.register(this, ExecutorCleanTask(executor))
}
}
val applicationScope = CoroutineScope(CoroutineName("Firefly-Application"))
inline fun compute(crossinline block: suspend CoroutineScope.() -> Unit): Job =
applicationScope.launch(CoroutineDispatchers.computation) { block(this) }
inline fun <T> computeAsync(crossinline block: suspend CoroutineScope.() -> T): Deferred<T> =
applicationScope.async(CoroutineDispatchers.computation) { block(this) }
inline fun blocking(crossinline block: suspend CoroutineScope.() -> Unit): Job =
applicationScope.launch(CoroutineDispatchers.ioBlocking) { block(this) }
inline fun <T> blockingAsync(crossinline block: suspend CoroutineScope.() -> T): Deferred<T> =
applicationScope.async(CoroutineDispatchers.ioBlocking) { block(this) }
inline fun event(crossinline block: suspend CoroutineScope.() -> Unit): Job =
applicationScope.launch(CoroutineDispatchers.singleThread) { block(this) }
inline fun <T> eventAsync(crossinline block: suspend CoroutineScope.() -> T): Deferred<T> =
applicationScope.async(CoroutineDispatchers.singleThread) { block(this) }
inline fun CoroutineScope.blocking(crossinline block: suspend CoroutineScope.() -> Unit): Job =
this.launch(CoroutineDispatchers.ioBlocking) { block(this) }
inline fun <T> CoroutineScope.blockingAsync(crossinline block: suspend CoroutineScope.() -> T): Deferred<T> =
this.async(CoroutineDispatchers.ioBlocking) { block(this) } | apache-2.0 | 9e7141789bb53a82d1b7fd8ece0c077c | 41.308642 | 113 | 0.733693 | 5.080059 | false | false | false | false |
genobis/tornadofx | src/main/java/tornadofx/Animation.kt | 1 | 38183 | package tornadofx
import javafx.animation.*
import javafx.beans.value.WritableValue
import javafx.event.ActionEvent
import javafx.event.EventHandler
import javafx.geometry.Point2D
import javafx.scene.Node
import javafx.scene.layout.Background
import javafx.scene.layout.BackgroundFill
import javafx.scene.layout.Pane
import javafx.scene.layout.StackPane
import javafx.scene.paint.Color
import javafx.scene.paint.Paint
import javafx.scene.shape.Shape
import javafx.scene.transform.Rotate
import javafx.util.Duration
import java.util.*
operator fun Timeline.plusAssign(keyFrame: KeyFrame) {
keyFrames.add(keyFrame)
}
operator fun KeyFrame.plusAssign(keyValue: KeyValue) {
values.add(keyValue)
}
fun SequentialTransition.timeline(op: (Timeline).() -> Unit): Timeline {
val timeline = timeline(false, op)
children.add(timeline)
return timeline
}
fun ParallelTransition.timeline(op: (Timeline).() -> Unit): Timeline {
val timeline = timeline(false, op)
children.add(timeline)
return timeline
}
fun sequentialTransition(play: Boolean = true, op: (SequentialTransition.() -> Unit)) = SequentialTransition().apply {
op(this)
if (play) play()
}
fun parallelTransition(play: Boolean = true, op: (ParallelTransition.() -> Unit)) = ParallelTransition().apply {
op(this)
if (play) play()
}
fun timeline(play: Boolean = true, op: (Timeline).() -> Unit): Timeline {
val timeline = Timeline()
timeline.op()
if (play) timeline.play()
return timeline
}
/**
* A convenience function for creating a [TranslateTransition] on a [UIComponent].
*
* @param time How long the animation will take
* @param destination Where to move the component (relative to its translation origin)
* @param easing How to interpolate the motion
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A TranslateTransition on this component
*/
fun UIComponent.move(time: Duration, destination: Point2D,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (TranslateTransition.() -> Unit)? = null)
= root.move(time, destination, easing, reversed, play, op)
/**
* A convenience function for creating a [TranslateTransition] on a [Node].
*
* @param time How long the animation will take
* @param destination Where to move the node (relative to its translation origin)
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A TranslateTransition on this node
*/
fun Node.move(time: Duration, destination: Point2D,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (TranslateTransition.() -> Unit)? = null): TranslateTransition {
val target: Point2D
if (reversed) {
target = point(translateX, translateY)
translateX = destination.x
translateY = destination.y
} else {
target = destination
}
return TranslateTransition(time, this).apply {
interpolator = easing
op?.invoke(this)
toX = target.x
toY = target.y
if (play) play()
}
}
/**
* A convenience function for creating a [RotateTransition] on a [UIComponent].
*
* @param time How long the animation will take
* @param angle How far to rotate the component (in degrees; relative to its 0 rotation)
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A RotateTransition on this component
*/
fun UIComponent.rotate(time: Duration, angle: Number,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (RotateTransition.() -> Unit)? = null)
= root.rotate(time, angle, easing, reversed, play, op)
/**
* A convenience function for creating a [RotateTransition] on a [Node].
*
* @param time How long the animation will take
* @param angle How far to rotate the node (in degrees; relative to its 0 rotation)
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A RotateTransition on this node
*/
fun Node.rotate(time: Duration, angle: Number,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (RotateTransition.() -> Unit)? = null): RotateTransition {
val target: Double
if (reversed) {
target = rotate
rotate = angle.toDouble()
} else {
target = angle.toDouble()
}
return RotateTransition(time, this).apply {
interpolator = easing
op?.invoke(this)
toAngle = target
if (play) play()
}
}
/**
* A convenience function for creating a [ScaleTransition] on a [UIComponent].
*
* @param time How long the animation will take
* @param scale How to scale the component (relative to its default scale)
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A ScaleTransition on this component
*/
fun UIComponent.scale(time: Duration, scale: Point2D,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (ScaleTransition.() -> Unit)? = null)
= root.scale(time, scale, easing, reversed, play, op)
/**
* A convenience function for creating a [ScaleTransition] on a [Node].
*
* @param time How long the animation will take
* @param scale How to scale the node (relative to its default scale)
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A ScaleTransition on this node
*/
fun Node.scale(time: Duration, scale: Point2D,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (ScaleTransition.() -> Unit)? = null): ScaleTransition {
val target: Point2D
if (reversed) {
target = point(scaleX, scaleY)
scaleX = scale.x
scaleY = scale.y
} else {
target = scale
}
return ScaleTransition(time, this).apply {
interpolator = easing
op?.invoke(this)
toX = target.x
toY = target.y
if (play) play()
}
}
/**
* A convenience function for creating a [FadeTransition] on a [UIComponent].
*
* @param time How long the animation will take
* @param opacity The final opacity of the component
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A FadeTransition on this component
*/
fun UIComponent.fade(time: Duration, opacity: Number,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (FadeTransition.() -> Unit)? = null)
= root.fade(time, opacity, easing, reversed, play, op)
/**
* A convenience function for creating a [FadeTransition] on a [Node].
*
* @param time How long the animation will take
* @param opacity The final opacity of the node
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A FadeTransition on this node
*/
fun Node.fade(time: Duration, opacity: Number,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (FadeTransition.() -> Unit)? = null): FadeTransition {
val target: Double
if (reversed) {
target = this.opacity
this.opacity = opacity.toDouble()
} else {
target = opacity.toDouble()
}
return FadeTransition(time, this).apply {
interpolator = easing
op?.invoke(this)
toValue = target
if (play) play()
}
}
/**
* A convenience function for creating a [TranslateTransition], [RotateTransition], [ScaleTransition], [FadeTransition]
* on a [UIComponent] that all run simultaneously.
*
* @param time How long the animation will take
* @param destination Where to move the component (relative to its translation origin)
* @param angle How far to rotate the component (in degrees; relative to its 0 rotation)
* @param scale How to scale the component (relative to its default scale)
* @param opacity The final opacity of the component
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A ParallelTransition on this component
*/
fun UIComponent.transform(time: Duration, destination: Point2D, angle: Number, scale: Point2D, opacity: Number,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (ParallelTransition.() -> Unit)? = null)
= root.transform(time, destination, angle, scale, opacity, easing, reversed, play, op)
/**
* A convenience function for creating a [TranslateTransition], [RotateTransition], [ScaleTransition], [FadeTransition]
* on a [Node] that all run simultaneously.
*
* @param time How long the animation will take
* @param destination Where to move the node (relative to its translation origin)
* @param angle How far to rotate the node (in degrees; relative to its 0 rotation)
* @param scale How to scale the node (relative to its default scale)
* @param opacity The final opacity of the node
* @param easing How to interpolate the animation
* @param reversed Whether the animation should be played in reverse
* @param play Whether the animation should start playing automatically
* @param op Modify the animation after it is created
* @return A ParallelTransition on this node
*/
fun Node.transform(time: Duration, destination: Point2D, angle: Number, scale: Point2D, opacity: Number,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (ParallelTransition.() -> Unit)? = null)
= move(time, destination, easing, reversed, play)
.and(rotate(time, angle, easing, reversed, play))
.and(scale(time, scale, easing, reversed, play))
.and(fade(time, opacity, easing, reversed, play))
.apply {
interpolator = easing
op?.invoke(this)
if (play) play()
}
/**
* A convenience function for creating a parallel animation from multiple animations.
*
* @receiver The base animation
* @param animation The animations to play with this one
* @param op Modify the animation after it is created
* @return A ParallelTransition
*/
fun Animation.and(vararg animation: Animation, op: (ParallelTransition.() -> Unit)? = null) : ParallelTransition {
if (this is ParallelTransition) {
children += animation
op?.invoke(this)
return this
} else {
val transition = ParallelTransition(this, *animation)
op?.invoke(transition)
return transition
}
}
infix fun Animation.and(animation: Animation): ParallelTransition {
if (this is ParallelTransition) {
children += animation
return this
} else {
return ParallelTransition(this, animation)
}
}
/**
* A convenience function for playing multiple animations in parallel.
*
* @receiver The animations to play in parallel
* @param play Whether to start playing immediately
* @param op Modify the animation before playing
* @return A ParallelTransition
*/
fun Iterable<Animation>.playParallel(play: Boolean = true, op: (ParallelTransition.() -> Unit)? = null) = ParallelTransition().apply {
children.setAll(toList())
op?.invoke(this)
if (play) play()
}
/**
* A convenience function for creating a sequential animation from multiple animations.
*
* @receiver The base animation
* @param animation The animations to play with this one
* @param op Modify the animation after it is created
* @return A SequentialTransition
*/
fun Animation.then(vararg animation: Animation, op: (SequentialTransition.() -> Unit)? = null): SequentialTransition {
if (this is SequentialTransition) {
children += animation
op?.invoke(this)
return this
} else {
val transition = SequentialTransition(this, *animation)
op?.invoke(transition)
return transition
}
}
infix fun Animation.then(animation: Animation): SequentialTransition {
if (this is SequentialTransition) {
children += animation
return this
} else {
return SequentialTransition(this, animation)
}
}
/**
* A convenience function for playing multiple animations in sequence.
*
* @receiver The animations to play in sequence
* @param play Whether to start playing immediately
* @param op Modify the animation before playing
* @return A SequentialTransition
*/
fun Iterable<Animation>.playSequential(play: Boolean = true, op: (SequentialTransition.() -> Unit)? = null) = SequentialTransition().apply {
children.setAll(toList())
op?.invoke(this)
if (play) play()
}
fun Shape.animateFill(time: Duration, from: Color, to: Color,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (FillTransition.() -> Unit)? = null): FillTransition {
return FillTransition(time, this, from, to).apply {
interpolator = easing
if (reversed) {
fromValue = to
toValue = from
}
op?.invoke(this)
if (play) play()
}
}
fun Shape.animateStroke(time: Duration, from: Color, to: Color,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (StrokeTransition.() -> Unit)? = null): StrokeTransition {
return StrokeTransition(time, this, from, to).apply {
interpolator = easing
if (reversed) {
fromValue = to
toValue = from
}
op?.invoke(this)
if (play) play()
}
}
fun Node.follow(time: Duration, path: Shape,
easing: Interpolator = Interpolator.EASE_BOTH, reversed: Boolean = false, play: Boolean = true,
op: (PathTransition.() -> Unit)? = null): PathTransition {
return PathTransition(time, path, this).apply {
interpolator = easing
op?.invoke(this)
if (reversed && rate > 0.0) rate = -rate
if (play) play()
}
}
fun pause(time: Duration, play: Boolean = true, op: (PauseTransition.() -> Unit)? = null) = PauseTransition(time).apply {
op?.invoke(this)
if (play) play()
}
fun Timeline.keyframe(duration: Duration, op: (KeyFrameBuilder).() -> Unit): KeyFrame {
val keyFrameBuilder = KeyFrameBuilder(duration)
keyFrameBuilder.op()
return keyFrameBuilder.build().apply {
this@keyframe += this
}
}
class KeyFrameBuilder(val duration: Duration) {
var keyValues: MutableList<KeyValue> = ArrayList()
var name: String? = null
private var _onFinished: (ActionEvent) -> Unit = {}
fun setOnFinished(onFinished: (ActionEvent) -> Unit) {
this._onFinished = onFinished
}
operator fun plusAssign(keyValue: KeyValue) {
keyValues.add(keyValue)
}
fun <T> keyvalue(writableValue: WritableValue<T>, endValue: T, interpolator: Interpolator? = null): KeyValue {
val keyValue = interpolator?.let { KeyValue(writableValue, endValue, it) } ?: KeyValue(writableValue, endValue)
this += keyValue
return keyValue
}
internal fun build() = KeyFrame(duration, name, _onFinished, keyValues)
}
fun <T> WritableValue<T>.animate(endValue: T, duration: Duration, interpolator: Interpolator? = null, op: (Timeline.() -> Unit)? = null) {
val writableValue = this
val timeline = Timeline()
timeline.apply {
keyframe(duration) {
keyvalue(writableValue, endValue, interpolator)
}
}
op?.apply { this.invoke(timeline) }
timeline.play()
}
val Number.millis: Duration get() = Duration.millis(this.toDouble())
val Number.seconds: Duration get() = Duration.seconds(this.toDouble())
val Number.minutes: Duration get() = Duration.minutes(this.toDouble())
val Number.hours: Duration get() = Duration.hours(this.toDouble())
operator fun Duration.plus(duration: Duration): Duration = this.add(duration)
operator fun Duration.minus(duration: Duration): Duration = this.minus(duration)
/**
* A class that, when used with [replaceWith] or [UIComponent.replaceWith], allows you to replace [View]s, [Fragment]s,
* or [Node]s using a transition effect.
*
* To create a new ViewTransition, you need to implement the [ViewTransition.create] function. You should also override
* [ViewTransition.onComplete] to cleanup any changes to the nodes (such as resetting transformations).
*
* During the transition, the view/fragment/node being transitioned is replaced with a temporary [StackPane] containing
* both the current node and its replacement. By default, this StackPane contains only these two nodes with the current
* node on top. You can override [ViewTransition.stack] to change how this works.
*
* If you need to change the order of the stack during the transition, you have access to the stack as a parameter of
* the create method, and there is also a StackPane extension function ([ViewTransition.moveToTop]) for convenience.
*/
abstract class ViewTransition {
/**
* Create an animation to play for the transition between two nodes. The [StackPane] used as a placeholder during
* the transition is also provided.
*
* There are a number of useful extensions functions for nodes defined above to make animations easier. See any of
* the ViewTransitions defined below for examples.
*
* @param current The node currently in the scenegraph that is to be replaced
* @param replacement The node that will be in the scenegraph after the transition
* @param stack The StackPane containing the nodes during the transition
* @return The animation that will play during the transition
*/
abstract fun create(current: Node, replacement: Node, stack: StackPane): Animation
/**
* Will be called after the transition is finished and the replacement node has been docked. This function is useful
* for resetting changes made to the node during the transition, such as position, scale, and opacity.
*
* See [Metro] for an example.
*
* @param removed The node that was removed from the scenegraph
* @param replacement The node now in the scenegraph
*/
open fun onComplete(removed: Node, replacement: Node) = Unit
var setup: StackPane.() -> Unit = {}
/**
* This allows users to modify the generated stack after the the ViewTransition is generated (so they can add things
* like AnchorPane and VGrow/HGrow constraints).
*/
fun setup(setup: StackPane.() -> Unit) {
this.setup = setup
}
internal fun call(current: Node, replacement: Node, attach: (Node) -> Unit) {
current.isTransitioning = true
replacement.isTransitioning = true
val currentUIComponent = current.properties[UI_COMPONENT_PROPERTY] as? UIComponent
val replacementUIComponent = replacement.properties[UI_COMPONENT_PROPERTY] as? UIComponent
currentUIComponent?.muteDocking = true
replacementUIComponent?.muteDocking = true
val stack = stack(current, replacement)
stack.setup()
attach(stack)
create(current, replacement, stack).apply {
val oldFinish: EventHandler<ActionEvent>? = onFinished
setOnFinished {
stack.children.clear()
current.removeFromParent()
replacement.removeFromParent()
stack.removeFromParent()
currentUIComponent?.let {
it.muteDocking = false
it.callOnUndock()
}
replacementUIComponent?.muteDocking = false
attach(replacement)
oldFinish?.handle(it)
onComplete(current, replacement)
current.isTransitioning = false
replacement.isTransitioning = false
}
}.play()
}
/**
* If the given node exists in this [StackPane], move it to be on top (visually).
*
* @param node The node to move to the top of the stack
*/
protected fun StackPane.moveToTop(node: Node) {
if (children.remove(node)) children.add(node)
}
/**
* Create a [StackPane] in which the transition will take place. You should generally put both the current and the
* replacement nodes in the stack, but it isn't technically required.
*
* See [FadeThrough] for an example.
*
* By default this returns a StackPane with only the current and replacement nodes in it (the current node will be
* on top).
*
* @param current The node that is currently in the scenegraph
* @param replacement The node that will be in the scenegraph after the transition
* @return The [StackPane] that will be in the scenegraph during the transition
*/
open fun stack(current: Node, replacement: Node) = StackPane(replacement, current)
companion object {
@Deprecated("Use `Slide(0.2.seconds)`", ReplaceWith("Slide(0.2.seconds)"))
val SlideIn = fun(existing: UIComponent, replacement: UIComponent, transitionCompleteCallback: () -> Unit) {
replacement.root.translateX = existing.root.boundsInLocal.width
val existingSlide = TranslateTransition(0.2.seconds, existing.root).apply {
toX = -existing.root.boundsInLocal.width
interpolator = Interpolator.EASE_OUT
}
val replacementSlide = TranslateTransition(0.2.seconds, replacement.root).apply {
toX = 0.0
onFinished = EventHandler { transitionCompleteCallback() }
interpolator = Interpolator.EASE_OUT
}
existingSlide.play()
replacementSlide.play()
}
@Deprecated("Use `Slide(0.2.seconds, Direction.LEFT)`", ReplaceWith("Slide(0.2.seconds, Direction.RIGHT)"))
val SlideOut = fun(existing: UIComponent, replacement: UIComponent, transitionCompleteCallback: () -> Unit) {
replacement.root.translateX = -existing.root.boundsInLocal.width
val existingSlide = TranslateTransition(0.2.seconds, existing.root).apply {
toX = existing.root.boundsInLocal.width
interpolator = Interpolator.EASE_OUT
}
val replacementSlide = TranslateTransition(0.2.seconds, replacement.root).apply {
toX = 0.0
onFinished = EventHandler { transitionCompleteCallback() }
interpolator = Interpolator.EASE_OUT
}
existingSlide.play()
replacementSlide.play()
}
}
enum class Direction { UP, RIGHT, DOWN, LEFT;
fun reversed() = when (this) {
UP -> DOWN
RIGHT -> LEFT
DOWN -> UP
LEFT -> RIGHT
}
}
/**
* A [ViewTransition] that smoothly fades from one node to another.
*
* @param duration How long the transition will take
*/
class Fade(val duration: Duration) : ViewTransition() {
override fun create(current: Node, replacement: Node, stack: StackPane)
= current.fade(duration, 0, play = false)
override fun onComplete(removed: Node, replacement: Node) {
removed.opacity = 1.0
}
}
/**
* A [ViewTransition] that fades from one node to another through a Paint (useful for fading through black).
*
* By default this fades through transparent, meaning it will show whatever is underneath the current node.
*
* @param duration How long the transition will take
* @param color The color to fade through (can be any [Paint])
*/
class FadeThrough(duration: Duration, val color: Paint = Color.TRANSPARENT) : ViewTransition() {
private val bg = Pane().apply { background = Background(BackgroundFill(color, null, null)) }
val halfTime = duration.divide(2.0)!!
override fun create(current: Node, replacement: Node, stack: StackPane)
= current.fade(halfTime, 0, easing = Interpolator.EASE_IN, play = false)
.then(replacement.fade(halfTime, 0, easing = Interpolator.EASE_OUT, reversed = true, play = false))
override fun stack(current: Node, replacement: Node) = StackPane(bg, replacement, current)
override fun onComplete(removed: Node, replacement: Node) {
removed.opacity = 1.0
}
}
/**
* A [ViewTransition] that can be reversed
*/
abstract class ReversibleViewTransition<out T : ViewTransition> : ViewTransition() {
/**
* Create a transition to be the reverse of the current transition. It's generally recommended (though in no way
* required) for the reverse transition to be a logical reversal of this transition.
*
* @return The reversed [ViewTransition]
*/
protected abstract fun reversed(): T
fun reversed(op: (T.() -> Unit)? = null): T {
val reversed = reversed()
op?.invoke(reversed)
return reversed
}
}
/**
* A [ReversibleViewTransition] that slides one node out (in a given direction) while sliding another in. The effect
* is similar to panning the camera in the opposite direction.
*
* The reverse is a Slide in the opposite direction.
*
* @param duration How long the transition will take
* @param direction The direction to slide the nodes
*/
class Slide(val duration: Duration, val direction: Direction = Direction.LEFT) : ReversibleViewTransition<Slide>() {
override fun create(current: Node, replacement: Node, stack: StackPane): Animation {
val bounds = current.boundsInLocal
val destination = when (direction) {
Direction.UP -> point(0, -bounds.height)
Direction.RIGHT -> point(bounds.width, 0)
Direction.DOWN -> point(0, bounds.height)
Direction.LEFT -> point(-bounds.width, 0)
}
return current.move(duration, destination, play = false)
.and(replacement.move(duration, destination.multiply(-1.0), reversed = true, play = false))
}
override fun stack(current: Node, replacement: Node) = super.stack(replacement, current)
override fun onComplete(removed: Node, replacement: Node) {
removed.translateX = 0.0
removed.translateY = 0.0
}
override fun reversed() = Slide(duration, direction.reversed()).apply { setup = [email protected] }
}
/**
* A [ReversibleViewTransition] where a node slides in in a given direction covering another node.
*
* The reverse is a [Reveal] in the opposite direction
*
* @param duration How long the transition will take
* @param direction The direction to slide the node
*/
class Cover(val duration: Duration, val direction: Direction = Direction.LEFT) : ReversibleViewTransition<Reveal>() {
override fun create(current: Node, replacement: Node, stack: StackPane): Animation {
val bounds = current.boundsInLocal
val destination = when (direction) {
Direction.UP -> point(0, bounds.height)
Direction.RIGHT -> point(-bounds.width, 0)
Direction.DOWN -> point(0, -bounds.height)
Direction.LEFT -> point(bounds.width, 0)
}
return replacement.move(duration, destination, reversed = true, play = false)
}
override fun stack(current: Node, replacement: Node) = super.stack(replacement, current)
override fun reversed() = Reveal(duration, direction.reversed()).apply { setup = [email protected] }
}
/**
* A [ReversibleViewTransition] where a node slides out in a given direction revealing another node.
*
* The reverse is a [Cover] in the opposite direction
*
* @param duration How long the transition will take
* @param direction The direction to slide the node
*/
class Reveal(val duration: Duration, val direction: Direction = Direction.LEFT) : ReversibleViewTransition<Cover>() {
override fun create(current: Node, replacement: Node, stack: StackPane): Animation {
val bounds = current.boundsInLocal
val destination = when (direction) {
Direction.UP -> point(0, -bounds.height)
Direction.RIGHT -> point(bounds.width, 0)
Direction.DOWN -> point(0, bounds.height)
Direction.LEFT -> point(-bounds.width, 0)
}
return current.move(duration, destination, play = false)
}
override fun onComplete(removed: Node, replacement: Node) {
removed.translateX = 0.0
removed.translateY = 0.0
}
override fun reversed() = Cover(duration, direction.reversed()).apply { setup = [email protected] }
}
/**
* A [ReversibleViewTransition] where a node fades and slides out in a given direction while another node fades and
* slides in. The effect is similar to effects commonly used in Windows applications (thus the name).
*
* The reverse is a Metro in the opposite direction.
*
* @param duration How long the transition will take
* @param direction The direction to slide the nodes
* @param distancePercentage The distance to move the nodes as a percentage of the size of the current node
*/
class Metro(val duration: Duration, val direction: Direction = Direction.LEFT, val distancePercentage: Double = 0.1) : ReversibleViewTransition<Metro>() {
override fun create(current: Node, replacement: Node, stack: StackPane): Animation {
val bounds = current.boundsInLocal
val destination = when (direction) {
Direction.UP -> point(0, -bounds.height * distancePercentage)
Direction.RIGHT -> point(bounds.width * distancePercentage, 0)
Direction.DOWN -> point(0, bounds.height * distancePercentage)
Direction.LEFT -> point(-bounds.width * distancePercentage, 0)
}
return current.transform(duration.divide(2.0), destination, 0, point(1, 1), 0, play = false)
.then(replacement.transform(duration.divide(2.0), destination.multiply(-1.0), 0, point(1, 1), 0,
reversed = true, play = false))
}
override fun onComplete(removed: Node, replacement: Node) {
removed.translateX = 0.0
removed.translateY = 0.0
removed.opacity = 1.0
}
override fun reversed() = Metro(duration, direction.reversed(), distancePercentage).apply { setup = [email protected] }
}
/**
* A [ReversibleViewTransition] that swaps the two nodes in a way that looks like two cards in a deck being swapped.
*
* The reverse is a Swap in the opposite direction
*
* @param duration How long the transition will take
* @param direction The direction the current node will initially move
* @param scale The starting scale of the replacement node and ending scale of the current node
*/
class Swap(val duration: Duration, val direction: Direction = Direction.LEFT, val scale: Point2D = point(.75, .75)) : ReversibleViewTransition<Swap>() {
override fun create(current: Node, replacement: Node, stack: StackPane): Animation {
val bounds = current.boundsInLocal
val destination = when (direction) {
Direction.UP -> point(0, -bounds.height * 0.5)
Direction.RIGHT -> point(bounds.width * 0.5, 0)
Direction.DOWN -> point(0, bounds.height * 0.5)
Direction.LEFT -> point(-bounds.width * 0.5, 0)
}
val halfTime = duration.divide(2.0)
return current.scale(duration, scale, play = false).and(replacement.scale(duration, scale, reversed = true, play = false))
.and(current.move(halfTime, destination).and(replacement.move(halfTime, destination.multiply(-1.0))) {
setOnFinished { stack.moveToTop(replacement) }
}.then(current.move(halfTime, Point2D.ZERO).and(replacement.move(halfTime, Point2D.ZERO))))
}
override fun onComplete(removed: Node, replacement: Node) {
removed.translateX = 0.0
removed.translateY = 0.0
removed.scaleX = 1.0
removed.scaleY = 1.0
}
override fun reversed() = Swap(duration, direction.reversed(), scale).apply { setup = [email protected] }
}
/**
* A [ViewTransition] similar to flipping a node over to reveal another on its back. The effect has no perspective
* (it isn't 3D) due to the limits of JavaFX's affine transformation system.
*
* @param duration How long the transition will take
* @param vertical Whether to flip the card vertically or horizontally
*/
class Flip(duration: Duration, vertical: Boolean = false) : ViewTransition() {
val halfTime = duration.divide(2.0)!!
val targetAxis = (if (vertical) Rotate.X_AXIS else Rotate.Y_AXIS)!!
override fun create(current: Node, replacement: Node, stack: StackPane): Animation {
return current.rotate(halfTime, 90, easing = Interpolator.EASE_IN, play = false) {
axis = targetAxis
}.then(replacement.rotate(halfTime, 90, easing = Interpolator.EASE_OUT, reversed = true, play = false) {
axis = targetAxis
})
}
override fun onComplete(removed: Node, replacement: Node) {
removed.rotate = 0.0
removed.rotationAxis = Rotate.Z_AXIS
replacement.rotationAxis = Rotate.Z_AXIS
}
}
/**
* A [ViewTransition] where a node spins and grows like a newspaper.
*
* The effect is similar to this: http://www.canstockphoto.com/spinning-news-paper-4032376.html
*
* @param duration How long the transition will take
* @param rotations How many time the paper will rotate (use a negative value for clockwise rotation)
*/
class NewsFlash(val duration: Duration, val rotations: Number = 2) : ViewTransition() {
override fun create(current: Node, replacement: Node, stack: StackPane)
= replacement.transform(duration, Point2D.ZERO, rotations.toDouble() * 360, Point2D.ZERO, 1,
easing = Interpolator.EASE_IN, reversed = true, play = false)
override fun stack(current: Node, replacement: Node) = super.stack(replacement, current)
}
/**
* A [ReversibleViewTransition] where a node grows and fades out revealing another node.
*
* The reverse is an [Implode]
*
* @param duration How long the transition will take
* @param scale How big to scale the node as it fades out
*/
class Explode(val duration: Duration, val scale: Point2D = point(2, 2)) : ReversibleViewTransition<Implode>() {
override fun create(current: Node, replacement: Node, stack: StackPane)
= current.transform(duration, Point2D.ZERO, 0, scale, 0, play = false)
override fun onComplete(removed: Node, replacement: Node) {
removed.scaleX = 1.0
removed.scaleY = 1.0
removed.opacity = 1.0
}
override fun reversed() = Implode(duration, scale).apply { setup = [email protected] }
}
/**
* A [ReversibleViewTransition] where a node shrinks and fades in revealing another node.
*
* The reverse is an [Explode]
*
* @param duration How long the transition will take
* @param scale The initial size the node shrinks from
*/
class Implode(val duration: Duration, val scale: Point2D = point(2, 2)) : ReversibleViewTransition<Explode>() {
override fun create(current: Node, replacement: Node, stack: StackPane)
= replacement.transform(duration, Point2D.ZERO, 0, scale, 0, reversed = true, play = false)
override fun stack(current: Node, replacement: Node) = super.stack(replacement, current)
override fun reversed() = Explode(duration, scale).apply { setup = [email protected] }
}
}
| apache-2.0 | 05fe8707060190f8333fda6b4dc58d96 | 40.503261 | 158 | 0.657099 | 4.480521 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsCompositeElement.kt | 1 | 2200 | package org.rust.lang.core.psi.ext
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.extapi.psi.StubBasedPsiElementBase
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.util.PsiTreeUtil
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.project.workspace.cargoWorkspace
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.RsModDeclItem
import org.rust.lang.core.resolve.ref.RsReference
interface RsCompositeElement : PsiElement {
override fun getReference(): RsReference?
}
val RsCompositeElement.containingMod: RsMod?
get() = PsiTreeUtil.getStubOrPsiParentOfType(this, RsMod::class.java)
val RsModDeclItem.containingMod: RsMod
get() = (this as RsCompositeElement).containingMod
?: error("Rust mod decl outside of a module")
val RsCompositeElement.crateRoot: RsMod? get() {
return if (this is RsFile) {
val root = superMods.lastOrNull()
if (root != null && root.isCrateRoot)
root
else
null
} else {
(context as? RsCompositeElement)?.crateRoot
}
}
val RsCompositeElement.containingCargoTarget: CargoWorkspace.Target? get() {
val cargoProject = module?.cargoWorkspace ?: return null
val root = crateRoot ?: return null
val file = root.containingFile.originalFile.virtualFile ?: return null
return cargoProject.findTargetForCrateRootFile(file)
}
val RsCompositeElement.containingCargoPackage: CargoWorkspace.Package? get() = containingCargoTarget?.pkg
abstract class RsCompositeElementImpl(node: ASTNode) : ASTWrapperPsiElement(node), RsCompositeElement {
override fun getReference(): RsReference? = null
}
abstract class RsStubbedElementImpl<StubT : StubElement<*>> : StubBasedPsiElementBase<StubT>, RsCompositeElement {
constructor(node: ASTNode) : super(node)
constructor(stub: StubT, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getReference(): RsReference? = null
override fun toString(): String = "${javaClass.simpleName}($elementType)"
}
| mit | 5dab16c43cf40d503a61ebd2b671d780 | 35.065574 | 114 | 0.759091 | 4.471545 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/lang/refactoring/RsNamesValidator.kt | 1 | 1002 | package org.rust.lang.refactoring
import com.intellij.lang.refactoring.NamesValidator
import com.intellij.openapi.project.Project
import com.intellij.psi.tree.IElementType
import org.rust.lang.core.lexer.RsLexer
import org.rust.lang.core.psi.RS_KEYWORDS
import org.rust.lang.core.psi.RsElementTypes.IDENTIFIER
import org.rust.lang.core.psi.RsElementTypes.QUOTE_IDENTIFIER
class RsNamesValidator : NamesValidator {
override fun isKeyword(name: String, project: Project?): Boolean = getLexerType(name) in RS_KEYWORDS
override fun isIdentifier(name: String, project: Project?): Boolean =
when (getLexerType(name)) {
IDENTIFIER, QUOTE_IDENTIFIER -> true
else -> false
}
private fun getLexerType(text: String): IElementType? {
val lexer = RsLexer()
lexer.start(text)
return if (lexer.tokenEnd == text.length) lexer.tokenType else null
}
companion object {
val PredefinedLifetimes = arrayOf("'static")
}
}
| mit | cb19081bca653e045e0d67ab507dacdd | 32.4 | 104 | 0.717565 | 4.123457 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.