repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/game/build/BuildingsView.kt | 1 | 10804 | package au.com.codeka.warworlds.client.game.build
import android.content.Context
import android.graphics.Typeface
import android.text.Html
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import android.widget.AdapterView.OnItemClickListener
import au.com.codeka.warworlds.client.R
import au.com.codeka.warworlds.client.concurrency.Threads
import au.com.codeka.warworlds.client.concurrency.Threads.Companion.checkOnThread
import au.com.codeka.warworlds.client.ctrl.fromHtml
import au.com.codeka.warworlds.common.proto.*
import au.com.codeka.warworlds.common.sim.BuildHelper
import au.com.codeka.warworlds.common.sim.DesignHelper
import java.util.*
import kotlin.math.roundToInt
class BuildingsView(
context: Context?, private var star: Star, private var colony: Colony,
buildLayout: BuildLayout)
: ListView(context), TabContentView {
companion object {
private const val HEADING_TYPE = 0
private const val EXISTING_BUILDING_TYPE = 1
private const val NEW_BUILDING_TYPE = 2
}
private val adapter: BuildingListAdapter
override fun refresh(star: Star, colony: Colony) {
this.star = star
this.colony = colony
adapter.refresh(star, colony)
}
/** This adapter is used to populate a list of buildings in a list view. */
private inner class BuildingListAdapter : BaseAdapter() {
private var entries: ArrayList<ItemEntry>? = null
fun refresh(star: Star, colony: Colony) {
checkOnThread(Threads.UI)
entries = ArrayList()
var buildings = colony.buildings
val existingBuildingEntries = ArrayList<ItemEntry>()
for (b in buildings) {
val entry = ItemEntry()
entry.building = b
// if the building is being upgraded (i.e. if there's a build request that
// references this building) then add the build request as well
for (br in BuildHelper.getBuildRequests(star)) {
if (br.building_id != null && br.building_id == b.id) {
entry.buildRequest = br
}
}
existingBuildingEntries.add(entry)
}
for (br in colony.build_requests) {
val design = DesignHelper.getDesign(br.design_type)
if (design.design_kind == Design.DesignKind.BUILDING && br.building_id == null) {
val entry = ItemEntry()
entry.buildRequest = br
existingBuildingEntries.add(entry)
}
}
existingBuildingEntries.sortWith { lhs: ItemEntry, rhs: ItemEntry ->
val leftBuilding = lhs.building
val rightBuilding = rhs.building
val a = leftBuilding?.design_type ?: lhs.buildRequest!!.design_type
val b = rightBuilding?.design_type ?: rhs.buildRequest!!.design_type
a.compareTo(b)
}
var title = ItemEntry()
title.title = "New Buildings"
entries!!.add(title)
for (design in DesignHelper.getDesigns(Design.DesignKind.BUILDING)) {
val maxPerColony = design.max_per_colony
if (maxPerColony != null && maxPerColony > 0) {
var numExisting = 0
for (e in existingBuildingEntries) {
if (e.building != null) {
if (e.building!!.design_type == design.type) {
numExisting++
}
} else if (e.buildRequest != null) {
if (e.buildRequest!!.design_type == design.type) {
numExisting++
}
}
}
if (numExisting >= maxPerColony) {
continue
}
}
// if (bd.getMaxPerEmpire() > 0) {
// int numExisting = BuildManager.i.getTotalBuildingsInEmpire(bd.getID());
// // If you're building one, we'll still think it's OK to build again, but it's
// // actually going to be blocked by the server.
// if (numExisting >= bd.getMaxPerEmpire()) {
// continue;
// }
// }
val entry = ItemEntry()
entry.design = design
entries!!.add(entry)
}
title = ItemEntry()
title.title = "Existing Buildings"
entries!!.add(title)
entries!!.addAll(existingBuildingEntries)
notifyDataSetChanged()
}
/**
* We have three types of items, the "headings", the list of existing buildings and the list of
* building designs.
*/
override fun getViewTypeCount(): Int {
return 3
}
override fun getItemViewType(position: Int): Int {
if (entries == null) return 0
if (entries!![position].title != null) return Companion.HEADING_TYPE
return if (entries!![position].design != null) Companion.NEW_BUILDING_TYPE else Companion.EXISTING_BUILDING_TYPE
}
override fun isEnabled(position: Int): Boolean {
if (position < 0 || position >= entries!!.size) {
return false
}
if (getItemViewType(position) == Companion.HEADING_TYPE) {
return false
}
// also, if it's an existing building that's at the max level it can't be
// upgraded any more, so also disabled.
val entry = entries!![position]
if (entry.building != null) {
val maxUpgrades = DesignHelper.getDesign(entry.building!!.design_type).upgrades.size
if (entry.building!!.level > maxUpgrades) {
return false
}
}
return true
}
override fun getCount(): Int {
return if (entries == null) 0 else entries!!.size
}
override fun getItem(position: Int): Any? {
return if (entries == null) null else entries!![position]
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val view = convertView ?: run {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val viewType = getItemViewType(position)
if (viewType == HEADING_TYPE) {
TextView(context)
} else {
inflater.inflate(R.layout.ctrl_build_design, parent, false)
}
}
val entry = entries!![position]
if (entry.title != null) {
val tv = view as TextView
tv.typeface = Typeface.DEFAULT_BOLD
tv.text = entry.title
} else if (entry.building != null || entry.buildRequest != null) {
// existing building/upgrading building
val icon = view.findViewById<ImageView>(R.id.building_icon)
val row1 = view.findViewById<TextView>(R.id.design_row1)
val row2 = view.findViewById<TextView>(R.id.design_row2)
val row3 = view.findViewById<TextView>(R.id.design_row3)
val level = view.findViewById<TextView>(R.id.build_level)
val levelLabel = view.findViewById<TextView>(R.id.build_level_label)
val progress = view.findViewById<ProgressBar>(R.id.build_progress)
val notes = view.findViewById<TextView>(R.id.notes)
val building = entry.building
val buildRequest = entry.buildRequest
val design = DesignHelper.getDesign(
building?.design_type ?: buildRequest!!.design_type
)
BuildViewHelper.setDesignIcon(design, icon)
val numUpgrades = design.upgrades.size
if (numUpgrades == 0 || building == null) {
level.visibility = View.GONE
levelLabel.visibility = View.GONE
} else {
level.text = String.format(Locale.US, "%d", building.level)
level.visibility = View.VISIBLE
levelLabel.visibility = View.VISIBLE
}
row1.text = design.display_name
if (buildRequest != null) {
val verb = if (building == null) "Building" else "Upgrading"
row2.text = fromHtml(String.format(Locale.ENGLISH,
"<font color=\"#0c6476\">%s:</font> %d %%, %s left",
verb, (buildRequest.progress!! * 100.0f).roundToInt(),
BuildHelper.formatTimeRemaining(buildRequest)))
row3.visibility = View.GONE
progress.visibility = View.VISIBLE
progress.progress = (buildRequest.progress!! * 100.0f).roundToInt()
} else /*if (building != null)*/ {
if (numUpgrades < building!!.level) {
row2.text = context.getString(R.string.no_more_upgrades)
row3.visibility = View.GONE
progress.visibility = View.GONE
} else {
progress.visibility = View.GONE
val requiredHtml = DesignHelper.getDependenciesHtml(colony, design, building.level + 1)
row2.text = fromHtml(requiredHtml)
row3.visibility = View.GONE
}
}
if (building?.notes != null) {
notes.text = building.notes
notes.visibility = View.VISIBLE
} /*else if (buildRequest != null && buildRequest.notes != null) {
notes.setText(buildRequest.getNotes());
notes.setVisibility(View.VISIBLE);
} */ else {
notes.text = ""
notes.visibility = View.GONE
}
} else {
// new building
val icon = view.findViewById<ImageView>(R.id.building_icon)
val row1 = view.findViewById<TextView>(R.id.design_row1)
val row2 = view.findViewById<TextView>(R.id.design_row2)
val row3 = view.findViewById<TextView>(R.id.design_row3)
view.findViewById<View>(R.id.build_progress).visibility = View.GONE
view.findViewById<View>(R.id.build_level).visibility = View.GONE
view.findViewById<View>(R.id.build_level_label).visibility = View.GONE
view.findViewById<View>(R.id.notes).visibility = View.GONE
val design = entries!![position].design
BuildViewHelper.setDesignIcon(design!!, icon)
row1.text = design.display_name
val requiredHtml = DesignHelper.getDependenciesHtml(colony, design)
row2.text = fromHtml(requiredHtml)
row3.visibility = View.GONE
}
return view
}
}
internal class ItemEntry {
var title: String? = null
var buildRequest: BuildRequest? = null
var building: Building? = null
var design: Design? = null
}
init {
adapter = BuildingListAdapter()
adapter.refresh(star, colony)
setAdapter(adapter)
onItemClickListener = OnItemClickListener { _: AdapterView<*>?, _: View?, position: Int, _: Long ->
val entry = adapter.getItem(position) as ItemEntry
if (entry.building == null && entry.buildRequest == null) {
buildLayout.showBuildSheet(entry.design)
} else if (entry.building != null && entry.buildRequest == null) {
buildLayout.showUpgradeSheet(entry.building)
} else {
// entry.buildRequest should not be null here.
buildLayout.showProgressSheet(entry.buildRequest!!)
}
}
}
} | mit | 6e7cc908f5036b70a8699ab8a3d8547b | 37.727599 | 118 | 0.628656 | 4.3216 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/perf/profilers/yk/YKProfilerHandler.kt | 2 | 4004 | // 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.perf.profilers.yk
import org.jetbrains.kotlin.idea.perf.profilers.ProfilerConfig
import org.jetbrains.kotlin.idea.perf.profilers.ProfilerHandler
import org.jetbrains.kotlin.idea.perf.profilers.ProfilerHandler.Companion.determinePhasePath
import org.jetbrains.kotlin.idea.perf.profilers.doOrThrow
import org.jetbrains.kotlin.idea.perf.util.logMessage
import java.io.PrintWriter
import java.io.StringWriter
import java.lang.management.ManagementFactory
import java.lang.reflect.Method
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* To use YKProfilerHandler:
* - ${YOURKIT_PROFILER_HOME}/lib/yjp-controller-api-redist.jar has to be in a classpath
* - add agentpath vm paramter like `-agentpath:${YOURKIT_PROFILER_HOME}/Resources/bin/mac/libyjpagent.dylib`
*/
class YKProfilerHandler(val profilerConfig: ProfilerConfig) : ProfilerHandler {
private var controller: Any
lateinit var phasePath: Path
init {
check(ManagementFactory.getRuntimeMXBean().inputArguments.any { it.contains("yjpagent") }) {
"vm parameter -agentpath:\$YOURKIT_PROFILER_HOME/bin/../libyjpagent is not specified"
}
controller = doOrThrow("Unable to create com.yourkit.api.Controller instance") {
ykLibClass.getConstructor().newInstance()
}
}
override fun startProfiling() {
try {
if (profilerConfig.tracing) {
startTracingMethod.invoke(controller, null)
} else {
startSamplingMethod.invoke(controller, null)
}
} catch (e: Exception) {
val stringWriter = StringWriter().also { e.printStackTrace(PrintWriter(it)) }
logMessage { "exception while starting profile ${e.localizedMessage} $stringWriter" }
}
}
override fun stopProfiling(attempt: Int) {
val pathToSnapshot = captureSnapshotMethod.invoke(controller, SNAPSHOT_WITHOUT_HEAP) as String
stopCpuProfilingMethod.invoke(controller)
val dumpPath = Paths.get(pathToSnapshot)
if (!this::phasePath.isInitialized)
phasePath = determinePhasePath(dumpPath, profilerConfig)
val targetFile = phasePath.resolve("$attempt-${profilerConfig.name}.snapshot")
logMessage { "dump is moved to $targetFile" }
Files.move(dumpPath, targetFile)
}
companion object {
const val SNAPSHOT_WITHOUT_HEAP = 0L
private val ykLibClass: Class<*> = doOrThrow("yjp-controller-api-redist.jar is not in a classpath") {
Class.forName("com.yourkit.api.Controller")
}
private val startSamplingMethod: Method = doOrThrow("com.yourkit.api.Controller#startSampling(String) not found") {
ykLibClass.getMethod(
"startSampling",
String::class.java
)
}
private val startTracingMethod: Method = doOrThrow("com.yourkit.api.Controller#startTracing(String) not found") {
ykLibClass.getMethod(
"startTracing",
String::class.java
)
}
private val captureSnapshotMethod: Method = doOrThrow("com.yourkit.api.Controller#captureSnapshot(long) not found") {
ykLibClass.getMethod(
"captureSnapshot",
SNAPSHOT_WITHOUT_HEAP::class.java
)
}
private val capturePerformanceSnapshotMethod: Method =
doOrThrow("com.yourkit.api.Controller#capturePerformanceSnapshot() not found") {
ykLibClass.getMethod("capturePerformanceSnapshot")
}
private val stopCpuProfilingMethod: Method = doOrThrow("com.yourkit.api.Controller#stopCPUProfiling() not found") {
ykLibClass.getMethod("stopCpuProfiling")
}
}
} | apache-2.0 | f0a3367f35cbcc11eee67f8279508340 | 40.71875 | 158 | 0.676324 | 4.586483 | false | true | false | false |
anitawoodruff/habitica-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/social/InvitationsView.kt | 1 | 1438 | package com.habitrpg.android.habitica.ui.views.social
import android.content.Context
import android.util.AttributeSet
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.inflate
import com.habitrpg.android.habitica.models.invitations.GenericInvitation
class InvitationsView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : LinearLayout(context, attrs, defStyleAttr) {
var acceptCall: ((String) -> Unit)? = null
var rejectCall: ((String) -> Unit)? = null
init {
orientation = VERTICAL
}
fun setInvitations(invitations: List<GenericInvitation>) {
removeAllViews()
for (invitation in invitations) {
val view = inflate(R.layout.view_invitation, true)
val textView = view.findViewById<TextView>(R.id.text_view)
textView.text = context.getString(R.string.invitation_title, context.getString(R.string.someone), invitation.name)
view.findViewById<Button>(R.id.accept_button).setOnClickListener {
invitation.id?.let { it1 -> acceptCall?.invoke(it1) }
}
view.findViewById<Button>(R.id.reject_button).setOnClickListener {
invitation.id?.let { it1 -> rejectCall?.invoke(it1) }
}
}
}
} | gpl-3.0 | 56f8249639cfeb7cc4f626596ee070b8 | 37.891892 | 126 | 0.689847 | 4.292537 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/automation/elements/InputPercent.kt | 1 | 959 | package info.nightscout.androidaps.plugins.general.automation.elements
import android.widget.LinearLayout
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.R
import info.nightscout.androidaps.utils.ui.NumberPicker
import java.text.DecimalFormat
class InputPercent(injector: HasAndroidInjector) : Element(injector) {
var value: Double = 100.0
constructor(injector: HasAndroidInjector, value: Double) : this(injector) {
this.value = value
}
override fun addToLayout(root: LinearLayout) {
val numberPicker = NumberPicker(root.context, null)
numberPicker.setParams(100.0, MIN, MAX, 5.0, DecimalFormat("0"), true, root.findViewById(R.id.ok))
numberPicker.value = value
numberPicker.setOnValueChangedListener { value: Double -> this.value = value }
root.addView(numberPicker)
}
companion object {
const val MIN = 70.0
const val MAX = 130.0
}
} | agpl-3.0 | 2ead0b7fa05959f64782db4c44dcf965 | 33.285714 | 106 | 0.720542 | 4.378995 | false | false | false | false |
FTL-Lang/FTL-Compiler | src/main/kotlin/com/thomas/needham/ftl/utils/SourceFile.kt | 1 | 2062 | /*
The MIT License (MIT)
FTL-Lang Copyright (c) 2016 thoma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.ftl.utils
import java.io.File
/**
* This class represents a source code file
* @author Thomas Needham
*/
class SourceFile {
/**
* Handle to the file
*/
val file: File
/**
* The text contained in the file
*/
val text: Array<Char>
/**
* The path to the file
*/
val path: String
/**
* the size of the file
*/
val length: Long
/**
* The number of lines in the file
*/
val lineCount: Long
/**
* Constructor for SourceFile
* @param file A handle to a file
*/
constructor(file: File) {
this.file = file
if (file.isFile && file.exists() && file.canRead()) {
this.text = (file.readText() + "\u0000").toCharArray().toTypedArray()
this.path = file.absolutePath
this.length = file.length()
this.lineCount = this.text.count { x -> x == '\n' }.toLong()
} else {
throw IllegalArgumentException("Invalid Source File")
}
}
} | mit | b0565d63caf1f5a9065aba8bd1b81baf | 26.878378 | 82 | 0.696896 | 4.099404 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/EvaluateCompileTimeExpressionIntention.kt | 1 | 3294 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class EvaluateCompileTimeExpressionIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>(
KtBinaryExpression::class.java,
KotlinBundle.lazyMessage("evaluate.compile.time.expression")
) {
companion object {
val constantNodeTypes = listOf(KtNodeTypes.FLOAT_CONSTANT, KtNodeTypes.CHARACTER_CONSTANT, KtNodeTypes.INTEGER_CONSTANT)
}
override fun isApplicableTo(element: KtBinaryExpression): Boolean {
if (element.getStrictParentOfType<KtBinaryExpression>() != null || !element.isConstantExpression()) return false
val constantValue = element.getConstantValue() ?: return false
setTextGetter { KotlinBundle.message("replace.with.0", constantValue) }
return true
}
override fun applyTo(element: KtBinaryExpression, editor: Editor?) {
val constantValue = element.getConstantValue() ?: return
element.replace(KtPsiFactory(element).createExpression(constantValue))
}
private fun KtExpression?.isConstantExpression(): Boolean {
return when (val expression = KtPsiUtil.deparenthesize(this)) {
is KtConstantExpression -> expression.elementType in constantNodeTypes
is KtPrefixExpression -> expression.baseExpression.isConstantExpression()
is KtBinaryExpression -> expression.left.isConstantExpression() && expression.right.isConstantExpression()
else -> false
}
}
private fun KtBinaryExpression.getConstantValue(): String? {
val context = analyze(BodyResolveMode.PARTIAL)
val type = getType(context) ?: return null
val constantValue = ConstantExpressionEvaluator.getConstant(this, context)?.toConstantValue(type) ?: return null
return when (val value = constantValue.value) {
is Char -> "'${StringUtil.escapeStringCharacters(value.toString())}'"
is Long -> "${value}L"
is Float -> when {
value.isNaN() -> "Float.NaN"
value.isInfinite() -> if (value > 0.0f) "Float.POSITIVE_INFINITY" else "Float.NEGATIVE_INFINITY"
else -> "${value}f"
}
is Double -> when {
value.isNaN() -> "Double.NaN"
value.isInfinite() -> if (value > 0.0) "Double.POSITIVE_INFINITY" else "Double.NEGATIVE_INFINITY"
else -> value.toString()
}
else -> value.toString()
}
}
}
| apache-2.0 | 4b746f643be0e5ff657fe5b9b90110d3 | 48.909091 | 158 | 0.708865 | 5.106977 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/extensions/gradle/SettingsScriptBuilder.kt | 5 | 3146 | // 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.extensions.gradle
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
abstract class SettingsScriptBuilder<T: PsiFile>(val scriptFile: T) {
private val builder = StringBuilder(scriptFile.text)
private fun findBlockBody(blockName: String, startFrom: Int = 0): Int {
val blockOffset = builder.indexOf(blockName, startFrom)
if (blockOffset < 0) return -1
return builder.indexOf('{', blockOffset + 1) + 1
}
private fun getOrPrependTopLevelBlockBody(blockName: String): Int {
val blockBody = findBlockBody(blockName)
if (blockBody >= 0) return blockBody
builder.insert(0, "$blockName {}\n")
return findBlockBody(blockName)
}
private fun getOrAppendInnerBlockBody(blockName: String, offset: Int): Int {
val repositoriesBody = findBlockBody(blockName, offset)
if (repositoriesBody >= 0) return repositoriesBody
builder.insert(offset, "\n$blockName {}\n")
return findBlockBody(blockName, offset)
}
private fun appendExpressionToBlockIfAbsent(expression: String, offset: Int) {
var braceCount = 1
var blockEnd = offset
for (i in offset..builder.lastIndex) {
when (builder[i]) {
'{' -> braceCount++
'}' -> braceCount--
}
if (braceCount == 0) {
blockEnd = i
break
}
}
if (!builder.substring(offset, blockEnd).contains(expression.trim())) {
builder.insert(blockEnd, "\n$expression\n")
}
}
private fun getOrCreatePluginManagementBody() = getOrPrependTopLevelBlockBody("pluginManagement")
protected fun addPluginRepositoryExpression(expression: String) {
val repositoriesBody = getOrAppendInnerBlockBody("repositories", getOrCreatePluginManagementBody())
appendExpressionToBlockIfAbsent(expression, repositoriesBody)
}
fun addMavenCentralPluginRepository() {
addPluginRepositoryExpression("mavenCentral()")
}
abstract fun addPluginRepository(repository: RepositoryDescription)
fun addResolutionStrategy(pluginId: String) {
val resolutionStrategyBody = getOrAppendInnerBlockBody("resolutionStrategy", getOrCreatePluginManagementBody())
val eachPluginBody = getOrAppendInnerBlockBody("eachPlugin", resolutionStrategyBody)
appendExpressionToBlockIfAbsent(
"""
if (requested.id.id == "$pluginId") {
useModule("org.jetbrains.kotlin:kotlin-gradle-plugin:${'$'}{requested.version}")
}
""".trimIndent(),
eachPluginBody
)
}
fun addIncludedModules(modules: List<String>) {
builder.append(modules.joinToString(prefix = "include ", postfix = "\n") { "'$it'" })
}
fun build() = builder.toString()
abstract fun buildPsiFile(project: Project): T
}
| apache-2.0 | 778f41bebf6485594e0787526be87715 | 37.839506 | 158 | 0.657661 | 5.341256 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/FileRankingCalculator.kt | 3 | 15723 | // 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.debugger
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.psi.PsiElement
import com.sun.jdi.*
import org.jetbrains.kotlin.codegen.ClassBuilderMode
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.diagnostics.DiagnosticUtils
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.util.getLineStartOffset
import org.jetbrains.kotlin.idea.debugger.FileRankingCalculator.Ranking.Companion.LOW
import org.jetbrains.kotlin.idea.debugger.FileRankingCalculator.Ranking.Companion.MAJOR
import org.jetbrains.kotlin.idea.debugger.FileRankingCalculator.Ranking.Companion.MINOR
import org.jetbrains.kotlin.idea.debugger.FileRankingCalculator.Ranking.Companion.NORMAL
import org.jetbrains.kotlin.idea.debugger.FileRankingCalculator.Ranking.Companion.ZERO
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.varargParameterPosition
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.util.capitalizeDecapitalize.capitalizeAsciiOnly
import org.jetbrains.kotlin.utils.keysToMap
import kotlin.jvm.internal.FunctionBase
object FileRankingCalculatorForIde : FileRankingCalculator() {
override fun analyze(element: KtElement) = element.analyze(BodyResolveMode.PARTIAL)
}
abstract class FileRankingCalculator(private val checkClassFqName: Boolean = true) {
abstract fun analyze(element: KtElement): BindingContext
fun findMostAppropriateSource(files: Collection<KtFile>, location: Location): KtFile {
val fileWithRankings: Map<KtFile, Int> = rankFiles(files, location)
val fileWithMaxScore = fileWithRankings.maxByOrNull { it.value }!!
return fileWithMaxScore.key
}
fun rankFiles(files: Collection<KtFile>, location: Location): Map<KtFile, Int> {
assert(files.isNotEmpty())
return files.keysToMap { fileRankingSafe(it, location).value }
}
private class Ranking(val value: Int) : Comparable<Ranking> {
companion object {
val LOW = Ranking(-1000)
val ZERO = Ranking(0)
val MINOR = Ranking(1)
val NORMAL = Ranking(5)
val MAJOR = Ranking(10)
fun minor(condition: Boolean) = if (condition) MINOR else ZERO
}
operator fun unaryMinus() = Ranking(-value)
operator fun plus(other: Ranking) = Ranking(value + other.value)
override fun compareTo(other: Ranking) = this.value - other.value
override fun toString() = value.toString()
}
private fun collect(vararg conditions: Any): Ranking {
return conditions
.map { condition ->
when (condition) {
is Boolean -> Ranking.minor(condition)
is Int -> Ranking(condition)
is Ranking -> condition
else -> error("Invalid condition type ${condition.javaClass.name}")
}
}.fold(ZERO) { sum, r -> sum + r }
}
private fun rankingForClass(clazz: KtClassOrObject, fqName: String, virtualMachine: VirtualMachine): Ranking {
val bindingContext = analyze(clazz)
val descriptor = bindingContext[BindingContext.CLASS, clazz] ?: return ZERO
val jdiType = virtualMachine.classesByName(fqName).firstOrNull() ?: run {
// Check at least the class name if not found
return rankingForClassName(fqName, descriptor, bindingContext)
}
return rankingForClass(clazz, jdiType)
}
private fun rankingForClass(clazz: KtClassOrObject, type: ReferenceType): Ranking {
val bindingContext = analyze(clazz)
val descriptor = bindingContext[BindingContext.CLASS, clazz] ?: return ZERO
return collect(
rankingForClassName(type.name(), descriptor, bindingContext),
Ranking.minor(type.isAbstract && descriptor.modality == Modality.ABSTRACT),
Ranking.minor(type.isFinal && descriptor.modality == Modality.FINAL),
Ranking.minor(type.isStatic && !descriptor.isInner),
rankingForVisibility(descriptor, type)
)
}
private fun rankingForClassName(fqName: String, descriptor: ClassDescriptor, bindingContext: BindingContext): Ranking {
if (DescriptorUtils.isLocal(descriptor)) return ZERO
val expectedFqName = makeTypeMapper(bindingContext).mapType(descriptor).className
return when {
checkClassFqName -> if (expectedFqName == fqName) MAJOR else LOW
else -> if (expectedFqName.simpleName() == fqName.simpleName()) MAJOR else LOW
}
}
private fun rankingForMethod(function: KtFunction, method: Method): Ranking {
val bindingContext = analyze(function)
val descriptor = bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, function] as? CallableMemberDescriptor ?: return ZERO
if (function !is KtConstructor<*> && method.name() != descriptor.name.asString())
return LOW
return collect(
method.isConstructor && function is KtConstructor<*>,
method.isAbstract && descriptor.modality == Modality.ABSTRACT,
method.isFinal && descriptor.modality == Modality.FINAL,
method.isVarArgs && descriptor.varargParameterPosition() >= 0,
rankingForVisibility(descriptor, method),
descriptor.valueParameters.size == (method.safeArguments()?.size ?: 0)
)
}
private fun rankingForAccessor(accessor: KtPropertyAccessor, method: Method): Ranking {
val methodName = method.name()
val expectedPropertyName = accessor.property.name ?: return ZERO
if (accessor.isSetter) {
if (!methodName.startsWith("set") || method.returnType() !is VoidType || method.argumentTypes().size != 1)
return -MAJOR
}
if (accessor.isGetter) {
if (!methodName.startsWith("get") && !methodName.startsWith("is"))
return -MAJOR
else if (method.returnType() is VoidType || method.argumentTypes().isNotEmpty())
return -NORMAL
}
val actualPropertyName = getPropertyName(methodName, accessor.isSetter)
return if (expectedPropertyName == actualPropertyName) NORMAL else -NORMAL
}
private fun getPropertyName(accessorMethodName: String, isSetter: Boolean): String {
if (isSetter) {
return accessorMethodName.drop(3)
}
return accessorMethodName.drop(if (accessorMethodName.startsWith("is")) 2 else 3)
}
private fun rankingForProperty(property: KtProperty, method: Method): Ranking {
val methodName = method.name()
val propertyName = property.name ?: return ZERO
if (property.isTopLevel && method.name() == "<clinit>") {
// For top-level property initializers
return MINOR
}
if (!methodName.startsWith("get") && !methodName.startsWith("set"))
return -MAJOR
// boolean is
return if (methodName.drop(3) == propertyName.capitalizeAsciiOnly()) MAJOR else -NORMAL
}
private fun rankingForVisibility(descriptor: DeclarationDescriptorWithVisibility, accessible: Accessible): Ranking {
return collect(
accessible.isPublic && descriptor.visibility == DescriptorVisibilities.PUBLIC,
accessible.isProtected && descriptor.visibility == DescriptorVisibilities.PROTECTED,
accessible.isPrivate && descriptor.visibility == DescriptorVisibilities.PRIVATE
)
}
private fun fileRankingSafe(file: KtFile, location: Location): Ranking {
return try {
fileRanking(file, location)
} catch (e: ClassNotLoadedException) {
LOG.error("ClassNotLoadedException should never happen in FileRankingCalculator", e)
ZERO
} catch (e: AbsentInformationException) {
ZERO
} catch (e: InternalException) {
ZERO
} catch (e: ProcessCanceledException) {
throw e
} catch (e: RuntimeException) {
LOG.error("Exception during Kotlin sources ranking", e)
ZERO
}
}
private fun fileRanking(file: KtFile, location: Location): Ranking {
val locationLineNumber = location.lineNumber() - 1
val lineStartOffset = file.getLineStartOffset(locationLineNumber) ?: return LOW
val elementAt = file.findElementAt(lineStartOffset) ?: return ZERO
var overallRanking = ZERO
val method = location.method()
if (method.isLambda()) {
val (className, methodName) = method.getContainingClassAndMethodNameForLambda() ?: return ZERO
if (method.isBridge && method.isSynthetic) {
// It might be a static lambda field accessor
val containingClass = elementAt.getParentOfType<KtClassOrObject>(false) ?: return LOW
return rankingForClass(containingClass, className, location.virtualMachine())
} else {
val containingFunctionLiteral =
findFunctionLiteralOnLine(elementAt)
?: findAnonymousFunctionInParent(elementAt)
?: return LOW
val containingCallable = findNonLocalCallableParent(containingFunctionLiteral) ?: return LOW
when (containingCallable) {
is KtFunction -> if (containingCallable.name == methodName) overallRanking += MAJOR
is KtProperty -> if (containingCallable.name == methodName) overallRanking += MAJOR
is KtPropertyAccessor -> if (containingCallable.property.name == methodName) overallRanking += MAJOR
}
val containingClass = containingCallable.getParentOfType<KtClassOrObject>(false)
if (containingClass != null) {
overallRanking += rankingForClass(containingClass, className, location.virtualMachine())
}
return overallRanking
}
}
// TODO support <clinit>
if (method.name() == "<init>") {
val containingClass = elementAt.getParentOfType<KtClassOrObject>(false) ?: return LOW
val constructorOrInitializer =
elementAt.getParentOfTypes2<KtConstructor<*>, KtClassInitializer>()?.takeIf { containingClass.isAncestor(it) }
?: containingClass.primaryConstructor?.takeIf { it.getLine() == containingClass.getLine() }
if (constructorOrInitializer == null
&& locationLineNumber < containingClass.getLine()
&& locationLineNumber > containingClass.lastChild.getLine()
) {
return LOW
}
overallRanking += rankingForClass(containingClass, location.declaringType())
if (constructorOrInitializer is KtConstructor<*>)
overallRanking += rankingForMethod(constructorOrInitializer, method)
} else {
val callable = findNonLocalCallableParent(elementAt) ?: return LOW
overallRanking += when (callable) {
is KtFunction -> rankingForMethod(callable, method)
is KtPropertyAccessor -> rankingForAccessor(callable, method)
is KtProperty -> rankingForProperty(callable, method)
else -> return LOW
}
val containingClass = elementAt.getParentOfType<KtClassOrObject>(false)
if (containingClass != null)
overallRanking += rankingForClass(containingClass, location.declaringType())
}
return overallRanking
}
private fun findFunctionLiteralOnLine(element: PsiElement): KtFunctionLiteral? {
val literal = element.getParentOfType<KtFunctionLiteral>(false)
if (literal != null) {
return literal
}
val callExpression = element.getParentOfType<KtCallExpression>(false) ?: return null
for (lambdaArgument in callExpression.lambdaArguments) {
if (element.getLine() == lambdaArgument.getLine()) {
val functionLiteral = lambdaArgument.getLambdaExpression()?.functionLiteral
if (functionLiteral != null) {
return functionLiteral
}
}
}
return null
}
private fun findAnonymousFunctionInParent(element: PsiElement): KtNamedFunction? {
val parentFun = element.getParentOfType<KtNamedFunction>(false)
if (parentFun != null && parentFun.isFunctionalExpression()) {
return parentFun
}
return null
}
private tailrec fun findNonLocalCallableParent(element: PsiElement): PsiElement? {
fun PsiElement.isCallableDeclaration() = this is KtProperty || this is KtFunction || this is KtAnonymousInitializer
// org.jetbrains.kotlin.psi.KtPsiUtil.isLocal
fun PsiElement.isLocalDeclaration(): Boolean {
val containingDeclaration = getParentOfType<KtDeclaration>(true)
return containingDeclaration is KtCallableDeclaration || containingDeclaration is KtPropertyAccessor
}
if (element.isCallableDeclaration() && !element.isLocalDeclaration()) {
return element
}
val containingCallable = element.getParentOfTypes3<KtProperty, KtFunction, KtAnonymousInitializer>()
?: return null
if (containingCallable.isLocalDeclaration()) {
return findNonLocalCallableParent(containingCallable)
}
return containingCallable
}
private fun Method.getContainingClassAndMethodNameForLambda(): Pair<String, String>? {
// TODO this breaks nested classes
val declaringClass = declaringType() as ClassType
val (className, methodName) = declaringClass.name().split('$', limit = 3)
.takeIf { it.size == 3 }
?: return null
return Pair(className, methodName)
}
private fun Method.isLambda(): Boolean {
val declaringClass = declaringType() as? ClassType ?: return false
tailrec fun ClassType.isLambdaClass(): Boolean {
if (interfaces().any { it.name() == FunctionBase::class.java.name }) {
return true
}
val superClass = superclass() ?: return false
return superClass.isLambdaClass()
}
return declaringClass.superclass()?.isLambdaClass() ?: false
}
private fun makeTypeMapper(bindingContext: BindingContext): KotlinTypeMapper {
return KotlinTypeMapper(
bindingContext,
ClassBuilderMode.LIGHT_CLASSES,
"debugger",
KotlinTypeMapper.LANGUAGE_VERSION_SETTINGS_DEFAULT, // TODO use proper LanguageVersionSettings
useOldInlineClassesManglingScheme = false
)
}
companion object {
val LOG = Logger.getInstance("FileRankingCalculator")
}
}
private fun String.simpleName() = substringAfterLast('.').substringAfterLast('$')
private fun PsiElement.getLine(): Int {
return DiagnosticUtils.getLineAndColumnInPsiFile(containingFile, textRange).line
}
| apache-2.0 | 07721a68c7b8f5067799158378353dc3 | 42.076712 | 158 | 0.660752 | 5.583452 | false | false | false | false |
androidx/androidx | navigation/navigation-safe-args-gradle-plugin/src/main/kotlin/androidx/navigation/safeargs/gradle/ArgumentsGenerationTask.kt | 3 | 6463 | /*
* Copyright 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 androidx.navigation.safeargs.gradle
import androidx.navigation.safe.args.generator.ErrorMessage
import androidx.navigation.safe.args.generator.SafeArgsGenerator
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.DirectoryProperty
import org.gradle.api.file.ProjectLayout
import org.gradle.api.provider.Property
import org.gradle.api.tasks.CacheableTask
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.InputFiles
import org.gradle.api.tasks.OutputDirectory
import org.gradle.api.tasks.PathSensitive
import org.gradle.api.tasks.PathSensitivity
import org.gradle.api.tasks.TaskAction
import org.gradle.work.ChangeType
import org.gradle.work.Incremental
import org.gradle.work.InputChanges
import java.io.File
import javax.inject.Inject
private const val MAPPING_FILE = "file_mappings.json"
@CacheableTask
abstract class ArgumentsGenerationTask @Inject constructor(
private val projectLayout: ProjectLayout
) : DefaultTask() {
@get:Input
abstract val rFilePackage: Property<String>
@get:Input
abstract val applicationId: Property<String>
@get:Input
abstract val useAndroidX: Property<Boolean>
@get:Input
abstract val generateKotlin: Property<Boolean>
@get:OutputDirectory
abstract val outputDir: DirectoryProperty
@get:PathSensitive(PathSensitivity.RELATIVE)
@get:Incremental
@get:InputFiles
abstract val navigationFiles: ConfigurableFileCollection
@get:OutputDirectory
abstract val incrementalFolder: DirectoryProperty
private fun generateArgs(navFiles: Collection<File>, out: File) = navFiles.map { file ->
val output = SafeArgsGenerator(
rFilePackage = rFilePackage.get(),
applicationId = applicationId.orNull ?: "",
navigationXml = file,
outputDir = out,
useAndroidX = useAndroidX.get(),
generateKotlin = generateKotlin.get()
).generate()
Mapping(
file.relativeTo(
projectLayout.projectDirectory.asFile
).path,
output.fileNames
) to output.errors
}.unzip().let { (mappings, errorLists) -> mappings to errorLists.flatten() }
private fun writeMappings(mappings: List<Mapping>) {
File(incrementalFolder.asFile.get(), MAPPING_FILE).writer().use {
Gson().toJson(mappings, it)
}
}
private fun readMappings(): List<Mapping> {
val type = object : TypeToken<List<Mapping>>() {}.type
val mappingsFile = File(incrementalFolder.asFile.get(), MAPPING_FILE)
return if (mappingsFile.exists()) {
mappingsFile.reader().use { Gson().fromJson(it, type) }
} else {
emptyList()
}
}
@TaskAction
internal fun taskAction(inputs: InputChanges) {
if (inputs.isIncremental) {
doIncrementalTaskAction(inputs)
} else {
logger.info("Unable do incremental execution: full task run")
doFullTaskAction()
}
}
private fun doFullTaskAction() {
val outputDirFile = outputDir.asFile.get()
if (outputDirFile.exists() && !outputDirFile.deleteRecursively()) {
logger.warn("Failed to clear directory for navigation arguments")
}
if (!outputDirFile.exists() && !outputDirFile.mkdirs()) {
throw GradleException("Failed to create directory for navigation arguments")
}
val (mappings, errors) = generateArgs(navigationFiles.files, outputDirFile)
writeMappings(mappings)
failIfErrors(errors)
}
private fun doIncrementalTaskAction(inputs: InputChanges) {
val modifiedFiles = mutableSetOf<File>()
val removedFiles = mutableSetOf<File>()
inputs.getFileChanges(navigationFiles).forEach { change ->
if (change.changeType == ChangeType.MODIFIED || change.changeType == ChangeType.ADDED) {
modifiedFiles.add(change.file)
} else if (change.changeType == ChangeType.REMOVED) {
removedFiles.add(change.file)
}
}
val oldMapping = readMappings()
val (newMapping, errors) = generateArgs(modifiedFiles, outputDir.asFile.get())
val newJavaFiles = newMapping.flatMap { it.javaFiles }.toSet()
val changedInputs = removedFiles + modifiedFiles
val (modified, unmodified) = oldMapping.partition {
File(projectLayout.projectDirectory.asFile, it.navFile) in changedInputs
}
modified.flatMap { it.javaFiles }
.filter { name -> name !in newJavaFiles }
.forEach { javaName ->
val fileExtension = if (generateKotlin.get()) { ".kt" } else { ".java" }
val fileName =
"${javaName.replace('.', File.separatorChar)}$fileExtension"
val file = File(outputDir.asFile.get(), fileName)
if (file.exists()) {
file.delete()
}
}
writeMappings(unmodified + newMapping)
failIfErrors(errors)
}
private fun failIfErrors(errors: List<ErrorMessage>) {
if (errors.isNotEmpty()) {
val errString = errors.joinToString("\n") { it.toClickableText() }
throw GradleException(
"androidx.navigation.safeargs plugin failed.\n " +
"Following errors found: \n$errString"
)
}
}
}
private fun ErrorMessage.toClickableText() = "$path:$line:$column " +
"(${File(path).name}:$line): \n" +
"error: $message"
private data class Mapping(val navFile: String, val javaFiles: List<String>)
| apache-2.0 | a5583e550c55e3ace4bf717654d98619 | 35.931429 | 100 | 0.663314 | 4.613133 | false | false | false | false |
aksiksi/workshop-jb | src/iii_properties/_18_Properties_.kt | 3 | 1434 | package iii_properties
import java.util.Random
import util.TODO
fun localVariables() {
// immutable variable
val i = 1
// doesn't compile:
// i = 2
// mutable variable
var j = 3
j = 1765
}
class SimpleProperty {
//In the bytecode the property corresponds to field + getter + setter (if it's mutable).
var property: String = "42"
}
fun usage(sp: SimpleProperty) {
// Usages are compiled to getter and setter invocations.
// You can open "View -> Tool windows -> Kotlin" in IntelliJ to see the bytecode.
val x = sp.property
sp.property = x + 1
}
class PropertiesWithCustomAccessors {
var generatedByDefault: Int = 0
set(value: Int) { $generatedByDefault = value }
get() = $generatedByDefault
val propertyWithoutBackingField: Int
get() = 42
val infiniteRecursion: Int? = Random().nextInt()
get() = if ($infiniteRecursion!! < 42) null else infiniteRecursion
}
class PropertyExample() {
var counter = 0
var propertyWithCounter: Int? = todoTask18()
}
fun todoTask18() = TODO(
"""
Task 18.
Add a custom setter to PropertyExample.propertyWithCounter so that
the 'counter' property is incremented every time 'propertyWithCounter' is assigned to.
Initialize 'propertyWithCounter' with null (the setter should NOT be invoked on initialization).
""",
references = { PropertyExample() }
)
| mit | b7461daafceb1868c24caf6d924bd022 | 25.555556 | 104 | 0.661785 | 4.306306 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/caches/project/VfsCodeBlockModificationListener.kt | 1 | 1598 | // 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.caches.project
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import org.jetbrains.kotlin.idea.caches.trackers.KotlinCodeBlockModificationListener
import org.jetbrains.kotlin.idea.core.KotlinPluginDisposable
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
class VfsCodeBlockModificationListener: StartupActivity.Background {
override fun runActivity(project: Project) {
val disposable = KotlinPluginDisposable.getInstance(project)
val kotlinOCBModificationListener = KotlinCodeBlockModificationListener.getInstance(project)
val connection = project.messageBus.connect(disposable)
connection.subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
val projectRelatedVfsFileChange = events.any { event ->
val file = event.takeIf { it.isFromRefresh }?.file ?: return@any false
ProjectRootsUtil.isProjectSourceFile(project, file)
}
if (projectRelatedVfsFileChange) {
kotlinOCBModificationListener.incModificationCount()
}
}
})
}
} | apache-2.0 | 7d0555b3d2047d9f446dabaac45df1bf | 52.3 | 158 | 0.737171 | 5.154839 | false | false | false | false |
dowenliu-xyz/ketcd | ketcd-core/src/main/kotlin/xyz/dowenliu/ketcd/option/CompactOption.kt | 1 | 1889 | package xyz.dowenliu.ketcd.option
/**
* The options for compaction operation.
*
* create at 2017/4/15
* @author liufl
* @since 0.1.0
*
* @property revision The revision to use for the compact request.
* @property physical Whether the compact should wait until physically applied
*/
class CompactOption private constructor(val revision: Long, val physical: Boolean) {
/**
* Companion object of [CompactOption]
*/
companion object {
/**
* The default compact options.
*/
@JvmStatic val DEFAULT = newBuilder().build()
/**
* Create a builder to construct options for compaction operation.
*
* @return builder
*/
@JvmStatic fun newBuilder() = Builder()
}
/**
* Builder to construct [CompactOption].
*/
class Builder internal constructor() {
private var revision = 0L
private var physical = false
/**
* Provide the revision to use for the compact request.
*
* All superseded keys with a revision less than the compaction revision will be removed.
*
* @param revision the revision to compact
* @return this builder to train.
*/
fun withRevision(revision: Long): Builder {
this.revision = revision
return this
}
/**
* Set the compact request to wait until the compaction is physically applied.
*
* @param physical whether the compact should wait until physically applied
* @return this builder to train.
*/
fun withPhysical(physical: Boolean): Builder {
this.physical = physical
return this
}
/**
* Construct a [CompactOption].
*/
fun build(): CompactOption = CompactOption(revision, physical)
}
} | apache-2.0 | 1628e09779c225f6db669e60b3223c66 | 27.208955 | 97 | 0.587612 | 5.050802 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/scripting/SdkValidator.kt | 1 | 2447 | // 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.gradleJava.scripting
import com.intellij.notification.NotificationType
import com.intellij.openapi.externalSystem.service.execution.ExternalSystemJdkUtil
import com.intellij.openapi.externalSystem.service.execution.InvalidSdkException
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JdkUtil
import com.intellij.openapi.startup.StartupActivity
import org.jetbrains.kotlin.idea.gradle.KotlinIdeaGradleBundle
import org.jetbrains.plugins.gradle.service.project.GradleNotification.NOTIFICATION_GROUP
import org.jetbrains.plugins.gradle.settings.GradleProjectSettings
import org.jetbrains.plugins.gradle.settings.GradleSettings
class SdkValidator : StartupActivity {
override fun runActivity(project: Project) {
GradleSettings.getInstance(project).linkedProjectsSettings.forEach {
it.validateGradleSdk(project)
}
}
}
fun GradleProjectSettings.validateGradleSdk(project: Project, jdkHomePath: String? = null) {
val gradleJvm = gradleJvm ?: return
var jdkName: String? = null
var message: String? = null
val homePath = if (jdkHomePath != null) {
jdkHomePath
} else {
// gradleJvm could be #USE_PROJECT_JDK etc, see ExternalSystemJdkUtil
val jdk = try {
ExternalSystemJdkUtil.getJdk(project, gradleJvm)
} catch (e: InvalidSdkException) {
message = e.message
null
} catch (e: Exception) {
null
}
jdkName = jdk?.name
jdk?.homePath
}
if (message == null) {
message = when {
homePath == null -> {
KotlinIdeaGradleBundle.message("notification.gradle.jvm.undefined")
}
!JdkUtil.checkForJdk(homePath) -> {
jdkName?.let { KotlinIdeaGradleBundle.message("notification.jdk.0.points.to.invalid.jdk", it) }
?: KotlinIdeaGradleBundle.message("notification.gradle.jvm.0.incorrect", homePath)
}
else -> null
}
}
message?.let {
NOTIFICATION_GROUP.createNotification(KotlinIdeaGradleBundle.message("notification.invalid.gradle.jvm.configuration.title"), message, NotificationType.ERROR).notify(project)
}
}
| apache-2.0 | 1c8da56d034f95553a31e1ad6ad817ab | 36.646154 | 181 | 0.698815 | 4.78865 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/eval4j/test/org/jetbrains/eval4j/test/main.kt | 3 | 14490 | // 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.eval4j.test
import junit.framework.TestCase
import junit.framework.TestSuite
import org.jetbrains.eval4j.*
import org.jetbrains.org.objectweb.asm.Opcodes.ACC_STATIC
import org.jetbrains.org.objectweb.asm.Type
import org.jetbrains.org.objectweb.asm.tree.MethodNode
import org.jetbrains.org.objectweb.asm.tree.analysis.Frame
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
import java.lang.reflect.*
import java.lang.reflect.Array as JArray
fun suite(): TestSuite = buildTestSuite { methodNode, ownerClass, expected ->
object : TestCase(getTestName(methodNode.name)) {
override fun runTest() {
if (!isIgnored(methodNode)) {
val value = interpreterLoop(
methodNode,
initFrame(
ownerClass.getInternalName(),
methodNode
),
REFLECTION_EVAL
)
if (expected is ExceptionThrown && value is ExceptionThrown) {
assertEquals(expected.exception.toString(), value.exception.toString())
} else {
assertEquals(expected.toString(), value.toString())
}
}
}
private fun isIgnored(methodNode: MethodNode): Boolean {
return methodNode.visibleAnnotations?.any {
val annotationDesc = it.desc
annotationDesc != null && Type.getType(annotationDesc) == Type.getType(IgnoreInReflectionTests::class.java)
} ?: false
}
}
}
fun Class<*>.getInternalName(): String = Type.getType(this).internalName
fun initFrame(
owner: String,
m: MethodNode
): Frame<Value> {
val current = Frame<Value>(m.maxLocals, m.maxStack)
current.setReturn(makeNotInitializedValue(Type.getReturnType(m.desc)))
var local = 0
if ((m.access and ACC_STATIC) == 0) {
val ctype = Type.getObjectType(owner)
val newInstance = REFLECTION_EVAL.newInstance(ctype)
val thisValue = REFLECTION_EVAL.invokeMethod(newInstance, MethodDescription(owner, "<init>", "()V", false), listOf(), true)
current.setLocal(local++, thisValue)
}
val args = Type.getArgumentTypes(m.desc)
for (i in args.indices) {
current.setLocal(local++, makeNotInitializedValue(args[i]))
if (args[i].size == 2) {
current.setLocal(local++, NOT_A_VALUE)
}
}
while (local < m.maxLocals) {
current.setLocal(local++, NOT_A_VALUE)
}
return current
}
fun objectToValue(obj: Any?, expectedType: Type): Value {
return when (expectedType.sort) {
Type.VOID -> VOID_VALUE
Type.BOOLEAN -> boolean(obj as Boolean)
Type.BYTE -> byte(obj as Byte)
Type.SHORT -> short(obj as Short)
Type.CHAR -> char(obj as Char)
Type.INT -> int(obj as Int)
Type.LONG -> long(obj as Long)
Type.DOUBLE -> double(obj as Double)
Type.FLOAT -> float(obj as Float)
Type.OBJECT -> if (obj == null) NULL_VALUE else ObjectValue(obj, expectedType)
else -> throw UnsupportedOperationException("Unsupported result type: $expectedType")
}
}
object REFLECTION_EVAL : Eval {
val lookup = ReflectionLookup(ReflectionLookup::class.java.classLoader!!)
override fun loadClass(classType: Type): Value {
return ObjectValue(findClass(classType), Type.getType(Class::class.java))
}
override fun loadString(str: String): Value = ObjectValue(str, Type.getType(String::class.java))
override fun newInstance(classType: Type): Value {
return NewObjectValue(classType)
}
override fun isInstanceOf(value: Value, targetType: Type): Boolean {
val _class = findClass(targetType)
return _class.isInstance(value.obj())
}
@Suppress("UNCHECKED_CAST")
override fun newArray(arrayType: Type, size: Int): Value {
return ObjectValue(JArray.newInstance(findClass(arrayType).componentType as Class<Any>, size), arrayType)
}
override fun newMultiDimensionalArray(arrayType: Type, dimensionSizes: List<Int>): Value {
return ObjectValue(ArrayHelper.newMultiArray(findClass(arrayType.elementType), *dimensionSizes.toTypedArray()), arrayType)
}
override fun getArrayLength(array: Value): Value {
return int(JArray.getLength(array.obj().checkNull()))
}
override fun getArrayElement(array: Value, index: Value): Value {
val asmType = array.asmType
val elementType = if (asmType.dimensions == 1) asmType.elementType else Type.getType(asmType.descriptor.substring(1))
val arr = array.obj().checkNull()
val ind = index.int
return mayThrow {
when (elementType.sort) {
Type.BOOLEAN -> boolean(JArray.getBoolean(arr, ind))
Type.BYTE -> byte(JArray.getByte(arr, ind))
Type.SHORT -> short(JArray.getShort(arr, ind))
Type.CHAR -> char(JArray.getChar(arr, ind))
Type.INT -> int(JArray.getInt(arr, ind))
Type.LONG -> long(JArray.getLong(arr, ind))
Type.FLOAT -> float(JArray.getFloat(arr, ind))
Type.DOUBLE -> double(JArray.getDouble(arr, ind))
Type.OBJECT,
Type.ARRAY -> {
val value = JArray.get(arr, ind)
if (value == null) NULL_VALUE else ObjectValue(value, Type.getType(value::class.java))
}
else -> throw UnsupportedOperationException("Unsupported array element type: $elementType")
}
}
}
override fun setArrayElement(array: Value, index: Value, newValue: Value) {
val arr = array.obj().checkNull()
val ind = index.int
if (array.asmType.dimensions > 1) {
JArray.set(arr, ind, newValue.obj())
return
}
val elementType = array.asmType.elementType
mayThrow {
when (elementType.sort) {
Type.BOOLEAN -> JArray.setBoolean(arr, ind, newValue.boolean)
Type.BYTE -> JArray.setByte(arr, ind, newValue.int.toByte())
Type.SHORT -> JArray.setShort(arr, ind, newValue.int.toShort())
Type.CHAR -> JArray.setChar(arr, ind, newValue.int.toChar())
Type.INT -> JArray.setInt(arr, ind, newValue.int)
Type.LONG -> JArray.setLong(arr, ind, newValue.long)
Type.FLOAT -> JArray.setFloat(arr, ind, newValue.float)
Type.DOUBLE -> JArray.setDouble(arr, ind, newValue.double)
Type.OBJECT,
Type.ARRAY -> {
JArray.set(arr, ind, newValue.obj())
}
else -> throw UnsupportedOperationException("Unsupported array element type: $elementType")
}
}
}
fun <T> mayThrow(f: () -> T): T {
try {
try {
return f()
} catch (ite: InvocationTargetException) {
throw ite.cause ?: ite
}
} catch (e: Throwable) {
throw ThrownFromEvaluatedCodeException(ObjectValue(e, Type.getType(e::class.java)))
}
}
override fun getStaticField(fieldDesc: FieldDescription): Value {
val field = findStaticField(fieldDesc)
val result = mayThrow { field.get(null) }
return objectToValue(result, fieldDesc.fieldType)
}
override fun setStaticField(fieldDesc: FieldDescription, newValue: Value) {
val field = findStaticField(fieldDesc)
val obj = newValue.obj(fieldDesc.fieldType)
mayThrow { field.set(null, obj) }
}
fun findStaticField(fieldDesc: FieldDescription): Field {
assertTrue(fieldDesc.isStatic)
val field = findClass(fieldDesc).findField(fieldDesc)
assertNotNull("Field not found: $fieldDesc", field)
assertTrue("Field is not static: $field", (field!!.modifiers and Modifier.STATIC) != 0)
return field
}
override fun invokeStaticMethod(methodDesc: MethodDescription, arguments: List<Value>): Value {
assertTrue(methodDesc.isStatic)
val method = findClass(methodDesc).findMethod(methodDesc)
assertNotNull("Method not found: $methodDesc", method)
val args = mapArguments(arguments, methodDesc.parameterTypes).toTypedArray()
val result = mayThrow { method!!.invoke(null, *args) }
return objectToValue(result, methodDesc.returnType)
}
fun findClass(memberDesc: MemberDescription): Class<Any> = findClass(Type.getObjectType(memberDesc.ownerInternalName))
fun findClass(asmType: Type): Class<Any> {
val owner = lookup.findClass(asmType)
assertNotNull("Class not found: ${asmType}", owner)
return owner as Class<Any>
}
override fun getField(instance: Value, fieldDesc: FieldDescription): Value {
val obj = instance.obj().checkNull()
val field = findInstanceField(obj, fieldDesc)
return objectToValue(mayThrow { field.get(obj) }, fieldDesc.fieldType)
}
override fun setField(instance: Value, fieldDesc: FieldDescription, newValue: Value) {
val obj = instance.obj().checkNull()
val field = findInstanceField(obj, fieldDesc)
val newObj = newValue.obj(fieldDesc.fieldType)
mayThrow { field.set(obj, newObj) }
}
fun findInstanceField(obj: Any, fieldDesc: FieldDescription): Field {
val _class = obj::class.java
val field = _class.findField(fieldDesc)
assertNotNull("Field not found: $fieldDesc", field)
return field!!
}
override fun invokeMethod(instance: Value, methodDesc: MethodDescription, arguments: List<Value>, invokeSpecial: Boolean): Value {
if (invokeSpecial) {
if (methodDesc.name == "<init>") {
// Constructor call
@Suppress("UNCHECKED_CAST")
val _class = findClass((instance as NewObjectValue).asmType)
val ctor = _class.findConstructor(methodDesc)
assertNotNull("Constructor not found: $methodDesc", ctor)
val args = mapArguments(arguments, methodDesc.parameterTypes).toTypedArray()
val result = mayThrow { ctor!!.newInstance(*args) }
instance.value = result
return objectToValue(result, instance.asmType)
} else {
// TODO
throw UnsupportedOperationException("invokespecial is not suported in reflection eval")
}
}
val obj = instance.obj().checkNull()
val method = obj::class.java.findMethod(methodDesc)
assertNotNull("Method not found: $methodDesc", method)
val args = mapArguments(arguments, methodDesc.parameterTypes).toTypedArray()
val result = mayThrow { method!!.invoke(obj, *args) }
return objectToValue(result, methodDesc.returnType)
}
private fun mapArguments(arguments: List<Value>, expecetedTypes: List<Type>): List<Any?> {
return arguments.zip(expecetedTypes).map {
val (arg, expectedType) = it
arg.obj(expectedType)
}
}
}
class ReflectionLookup(val classLoader: ClassLoader) {
@Suppress("UNCHECKED_CAST")
fun findClass(asmType: Type): Class<*>? {
return when (asmType.sort) {
Type.BOOLEAN -> java.lang.Boolean.TYPE
Type.BYTE -> java.lang.Byte.TYPE
Type.SHORT -> java.lang.Short.TYPE
Type.CHAR -> Character.TYPE
Type.INT -> Integer.TYPE
Type.LONG -> java.lang.Long.TYPE
Type.FLOAT -> java.lang.Float.TYPE
Type.DOUBLE -> java.lang.Double.TYPE
Type.OBJECT -> classLoader.loadClass(asmType.internalName.replace('/', '.'))
Type.ARRAY -> Class.forName(asmType.descriptor.replace('/', '.'))
else -> throw UnsupportedOperationException("Unsupported type: $asmType")
}
}
}
@Suppress("UNCHECKED_CAST")
fun Class<out Any>.findMethod(methodDesc: MethodDescription): Method? {
for (declared in declaredMethods) {
if (methodDesc.matches(declared)) return declared
}
val fromSuperClass = (superclass as Class<Any>).findMethod(methodDesc)
if (fromSuperClass != null) return fromSuperClass
for (supertype in interfaces) {
val fromSuper = (supertype as Class<Any>).findMethod(methodDesc)
if (fromSuper != null) return fromSuper
}
return null
}
@Suppress("UNCHECKED_CAST")
fun Class<Any>.findConstructor(methodDesc: MethodDescription): Constructor<Any?>? {
for (declared in declaredConstructors) {
if (methodDesc.matches(declared)) return declared as Constructor<Any?>
}
return null
}
fun MethodDescription.matches(ctor: Constructor<*>): Boolean {
val methodParams = ctor.parameterTypes!!
if (parameterTypes.size != methodParams.size) return false
for ((i, p) in parameterTypes.withIndex()) {
if (!p.matches(methodParams[i])) return false
}
return true
}
fun MethodDescription.matches(method: Method): Boolean {
if (name != method.name) return false
val methodParams = method.parameterTypes!!
if (parameterTypes.size != methodParams.size) return false
for ((i, p) in parameterTypes.withIndex()) {
if (!p.matches(methodParams[i])) return false
}
return returnType.matches(method.returnType!!)
}
@Suppress("UNCHECKED_CAST")
fun Class<out Any>.findField(fieldDesc: FieldDescription): Field? {
for (declared in declaredFields) {
if (fieldDesc.matches(declared)) return declared
}
val superclass = superclass
if (superclass != null) {
val fromSuperClass = (superclass as Class<Any>).findField(fieldDesc)
if (fromSuperClass != null) return fromSuperClass
}
for (supertype in interfaces) {
val fromSuper = (supertype as Class<Any>).findField(fieldDesc)
if (fromSuper != null) return fromSuper
}
return null
}
fun FieldDescription.matches(field: Field): Boolean {
if (name != field.name) return false
return fieldType.matches(field.type!!)
}
fun Type.matches(_class: Class<*>): Boolean = this == Type.getType(_class) | apache-2.0 | ad897829b94b6a4625ca02d70dfbad21 | 37.437666 | 158 | 0.630228 | 4.59854 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/check/ComponentsCheck.kt | 1 | 3064 | package com.cognifide.gradle.aem.common.instance.check
import com.cognifide.gradle.aem.common.utils.shortenClass
import com.cognifide.gradle.common.utils.Formats
@Suppress("MagicNumber")
class ComponentsCheck(group: CheckGroup) : DefaultCheck(group) {
val platformComponents = aem.obj.strings {
convention(listOf(
"com.day.crx.packaging.*",
"org.apache.sling.installer.*",
"!org.apache.sling.installer.hc.*",
"!org.apache.sling.installer.core.impl.console.*"
))
}
val specificComponents = aem.obj.strings { convention(listOf()) }
init {
sync.apply {
http.connectionTimeout.convention(15_000)
}
}
@Suppress("ComplexMethod")
override fun check() {
logger.info("Checking OSGi components on $instance")
val state = state(sync.osgiFramework.determineComponentState())
if (state.unknown) {
statusLogger.error(
"Components unknown",
"Unknown component state on $instance"
)
return
}
val total = state.components.size
val inactive = state.find(platformComponents.get(), listOf()).filter { !it.active }
if (inactive.isNotEmpty()) {
statusLogger.error(
when (inactive.size) {
1 -> "Component inactive '${inactive.first().uid.shortenClass()}'"
in 2..10 -> "Components inactive (${inactive.size})"
else -> "Components inactive (${Formats.percentExplained(inactive.size, total)})"
},
"Inactive components detected on $instance:\n${logValues(inactive)}"
)
}
val failed = state.find(specificComponents.get(), listOf()).filter { it.failedActivation }
if (failed.isNotEmpty()) {
statusLogger.error(
when (failed.size) {
1 -> "Component failed '${failed.first().uid.shortenClass()}'"
in 2..10 -> "Components failed (${failed.size})"
else -> "Components failed (${Formats.percentExplained(failed.size, total)})"
},
"Components with failed activation detected on $instance:\n${logValues(failed)}"
)
}
val unsatisfied = state.find(specificComponents.get(), listOf()).filter { it.unsatisfied }
if (unsatisfied.isNotEmpty()) {
statusLogger.error(
when (unsatisfied.size) {
1 -> "Component unsatisfied '${unsatisfied.first().uid.shortenClass()}'"
in 2..10 -> "Components unsatisfied (${unsatisfied.size})"
else -> "Components unsatisified (${Formats.percentExplained(unsatisfied.size, total)})"
},
"Unsatisfied components detected on $instance:\n${logValues(unsatisfied)}"
)
}
}
}
| apache-2.0 | c1d69fb6c3f21532f661ff8549a70542 | 38.792208 | 112 | 0.548629 | 5.089701 | false | false | false | false |
gregcockroft/AndroidMath | mathdisplaylib/src/main/java/com/agog/mathdisplay/MTFontManager.kt | 1 | 1762 | package com.agog.mathdisplay
import android.content.Context
import android.content.res.AssetManager
import com.agog.mathdisplay.parse.MathDisplayException
import com.agog.mathdisplay.render.MTFont
const val KDefaultFontSize = 20f
class MTFontManager {
companion object {
private var assets: AssetManager? = null
private val nameToFontMap: HashMap<String, MTFont> = HashMap<String, MTFont>()
/*
@param name filename in that assets directory of the opentype font minus the otf extension
@param size device pixels
*/
fun fontWithName(name: String, size: Float): MTFont? {
var f = nameToFontMap[name]
if (f == null) {
val a = assets
if (a == null) {
throw MathDisplayException("MTFontManager assets is null")
} else {
f = MTFont(a, name, size)
nameToFontMap[name] = f
}
return f
}
if (f.fontSize == size) {
return f
} else {
return f.copyFontWithSize(size)
}
}
fun setContext(context: Context) {
assets = context.assets
}
fun latinModernFontWithSize(size: Float): MTFont? {
return fontWithName("latinmodern-math", size)
}
fun xitsFontWithSize(size: Float): MTFont? {
return fontWithName("xits-math", size)
}
fun termesFontWithSize(size: Float): MTFont? {
return fontWithName("texgyretermes-math", size)
}
fun defaultFont(): MTFont? {
return latinModernFontWithSize(KDefaultFontSize)
}
}
} | mit | a0a7325a60aa3f6130f94d133f8fcf4d | 28.383333 | 103 | 0.557321 | 4.71123 | false | false | false | false |
ReactiveX/RxKotlin | src/test/kotlin/io/reactivex/rxkotlin/ExtensionTests.kt | 1 | 9338 | /**
* Copyright 2017 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 io.reactivex.rxkotlin
import io.reactivex.Notification
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.functions.Function3
import io.reactivex.schedulers.TestScheduler
import org.funktionale.partials.invoke
import org.junit.Assert.assertEquals
import org.junit.Assert.fail
import org.junit.Test
import org.mockito.Mockito.*
import java.util.concurrent.TimeUnit
import kotlin.concurrent.thread
/**
* This class contains tests using the extension functions provided by the language adaptor.
*/
class ExtensionTests : KotlinTests() {
@Test fun testCreate() {
Observable.create<String> { subscriber ->
subscriber.onNext("Hello")
subscriber.onComplete()
}.subscribe { result ->
a.received(result)
}
verify(a, times(1)).received("Hello")
}
@Test fun testFilter() {
listOf(1, 2, 3).toObservable().filter { it >= 2 }.subscribe(received())
verify(a, times(0)).received(1)
verify(a, times(1)).received(2)
verify(a, times(1)).received(3)
}
@Test fun testLast() {
assertEquals("three", listOf("one", "two", "three").toObservable().blockingLast())
}
@Test fun testLastWithPredicate() {
assertEquals("two", listOf("one", "two", "three").toObservable().filter { it.length == 3 }.blockingLast())
}
@Test fun testMap2() {
listOf(1, 2, 3).toObservable().map { v -> "hello_$v" }.subscribe(received())
verify(a, times(1)).received("hello_1")
verify(a, times(1)).received("hello_2")
verify(a, times(1)).received("hello_3")
}
@Test fun testMaterialize() {
listOf(1, 2, 3).toObservable().materialize().subscribe(received())
verify(a, times(4)).received(any(Notification::class.java))
verify(a, times(0)).error(any(Exception::class.java))
}
@Test fun testMerge() {
listOf(listOf(1, 2, 3).toObservable(),
listOf(Observable.just(6),
Observable.error(NullPointerException()),
Observable.just(7)
).merge(),
listOf(4, 5).toObservable()
).merge().subscribe(received(), { e -> a.error(e) })
verify(a, times(1)).received(1)
verify(a, times(1)).received(2)
verify(a, times(1)).received(3)
verify(a, times(0)).received(4)
verify(a, times(0)).received(5)
verify(a, times(1)).received(6)
verify(a, times(0)).received(7)
verify(a, times(1)).error(any(NullPointerException::class.java))
}
@Test fun testScriptWithMaterialize() {
TestFactory().observable.materialize().subscribe(received())
verify(a, times(2)).received(any(Notification::class.java))
}
@Test fun testScriptWithMerge() {
val factory = TestFactory()
(factory.observable.mergeWith(factory.observable)).subscribe((received()))
verify(a, times(1)).received("hello_1")
verify(a, times(1)).received("hello_2")
}
@Test fun testFromWithIterable() {
assertEquals(5, listOf(1, 2, 3, 4, 5).toObservable().count().blockingGet())
}
@Test fun testStartWith() {
val list = listOf(10, 11, 12, 13, 14)
val startList = listOf(1, 2, 3, 4, 5)
assertEquals(6, list.toObservable().startWith(0).count().blockingGet())
assertEquals(10, list.toObservable().startWith(startList).count().blockingGet())
}
@Test fun testScriptWithOnNext() {
TestFactory().observable
.subscribe(received())
verify(a, times(1)).received("hello_1")
}
@Test fun testSkipTake() {
listOf(1, 2, 3)
.toObservable()
.skip(1)
.take(1)
.subscribe(received())
verify(a, times(0)).received(1)
verify(a, times(1)).received(2)
verify(a, times(0)).received(3)
}
@Test fun testSkip() {
listOf(1, 2, 3)
.toObservable()
.skip(2)
.subscribe(received())
verify(a, times(0)).received(1)
verify(a, times(0)).received(2)
verify(a, times(1)).received(3)
}
@Test fun testTake() {
listOf(1, 2, 3)
.toObservable()
.take(2)
.subscribe(received())
verify(a, times(1)).received(1)
verify(a, times(1)).received(2)
verify(a, times(0)).received(3)
}
@Test fun testTakeLast() {
TestFactory().observable
.takeLast(1)
.subscribe(received())
verify(a, times(1)).received("hello_1")
}
@Test fun testTakeWhile() {
listOf(1, 2, 3)
.toObservable()
.takeWhile { x -> x < 3 }
.subscribe(received())
verify(a, times(1)).received(1)
verify(a, times(1)).received(2)
verify(a, times(0)).received(3)
}
@Test fun testToSortedList() {
TestFactory().numbers.toSortedList().subscribe(received())
verify(a, times(1)).received(listOf(1, 2, 3, 4, 5))
}
@Test fun testForEach() {
Observable.create(asyncObservable).blockingForEach(received())
verify(a, times(1)).received(1)
verify(a, times(1)).received(2)
verify(a, times(1)).received(3)
}
@Test(expected = RuntimeException::class) fun testForEachWithError() {
Observable.create(asyncObservable).blockingForEach { throw RuntimeException("err") }
fail("we expect an exception to be thrown")
}
@Test fun testLastOrDefault() {
assertEquals("two", listOf("one", "two").toObservable().blockingLast("default"))
assertEquals("default", listOf("one", "two").toObservable().filter { it.length > 3 }.blockingLast("default"))
}
@Test fun testDefer() {
Observable.defer { listOf(1, 2).toObservable() }.subscribe(received())
verify(a, times(1)).received(1)
verify(a, times(1)).received(2)
}
@Test fun testAll() {
listOf(1, 2, 3).toObservable().all { x -> x > 0 }.subscribe(received())
verify(a, times(1)).received(true)
}
@Test fun testZip() {
val o1 = listOf(1, 2, 3).toObservable()
val o2 = listOf(4, 5, 6).toObservable()
val o3 = listOf(7, 8, 9).toObservable()
val values = Observable.zip(o1, o2, o3, Function3 <Int, Int, Int, List<Int>> { a, b, c -> listOf(a, b, c) }).toList().blockingGet()
assertEquals(listOf(1, 4, 7), values[0])
assertEquals(listOf(2, 5, 8), values[1])
assertEquals(listOf(3, 6, 9), values[2])
}
@Test fun testSwitchOnNext() {
val testScheduler = TestScheduler()
val worker = testScheduler.createWorker()
val observable = Observable.create<Observable<Long>> { s ->
fun at(delay: Long, func: () -> Unit) {
worker.schedule({
func()
}, delay, TimeUnit.MILLISECONDS)
}
val first = Observable.interval(5, TimeUnit.MILLISECONDS, testScheduler).take(3)
at(0, { s.onNext(first) })
val second = Observable.interval(5, TimeUnit.MILLISECONDS, testScheduler).take(3)
at(11, { s.onNext(second) })
at(40, { s.onComplete() })
}
observable.switchOnNext().subscribe(received())
val inOrder = inOrder(a)
testScheduler.advanceTimeTo(10, TimeUnit.MILLISECONDS)
inOrder.verify(a, times(1)).received(0L)
inOrder.verify(a, times(1)).received(1L)
testScheduler.advanceTimeTo(40, TimeUnit.MILLISECONDS)
inOrder.verify(a, times(1)).received(0L)
inOrder.verify(a, times(1)).received(1L)
inOrder.verify(a, times(1)).received(2L)
inOrder.verifyNoMoreInteractions()
}
val funOnSubscribe: (Int, ObservableEmitter<in String>) -> Unit = { counter, subscriber ->
subscriber.onNext("hello_$counter")
subscriber.onComplete()
}
val asyncObservable: (ObservableEmitter<in Int>) -> Unit = { subscriber ->
thread {
Thread.sleep(50)
subscriber.onNext(1)
subscriber.onNext(2)
subscriber.onNext(3)
subscriber.onComplete()
}
}
inner class TestFactory {
var counter = 1
val numbers: Observable<Int>
get() = listOf(1, 3, 2, 5, 4).toObservable()
val onSubscribe: (ObservableEmitter<in String>) -> Unit
get() = funOnSubscribe(p1 = counter++) // partial applied function
val observable: Observable<String>
get() = Observable.create(onSubscribe)
}
}
| apache-2.0 | 7e3918554ea7b6c7f0cf5b6803a7c3e0 | 32.589928 | 139 | 0.589741 | 4.007725 | false | true | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/ui/contract/AlbumContract.kt | 1 | 1421 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.ui.contract
import com.zwq65.unity.data.network.retrofit.response.enity.Image
import com.zwq65.unity.ui._base.BaseContract
import com.zwq65.unity.ui._base.RefreshMvpView
/**
* ================================================
* <p>
* Created by NIRVANA on 2017/09/26
* Contact with <[email protected]>
* ================================================
*/
interface AlbumContract {
interface View<T : Image> : RefreshMvpView<T>
interface Presenter<V : BaseContract.View> : BaseContract.Presenter<V> {
/**
* 初始化
*/
fun init()
/**
* 加载图片资源
*
* @param isRefresh 是否为刷新操作
*/
fun loadImages(isRefresh: Boolean?)
}
}
| apache-2.0 | df5c96a9229de2a04743c89f61d90842 | 28.553191 | 78 | 0.611231 | 4.121662 | false | false | false | false |
Waboodoo/HTTP-Shortcuts | HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/activities/editor/authentication/AuthenticationActivity.kt | 1 | 6527 | package ch.rmy.android.http_shortcuts.activities.editor.authentication
import android.content.ActivityNotFoundException
import android.os.Bundle
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import ch.rmy.android.framework.extensions.bindViewModel
import ch.rmy.android.framework.extensions.collectEventsWhileActive
import ch.rmy.android.framework.extensions.collectViewStateWhileActive
import ch.rmy.android.framework.extensions.doOnTextChanged
import ch.rmy.android.framework.extensions.initialize
import ch.rmy.android.framework.extensions.setSubtitle
import ch.rmy.android.framework.extensions.showToast
import ch.rmy.android.framework.ui.BaseIntentBuilder
import ch.rmy.android.framework.utils.FilePickerUtil
import ch.rmy.android.framework.viewmodel.ViewModelEvent
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.activities.BaseActivity
import ch.rmy.android.http_shortcuts.dagger.ApplicationComponent
import ch.rmy.android.http_shortcuts.data.enums.ClientCertParams
import ch.rmy.android.http_shortcuts.data.enums.ShortcutAuthenticationType
import ch.rmy.android.http_shortcuts.databinding.ActivityAuthenticationBinding
import ch.rmy.android.http_shortcuts.utils.ClientCertUtil
import kotlinx.coroutines.launch
class AuthenticationActivity : BaseActivity() {
private val openFilePickerForCertificate = registerForActivityResult(FilePickerUtil.PickFile) { fileUri ->
fileUri?.let(viewModel::onCertificateFileSelected)
}
private val viewModel: AuthenticationViewModel by bindViewModel()
private lateinit var binding: ActivityAuthenticationBinding
override fun inject(applicationComponent: ApplicationComponent) {
applicationComponent.inject(this)
}
override fun onCreated(savedState: Bundle?) {
viewModel.initialize()
initViews()
initUserInputBindings()
initViewModelBindings()
}
private fun initViews() {
binding = applyBinding(ActivityAuthenticationBinding.inflate(layoutInflater))
setTitle(R.string.section_authentication)
binding.inputAuthenticationType.setItemsFromPairs(
AUTHENTICATION_METHODS.map {
it.first.type to getString(it.second)
}
)
}
private fun initUserInputBindings() {
binding.variableButtonUsername.setOnClickListener {
viewModel.onUsernameVariableButtonClicked()
}
binding.variableButtonPassword.setOnClickListener {
viewModel.onPasswordVariableButtonClicked()
}
binding.variableButtonToken.setOnClickListener {
viewModel.onTokenVariableButtonClicked()
}
lifecycleScope.launch {
binding.inputAuthenticationType.selectionChanges.collect {
viewModel.onAuthenticationTypeChanged(ShortcutAuthenticationType.parse(it))
}
}
binding.inputUsername.doOnTextChanged {
viewModel.onUsernameChanged(binding.inputUsername.rawString)
}
binding.inputPassword.doOnTextChanged {
viewModel.onPasswordChanged(binding.inputPassword.rawString)
}
binding.inputToken.doOnTextChanged {
viewModel.onTokenChanged(binding.inputToken.rawString)
}
binding.buttonClientCert.setOnClickListener {
viewModel.onClientCertButtonClicked()
}
}
private fun initViewModelBindings() {
collectViewStateWhileActive(viewModel) { viewState ->
binding.containerUsername.isVisible = viewState.isUsernameAndPasswordVisible
binding.containerPassword.isVisible = viewState.isUsernameAndPasswordVisible
binding.containerToken.isVisible = viewState.isTokenVisible
binding.inputAuthenticationType.selectedItem = viewState.authenticationType.type
binding.inputUsername.rawString = viewState.username
binding.inputPassword.rawString = viewState.password
binding.inputToken.rawString = viewState.token
binding.buttonClientCert.isEnabled = viewState.isClientCertButtonEnabled
binding.buttonClientCert.setSubtitle(viewState.clientCertSubtitle)
binding.layoutContainer.isVisible = true
setDialogState(viewState.dialogState, viewModel)
}
collectEventsWhileActive(viewModel, ::handleEvent)
}
override fun handleEvent(event: ViewModelEvent) {
when (event) {
is AuthenticationEvent.PromptForClientCertAlias -> {
promptForClientCertAlias()
}
is AuthenticationEvent.OpenCertificateFilePicker -> {
openCertificateFilePicker()
}
is AuthenticationEvent.InsertVariablePlaceholderForUsername -> {
binding.inputUsername.insertVariablePlaceholder(event.variablePlaceholder)
}
is AuthenticationEvent.InsertVariablePlaceholderForPassword -> {
binding.inputPassword.insertVariablePlaceholder(event.variablePlaceholder)
}
is AuthenticationEvent.InsertVariablePlaceholderForToken -> {
binding.inputToken.insertVariablePlaceholder(event.variablePlaceholder)
}
else -> super.handleEvent(event)
}
}
private fun promptForClientCertAlias() {
try {
ClientCertUtil.promptForAlias(this) { alias ->
viewModel.onClientCertParamsChanged(
ClientCertParams.Alias(alias)
)
}
} catch (e: ActivityNotFoundException) {
showToast(R.string.error_not_supported)
}
}
private fun openCertificateFilePicker() {
try {
openFilePickerForCertificate.launch("application/x-pkcs12")
} catch (e: ActivityNotFoundException) {
showToast(R.string.error_not_supported)
}
}
override fun onBackPressed() {
viewModel.onBackPressed()
}
class IntentBuilder : BaseIntentBuilder(AuthenticationActivity::class)
companion object {
private val AUTHENTICATION_METHODS = listOf(
ShortcutAuthenticationType.NONE to R.string.authentication_none,
ShortcutAuthenticationType.BASIC to R.string.authentication_basic,
ShortcutAuthenticationType.DIGEST to R.string.authentication_digest,
ShortcutAuthenticationType.BEARER to R.string.authentication_bearer,
)
}
}
| mit | 4a10dc0952b8535aa34ad37daa17eef1 | 38.79878 | 110 | 0.712119 | 5.631579 | false | false | false | false |
holgerbrandl/kscript-support-api | src/test/kotlin/kscript/test/SupportApiTest.kt | 1 | 1761 | package kscript.test
import io.kotlintest.matchers.*
import kscript.text.resolveArgFile
import kscript.text.select
import kscript.text.split
import kscript.text.with
import org.junit.Test
/**
* @author Holger Brandl
*/
fun someFlights() = resolveArgFile(arrayOf("src/test/resources/some_flights.tsv"))
fun flightsZipped() = resolveArgFile(arrayOf("src/test/resources/flights.tsv.gz"))
fun flights() = resolveArgFile(arrayOf("src/test/resources/flights.txt"))
class SupportApiTest {
init {
kscript.isTestMode = true
}
@Test
fun `extract field with column filter`() {
someFlights().split().
filter { it[12] == "N14228" }.
map { it[13] }.
toList().
apply {
size shouldEqual 1
first() shouldEqual "EWR"
}
}
@Test
fun `allow to select column`() {
someFlights().split()
.select(with(3).and(11..13).and(1))
.first().data shouldBe listOf("day", "flight", "tailnum", "origin", "year")
}
@Test
fun `is should perform a negative selection`() {
someFlights().split()
.select(1, 2, 3)
.select(-2)
.first().data shouldBe listOf("year", "day")
}
@Test
fun `rejeced mixed select`() {
shouldThrow<IllegalArgumentException> {
someFlights().split().select(1, -2)
}.message shouldBe "[ERROR] Can not mix positive and negative selections"
}
@Test
fun `compressed lines should be unzipped on the fly`() {
resolveArgFile(arrayOf("src/test/resources/flights.tsv.gz")).
drop(1).first() should startWith("2013")
}
} | mit | 1a86e9322d4958ae1fb7dfc4907643d2 | 23.816901 | 91 | 0.57297 | 4.066975 | false | true | false | false |
google/intellij-gn-plugin | src/main/java/com/google/idea/gn/GnCommenter.kt | 1 | 552 | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn
import com.intellij.lang.Commenter
class GnCommenter : Commenter {
override fun getCommentedBlockCommentPrefix(): String? = null
override fun getCommentedBlockCommentSuffix(): String? = null
override fun getBlockCommentPrefix(): String? = null
override fun getBlockCommentSuffix(): String? = null
override fun getLineCommentPrefix(): String? = "#"
}
| bsd-3-clause | 4aa0ab378665ecb07435bfbbcc8602cf | 28.052632 | 63 | 0.755435 | 4.638655 | false | false | false | false |
rfcx/rfcx-guardian-android | role-guardian/src/main/java/org/rfcx/guardian/guardian/api/http/ApiRest.kt | 1 | 602 | package org.rfcx.guardian.guardian.api.http
import android.content.Context
import org.rfcx.guardian.guardian.RfcxGuardian
class ApiRest {
companion object {
fun baseUrl(context: Context): String {
val prefs = (context.getApplicationContext() as RfcxGuardian).rfcxPrefs
val protocol = prefs.getPrefAsString("api_rest_protocol")
val host = prefs.getPrefAsString("api_rest_host")
if (protocol != null && host != null) {
return "${protocol}://${host}/"
}
return "https://api.rfcx.org/"
}
}
}
| apache-2.0 | b1a3c8d8bb95ac36167c0f37f2f1b4c4 | 32.444444 | 83 | 0.607973 | 4.3 | false | false | false | false |
universum-studios/gradle_github_plugin | plugin/src/labels/kotlin/universum/studios/gradle/github/label/manage/LabelManager.kt | 1 | 4992 | /*
* *************************************************************************************************
* Copyright 2017 Universum Studios
* *************************************************************************************************
* 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 universum.studios.gradle.github.label.manage
import org.gradle.api.Project
import universum.studios.gradle.github.label.data.model.Label
import universum.studios.gradle.github.label.data.model.LabelModelMappers
import universum.studios.gradle.github.label.service.api.LabelsApi
/**
* Manager which may be used for issue labels management (uploading, editing, deleting).
*
* @author Martin Albedinsky
* @since 1.0
*
* @property project The project to which is the parent plugin applied.
* @property api The api that should be used by the manager to perform calls to the GitHub Labels API.
* @constructor Creates a new instance of LabelManager with the specified *api*.
*/
internal class LabelManager(val project: Project, val api: LabelsApi) {
/*
* Companion ===================================================================================
*/
/**
*/
companion object {
/**
* Constant used to identify no result.
*/
const val NO_RESULT = -1
}
/*
* Interface ===================================================================================
*/
/*
* Members =====================================================================================
*/
/*
* Constructors ================================================================================
*/
/**
* Creates all the given *labels* on the GitHub server.
*
* @param labels List of labels to be created.
* @return Count of the successfully created labels.
*/
fun createLabels(labels: List<Label>): Int {
var result = 0
if (labels.isNotEmpty()) labels.forEach {
if (createLabel(it)) result++
}
return result
}
/**
* Creates the specified *label* on the GitHub server.
*
* @param label The desired label to be created.
* @return *True* if the requested label has been successfully created, *false* otherwise.
*/
fun createLabel(label: Label): Boolean {
val repository = api.getRepository()
project.logger.info("Creating label '${label.name}' for '${repository.path()}' ...")
val response = api.createLabel(LabelModelMappers.LABEL_TO_REMOTE_LABEL.map(label)).execute()
when (response.isSuccessful) {
true -> project.logger.quiet("Label '${label.name}' successfully created for '${repository.path()}'.")
false -> project.logger.error("Failed to create label '${label.name}' for '${repository.path()}'!")
}
return response.isSuccessful
}
/**
* Deletes all issue labels defined on the GitHub server.
*
* @return The count of successfully deleted labels or [NO_RESULT] if there were no labels to
* be deleted.
*/
fun deleteAllLabels(): Int {
var result = NO_RESULT
val response = api.getLabels().execute()
if (response.isSuccessful) {
val labels = response.body()
if (labels != null && labels.isNotEmpty()) {
result = 0
val repository = api.getRepository()
project.logger.info("Deleting all issue labels for '${repository.path()}' ...")
labels.forEach {
val deleteResponse = api.deleteLabel(it).execute()
when (deleteResponse.isSuccessful) {
true -> {
result++
project.logger.debug("Label '${it.name}' successfully deleted for '$${repository.path()}'!")
}
false -> project.logger.error("Failed to delete label '${it.name}' for '${repository.path()}'!")
}
}
}
}
return result
}
/*
* Inner classes ===============================================================================
*/
} | apache-2.0 | 625e2be7491803f7b8aa0c56b67c4003 | 38.007813 | 120 | 0.500401 | 5.455738 | false | false | false | false |
manami-project/manami | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/migration/MigrationAlerts.kt | 1 | 2534 | package io.github.manamiproject.manami.gui.migration
import io.github.manamiproject.manami.gui.components.Alerts.AlertOption
import javafx.scene.control.Alert
import javafx.scene.control.ButtonBar
import javafx.scene.control.ButtonType
object MigrationAlerts {
fun migrateEntries(
numberOfEntriesAnimeList: Int,
numberOfEntriesWatchList: Int,
numberOfEntriesIgnoreList: Int,
): AlertOption {
val totalEntries = numberOfEntriesAnimeList + numberOfEntriesWatchList + numberOfEntriesIgnoreList
val alertResult = Alert(Alert.AlertType.CONFIRMATION).apply {
title = "Migrate entries?"
headerText = "Do you really want to migrate $totalEntries entries?"
contentText = "Anime List: $numberOfEntriesAnimeList\nWatch List: $numberOfEntriesWatchList\nIgnore List: $numberOfEntriesIgnoreList"
buttonTypes.clear()
buttonTypes.addAll(
ButtonType("Yes", ButtonBar.ButtonData.YES),
ButtonType("No", ButtonBar.ButtonData.NO),
)
}.showAndWait().get()
return when(alertResult.buttonData.typeCode) {
ButtonBar.ButtonData.YES.typeCode -> AlertOption.YES
ButtonBar.ButtonData.NO.typeCode -> AlertOption.NO
else -> throw IllegalStateException("Unknown ButtonType")
}
}
fun removeUnmappedEntries(
numberOfEntriesAnimeList: Int,
numberOfEntriesWatchList: Int,
numberOfEntriesIgnoreList: Int,
): AlertOption {
val totalEntries = numberOfEntriesAnimeList + numberOfEntriesWatchList + numberOfEntriesIgnoreList
val alertResult = Alert(Alert.AlertType.CONFIRMATION).apply {
title = "Remove unmapped entries?"
headerText = "Do you want to remove $totalEntries entries which couldn't be mapped to the new meta data provider?"
contentText = "Anime List: $numberOfEntriesAnimeList\nWatch List: $numberOfEntriesWatchList\nIgnore List: $numberOfEntriesIgnoreList"
buttonTypes.clear()
buttonTypes.addAll(
ButtonType("Yes", ButtonBar.ButtonData.YES),
ButtonType("No", ButtonBar.ButtonData.NO),
)
}.showAndWait().get()
return when(alertResult.buttonData.typeCode) {
ButtonBar.ButtonData.YES.typeCode -> AlertOption.YES
ButtonBar.ButtonData.NO.typeCode -> AlertOption.NO
else -> throw IllegalStateException("Unknown ButtonType")
}
}
} | agpl-3.0 | c9733e72a655c1f1a539b23b88a1ed66 | 43.473684 | 145 | 0.678374 | 5.461207 | false | false | false | false |
luxons/seven-wonders | sw-engine/src/main/kotlin/org/luxons/sevenwonders/engine/resources/Resources.kt | 1 | 3544 | package org.luxons.sevenwonders.engine.resources
import org.luxons.sevenwonders.model.resources.ResourceType
fun emptyResources(): Resources = MutableResources()
fun resourcesOf(singleResource: ResourceType): Resources = mapOf(singleResource to 1).toMutableResources()
fun resourcesOf(vararg resources: ResourceType): Resources = mutableResourcesOf(*resources)
fun resourcesOf(vararg resources: Pair<ResourceType, Int>): Resources = mutableResourcesOf(*resources)
fun Iterable<Pair<ResourceType, Int>>.toResources(): Resources = toMutableResources()
/**
* Creates [Resources] from a copy of the given map. Future modifications to the input map won't affect the return
* resources.
*/
fun Map<ResourceType, Int>.toResources(): Resources = toMutableResources()
fun Iterable<Resources>.merge(): Resources = fold(MutableResources()) { r1, r2 -> r1.add(r2); r1 }
internal fun mutableResourcesOf() = MutableResources()
internal fun mutableResourcesOf(vararg resources: ResourceType): MutableResources =
resources.map { it to 1 }.toMutableResources()
internal fun mutableResourcesOf(vararg resources: Pair<ResourceType, Int>) = resources.asIterable().toMutableResources()
internal fun Iterable<Pair<ResourceType, Int>>.toMutableResources(): MutableResources =
fold(MutableResources()) { mr, (type, qty) -> mr.add(type, qty); mr }
internal fun Map<ResourceType, Int>.toMutableResources(): MutableResources = MutableResources(toMutableMap())
internal fun Resources.toMutableResources(): MutableResources = quantities.toMutableResources()
interface Resources {
val quantities: Map<ResourceType, Int>
val size: Int
get() = quantities.values.sum()
fun isEmpty(): Boolean = size == 0
operator fun get(key: ResourceType): Int = quantities.getOrDefault(key, 0)
fun containsAll(resources: Resources): Boolean = resources.quantities.all { it.value <= this[it.key] }
operator fun plus(resources: Resources): Resources =
ResourceType.values().map { it to this[it] + resources[it] }.toResources()
/**
* Returns new resources containing these resources minus the given [resources]. If the given resources contain
* more than these resources contain for a resource type, then the resulting resources will contain none of that
* type.
*/
operator fun minus(resources: Resources): Resources =
quantities.mapValues { (type, q) -> (q - resources[type]).coerceAtLeast(0) }.toResources()
fun toList(): List<ResourceType> = quantities.flatMap { (type, quantity) -> List(quantity) { type } }
fun copy(): Resources = quantities.toResources()
}
class MutableResources(
override val quantities: MutableMap<ResourceType, Int> = mutableMapOf(),
) : Resources {
fun add(type: ResourceType, quantity: Int) {
quantities.merge(type, quantity) { x, y -> x + y }
}
fun add(resources: Resources) = resources.quantities.forEach { (type, quantity) -> add(type, quantity) }
fun remove(type: ResourceType, quantity: Int) {
if (this[type] < quantity) {
throw NoSuchElementException("Can't remove $quantity resources of type $type")
}
quantities.computeIfPresent(type) { _, oldQty -> oldQty - quantity }
}
override fun equals(other: Any?): Boolean =
other is Resources && quantities.filterValues { it > 0 } == other.quantities.filterValues { it > 0 }
override fun hashCode(): Int = quantities.filterValues { it > 0 }.hashCode()
override fun toString(): String = "$quantities"
}
| mit | 4daeaf8827347d0f09efdbab8c11458b | 38.820225 | 120 | 0.717269 | 4.572903 | false | false | false | false |
proxer/ProxerAndroid | src/main/kotlin/me/proxer/app/anime/stream/StreamPlayerManager.kt | 1 | 12450 | package me.proxer.app.anime.stream
import android.app.Activity
import android.net.Uri
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.ExoPlaybackException
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.audio.AudioAttributes
import com.google.android.exoplayer2.drm.DrmSessionManager
import com.google.android.exoplayer2.ext.cast.CastPlayer
import com.google.android.exoplayer2.ext.cast.SessionAvailabilityListener
import com.google.android.exoplayer2.ext.ima.ImaAdsLoader
import com.google.android.exoplayer2.ext.okhttp.OkHttpDataSourceFactory
import com.google.android.exoplayer2.source.MediaSource
import com.google.android.exoplayer2.source.MediaSourceFactory
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.source.ads.AdsMediaSource
import com.google.android.exoplayer2.source.dash.DashMediaSource
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource
import com.google.android.exoplayer2.source.hls.HlsMediaSource
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultBandwidthMeter
import com.google.android.exoplayer2.util.MimeTypes
import com.google.android.exoplayer2.util.Util
import com.google.android.gms.cast.MediaInfo
import com.google.android.gms.cast.MediaMetadata
import com.google.android.gms.cast.MediaQueueItem
import com.google.android.gms.common.images.WebImage
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.PublishSubject
import me.proxer.app.MainApplication.Companion.USER_AGENT
import me.proxer.app.util.DefaultActivityLifecycleCallbacks
import me.proxer.app.util.ErrorUtils
import okhttp3.OkHttpClient
import java.lang.ref.WeakReference
import kotlin.properties.Delegates
/**
* @author Ruben Gees
*/
class StreamPlayerManager(context: StreamActivity, rawClient: OkHttpClient, adTag: Uri?) {
private companion object {
private const val WAS_PLAYING_EXTRA = "was_playing"
private const val LAST_POSITION_EXTRA = "last_position"
}
private val weakContext = WeakReference(context)
private val castSessionAvailabilityListener = object : SessionAvailabilityListener {
override fun onCastSessionAvailable() {
if (castPlayer != null) {
castPlayer.loadItem(castMediaSource, localPlayer.currentPosition)
currentPlayer = castPlayer
}
}
override fun onCastSessionUnavailable() {
currentPlayer = localPlayer
if (!isResumed) {
wasPlaying = false
}
}
}
private val eventListener = object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
when (playbackState) {
Player.STATE_BUFFERING, Player.STATE_IDLE -> playerStateSubject.onNext(PlayerState.LOADING)
Player.STATE_ENDED -> playerStateSubject.onNext(PlayerState.PAUSING)
Player.STATE_READY -> playerStateSubject.onNext(
when (playWhenReady) {
true -> PlayerState.PLAYING
false -> PlayerState.PAUSING
}
)
}
}
override fun onPlayerError(error: ExoPlaybackException) {
lastPosition = currentPlayer.currentPosition
errorSubject.onNext(ErrorUtils.handle(error))
}
}
private val lifecycleCallbacks = object : DefaultActivityLifecycleCallbacks {
override fun onActivityResumed(activity: Activity) {
if (activity == weakContext.get()) {
isResumed = true
}
}
override fun onActivityPaused(activity: Activity) {
if (activity == weakContext.get()) {
isFirstStart = false
isResumed = false
}
}
override fun onActivityDestroyed(activity: Activity) {
if (activity == weakContext.get()) {
activity.application.unregisterActivityLifecycleCallbacks(this)
localPlayer.release()
castPlayer?.release()
localPlayer.removeListener(eventListener)
castPlayer?.removeListener(eventListener)
castPlayer?.setSessionAvailabilityListener(null)
adsLoader?.release()
adsLoader = null
}
}
}
private val client = buildClient(rawClient)
private val localPlayer = buildLocalPlayer(context)
private val castPlayer = buildCastPlayer(context)
private var adsLoader: ImaAdsLoader? = when {
adTag != null -> ImaAdsLoader(context, adTag).apply {
setPlayer(localPlayer)
}
else -> null
}
private var localMediaSource = buildLocalMediaSourceWithAds(client, uri)
private var castMediaSource = buildCastMediaSource(name, episode, coverUri, uri)
private val uri get() = requireNotNull(weakContext.get()?.uri)
private val name: String? get() = weakContext.get()?.name
private val episode: Int? get() = weakContext.get()?.episode
private val coverUri: Uri? get() = weakContext.get()?.coverUri
private val referer: String? get() = weakContext.get()?.referer
private var lastPosition: Long
get() = weakContext.get()?.intent?.getLongExtra(LAST_POSITION_EXTRA, -1) ?: -1
set(value) {
weakContext.get()?.intent?.putExtra(LAST_POSITION_EXTRA, value)
}
private var wasPlaying: Boolean
get() = weakContext.get()?.intent?.getBooleanExtra(WAS_PLAYING_EXTRA, false) ?: false
set(value) {
weakContext.get()?.intent?.putExtra(WAS_PLAYING_EXTRA, value)
}
private var isResumed = false
private var isFirstStart = true
var currentPlayer by Delegates.observable<Player>(localPlayer) { _, old, new ->
old.playWhenReady = false
new.playWhenReady = isResumed
new.seekTo(old.currentPosition)
playerReadySubject.onNext(new)
}
private set
val isPlayingAd: Boolean
get() = localPlayer.isPlayingAd
val playerReadySubject = BehaviorSubject.createDefault<Player>(localPlayer)
val playerStateSubject = PublishSubject.create<PlayerState>()
val errorSubject = PublishSubject.create<ErrorUtils.ErrorAction>()
init {
localPlayer.addListener(eventListener)
castPlayer?.addListener(eventListener)
localPlayer.prepare(localMediaSource)
context.application.registerActivityLifecycleCallbacks(lifecycleCallbacks)
}
fun play(position: Long? = null) {
if (isFirstStart && position != null) {
lastPosition = position
}
if (currentPlayer.currentPosition <= 0 && lastPosition > 0) {
currentPlayer.seekTo(lastPosition)
}
if (isFirstStart || wasPlaying) {
currentPlayer.playWhenReady = true
}
}
fun pause() {
wasPlaying = currentPlayer.playWhenReady == true && currentPlayer.playbackState == Player.STATE_READY
lastPosition = currentPlayer.currentPosition
localPlayer.playWhenReady = false
}
fun toggle() {
currentPlayer.playWhenReady = currentPlayer.playWhenReady.not()
}
fun retry() {
if (currentPlayer == localPlayer) {
localPlayer.prepare(localMediaSource, false, false)
} else if (currentPlayer == castPlayer) {
castPlayer.loadItem(castMediaSource, lastPosition)
}
}
fun reset() {
currentPlayer.playWhenReady = false
wasPlaying = false
lastPosition = -1
localMediaSource = buildLocalMediaSourceWithAds(client, uri)
castMediaSource = buildCastMediaSource(name, episode, coverUri, uri)
retry()
currentPlayer.playWhenReady = true
}
private fun buildClient(rawClient: OkHttpClient): OkHttpClient {
return referer.let { referer ->
if (referer == null) {
rawClient
} else {
rawClient.newBuilder()
.addInterceptor {
val requestWithReferer = it.request().newBuilder()
.header("Referer", referer)
.build()
it.proceed(requestWithReferer)
}
.build()
}
}
}
private fun buildLocalMediaSourceWithAds(client: OkHttpClient, uri: Uri): MediaSource {
val context = requireNotNull(weakContext.get())
val bandwidthMeter = DefaultBandwidthMeter.Builder(context).build()
val okHttpDataSourceFactory = OkHttpDataSourceFactory(client, USER_AGENT, bandwidthMeter)
val imaFactory = ImaMediaSourceFactory(okHttpDataSourceFactory, this::buildLocalMediaSource)
val localMediaSource = buildLocalMediaSource(okHttpDataSourceFactory, uri)
val safeAdsLoader = adsLoader
return if (safeAdsLoader != null) {
AdsMediaSource(localMediaSource, imaFactory, safeAdsLoader, context.playerView)
} else {
localMediaSource
}
}
private fun buildLocalMediaSource(dataSourceFactory: DataSource.Factory, uri: Uri): MediaSource {
return when (val streamType = Util.inferContentType(uri)) {
C.TYPE_SS ->
SsMediaSource.Factory(DefaultSsChunkSource.Factory(dataSourceFactory), dataSourceFactory)
.createMediaSource(uri)
C.TYPE_DASH ->
DashMediaSource.Factory(DefaultDashChunkSource.Factory(dataSourceFactory), dataSourceFactory)
.createMediaSource(uri)
C.TYPE_HLS -> HlsMediaSource.Factory(dataSourceFactory).createMediaSource(uri)
C.TYPE_OTHER -> ProgressiveMediaSource.Factory(dataSourceFactory).createMediaSource(uri)
else -> error("Unknown streamType: $streamType")
}
}
private fun buildCastMediaSource(name: String?, episode: Int?, coverUri: Uri?, uri: Uri): MediaQueueItem {
val mediaMetadata = MediaMetadata(MediaMetadata.MEDIA_TYPE_TV_SHOW).apply {
if (name != null) {
putString(MediaMetadata.KEY_TITLE, name)
}
if (episode != null) {
putInt(MediaMetadata.KEY_EPISODE_NUMBER, episode)
}
if (coverUri != null) {
addImage(WebImage(coverUri))
}
}
val mediaInfo = MediaInfo.Builder(uri.toString())
.setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
.setContentType(MimeTypes.VIDEO_MP4)
.setMetadata(mediaMetadata)
.build()
return MediaQueueItem.Builder(mediaInfo).build()
}
private fun buildLocalPlayer(context: StreamActivity): SimpleExoPlayer {
return SimpleExoPlayer.Builder(context).build().apply {
val audioAttributes = AudioAttributes.Builder()
.setContentType(C.CONTENT_TYPE_MOVIE)
.setUsage(C.USAGE_MEDIA)
.build()
setWakeMode(C.WAKE_MODE_NETWORK)
setHandleAudioBecomingNoisy(true)
setAudioAttributes(audioAttributes, true)
}
}
private fun buildCastPlayer(context: StreamActivity): CastPlayer? {
return context.getSafeCastContext()
?.let { CastPlayer(it) }
?.apply { setSessionAvailabilityListener(castSessionAvailabilityListener) }
}
enum class PlayerState {
PLAYING, PAUSING, LOADING
}
private class ImaMediaSourceFactory(
private val okHttpDataSourceFactory: OkHttpDataSourceFactory,
private val mediaSourceFunction: (DataSource.Factory, Uri) -> MediaSource
) : MediaSourceFactory {
override fun getSupportedTypes() = intArrayOf(C.TYPE_DASH, C.TYPE_HLS, C.TYPE_OTHER)
override fun createMediaSource(uri: Uri) = mediaSourceFunction(okHttpDataSourceFactory, uri)
override fun setDrmSessionManager(drmSessionManager: DrmSessionManager<*>?) = this
}
}
| gpl-3.0 | 27c7642adfcc636998ae6b0d9f74dac7 | 35.403509 | 110 | 0.663454 | 5.131904 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/views/UserBannedView.kt | 1 | 1765 | package net.perfectdreams.loritta.morenitta.website.views
import net.perfectdreams.loritta.morenitta.dao.Profile
import net.perfectdreams.loritta.common.locale.BaseLocale
import kotlinx.html.DIV
import kotlinx.html.code
import kotlinx.html.div
import kotlinx.html.h1
import kotlinx.html.img
import kotlinx.html.p
import kotlinx.html.style
import net.perfectdreams.loritta.morenitta.LorittaBot
import org.jetbrains.exposed.sql.ResultRow
class UserBannedView(loritta: LorittaBot, locale: BaseLocale, path: String, val profile: Profile, val bannedState: ResultRow) : NavbarView(loritta, locale, path) {
override fun getTitle() = "¯\\_(ツ)_/¯"
override fun DIV.generateContent() {
div(classes = "odd-wrapper") {
style = "text-align: center;"
div(classes = "media single-column") {
div(classes = "media-body") {
div {
style = "text-align: center;"
img(src = "https://loritta.website/assets/img/fanarts/l6.png") {
width = "175"
}
h1 {
+ locale["website.userBanned.title"]
}
for (str in locale.getList("website.userBanned.description")) {
p {
+ str
}
}
p {
code {
+ (bannedState[net.perfectdreams.loritta.morenitta.tables.BannedUsers.reason] ?: "¯\\_(ツ)_/¯")
}
}
}
}
}
}
}
} | agpl-3.0 | 4b40fb8f64ab93ab95d7b35778e29c2c | 34.16 | 163 | 0.495731 | 4.949296 | false | false | false | false |
JustinMullin/drifter-kotlin | src/main/kotlin/xyz/jmullin/drifter/geometry/VectorHex.kt | 1 | 2237 | package xyz.jmullin.drifter.geometry
import com.badlogic.gdx.math.Vector2
import xyz.jmullin.drifter.extensions.*
data class VectorHex(val q: Float, val r: Float, val s: Float) {
init {
assert(q + r + s == 0f, { "Hex coordinates don't meet q+r+s = 0 equality invariant." })
}
constructor(q: Float, s: Float): this(q, -q-s, s)
constructor(q: Int, s: Int): this(q*1f, s*1f)
constructor(q: Int, r: Int, s: Int): this(q*1f, r*1f, s*1f)
operator fun plus(o: VectorHex) = VectorHex(q + o.q, r + o.r, s + o.s)
operator fun minus(o: VectorHex) = VectorHex(q - o.q, r - o.r, s - o.s)
operator fun times(o: VectorHex) = VectorHex(q * o.q, r * o.r, s * o.s)
operator fun div(o: VectorHex) = VectorHex(q / o.q, r / o.r, s / o.s)
fun inverse() = VectorHex(-q, -r, -s)
fun fixZeroes() = VectorHex(if(q == 0.0f) 0.0f else q, if(r == 0.0f) 0.0f else r, if(s == 0.0f) 0.0f else s)
fun manhattanTo(o: VectorHex) = ((q - o.q).abs() + (r - o.r).abs() + (s - o.s).abs()) / 2f
fun neighbors() = directions.map { plus(it) }
fun toV() = V2(3f/2f * q, 3f.sqrt() * (r + q/2f))
fun hexCorner(cornerIndex: Int): Vector2 {
val angle = (Pi / 3f) * cornerIndex
return V2(angle.cos(), angle.sin())
}
fun cornerOffsets(size: Vector2) = (0..5).map { size * hexCorner(it) }
fun snap(): VectorHex {
val rQ = q.round()
val rR = r.round()
val rS = s.round()
return if ((rQ - q).abs() > (rR - r).abs() && (rQ - q).abs() > (rS - s).abs()) {
Vh(-rR-rS, rR, rS)
} else if ((rR - r).abs() > (rS - s).abs()) {
Vh(rQ, -rQ-rS, rS)
} else {
Vh(rQ, rR, -rQ-rR)
}
}
override fun equals(other: Any?): Boolean {
if(other !is VectorHex) return false
return q.fEq(other.q) && r.fEq(other.r) && s.fEq(other.s)
}
override fun hashCode(): Int {
return 23 + (q+0f).hashCode()*31 + (r+0f).hashCode()*31*31 + (s+0f).hashCode()*31*31*31
}
companion object {
val directions = listOf(
Vh(+1f, -1f, 0f), Vh(+1f, 0f, -1f), Vh(0f, +1f, -1f),
Vh(-1f, +1f, 0f), Vh(-1f, 0f, +1f), Vh(0f, -1f, +1f)
)
}
} | mit | 96f06b926cac8b9decf488285fe81ac5 | 33.96875 | 112 | 0.520787 | 2.659929 | false | false | false | false |
signed/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerPathToFileManager.kt | 1 | 7256 | package org.jetbrains.builtInWebServer
import com.google.common.base.Function
import com.google.common.cache.CacheBuilder
import com.google.common.cache.CacheLoader
import com.intellij.ProjectTopics
import com.intellij.openapi.application.Application
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.project.rootManager
import com.intellij.util.SmartList
import com.intellij.util.containers.computeOrNull
import com.intellij.util.io.exists
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
private val cacheSize: Long = 4096 * 4
/**
* Implement [WebServerRootsProvider] to add your provider
*/
class WebServerPathToFileManager(application: Application, private val project: Project) {
val pathToInfoCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, PathInfo>()!!
// time to expire should be greater than pathToFileCache
private val virtualFileToPathInfo = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(11, TimeUnit.MINUTES).build<VirtualFile, PathInfo>()
internal val pathToExistShortTermCache = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(5, TimeUnit.SECONDS).build<String, Boolean>()!!
/**
* https://youtrack.jetbrains.com/issue/WEB-25900
*
* Compute suitable roots for oldest parent (web/foo/my/file.dart -> oldest is web and we compute all suitable roots for it in advance) to avoid linear search
* (i.e. to avoid two queries for root if files web/foo and web/bar requested if root doesn't have web dir)
*/
internal val parentToSuitableRoot = CacheBuilder.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, List<SuitableRoot>>(
CacheLoader.from(Function { path ->
val suitableRoots = SmartList<SuitableRoot>()
var moduleQualifier: String? = null
val modules = runReadAction { ModuleManager.getInstance(project).modules }
for (rootProvider in RootProvider.values()) {
for (module in modules) {
if (module.isDisposed) {
continue
}
for (root in rootProvider.getRoots(module.rootManager)) {
if (root.findChild(path!!) != null) {
if (moduleQualifier == null) {
moduleQualifier = getModuleNameQualifier(project, module)
}
suitableRoots.add(SuitableRoot(root, moduleQualifier))
}
}
}
}
suitableRoots
}))!!
init {
application.messageBus.connect(project).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
for (event in events) {
if (event is VFileContentChangeEvent) {
val file = event.file
for (rootsProvider in WebServerRootsProvider.EP_NAME.extensions) {
if (rootsProvider.isClearCacheOnFileContentChanged(file)) {
clearCache()
break
}
}
}
else {
clearCache()
break
}
}
}
})
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
clearCache()
}
})
}
companion object {
@JvmStatic fun getInstance(project: Project) = ServiceManager.getService(project, WebServerPathToFileManager::class.java)!!
}
private fun clearCache() {
pathToInfoCache.invalidateAll()
virtualFileToPathInfo.invalidateAll()
pathToExistShortTermCache.invalidateAll()
parentToSuitableRoot.invalidateAll()
}
@JvmOverloads fun findVirtualFile(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): VirtualFile? {
return getPathInfo(path, cacheResult, pathQuery)?.getOrResolveVirtualFile()
}
@JvmOverloads fun getPathInfo(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): PathInfo? {
var pathInfo = pathToInfoCache.getIfPresent(path)
if (pathInfo == null || !pathInfo.isValid) {
if (pathToExistShortTermCache.getIfPresent(path) == false) {
return null
}
pathInfo = doFindByRelativePath(path, pathQuery)
if (cacheResult) {
if (pathInfo != null && pathInfo.isValid) {
pathToInfoCache.put(path, pathInfo)
}
else {
pathToExistShortTermCache.put(path, false)
}
}
}
return pathInfo
}
fun getPath(file: VirtualFile) = getPathInfo(file)?.path
fun getPathInfo(child: VirtualFile): PathInfo? {
var result = virtualFileToPathInfo.getIfPresent(child)
if (result == null) {
result = WebServerRootsProvider.EP_NAME.extensions.computeOrNull { it.getPathInfo(child, project) }
if (result != null) {
virtualFileToPathInfo.put(child, result)
}
}
return result
}
internal fun doFindByRelativePath(path: String, pathQuery: PathQuery): PathInfo? {
val result = WebServerRootsProvider.EP_NAME.extensions.computeOrNull { it.resolve(path, project, pathQuery) } ?: return null
result.file?.let {
virtualFileToPathInfo.put(it, result)
}
return result
}
fun getResolver(path: String) = if (path.isEmpty()) EMPTY_PATH_RESOLVER else RELATIVE_PATH_RESOLVER
}
interface FileResolver {
fun resolve(path: String, root: VirtualFile, moduleName: String? = null, isLibrary: Boolean = false, pathQuery: PathQuery): PathInfo?
}
private val RELATIVE_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
// WEB-17691 built-in server doesn't serve files it doesn't have in the project tree
// temp:// reports isInLocalFileSystem == true, but it is not true
if (pathQuery.useVfs || root.fileSystem != LocalFileSystem.getInstance() || path == ".htaccess" || path == "config.json") {
return root.findFileByRelativePath(path)?.let { PathInfo(null, it, root, moduleName, isLibrary) }
}
val file = Paths.get(root.path, path)
return if (file.exists()) {
PathInfo(file, null, root, moduleName, isLibrary)
}
else {
null
}
}
}
private val EMPTY_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
val file = findIndexFile(root) ?: return null
return PathInfo(null, file, root, moduleName, isLibrary)
}
}
internal val defaultPathQuery = PathQuery() | apache-2.0 | 1a372ff58b6dc2c64e832aa9a0f1ff2f | 38.440217 | 161 | 0.70769 | 4.751801 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/website/routes/user/dashboard/ShipEffectsRoute.kt | 1 | 2482 | package net.perfectdreams.loritta.morenitta.website.routes.user.dashboard
import com.github.salomonbrys.kotson.jsonObject
import net.perfectdreams.loritta.morenitta.dao.ShipEffect
import net.perfectdreams.loritta.morenitta.tables.ShipEffects
import net.perfectdreams.loritta.morenitta.website.utils.WebsiteUtils
import net.perfectdreams.loritta.morenitta.utils.gson
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.morenitta.website.evaluate
import io.ktor.server.application.ApplicationCall
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.website.routes.RequiresDiscordLoginLocalizedRoute
import net.perfectdreams.loritta.morenitta.website.session.LorittaJsonWebSession
import net.perfectdreams.loritta.morenitta.website.utils.extensions.legacyVariables
import net.perfectdreams.loritta.morenitta.website.utils.extensions.respondHtml
import net.perfectdreams.temmiediscordauth.TemmieDiscordAuth
import org.jetbrains.exposed.sql.and
class ShipEffectsRoute(loritta: LorittaBot) : RequiresDiscordLoginLocalizedRoute(loritta, "/user/@me/dashboard/ship-effects") {
override suspend fun onAuthenticatedRequest(call: ApplicationCall, locale: BaseLocale, discordAuth: TemmieDiscordAuth, userIdentification: LorittaJsonWebSession.UserIdentification) {
val variables = call.legacyVariables(loritta, locale)
val userId = userIdentification.id
val user = loritta.lorittaShards.retrieveUserById(userId)!!
val lorittaProfile = loritta.getOrCreateLorittaProfile(userId)
variables["profileUser"] = user
variables["lorittaProfile"] = lorittaProfile
variables["saveType"] = "ship_effects"
variables["profile_json"] = gson.toJson(
WebsiteUtils.getProfileAsJson(lorittaProfile)
)
val shipEffects = loritta.newSuspendedTransaction {
ShipEffect.find {
(ShipEffects.buyerId eq user.idLong) and
(ShipEffects.expiresAt greaterEq System.currentTimeMillis())
}.toMutableList()
}
variables["ship_effects_json"] =
gson.toJson(
shipEffects.map {
jsonObject(
"buyerId" to it.buyerId,
"user1Id" to it.user1Id,
"user2Id" to it.user2Id,
"editedShipValue" to it.editedShipValue,
"expiresAt" to it.expiresAt
)
}
)
variables["profile_json"] = gson.toJson(
WebsiteUtils.getProfileAsJson(lorittaProfile)
)
call.respondHtml(evaluate("profile_dashboard_ship_effects.html", variables))
}
} | agpl-3.0 | 24e634569ccfe7fb6001d4e06800b11b | 40.383333 | 183 | 0.794118 | 4.213922 | false | false | false | false |
HelloHuDi/usb-with-serial-port | usb-serial-port-measure/src/main/java/com/aio/usbserialport/device/SerialPortDevice.kt | 1 | 1218 | package com.aio.usbserialport.device
import android.content.Context
import com.aio.usbserialport.parser.DataPackageEntity
import com.aio.usbserialport.parser.Parser
import com.hd.serialport.listener.SerialPortMeasureListener
import com.hd.serialport.method.DeviceMeasureController
import com.hd.serialport.param.SerialPortMeasureParameter
import java.io.OutputStream
import java.util.*
/**
* Created by hd on 2017/8/28 .
*
*/
open class SerialPortDevice(context: Context, aioDeviceType: Int, private val parameter: SerialPortMeasureParameter, parser: Parser)
: Device(context, aioDeviceType, parser), SerialPortMeasureListener {
override fun write(tag: Any?, outputStream: OutputStream) {
outputStreamList.add(outputStream)
}
override fun measure() {
DeviceMeasureController.measure(parameter = parameter, listener = this)
}
override fun release() {
}
override fun measureError(tag: Any?, message: String) {
error(message)
}
override fun measuring(tag: Any?, path: String, data: ByteArray) {
dataQueue.put(DataPackageEntity(path = path, data = data))
addLogcat(path + "====" + Arrays.toString(data))
}
} | apache-2.0 | e5e2077409c0ebaf194d7b7538738922 | 30.25641 | 132 | 0.721675 | 4.185567 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/run/attach/UnityLocalAttachProcessPresentationGroup.kt | 1 | 1346 | package com.jetbrains.rider.plugins.unity.run.attach
import com.intellij.execution.process.ProcessInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.UserDataHolder
import com.intellij.xdebugger.attach.XAttachProcessPresentationGroup
import com.jetbrains.rider.plugins.unity.UnityBundle
import icons.UnityIcons
object UnityLocalAttachProcessPresentationGroup : XAttachProcessPresentationGroup {
override fun getOrder(): Int = 3
override fun getGroupName(): String = UnityBundle.message("group.name.local.unity.processes")
override fun getItemIcon(project: Project, process: ProcessInfo, userData: UserDataHolder) = UnityIcons.Icons.UnityLogo
override fun getItemDisplayText(project: Project, process: ProcessInfo, userData: UserDataHolder): String {
val displayNames = userData.getUserData(UnityLocalAttachProcessDebuggerProvider.PROCESS_INFO_KEY)?.get(process.pid)
@NlsSafe
val projectName = if (displayNames?.projectName != null) " (${displayNames.projectName})" else ""
val roleName = if (displayNames?.roleName != null) " ${displayNames.roleName}" else ""
return process.executableDisplayName + roleName + projectName
}
override fun compare(p1: ProcessInfo, p2: ProcessInfo) = p1.pid.compareTo(p2.pid)
} | apache-2.0 | 3186c4cae22ff193ab2ea48b34948d1c | 52.88 | 123 | 0.781575 | 4.706294 | false | false | false | false |
phase/sbhs | src/main/kotlin/io/jadon/sbhs/SplashScreen.kt | 1 | 817 | package io.jadon.sbhs
import java.awt.Color
import java.awt.Graphics
import javax.swing.JWindow
class SplashScreen : JWindow() {
init {
setSize(490, 364)
isVisible = true
}
var timer = System.nanoTime()
var message = "JFrame"
set(x) {
val time = System.nanoTime() - timer
println("$message took ${time / 1000000000.0}s")
field = x
timer = System.nanoTime()
repaint()
}
override fun paint(g: Graphics?) {
if (g == null) return
g.drawImage(SBHS.splashImage, 0, 0, null)
val textWidth = (width * (1.0 / 10)).toInt()
val textHeight = (height * (14.0 / 15)).toInt()
g.color = Color.white
g.drawString("Loading $message...", textWidth, textHeight)
}
}
| mpl-2.0 | b5a90c46c74e58b1896739309f3b34d7 | 23.029412 | 66 | 0.553244 | 3.909091 | false | false | false | false |
kharchenkovitaliypt/AndroidMvp | sample/src/main/java/com/idapgroup/android/mvpsample/SampleLceActivity.kt | 1 | 2737 | package com.idapgroup.android.mvpsample
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.idapgroup.android.mvp.impl.LcePresenterActivity
class SampleLceActivity : SampleLceMvp.View, LcePresenterActivity<SampleLceMvp.View, SampleLceMvp.Presenter>() {
override fun showError(error: Throwable, retry: (() -> Unit)?) {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onCreatePresenter(): SampleLceMvp.Presenter {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
override fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup): View {
TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
}
//
// override var retainPresenter = true
//
// var loadDialog: ProgressDialog? = null
//
// override fun onCreatePresenter() = SampleLcePresenter()
//
// override fun onCreateContentView(inflater: LayoutInflater, container: ViewGroup): View {
// return inflater.inflate(R.layout.screen_sample, container, false)
// }
//
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
//
// findViewById(R.id.ask).setOnClickListener {
// val question = (findViewById(R.id.question) as TextView).text
// presenter.onAsk(question.toString())
// }
// findViewById(R.id.confirm).setOnClickListener { presenter.onConfirm() }
//
// if (savedInstanceState != null) {
// if(savedInstanceState.getBoolean("load_dialog_shown", false)) {
// showLoad()
// }
// }
// }
//
// override fun onSaveInstanceState(outState: Bundle) {
// super.onSaveInstanceState(outState)
// outState.putBoolean("load_dialog_shown", loadDialog != null)
// }
//
// override fun goToMain() {
// finish()
// }
//
// override fun showMessage(message: String) {
// (findViewById(R.id.result) as TextView).text = message
// }
//
// override fun showLceLoad() {
// // Because was override by SampleMvp.View interface
// super.showLoad()
// }
//
// override fun showLoad() {
// val loadDialog = ProgressDialog(this)
// loadDialog.setMessage("Processing...")
// loadDialog.isIndeterminate = true
// loadDialog.show()
// this.loadDialog = loadDialog
// }
//
// override fun hideLoad() {
// loadDialog!!.hide()
// loadDialog = null
// }
//
// override fun showError(error: Throwable, retry: (() -> Unit)?) {
//
// }
} | apache-2.0 | d789418d3dae1da340c95a02b6f3f2bb | 32.390244 | 112 | 0.641578 | 4.204301 | false | false | false | false |
sys1yagi/goat-reader-2-android-prototype | app/src/main/kotlin/com/sys1yagi/goatreader/views/MenuListAdapter.kt | 1 | 974 | package com.sys1yagi.goatreader.views
import android.content.Context
import android.widget.ArrayAdapter
import com.sys1yagi.goatreader.models.Menu
import android.view.View
import android.view.ViewGroup
import com.sys1yagi.goatreader.R
import android.widget.ImageView
import android.widget.TextView
class MenuListAdapter(context: Context) : ArrayAdapter<Menu>(context, -1) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
var view: View? = convertView
if (view == null) {
view = createView()
}
val menu = getItem(position)
(view?.findViewById(R.id.icon) as ImageView)?.setImageResource(menu?.iconResId!!)
(view?.findViewById(R.id.title) as TextView)?.setText(menu?.title)
(view?.findViewById(R.id.count_text) as TextView)?.setText("(${menu?.count})")
return view
}
fun createView() = View.inflate(getContext()!!, R.layout.listitem_menu, null)
}
| apache-2.0 | 56e9a739819c86124ffcf09de0ee57c7 | 33.785714 | 89 | 0.699179 | 3.991803 | false | false | false | false |
elpassion/android-commons | recycler-example/src/main/java/com/elpassion/android/commons/recycler_example/list/BasicListActivity.kt | 1 | 1780 | package com.elpassion.android.commons.recycler_example.list
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import com.elpassion.android.commons.recycler.adapters.basicAdapterWithConstructors
import com.elpassion.android.commons.recycler_example.R
import com.elpassion.android.commons.recycler_example.common.OtherSimpleUserViewHolder
import com.elpassion.android.commons.recycler_example.common.SimpleUserViewHolder
import com.elpassion.android.commons.recycler_example.common.User
import com.elpassion.android.commons.recycler_example.common.createManyUsers
import kotlinx.android.synthetic.main.recycler_view.*
class BasicListActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.recycler_view)
recyclerView.layoutManager = LinearLayoutManager(this)
// tag::recycler-basic-adapter-with-constructor[]
val users = createManyUsers()
recyclerView.adapter = basicAdapterWithConstructors(users) { position ->
getLayoutAndConstructor(users[position])
}
}
private fun getLayoutAndConstructor(user: User) = when (user.organization) {
"A" -> R.layout.github_item to ::SimpleUserViewHolder
else -> R.layout.other_github_item to ::OtherSimpleUserViewHolder
}
// end::recycler-basic-adapter-with-constructor[]
companion object {
fun start(context: Context) {
context.startActivity(Intent(context, BasicListActivity::class.java))
}
const val DESCRIPTION = "Basic recycler with different item views"
}
}
| apache-2.0 | 65b5193709b468f896dbec93fc19a56e | 40.395349 | 86 | 0.762921 | 4.64752 | false | false | false | false |
Deletescape-Media/Lawnchair | lawnchair/src/app/lawnchair/gestures/DirectionalGestureListener.kt | 1 | 2154 | package app.lawnchair.gestures
import android.annotation.SuppressLint
import android.content.Context
import android.view.GestureDetector
import android.view.GestureDetector.SimpleOnGestureListener
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import kotlin.math.abs
open class DirectionalGestureListener(ctx: Context?) : OnTouchListener {
private val mGestureDetector: GestureDetector
@SuppressLint("ClickableViewAccessibility")
override fun onTouch(v: View, event: MotionEvent): Boolean {
return mGestureDetector.onTouchEvent(event)
}
@Suppress("PrivatePropertyName")
private inner class GestureListener : SimpleOnGestureListener() {
private val SWIPE_THRESHOLD = 100
private val SWIPE_VELOCITY_THRESHOLD = 100
override fun onDown(e: MotionEvent): Boolean {
return true
}
private fun shouldReactToSwipe(diff: Float, velocity: Float): Boolean =
abs(diff) > SWIPE_THRESHOLD && abs(velocity) > SWIPE_VELOCITY_THRESHOLD
override fun onFling(e1: MotionEvent?, e2: MotionEvent?, velocityX: Float, velocityY: Float): Boolean {
if (e1 == null || e2 == null) return false
return try {
val diffY = e2.y - e1.y
val diffX = e2.x - e1.x
when {
abs(diffX) > abs(diffY) && shouldReactToSwipe(diffX, velocityX) -> {
if (diffX > 0) onSwipeRight() else onSwipeLeft()
true
}
shouldReactToSwipe(diffY, velocityY) -> {
if (diffY > 0) onSwipeBottom() else onSwipeTop()
true
}
else -> false
}
} catch (exception: Exception) {
exception.printStackTrace()
false
}
}
}
fun onSwipeRight() {}
fun onSwipeLeft() {}
fun onSwipeTop() {}
open fun onSwipeBottom() {}
init {
mGestureDetector = GestureDetector(ctx, GestureListener())
}
} | gpl-3.0 | 55035016b7ce13c1ac334ec48f270a0b | 32.671875 | 111 | 0.5961 | 5.15311 | false | false | false | false |
camsteffen/polite | src/main/java/me/camsteffen/polite/di/AppModule.kt | 1 | 5557 | package me.camsteffen.polite.di
import android.app.AlarmManager
import android.app.Application
import android.app.NotificationManager
import android.content.ContentResolver
import android.content.Context
import android.content.SharedPreferences
import android.content.res.Resources
import android.media.AudioManager
import android.preference.PreferenceManager
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.work.WorkManager
import dagger.Binds
import dagger.Module
import dagger.Provides
import dagger.android.ContributesAndroidInjector
import dagger.multibindings.IntoMap
import dagger.multibindings.IntoSet
import me.camsteffen.polite.AppBroadcastReceiver
import me.camsteffen.polite.AppTimingConfig
import me.camsteffen.polite.MainActivity
import me.camsteffen.polite.Polite
import me.camsteffen.polite.R
import me.camsteffen.polite.db.AppDatabase
import me.camsteffen.polite.db.PoliteStateDao
import me.camsteffen.polite.defaultAppTimingConfig
import me.camsteffen.polite.receiver.CalendarChangeReceiver
import me.camsteffen.polite.rule.RuleMasterDetailViewModel
import me.camsteffen.polite.rule.edit.EditCalendarRuleViewModel
import me.camsteffen.polite.rule.edit.EditScheduleRuleViewModel
import me.camsteffen.polite.settings.PreferenceDefaults
import me.camsteffen.polite.util.CalendarRuleEventFinder
import me.camsteffen.polite.util.RuleEventFinder
import me.camsteffen.polite.util.ScheduleRuleEventFinder
import me.camsteffen.polite.util.SharedPreferenceBooleanLiveData
import org.threeten.bp.Clock
import javax.inject.Singleton
@Module
abstract class AppModule {
@Binds
abstract fun app(app: Polite): Application
@Binds
abstract fun provideContext(app: Application): Context
@ActivityScope
@ContributesAndroidInjector(
modules = [MainActivityModule::class, MainActivityFragmentsModule::class]
)
abstract fun contributeMainActivity(): MainActivity
@ContributesAndroidInjector
abstract fun contributeAppBroadcastReceiver(): AppBroadcastReceiver
@ContributesAndroidInjector
abstract fun contributeCalendarChangeReceiver(): CalendarChangeReceiver
@Binds
abstract fun bindViewModelFactory(viewModelFactory: ViewModelFactory): ViewModelProvider.Factory
@Binds
@IntoMap
@ViewModelKey(RuleMasterDetailViewModel::class)
abstract fun bindRuleMasterDetailViewModel(
ruleMasterDetailViewModel: RuleMasterDetailViewModel
): ViewModel
@Binds
@IntoMap
@ViewModelKey(EditCalendarRuleViewModel::class)
abstract fun bindEditCalendarRuleViewModel(
editCalendarRuleViewModel: EditCalendarRuleViewModel
): ViewModel
@Binds
@IntoMap
@ViewModelKey(EditScheduleRuleViewModel::class)
abstract fun bindEditScheduleRuleViewModel(
editScheduleRuleViewModel: EditScheduleRuleViewModel
): ViewModel
@Binds
@IntoSet
abstract fun bindCalendarRuleEventFinder(
calendarRuleEventFinder: CalendarRuleEventFinder
): RuleEventFinder<*>
@Binds
@IntoSet
abstract fun bindScheduleRuleEventFinder(
scheduleRuleEventFinder: ScheduleRuleEventFinder
): RuleEventFinder<*>
@Module
companion object {
@JvmStatic
@Provides
fun provideContentResolver(app: Application): ContentResolver = app.contentResolver
@JvmStatic
@Provides
fun provideNotificationManager(app: Application): NotificationManager =
app.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
@JvmStatic
@Provides
@Singleton
fun database(context: Context): AppDatabase {
return AppDatabase.init(context)
}
@JvmStatic
@Provides
fun ruleDao(database: AppDatabase) = database.ruleDao
@JvmStatic
@Provides
fun politeStateDao(database: AppDatabase): PoliteStateDao = database.politeStateDao
@JvmStatic
@Provides
fun provideResources(app: Application): Resources = app.resources
@JvmStatic
@Provides
fun provideSharedPreferences(app: Application): SharedPreferences =
PreferenceManager.getDefaultSharedPreferences(app)
@JvmStatic
@Provides
fun provideEnableLiveData(
sharedPreferences: SharedPreferences,
resources: Resources
): LiveData<Boolean> {
val key = resources.getString(R.string.preference_enable)
return SharedPreferenceBooleanLiveData(
sharedPreferences,
key,
PreferenceDefaults.ENABLE
)
}
@JvmStatic
@Provides
fun provideAlarmManager(context: Context): AlarmManager {
return context.getSystemService(Context.ALARM_SERVICE) as AlarmManager
}
@JvmStatic
@Provides
fun provideAudioManager(context: Context): AudioManager {
return context.getSystemService(Context.AUDIO_SERVICE) as AudioManager
}
@JvmStatic
@Provides
fun provideClock(): Clock {
return Clock.systemDefaultZone()
}
@JvmStatic
@Provides
fun provideAppTimingConfig(): AppTimingConfig {
return defaultAppTimingConfig
}
@JvmStatic
@Provides
fun provideWorkManager(context: Context): WorkManager {
return WorkManager.getInstance(context)
}
}
}
| mpl-2.0 | 534279f3605e0c10eeeed7b68d1a91d8 | 30.044693 | 100 | 0.733669 | 5.722966 | false | false | false | false |
Kotlin/dokka | kotlin-analysis/src/main/kotlin/org/jetbrains/dokka/analysis/DokkaResolutionFacade.kt | 1 | 5004 | @file:OptIn(FrontendInternals::class)
package org.jetbrains.dokka.analysis
import com.google.common.collect.ImmutableMap
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.ResolverForModule
import org.jetbrains.kotlin.analyzer.ResolverForProject
import org.jetbrains.kotlin.container.getService
import org.jetbrains.kotlin.container.tryGetService
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.diagnostics.DiagnosticSink
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.BindingTrace
import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.ResolveSession
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.util.slicedMap.ReadOnlySlice
import org.jetbrains.kotlin.util.slicedMap.WritableSlice
class DokkaResolutionFacade(
override val project: Project,
override val moduleDescriptor: ModuleDescriptor,
val resolverForModule: ResolverForModule
) : ResolutionFacade {
override fun analyzeWithAllCompilerChecks(
elements: Collection<KtElement>,
callback: DiagnosticSink.DiagnosticsCallback?
): AnalysisResult {
throw UnsupportedOperationException()
}
@OptIn(FrontendInternals::class)
override fun <T : Any> tryGetFrontendService(element: PsiElement, serviceClass: Class<T>): T? {
return resolverForModule.componentProvider.tryGetService(serviceClass)
}
override fun resolveToDescriptor(
declaration: KtDeclaration,
bodyResolveMode: BodyResolveMode
): DeclarationDescriptor {
return resolveSession.resolveToDescriptor(declaration)
}
override fun analyze(elements: Collection<KtElement>, bodyResolveMode: BodyResolveMode): BindingContext {
throw UnsupportedOperationException()
}
val resolveSession: ResolveSession get() = getFrontendService(ResolveSession::class.java)
override fun analyze(element: KtElement, bodyResolveMode: BodyResolveMode): BindingContext {
if (element is KtDeclaration) {
val descriptor = resolveToDescriptor(element)
return object : BindingContext {
override fun <K : Any?, V : Any?> getKeys(p0: WritableSlice<K, V>?): Collection<K> {
throw UnsupportedOperationException()
}
override fun getType(p0: KtExpression): KotlinType? {
throw UnsupportedOperationException()
}
override fun <K : Any?, V : Any?> get(slice: ReadOnlySlice<K, V>?, key: K): V? {
if (key != element) {
throw UnsupportedOperationException()
}
@Suppress("UNCHECKED_CAST")
return when {
slice == BindingContext.DECLARATION_TO_DESCRIPTOR -> descriptor as V
slice == BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER && (element as KtParameter).hasValOrVar() -> descriptor as V
else -> null
}
}
override fun getDiagnostics(): Diagnostics {
throw UnsupportedOperationException()
}
override fun addOwnDataTo(p0: BindingTrace, p1: Boolean) {
throw UnsupportedOperationException()
}
override fun <K : Any?, V : Any?> getSliceContents(p0: ReadOnlySlice<K, V>): ImmutableMap<K, V> {
throw UnsupportedOperationException()
}
}
}
throw UnsupportedOperationException()
}
override fun <T : Any> getFrontendService(element: PsiElement, serviceClass: Class<T>): T {
throw UnsupportedOperationException()
}
override fun <T : Any> getFrontendService(serviceClass: Class<T>): T {
return resolverForModule.componentProvider.getService(serviceClass)
}
override fun <T : Any> getFrontendService(moduleDescriptor: ModuleDescriptor, serviceClass: Class<T>): T {
return resolverForModule.componentProvider.getService(serviceClass)
}
override fun <T : Any> getIdeService(serviceClass: Class<T>): T {
throw UnsupportedOperationException()
}
override fun getResolverForProject(): ResolverForProject<out ModuleInfo> {
throw UnsupportedOperationException()
}
}
| apache-2.0 | 0614b95edbb9a059b9b2376596fb787d | 39.682927 | 138 | 0.696043 | 5.445049 | false | false | false | false |
cscenter/hpcourse | csc/2017/2.LockFreeSet/BogdanovPA/LockFreeSetImpl.kt | 1 | 3999 | import java.util.concurrent.atomic.AtomicMarkableReference
class LockFreeSetImpl<T : Comparable<T>> : LockFreeSet<T> {
private val head: Node<T> = Head()
private fun findPrev(value: T): Node<T> {
var prev: Node<T> = head
var cur: Node<T>? = head.next
retry@ while (cur != null) {
if (prev.nextMarked) {
val succ = cur.next
if (!prev.removeNext()) {
continue@retry
} else if (succ == null) {
return prev
} else {
cur = succ
}
} else if (cur.value >= value) {
return prev
}
prev = cur
cur = cur.next
}
return prev
}
override fun add(value: T): Boolean {
while (true) {
val prev = findPrev(value)
val next = prev.next
// if persist and equal --> false
if (next != null && !prev.nextMarked && next.value == value) {
return false
}
val newN = NodeImpl(value, next)
if (prev.insert(newN)) {
return true
}
}
}
override fun remove(value: T): Boolean {
while (true) {
val prev = findPrev(value)
val next = prev.next
if (next == null || next.value != value) {
return false
}
if (prev.markNext(true)) {
// try to remove
prev.removeNext()
return true
}
}
}
override fun contains(value: T): Boolean {
val prev = findPrevWithoutRemove(value)
return (value == prev.next?.value && !prev.nextMarked)
}
private fun findPrevWithoutRemove(value: T): Node<T> {
var prev: Node<T> = head
var cur: Node<T>? = head.next
while (cur != null) {
if (cur.value >= value) {
return prev
}
prev = cur
cur = cur.next
}
return prev
}
override fun isEmpty(): Boolean {
var cur: Node<T> = head
while (cur.next != null) {
if (!cur.nextMarked) return false
cur = cur.next!!
}
return true
}
// inner classes -----------------------------------
private interface Node<T> {
val next: Node<T>?
val value: T
val nextMarked: Boolean
val isHead: Boolean
fun insert(node: Node<T>): Boolean
fun markNext(flag: Boolean): Boolean
fun removeNext(): Boolean
}
private abstract class AbstractNode<T>(next: Node<T>? = null) : Node<T> {
private val ref: AtomicMarkableReference<Node<T>?> = AtomicMarkableReference(next, false)
override val next: Node<T>?
get() = ref.reference
override val nextMarked: Boolean
get() = ref.isMarked
override fun insert(node: Node<T>): Boolean {
val next = this.next
return ref.compareAndSet(next, node, nextMarked, node.nextMarked)
}
override fun markNext(flag: Boolean): Boolean {
return ref.compareAndSet(next, next, nextMarked, flag)
}
override fun removeNext(): Boolean {
// if (!nextMarked) throw IllegalStateException("Can't remove the unmarked element")
if (!nextMarked) return false
val succ = next?.next
return ref.compareAndSet(next, succ, true, succ?.nextMarked ?: false)
}
}
private class Head<T>(next: Node<T>? = null) : AbstractNode<T>(next) {
override val isHead = false
override val value: T
get() = throw UnsupportedOperationException("Head can not contain element")
}
private class NodeImpl<T>(override val value: T, next: Node<T>? = null) : AbstractNode<T>(next) {
override val isHead: Boolean = false
}
} | gpl-2.0 | 1fe6fe9e7dcc2922f0cd81c553ca2d6c | 28.62963 | 101 | 0.507127 | 4.478163 | false | false | false | false |
NordicSemiconductor/Android-nRF-Toolbox | profile_bps/src/main/java/no/nordicsemi/android/bps/view/BPSContentView.kt | 1 | 2648 | /*
* Copyright (c) 2022, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
* OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package no.nordicsemi.android.bps.view
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import no.nordicsemi.android.bps.R
import no.nordicsemi.android.bps.data.BPSData
@Composable
internal fun BPSContentView(state: BPSData, onEvent: (BPSViewEvent) -> Unit) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(16.dp)
) {
BPSSensorsReadingView(state = state)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = { onEvent(DisconnectEvent) }
) {
Text(text = stringResource(id = R.string.disconnect))
}
}
}
| bsd-3-clause | 211ad97d9ec61560f044d1ca9c043fc2 | 40.375 | 89 | 0.763595 | 4.495756 | false | false | false | false |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/actions/RsJoinLinesHandler.kt | 2 | 3626 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate
import com.intellij.codeInsight.editorActions.JoinLinesHandlerDelegate.CANNOT_JOIN
import com.intellij.openapi.editor.Document
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.util.text.CharSequenceSubSequence
import org.rust.ide.formatter.impl.CommaList
import org.rust.ide.typing.endsWithUnescapedBackslash
import org.rust.lang.core.parser.RustParserDefinition.Companion.INNER_EOL_DOC_COMMENT
import org.rust.lang.core.parser.RustParserDefinition.Companion.OUTER_EOL_DOC_COMMENT
import org.rust.lang.core.psi.RS_STRING_LITERALS
import org.rust.lang.core.psi.RsElementTypes.COMMA
import org.rust.lang.core.psi.RsFile
import org.rust.lang.core.psi.ext.elementType
class RsJoinLinesHandler : JoinLinesHandlerDelegate {
/**
* Fixup lines **after** they have been join.
* See [RsJoinRawLinesHandler]
*/
override fun tryJoinLines(document: Document, file: PsiFile, offsetNear: Int, end: Int): Int {
if (file !is RsFile) return CANNOT_JOIN
val leftPsi = file.findElementAt(offsetNear) ?: return CANNOT_JOIN
val rightPsi = file.findElementAt(end) ?: return CANNOT_JOIN
val tryJoinCommaList = joinCommaList(document, leftPsi, rightPsi)
if (tryJoinCommaList != CANNOT_JOIN) return tryJoinCommaList
if (leftPsi != rightPsi) return CANNOT_JOIN
val elementType = leftPsi.elementType
return when (elementType) {
in RS_STRING_LITERALS ->
joinStringLiteral(document, offsetNear, end)
INNER_EOL_DOC_COMMENT, OUTER_EOL_DOC_COMMENT ->
joinLineDocComment(document, offsetNear, end)
else -> CANNOT_JOIN
}
}
private fun joinCommaList(document: Document, leftPsi: PsiElement, rightPsi: PsiElement): Int {
if (leftPsi.elementType != COMMA) return CANNOT_JOIN
val parentType = leftPsi.parent?.elementType ?: return CANNOT_JOIN
val rightType = rightPsi.elementType
val list = CommaList.forElement(parentType) ?: return CANNOT_JOIN
if (rightType == list.closingBrace) {
val replaceWith = if (list.needsSpaceBeforeClosingBrace) " " else ""
document.replaceString(leftPsi.textOffset, rightPsi.textOffset, replaceWith)
return leftPsi.textOffset
}
return CANNOT_JOIN
}
// Normally this is handled by `CodeDocumentationAwareCommenter`, but Rust have different styles
// of documentation comments, so we handle this manually.
private fun joinLineDocComment(document: Document, offsetNear: Int, end: Int): Int {
val prefix = document.charsSequence.subSequence(end, end + 3).toString()
if (prefix != "///" && prefix != "//!") return CANNOT_JOIN
document.deleteString(offsetNear + 1, end + prefix.length)
return offsetNear + 1
}
private fun joinStringLiteral(document: Document, offsetNear: Int, end: Int): Int {
val text = document.charsSequence
var start = offsetNear
// Strip newline escape
if (CharSequenceSubSequence(text, 0, start + 1).endsWithUnescapedBackslash()) {
start--
while (start >= 0 && (text[start] == ' ' || text[start] == '\t')) {
start--
}
}
document.deleteString(start + 1, end)
document.insertString(start + 1, " ")
return start + 1
}
}
| mit | fe213b0269d591541e7e843ab7999a64 | 38.413043 | 100 | 0.684777 | 4.515567 | false | false | false | false |
wuseal/JsonToKotlinClass | src/main/kotlin/wu/seal/jsontokotlin/utils/SimplifiedMethods.kt | 1 | 2841 | package wu.seal.jsontokotlin.utils
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.notification.Notifications
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.project.Project
import wu.seal.jsontokotlin.model.ConfigManager
import java.lang.IllegalStateException
import java.util.regex.Pattern
/**
* File contains functions which simply other functions's invoke
* Created by Seal.Wu on 2018/2/7.
*/
/**
* do the action that could be roll-back
*/
fun executeCouldRollBackAction(project: Project?, action: (Project?) -> Unit) {
CommandProcessor.getInstance().executeCommand(project, {
ApplicationManager.getApplication().runWriteAction {
action.invoke(project)
}
}, "insertKotlin", "JsonToKotlin")
}
/**
* get the indent when generate kotlin class code
*/
fun getIndent(): String {
return buildString {
for (i in 1..ConfigManager.indent) {
append(" ")
}
}
}
/**
* get class string block list from a big string which contains classes
*/
fun getClassesStringList(classesString: String): List<String> {
return classesString.split("\n\n").filter { it.isNotBlank() }
}
/**
* export the class name from class block string
*/
fun getClassNameFromClassBlockString(classBlockString: String): String {
val pattern = Pattern.compile("(data )?class (?<className>[^(]+).*")
val matcher = pattern.matcher(classBlockString)
if (matcher.find()) {
return matcher.group("className").trim()
}
throw IllegalStateException("cannot find class name in classBlockString: $classBlockString")
}
fun replaceClassNameToClassBlockString(classBlockString: String, newClassName: String): String {
val blockPre = classBlockString.substringBefore("data class")
val blockAfter = classBlockString.substringAfter("(")
val blockMid = "data class $newClassName("
return blockPre + blockMid + blockAfter
}
fun showNotify(notifyMessage: String, project: Project?) {
val notificationGroup = NotificationGroup("JSON to Kotlin Class", NotificationDisplayType.BALLOON, true)
ApplicationManager.getApplication().invokeLater {
val notification = notificationGroup.createNotification(notifyMessage, NotificationType.INFORMATION)
Notifications.Bus.notify(notification, project)
}
}
fun <E> List<E>.firstIndexAfterSpecificIndex(element: E, afterIndex: Int): Int {
forEachIndexed { index, e ->
if (e == element && index > afterIndex) {
return index
}
}
return -1
}
fun getCommentCode(comment: String): String {
return comment.replace(Regex("[\n\r]"), "")
}
| gpl-3.0 | 851b322796a36f594fb6629eda3c4cef | 30.921348 | 108 | 0.725097 | 4.560193 | false | false | false | false |
herbeth1u/VNDB-Android | app/src/main/java/com/booboot/vndbandroid/dao/TraitDao.kt | 1 | 1401 | package com.booboot.vndbandroid.dao
import com.booboot.vndbandroid.model.vndb.Trait
import io.objectbox.BoxStore
import io.objectbox.annotation.Entity
import io.objectbox.annotation.Id
import io.objectbox.kotlin.boxFor
import io.objectbox.relation.ToMany
@Entity
class TraitDao() {
@Id(assignable = true) var id: Long = 0
var name: String = ""
var description: String = ""
var meta: Boolean = false
var chars: Int = 0
lateinit var aliases: ToMany<TraitAlias>
lateinit var parents: ToMany<TraitParent>
constructor(trait: Trait, boxStore: BoxStore) : this() {
id = trait.id
name = trait.name
description = trait.description
meta = trait.meta
chars = trait.chars
boxStore.boxFor<TraitDao>().attach(this)
trait.aliases.forEach { aliases.add(TraitAlias(it.hashCode().toLong(), it)) }
trait.parents.forEach { parents.add(TraitParent(it)) }
boxStore.boxFor<TraitAlias>().put(aliases)
boxStore.boxFor<TraitParent>().put(parents)
}
fun toBo() = Trait(
id,
name,
description,
meta,
chars,
aliases.map { it.alias },
parents.map { it.id }
)
}
@Entity
data class TraitAlias(
@Id(assignable = true) var id: Long = 0,
var alias: String = ""
)
@Entity
data class TraitParent(
@Id(assignable = true) var id: Long = 0
) | gpl-3.0 | f786b90a59d95d1f6d244c68cd564ccf | 24.490909 | 85 | 0.643112 | 3.817439 | false | false | false | false |
TakuSemba/Spotlight | spotlight/src/main/java/com/takusemba/spotlight/Spotlight.kt | 1 | 6743 | package com.takusemba.spotlight
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.TimeInterpolator
import android.app.Activity
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.animation.DecelerateInterpolator
import androidx.annotation.ColorInt
import androidx.annotation.ColorRes
import androidx.core.content.ContextCompat
import java.util.concurrent.TimeUnit
/**
* Holds all of the [Target]s and [SpotlightView] to show/hide [Target], [SpotlightView] properly.
* [SpotlightView] can be controlled with [start]/[finish].
* All of the [Target]s can be controlled with [next]/[previous]/[show].
*
* Once you finish the current [Spotlight] with [finish], you can not start the [Spotlight] again
* unless you create a new [Spotlight] to start again.
*/
class Spotlight private constructor(
private val spotlight: SpotlightView,
private val targets: Array<Target>,
private val duration: Long,
private val interpolator: TimeInterpolator,
private val container: ViewGroup,
private val spotlightListener: OnSpotlightListener?
) {
private var currentIndex = NO_POSITION
init {
container.addView(spotlight, MATCH_PARENT, MATCH_PARENT)
}
/**
* Starts [SpotlightView] and show the first [Target].
*/
fun start() {
startSpotlight()
}
/**
* Closes the current [Target] if exists, and shows a [Target] at the specified [index].
* If target is not found at the [index], it will throw an exception.
*/
fun show(index: Int) {
showTarget(index)
}
/**
* Closes the current [Target] if exists, and shows the next [Target].
* If the next [Target] is not found, Spotlight will finish.
*/
fun next() {
showTarget(currentIndex + 1)
}
/**
* Closes the current [Target] if exists, and shows the previous [Target].
* If the previous target is not found, it will throw an exception.
*/
fun previous() {
showTarget(currentIndex - 1)
}
/**
* Closes Spotlight and [SpotlightView] will remove all children and be removed from the [container].
*/
fun finish() {
finishSpotlight()
}
/**
* Starts Spotlight.
*/
private fun startSpotlight() {
spotlight.startSpotlight(duration, interpolator, object : AnimatorListenerAdapter() {
override fun onAnimationStart(animation: Animator) {
spotlightListener?.onStarted()
}
override fun onAnimationEnd(animation: Animator) {
showTarget(0)
}
})
}
/**
* Closes the current [Target] if exists, and show the [Target] at [index].
*/
private fun showTarget(index: Int) {
if (currentIndex == NO_POSITION) {
val target = targets[index]
currentIndex = index
spotlight.startTarget(target)
target.listener?.onStarted()
} else {
spotlight.finishTarget(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
val previousIndex = currentIndex
val previousTarget = targets[previousIndex]
previousTarget.listener?.onEnded()
if (index < targets.size) {
val target = targets[index]
currentIndex = index
spotlight.startTarget(target)
target.listener?.onStarted()
} else {
finishSpotlight()
}
}
})
}
}
/**
* Closes Spotlight.
*/
private fun finishSpotlight() {
spotlight.finishSpotlight(duration, interpolator, object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
spotlight.cleanup()
container.removeView(spotlight)
spotlightListener?.onEnded()
}
})
}
companion object {
private const val NO_POSITION = -1
}
/**
* Builder to build [Spotlight].
* All parameters should be set in this [Builder].
*/
class Builder(private val activity: Activity) {
private var targets: Array<Target>? = null
private var duration: Long = DEFAULT_DURATION
private var interpolator: TimeInterpolator = DEFAULT_ANIMATION
@ColorInt private var backgroundColor: Int = DEFAULT_OVERLAY_COLOR
private var container: ViewGroup? = null
private var listener: OnSpotlightListener? = null
/**
* Sets [Target]s to show on [Spotlight].
*/
fun setTargets(vararg targets: Target): Builder = apply {
require(targets.isNotEmpty()) { "targets should not be empty. " }
this.targets = arrayOf(*targets)
}
/**
* Sets [Target]s to show on [Spotlight].
*/
fun setTargets(targets: List<Target>): Builder = apply {
require(targets.isNotEmpty()) { "targets should not be empty. " }
this.targets = targets.toTypedArray()
}
/**
* Sets [duration] to start/finish [Spotlight].
*/
fun setDuration(duration: Long): Builder = apply {
this.duration = duration
}
/**
* Sets [backgroundColor] resource on [Spotlight].
*/
fun setBackgroundColorRes(@ColorRes backgroundColorRes: Int): Builder = apply {
this.backgroundColor = ContextCompat.getColor(activity, backgroundColorRes)
}
/**
* Sets [backgroundColor] on [Spotlight].
*/
fun setBackgroundColor(@ColorInt backgroundColor: Int): Builder = apply {
this.backgroundColor = backgroundColor
}
/**
* Sets [interpolator] to start/finish [Spotlight].
*/
fun setAnimation(interpolator: TimeInterpolator): Builder = apply {
this.interpolator = interpolator
}
/**
* Sets [container] to hold [SpotlightView]. DecoderView will be used if not specified.
*/
fun setContainer(container: ViewGroup) = apply {
this.container = container
}
/**
* Sets [OnSpotlightListener] to notify the state of [Spotlight].
*/
fun setOnSpotlightListener(listener: OnSpotlightListener): Builder = apply {
this.listener = listener
}
fun build(): Spotlight {
val spotlight = SpotlightView(activity, null, 0, backgroundColor)
val targets = requireNotNull(targets) { "targets should not be null. " }
val container = container ?: activity.window.decorView as ViewGroup
return Spotlight(
spotlight = spotlight,
targets = targets,
duration = duration,
interpolator = interpolator,
container = container,
spotlightListener = listener
)
}
companion object {
private val DEFAULT_DURATION = TimeUnit.SECONDS.toMillis(1)
private val DEFAULT_ANIMATION = DecelerateInterpolator(2f)
@ColorInt private val DEFAULT_OVERLAY_COLOR: Int = 0x6000000
}
}
}
| apache-2.0 | 6987826fad4a7571511a7e287efb1b46 | 27.939914 | 103 | 0.662316 | 4.676144 | false | false | false | false |
italoag/qksms | data/src/main/java/com/moez/QKSMS/repository/ContactRepositoryImpl.kt | 3 | 6291 | /*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.repository
import android.content.Context
import android.net.Uri
import android.provider.BaseColumns
import android.provider.ContactsContract
import android.provider.ContactsContract.CommonDataKinds.Email
import android.provider.ContactsContract.CommonDataKinds.Phone
import com.moez.QKSMS.extensions.asFlowable
import com.moez.QKSMS.extensions.asObservable
import com.moez.QKSMS.extensions.mapNotNull
import com.moez.QKSMS.model.Contact
import com.moez.QKSMS.model.ContactGroup
import com.moez.QKSMS.util.Preferences
import io.reactivex.Flowable
import io.reactivex.Observable
import io.reactivex.Single
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import io.realm.Realm
import io.realm.RealmResults
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ContactRepositoryImpl @Inject constructor(
private val context: Context,
private val prefs: Preferences
) : ContactRepository {
override fun findContactUri(address: String): Single<Uri> {
return Flowable.just(address)
.map {
when {
address.contains('@') -> {
Uri.withAppendedPath(Email.CONTENT_FILTER_URI, Uri.encode(address))
}
else -> {
Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(address))
}
}
}
.mapNotNull { uri -> context.contentResolver.query(uri, arrayOf(BaseColumns._ID), null, null, null) }
.flatMap { cursor -> cursor.asFlowable() }
.firstOrError()
.map { cursor -> cursor.getString(cursor.getColumnIndexOrThrow(BaseColumns._ID)) }
.map { id -> Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, id) }
}
override fun getContacts(): RealmResults<Contact> {
val realm = Realm.getDefaultInstance()
return realm.where(Contact::class.java)
.sort("name")
.findAll()
}
override fun getUnmanagedContact(lookupKey: String): Contact? {
return Realm.getDefaultInstance().use { realm ->
realm.where(Contact::class.java)
.equalTo("lookupKey", lookupKey)
.findFirst()
?.let(realm::copyFromRealm)
}
}
override fun getUnmanagedContacts(starred: Boolean): Observable<List<Contact>> {
val realm = Realm.getDefaultInstance()
val mobileOnly = prefs.mobileOnly.get()
val mobileLabel by lazy { Phone.getTypeLabel(context.resources, Phone.TYPE_MOBILE, "Mobile").toString() }
var query = realm.where(Contact::class.java)
if (mobileOnly) {
query = query.contains("numbers.type", mobileLabel)
}
if (starred) {
query = query.equalTo("starred", true)
}
return query
.findAllAsync()
.asObservable()
.filter { it.isLoaded }
.filter { it.isValid }
.map { realm.copyFromRealm(it) }
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io())
.map { contacts ->
if (mobileOnly) {
contacts.map { contact ->
val filteredNumbers = contact.numbers.filter { number -> number.type == mobileLabel }
contact.numbers.clear()
contact.numbers.addAll(filteredNumbers)
contact
}
} else {
contacts
}
}
.map { contacts ->
contacts.sortedWith(Comparator { c1, c2 ->
val initial = c1.name.firstOrNull()
val other = c2.name.firstOrNull()
if (initial?.isLetter() == true && other?.isLetter() != true) {
-1
} else if (initial?.isLetter() != true && other?.isLetter() == true) {
1
} else {
c1.name.compareTo(c2.name, ignoreCase = true)
}
})
}
}
override fun getUnmanagedContactGroups(): Observable<List<ContactGroup>> {
val realm = Realm.getDefaultInstance()
return realm.where(ContactGroup::class.java)
.isNotEmpty("contacts")
.findAllAsync()
.asObservable()
.filter { it.isLoaded }
.filter { it.isValid }
.map { realm.copyFromRealm(it) }
.subscribeOn(AndroidSchedulers.mainThread())
.observeOn(Schedulers.io())
}
override fun setDefaultPhoneNumber(lookupKey: String, phoneNumberId: Long) {
Realm.getDefaultInstance().use { realm ->
realm.refresh()
val contact = realm.where(Contact::class.java)
.equalTo("lookupKey", lookupKey)
.findFirst()
?: return
realm.executeTransaction {
contact.numbers.forEach { number ->
number.isDefault = number.id == phoneNumberId
}
}
}
}
}
| gpl-3.0 | 46915f38155369d7824fcb5c0f89a09e | 37.127273 | 118 | 0.567159 | 5.114634 | false | false | false | false |
weibaohui/korm | src/main/kotlin/com/sdibt/korm/core/db/ColumnInfo.kt | 1 | 3523 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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.sdibt.korm.core.db
/** 实体字段信息
* <功能详细描述>
*/
data class ColumnInfo(
/**
* (Optional) The name of the column. Defaults to
* the property or field name.
*/
var name: String,
/**
* (Optional) Whether the property is a unique key. This is a
* shortcut for the UniqueConstraint annotation at the table
* level and is useful for when the unique key constraint is
* only a single field. This constraint applies in addition
* to any constraint entailed by primary key mapping and
* to constraints specified at the table level.
*/
var unique: Boolean = false,
/**
* (Optional) Whether the database column is nullable.
*/
var nullable: Boolean = true,
/**
* (Optional) Whether the column is included in SQL INSERT
* statements generated by the persistence provider.
*/
var insertable: Boolean = true,
/**
* (Optional) Whether the column is included in SQL UPDATE
* statements generated by the persistence provider.
*/
var updatable: Boolean = true,
/**
* (Optional) The SQL fragment that is used when
* generating the DDL for the column.
*
* Defaults to the generated SQL to create a
* column of the inferred type.
*/
var columnDefinition: String = "",
/**
* (Optional) The name of the table that contains the column.
* If absent the column is assumed to be in the primary table.
*/
var table: String = "",
/**
* (Optional) The column length. (Applies only if a
* string-valued column is used.)
*/
var length: Int = 255,
/**
* (Optional) The precision for a decimal (exact numeric)
* column. (Applies only if a decimal column is used.)
* Value must be set by developer if used when generating
* the DDL for the column.
*/
var precision: Int = 10,
/**
* (Optional) The scale for a decimal (exact numeric) column.
* (Applies only if a decimal column is used.)
*/
var scale: Int = 0,
/**
* (Optional) The Column comment
*/
var comment: String? = null,
/**
* (Optional) Whether the column is pk.
*/
var isPk: Boolean = false,
/**
* The Column Type
*/
var type: Any,
/**
* The Column defaultValue
*/
var defaultValue: String? = null
)
| apache-2.0 | feda7d25c8bd5d401698e3fa350bb459 | 31.700935 | 76 | 0.587025 | 4.709287 | false | false | false | false |
gameover-fwk/gameover-fwk | src/main/kotlin/gameover/fwk/libgdx/gfx/GfxUtils.kt | 1 | 905 | package gameover.fwk.libgdx.gfx
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Pixmap
import com.badlogic.gdx.utils.ScreenUtils
object GfxUtils {
/**
* Take a screenshot of the GDX viewport.
*/
fun takeScreenShot() : Pixmap {
val width = Gdx.graphics.width
val height = Gdx.graphics.height
val pixmap = ScreenUtils.getFrameBufferPixmap(0, 0, width, height)
val pixels = pixmap.pixels
val amountOfBytes = width * height * 4
val lines = ByteArray(amountOfBytes) { 0 }
val amountOfBytesPerLine = width * 4
for (i in 0 until height) {
pixels.position((height - i - 1) * amountOfBytesPerLine)
pixels.get(lines, i * amountOfBytesPerLine, amountOfBytesPerLine)
}
pixels.clear()
pixels.put(lines)
return pixmap
}
} | mit | c75833d22751208150f09c81b657a888 | 29.2 | 77 | 0.646409 | 4.151376 | false | false | false | false |
openMF/android-client | mifosng-android/src/main/java/com/mifos/mifosxdroid/AboutActivity.kt | 1 | 1090 | package com.mifos.mifosxdroid
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import com.mifos.mifosxdroid.core.MifosBaseActivity
class AboutActivity : MifosBaseActivity() {
var contributors = "https://github.com/openMF/android-client/graphs/contributors"
var gitHub = "https://github.com/openMF/android-client"
var twitter = "https://twitter.com/mifos"
var license = "https://github.com/openMF/android-client/blob/master/LICENSE.md"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_about)
showBackButton()
}
fun goToWeb(view: View?) {
link(contributors)
}
fun goToGit(view: View?) {
link(gitHub)
}
fun goToTwitter(view: View?) {
link(twitter)
}
fun goToLicense(view: View?) {
link(license)
}
fun link(url: String?) {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse(url)
startActivity(intent)
}
} | mpl-2.0 | ffa652f930ab8aa37d833b161c8c07ff | 25.609756 | 85 | 0.670642 | 4.007353 | false | false | false | false |
milos85vasic/Decorator | Decorator/src/test/kotlin/net/milosvasic/decorator/IfTest.kt | 1 | 8818 | package net.milosvasic.decorator
import net.milosvasic.decorator.data.DataBuilder
import net.milosvasic.logger.SimpleLogger
import net.milosvasic.logger.VariantsConfiguration
import org.junit.After
import org.junit.Assert
import org.junit.Test
class IfTest {
private val tag = ""
val logger = SimpleLogger(VariantsConfiguration(BuildConfig.VARIANT, listOf("DEV")))
@Test
fun testForeach() {
val data = DataBuilder()
.append("exist", "exist")
.append("does_not_exist", "")
.append("something", "nice!")
.append("person", "John")
.append("company", "has value")
.append("company2", "has value too")
.build()
var html = ""
val decorator = Decorator("if", data)
for (x in 0..10) { // Repeat a few times to see timings.
val start = System.currentTimeMillis()
html = decorator.getContent()
val end = System.currentTimeMillis() - start
logger.i(tag, "Template generated in $end ms.")
assertHtml(html) // Check if we got valid result.
}
logger.v("", html)
}
fun assertHtml(html: String) {
val lines = mutableListOf<String>()
lines.addAll(html.split("\n"))
Assert.assertFalse(lines.isEmpty())
lines.removeAt(lines.lastIndex)
Assert.assertFalse(lines.isEmpty())
Assert.assertEquals("m 1", lines[0])
Assert.assertEquals("t 2", lines[1])
Assert.assertEquals("m 3", lines[2])
Assert.assertEquals("t 4", lines[3])
Assert.assertEquals("m 5", lines[4])
Assert.assertEquals("m 8", lines[5])
Assert.assertEquals("s 1", lines[6])
Assert.assertEquals("s 3", lines[7])
Assert.assertEquals("s 5", lines[8])
Assert.assertEquals("x 1", lines[9])
Assert.assertEquals("y 2", lines[10])
Assert.assertEquals("x 3", lines[11])
Assert.assertEquals("x 4", lines[12])
Assert.assertEquals("k 1", lines[13])
Assert.assertEquals("k 3", lines[14])
Assert.assertEquals("aaaccc", lines[15])
Assert.assertEquals("aaaddd", lines[16])
Assert.assertEquals("bbbccc", lines[17])
Assert.assertEquals("bbbddd", lines[18])
Assert.assertEquals("--> nice! <--", lines[19])
Assert.assertEquals("nice!!!!", lines[20])
Assert.assertEquals("--> nice!!!!", lines[21])
Assert.assertEquals("nice! <--", lines[22])
Assert.assertEquals("--> nice! <--", lines[23])
Assert.assertEquals("~ ~ ~ nice! <--", lines[24])
Assert.assertEquals("--> nice!!!!", lines[25])
Assert.assertEquals("~ ~ ~ nice!!!!", lines[26])
Assert.assertEquals("sss sss sss ", lines[27])
Assert.assertEquals("John is right! Run now!", lines[28])
Assert.assertEquals("John is not right! Do not run now!", lines[29])
Assert.assertEquals("John is not right! Run now!", lines[30])
Assert.assertEquals("John is right! Do not run now!", lines[31])
Assert.assertEquals("John is right! John knows all!", lines[32])
Assert.assertEquals("John is not right! John does not know all!", lines[33])
Assert.assertEquals("John is not right! John knows all!", lines[34])
Assert.assertEquals("John is right! John does not know all!", lines[35])
Assert.assertEquals("--- repeating stuff", lines[36])
Assert.assertEquals("k 1", lines[37])
Assert.assertEquals("k 3", lines[38])
Assert.assertEquals("aaaccc", lines[39])
Assert.assertEquals("aaaddd", lines[40])
Assert.assertEquals("bbbccc", lines[41])
Assert.assertEquals("bbbddd", lines[42])
Assert.assertEquals("--> nice! <--", lines[43])
Assert.assertEquals("nice!!!!", lines[44])
Assert.assertEquals("--> nice!!!!", lines[45])
Assert.assertEquals("nice! <--", lines[46])
Assert.assertEquals("--> nice! <--", lines[47])
Assert.assertEquals("~ ~ ~ nice! <--", lines[48])
Assert.assertEquals("--> nice!!!!", lines[49])
Assert.assertEquals("~ ~ ~ nice!!!!", lines[50])
Assert.assertEquals("--- repeating stuff - END", lines[51])
Assert.assertEquals("--- end commented invalid ifs", lines[52])
Assert.assertEquals(". . . . .", lines[53])
Assert.assertEquals("nice!", lines[54])
Assert.assertEquals("- - -", lines[55])
Assert.assertEquals("YyY", lines[56])
Assert.assertEquals("- - -", lines[57])
Assert.assertEquals("Ha ha ha!", lines[58])
Assert.assertEquals("- - -", lines[59])
Assert.assertEquals("Repeating - START", lines[60])
Assert.assertEquals("---", lines[61])
Assert.assertEquals("m 1", lines[62])
Assert.assertEquals("t 2", lines[63])
Assert.assertEquals("m 3", lines[64])
Assert.assertEquals("t 4", lines[65])
Assert.assertEquals("m 5", lines[66])
Assert.assertEquals("m 8", lines[67])
Assert.assertEquals("s 1", lines[68])
Assert.assertEquals("s 3", lines[69])
Assert.assertEquals("s 5", lines[70])
Assert.assertEquals("x 1", lines[71])
Assert.assertEquals("y 2", lines[72])
Assert.assertEquals("x 3", lines[73])
Assert.assertEquals("x 4", lines[74])
Assert.assertEquals("k 1", lines[75])
Assert.assertEquals("k 3", lines[76])
Assert.assertEquals("aaaccc", lines[77])
Assert.assertEquals("aaaddd", lines[78])
Assert.assertEquals("bbbccc", lines[79])
Assert.assertEquals("bbbddd", lines[80])
Assert.assertEquals("--> nice! <--", lines[81])
Assert.assertEquals("nice!!!!", lines[82])
Assert.assertEquals("--> nice!!!!", lines[83])
Assert.assertEquals("nice! <--", lines[84])
Assert.assertEquals("--> nice! <--", lines[85])
Assert.assertEquals("~ ~ ~ nice! <--", lines[86])
Assert.assertEquals("--> nice!!!!", lines[87])
Assert.assertEquals("~ ~ ~ nice!!!!", lines[88])
Assert.assertEquals("---", lines[89])
Assert.assertEquals("Repeating - END", lines[90])
Assert.assertEquals("s 7", lines[91])
Assert.assertEquals("---", lines[92])
Assert.assertEquals("-", lines[93])
Assert.assertEquals("-", lines[94])
Assert.assertEquals("-", lines[95])
Assert.assertEquals("-", lines[96])
Assert.assertEquals("-", lines[97])
Assert.assertEquals("-", lines[98])
Assert.assertEquals("-", lines[99])
Assert.assertEquals("-", lines[100])
Assert.assertEquals("-", lines[101])
Assert.assertEquals("mm", lines[102])
Assert.assertEquals("-", lines[103])
Assert.assertEquals(" mm", lines[104])
Assert.assertEquals("-", lines[105])
Assert.assertEquals(" mm ", lines[106])
Assert.assertEquals("-", lines[107])
Assert.assertEquals("mm", lines[108])
Assert.assertEquals("-", lines[109])
Assert.assertEquals(" mm", lines[110])
Assert.assertEquals("-", lines[111])
Assert.assertEquals(" mm ", lines[112])
Assert.assertEquals("-- -- --", lines[113])
Assert.assertEquals("-", lines[114])
Assert.assertEquals("-", lines[115])
Assert.assertEquals("ggg", lines[116])
Assert.assertEquals("-", lines[117])
Assert.assertEquals("-", lines[118])
Assert.assertEquals("ggg2 ", lines[119])
Assert.assertEquals("-", lines[120])
Assert.assertEquals(" sss ", lines[121])
Assert.assertEquals("-", lines[122])
Assert.assertEquals("-", lines[123])
Assert.assertEquals("sss2 ", lines[124])
Assert.assertEquals("-", lines[125])
Assert.assertEquals("x1 ", lines[126])
Assert.assertEquals("-", lines[127])
Assert.assertEquals(" x2", lines[128])
Assert.assertEquals("-", lines[129])
Assert.assertEquals(" x3", lines[130])
Assert.assertEquals("-", lines[131])
Assert.assertEquals(" x4", lines[132])
Assert.assertEquals("-", lines[133])
Assert.assertEquals("mm", lines[134])
Assert.assertEquals("-", lines[135])
Assert.assertEquals(" mm", lines[136])
Assert.assertEquals("-", lines[137])
Assert.assertEquals(" mm ", lines[138])
Assert.assertEquals("-", lines[139])
Assert.assertEquals("mm", lines[140])
Assert.assertEquals("-", lines[141])
Assert.assertEquals(" mm", lines[142])
Assert.assertEquals("-", lines[143])
Assert.assertEquals(" mm ", lines[144])
Assert.assertEquals("-- END", lines[145])
Assert.assertEquals(146, lines.size)
}
} | apache-2.0 | 33a72f0965e6eee68c0068d87813fb66 | 44.458763 | 88 | 0.584146 | 4.322549 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/view/custom/CategoryList.kt | 1 | 2067 | /*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.view.custom
import android.content.Context
import android.util.AttributeSet
import android.widget.TextView
import com.google.android.flexbox.FlexboxLayout
import com.toshi.R
class CategoryList : FlexboxLayout {
constructor(context: Context) : super(context) {
init()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init()
}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
init()
}
var itemClickedListener: ((Int, String) -> Unit)? = null
fun init() {
inflate(context, R.layout.view_category_list, this)
}
fun addCategories(categories: Map<Int, String>) {
removeAllViews()
val sortedMap = categories.toSortedMap()
sortedMap.forEach {
val renderComma = it.key != sortedMap.lastKey()
addTextView(it.key, it.value, renderComma)
}
}
private fun addTextView(key: Int, value: String, renderComma: Boolean) {
val textView = inflate(context, R.layout.view_category__item, null) as TextView
textView.text = if (renderComma) "$value, " else value
textView.setOnClickListener { itemClickedListener?.invoke(key, (it as TextView).text.toString()) }
addView(textView)
}
} | gpl-3.0 | 3b83ec198be17fe40f7f7ba315b4cedb | 34.655172 | 106 | 0.675375 | 4.167339 | false | false | false | false |
SpryServers/sprycloud-android | src/test/java/com/nextcloud/client/logger/LoggerTest.kt | 2 | 10786 | /*
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.logger
import android.os.Handler
import com.nextcloud.client.core.Clock
import com.nextcloud.client.core.ClockImpl
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argThat
import com.nhaarman.mockitokotlin2.capture
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.inOrder
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.mockito.ArgumentCaptor
import org.mockito.MockitoAnnotations
import java.nio.file.Files
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
class LoggerTest {
private companion object {
const val QUEUE_CAPACITY = 100
const val FILE_SIZE = 1024L
const val LATCH_WAIT = 3L
const val LATCH_INIT = 3
const val EMPTY = 0
const val EMPTY_LONG = 0L
const val TIMEOUT = 3000L
const val MESSAGE_COUNT = 3
}
private lateinit var clock: Clock
private lateinit var logHandler: FileLogHandler
private lateinit var osHandler: Handler
private lateinit var logger: LoggerImpl
@Before
fun setUp() {
MockitoAnnotations.initMocks(this)
val tempDir = Files.createTempDirectory("log-test").toFile()
clock = ClockImpl()
logHandler = spy(FileLogHandler(tempDir, "log.txt", FILE_SIZE))
osHandler = mock()
logger = LoggerImpl(clock, logHandler, osHandler, QUEUE_CAPACITY)
}
@Test
fun `write is done on background thread`() {
val callerThreadId = Thread.currentThread().id
val writerThreadIds = mutableListOf<Long>()
val latch = CountDownLatch(LATCH_INIT)
doAnswer {
writerThreadIds.add(Thread.currentThread().id)
it.callRealMethod()
latch.countDown()
}.whenever(logHandler).open()
doAnswer {
writerThreadIds.add(Thread.currentThread().id)
it.callRealMethod()
latch.countDown()
}.whenever(logHandler).write(any())
doAnswer {
writerThreadIds.add(Thread.currentThread().id)
it.callRealMethod()
latch.countDown()
}.whenever(logHandler).close()
// GIVEN
// logger event loop is running
logger.start()
// WHEN
// message is logged
logger.d("tag", "message")
// THEN
// message is processed on bg thread
// all handler invocations happen on bg thread
// all handler invocations happen on single thread
assertTrue(latch.await(LATCH_WAIT, TimeUnit.SECONDS))
writerThreadIds.forEach { writerThreadId ->
assertNotEquals("All requests must be made on bg thread", callerThreadId, writerThreadId)
}
writerThreadIds.forEach {
assertEquals("All requests must be made on single thread", writerThreadIds[0], it)
}
}
@Test
fun `message is written via log handler`() {
val tag = "test tag"
val message = "test log message"
val latch = CountDownLatch(LATCH_INIT)
doAnswer { it.callRealMethod(); latch.countDown() }.whenever(logHandler).open()
doAnswer { it.callRealMethod(); latch.countDown() }.whenever(logHandler).write(any())
doAnswer { it.callRealMethod(); latch.countDown() }.whenever(logHandler).close()
// GIVEN
// logger event loop is running
logger.start()
// WHEN
// log message is written
logger.d(tag, message)
// THEN
// log handler opens log file
// log handler writes entry
// log handler closes log file
// no lost messages
val called = latch.await(LATCH_WAIT, TimeUnit.SECONDS)
assertTrue("Expected open(), write() and close() calls on bg thread", called)
val inOrder = inOrder(logHandler)
inOrder.verify(logHandler).open()
inOrder.verify(logHandler).write(argThat {
tag in this && message in this
})
inOrder.verify(logHandler).close()
assertFalse(logger.lostEntries)
}
@Test
fun `logs are loaded in background thread and posted to main thread`() {
val currentThreadId = Thread.currentThread().id
var loggerThreadId: Long = -1
val listener: OnLogsLoaded = mock()
val latch = CountDownLatch(2)
// log handler will be called on bg thread
doAnswer {
loggerThreadId = Thread.currentThread().id
latch.countDown()
it.callRealMethod()
}.whenever(logHandler).loadLogFiles(any())
// os handler will be called on bg thread
whenever(osHandler.post(any())).thenAnswer {
latch.countDown()
true
}
// GIVEN
// logger event loop is running
logger.start()
// WHEN
// messages are logged
// log contents are requested
logger.d("tag", "message 1")
logger.d("tag", "message 2")
logger.d("tag", "message 3")
logger.load(listener)
val called = latch.await(LATCH_WAIT, TimeUnit.SECONDS)
assertTrue("Response not posted", called)
// THEN
// log contents are loaded on background thread
// logs are posted to main thread handler
// contents contain logged messages
// messages are in order of writes
assertNotEquals(currentThreadId, loggerThreadId)
val postedCaptor = ArgumentCaptor.forClass(Runnable::class.java)
verify(osHandler).post(capture(postedCaptor))
postedCaptor.value.run()
val logsCaptor = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor<List<LogEntry>>
val sizeCaptor = ArgumentCaptor.forClass(Long::class.java)
verify(listener).invoke(capture(logsCaptor), capture(sizeCaptor))
assertEquals(MESSAGE_COUNT, logsCaptor.value.size)
assertTrue("message 1" in logsCaptor.value[0].message)
assertTrue("message 2" in logsCaptor.value[1].message)
assertTrue("message 3" in logsCaptor.value[2].message)
}
@Test
fun `log level can be decoded from tags`() {
Level.values().forEach {
val decodedLevel = Level.fromTag(it.tag)
assertEquals(it, decodedLevel)
}
}
@Test
fun `queue limit is enforced`() {
// GIVEN
// logger event loop is no running
// WHEN
// queue is filled up to it's capacity
for (i in 0 until QUEUE_CAPACITY + 1) {
logger.d("tag", "Message $i")
}
// THEN
// overflow flag is raised
assertTrue(logger.lostEntries)
}
@Test
fun `queue overflow warning is logged`() {
// GIVEN
// logger loop is overflown
for (i in 0..QUEUE_CAPACITY + 1) {
logger.d("tag", "Message $i")
}
// WHEN
// logger event loop processes events
//
logger.start()
// THEN
// overflow occurrence is logged
val posted = CountDownLatch(1)
whenever(osHandler.post(any())).thenAnswer {
(it.arguments[0] as Runnable).run()
posted.countDown()
true
}
val listener: OnLogsLoaded = mock()
logger.load(listener)
assertTrue("Logs not loaded", posted.await(1, TimeUnit.SECONDS))
verify(listener).invoke(argThat {
"Logger queue overflow" in last().message
}, any())
}
@Test
fun `all log files are deleted`() {
val latch = CountDownLatch(1)
doAnswer {
it.callRealMethod()
latch.countDown()
}.whenever(logHandler).deleteAll()
// GIVEN
// logger is started
logger.start()
// WHEN
// logger has some writes
// logs are deleted
logger.d("tag", "message")
logger.d("tag", "message")
logger.d("tag", "message")
logger.deleteAll()
// THEN
// handler writes files
// handler deletes all files
assertTrue(latch.await(LATCH_WAIT, TimeUnit.SECONDS))
verify(logHandler, times(MESSAGE_COUNT)).write(any())
verify(logHandler).deleteAll()
val loaded = logHandler.loadLogFiles(logHandler.maxLogFilesCount)
assertEquals(EMPTY, loaded.lines.size)
assertEquals(EMPTY_LONG, loaded.logSize)
}
@Test
@Suppress("TooGenericExceptionCaught")
fun `thread interruption is handled while posting log message`() {
Thread {
val callerThread = Thread.currentThread()
// GIVEN
// logger is running
// caller thread is interrupted
logger.start()
callerThread.interrupt()
// WHEN
// message is logged on interrupted thread
var loggerException: Throwable? = null
try {
logger.d("test", "test")
} catch (ex: Throwable) {
loggerException = ex
}
// THEN
// message post is gracefully skipped
// thread interruption flag is not cleared
assertNull(loggerException)
assertTrue("Expected current thread to stay interrupted", callerThread.isInterrupted)
}.apply {
start()
join(TIMEOUT)
}
}
}
| gpl-2.0 | 1a3ba686026c29d73375c6d24c817582 | 31.984709 | 101 | 0.613202 | 4.783149 | false | false | false | false |
Fargren/kotlin-map-alarm | alarm-lib/src/test/java/com/mapalarm/usecases/AddTriggerUseCaseTests.kt | 1 | 1844 | package com.mapalarm.usecases
import com.mapalarm.AddTriggerGateway
import com.mapalarm.Environment
import com.mapalarm.PresentableTrigger
import com.mapalarm.datatypes.Position
import com.mapalarm.entities.PositionTrigger
import com.mapalarm.usecases.AddAlarmPresenter
import com.mapalarm.usecases.AddTriggerUseCase
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import java.util.*
class AddTriggerUseCaseTests {
lateinit var gatewaySpy: AddTriggerGatewaySpy
lateinit var presenter: AddAlarmPresenterSpy
lateinit var sut: AddTriggerUseCase
private val DEFAULT_POSITION = Position(34.5, -18.44)
@Before fun setUp() {
gatewaySpy = AddTriggerGatewaySpy()
Environment.addTriggerGateway = gatewaySpy
presenter = AddAlarmPresenterSpy()
sut = AddTriggerUseCase(presenter)
}
@Test @Throws(Exception::class) fun addTriggerAt_newPosition_isRegistered() {
sut.addTriggerAt(DEFAULT_POSITION)
assertEquals(Collections.singleton(PositionTrigger(DEFAULT_POSITION, 200.0)),
gatewaySpy.triggers)
}
@Test @Throws(Exception::class) fun addTriggerAt_newAlarm_isPresented() {
sut.addTriggerAt(DEFAULT_POSITION)
assertEquals(Collections.singleton(PresentableTrigger(DEFAULT_POSITION, 200.0)),
presenter.triggers)
}
}
class AddAlarmPresenterSpy : AddAlarmPresenter {
var triggers: HashSet<PresentableTrigger> = HashSet()
override fun presentTrigger(trigger: PresentableTrigger) {
triggers.add(trigger)
}
}
class AddTriggerGatewaySpy : AddTriggerGateway {
var triggers: HashSet<PositionTrigger> = HashSet()
override fun addTrigger(trigger: PositionTrigger) {
triggers.add(trigger)
}
}
| mit | 455b52c9f7f0a8fa1090be38a0dae651 | 29.793103 | 88 | 0.721258 | 4.530713 | false | true | false | false |
BasinMC/Basin | faucet/src/main/kotlin/org/basinmc/faucet/extension/dependency/ExtensionDependency.kt | 1 | 1462 | /*
* Copyright 2018 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.faucet.extension.dependency
import org.basinmc.faucet.util.VersionRange
/**
* Represents a dependency to another extension.
*
* @author [Johannes Donath](mailto:[email protected])
* @since 1.0
*/
class ExtensionDependency(identifier: String, versionRange: VersionRange, val optional: Boolean) :
ExtensionReference(identifier, versionRange) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ExtensionDependency) return false
if (!super.equals(other)) return false
if (optional != other.optional) return false
return true
}
override fun hashCode(): Int {
var result = super.hashCode()
result = 31 * result + optional.hashCode()
return result
}
}
| apache-2.0 | 92ca3292672eb404a8c5373667a33b15 | 31.488889 | 98 | 0.727086 | 4.213256 | false | false | false | false |
fossasia/open-event-android | app/src/main/java/org/fossasia/openevent/general/sponsor/SponsorsFragment.kt | 1 | 3035 | package org.fossasia.openevent.general.sponsor
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import kotlinx.android.synthetic.main.fragment_sponsors.view.sponsorDetailProgressBar
import kotlinx.android.synthetic.main.fragment_sponsors.view.sponsorsDetailRecyclerView
import org.fossasia.openevent.general.R
import org.fossasia.openevent.general.utils.Utils
import org.fossasia.openevent.general.utils.extensions.nonNull
import org.jetbrains.anko.design.snackbar
import org.koin.androidx.viewmodel.ext.android.viewModel
class SponsorsFragment : Fragment() {
private lateinit var rootView: View
private val sponsorsDetailViewModel by viewModel<SponsorsViewModel>()
private val sponsorsAdapter = SponsorsDetailAdapter()
private val safeArgs: SponsorsFragmentArgs by navArgs()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
rootView = inflater.inflate(R.layout.fragment_sponsors, container, false)
Utils.setToolbar(activity, getString(R.string.sponsors))
setHasOptionsMenu(true)
val sponsorURLClickListener = object : SponsorURLClickListener {
override fun onClick(sponsorURL: String?) {
if (sponsorURL.isNullOrBlank()) return
context?.let { Utils.openUrl(it, sponsorURL) }
}
}
sponsorsAdapter.apply {
onURLClickListener = sponsorURLClickListener
}
val layoutManager = LinearLayoutManager(context)
layoutManager.orientation = RecyclerView.VERTICAL
rootView.sponsorsDetailRecyclerView.layoutManager = layoutManager
rootView.sponsorsDetailRecyclerView.adapter = sponsorsAdapter
sponsorsDetailViewModel.error
.nonNull()
.observe(viewLifecycleOwner, Observer {
rootView.snackbar(it)
})
sponsorsDetailViewModel.sponsors
.nonNull()
.observe(viewLifecycleOwner, Observer { sponsors ->
sponsorsAdapter.addAll(sponsors)
})
sponsorsDetailViewModel.progress
.nonNull()
.observe(viewLifecycleOwner, Observer { isLoading ->
rootView.sponsorDetailProgressBar.isVisible = isLoading
})
sponsorsDetailViewModel.loadSponsors(safeArgs.eventId)
return rootView
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
android.R.id.home -> {
activity?.onBackPressed()
true
}
else -> super.onOptionsItemSelected(item)
}
}
}
| apache-2.0 | be65079396f654ebba9e13eae3bd7a6a | 36.469136 | 116 | 0.707743 | 5.409982 | false | false | false | false |
wordpress-mobile/WordPress-Stores-Android | fluxc/src/main/java/org/wordpress/android/fluxc/network/rest/wpcom/scan/threat/FixThreatsStatusDeserializer.kt | 2 | 1992 | package org.wordpress.android.fluxc.network.rest.wpcom.scan.threat
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import com.google.gson.JsonObject
import org.wordpress.android.fluxc.network.rest.wpcom.scan.threat.FixThreatsStatusResponse.FixThreatStatus
import java.lang.reflect.Type
class FixThreatsStatusDeserializer : JsonDeserializer<List<FixThreatStatus>?> {
override fun deserialize(
json: JsonElement?,
typeOfT: Type?,
context: JsonDeserializationContext?
) = if (context != null && json != null && json.isJsonObject) {
deserializeJson(json)
} else {
null
}
/**
* Input: { "39154018": {"status": "fixed" }} / { "39154018": {"error": "not_found" }}
* Output: [{ "id": 39154018, "status": "fixed" }] / [{ "id": 39154018, "error": "not_found" }]
*/
private fun deserializeJson(json: JsonElement) = mutableListOf<FixThreatStatus>().apply {
val inputJsonObject = json.asJsonObject
inputJsonObject.keySet().iterator().forEach { key ->
getFixThreatStatus(key, inputJsonObject)?.let { add(it) }
}
}.toList()
@Suppress("SwallowedException")
private fun getFixThreatStatus(key: String, inputJsonObject: JsonObject) =
inputJsonObject.get(key)?.takeIf { it.isJsonObject }?.asJsonObject?.let { threat ->
try {
FixThreatStatus(
id = key.toLong(),
status = threat.get(STATUS)?.asString,
error = threat.get(ERROR)?.asString
)
} catch (ex: ClassCastException) {
null
} catch (ex: IllegalStateException) {
null
} catch (ex: NumberFormatException) {
null
}
}
companion object {
private const val STATUS = "status"
private const val ERROR = "error"
}
}
| gpl-2.0 | 34f17381495a6aac7c033abc885bdf81 | 35.888889 | 106 | 0.60994 | 4.654206 | false | false | false | false |
sbhachu/kotlin-bootstrap | app/src/main/kotlin/com/sbhachu/bootstrap/presentation/common/BaseActivity.kt | 1 | 2659 | package com.sbhachu.bootstrap.presentation.common
import android.app.Dialog
import android.content.SharedPreferences
import android.graphics.drawable.TransitionDrawable
import android.os.Bundle
import android.support.design.widget.Snackbar
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.widget.LinearLayout
import com.sbhachu.bootstrap.R
import com.sbhachu.bootstrap.extensions.action
import com.sbhachu.bootstrap.extensions.snack
import com.sbhachu.bootstrap.presentation.common.BasePresenter
abstract class BaseActivity<T : BasePresenter<*>> : AppCompatActivity() {
protected var presenter: T?
protected abstract var layoutId: Int
var snackbarContainer: LinearLayout? = null
private lateinit var dialog: Dialog
var snackbar: Snackbar? = null
init {
presenter = initialisePresenter()
}
protected abstract fun initialisePresenter(): T
protected abstract fun initialiseViews(): Unit
protected abstract fun initialiseListeners(): Unit
protected abstract fun handleExtras(bundle: Bundle?): Unit
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layoutId)
handleExtras(intent?.extras)
snackbarContainer = findViewById(R.id.snackbar_container) as LinearLayout?
initialiseViews()
initialiseListeners()
}
override fun onDestroy() {
super.onDestroy()
presenter?.dispose()
presenter = null
}
/**
* Show a custom alertDialog
*
* dialogBuilder - Configure and pass in an instance of an AlertDialog.Builder
*/
protected fun showDialog(dialogBuilder: AlertDialog.Builder?) {
dialog = dialogBuilder?.create() as Dialog
dialog.show()
}
/**
* Show a custom snackbar
*
* message - Snackbar text
* duration - Snackbar duration, defaults to LENGTH_LONG
* actionLabel - Snackbar action label, for example Dismiss
* actionFunction - Snackbar action handler function
*/
protected fun showSnackbar(message: String, duration: Int?, actionLabel: String, actionFunction: () -> Unit): Unit {
if (snackbar?.isShown ?: false) return
snackbar = snackbarContainer?.snack(message, duration ?: Snackbar.LENGTH_LONG) {
action(actionLabel) { actionFunction() }
}
snackbar?.show()
}
/**
* Hide custom snackbar
*/
protected fun hideSnackbar(): () -> Unit = { snackbar?.dismiss() }
} | apache-2.0 | d7bc12597c1a13ff619d5e9aa2c595b8 | 28.586207 | 120 | 0.676194 | 5.08413 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/AbstractCustomPayloadCodec.kt | 1 | 7070 | /*
* 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.codec.play
import com.google.common.base.Joiner
import com.google.common.base.Splitter
import io.netty.handler.codec.CodecException
import io.netty.handler.codec.DecoderException
import io.netty.util.AttributeKey
import org.lanternpowered.server.LanternGame
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.buffer.UnpooledByteBufferAllocator
import org.lanternpowered.server.network.packet.Packet
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.PacketEncoder
import org.lanternpowered.server.network.packet.UnknownPacket
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ChannelPayloadPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.RegisterChannelsPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.UnregisterChannelsPacket
abstract class AbstractCustomPayloadCodec : PacketEncoder<Packet>, PacketDecoder<Packet> {
override fun encode(ctx: CodecContext, packet: Packet): ByteBuffer {
val buf = ctx.byteBufAlloc().buffer()
val channel: String
val content: ByteBuffer
when (packet) {
is ChannelPayloadPacket -> {
content = packet.content
// Retain because content will be released when written, MessagePlayInOutChannelPayload
// is ReferenceCounted so it will be cleaned up later.
content.retain()
channel = packet.channel
}
is RegisterChannelsPacket -> {
content = encodeChannels(packet.channels)
channel = "minecraft:register"
}
is UnregisterChannelsPacket -> {
content = encodeChannels(packet.channels)
channel = "minecraft:unregister"
}
else -> {
val result = encode0(ctx, packet)
channel = result.channel
content = result.byteBuf
}
}
try {
buf.writeString(channel)
buf.writeBytes(content)
} finally {
content.release()
}
return buf
}
override fun decode(ctx: CodecContext, buf: ByteBuffer): Packet {
val channel = buf.readLimitedString(100)
val length = buf.available()
if (length > Short.MAX_VALUE) {
throw DecoderException("CustomPayload messages may not be longer then " + Short.MAX_VALUE + " bytes")
}
val content = buf.slice()
val packet = decode0(ctx, content, channel)
if (content.available() > 0) {
LanternGame.logger.warn("Trailing bytes {}b after decoding with custom payload message codec {} with channel {}!\n{}",
content.available(), javaClass.name, channel, packet)
}
// Skip all the bytes, we already processed them
buf.readerIndex(buf.readerIndex() + buf.available())
return packet
}
private fun decode0(context: CodecContext, content: ByteBuffer, channel: String): Packet {
if ("minecraft:register" == channel) {
val channels = decodeChannels(content)
channels.removeIf { c: String -> c.startsWith("FML") }
if (channels.isNotEmpty()) {
return RegisterChannelsPacket(channels)
}
} else if ("minecraft:unregister" == channel) {
val channels = decodeChannels(content)
channels.removeIf { c: String -> c.startsWith("FML") }
if (channels.isNotEmpty()) {
return UnregisterChannelsPacket(channels)
}
} else if ("FML|MP" == channel) {
val attribute = context.session.attr(FML_MULTI_PART_MESSAGE)
val message0 = attribute.get()
if (message0 == null) {
val channel0 = content.readString()
val parts: Int = content.readByte().toInt() and 0xff
val size = content.readInt()
if (size <= 0) {
throw CodecException("Received FML MultiPart packet outside of valid length bounds, Received: $size")
}
attribute.set(MultiPartMessage(channel0, context.byteBufAlloc().buffer(size), parts))
} else {
val part: Int = content.readByte().toInt() and 0xff
if (part != message0.index) {
throw CodecException("Received FML MultiPart packet out of order, Expected: " + message0.index + ", Got: " + part)
}
val len = content.available() - 1
content.readBytes(message0.buffer, message0.offset, len)
message0.offset += len
message0.index++
if (message0.index >= message0.parts) {
val packet = decode0(context, message0.channel, message0.buffer)
attribute.set(null)
return packet
}
}
} else {
return decode0(context, channel, content)
}
return UnknownPacket
}
protected abstract fun encode0(context: CodecContext, packet: Packet): MessageResult
protected abstract fun decode0(context: CodecContext, channel: String, content: ByteBuffer): Packet
protected class MessageResult(
val channel: String,
val byteBuf: ByteBuffer
)
private class MultiPartMessage internal constructor(
val channel: String,
val buffer: ByteBuffer,
val parts: Int
) {
var index = 0
var offset = 0
}
companion object {
private val FML_MULTI_PART_MESSAGE = AttributeKey.valueOf<MultiPartMessage>("fml-mpm")
/**
* Decodes the byte buffer into a set of channels.
*
* @param buffer the byte buffer
* @return the channels
*/
private fun decodeChannels(buffer: ByteBuffer): MutableSet<String> {
val bytes = ByteArray(buffer.available())
buffer.readBytes(bytes)
return Splitter.on('\u0000').split(String(bytes, Charsets.UTF_8)).toHashSet()
}
/**
* Encodes the set of channels into a byte buffer.
*
* @param channels the channels
* @return the byte buffer
*/
private fun encodeChannels(channels: Set<String?>): ByteBuffer {
return UnpooledByteBufferAllocator.wrappedBuffer(Joiner.on('\u0000').join(channels).toByteArray(Charsets.UTF_8))
}
}
}
| mit | e3be504448fd8e9756ab0ede11ad9af0 | 39.867052 | 134 | 0.615417 | 4.872502 | false | false | false | false |
ekager/focus-android | app/src/main/java/org/mozilla/focus/utils/IntentUtils.kt | 1 | 6268 | /* 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.utils
import android.content.ActivityNotFoundException
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.support.annotation.StringRes
import android.support.v7.app.AlertDialog
import org.mozilla.focus.R
import org.mozilla.focus.web.IWebView
import java.net.URISyntaxException
object IntentUtils {
private const val MARKET_INTENT_URI_PACKAGE_PREFIX = "market://details?id="
private const val EXTRA_BROWSER_FALLBACK_URL = "browser_fallback_url"
/**
* Find and open the appropriate app for a given Uri. If appropriate, let the user select between
* multiple supported apps. Returns a boolean indicating whether the URL was handled. A fallback
* URL will be opened in the supplied WebView if appropriate (in which case the URL was handled,
* and true will also be returned). If not handled, we should fall back to webviews error handling
* (which ends up calling our error handling code as needed).
*
* Note: this method "leaks" the target Uri to Android before asking the user whether they
* want to use an external app to open the uri. Ultimately the OS can spy on anything we're
* doing in the app, so this isn't an actual "bug".
*/
fun handleExternalUri(context: Context, webView: IWebView, uri: String): Boolean {
// This code is largely based on Fennec's ExternalIntentDuringPrivateBrowsingPromptFragment.java
val intent = try { Intent.parseUri(uri, 0) } catch (e: URISyntaxException) { return false }
// Since we're a browser:
intent.addCategory(Intent.CATEGORY_BROWSABLE)
// This is where we "leak" the uri to the OS. If we're using the system webview, then the OS
// already knows that we're opening this uri. Even if we're using GeckoView, the OS can still
// see what domains we're visiting, so there's no loss of privacy here:
val packageManager = context.packageManager
val matchingActivities = packageManager.queryIntentActivities(intent, 0)
when (matchingActivities.size) {
0 -> handleUnsupportedLink(context, webView, intent)
1 -> {
val info = matchingActivities[0]
val externalAppTitle = info?.loadLabel(packageManager) ?: "(null)"
showConfirmationDialog(
context,
intent,
context.getString(R.string.external_app_prompt_title),
R.string.external_app_prompt,
externalAppTitle)
}
else -> {
val chooserTitle = context.getString(R.string.external_multiple_apps_matched_exit)
val chooserIntent = Intent.createChooser(intent, chooserTitle)
context.startActivity(chooserIntent)
}
}
return true
}
private fun handleUnsupportedLink(context: Context, webView: IWebView, intent: Intent): Boolean {
val fallbackUrl = intent.getStringExtra(EXTRA_BROWSER_FALLBACK_URL)
if (fallbackUrl != null) {
webView.loadUrl(fallbackUrl)
return true
}
if (intent.getPackage() != null) {
// The url included the target package:
val marketUri = MARKET_INTENT_URI_PACKAGE_PREFIX + intent.getPackage()!!
val marketIntent = Intent(Intent.ACTION_VIEW, Uri.parse(marketUri))
marketIntent.addCategory(Intent.CATEGORY_BROWSABLE)
val packageManager = context.packageManager
val info = packageManager.resolveActivity(marketIntent, 0)
val marketTitle = info?.loadLabel(packageManager) ?: "(null)"
showConfirmationDialog(context, marketIntent,
context.getString(R.string.external_app_prompt_no_app_title),
R.string.external_app_prompt_no_app, marketTitle)
// Stop loading, we essentially have a result.
return true
}
// If there's really no way to handle this, we just let the browser handle this URL
// (which then shows the unsupported protocol page).
return false
}
// We only need one param for both scenarios, hence we use just one "param" argument. If we ever
// end up needing more or a variable number we can change this, but java varargs are a bit messy
// so let's try to avoid that seeing as it's not needed right now.
private fun showConfirmationDialog(
context: Context,
targetIntent: Intent,
title: String,
@StringRes messageResource: Int,
param: CharSequence
) {
val builder = AlertDialog.Builder(context, R.style.DialogStyle)
val ourAppName = context.getString(R.string.app_name)
builder.apply {
setTitle(title)
setMessage(context.resources.getString(messageResource, ourAppName, param))
setPositiveButton(R.string.action_ok) { _, _ ->
try {
context.startActivity(targetIntent)
} catch (_: ActivityNotFoundException) {
return@setPositiveButton
}
}
setNegativeButton(R.string.action_cancel) { dialog, _ -> dialog.dismiss() }
show()
}
}
fun activitiesFoundForIntent(context: Context, intent: Intent?): Boolean {
return intent?.let {
val packageManager = context.packageManager
val resolveInfoList = packageManager.queryIntentActivities(intent, 0)
resolveInfoList.size > 0
} ?: false
}
fun createOpenFileIntent(uriFile: Uri?, mimeType: String?): Intent? {
if (uriFile == null || mimeType == null) {
return null
}
val openFileIntent = Intent(Intent.ACTION_VIEW)
openFileIntent.setDataAndType(uriFile, mimeType)
openFileIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
return openFileIntent
}
}
| mpl-2.0 | 8df866fb725ddd117897b90c9c37de42 | 42.527778 | 104 | 0.644065 | 4.7738 | false | false | false | false |
ekamp/KotlinWeather | app/src/main/java/weather/ekamp/com/weatherappkotlin/view/Landing.kt | 1 | 3830 | package weather.ekamp.com.weatherappkotlin.view
import android.location.Location
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.view.animation.Animation
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.activity_main.*
import toothpick.Scope
import toothpick.Toothpick
import weather.ekamp.com.weatherappkotlin.R
import weather.ekamp.com.weatherappkotlin.model.location.UserLocationManager
import weather.ekamp.com.weatherappkotlin.model.parsers.WeatherDescription
import weather.ekamp.com.weatherappkotlin.presenter.LandingPresenter
import javax.inject.Inject
import android.view.animation.AnimationUtils
class Landing : AppCompatActivity(), LandingView {
@Inject lateinit var presenter : LandingPresenter
@Inject lateinit var userLocationManager : UserLocationManager
lateinit private var errorDialog : ErrorDialog
lateinit private var activityScope : Scope
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityScope = Toothpick.openScopes(application, this)
Toothpick.inject(this, activityScope)
setContentView(R.layout.activity_main)
sync_button.setOnClickListener { onRefresh() }
presenter.onAttachView(this)
}
override fun displayCurrentWeather(weatherDescription: WeatherDescription) {
weather_description.text = weatherDescription.getWeatherInformation().description
temperature.text = weatherDescription.main.temp
var weatherIconPath = weatherDescription.getIconUrlPath()
Picasso.with(this).
load(weatherIconPath).
fit().
placeholder(R.drawable.cloud).
error(R.drawable.cloud).
into(weather_representation)
}
override fun displayUserLocation(userLocationForDisplay : String) {
user_location.text = userLocationForDisplay
}
override fun displayLoadingIndicator() {
loading_indicator.visibility = View.VISIBLE
weather_description.visibility = View.GONE
temperature.visibility = View.GONE
weather_representation.visibility = View.GONE
sync_button.animation?.let {
sync_button.animation.repeatCount = Animation.INFINITE
} ?:run {
val rotation = AnimationUtils.loadAnimation(this, R.animator.sync_rotator)
rotation.repeatCount = Animation.INFINITE
sync_button.startAnimation(rotation)
}
}
override fun hideLoadingIndicator() {
loading_indicator.visibility = View.GONE
weather_description.visibility = View.VISIBLE
temperature.visibility = View.VISIBLE
weather_representation.visibility = View.VISIBLE
sync_button.animation.repeatCount = 0 // finish current animation
}
override fun displayErrorToUser(message: String) {
errorDialog = ErrorDialog.newInstance(message)
errorDialog.show(supportFragmentManager, "errorDialog")
}
override fun getUsersLocation() {
userLocationManager.getLocationFromGoogleAPI(this, this)
}
override fun onLocationUpdated(location: Location) {
presenter.onLocationCollected(location, userLocationManager.getCurrentAddress(location.latitude, location.longitude))
}
override fun onLocationNotFound() {
//Notify the user that the location could not be collected
displayErrorToUser("Location Could not be determined please try again")
}
override fun onRefresh() {
presenter.onWeatherRequest()
}
override fun onPause() {
super.onPause()
sync_button.clearAnimation()
}
override fun onDestroy() {
super.onDestroy()
presenter.onViewDestroy()
}
}
| apache-2.0 | b81d02731dfa7b3fa1abdfc800ceed15 | 35.47619 | 125 | 0.720366 | 5.127175 | false | false | false | false |
PKRoma/github-android | app/src/main/java/com/github/pockethub/android/ui/item/news/DeleteEventItem.kt | 5 | 1183 | package com.github.pockethub.android.ui.item.news
import android.view.View
import androidx.core.text.buildSpannedString
import com.github.pockethub.android.ui.view.OcticonTextView
import com.github.pockethub.android.util.AvatarLoader
import com.meisolsson.githubsdk.model.GitHubEvent
import com.meisolsson.githubsdk.model.payload.DeletePayload
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.news_item.*
class DeleteEventItem(
avatarLoader: AvatarLoader,
gitHubEvent: GitHubEvent
) : NewsItem(avatarLoader, gitHubEvent) {
override fun bind(holder: ViewHolder, position: Int) {
super.bind(holder, position)
holder.tv_event_icon.text = OcticonTextView.ICON_DELETE
holder.tv_event.text = buildSpannedString {
val context = holder.root.context
boldActor(context, this, gitHubEvent)
val payload = gitHubEvent.payload() as DeletePayload?
append(" deleted ${payload?.refType()?.name?.toLowerCase()} ${payload?.ref()} at ")
boldRepo(context, this, gitHubEvent)
}
holder.tv_event_details.visibility = View.GONE
}
}
| apache-2.0 | 27e699975b1dea8be87b671ff2866b7d | 39.793103 | 95 | 0.726965 | 4.414179 | false | false | false | false |
actorapp/actor-bots | actor-bots/src/main/java/im/actor/bots/framework/stateful/Expect.kt | 1 | 4604 | package im.actor.bots.framework.stateful
import im.actor.bots.BotMessages
import im.actor.bots.framework.*
import im.actor.bots.framework.traits.ModernMessage
import org.json.JSONObject
import java.util.*
abstract class Expect(val stateName: String, val parent: Expect?) : ExpectContainer {
var defaultState: String? = null
var child = HashMap<String, Expect>()
private var beforeClosure: (ExpectContext.() -> Unit)? = null
fun before(before: (ExpectContext.() -> Unit)?) {
beforeClosure = before
}
open fun onReceived(context: ExpectContext) {
}
open fun onBefore(context: ExpectContext) {
if (beforeClosure != null) {
applyContext(context, beforeClosure!!)
}
}
override fun addChild(expect: Expect) {
if (defaultState == null) {
defaultState = expect.stateName
}
child.put(expect.stateName, expect)
}
protected fun applyContext(context: ExpectContext, closure: ExpectContext.() -> Unit) {
context.closure()
}
protected fun applyContext(context: ExpectContext, closure: ExpectContext.() -> Boolean): Boolean {
return context.closure()
}
fun fullName(): String {
var res = stateName
if (parent != null) {
res = parent.fullName() + "." + res
}
return res
}
override fun getContainer(): Expect? {
return this
}
}
interface ExpectContext {
var body: MagicBotMessage?
get
fun goto(stateId: String)
fun tryGoto(stateId: String): Boolean
fun gotoParent(level: Int)
fun gotoParent()
fun log(text: String)
fun sendText(text: String)
fun sendJson(dataType: String, json: JSONObject)
fun sendModernText(message: ModernMessage)
}
interface ExpectContainer {
fun addChild(expect: Expect)
fun getContainer(): Expect?
}
interface ExpectCommandContainer : ExpectContainer {
}
var ExpectContext.text: String
get() {
if (body is MagicBotTextMessage) {
return (body as MagicBotTextMessage).text!!
}
throw RuntimeException()
}
private set(v) {
}
var ExpectContext.isText: Boolean
get() {
if (body is MagicBotTextMessage) {
return (body as MagicBotTextMessage).command == null
}
return false
}
private set(v) {
}
var ExpectContext.isCommand: Boolean
get() {
if (body is MagicBotTextMessage) {
return (body as MagicBotTextMessage).command != null
}
return false
}
private set(v) {
}
var ExpectContext.command: String?
get() {
if (body is MagicBotTextMessage) {
return (body as MagicBotTextMessage).command
}
return null
}
private set(v) {
}
var ExpectContext.commandArgs: String?
get() {
if (body is MagicBotTextMessage) {
return (body as MagicBotTextMessage).commandArgs
}
return null
}
private set(v) {
}
var ExpectContext.isCancel: Boolean
get() {
return isCommand && command == "cancel"
}
private set(v) {
}
var ExpectContext.isDoc: Boolean
get() {
return body is MagicBotDocMessage
}
private set(v) {
}
var ExpectContext.doc: BotMessages.DocumentMessage
get() {
if (body is MagicBotDocMessage) {
return (body as MagicBotDocMessage).doc
}
throw RuntimeException()
}
private set(v) {
}
var ExpectContext.isSticker: Boolean
get() {
return body is MagicBotStickerMessage
}
private set(v) {
}
var ExpectContext.sticker: BotMessages.StickerMessage
get() {
if (body is MagicBotStickerMessage) {
return (body as MagicBotStickerMessage).sticker
}
throw RuntimeException()
}
private set(v) {
}
var ExpectContext.isPhoto: Boolean
get() {
if (body is MagicBotDocMessage) {
val doc = body as MagicBotDocMessage
if (doc.doc.ext.isPresent && doc.doc.ext.get() is BotMessages.DocumentExPhoto) {
return true
}
}
return false
}
private set(v) {
}
var ExpectContext.responseJson: JSONObject
get() {
if (body is MagicBotJsonMessage) {
return (body as MagicBotJsonMessage).json
}
throw RuntimeException()
}
private set(v) {
}
var ExpectContext.isJson: Boolean
get() {
return body is MagicBotJsonMessage
}
private set(v) {
} | apache-2.0 | eea9f3c7c24d9356d59c42569b967e10 | 20.418605 | 103 | 0.605343 | 4.544916 | false | false | false | false |
mopsalarm/Pr0 | model/src/main/java/com/pr0gramm/app/api/pr0gramm/Api.kt | 1 | 24785 | package com.pr0gramm.app.api.pr0gramm
import com.pr0gramm.app.Instant
import com.pr0gramm.app.model.config.Rule
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import okhttp3.RequestBody
import retrofit2.Response
import retrofit2.http.*
import java.util.*
interface Api {
@GET("/api/items/get")
suspend fun itemsGet(
@Query("promoted") promoted: Int?,
@Query("following") following: Int?,
@Query("older") older: Long?,
@Query("newer") newer: Long?,
@Query("id") around: Long?,
@Query("flags") flags: Int,
@Query("tags") tags: String?,
@Query("collection") collection: String?,
@Query("self") self: Boolean?,
@Query("user") user: String?
): Feed
@FormUrlEncoded
@POST("/api/items/vote")
suspend fun vote(
@Field("_nonce") nonce: Nonce?,
@Field("id") id: Long,
@Field("vote") voteValue: Int
)
@FormUrlEncoded
@POST("/api/tags/vote")
suspend fun voteTag(
@Field("_nonce") nonce: Nonce?,
@Field("id") id: Long,
@Field("vote") voteValue: Int
)
@FormUrlEncoded
@POST("/api/comments/vote")
suspend fun voteComment(
@Field("_nonce") nonce: Nonce?,
@Field("id") id: Long,
@Field("vote") voteValue: Int
)
@FormUrlEncoded
@POST("/api/comments/fav")
suspend fun commentsFav(
@Field("_nonce") nonce: Nonce?,
@Field("id") id: Long
)
@FormUrlEncoded
@POST("/api/comments/unfav")
suspend fun commentsUnfav(
@Field("_nonce") nonce: Nonce?,
@Field("id") id: Long
)
@FormUrlEncoded
@POST("/api/user/login")
suspend fun login(
@Field("name") username: String,
@Field("password") password: String,
@Field("token") token: String,
@Field("captcha") answer: String
): Response<Login>
@GET("/api/user/identifier")
suspend fun identifier(): Identifier
@FormUrlEncoded
@POST("/api/tags/add")
suspend fun addTags(
@Field("_nonce") nonce: Nonce?,
@Field("itemId") lastId: Long,
@Field("tags") tags: String
): NewTag
@GET("/api/tags/top")
suspend fun topTags(): TagTopList
@FormUrlEncoded
@POST("/api/comments/post")
suspend fun postComment(
@Field("_nonce") nonce: Nonce?,
@Field("itemId") itemId: Long,
@Field("parentId") parentId: Long,
@Field("comment") comment: String
): NewComment
@FormUrlEncoded
@POST("/api/comments/delete")
suspend fun hardDeleteComment(
@Field("_nonce") nonce: Nonce?,
@Field("id") commentId: Long,
@Field("reason") reason: String
)
@FormUrlEncoded
@POST("/api/comments/softDelete")
suspend fun softDeleteComment(
@Field("_nonce") nonce: Nonce?,
@Field("id") commentId: Long,
@Field("reason") reason: String
)
@GET("/api/items/info")
suspend fun info(
@Query("itemId") itemId: Long,
@Query("bust") bust: Long?
): Post
@GET("/api/user/sync")
suspend fun sync(
@Query("offset") offset: Long
): Sync
@FormUrlEncoded
@POST("/api/user/sitesettings")
suspend fun storeSettings(
@Field("_nonce") nonce: Nonce?,
@FieldMap settings: GenericSettings,
)
@GET("/api/user/info")
suspend fun accountInfo(): AccountInfo
@GET("/api/profile/info")
suspend fun info(
@Query("name") name: String,
@Query("flags") flags: Int?
): Info
@GET("/api/inbox/pending")
suspend fun inboxPending(): Inbox
@GET("/api/inbox/conversations")
suspend fun listConversations(
@Query("older") older: Long?
): Conversations
@FormUrlEncoded
@POST("/api/inbox/deleteConversation")
suspend fun deleteConversation(
@Field("_nonce") nonce: Nonce?,
@Field("recipientName") name: String
): ConversationMessages
@GET("/api/inbox/messages")
suspend fun messagesWith(
@Query("with") name: String,
@Query("older") older: Long?
): ConversationMessages
@GET("/api/inbox/comments")
suspend fun inboxComments(
@Query("older") older: Long?
): Inbox
@GET("/api/inbox/all")
suspend fun inboxAll(
@Query("older") older: Long?
): Inbox
@GET("/api/inbox/follows")
suspend fun inboxFollows(
@Query("older") older: Long?
): Inbox
@GET("/api/inbox/notifications")
suspend fun inboxNotifications(
@Query("older")
older: Long?
): Inbox
@GET("/api/profile/comments")
suspend fun userComments(
@Query("name") user: String,
@Query("before") before: Long?,
@Query("flags") flags: Int?
): UserComments
@GET("/api/profile/commentlikes")
suspend fun userCommentsLike(
@Query("name") user: String,
@Query("before") before: Long,
@Query("flags") flags: Int?
): FavedUserComments
@FormUrlEncoded
@POST("/api/inbox/post")
suspend fun sendMessage(
@Field("_nonce") nonce: Nonce?,
@Field("comment") text: String,
@Field("recipientId") recipient: Long
)
@FormUrlEncoded
@POST("/api/inbox/post")
suspend fun sendMessage(
@Field("_nonce") nonce: Nonce?,
@Field("comment") text: String,
@Field("recipientName") recipient: String
): ConversationMessages
@FormUrlEncoded
@POST("/api/inbox/read")
suspend fun markAsRead(
@Field("_nonce") nonce: Nonce?,
@Field("type") text: String,
@Field("messageId") messageId: Long,
)
@GET("/api/items/ratelimited")
suspend fun ratelimited()
@POST("/api/items/upload")
suspend fun upload(
@Body body: RequestBody
): Upload
@FormUrlEncoded
@POST("/api/items/post")
suspend fun post(
@Field("_nonce") nonce: Nonce?,
@Field("sfwstatus") sfwStatus: String,
@Field("tags") tags: String,
@Field("checkSimilar") checkSimilar: Int,
@Field("key") key: String,
@Field("processAsync") processAsync: Int?
): Posted
@GET("/api/items/queue")
suspend fun queue(
@Query("id") id: Long?
): QueueState
@FormUrlEncoded
@POST("/api/user/invite")
suspend fun invite(
@Field("_nonce") nonce: Nonce?,
@Field("email") email: String
): Invited
// Extra stuff for admins
@FormUrlEncoded
@POST("api/items/delete")
suspend fun deleteItem(
@Field("_nonce") none: Nonce?,
@Field("id") id: Long,
@Field("reason") reason: String,
@Field("customReason") customReason: String,
@Field("banUser") banUser: String?,
@Field("days") days: Float?
)
@FormUrlEncoded
@POST("backend/admin/?view=users&action=ban")
suspend fun userBan(
@Field("name") name: String,
@Field("reason") reason: String,
@Field("customReason") reasonCustom: String,
@Field("days") days: Float,
@Field("mode") mode: BanMode
)
@GET("api/tags/details")
suspend fun tagDetails(
@Query("itemId") itemId: Long
): TagDetails
@FormUrlEncoded
@POST("api/tags/delete")
suspend fun deleteTag(
@Field("_nonce") nonce: Nonce?,
@Field("itemId") itemId: Long,
@Field("banUsers") banUser: String?,
@Field("days") days: Float?,
@Field("tags[]") tagId: List<Long> = listOf()
)
@FormUrlEncoded
@POST("api/profile/follow")
suspend fun profileFollow(
@Field("_nonce") nonce: Nonce?,
@Field("name") username: String
)
@FormUrlEncoded
@POST("api/profile/subscribe")
suspend fun profileSubscribe(
@Field("_nonce") nonce: Nonce?,
@Field("name") username: String,
)
@FormUrlEncoded
@POST("api/profile/unsubscribe")
suspend fun profileUnsubscribe(
@Field("_nonce") nonce: Nonce?,
@Field("name") username: String,
@Field("keepFollow") keepFollow: Boolean? = null,
)
@GET("api/profile/suggest")
suspend fun suggestUsers(
@Query("prefix") prefix: String
): Names
@FormUrlEncoded
@POST("api/contact/send")
suspend fun contactSend(
@Field("faqCategory") faqCategory: String,
@Field("subject") subject: String,
@Field("email") email: String,
@Field("message") message: String,
@Field("extraText") extraText: String?
)
@FormUrlEncoded
@POST("api/contact/report")
suspend fun report(
@Field("_nonce") nonce: Nonce?,
@Field("itemId") item: Long,
@Field("commentId") commentId: Long,
@Field("reason") reason: String
)
@FormUrlEncoded
@POST("api/user/sendpasswordresetmail")
suspend fun requestPasswordRecovery(
@Field("email") email: String
)
@FormUrlEncoded
@POST("api/user/resetpassword")
suspend fun resetPassword(
@Field("name") name: String,
@Field("token") token: String,
@Field("password") password: String
): ResetPassword
@FormUrlEncoded
@POST("api/user/handoverrequest")
suspend fun handoverToken(
@Field("_nonce") nonce: Nonce?
): HandoverToken
@GET("api/bookmarks/get")
suspend fun bookmarks(): Bookmarks
@GET("api/bookmarks/get?default")
suspend fun defaultBookmarks(): Bookmarks
@FormUrlEncoded
@POST("api/bookmarks/add")
suspend fun bookmarksAdd(
@Field("_nonce") nonce: Nonce?,
@Field("name") name: String,
@Field("link") link: String
): Bookmarks
@FormUrlEncoded
@POST("api/bookmarks/delete")
suspend fun bookmarksDelete(
@Field("_nonce") nonce: Nonce?,
@Field("name") name: String
): Bookmarks
@GET("media/app-config.json")
suspend fun remoteConfig(@Query("bust") bust: Long): List<Rule>
@GET("api/user/captcha")
suspend fun userCaptcha(): UserCaptcha
@GET("api/collections/get?thumbs=0")
suspend fun collectionsGet(): Collections
@FormUrlEncoded
@POST("api/collections/create")
suspend fun collectionsCreate(
@Field("_nonce") nonce: Nonce?,
@Field("name") name: String,
@Field("isPublic") isPublic: Int,
@Field("isDefault") isDefault: Int
): CollectionCreated
@FormUrlEncoded
@POST("api/collections/edit")
suspend fun collectionsEdit(
@Field("_nonce") nonce: Nonce?,
@Field("collectionId") id: Long,
@Field("name") name: String,
@Field("isPublic") isPublic: Int,
@Field("isDefault") isDefault: Int
): CollectionCreated
@FormUrlEncoded
@POST("api/collections/delete")
suspend fun collectionsDelete(
@Field("_nonce") nonce: Nonce?,
@Field("collectionId") collectionId: Long
): CollectionCreated
@FormUrlEncoded
@POST("api/collections/add")
suspend fun collectionsAdd(
@Field("_nonce") nonce: Nonce?,
@Field("collectionId") collectionId: Long?,
@Field("itemId") itemId: Long
): AddToCollectionResponse
@FormUrlEncoded
@POST("api/collections/remove")
suspend fun collectionsRemove(
@Field("_nonce") nonce: Nonce?,
@Field("collectionId") collectionId: Long,
@Field("itemId") itemId: Long
): CollectionResponse
@FormUrlEncoded
@POST("api/user/validate")
suspend fun userValidate(
@Field("token") uriToken: String,
): UserValidateResponse
class Nonce(val value: String) {
override fun toString(): String = value.take(16)
}
@JsonClass(generateAdapter = true)
class Error(
val error: String,
val code: Int,
val msg: String
)
@JsonClass(generateAdapter = true)
class UserValidateResponse(
val success: Boolean = false,
)
@JsonClass(generateAdapter = true)
class CollectionResponse(
val error: String? = null
)
@JsonClass(generateAdapter = true)
class AddToCollectionResponse(
val error: String? = null,
val collectionId: Long = 0
)
@JsonClass(generateAdapter = true)
class AccountInfo(
val account: Account,
val invited: List<Invite> = listOf()
) {
@JsonClass(generateAdapter = true)
class Account(
val email: String,
val invites: Int
)
@JsonClass(generateAdapter = true)
class Invite(
val email: String,
val created: Instant,
val name: String?,
val mark: Int?
)
}
@JsonClass(generateAdapter = true)
data class Comment(
val id: Long,
val confidence: Float,
val name: String,
val content: String,
val created: Instant,
@Json(name = "parent")
val parentId: Long,
val up: Int,
val down: Int,
val mark: Int
) {
val score: Int get() = up - down
}
@JsonClass(generateAdapter = true)
data class Feed(
val error: String? = null,
@Json(name = "items") val _items: List<Item>? = null,
@Json(name = "atStart") val isAtStart: Boolean = false,
@Json(name = "atEnd") val isAtEnd: Boolean = false
) {
@Transient
val items = _items.orEmpty()
@JsonClass(generateAdapter = true)
class Item(
val id: Long,
val promoted: Long,
val userId: Long,
val image: String,
val thumb: String,
val fullsize: String,
val user: String,
val up: Int,
val down: Int,
val mark: Int,
val flags: Int,
val width: Int = 0,
val height: Int = 0,
val created: Instant,
val audio: Boolean = false,
val deleted: Boolean = false
)
}
@JsonClass(generateAdapter = true)
class Info(
val user: User,
val badges: List<Badge> = listOf(),
val collectedCount: Int,
override val collections: List<Collection> = listOf(),
override val curatorCollections: List<Collection> = listOf(),
val uploadCount: Int,
val commentCount: Int,
val tagCount: Int,
// val likesArePublic: Boolean,
// val following: Boolean,
@Json(name = "pr0mium") val premiumTime: Int,
@Json(name = "pr0miumGift") val premiumGift: Int,
val appLinks: List<AppLink>? = null
) : HasCollections {
@JsonClass(generateAdapter = true)
class Badge(
val created: Instant,
val link: String,
val image: String,
val description: String?
)
@JsonClass(generateAdapter = true)
class User(
val id: Int,
val mark: Int,
val score: Int,
val name: String,
val registered: Instant,
val banned: Boolean = false,
val bannedUntil: Instant?,
val inactive: Boolean = false,
@Json(name = "commentDelete") val commentDeleteCount: Int,
@Json(name = "itemDelete") val itemDeleteCount: Int,
val canReceiveMessages: Boolean = true
)
@JsonClass(generateAdapter = true)
class AppLink(
val text: String,
val icon: String? = null,
val link: String? = null
)
}
@JsonClass(generateAdapter = true)
class Invited(val error: String?)
@JsonClass(generateAdapter = true)
class Identifier(val identifier: String)
@JsonClass(generateAdapter = true)
class Login(
val success: Boolean? = null,
val identifier: String? = null,
val error: String? = null,
@Json(name = "ban") val banInfo: BanInfo? = null,
val settings: Map<String, Any?>? = null,
) {
@JsonClass(generateAdapter = true)
class BanInfo(
val banned: Boolean,
val reason: String,
@Json(name = "till") val endTime: Instant?
)
}
@JsonClass(generateAdapter = true)
class Inbox(val messages: List<Item> = listOf()) {
@JsonClass(generateAdapter = true)
class Item(
val type: String,
val id: Long,
val read: Boolean,
@Json(name = "created") val creationTime: Instant,
val name: String? = null,
val mark: Int? = null,
val senderId: Int? = null,
val score: Int? = null,
val itemId: Long? = null,
val message: String? = null,
val flags: Int? = null,
val image: String? = null,
@Json(name = "thumb") val thumbnail: String? = null
)
}
@JsonClass(generateAdapter = true)
class NewComment(
val commentId: Long? = null,
val comments: List<Comment> = listOf()
)
@JsonClass(generateAdapter = true)
class NewTag(
val tagIds: List<Long> = listOf(),
val tags: List<Tag> = listOf()
)
@JsonClass(generateAdapter = true)
class Post(
val tags: List<Tag> = listOf(),
val comments: List<Comment> = listOf()
)
@JsonClass(generateAdapter = true)
class QueueState(
val position: Long,
val item: Posted.PostedItem?,
val status: String
)
@JsonClass(generateAdapter = true)
class Posted(
val error: String?,
val item: PostedItem?,
val similar: List<SimilarItem> = listOf(),
val report: VideoReport?,
val queueId: Long?
) {
val itemId: Long = item?.id ?: -1
@JsonClass(generateAdapter = true)
class PostedItem(val id: Long?)
@JsonClass(generateAdapter = true)
class SimilarItem(
val id: Long,
val image: String,
@Json(name = "thumb") val thumbnail: String
)
@JsonClass(generateAdapter = true)
class VideoReport(
val duration: Float = 0f,
val height: Int = 0,
val width: Int = 0,
val format: String?,
val error: String?,
val streams: List<MediaStream> = listOf()
)
@JsonClass(generateAdapter = true)
class MediaStream(
val codec: String?,
val type: String
)
}
@JsonClass(generateAdapter = true)
class Sync(
val logLength: Long,
val log: String,
val score: Int,
val inbox: InboxCounts = InboxCounts(),
val settings: Map<String, Any?>? = null,
)
@JsonClass(generateAdapter = true)
class InboxCounts(
val comments: Int = 0,
val mentions: Int = 0,
val notifications: Int = 0,
val follows: Int = 0,
val messages: Int = 0
) {
val total: Int get() = comments + mentions + messages + notifications + follows
}
@JsonClass(generateAdapter = true)
class Tag(
val id: Long,
val confidence: Float,
@Json(name = "tag")
val text: String
) {
override fun hashCode(): Int = text.hashCode()
override fun equals(other: Any?): Boolean = other is Tag && other.text == text
}
@JsonClass(generateAdapter = true)
class Upload(val key: String)
@JsonClass(generateAdapter = true)
class UserComments(
val user: UserInfo,
val comments: List<UserComment> = listOf()
) {
@JsonClass(generateAdapter = true)
class UserComment(
val id: Long,
val itemId: Long,
val created: Instant,
val thumb: String,
val up: Int,
val down: Int,
val content: String
) {
val score: Int get() = up - down
}
@JsonClass(generateAdapter = true)
class UserInfo(
val id: Int,
val mark: Int,
val name: String
)
}
@JsonClass(generateAdapter = true)
class FavedUserComments(
val user: UserComments.UserInfo,
val comments: List<FavedUserComment> = listOf()
)
@JsonClass(generateAdapter = true)
class FavedUserComment(
val id: Long,
val itemId: Long,
val created: Instant,
val thumb: String,
val name: String,
val up: Int,
val down: Int,
val mark: Int,
val content: String,
// @Json(name = "ccreated") val commentCreated: Instant
)
@JsonClass(generateAdapter = true)
class ResetPassword(val error: String?)
@JsonClass(generateAdapter = true)
class TagDetails(
val tags: List<TagInfo> = listOf()
) {
@JsonClass(generateAdapter = true)
class TagInfo(
val id: Long,
val up: Int,
val down: Int,
val confidence: Float,
val tag: String,
val user: String,
val votes: List<Vote> = listOf()
)
@JsonClass(generateAdapter = true)
class Vote(val vote: Int, val user: String)
}
@JsonClass(generateAdapter = true)
class HandoverToken(val token: String)
@JsonClass(generateAdapter = true)
class Names(val users: List<String> = listOf())
@JsonClass(generateAdapter = true)
class TagTopList(
val tags: List<String> = listOf(),
val blacklist: List<String> = listOf()
)
@JsonClass(generateAdapter = true)
class Conversations(
val conversations: List<Conversation>,
val atEnd: Boolean
)
@JsonClass(generateAdapter = true)
data class Conversation(
val lastMessage: Instant,
val mark: Int,
val name: String,
val unreadCount: Int,
val canReceiveMessages: Boolean = true
)
@JsonClass(generateAdapter = true)
class ConversationMessages(
val atEnd: Boolean = true,
val error: String? = null,
val messages: List<ConversationMessage> = listOf(),
// Only available in GET /api/inbox/messages
val with: ConversationMessagePartner?
) {
@JsonClass(generateAdapter = true)
class ConversationMessagePartner(
val name: String,
val blocked: Boolean = false,
val canReceiveMessages: Boolean = true,
val mark: Int
)
}
@JsonClass(generateAdapter = true)
class ConversationMessage(
val id: Long,
@Json(name = "created") val creationTime: Instant,
@Json(name = "message") val messageText: String,
val sent: Boolean
)
@JsonClass(generateAdapter = true)
class Bookmarks(
val bookmarks: List<Bookmark> = listOf(),
val trending: List<Bookmark> = listOf(),
val error: String? = null
)
@JsonClass(generateAdapter = true)
class Bookmark(
val name: String,
val link: String,
val velocity: Float = 0.0f
)
@JsonClass(generateAdapter = true)
class UserCaptcha(
val token: String,
@Json(name = "captcha") val image: String
)
interface HasCollections {
val collections: List<Collection>
val curatorCollections: List<Collection>
val allCollections: List<Collection>
get() = collections + curatorCollections
}
@JsonClass(generateAdapter = true)
class Collections(
override val collections: List<Collection>,
override val curatorCollections: List<Collection>,
) : HasCollections
@JsonClass(generateAdapter = true)
class CollectionCreated(
val collectionId: Long = 0,
override val collections: List<Collection> = listOf(),
override val curatorCollections: List<Collection> = listOf(),
override val error: String? = null
) : HasError, HasCollections
@JsonClass(generateAdapter = true)
class Collection(
val id: Long,
val name: String,
val keyword: String,
val isPublic: Boolean,
val isDefault: Boolean,
val owner: String?,
val ownerMark: Int?,
// val items: List<Item>,
) {
@JsonClass(generateAdapter = true)
class Item(
val id: Long,
val thumb: String
)
}
enum class BanMode {
Default, Single, Branch;
override fun toString(): String = name.lowercase(Locale.ROOT)
}
interface HasError {
val error: String?
}
}
// To work around some quirks in moshis serialization we use java.util.Map here.
typealias GenericSettings = java.util.Map<String, Object?>
| mit | c0cb579fb6aa442c46b0b5d47b6be81d | 25.969532 | 87 | 0.575994 | 4.330014 | false | false | false | false |
qaware/kubepad | src/main/kotlin/de/qaware/cloud/nativ/kpad/launchpad/LaunchpadMK2.kt | 1 | 9603 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 QAware GmbH, Munich, Germany
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package de.qaware.cloud.nativ.kpad.launchpad
import de.qaware.cloud.nativ.kpad.launchpad.LaunchpadEvent.Switch.ON
import org.slf4j.Logger
import java.nio.charset.Charset
import java.util.*
import javax.annotation.PostConstruct
import javax.annotation.PreDestroy
import javax.enterprise.context.ApplicationScoped
import javax.enterprise.event.Event
import javax.enterprise.event.Observes
import javax.enterprise.util.AnnotationLiteral
import javax.inject.Inject
import javax.sound.midi.*
/**
* This class models the main interaction with the Novation Launchpad MK2 midi device.
*/
@ApplicationScoped
open class LaunchpadMK2 @Inject constructor(private val transmitter: Transmitter,
private val receiver: Receiver,
private val event: Event<SwitchableEvent>,
private val logger: Logger) {
/**
* Register with the Launchpad to receive MIDI messages.
*/
@PostConstruct
open fun postConstruct() {
transmitter.receiver = object : Receiver {
override fun send(message: MidiMessage, timeStamp: Long) {
if (message is ShortMessage) handle(message)
}
override fun close() {
}
}
}
private fun handle(message: ShortMessage) {
logger.debug("Handling {}[{} {} {} {}]", message, message.command, message.channel, message.data1, message.data2)
// determine the actual Switchable based in the ID in data1
val switchable = when (message.data1) {
in 104..111 -> Button.find(message.command, message.data1)
in 19..89 step 10 -> Button.find(message.command, message.data1)
else -> Square.from(message.data1)
}
when (message.data2) {
127 -> event.select(object : AnnotationLiteral<SwitchableEvent.Pressed>() {}).fire(SwitchableEvent(switchable))
else -> event.select(object : AnnotationLiteral<SwitchableEvent.Released>() {}).fire(SwitchableEvent(switchable))
}
}
/**
* Switch the light on or off for a given event.
*/
open fun light(@Observes @LaunchpadEvent.Light event: LaunchpadEvent) {
when (event.switch) {
ON -> event.switchable?.on(receiver, event.color)
else -> event.switchable?.off(receiver)
}
}
/**
* Pulse the switchable for a given event.
*/
open fun pulse(@Observes @LaunchpadEvent.Pulse event: LaunchpadEvent) {
event.switchable?.pulse(receiver, event.color)
}
/**
* Blink the switchable for a given event.
*/
open fun blink(@Observes @LaunchpadEvent.Blink event: LaunchpadEvent) {
event.switchable?.blink(receiver, event.color)
}
/**
* Write the given text event as a SysexMessage to the LaunchpadMK2. Due to a bug in the
* MacOSX JVM, this function will only work on Windows for now.
*/
open fun text(@Observes @LaunchpadEvent.Text event: LaunchpadEvent) {
val preamble = byteArrayOf(240.toByte(), 0, 32, 41, 2, 24, 20)
val text = event.text?.toByteArray(Charset.defaultCharset())
val data = ArrayList<Byte>()
data.addAll(preamble.toList())
data.add(event.color.value.toByte())
data.add(0) // do not loop
data.addAll(text!!.toList())
data.add(247.toByte())
receiver.send(SysexMessage(data.toByteArray(), data.size), -1)
}
/**
* Reset the Launchpad and turn off all the buttons.
*/
@PreDestroy
open fun reset(@Observes @LaunchpadEvent.Reset event: LaunchpadEvent) {
Button.values().forEach { it.off(receiver) }
IntRange(0, 7).forEach { r ->
IntRange(0, 7).forEach { c ->
Square(r, c).off(receiver)
}
}
}
/**
* The common interface for Switchable elements of the Launchpad.
*/
interface Switchable {
val command: Int
val id: Int
val row: Int
/**
* Turn button on by setting the color to specified value.
*
* @param receiver the MIDI receiver
* @param color the color value
*/
fun on(receiver: Receiver, color: Color) = receiver.send(ShortMessage(command, 0, id, color.value), -1)
/**
* Start blinking between the current color and the given color.
*
* @param receiver the MIDI receiver
* @param color the color value
*/
fun blink(receiver: Receiver, color: Color) = receiver.send(ShortMessage(command + 1, 1, id, color.value), -1)
/**
* Start pulsing at the given color.
*
* @param receiver the MIDI receiver
* @param color the color value
*/
fun pulse(receiver: Receiver, color: Color) = receiver.send(ShortMessage(command + 2, 2, id, color.value), -1)
/**
* Turn this color off, by setting color to zero.
*
* @param receiver the MIDI receiver
*/
fun off(receiver: Receiver) = receiver.send(ShortMessage(command, 0, id, 0), -1)
}
/**
* The buttons on our Launchpad MK2. Read the programmers reference for more details.
*
* Commands:
* - 176 are the top buttons,
* - 144 are the other buttons
*
* Id:
* - top buttons start from left with 104 to 111
* - other buttons start at the lower left corner with 11 up to 89
* - move one to the right with +1
* - move one row up with +10
*
*/
enum class Button(override val command: Int, override val id: Int, override val row: Int) : Switchable {
CURSOR_UP(176, 104, 8), CURSOR_DOWN(176, 105, 8),
CURSOR_LEFT(176, 106, 8), CURSOR_RIGHT(176, 107, 8),
/** Stop all */
SESSION(176, 108, 8),
/** Start all */
USER_1(176, 109, 8),
/** Reload all apps */
USER_2(176, 110, 8),
/** Start snake game */
MIXER(176, 111, 8),
RECORD(144, 19, 0), SOLO(144, 29, 1),
MUTE(144, 39, 2), STOP(144, 49, 3),
SEND_B(144, 59, 4), SEND_A(144, 69, 5),
PAN(144, 79, 6), VOLUME(144, 89, 7);
companion object {
/**
* Finds a Button by a given command and ID.
*
* @param command the command
* @param id the ID
* @return the button if found
*/
fun find(command: Int, id: Int) = values().find { it.command == command && it.id == id }
/**
* Get one of the top buttons by index.
*
* @param index the index between 0..7
* @return a button
*/
fun top(index: Int) = values()[index]
/**
* Get one of the right buttons by index.
*
* @param index the index between 0..7
* @return a button
*/
fun right(index: Int) = values()[index + 8]
}
}
/**
* The data class to represent the square buttons on the Launchpad.
* A square button is located by its position in the 64x64 grid identified by row and column.
* The origin of the grid is in the lower left corner.
*
* The command value for square buttons is always 144.
*
* The ID can be calculated, the lower left corner starts at 11 and advances to the right.
* Every row adds 10 to the ID value.
*/
data class Square(override val row: Int, val column: Int) : Switchable {
override val command = 144
override val id = 11 + column + 10 * row
companion object {
/**
* Create a Square from the ID.
*/
fun from(id: Int): Square {
val row = id / 10 - 1
val col = id - row * 10 - 11
if (row !in 0..7 || col !in 0..7) {
throw UnsupportedOperationException("$id is not a Square.")
}
return Square(row, col)
}
}
}
/**
* Enum class for commonly used colors.
*/
enum class Color(val value: Int) {
NONE(0),
RED(5),
ORANGE(9),
YELLOW(13),
LIGHT_GREEN(17),
CYAN(33),
LIGHT_BLUE(37),
BLUE(45),
PURPLE(53)
}
} | mit | b72d51e704d7d35ff53fe03ababd7bf3 | 33.546763 | 125 | 0.587837 | 4.317896 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/view/dialog/SimpleProgressDialogFragment.kt | 1 | 2542 | package me.ykrank.s1next.view.dialog
import android.app.Dialog
import android.app.DialogFragment
import android.app.FragmentManager
import android.app.ProgressDialog
import android.os.Bundle
import androidx.annotation.CallSuper
/**
* A [ProgressDialogFragment] subscribe a observable
*/
class SimpleProgressDialogFragment : DialogFragment() {
private var progressMsg: CharSequence? = null
private var dialogNotCancelableOnTouchOutside: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
dialogNotCancelableOnTouchOutside = arguments.getBoolean(ARG_DIALOG_NOT_CANCELABLE_ON_TOUCH_OUTSIDE, false)
progressMsg = arguments.getCharSequence(ARG_PROGRESS_MSG)
// retain this Fragment
retainInstance = true
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val progressDialog = ProgressDialog(activity)
progressDialog.setMessage(progressMsg)
//press back will remove this fragment, so set cancelable no effect
progressDialog.setCanceledOnTouchOutside(!dialogNotCancelableOnTouchOutside)
return progressDialog
}
@CallSuper
override fun onDestroyView() {
// see https://code.google.com/p/android/issues/detail?id=17423
val dialog = dialog
if (dialog != null) {
getDialog().setOnDismissListener(null)
}
super.onDestroyView()
}
companion object {
val TAG: String = SimpleProgressDialogFragment::class.java.name
private const val ARG_DIALOG_NOT_CANCELABLE_ON_TOUCH_OUTSIDE = "dialog_not_cancelable_on_touch_outside"
private const val ARG_PROGRESS_MSG = "progress_msg"
/**
* start a progress dialog to subscribe a observable and show msg (or not) after subscribed
* @param progressMsg Message show in progress dialog
* *
* @param cancelable whether dialog cancelable on touch outside
*/
fun start(fm: FragmentManager, progressMsg: CharSequence? = null, cancelable: Boolean = false): SimpleProgressDialogFragment {
val fragment = SimpleProgressDialogFragment()
val bundle = Bundle()
bundle.putCharSequence(ARG_PROGRESS_MSG, progressMsg)
bundle.putBoolean(ARG_DIALOG_NOT_CANCELABLE_ON_TOUCH_OUTSIDE, !cancelable)
fragment.arguments = bundle
fragment.show(fm, SimpleProgressDialogFragment.TAG)
return fragment
}
}
}
| apache-2.0 | 996267074ee558344c82c5757a28b3fe | 34.305556 | 134 | 0.696696 | 5.209016 | false | false | false | false |
jeffersonvenancio/BarzingaNow | android/app/src/main/java/com/barzinga/viewmodel/ItemProductViewModel.kt | 1 | 1188 | package com.barzinga.viewmodel
import android.app.Activity
import android.content.Context
import android.databinding.BaseObservable
import android.databinding.BindingAdapter
import android.widget.ImageView
import com.barzinga.model.Product
import com.bumptech.glide.Glide
import java.text.NumberFormat
import java.util.*
/**
* Created by diego.santos on 04/10/17.
*/
class ItemProductViewModel(mContext: Activity, internal var mProduct: Product) : BaseObservable() {
internal var mContext: Context
val image: String?
get() = mProduct.image_url
val name: String?
get() = mProduct.description
val price: String
get() {
val brLocale = Locale("pt", "BR")
val `in` = NumberFormat.getCurrencyInstance(brLocale)
return `in`.format(mProduct.price)
}
init {
this.mContext = mContext
}
fun setProduct(Product: Product) {
this.mProduct = Product
notifyChange()
}
companion object {
@BindingAdapter("imageUrl")
fun loadImage(view: ImageView, imageUrl: String) {
Glide.with(view.context).load(imageUrl).into(view)
}
}
} | apache-2.0 | 2cd0ac777d34e6d8c50f3a766b116fe2 | 22.313725 | 99 | 0.6633 | 4.32 | false | false | false | false |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/libraries/GivenALibrary/AndGettingTheLibraryFaults/WhenRetrievingTheLibraryConnection.kt | 2 | 3385 | package com.lasthopesoftware.bluewater.client.connection.libraries.GivenALibrary.AndGettingTheLibraryFaults
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.BuildingConnectionStatus
import com.lasthopesoftware.bluewater.client.connection.IConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.builder.live.ProvideLiveUrl
import com.lasthopesoftware.bluewater.client.connection.libraries.LibraryConnectionProvider
import com.lasthopesoftware.bluewater.client.connection.okhttp.OkHttpFactory
import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.settings.ValidateConnectionSettings
import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider
import com.lasthopesoftware.bluewater.client.connection.waking.NoopServerAlarm
import com.lasthopesoftware.bluewater.shared.promises.extensions.DeferredPromise
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
import java.io.IOException
import java.util.*
import java.util.concurrent.ExecutionException
import java.util.concurrent.TimeUnit
class WhenRetrievingTheLibraryConnection {
companion object {
private val urlProvider = mockk<IUrlProvider>()
private val statuses: MutableList<BuildingConnectionStatus> = ArrayList()
private var connectionProvider: IConnectionProvider? = null
private var exception: IOException? = null
@BeforeClass
@JvmStatic
fun before() {
val validateConnectionSettings = mockk<ValidateConnectionSettings>()
every { validateConnectionSettings.isValid(any()) } returns true
val deferredConnectionSettings = DeferredPromise<ConnectionSettings?>(IOException("OMG"))
val lookupConnection = mockk<LookupConnectionSettings>()
every {
lookupConnection.lookupConnectionSettings(LibraryId(2))
} returns deferredConnectionSettings
val liveUrlProvider = mockk<ProvideLiveUrl>()
every { liveUrlProvider.promiseLiveUrl(LibraryId(2)) } returns Promise(urlProvider)
val libraryConnectionProvider = LibraryConnectionProvider(
validateConnectionSettings,
lookupConnection,
NoopServerAlarm(),
liveUrlProvider,
OkHttpFactory
)
val futureConnectionProvider =
libraryConnectionProvider
.promiseLibraryConnection(LibraryId(2))
.apply {
progress.then(statuses::add)
updates(statuses::add)
}
.toFuture()
deferredConnectionSettings.resolve()
try {
connectionProvider = futureConnectionProvider[30, TimeUnit.SECONDS]
} catch (e: ExecutionException) {
exception = e.cause as? IOException ?: throw e
}
}
}
@Test
fun thenAConnectionProviderIsNotReturned() {
assertThat(connectionProvider).isNull()
}
@Test
fun thenAnIOExceptionIsReturned() {
assertThat(exception).isNotNull
}
@Test
fun thenGettingLibraryIsBroadcast() {
assertThat(statuses)
.containsExactly(
BuildingConnectionStatus.GettingLibrary,
BuildingConnectionStatus.GettingLibraryFailed
)
}
}
| lgpl-3.0 | 26b15c7196a329c8b7a0cb2301ad15d0 | 34.631579 | 107 | 0.815362 | 4.77433 | false | false | false | false |
colriot/anko | dsl/static/src/common/viewChildrenSequences.kt | 1 | 3099 | /*
* Copyright 2015 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.
*/
@file:JvmMultifileClass
@file:JvmName("ViewChildrenSequencesKt")
package org.jetbrains.anko
import android.view.*
import java.util.*
fun View.childrenSequence(): Sequence<View> = ViewChildrenSequence(this)
fun View.childrenRecursiveSequence(): Sequence<View> = ViewChildrenRecursiveSequence(this)
private class ViewChildrenSequence(private val view: View) : Sequence<View> {
override fun iterator(): Iterator<View> {
if (view !is ViewGroup) return emptyList<View>().iterator()
return ViewIterator(view)
}
private class ViewIterator(private val view: ViewGroup) : Iterator<View> {
private var index = 0
private val count = view.childCount
override fun next(): View {
if (!hasNext()) throw NoSuchElementException()
return view.getChildAt(index++)
}
override fun hasNext(): Boolean {
checkCount()
return index < count
}
private fun checkCount() {
if (count != view.childCount) throw ConcurrentModificationException()
}
}
}
private class ViewChildrenRecursiveSequence(private val view: View) : Sequence<View> {
override fun iterator() = RecursiveViewIterator(view)
private class RecursiveViewIterator(private val view: View) : Iterator<View> {
private val sequences = arrayListOf(sequenceOf(view))
private var itemIterator: Iterator<View>? = null
override fun next(): View {
initItemIterator()
val iterator = itemIterator ?: throw NoSuchElementException()
val view = iterator.next()
if (view is ViewGroup && view.childCount > 0) {
sequences.add(view.childrenSequence())
}
return view
}
override fun hasNext(): Boolean {
initItemIterator()
val iterator = itemIterator ?: return false
return iterator.hasNext()
}
private fun initItemIterator() {
val seqs = sequences
val iterator = itemIterator
if (iterator == null || (!iterator.hasNext() && seqs.isNotEmpty())) {
itemIterator = seqs.removeLast()?.iterator()
} else {
itemIterator = null
}
}
@Suppress("NOTHING_TO_INLINE")
private inline fun <T: Any> MutableList<T>.removeLast(): T? {
if (isEmpty()) return null
return removeAt(size - 1)
}
}
}
| apache-2.0 | dc4148d44a0e601d4829afb70fdf70a8 | 31.28125 | 90 | 0.631494 | 4.926868 | false | false | false | false |
didi/DoraemonKit | Android/app/src/main/java/com/didichuxing/doraemondemo/mc/DoKitWebView.kt | 1 | 985 | package com.didichuxing.doraemondemo.mc
import android.content.Context
import android.util.AttributeSet
import android.webkit.WebView
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2020/12/7-19:27
* 描 述:
* 修订历史:
* ================================================
*/
class DoKitWebView : WebView {
companion object {
const val TAG = "DoKitWebView"
}
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
override fun getAccessibilityClassName(): CharSequence {
return super.getAccessibilityClassName()
}
override fun getAccessibilityTraversalBefore(): Int {
return super.getAccessibilityTraversalBefore()
}
}
| apache-2.0 | 1124632155e6b0a4c8fac1670b01f9b7 | 24.378378 | 83 | 0.601704 | 4.514423 | false | false | false | false |
nickthecoder/paratask | paratask-core/src/main/kotlin/uk/co/nickthecoder/paratask/util/FileLister.kt | 1 | 7190 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.util
import java.io.File
import java.io.FileFilter
import java.io.IOException
/**
* Lists files recursively through directory tree structure.
* Each directory is sorted by the given fileComparator, which defaults to sorting by file name case insensitively.
*
* Note. If you wish to sort the whole list, rather than individual sub-directories, then set fileComparator to null,
* and sort the resulting list yourself afterwards.
*/
class FileLister(
val depth: Int = 1,
val onlyFiles: Boolean? = true, // true for files, false for directories, null for either
val extensions: List<String>? = null,
val fileComparator: (Comparator<File>)? = FileLister.CASE_INSENSITIVE,
val directoryComparator: (Comparator<File>)? = fileComparator,
val includeHidden: Boolean = false,
val enterHidden: Boolean = includeHidden,
val includeBase: Boolean = false,
val errorHandler: (Exception) -> Unit = { throw(it) }
) : Stoppable, FileFilter {
companion object {
fun matchesExtensions(file: File, extensions: List<String>): Boolean {
if (file.isDirectory) {
// We do NOT exclude directories based on file extensions.
return true
}
val lastDot = file.name.lastIndexOf('.')
if (lastDot < 0) {
return false
}
val fe = file.name.substring(lastDot + 1)
return extensions.contains(fe)
}
val CASE_INSENSITIVE: Comparator<File> = Comparator { a, b -> a.path.toLowerCase().compareTo(b.path.toLowerCase()); }
/**
* Compares files based on how their path name strings compare.
*/
val CASE_SENSITIVE: Comparator<File> = Comparator { a, b -> a.path.compareTo(b.path); }
val SIZE_ORDER = Comparator<File> { a, b -> a.length().compareTo(b.length()) }
val MODIFIED_ORDER = Comparator<File> { a, b -> a.lastModified().compareTo(b.lastModified()) }
}
var stopping: Boolean = false
override fun stop() {
stopping = true
}
fun listFiles(directory: File): List<File> {
stopping = false
val result = mutableListOf<File>()
if (includeBase) result.add(directory)
if (!directory.exists() || !directory.isDirectory) {
return result
}
fun listSingle(dir: File, level: Int) {
if (stopping || depth < level) return
val filesAndDirectories: Array<File>?
try {
filesAndDirectories = dir.listFiles(this)
if (filesAndDirectories == null) {
throw IOException("Failed to list directory $dir")
}
val files = filesAndDirectories.filter { !it.isDirectory }
val sortedFiles = if (fileComparator == null) files else files.sortedWith<File>(fileComparator)
val directories = filesAndDirectories.filter { it.isDirectory }
val sortedDirectories = if (directoryComparator == null)
directories
else
directories.sortedWith<File>(directoryComparator)
for (subDirectory in sortedDirectories) {
if (onlyFiles != true && (includeHidden || !subDirectory.isHidden)) {
result.add(subDirectory)
}
listSingle(subDirectory, level + 1)
}
for (file in sortedFiles) {
if (onlyFiles != false) {
result.add(file)
}
}
} catch (e: Exception) {
errorHandler(e)
}
}
listSingle(directory, level = 1)
return result
}
override fun accept(file: File): Boolean {
val isDirectory = file.isDirectory
if (onlyFiles == false && !isDirectory) {
return false
}
if (isDirectory) {
if (!enterHidden && !includeHidden && file.isHidden) {
return false
}
} else {
if (!includeHidden && file.isHidden) {
return false
}
if (extensions != null && extensions.isNotEmpty()) {
if (!matchesExtensions(file, extensions)) {
return false
}
}
}
return true
}
/**
* Finds the file immediately before the file given as argument, or null if 'file' was not listed, or
* was the first file in the list.
*/
fun nextFile(file: File): File? {
val files = listFiles(file.parentFile)
var found = false
for (f in files) {
if (f == file) {
found = true
} else if (found) {
return f
}
}
return null
}
/**
* Finds the file immediately after the file given as argument, or null is 'file' was not listed, or
* was the lst file in the list.
*/
fun previousFile(file: File): File? {
val files = listFiles(file.parentFile)
var found: File? = null
for (f in files) {
if (f == file) {
return found
}
found = f
}
return null
}
/**
* To make it slightly easier to use FileLister from Groovy (and Java)
*/
class Builder(
var depth: Int = 1,
var onlyFiles: Boolean? = true, // true for files, false for directories, null for either
var extensions: List<String>? = null,
var fileComparator: (Comparator<File>)? = CASE_INSENSITIVE,
var directoryComparator: (Comparator<File>)? = fileComparator,
var includeHidden: Boolean = false,
var enterHidden: Boolean = includeHidden,
var includeBase: Boolean = false,
var errorHandler: (Exception) -> Unit = { throw(it) }
) {
fun build() = FileLister(
depth = depth,
onlyFiles = onlyFiles,
extensions = extensions,
fileComparator = fileComparator,
directoryComparator = directoryComparator,
includeHidden = includeHidden,
enterHidden = enterHidden,
includeBase = includeBase,
errorHandler = errorHandler)
}
} | gpl-3.0 | d320ab39f26a289c798980651ac239ca | 32.602804 | 125 | 0.568567 | 4.931413 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/cargo/toolchain/Cargo.kt | 1 | 7352 | package org.rust.cargo.toolchain
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.intellij.execution.ExecutionException
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessHandler
import com.intellij.execution.process.ProcessListener
import com.intellij.execution.process.ProcessOutput
import com.intellij.openapi.Disposable
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PathUtil
import org.rust.cargo.CargoConstants
import org.rust.cargo.CargoConstants.RUST_BACTRACE_ENV_VAR
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.toolchain.impl.CargoMetadata
import org.rust.utils.fullyRefreshDirectory
import java.io.File
/**
* A main gateway for executing cargo commands.
*
* This class is not aware of SDKs or projects, so you'll need to provide
* paths yourself.
*
* It is impossible to guarantee that paths to the project or executables are valid,
* because the user can always just `rm ~/.cargo/bin -rf`.
*/
class Cargo(
private val pathToCargoExecutable: String,
private val pathToRustExecutable: String,
// It's more convenient to use project directory rather then path to `Cargo.toml`
// because some commands don't accept `--manifest-path` argument
private val projectDirectory: String?,
private val rustup: Rustup?
) {
/**
* Fetch all dependencies and calculate project information.
*
* This is a potentially long running operation which can
* legitimately fail due to network errors or inability
* to resolve dependencies. Hence it is mandatory to
* pass an [owner] to correctly kill the process if it
* runs for too long.
*/
@Throws(ExecutionException::class)
fun fullProjectDescription(owner: Disposable, listener: ProcessListener? = null): CargoWorkspace {
val hasAllFeatures = "--all-features" in generalCommand("metadata", listOf("--help")).execute(owner = owner).stdout
val command = generalCommand("metadata", listOf("--verbose", "--format-version", "1")).apply {
if (hasAllFeatures) addParameter("--all-features")
}
val output = command.execute(owner, listener)
val rawData = parse(output.stdout)
val projectDescriptionData = CargoMetadata.clean(rawData)
return CargoWorkspace.deserialize(projectDescriptionData)
}
@Throws(ExecutionException::class)
fun init(owner: Disposable, directory: VirtualFile) {
val path = PathUtil.toSystemDependentName(directory.path)
generalCommand("init", listOf("--bin", path)).execute(owner)
check(File(directory.path, RustToolchain.Companion.CARGO_TOML).exists())
fullyRefreshDirectory(directory)
}
fun reformatFile(owner: Disposable, file: VirtualFile, listener: ProcessListener? = null): ProcessOutput {
val result = rustfmtCommandline(file.path).execute(owner, listener)
VfsUtil.markDirtyAndRefresh(true, true, true, file)
return result
}
fun checkProject(owner: Disposable) = checkCommandline().execute(owner, ignoreExitCode = true)
fun generalCommand(commandLine: CargoCommandLine): GeneralCommandLine {
val env = when (commandLine.backtraceMode) {
BacktraceMode.SHORT -> mapOf(RUST_BACTRACE_ENV_VAR to "short")
BacktraceMode.FULL -> mapOf(RUST_BACTRACE_ENV_VAR to "full")
else -> emptyMap()
} + commandLine.environmentVariables
val args = commandLine.additionalArguments.toMutableList()
if (commandLine.command == "test" && commandLine.nocapture && "--nocapture" !in args) {
if ("--" !in args) {
args += "--"
}
args += "--nocapture"
}
return generalCommand(commandLine.command, args, env, commandLine.channel)
}
fun generalCommand(
command: String,
additionalArguments: List<String> = emptyList(),
environmentVariables: Map<String, String> = emptyMap(),
channel: RustChannel = RustChannel.DEFAULT
): GeneralCommandLine {
val cmdLine = if (channel == RustChannel.DEFAULT) {
GeneralCommandLine(pathToCargoExecutable)
} else {
if (rustup == null) error("Channel '$channel' cannot be set explicitly because rustup is not avaliable")
rustup.createRunCommandLine(channel, pathToCargoExecutable)
}
cmdLine.withCharset(Charsets.UTF_8)
.withWorkDirectory(projectDirectory)
.withParameters(command)
// Make output colored
if (!SystemInfo.isWindows
&& command in COLOR_ACCEPTING_COMMANDS
&& additionalArguments.none { it.startsWith("--color") }) {
cmdLine
.withEnvironment("TERM", "ansi")
.withRedirectErrorStream(true)
.withParameters("--color=always") // Must come first in order not to corrupt the running program arguments
}
return cmdLine
.withEnvironment(CargoConstants.RUSTC_ENV_VAR, pathToRustExecutable)
.withEnvironment(environmentVariables)
.withParameters(additionalArguments)
}
fun clippyCommandLine(channel: RustChannel): CargoCommandLine =
CargoCommandLine("clippy", channel = channel)
private fun rustfmtCommandline(filePath: String) =
generalCommand("fmt").withParameters("--", "--write-mode=overwrite", "--skip-children", filePath)
fun checkCommandline() = generalCommand("check").withParameters("--message-format=json", "--all")
private fun GeneralCommandLine.execute(owner: Disposable, listener: ProcessListener? = null,
ignoreExitCode: Boolean = false): ProcessOutput {
val handler = CapturingProcessHandler(this)
val cargoKiller = Disposable {
// Don't attempt a graceful termination, Cargo can be SIGKILLed safely.
// https://github.com/rust-lang/cargo/issues/3566
handler.destroyProcess()
}
Disposer.register(owner, cargoKiller)
listener?.let { handler.addProcessListener(it) }
val output = try {
handler.runProcess()
} finally {
Disposer.dispose(cargoKiller)
}
if (!ignoreExitCode && output.exitCode != 0) {
throw ExecutionException("""
Cargo execution failed (exit code ${output.exitCode}).
$commandLineString
stdout : ${output.stdout}
stderr : ${output.stderr}""".trimIndent())
}
return output
}
private fun parse(output: String): CargoMetadata.Project {
// Skip "Downloading..." stuff
val json = output.dropWhile { it != '{' }
return try {
Gson().fromJson(json, CargoMetadata.Project::class.java)
} catch(e: JsonSyntaxException) {
throw ExecutionException(e)
}
}
private companion object {
val COLOR_ACCEPTING_COMMANDS = listOf("bench", "build", "check", "clean", "clippy", "doc", "install", "publish", "run", "rustc", "test", "update")
}
}
| mit | ddcafa7287fb76a3c76620a4b5ff1751 | 40.303371 | 154 | 0.668934 | 4.89155 | false | false | false | false |
kotlin-graphics/imgui | core/src/main/kotlin/imgui/internal/api/newFrame.kt | 2 | 8827 | package imgui.internal.api
import glm_.f
import imgui.*
import imgui.ImGui.clearActiveID
import imgui.ImGui.closePopupsOverWindow
import imgui.ImGui.focusWindow
import imgui.ImGui.io
import imgui.ImGui.isMousePosValid
import imgui.ImGui.isPopupOpen
import imgui.ImGui.keepAliveID
import imgui.ImGui.topMostPopupModal
import imgui.api.g
import imgui.static.findHoveredWindow
/** NewFrame */
internal interface newFrame {
/** The reason this is exposed in imgui_internal.h is: on touch-based system that don't have hovering,
* we want to dispatch inputs to the right target (imgui vs imgui+app) */
fun updateHoveredWindowAndCaptureFlags() {
// Find the window hovered by mouse:
// - Child windows can extend beyond the limit of their parent so we need to derive HoveredRootWindow from HoveredWindow.
// - When moving a window we can skip the search, which also conveniently bypasses the fact that window->WindowRectClipped is lagging as this point of the frame.
// - We also support the moved window toggling the NoInputs flag after moving has started in order to be able to detect windows below it, which is useful for e.g. docking mechanisms.
var clearHoveredWindows = false
findHoveredWindow()
// Modal windows prevents mouse from hovering behind them.
val modalWindow = topMostPopupModal
val hovered = g.hoveredRootWindow
if (modalWindow != null && hovered != null && !hovered.isChildOf(modalWindow))
clearHoveredWindows = true
// Disabled mouse?
if (io.configFlags has ConfigFlag.NoMouse)
clearHoveredWindows = true
// We track click ownership. When clicked outside of a window the click is owned by the application and won't report hovering nor request capture even while dragging over our windows afterward.
var mouseEarliestButtonDown = -1
var mouseAnyDown = false
for (i in io.mouseDown.indices) {
if (io.mouseClicked[i])
io.mouseDownOwned[i] = g.hoveredWindow != null || g.openPopupStack.isNotEmpty()
mouseAnyDown = mouseAnyDown || io.mouseDown[i]
if (io.mouseDown[i])
if (mouseEarliestButtonDown == -1 || io.mouseClickedTime[i] < io.mouseClickedTime[mouseEarliestButtonDown])
mouseEarliestButtonDown = i
}
val mouseAvailToImgui = mouseEarliestButtonDown == -1 || io.mouseDownOwned[mouseEarliestButtonDown]
// If mouse was first clicked outside of ImGui bounds we also cancel out hovering.
// FIXME: For patterns of drag and drop across OS windows, we may need to rework/remove this test (first committed 311c0ca9 on 2015/02)
val mouseDraggingExternPayload = g.dragDropActive && g.dragDropSourceFlags has DragDropFlag.SourceExtern
if (!mouseAvailToImgui && !mouseDraggingExternPayload)
clearHoveredWindows = true
if(clearHoveredWindows) {
g.hoveredWindow = null
g.hoveredRootWindow = null
g.hoveredWindowUnderMovingWindow = null
}
// Update io.WantCaptureMouse for the user application (true = dispatch mouse info to Dear ImGui, false = dispatch mouse info to imgui + app)
if (g.wantCaptureMouseNextFrame != -1)
io.wantCaptureMouse = g.wantCaptureMouseNextFrame != 0
else
io.wantCaptureMouse = (mouseAvailToImgui && (g.hoveredWindow != null || mouseAnyDown)) || g.openPopupStack.isNotEmpty()
// Update io.WantCaptureKeyboard for the user application (true = dispatch keyboard info to Dear ImGui, false = dispatch keyboard info to imgui + app)
if (g.wantCaptureKeyboardNextFrame != -1)
io.wantCaptureKeyboard = g.wantCaptureKeyboardNextFrame != 0
else
io.wantCaptureKeyboard = g.activeId != 0 || modalWindow != null
if (io.navActive && io.configFlags has ConfigFlag.NavEnableKeyboard && io.configFlags hasnt ConfigFlag.NavNoCaptureKeyboard)
io.wantCaptureKeyboard = true
// Update io.WantTextInput flag, this is to allow systems without a keyboard (e.g. mobile, hand-held) to show a software keyboard if possible
io.wantTextInput = if (g.wantTextInputNextFrame != -1) g.wantTextInputNextFrame != 0 else false
}
/** Handle mouse moving window
* Note: moving window with the navigation keys (Square + d-pad / CTRL+TAB + Arrows) are processed in NavUpdateWindowing()
* FIXME: We don't have strong guarantee that g.MovingWindow stay synched with g.ActiveId == g.MovingWindow->MoveId.
* This is currently enforced by the fact that BeginDragDropSource() is setting all g.ActiveIdUsingXXXX flags to inhibit navigation inputs,
* but if we should more thoroughly test cases where g.ActiveId or g.MovingWindow gets changed and not the other. */
fun updateMouseMovingWindowNewFrame() {
val mov = g.movingWindow
if (mov != null) {
/* We actually want to move the root window. g.movingWindow === window we clicked on
(could be a child window).
We track it to preserve Focus and so that generally activeIdWindow === movingWindow and
activeId == movingWindow.moveId for consistency. */
keepAliveID(g.activeId)
assert(mov.rootWindow != null)
val movingWindow = mov.rootWindow!!
if (io.mouseDown[0] && isMousePosValid(io.mousePos)) {
val pos = io.mousePos - g.activeIdClickOffset
if (movingWindow.pos.x.f != pos.x || movingWindow.pos.y.f != pos.y) {
movingWindow.markIniSettingsDirty()
movingWindow.setPos(pos, Cond.Always)
}
focusWindow(mov)
} else {
clearActiveID()
g.movingWindow = null
}
} else
/* When clicking/dragging from a window that has the _NoMove flag, we still set the ActiveId in order
to prevent hovering others. */
if (g.activeIdWindow?.moveId == g.activeId) {
keepAliveID(g.activeId)
if (!io.mouseDown[0])
clearActiveID()
}
}
/** Initiate moving window, handle left-click and right-click focus
* Handle left-click and right-click focus. */
fun updateMouseMovingWindowEndFrame() {
if (g.activeId != 0 || g.hoveredId != 0) return
// Unless we just made a window/popup appear
if (g.navWindow?.appearing == true) return
// Click on empty space to focus window and start moving (after we're done with all our widgets)
if (io.mouseClicked[0]) {
// Handle the edge case of a popup being closed while clicking in its empty space.
// If we try to focus it, FocusWindow() > ClosePopupsOverWindow() will accidentally close any parent popups because they are not linked together any more.
val rootWindow = g.hoveredRootWindow
val isClosedPopup = rootWindow != null && rootWindow.flags has WindowFlag._Popup && !isPopupOpen(rootWindow.popupId, PopupFlag.AnyPopupLevel.i)
if (rootWindow != null && !isClosedPopup) {
g.hoveredWindow!!.startMouseMoving() //-V595
// Cancel moving if clicked outside of title bar
if (io.configWindowsMoveFromTitleBarOnly && rootWindow.flags hasnt WindowFlag.NoTitleBar)
if (io.mouseClickedPos[0] !in rootWindow.titleBarRect())
g.movingWindow = null
// Cancel moving if clicked over an item which was disabled or inhibited by popups (note that we know HoveredId == 0 already)
if (g.hoveredIdDisabled)
g.movingWindow = null
}
else if (rootWindow == null && g.navWindow != null && topMostPopupModal == null)
focusWindow() // Clicking on void disable focus
}
/* With right mouse button we close popups without changing focus based on where the mouse is aimed
Instead, focus will be restored to the window under the bottom-most closed popup.
(The left mouse button path calls FocusWindow on the hovered window, which will lead NewFrame->ClosePopupsOverWindow to trigger) */
if (io.mouseClicked[1]) {
// Find the top-most window between HoveredWindow and the top-most Modal Window.
// This is where we can trim the popup stack.
val modal = topMostPopupModal
val hoveredWindowAboveModal = g.hoveredWindow?.isAbove(modal) == true
closePopupsOverWindow(if (hoveredWindowAboveModal) g.hoveredWindow else modal, true)
}
}
} | mit | f77c3d7c6587dab901939a3c6c34bf8b | 53.493827 | 201 | 0.657641 | 4.727906 | false | false | false | false |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/dialog/RxDialog.kt | 1 | 3425 | package com.tamsiree.rxui.view.dialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.view.Gravity
import android.view.ViewGroup
import android.view.Window
import android.view.WindowManager
import com.tamsiree.rxui.R
/**
* @author tamsiree
*/
open class RxDialog : Dialog {
protected lateinit var mContext: Context
var layoutParams: WindowManager.LayoutParams? = null
constructor(context: Context, themeResId: Int) : super(context, themeResId) {
initView(context)
}
constructor(context: Context, cancelable: Boolean, cancelListener: DialogInterface.OnCancelListener?) : super(context, cancelable, cancelListener) {
initView(context)
}
constructor(context: Context) : super(context) {
initView(context)
}
private fun initView(context: Context) {
requestWindowFeature(Window.FEATURE_NO_TITLE)
window?.setBackgroundDrawableResource(R.drawable.transparent_bg)
mContext = context
val window = this.window
layoutParams = window!!.attributes
layoutParams?.alpha = 1f
window.attributes = layoutParams
if (layoutParams != null) {
layoutParams?.height = ViewGroup.LayoutParams.MATCH_PARENT
layoutParams?.gravity = Gravity.CENTER
}
}
/**
* @param context 实体
* @param alpha 透明度 0.0f--1f(不透明)
* @param gravity 方向(Gravity.BOTTOM,Gravity.TOP,Gravity.LEFT,Gravity.RIGHT)
*/
constructor(context: Context?, alpha: Float, gravity: Int) : super(context!!) {
requestWindowFeature(Window.FEATURE_NO_TITLE)
window?.setBackgroundDrawableResource(R.drawable.transparent_bg)
mContext = context
val window = this.window
layoutParams = window!!.attributes
layoutParams?.alpha = 1f
window.attributes = layoutParams
if (layoutParams != null) {
layoutParams?.height = ViewGroup.LayoutParams.MATCH_PARENT
layoutParams?.gravity = gravity
}
}
/**
* 隐藏头部导航栏状态栏
*/
fun skipTools() {
window?.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN)
}
/**
* 设置全屏显示
*/
fun setFullScreen() {
val window = window!!
window.decorView.setPadding(0, 0, 0, 0)
val lp = window.attributes
lp.width = WindowManager.LayoutParams.FILL_PARENT
lp.height = WindowManager.LayoutParams.FILL_PARENT
window.attributes = lp
}
/**
* 设置宽度match_parent
*/
fun setFullScreenWidth() {
val window = window!!
window.decorView.setPadding(0, 0, 0, 0)
val lp = window.attributes
lp.width = WindowManager.LayoutParams.FILL_PARENT
lp.height = WindowManager.LayoutParams.WRAP_CONTENT
window.attributes = lp
}
/**
* 设置高度为match_parent
*/
fun setFullScreenHeight() {
val window = window!!
window.decorView.setPadding(0, 0, 0, 0)
val lp = window.attributes
lp.width = WindowManager.LayoutParams.WRAP_CONTENT
lp.height = WindowManager.LayoutParams.FILL_PARENT
window.attributes = lp
}
fun setOnWhole() {
window?.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
}
} | apache-2.0 | 55e538ed5630e6eff31e56d32fc27bc6 | 29.234234 | 152 | 0.653949 | 4.533784 | false | false | false | false |
Ribesg/anko | dsl/src/org/jetbrains/android/anko/generator/viewClassGenerators.kt | 4 | 1562 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko.generator
import org.jetbrains.android.anko.utils.isAbstract
import org.objectweb.asm.tree.ClassNode
abstract class AbstractViewGenerator(private val forLayouts: Boolean) : Generator<ViewElement> {
override fun generate(state: GenerationState) = with (state) {
fun ClassNode.isViewGroupWithParams() = isViewGroup && hasLayoutParams(this)
state.availableClasses
.filter { it.isView && forLayouts == it.isViewGroupWithParams() }
.map { ViewElement(it, if (forLayouts) true else it.isViewGroup, { it.resolveAllMethods() }) }
.sortedBy { it.clazz.name }
}
private fun GenerationState.hasLayoutParams(viewGroup: ClassNode): Boolean {
return !viewGroup.isAbstract && extractLayoutParams(viewGroup) != null
}
}
class ViewGenerator : AbstractViewGenerator(forLayouts = false)
class ViewGroupGenerator : AbstractViewGenerator(forLayouts = true) | apache-2.0 | 8d5acdf9b94cc4dbd48a5146f1bc26f0 | 38.075 | 110 | 0.729193 | 4.38764 | false | false | false | false |
Ribesg/anko | dsl/src/org/jetbrains/android/anko/Main.kt | 1 | 3627 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.android.anko
import org.jetbrains.android.anko.config.DefaultAnkoConfiguration
import org.jetbrains.android.anko.config.GeneratorOption
import org.jetbrains.android.anko.utils.AndroidVersionDirectoryFilter
import org.jetbrains.android.anko.utils.JarFileFilter
import java.io.File
object Launcher {
@JvmStatic
fun main(args: Array<String>) {
val generatorOptions = System.getProperty("gen.options", "")
.split(',')
.map { GeneratorOption.parse(it) }
.filterNotNull()
.toSet()
if (args.isNotEmpty()) {
args.forEach { taskName ->
println(":: $taskName")
when (taskName) {
"gen", "generate" -> gen(generatorOptions)
"clean" -> clean()
"versions" -> versions()
else -> {
println("Invalid task $taskName")
return
}
}
}
println("Done.")
} else gen(generatorOptions)
}
}
private fun clean() {
deleteDirectory(File("workdir/gen/"))
}
private fun versions() {
for (version in getVersionDirs()) {
val (platformJars, versionJars) = getJars(version)
println("${version.name}")
(platformJars + versionJars).forEach { println(" ${it.name}") }
}
}
private fun deleteDirectory(f: File) {
if (!f.exists()) return
if (f.isDirectory) {
f.listFiles()?.forEach { deleteDirectory(it) }
}
if (!f.delete()) {
throw RuntimeException("Failed to delete ${f.absolutePath}")
}
}
private fun getVersionDirs(): Array<File> {
val original = File("workdir/original/")
if (!original.exists() || !original.isDirectory) {
throw RuntimeException("\"workdir/original\" directory does not exist.")
}
return original.listFiles(AndroidVersionDirectoryFilter()) ?: arrayOf<File>()
}
private fun getJars(version: File) = version.listFiles(JarFileFilter()).partition { it.name.startsWith("platform.") }
private fun gen(generatorOptions: Set<GeneratorOption>) {
for (versionDir in getVersionDirs()) {
val (platformJars, versionJars) = getJars(versionDir)
val versionName = versionDir.name
if (platformJars.isNotEmpty()) {
println("Processing version $versionName")
println(" Platform jars: ${platformJars.joinToString()}")
if (versionJars.isNotEmpty()) println(" Version jars: ${versionJars.joinToString()}")
val outputDirectory = File("workdir/gen/$versionName/")
val fileOutputDirectory = File(outputDirectory, "src/main/kotlin/")
if (!fileOutputDirectory.exists()) {
fileOutputDirectory.mkdirs()
}
DSLGenerator(versionDir, platformJars, versionJars,
DefaultAnkoConfiguration(outputDirectory, versionName, generatorOptions)).run()
}
}
} | apache-2.0 | 8c3ade26ec169a7ecc12e634ee45225a | 33.552381 | 117 | 0.622002 | 4.741176 | false | false | false | false |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-standard/src/main/kotlin/ch/schulealtendorf/psa/service/standard/manager/GroupManagerImpl.kt | 1 | 5634 | /*
* Copyright (c) 2018 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Sporttag PSA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.standard.manager
import ch.schulealtendorf.psa.dto.group.GroupStatusType
import ch.schulealtendorf.psa.dto.group.OverviewGroupDto
import ch.schulealtendorf.psa.dto.group.SimpleGroupDto
import ch.schulealtendorf.psa.dto.participation.ATHLETICS
import ch.schulealtendorf.psa.dto.status.StatusDto
import ch.schulealtendorf.psa.dto.status.StatusEntry
import ch.schulealtendorf.psa.dto.status.StatusSeverity
import ch.schulealtendorf.psa.service.standard.entity.GroupEntity
import ch.schulealtendorf.psa.service.standard.entity.ParticipantEntity
import ch.schulealtendorf.psa.service.standard.repository.GroupRepository
import ch.schulealtendorf.psa.service.standard.repository.ParticipantRepository
import ch.schulealtendorf.psa.service.standard.simpleGroupDtoOf
import org.springframework.stereotype.Component
import java.util.Optional
/**
* A {@link GroupManager} which uses repositories to process its data.
*
* @author nmaerchy <[email protected]>
* @since 2.0.0
*/
@Component
class GroupManagerImpl(
private val groupRepository: GroupRepository,
private val participantRepository: ParticipantRepository
) : GroupManager {
override fun hasPendingParticipation(group: SimpleGroupDto): Boolean {
val participants = participantRepository.findByGroupName(group.name)
return hasPendingParticipation(participants)
}
override fun isCompetitive(group: SimpleGroupDto): Boolean {
val participants = participantRepository.findByGroupName(group.name)
return hasCompetitors(participants)
}
override fun getGroup(name: String): Optional<SimpleGroupDto> {
return groupRepository.findById(name)
.map { it.toDto() }
}
override fun getGroups(): List<SimpleGroupDto> {
return groupRepository.findAll()
.map { it.toDto() }
}
override fun getGroupsBy(filter: GroupStatusType): List<SimpleGroupDto> {
return getOverviewBy(filter)
.map { it.group }
}
override fun getOverview(): List<OverviewGroupDto> {
return groupRepository.findAll()
.map { it.toOverview() }
}
override fun getOverviewBy(filter: GroupStatusType): List<OverviewGroupDto> {
return getOverview()
.filter { it.status.contains(filter) }
}
private fun hasPendingParticipation(participants: List<ParticipantEntity>): Boolean {
return participants.any { it.sport == null }
}
private fun hasCompetitors(participants: List<ParticipantEntity>): Boolean {
return participants.any { it.isCompetitive() }
}
private fun hasNonCompetitors(participants: List<ParticipantEntity>): Boolean {
return participants.any { it.isCompetitive().not() }
}
private fun ParticipantEntity.isCompetitive() = sport != null && sport?.name == ATHLETICS
private fun GroupEntity.toDto() = simpleGroupDtoOf(this)
private fun GroupEntity.toOverview(): OverviewGroupDto {
var severity = StatusSeverity.OK
val statusList = ArrayList<StatusEntry>()
val participants = participantRepository.findByGroupName(name)
if (hasPendingParticipation(participants)) {
severity = StatusSeverity.INFO
statusList.add(
StatusEntry(
StatusSeverity.INFO,
GroupStatusType.UNFINISHED_PARTICIPANTS
)
)
}
if (hasCompetitors(participants)) {
statusList.add(
StatusEntry(
StatusSeverity.INFO,
GroupStatusType.GROUP_TYPE_COMPETITIVE
)
)
}
if (hasNonCompetitors(participants)) {
statusList.add(
StatusEntry(
StatusSeverity.INFO,
GroupStatusType.GROUP_TYPE_FUN
)
)
}
return OverviewGroupDto(
this.toDto(),
StatusDto(
severity,
statusList
)
)
}
}
| gpl-3.0 | 4162f7acdea8147fc483acc5d7ded706 | 33.931677 | 93 | 0.691501 | 4.823328 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/analytics/LinkPreviewFunnel.kt | 1 | 1094 | package org.wikipedia.analytics
import org.json.JSONObject
import org.wikipedia.WikipediaApp
import org.wikipedia.settings.Prefs
class LinkPreviewFunnel(app: WikipediaApp, private val source: Int) : TimedFunnel(app, SCHEMA_NAME, REV_ID, SAMPLE_LOG_ALL) {
private var pageId = 0
override fun preprocessData(eventData: JSONObject): JSONObject {
preprocessData(eventData, "version", PROD_LINK_PREVIEW_VERSION)
preprocessData(eventData, "source", source)
preprocessData(eventData, "page_id", pageId)
return super.preprocessData(eventData)
}
fun setPageId(pageId: Int) {
this.pageId = pageId
}
fun logLinkClick() {
log("action", "linkclick")
}
fun logNavigate() {
log("action", if (Prefs.isLinkPreviewEnabled) "navigate" else "disabled")
}
fun logCancel() {
log("action", "cancel")
}
companion object {
private const val SCHEMA_NAME = "MobileWikiAppLinkPreview"
private const val REV_ID = 23808516
private const val PROD_LINK_PREVIEW_VERSION = 3
}
}
| apache-2.0 | 57ae111ce02887a8e09475918a171019 | 27.051282 | 125 | 0.670018 | 4.112782 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/wiktionary/WiktionaryDialog.kt | 1 | 8005 | package org.wikipedia.wiktionary
import android.content.DialogInterface
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.os.bundleOf
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.schedulers.Schedulers
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.FragmentUtil
import org.wikipedia.analytics.WiktionaryDialogFunnel
import org.wikipedia.databinding.DialogWiktionaryBinding
import org.wikipedia.databinding.ItemWiktionaryDefinitionWithExamplesBinding
import org.wikipedia.databinding.ItemWiktionaryDefinitionsListBinding
import org.wikipedia.databinding.ItemWiktionaryExampleBinding
import org.wikipedia.dataclient.ServiceFactory
import org.wikipedia.dataclient.WikiSite
import org.wikipedia.dataclient.restbase.RbDefinition
import org.wikipedia.dataclient.restbase.RbDefinition.Usage
import org.wikipedia.page.ExtendedBottomSheetDialogFragment
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.page.PageTitle
import org.wikipedia.util.L10nUtil
import org.wikipedia.util.StringUtil
import org.wikipedia.util.log.L
import java.util.*
class WiktionaryDialog : ExtendedBottomSheetDialogFragment() {
interface Callback {
fun wiktionaryShowDialogForTerm(term: String)
}
private var _binding: DialogWiktionaryBinding? = null
private val binding get() = _binding!!
private lateinit var pageTitle: PageTitle
private lateinit var selectedText: String
private var currentDefinition: RbDefinition? = null
private var funnel: WiktionaryDialogFunnel? = null
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
pageTitle = requireArguments().getParcelable(TITLE)!!
selectedText = requireArguments().getString(SELECTED_TEXT)!!
}
override fun onDestroyView() {
disposables.clear()
_binding = null
super.onDestroyView()
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
_binding = DialogWiktionaryBinding.inflate(inflater, container, false)
binding.wiktionaryDefinitionDialogTitle.text = sanitizeForDialogTitle(selectedText)
L10nUtil.setConditionalLayoutDirection(binding.root, pageTitle.wikiSite.languageCode)
loadDefinitions()
funnel = WiktionaryDialogFunnel(WikipediaApp.instance, selectedText)
return binding.root
}
override fun onDismiss(dialogInterface: DialogInterface) {
super.onDismiss(dialogInterface)
funnel?.logClose()
}
private fun loadDefinitions() {
if (selectedText.trim().isEmpty()) {
displayNoDefinitionsFound()
return
}
// TODO: centralize the Wiktionary domain better. Maybe a SharedPreference that defaults to
val finalSelectedText = StringUtil.addUnderscores(selectedText)
disposables.add(ServiceFactory.getRest(WikiSite(pageTitle.wikiSite.subdomain() + WIKTIONARY_DOMAIN)).getDefinition(finalSelectedText)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn {
L.w("Cannot find the definition. Try to use lowercase text.")
ServiceFactory.getRest(WikiSite(pageTitle.wikiSite.subdomain() + WIKTIONARY_DOMAIN))
.getDefinition(finalSelectedText.lowercase(Locale.getDefault())).blockingFirst()
}
.map { usages -> RbDefinition(usages) }
.subscribe({ definition ->
binding.dialogWiktionaryProgress.visibility = View.GONE
currentDefinition = definition
layOutDefinitionsByUsage()
}) { throwable ->
displayNoDefinitionsFound()
L.e(throwable)
})
}
private fun displayNoDefinitionsFound() {
binding.wiktionaryNoDefinitionsFound.visibility = View.VISIBLE
binding.dialogWiktionaryProgress.visibility = View.GONE
}
private fun layOutDefinitionsByUsage() {
currentDefinition?.usagesByLang?.get("en")?.let { usageList ->
if (usageList.isNullOrEmpty()) {
displayNoDefinitionsFound()
return
}
usageList.forEach {
binding.wiktionaryDefinitionsByPartOfSpeech.addView(layOutUsage(it))
}
}
}
private fun layOutUsage(currentUsage: Usage): View {
val usageBinding = ItemWiktionaryDefinitionsListBinding.inflate(LayoutInflater.from(context), binding.root, false)
usageBinding.wiktionaryPartOfSpeech.text = currentUsage.partOfSpeech
for (i in currentUsage.definitions.indices) {
usageBinding.listWiktionaryDefinitionsWithExamples.addView(layOutDefinitionWithExamples(currentUsage.definitions[i], i + 1))
}
return usageBinding.root
}
private fun layOutDefinitionWithExamples(currentDefinition: RbDefinition.Definition, count: Int): View {
val definitionBinding = ItemWiktionaryDefinitionWithExamplesBinding.inflate(LayoutInflater.from(context), binding.root, false)
val definitionWithCount = "$count. ${currentDefinition.definition}"
definitionBinding.wiktionaryDefinition.text = StringUtil.fromHtml(definitionWithCount)
definitionBinding.wiktionaryDefinition.movementMethod = linkMovementMethod
currentDefinition.examples?.forEach {
definitionBinding.wiktionaryExamples.addView(layoutExamples(it))
}
return definitionBinding.root
}
private fun layoutExamples(example: String): View {
val exampleBinding = ItemWiktionaryExampleBinding.inflate(LayoutInflater.from(context), binding.root, false)
exampleBinding.itemWiktionaryExample.text = StringUtil.fromHtml(example)
exampleBinding.itemWiktionaryExample.movementMethod = linkMovementMethod
return exampleBinding.root
}
private val linkMovementMethod = LinkMovementMethodExt { url: String ->
if (url.startsWith(PATH_WIKI) || url.startsWith(PATH_CURRENT)) {
dismiss()
showNewDialogForLink(url)
}
}
private fun getTermFromWikiLink(url: String): String {
return removeLinkFragment(url.substring(url.lastIndexOf("/") + 1))
}
private fun removeLinkFragment(url: String): String {
val splitUrl = url.split('#')
return if (splitUrl[0].endsWith(GLOSSARY_OF_TERMS) && splitUrl.size > 1) splitUrl[1] else splitUrl[0]
}
private fun showNewDialogForLink(url: String) {
callback()?.wiktionaryShowDialogForTerm(getTermFromWikiLink(url))
}
private fun sanitizeForDialogTitle(text: String?): String {
return StringUtil.removeUnderscores(StringUtil.removeSectionAnchor(text))
}
private fun callback(): Callback? {
return FragmentUtil.getCallback(this, Callback::class.java)
}
companion object {
private const val WIKTIONARY_DOMAIN = ".wiktionary.org"
private const val TITLE = "title"
private const val SELECTED_TEXT = "selected_text"
private const val PATH_WIKI = "/wiki/"
private const val PATH_CURRENT = "./"
// Try to get the correct definition from glossary terms: https://en.wiktionary.org/wiki/Appendix:Glossary
private const val GLOSSARY_OF_TERMS = ":Glossary"
val enabledLanguages = listOf("en")
fun newInstance(title: PageTitle, selectedText: String): WiktionaryDialog {
return WiktionaryDialog().apply {
arguments = bundleOf(TITLE to title, SELECTED_TEXT to selectedText)
}
}
}
}
| apache-2.0 | f007bd2076e2018dbb612444cd666864 | 41.131579 | 141 | 0.705934 | 5.430801 | false | false | false | false |
alexcustos/linkasanote | app/src/main/java/com/bytesforge/linkasanote/sync/SyncState.kt | 1 | 7784 | /*
* LaaNo Android application
*
* @author Aleksandr Borisenko <[email protected]>
* Copyright (C) 2017 Aleksandr Borisenko
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bytesforge.linkasanote.sync
import android.content.ContentValues
import android.database.Cursor
import android.os.Parcel
import android.os.Parcelable
import com.bytesforge.linkasanote.data.source.local.BaseEntry
import com.google.common.base.Objects
class SyncState : Parcelable {
val rowId: Long
val duplicated: Int
val isConflicted: Boolean
val isDeleted: Boolean
val isSynced: Boolean
var eTag: String?
private set
override fun describeContents(): Int {
return super.hashCode()
}
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeLong(rowId)
dest.writeString(eTag)
dest.writeInt(duplicated)
dest.writeInt(if (isConflicted) 1 else 0)
dest.writeInt(if (isDeleted) 1 else 0)
dest.writeInt(if (isSynced) 1 else 0)
}
enum class State {
UNSYNCED, SYNCED, DELETED, CONFLICTED_UPDATE, CONFLICTED_DELETE
}
constructor() : this(-1, null, 0, false, false, false) {
// UNSYNCED
}
private constructor(
rowId: Long, eTag: String?,
duplicated: Int, conflicted: Boolean, deleted: Boolean, synced: Boolean
) {
this.rowId = rowId
this.eTag = eTag
this.duplicated = duplicated
isConflicted = conflicted
isDeleted = deleted
isSynced = synced
}
private constructor(source: Parcel) {
rowId = source.readLong()
eTag = source.readString()
duplicated = source.readInt()
isConflicted = source.readInt() != 0
isDeleted = source.readInt() != 0
isSynced = source.readInt() != 0
}
constructor(syncState: SyncState?, state: State) {
val syncStateLocal = syncState ?: SyncState()
rowId = syncStateLocal.rowId
eTag = syncStateLocal.eTag
duplicated = syncStateLocal.duplicated
when (state) {
State.UNSYNCED -> {
isConflicted = syncStateLocal.isConflicted
isDeleted = syncStateLocal.isDeleted
isSynced = false
}
State.SYNCED -> {
isConflicted = syncStateLocal.isConflicted
isDeleted = false
isSynced = true
}
State.DELETED -> {
isConflicted = syncStateLocal.isConflicted
isDeleted = true
isSynced = false
}
State.CONFLICTED_UPDATE -> {
// NOTE: Local record was updated and Cloud one was modified or deleted
isConflicted = true
isDeleted = false
isSynced = false
}
State.CONFLICTED_DELETE -> {
// NOTE: Local record was deleted and Cloud one was modified
isConflicted = true
isDeleted = true
isSynced = false
}
else -> throw IllegalArgumentException(
"Unexpected state was provided [" + state.name + "]")
}
}
constructor(state: State) : this(null as SyncState?, state)
constructor(eTag: String?, duplicated: Int) {
requireNotNull(eTag) { "Duplicate conflict state must be constructed with valid eTag" }
require(duplicated > 0) { "Cannot setup duplicate conflict state for primary record" }
rowId = -1
this.eTag = eTag
// CONFLICTED_DUPLICATE: CdS && duplicated > 0, duplicated = 0 resolved (otherState)
this.duplicated = duplicated
isConflicted = true
isDeleted = false
isSynced = true
}
constructor(eTag: String, state: State) : this(state) {
this.eTag = eTag
}// NOTE: lets DB maintain the default value
// NOTE: rowId must not be here
val contentValues: ContentValues
get() {
val values = ContentValues()
// NOTE: rowId must not be here
if (eTag != null) {
// NOTE: lets DB maintain the default value
values.put(BaseEntry.COLUMN_NAME_ETAG, eTag)
}
values.put(BaseEntry.COLUMN_NAME_DUPLICATED, duplicated)
values.put(BaseEntry.COLUMN_NAME_CONFLICTED, isConflicted)
values.put(BaseEntry.COLUMN_NAME_DELETED, isDeleted)
values.put(BaseEntry.COLUMN_NAME_SYNCED, isSynced)
return values
}
fun isDuplicated(): Boolean {
return duplicated != 0
}
override fun hashCode(): Int {
return Objects.hashCode(rowId, eTag, duplicated, isConflicted, isDeleted, isSynced)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as SyncState
if (rowId != other.rowId) return false
if (duplicated != other.duplicated) return false
if (isConflicted != other.isConflicted) return false
if (isDeleted != other.isDeleted) return false
if (isSynced != other.isSynced) return false
if (eTag != other.eTag) return false
return true
}
companion object {
@JvmField
val CREATOR: Parcelable.Creator<SyncState> = object : Parcelable.Creator<SyncState> {
override fun createFromParcel(source: Parcel): SyncState {
return SyncState(source)
}
override fun newArray(size: Int): Array<SyncState?> {
return arrayOfNulls(size)
}
}
@JvmStatic
fun from(cursor: Cursor): SyncState {
val rowId = cursor.getLong(cursor.getColumnIndexOrThrow(BaseEntry._ID))
val eTag = cursor.getString(cursor.getColumnIndexOrThrow(
BaseEntry.COLUMN_NAME_ETAG))
val duplicated = cursor.getInt(cursor.getColumnIndexOrThrow(
BaseEntry.COLUMN_NAME_DUPLICATED))
val conflicted = cursor.getInt(cursor.getColumnIndexOrThrow(
BaseEntry.COLUMN_NAME_CONFLICTED)) == 1
val deleted = cursor.getInt(cursor.getColumnIndexOrThrow(
BaseEntry.COLUMN_NAME_DELETED)) == 1
val synced = cursor.getInt(cursor.getColumnIndexOrThrow(
BaseEntry.COLUMN_NAME_SYNCED)) == 1
return SyncState(rowId, eTag, duplicated, conflicted, deleted, synced)
}
@JvmStatic
fun from(values: ContentValues): SyncState {
val rowId = values.getAsLong(BaseEntry._ID)
val eTag = values.getAsString(BaseEntry.COLUMN_NAME_ETAG)
val duplicated = values.getAsInteger(BaseEntry.COLUMN_NAME_DUPLICATED)
val conflicted = values.getAsBoolean(BaseEntry.COLUMN_NAME_CONFLICTED)
val deleted = values.getAsBoolean(BaseEntry.COLUMN_NAME_DELETED)
val synced = values.getAsBoolean(BaseEntry.COLUMN_NAME_SYNCED)
return SyncState(rowId, eTag, duplicated, conflicted, deleted, synced)
}
}
} | gpl-3.0 | 57c0ca116469d38b475c7b9a7fff9f74 | 34.226244 | 95 | 0.616264 | 5.018698 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/RsCodeFragmentFactory.kt | 2 | 2077 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import com.intellij.openapi.project.Project
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.lang.core.macros.setContext
import org.rust.lang.core.parser.RustParserUtil.PathParsingMode
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.resolve.Namespace
import org.rust.lang.core.resolve.TYPES_N_VALUES
import org.rust.lang.core.resolve.TYPES_N_VALUES_N_MACROS
import org.rust.openapiext.toPsiFile
class RsCodeFragmentFactory(private val project: Project) {
private val psiFactory = RsPsiFactory(project, markGenerated = false)
fun createCrateRelativePath(pathText: String, target: CargoWorkspace.Target): RsPath? {
check(!pathText.startsWith("::"))
val vFile = target.crateRoot ?: return null
val crateRoot = vFile.toPsiFile(project) as? RsFile ?: return null
return createPath(pathText, crateRoot, ns = TYPES_N_VALUES_N_MACROS)
}
fun createPath(
path: String,
context: RsElement,
mode: PathParsingMode = PathParsingMode.TYPE,
ns: Set<Namespace> = TYPES_N_VALUES
): RsPath? {
return RsPathCodeFragment(project, path, false, context, mode, ns).path
}
fun createPathInTmpMod(
importingPathName: String,
context: RsMod,
mode: PathParsingMode,
ns: Set<Namespace>,
usePath: String,
crateName: String?
): RsPath? {
val (externCrateItem, useItem) = if (crateName != null) {
"extern crate $crateName;" to "use self::$usePath;"
} else {
"" to "use $usePath;"
}
val mod = psiFactory.createModItem(TMP_MOD_NAME, """
$externCrateItem
use super::*;
$useItem
""")
mod.setContext(context)
return createPath(importingPathName, mod, mode, ns)
}
}
const val TMP_MOD_NAME: String = "__tmp__"
| mit | 194696cf3287c225bacdd6087fa7e451 | 32.5 | 91 | 0.664901 | 4.064579 | false | false | false | false |
androidx/androidx | compose/material/material/icons/generator/src/test/kotlin/androidx/compose/material/icons/generator/IconParserTest.kt | 3 | 2967 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.material.icons.generator
import androidx.compose.material.icons.generator.vector.FillType
import androidx.compose.material.icons.generator.vector.PathNode
import androidx.compose.material.icons.generator.vector.VectorNode
import com.google.common.truth.Truth
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/**
* Test for [IconParser].
*/
@RunWith(JUnit4::class)
class IconParserTest {
@Test
fun parseVector() {
val icon = Icon("SimpleVector", "simple_vector", IconTheme.Filled, TestVector)
val vector = IconParser(icon).parse()
val nodes = vector.nodes
Truth.assertThat(nodes.size).isEqualTo(2)
val firstPath = nodes[0] as VectorNode.Path
Truth.assertThat(firstPath.fillAlpha).isEqualTo(0.3f)
Truth.assertThat(firstPath.strokeAlpha).isEqualTo(1f)
Truth.assertThat(firstPath.fillType).isEqualTo(FillType.NonZero)
val expectedFirstPathNodes = listOf(
PathNode.MoveTo(20f, 10f),
PathNode.RelativeLineTo(10f, 10f),
PathNode.RelativeLineTo(0f, 10f),
PathNode.RelativeLineTo(-10f, 0f),
PathNode.Close
)
Truth.assertThat(firstPath.nodes).isEqualTo(expectedFirstPathNodes)
val secondPath = nodes[1] as VectorNode.Path
Truth.assertThat(secondPath.fillAlpha).isEqualTo(1f)
Truth.assertThat(secondPath.strokeAlpha).isEqualTo(0.9f)
Truth.assertThat(secondPath.fillType).isEqualTo(FillType.EvenOdd)
val expectedSecondPathNodes = listOf(
PathNode.MoveTo(16.5f, 9.0f),
PathNode.RelativeHorizontalTo(3.5f),
PathNode.RelativeVerticalTo(9f),
PathNode.RelativeHorizontalTo(-3.5f),
PathNode.Close
)
Truth.assertThat(secondPath.nodes).isEqualTo(expectedSecondPathNodes)
}
}
private val TestVector = """
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp"
android:height="24dp">
<path
android:fillAlpha=".3"
android:pathData="M20,10, l10,10 0,10 -10, 0z" />
<path
android:strokeAlpha=".9"
android:pathData="M16.5,9h3.5v9h-3.5z"
android:fillType="evenOdd" />
</vector>
""".trimIndent()
| apache-2.0 | 5d9417ff8bb1ac378c754e42030cc3b1 | 34.746988 | 86 | 0.683182 | 4.075549 | false | true | false | false |
androidx/androidx | room/room-compiler-processing/src/main/java/androidx/room/compiler/processing/javac/JavacDeclaredType.kt | 3 | 2810 | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.room.compiler.processing.javac
import androidx.room.compiler.processing.XNullability
import androidx.room.compiler.processing.javac.kotlin.KmType
import javax.lang.model.type.DeclaredType
/**
* Declared types are different from non declared types in java (e.g. primitives, or wildcard
* types). Even thought XProcessing does not distinguish between these these, in the java
* implementation, it is handy to have a separate type for explicit typeMirror information.
*/
internal class JavacDeclaredType private constructor(
env: JavacProcessingEnv,
override val typeMirror: DeclaredType,
nullability: XNullability?,
override val kotlinType: KmType?
) : JavacType(
env, typeMirror, nullability
) {
constructor(
env: JavacProcessingEnv,
typeMirror: DeclaredType
) : this(
env = env,
typeMirror = typeMirror,
nullability = null,
kotlinType = null
)
constructor(
env: JavacProcessingEnv,
typeMirror: DeclaredType,
kotlinType: KmType
) : this(
env = env,
typeMirror = typeMirror,
nullability = kotlinType.nullability,
kotlinType = kotlinType
)
constructor(
env: JavacProcessingEnv,
typeMirror: DeclaredType,
nullability: XNullability
) : this(
env = env,
typeMirror = typeMirror,
nullability = nullability,
kotlinType = null
)
override val equalityItems: Array<out Any?> by lazy {
arrayOf(typeMirror)
}
override val typeArguments: List<JavacType> by lazy {
typeMirror.typeArguments.mapIndexed { index, typeMirror ->
env.wrap<JavacType>(
typeMirror = typeMirror,
kotlinType = kotlinType?.typeArguments?.getOrNull(index),
elementNullability = XNullability.UNKNOWN
)
}
}
override fun copyWithNullability(nullability: XNullability): JavacDeclaredType {
return JavacDeclaredType(
env = env,
typeMirror = typeMirror,
kotlinType = kotlinType,
nullability = nullability
)
}
}
| apache-2.0 | cf3470bba5264e5bac445ccbd4f2f848 | 30.222222 | 93 | 0.667972 | 5.109091 | false | false | false | false |
androidx/androidx | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/Divider.kt | 3 | 2418 | /*
* 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.compose.material3
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.material3.tokens.DividerTokens
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
/**
* <a href="https://m3.material.io/components/divider/overview" class="external" target="_blank">Material Design divider</a>.
*
* A divider is a thin line that groups content in lists and layouts.
*
* 
*
* @param modifier the [Modifier] to be applied to this divider line.
* @param thickness thickness of this divider line. Using [Dp.Hairline] will produce a single pixel
* divider regardless of screen density.
* @param color color of this divider line.
*/
@Composable
fun Divider(
modifier: Modifier = Modifier,
thickness: Dp = DividerDefaults.Thickness,
color: Color = DividerDefaults.color,
) {
val targetThickness = if (thickness == Dp.Hairline) {
(1f / LocalDensity.current.density).dp
} else {
thickness
}
Box(
modifier
.fillMaxWidth()
.height(targetThickness)
.background(color = color)
)
}
/** Default values for [Divider] */
object DividerDefaults {
/** Default thickness of a divider. */
val Thickness: Dp = DividerTokens.Thickness
/** Default color of a divider. */
val color: Color @Composable get() = DividerTokens.Color.toColor()
} | apache-2.0 | e70d7d454eb9e80505fa748c1c7dde39 | 34.057971 | 125 | 0.733664 | 4.16179 | false | false | false | false |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/system/linux/templates/X11.kt | 1 | 15864 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.system.linux.templates
import org.lwjgl.generator.*
import org.lwjgl.system.linux.*
val X11 = "X11".nativeClass(LINUX_PACKAGE, binding = simpleBinding("X11")) {
documentation = "Native bindings to libX11."
IntConstant(
"Boolean values",
"True".."1",
"False".."0"
)
IntConstant(
"RESERVED RESOURCE AND CONSTANT DEFINITIONS",
"None".."0",
"ParentRelative".."1",
"CopyFromParent".."0",
"PointerWindow".."0",
"InputFocus".."1",
"PointerRoot".."1",
"AnyPropertyType".."0",
"AnyKey".."0",
"AnyButton".."0",
"AllTemporary".."0",
"CurrentTime".."0",
"NoSymbol".."0"
)
IntConstant(
"ERROR CODES",
"Success".."0",
"BadRequest".."1",
"BadValue".."2",
"BadWindow".."3",
"BadPixmap".."4",
"BadAtom".."5",
"BadCursor".."6",
"BadFont".."7",
"BadMatch".."8",
"BadDrawable".."9",
"BadAccess".."10",
"BadAlloc".."11",
"BadColor".."12",
"BadGC".."13",
"BadIDChoice".."14",
"BadName".."15",
"BadLength".."16",
"BadImplementation".."17"
)
IntConstant(
"Window attributes for CreateWindow and ChangeWindowAttributes",
"CWBackPixmap".."1 << 0",
"CWBackPixel".."1 << 1",
"CWBorderPixmap".."1 << 2",
"CWBorderPixel".."1 << 3",
"CWBitGravity".."1 << 4",
"CWWinGravity".."1 << 5",
"CWBackingStore".."1 << 6",
"CWBackingPlanes".."1 << 7",
"CWBackingPixel".."1 << 8",
"CWOverrideRedirect".."1 << 9",
"CWSaveUnder".."1 << 10",
"CWEventMask".."1 << 11",
"CWDontPropagate".."1 << 12",
"CWColormap".."1 << 13",
"CWCursor".."1 << 14"
)
IntConstant(
"Input Event Masks. Used as event-mask window attribute and as arguments to Grab requests. Not to be confused with event names.",
"NoEventMask".."0",
"KeyPressMask".."1 << 0",
"KeyReleaseMask".."1 << 1",
"ButtonPressMask".."1 << 2",
"ButtonReleaseMask".."1 << 3",
"EnterWindowMask".."1 << 4",
"LeaveWindowMask".."1 << 5",
"PointerMotionMask".."1 << 6",
"PointerMotionHintMask".."1 << 7",
"Button1MotionMask".."1 << 8",
"Button2MotionMask".."1 << 9",
"Button3MotionMask".."1 << 10",
"Button4MotionMask".."1 << 11",
"Button5MotionMask".."1 << 12",
"ButtonMotionMask".."1 << 13",
"KeymapStateMask".."1 << 14",
"ExposureMask".."1 << 15",
"VisibilityChangeMask".."1 << 16",
"StructureNotifyMask".."1 << 17",
"ResizeRedirectMask".."1 << 18",
"SubstructureNotifyMask".."1 << 19",
"SubstructureRedirectMask".."1 << 20",
"FocusChangeMask".."1 << 21",
"PropertyChangeMask".."1 << 22",
"ColormapChangeMask".."1 << 23",
"OwnerGrabButtonMask".."1 << 24"
)
IntConstant(
"""
Event names. Used in "type" field in {@code XEvent} structures. Not to be confused with event masks above. They start from 2 because 0 and 1 are reserved in
the protocol for errors and replies.
""",
"KeyPress".."2",
"KeyRelease".."3",
"ButtonPress".."4",
"ButtonRelease".."5",
"MotionNotify".."6",
"EnterNotify".."7",
"LeaveNotify".."8",
"FocusIn".."9",
"FocusOut".."10",
"KeymapNotify".."11",
"Expose".."12",
"GraphicsExpose".."13",
"NoExpose".."14",
"VisibilityNotify".."15",
"CreateNotify".."16",
"DestroyNotify".."17",
"UnmapNotify".."18",
"MapNotify".."19",
"MapRequest".."20",
"ReparentNotify".."21",
"ConfigureNotify".."22",
"ConfigureRequest".."23",
"GravityNotify".."24",
"ResizeRequest".."25",
"CirculateNotify".."26",
"CirculateRequest".."27",
"PropertyNotify".."28",
"SelectionClear".."29",
"SelectionRequest".."30",
"SelectionNotify".."31",
"ColormapNotify".."32",
"ClientMessage".."33",
"MappingNotify".."34",
"GenericEvent".."35",
"LASTEvent".."36"
)
IntConstant(
"Key masks. Used as modifiers to GrabButton and GrabKey, results of QueryPointer, state in various key-, mouse-, and button-related events.",
"ShiftMask".."1<<0",
"LockMask".."1<<1",
"ControlMask".."1<<2",
"Mod1Mask".."1<<3",
"Mod2Mask".."1<<4",
"Mod3Mask".."1<<5",
"Mod4Mask".."1<<6",
"Mod5Mask".."1<<7"
)
IntConstant(
"modifier names. Used to build a SetModifierMapping request or to read a GetModifierMapping request. These correspond to the masks defined above.",
"ShiftMapIndex".."0",
"LockMapIndex".."1",
"ControlMapIndex".."2",
"Mod1MapIndex".."3",
"Mod2MapIndex".."4",
"Mod3MapIndex".."5",
"Mod4MapIndex".."6",
"Mod5MapIndex".."7"
)
IntConstant(
"button masks. Used in same manner as Key masks above. Not to be confused with button names below.",
"Button1Mask".."1<<8",
"Button2Mask".."1<<9",
"Button3Mask".."1<<10",
"Button4Mask".."1<<11",
"Button5Mask".."1<<12",
"AnyModifier".."1<<15"
)
IntConstant(
"""
button names. Used as arguments to GrabButton and as detail in ButtonPress and ButtonRelease events. Not to be confused with button masks above. Note
that 0 is already defined above as "AnyButton".
""",
"Button1".."1",
"Button2".."2",
"Button3".."3",
"Button4".."4",
"Button5".."5"
)
IntConstant(
"Notify modes",
"NotifyNormal".."0",
"NotifyGrab".."1",
"NotifyUngrab".."2",
"NotifyWhileGrabbed".."3",
"NotifyHint".."1"
)
IntConstant(
"Notify detail",
"NotifyAncestor".."0",
"NotifyVirtual".."1",
"NotifyInferior".."2",
"NotifyNonlinear".."3",
"NotifyNonlinearVirtual".."4",
"NotifyPointer".."5",
"NotifyPointerRoot".."6",
"NotifyDetailNone".."7"
)
IntConstant(
"Visibility notify",
"VisibilityUnobscured".."0",
"VisibilityPartiallyObscured".."1",
"VisibilityFullyObscured".."2"
)
IntConstant(
"Circulation request",
"PlaceOnTop".."0",
"PlaceOnBottom".."1"
)
IntConstant(
"Property notification",
"PropertyNewValue".."0",
"PropertyDelete".."1"
)
IntConstant(
"Color Map notification",
"ColormapUninstalled".."0",
"ColormapInstalled".."1"
)
IntConstant(
"GrabPointer, GrabButton, GrabKeyboard, GrabKey Modes",
"GrabModeSync".."0",
"GrabModeAsync".."1"
)
IntConstant(
"GrabPointer, GrabKeyboard reply status",
"GrabSuccess".."0",
"AlreadyGrabbed".."1",
"GrabInvalidTime".."2",
"GrabNotViewable".."3",
"GrabFrozen".."4"
)
IntConstant(
"AllowEvents modes",
"AsyncPointer".."0",
"SyncPointer".."1",
"ReplayPointer".."2",
"AsyncKeyboard".."3",
"SyncKeyboard".."4",
"ReplayKeyboard".."5",
"AsyncBoth".."6",
"SyncBoth".."7"
)
IntConstant(
"For #XCreateColormap().",
"AllocNone".."0",
"AllocAll".."1"
)
IntConstant(
"Used in XSetInputFocus(), XGetInputFocus().",
"RevertToNone".."None",
"RevertToPointerRoot".."PointerRoot",
"RevertToParent".."2"
)
IntConstant(
"Window classes used by #XCreateWindow().",
"InputOutput".."1",
"InputOnly".."2"
)
IntConstant(
"SCREEN SAVER STUFF",
"DontPreferBlanking".."0",
"PreferBlanking".."1",
"DefaultBlanking".."2",
"DisableScreenSaver".."0",
"DisableScreenInterval".."0",
"DontAllowExposures".."0",
"AllowExposures".."1",
"DefaultExposures".."2",
"ScreenSaverReset".."0",
"ScreenSaverActive".."1"
)
IntConstant(
"Property modes",
"PropModeReplace".."0",
"PropModePrepend".."1",
"PropModeAppend".."2"
)
IntConstant(
"graphics functions, as in GC.alu",
"GXclear"..0x0,
"GXand"..0x1,
"GXandReverse"..0x2,
"GXcopy"..0x3,
"GXandInverted"..0x4,
"GXnoop"..0x5,
"GXxor"..0x6,
"GXor"..0x7,
"GXnor"..0x8,
"GXequiv"..0x9,
"GXinvert"..0xa,
"GXorReverse"..0xb,
"GXcopyInverted"..0xc,
"GXorInverted"..0xd,
"GXnand"..0xe,
"GXset"..0xf
)
IntConstant(
"LineStyle",
"LineSolid".."0",
"LineOnOffDash".."1",
"LineDoubleDash".."2"
)
IntConstant(
"capStyle",
"CapNotLast".."0",
"CapButt".."1",
"CapRound".."2",
"CapProjecting".."3"
)
IntConstant(
"joinStyle",
"JoinMiter".."0",
"JoinRound".."1",
"JoinBevel".."2"
)
IntConstant(
"fillStyle",
"FillSolid".."0",
"FillTiled".."1",
"FillStippled".."2",
"FillOpaqueStippled".."3"
)
IntConstant(
"fillRule",
"EvenOddRule".."0",
"WindingRule".."1"
)
IntConstant(
"subwindow mode",
"ClipByChildren".."0",
"IncludeInferiors".."1"
)
IntConstant(
"SetClipRectangles ordering",
"Unsorted".."0",
"YSorted".."1",
"YXSorted".."2",
"YXBanded".."3"
)
IntConstant(
"CoordinateMode for drawing routines",
"CoordModeOrigin".."0",
"CoordModePrevious".."1"
)
IntConstant(
"Polygon shapes",
"Complex".."0",
"Nonconvex".."1",
"Convex".."2"
)
IntConstant(
"Arc modes for PolyFillArc",
"ArcChord".."0",
"ArcPieSlice".."1"
)
IntConstant(
"GC components: masks used in CreateGC, CopyGC, ChangeGC, OR'ed into GC.stateChanges",
"GCFunction".."1<<0",
"GCPlaneMask".."1<<1",
"GCForeground".."1<<2",
"GCBackground".."1<<3",
"GCLineWidth".."1<<4",
"GCLineStyle".."1<<5",
"GCCapStyle".."1<<6",
"GCJoinStyle".."1<<7",
"GCFillStyle".."1<<8",
"GCFillRule".."1<<9",
"GCTile".."1<<10",
"GCStipple".."1<<11",
"GCTileStipXOrigin".."1<<12",
"GCTileStipYOrigin".."1<<13",
"GCFont".."1<<14",
"GCSubwindowMode".."1<<15",
"GCGraphicsExposures".."1<<16",
"GCClipXOrigin".."1<<17",
"GCClipYOrigin".."1<<18",
"GCClipMask".."1<<19",
"GCDashOffset".."1<<20",
"GCDashList".."1<<21",
"GCArcMode".."1<<22",
"GCLastBit".."22"
)
val DISPLAY = Display_p.IN("display", "the connection to the X server")
val WINDOW = Window.IN("w", "the window")
//val DRAWABLE = Drawable.IN("d", "the drawable")
Display_p(
"XOpenDisplay",
"""
Returns a Display structure that serves as the connection to the X server and that contains all the information about that X server. {@code XOpenDisplay}
connects your application to the X server through TCP or DECnet communications protocols, or through some local inter-process communication protocol.
If the hostname is a host machine name and a single colon (:) separates the hostname and display number, {@code XOpenDisplay} connects using TCP streams.
If the hostname is not specified, Xlib uses whatever it believes is the fastest transport. If the hostname is a host machine name and a double colon
(::) separates the hostname and display number, {@code XOpenDisplay} connects using DECnet. A single X server can support any or all of these transport
mechanisms simultaneously. A particular Xlib implementation can support many more of these transport mechanisms.
""",
nullable..const..charASCII_p.IN(
"display_name",
"""
the hardware display name, which determines the display and communications domain to be used. On a POSIX-conformant system, if the
{@code display_name} is $NULL, it defaults to the value of the DISPLAY environment variable.
"""
)
)
void(
"XCloseDisplay",
"""
Closes the connection to the X server for the display specified in the {@code Display} structure and destroys all windows, resource IDs (Window, Font,
Pixmap, Colormap, Cursor, and GContext), or other resources that the client has created on this display, unless the close-down mode of the resource has
been changed (see {@code XSetCloseDownMode()}). Therefore, these windows, resource IDs, and other resources should never be referenced again or an error will
be generated. Before exiting, you should call {@code XCloseDisplay()} explicitly so that any pending errors are reported as {@code XCloseDisplay()}
performs a final {@code XSync()} operation.
""",
DISPLAY
)
int(
"XDefaultScreen",
"Returns a pointer to the default screen.",
DISPLAY
)
Window(
"XRootWindow",
"Returns the root window of the specified screen.",
DISPLAY,
int.IN("screen_number", "the appropriate screen number on the host server")
)
Colormap(
"XCreateColormap",
"""
Creates a colormap of the specified visual type for the screen on which the specified window resides and returns the colormap ID associated with it.
Note that the specified window is only used to determine the screen.
""",
DISPLAY,
WINDOW,
Visual_p.IN("visual", "a visual type supported on the screen. If the visual type is not one supported by the screen, a {@code BadMatch} error results."),
int.IN("alloc", "the colormap entries to be allocated. You can pass AllocNone or AllocAll.")
)
int(
"XFreeColormap",
"""
Deletes the association between the {@code colormap} resource ID and the {@code colormap} and frees the {@code colormap} storage. However, this function
has no effect on the default colormap for a screen. If the specified {@code colormap} is an installed map for a screen, it is uninstalled. If the
specified {@code colormap} is defined as the {@code colormap} for a window, {@code XFreeColormap()} changes the colormap associated with the window to
#None and generates a {@code ColormapNotify} event. X does not define the colors displayed for a window with a colormap of #None.
""",
DISPLAY,
Colormap.IN("colormap", "the colormap to destroy")
)
Window(
"XCreateWindow",
"""
Creates an unmapped subwindow for a specified parent window, returns the window ID of the created window, and causes the X server to generate a
{@code CreateNotify }event. The created window is placed on top in the stacking order with respect to siblings.
The coordinate system has the X axis horizontal and the Y axis vertical with the origin [0, 0] at the upper-left corner. Coordinates are integral, in
terms of pixels, and coincide with pixel centers. Each window and pixmap has its own coordinate system. For a window, the origin is inside the border at
the inside, upper-left corner.
The x and y coordinates are the top-left outside corner of the window's borders and are relative to the inside of the parent window's borders.
The width and height are the created window's inside dimensions and do not include the created window's borders.
""",
DISPLAY,
Window.IN("parent", "the parent window"),
int.IN("x", "the window x-coordinate"),
int.IN("y", "the window y-coordinate"),
unsigned_int.IN("width", "the window width"),
unsigned_int.IN("height", "the window height"),
unsigned_int.IN("border_width", "the border width"),
int.IN("depth", "the window's depth. A depth of #CopyFromParent means the depth is taken from the parent."),
unsigned_int.IN("windowClass", "the created window's class", "#InputOutput #InputOnly #CopyFromParent"),
Visual_p.IN("visual", "the visual type. A visual of #CopyFromParent means the visual type is taken from the parent."),
unsigned_long.IN(
"valuemask",
"""
which window attributes are defined in the attributes argument. This mask is the bitwise inclusive OR of the valid attribute mask bits. If
{@code valuemask} is zero, the attributes are ignored and are not referenced.
"""
),
XSetWindowAttributes_p.IN("attributes", "the structure from which the values (as specified by the value mask) are to be taken")
)
int(
"XDestroyWindow",
"""
Destroys the specified window as well as all of its subwindows and causes the X server to generate a {@code DestroyNotify} event for each window. The
window should never be referenced again. If the window specified by the {@code w} argument is mapped, it is unmapped automatically. The ordering of the
{@code DestroyNotify} events is such that for any given window being destroyed, {@code DestroyNotify} is generated on any inferiors of the window before
being generated on the window itself. The ordering among siblings and across subhierarchies is not otherwise constrained. If the window you specified is
a root window, no windows are destroyed. Destroying a mapped window will generate {@code Expose} events on other windows that were obscured by the
window being destroyed.
""",
DISPLAY,
WINDOW
)
int(
"XFree",
"Free in-memory data that was created by an Xlib function.",
MultiType(PointerMapping.DATA_POINTER)..void_p.IN("data", "the data that is to be freed")
)
} | bsd-3-clause | 976366bc8c757184c5845acf622537f4 | 25.708754 | 159 | 0.662758 | 3.256826 | false | false | false | false |
Ribesg/Purpur | src/main/kotlin/fr/ribesg/minecraft/purpur/event/EventManager.kt | 1 | 6265 | package fr.ribesg.minecraft.purpur.event
import fr.ribesg.minecraft.purpur.Log
import fr.ribesg.minecraft.purpur.api.event.Event
import fr.ribesg.minecraft.purpur.api.event.EventHandler
import fr.ribesg.minecraft.purpur.api.event.EventHandlerPriority
import fr.ribesg.minecraft.purpur.api.event.InvalidEventHandlerException
import java.lang.reflect.Method
import java.lang.reflect.Modifier
import java.util.*
import java.util.concurrent.ConcurrentHashMap
import java.util.concurrent.ConcurrentLinkedQueue
/**
* Manages Events. Yeah.
* @author Ribesg
*/
object EventManager {
/**
* This little private Class is used to be able to store Object instances
* and associated EventHandler methods in pairs.
*/
private class ObjectMethod(
/**
* Object instance
*/
val instance: Any,
/**
* EventHandler method
*/
val method: Method,
/**
* If this method should be called for a consumed Event
*/
val ignoreConsumed: Boolean
)
/**
* A Map to store all the EventHandlers
*/
private val handlers: MutableMap<Class<out Event>, MutableMap<EventHandlerPriority, Queue<ObjectMethod>>>
/**
* Builds the EventManager instance
*/
init {
this.handlers = ConcurrentHashMap()
}
/**
* Registers all handlers of the provided object.
* <p>
* Valid EventHandlers are public method with the
* [EventHandler] annotation.
*
* @param handlersHolder an object holding one or multiple EventHandlers
*/
@Suppress("UNCHECKED_CAST")
fun registerHandlers(handlersHolder: Any, ignoreErrors: Boolean = false) {
var eh: EventHandler?
var parameterType: Class<*>
var handlerRegistered = false
for (m: Method in handlersHolder.javaClass.methods) {
eh = m.getAnnotation(EventHandler::class.java)
if (eh != null) {
parameterType = m.parameterTypes[0]
if (m.parameterCount != 1 || !Event::class.java.isAssignableFrom(parameterType)) {
throw InvalidEventHandlerException(m, "Invalid parameter count or type")
} else if (!Modifier.isPublic(m.modifiers)) {
throw InvalidEventHandlerException(m, "Not public")
} else {
var eventHandlers = this.handlers.getOrPut(
parameterType as Class<out Event>,
{ ConcurrentHashMap() }
)
var priorityHandlers = eventHandlers.getOrPut(
eh.priority,
{ ConcurrentLinkedQueue() }
)
priorityHandlers.add(ObjectMethod(handlersHolder, m, eh.ignoreConsumed))
handlerRegistered = true
}
}
}
if (!ignoreErrors && !handlerRegistered) {
throw IllegalArgumentException("Provided object class '" + handlersHolder.javaClass.name + "' has no valid EventHandler")
}
}
/**
* Unregisters all handlers of the provided object.
*
* @param handlersHolder an object holding one or multiple registered
* EventHandlers
* @param ignoreUnregistered if this call should ignore errors that may
* occur if the provided instance isn't
* registered
*/
fun unRegisterHandlers(handlersHolder: Any, ignoreErrors: Boolean = false) {
var eh: EventHandler?
var parameterType: Class<*>
var registeredHandlerFound = false
for (m: Method in handlersHolder.javaClass.methods) {
eh = m.getAnnotation(EventHandler::class.java)
if (m.isAccessible && eh != null) {
parameterType = m.parameterTypes[0]
if (m.parameterCount != 1 || !Event::class.java.isAssignableFrom(parameterType)) {
throw InvalidEventHandlerException(m, "Invalid parameter count or type")
} else {
var eventHandlers = this.handlers.get(parameterType)
if (eventHandlers != null) {
var priorityHandlers = eventHandlers.get(eh.priority)
if (priorityHandlers != null) {
val it = priorityHandlers.iterator()
while (it.hasNext()) {
if (it.next().instance == handlersHolder) {
it.remove()
registeredHandlerFound = true
break
}
}
if (priorityHandlers.isEmpty()) {
eventHandlers.remove(eh.priority)
}
}
if (eventHandlers.isEmpty()) {
this.handlers.remove(parameterType)
}
}
}
}
}
if (!ignoreErrors && !registeredHandlerFound) {
throw IllegalArgumentException("Provided instance of '" + handlersHolder.javaClass.name + "' has no registered EventHandler")
}
}
/**
* Calls an Event.
*
* @param event an Event
*/
fun call(event: Event) {
val clazz = event.javaClass
val eventHandlers = this.handlers.get(clazz) ?: return
for (priority in EventHandlerPriority.values ()) {
val priorityHandlers = eventHandlers.get(priority) ?: continue
priorityHandlers.forEach { om ->
try {
if (!event.isConsumed() || !om.ignoreConsumed) {
om.method.invoke(om.instance, event)
}
} catch (t: Throwable) {
Log.error(
"EventHandler '" + om.method.declaringClass.name + '.' + om.method.name +
"(...)' invokation failed", t
)
}
}
}
}
}
| agpl-3.0 | 5295c7a44764084aaf909f4b3425a295 | 36.740964 | 137 | 0.535994 | 5.514965 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/SearchAuthorsViewHolder.kt | 2 | 3111 | package ru.fantlab.android.ui.adapter.viewholder
import android.net.Uri
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.search_authors_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.SearchAuthor
import ru.fantlab.android.provider.scheme.LinkParserHelper.HOST_DATA
import ru.fantlab.android.provider.scheme.LinkParserHelper.PROTOCOL_HTTPS
import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter
import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder
import java.text.NumberFormat
class SearchAuthorsViewHolder(itemView: View, adapter: BaseRecyclerAdapter<SearchAuthor, SearchAuthorsViewHolder>)
: BaseViewHolder<SearchAuthor>(itemView, adapter) {
private val numberFormat = NumberFormat.getNumberInstance()
override fun bind(author: SearchAuthor) {
itemView.avatarLayout.setUrl(Uri.Builder().scheme(PROTOCOL_HTTPS)
.authority(HOST_DATA)
.appendPath("images")
.appendPath("autors")
.appendPath(author.authorId.toString())
.toString())
itemView.name.text = if (author.rusName.isNotEmpty()) {
if (author.name.isNotEmpty()) {
String.format("%s / %s", author.rusName, author.name)
} else {
author.rusName
}
} else {
author.name
}
if (author.pseudoNames.isNotEmpty()) {
itemView.pseudo_names.text = author.pseudoNames
itemView.pseudo_names.visibility = View.VISIBLE
} else {
itemView.pseudo_names.visibility = View.GONE
}
if (author.country.isNotEmpty()) itemView.country.text = author.country else itemView.country.visibility = View.GONE
if (author.birthYear != 0 || author.deathYear != 0) {
itemView.dates.text = StringBuilder()
.append(if (author.birthYear != 0) author.birthYear else "N/A")
.append(if (author.deathYear != 0) " - ${author.deathYear}" else "")
} else itemView.dates.visibility = View.GONE
if (author.markCount != 0) {
itemView.rating.text = String.format("%s / %s",
numberFormat.format(author.midMark / 100.0),
numberFormat.format(author.markCount.toLong()))
itemView.rating.visibility = View.VISIBLE
} else {
itemView.rating.visibility = View.GONE
}
if (author.responseCount != 0) {
itemView.responses.text = numberFormat.format(author.responseCount.toLong())
itemView.responses.visibility = View.VISIBLE
} else {
itemView.responses.visibility = View.GONE
}
if (author.editionCount != 0) {
itemView.editions.text = numberFormat.format(author.editionCount.toLong())
itemView.editions.visibility = View.VISIBLE
} else {
itemView.editions.visibility = View.GONE
}
if (author.movieCount != 0) {
itemView.movies.text = numberFormat.format(author.movieCount.toLong())
itemView.movies.visibility = View.VISIBLE
} else {
itemView.movies.visibility = View.GONE
}
}
companion object {
fun newInstance(
viewGroup: ViewGroup,
adapter: BaseRecyclerAdapter<SearchAuthor, SearchAuthorsViewHolder>
): SearchAuthorsViewHolder =
SearchAuthorsViewHolder(getView(viewGroup, R.layout.search_authors_row_item), adapter)
}
} | gpl-3.0 | 5d27f41cc58b1ffcb47de91ab8a565e1 | 32.462366 | 118 | 0.740598 | 3.655699 | false | false | false | false |
RobotPajamas/Blueteeth | blueteeth/src/test/kotlin/com/robotpajamas/blueteeth/models/ResultTest.kt | 1 | 3737 | package com.robotpajamas.blueteeth.models
import org.junit.Assert.*
import org.junit.Test
// TODO: Get JUnit5 or Spek in here for easier BDD
// Or use JUnit4 nested test runners
class ResultTest {
@Test
fun success_whenConstructed_shouldPopulateValue() {
val expectedString = "hello"
val resultString = Result.Success(expectedString)
assertEquals(resultString.value, expectedString)
val expectedInt = 42
val resultInt = Result.Success(expectedInt)
assertEquals(resultInt.value, expectedInt)
val expectedDouble = 42.123
val resultDouble = Result.Success(expectedDouble)
assertEquals(resultDouble.value, expectedDouble, 0.0001)
val expectedList = listOf(1, 2, 3, 4)
val resultList = Result.Success(expectedList)
assertArrayEquals(resultList.value.toIntArray(), expectedList.toIntArray())
val expectedObject = object {
val x: Int = 56
var y: String = "asdasd"
}
val resultObject = Result.Success(expectedObject)
assertEquals(resultObject.value, expectedObject) // Just checks references, not fields
}
@Test
fun success_whenConstructed_shouldNotPopulateError() {
val result = Result.Success(0)
assertNull(result.error)
}
@Test
fun failure_whenConstructed_shouldNotPopulateValue() {
val exception = NullPointerException()
val result: Result<Any> = Result.Failure(exception)
assertNull(result.value)
}
@Test
fun failure_whenConstructed_shouldPopulateError() {
val exception = NullPointerException()
val result: Result<Any> = Result.Failure(exception)
assertEquals(result.error, exception)
}
@Test
fun isSuccess_whenSuccessCreated_shouldReturnTrue() {
val result = Result.Success(0)
assertTrue(result.isSuccess)
}
@Test
fun isFailure_whenSuccessCreated_shouldReturnFalse() {
val result = Result.Success(0)
assertFalse(result.isFailure)
}
@Test
fun isSuccess_whenFailureCreated_shouldReturnFalse() {
val result: Result<Any> = Result.Failure(NullPointerException())
assertFalse(result.isSuccess)
}
@Test
fun isFailure_whenFailureCreated_shouldReturnTrue() {
val result: Result<Any> = Result.Failure(NullPointerException())
assertTrue(result.isFailure)
}
@Test
fun successCallback_whenSuccessCreated_shouldBeCalled() {
val expected = 42
val result = Result.Success(expected)
var value = 0
result.success {
value = it
}
assertEquals(value, expected)
}
@Test
fun successCallback_whenFailureCreated_shouldNotBeCalled() {
val result: Result<Any> = Result.Failure(NullPointerException())
result.success { fail() }
}
@Test
fun failureCallback_whenSuccessCreated_shouldNotBeCalled() {
val result = Result.Success(42)
result.failure { fail() }
}
@Test
fun failureCallback_whenFailureCreated_shouldBeCalled() {
val result: Result<Any> = Result.Failure(NullPointerException())
var failureCalled = false
result.failure {
failureCalled = true
}
assertTrue(failureCalled)
}
@Test
fun unwrap_whenSuccessCreated_shouldReturnTrue() {
val result = Result.Success(0)
assertEquals(result.unwrap(), 0)
}
@Test(expected = NullPointerException::class)
fun unwrap_whenFailureCreated_shouldThrowException() {
val exception = NullPointerException()
val result: Result<Any> = Result.Failure(exception)
result.unwrap()
}
} | apache-2.0 | 36ded681f54dc5ea00498cac76046edc | 28.904 | 94 | 0.658014 | 4.73038 | false | true | false | false |
C6H2Cl2/SolidXp | src/main/java/c6h2cl2/solidxp/network/CMessageUpdateTileEntity.kt | 1 | 872 | package c6h2cl2.solidxp.network
import io.netty.buffer.ByteBuf
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.network.PacketBuffer
import net.minecraft.util.math.BlockPos
import net.minecraftforge.fml.common.network.simpleimpl.IMessage
/**
* @author C6H2Cl2
*/
class CMessageUpdateTileEntity : IMessage {
lateinit var data: NBTTagCompound
lateinit var pos: BlockPos
constructor()
constructor(nbtTagCompound: NBTTagCompound, pos: BlockPos) {
data = nbtTagCompound
this.pos = pos
}
override fun fromBytes(buf: ByteBuf) {
val packet = PacketBuffer(buf)
data = packet.readCompoundTag() ?: return
pos = packet.readBlockPos()
}
override fun toBytes(buf: ByteBuf) {
val packet = PacketBuffer(buf)
packet.writeCompoundTag(data)
packet.writeBlockPos(pos)
}
} | mpl-2.0 | a5a9550dcf3d2eb44247bc793aaf965d | 23.942857 | 64 | 0.702982 | 4.21256 | false | false | false | false |
lydia-schiff/hella-renderscript | hella/src/main/java/com/lydiaschiff/hella/RsUtil.kt | 1 | 7512 | package com.lydiaschiff.hella
import android.graphics.ImageFormat
import android.os.Build
import android.renderscript.Allocation
import android.renderscript.Element
import android.renderscript.RenderScript
import android.renderscript.Type
import androidx.annotation.ColorInt
import androidx.annotation.RequiresApi
import java.util.concurrent.atomic.AtomicReference
import kotlin.math.roundToInt
/**
* Static utilities for Renderscript. I'm going to leave in any unneeded API annotations because
* they are interesting documentation.
*/
object RsUtil {
fun width(a: Allocation): Int = a.type.x
fun height(a: Allocation): Int = a.type.y
/**
* Create a sized RGBA_8888 Allocation to use with scripts.
*
* @param rs RenderScript context
* @param x width in pixels
* @param y height in pixels
* @return an RGBA_8888 Allocation
*/
fun createRgbAlloc(rs: RenderScript, x: Int, y: Int) =
Allocation.createTyped(rs, createType(rs, Element.RGBA_8888(rs), x, y))
/**
* Create an RGBA_8888 allocation that can act as a Surface producer. This lets us call
* [Allocation.setSurface] and call [Allocation.ioSend]. If
* you wanted to read the data from this Allocation, do so before calling ioSend(), because
* after, the data is undefined.
*
* @param rs rs context
* @param x width in pixels
* @param y height in pixels
* @return an RGBA_8888 Allocation with USAGE_IO_INPUT
*/
@RequiresApi(16)
fun createRgbIoOutputAlloc(rs: RenderScript, x: Int, y: Int) =
Allocation.createTyped(rs, createType(rs, Element.RGBA_8888(rs), x, y),
Allocation.USAGE_IO_OUTPUT or Allocation.USAGE_SCRIPT)
/**
* Create an Allocation with the same Type (size and elements) as a source Allocation.
*
* @param rs rs context
* @param a source alloc
* @return a new Allocation with matching Type
*/
fun createMatchingAlloc(rs: RenderScript, a: Allocation) = Allocation.createTyped(rs, a.type)
fun createMatchingAllocScaled(rs: RenderScript, a: Allocation,
scaled: Float): Allocation {
val scaledX = scaled.toInt() * width(a)
val scaledY = scaled.toInt() * height(a)
return Allocation.createTyped(rs, createType(rs, a.type.element, scaledX, scaledY))
}
/**
* Create an YUV allocation that can act as a Surface consumer. This lets us call
* [Allocation.getSurface], set a [Allocation.OnBufferAvailableListener]
* callback to be notified when a frame is ready, and call [Allocation.ioReceive] to
* latch a frame and access its yuv pixel data.
*
* The yuvFormat should be {@value ImageFormat#YUV_420_888}, {@value ImageFormat#NV21}, or maybe
* [ImageFormat.YV12].
*
* @param rs RenderScript context
* @param x width in pixels
* @param y height in pixels
* @param yuvFormat yuv pixel format
* @return a YUV Allocation with USAGE_IO_INPUT
*/
@RequiresApi(18)
fun createYuvIoInputAlloc(rs: RenderScript, x: Int, y: Int, yuvFormat: Int) =
Allocation.createTyped(rs, createYuvType(rs, x, y, yuvFormat),
Allocation.USAGE_IO_INPUT or Allocation.USAGE_SCRIPT)
fun createType(rs: RenderScript, e: Element, x: Int, y: Int): Type =
if (Build.VERSION.SDK_INT >= 21) Type.createXY(rs, e, x, y)
else Type.Builder(rs, e).setX(x).setY(y).create()
@RequiresApi(18)
fun createYuvType(rs: RenderScript, x: Int, y: Int, yuvFormat: Int): Type {
var supported = yuvFormat == ImageFormat.NV21 || yuvFormat == ImageFormat.YV12
if (Build.VERSION.SDK_INT >= 19) {
supported = supported or (yuvFormat == ImageFormat.YUV_420_888)
}
require(supported) { "invalid yuv format: $yuvFormat" }
return Type.Builder(rs, createYuvElement(rs)).setX(x).setY(y).setYuvFormat(yuvFormat)
.create()
}
fun createYuvElement(rs: RenderScript?): Element =
if (Build.VERSION.SDK_INT >= 19) Element.YUV(rs)
else Element.createPixel(rs, Element.DataType.UNSIGNED_8, Element.DataKind.PIXEL_YUV)
/**
* A 3D Type suitable for color LUT data for use with ScriptIntrinsic3DLUT.
*/
fun lut3dType(rs: RenderScript, x: Int, y: Int = x, z: Int = x) =
if (Build.VERSION.SDK_INT >= 21) Type.createXYZ(rs, Element.RGBA_8888(rs), x, y, x)
else Type.Builder(rs, Element.RGBA_8888(rs)).setX(x).setY(y).setZ(z).create()
/**
* A cubic 3D Allocation suitable for color LUT data for use with ScriptIntrinsic3DLUT.
*/
fun lut3dAlloc(
rs: RenderScript,
setIdentity: Boolean,
x: Int,
y: Int = x,
z: Int = x
): Allocation = Allocation.createTyped(rs, lut3dType(rs, x, y, z)).also {
if (setIdentity) IdentityLut.setIdentityLutData(it)
}
fun copyColorIntsToAlloc(colorInts: IntArray, lut3dAlloc: Allocation) {
val buffer = PooledBuffer.acquire(colorInts.size)
colorInts.forEachIndexed { n, c -> buffer[n] = colorIntToRsPackedColor8888(c) }
lut3dAlloc.copyFromUnchecked(buffer)
PooledBuffer.returnBuffer(buffer)
}
fun copyRgbFloatsToAlloc(rgbFloats: FloatArray, lut3dAlloc: Allocation) {
val nColors = rgbFloats.size / 3
require(lut3dAlloc.type.count == nColors)
val buffer = PooledBuffer.acquire(nColors)
for (n in 0 until nColors) {
buffer[n] = rsPackedColor8888(rgbFloats, n * 3)
}
lut3dAlloc.copyFromUnchecked(buffer)
PooledBuffer.returnBuffer(buffer)
}
/**
* Able to be copied unchecked into an alloc with RGBA_8888 or U8_4 elements.
*/
fun rsPackedColor8888(r: Int, g: Int, b: Int): Int = 0xff00000 or (b shl 16) or (g shl 8) or r
fun rsPackedColor8888(r: Float, g: Float, b: Float): Int = rsPackedColor8888(
(r * 255).roundToInt() and 0xff,
(g * 255).roundToInt() and 0xff,
(b * 255).roundToInt() and 0xff)
fun rsPackedColor8888(rgbFloats: FloatArray, start: Int) = rsPackedColor8888(
rgbFloats[start],
rgbFloats[start + 1],
rgbFloats[start + 2])
fun colorIntToRsPackedColor8888(@ColorInt c: Int): Int = swapRb(c)
@ColorInt
fun rsPackedColor8888ToColorInt(c: Int): Int = swapRb(c)
/**
* When we convert an Android ColorInt unchecked into renderscript U8_4, we have to swap red
* and blue. Much endian. Very bit-shifting.
*/
private fun swapRb(c: Int): Int {
val r = c shr 16 and 0xff
val g = c shr 8 and 0xff
val b = c and 0xff
return 0xff00000 or (b shl 16) or (g shl 8) or r
}
/**
* There are certain calling patterns during rendering where we may need to update a 3D LUT
* allocation using an IntArray of fixed size as often as several times per-second. This is a
* thread-safe way to not allocate big IntArrays repeatedly inside a render loop.
*/
object PooledBuffer {
private val pooledBuffer = AtomicReference<IntArray>()
fun acquire(size: Int): IntArray = pooledBuffer.getAndSet(null)
?.takeIf { it.size == size } ?: IntArray(size)
fun returnBuffer(buffer: IntArray) = pooledBuffer.compareAndSet(null, buffer)
fun release() = pooledBuffer.set(null)
}
} | mit | b80208ed13b91e9865d644a9b4d58fac | 38.751323 | 100 | 0.644968 | 3.968304 | false | false | false | false |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/util/SlippyMapMath.kt | 1 | 5012 | package de.westnordost.streetcomplete.util
import de.westnordost.osmapi.map.data.BoundingBox
import de.westnordost.osmapi.map.data.LatLon
import de.westnordost.osmapi.map.data.OsmLatLon
import java.io.Serializable
import kotlin.math.*
/** X and Y position of a tile */
data class Tile(val x: Int, val y:Int) {
/** Returns this tile rect as a bounding box */
fun asBoundingBox(zoom: Int): BoundingBox {
return BoundingBox(
tile2lat(y + 1, zoom),
tile2lon(x, zoom),
tile2lat(y, zoom),
tile2lon(x + 1, zoom)
)
}
fun toTilesRect() = TilesRect(x,y,x,y)
}
/** Returns the minimum rectangle of tiles that encloses all the tiles */
fun Collection<Tile>.minTileRect(): TilesRect? {
if (isEmpty()) return null
val right = maxByOrNull { it.x }!!.x
val left = minByOrNull { it.x }!!.x
val bottom = maxByOrNull { it.y }!!.y
val top = minByOrNull { it.y }!!.y
return TilesRect(left, top, right, bottom)
}
/** Returns the tile that encloses the position at the given zoom level */
fun LatLon.enclosingTile(zoom: Int): Tile {
return Tile(
lon2tile(((longitude + 180) % 360) - 180, zoom),
lat2tile(latitude, zoom)
)
}
/** A rectangle that represents containing all tiles from left bottom to top right */
data class TilesRect(val left: Int, val top: Int, val right: Int, val bottom: Int) : Serializable {
init {
require(left <= right && top <= bottom)
}
/** size of the tiles rect */
val size: Int get() = (bottom - top + 1) * (right - left + 1)
/** Returns all the individual tiles contained in this tile rect as an iterable sequence */
fun asTileSequence(): Sequence<Tile> = sequence {
for (y in top..bottom) {
for (x in left..right) {
yield(Tile(x, y))
}
}
}
/** Returns this tile rect as a bounding box */
fun asBoundingBox(zoom: Int): BoundingBox {
return BoundingBox(
tile2lat(bottom + 1, zoom),
tile2lon(left, zoom),
tile2lat(top, zoom),
tile2lon(right + 1, zoom)
)
}
fun zoom(from: Int, to: Int): TilesRect {
val delta = to - from
return when {
delta > 0 -> TilesRect(
left shl delta,
top shl delta,
right shl delta,
bottom shl delta
)
delta < 0 -> TilesRect(
left shr -delta,
top shr -delta,
right shr -delta,
bottom shr -delta
)
else -> this
}
}
fun getAsLeftBottomRightTopString() = "$left,$bottom,$right,$top"
}
/** Returns the bounding box of the tile rect at the given zoom level that encloses this bounding box.
* In other words, it expands this bounding box to fit to the tile boundaries.
* If this bounding box crosses the 180th meridian, it'll take only the first half of the bounding
* box*/
fun BoundingBox.asBoundingBoxOfEnclosingTiles(zoom: Int): BoundingBox {
return enclosingTilesRect(zoom).asBoundingBox(zoom)
}
/** Returns the tile rect that enclose this bounding box at the given zoom level. If this bounding
* box crosses the 180th meridian, it'll take only the first half of the bounding box */
fun BoundingBox.enclosingTilesRect(zoom: Int): TilesRect {
return if (crosses180thMeridian()) {
splitAt180thMeridian().first().enclosingTilesRectOfBBoxNotCrossing180thMeridian(zoom)
}
else {
enclosingTilesRectOfBBoxNotCrossing180thMeridian(zoom)
}
}
private fun BoundingBox.enclosingTilesRectOfBBoxNotCrossing180thMeridian(zoom: Int): TilesRect {
/* TilesRect.asBoundingBox returns a bounding box that intersects in line with the neighbouring
* tiles to ensure that there is no space between the tiles. So when converting a bounding box
* that exactly fits a tiles rect back to a tiles rect, it must be made smaller by the tiniest
* amount */
val notTheNextTile = 1e-7
val min = OsmLatLon(min.latitude + notTheNextTile, min.longitude + notTheNextTile)
val max = OsmLatLon(max.latitude - notTheNextTile, max.longitude - notTheNextTile)
val minTile = min.enclosingTile(zoom)
val maxTile = max.enclosingTile(zoom)
return TilesRect(minTile.x, maxTile.y, maxTile.x, minTile.y)
}
private fun tile2lon(x: Int, zoom: Int): Double =
x / numTiles(zoom).toDouble() * 360.0 - 180.0
private fun tile2lat(y: Int, zoom: Int): Double =
atan(sinh(PI - 2.0 * PI * y / numTiles(zoom))).toDegrees()
private fun lon2tile(lon: Double, zoom: Int): Int =
(numTiles(zoom) * (lon + 180.0) / 360.0).toInt()
private fun lat2tile(lat: Double, zoom: Int): Int =
(numTiles(zoom) * (1.0 - asinh(tan(lat.toRadians())) / PI) / 2.0).toInt()
private fun numTiles(zoom: Int): Int = 1 shl zoom
private fun Double.toDegrees() = this / PI * 180.0
private fun Double.toRadians() = this / 180.0 * PI
| gpl-3.0 | 1534cbe24191b9e4724573dc42573ccb | 34.546099 | 102 | 0.63747 | 3.900389 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/wishlist/dispatcher/WishlistActionDispatcher.kt | 1 | 2224 | package org.stepik.android.presentation.wishlist.dispatcher
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.rxkotlin.plusAssign
import io.reactivex.rxkotlin.subscribeBy
import org.stepic.droid.di.qualifiers.BackgroundScheduler
import org.stepic.droid.di.qualifiers.MainScheduler
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.wishlist.interactor.WishlistInteractor
import org.stepik.android.domain.wishlist.model.WishlistOperationData
import org.stepik.android.presentation.wishlist.WishlistFeature
import org.stepik.android.view.injection.course_list.WishlistOperationBus
import ru.nobird.android.domain.rx.emptyOnErrorStub
import ru.nobird.android.presentation.redux.dispatcher.RxActionDispatcher
import javax.inject.Inject
class WishlistActionDispatcher
@Inject
constructor(
private val wishlistInteractor: WishlistInteractor,
@WishlistOperationBus
private val wishlistOperationObservable: Observable<WishlistOperationData>,
@BackgroundScheduler
private val backgroundScheduler: Scheduler,
@MainScheduler
private val mainScheduler: Scheduler
) : RxActionDispatcher<WishlistFeature.Action, WishlistFeature.Message>() {
init {
compositeDisposable += wishlistOperationObservable
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onNext = { onNewMessage(WishlistFeature.Message.WishlistOperationUpdate(it)) },
onError = emptyOnErrorStub
)
}
override fun handleAction(action: WishlistFeature.Action) {
when (action) {
is WishlistFeature.Action.FetchWishList -> {
compositeDisposable += wishlistInteractor.getWishlistSyncedWithUserCourses(dataSourceType = DataSourceType.REMOTE)
.subscribeOn(backgroundScheduler)
.observeOn(mainScheduler)
.subscribeBy(
onSuccess = { onNewMessage(WishlistFeature.Message.FetchWishlistSuccess(it)) },
onError = { onNewMessage(WishlistFeature.Message.FetchWishListError) }
)
}
}
}
} | apache-2.0 | afeb53233c0fe26c40e33690fd9cabef | 42.627451 | 130 | 0.733363 | 5.411192 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/stdlib/OrderingTest/sortComparatorThenComparator.kt | 2 | 643 | import kotlin.test.*
import kotlin.comparisons.*
data class Item(val name: String, val rating: Int) : Comparable<Item> {
public override fun compareTo(other: Item): Int {
return compareValuesBy(this, other, { it.rating }, { it.name })
}
}
val v1 = Item("wine", 9)
val v2 = Item("beer", 10)
fun box() {
val comparator = Comparator<Item> { a, b -> a.name.compareTo(b.name) }.thenComparator { a, b -> a.rating.compareTo(b.rating) }
val diff = comparator.compare(v1, v2)
assertTrue(diff > 0)
val items = arrayListOf(v1, v2).sortedWith(comparator)
assertEquals(v2, items[0])
assertEquals(v1, items[1])
}
| apache-2.0 | 9bcbaf2829c5377311af0f44e6ea1b85 | 29.619048 | 130 | 0.654743 | 3.247475 | false | false | false | false |
CarlosEsco/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/ui/reader/viewer/navigation/LNavigation.kt | 1 | 942 | package eu.kanade.tachiyomi.ui.reader.viewer.navigation
import android.graphics.RectF
import eu.kanade.tachiyomi.ui.reader.viewer.ViewerNavigation
/**
* Visualization of default state without any inversion
* +---+---+---+
* | P | P | P | P: Previous
* +---+---+---+
* | P | M | N | M: Menu
* +---+---+---+
* | N | N | N | N: Next
* +---+---+---+
*/
open class LNavigation : ViewerNavigation() {
override var regions: List<Region> = listOf(
Region(
rectF = RectF(0f, 0.33f, 0.33f, 0.66f),
type = NavigationRegion.PREV,
),
Region(
rectF = RectF(0f, 0f, 1f, 0.33f),
type = NavigationRegion.PREV,
),
Region(
rectF = RectF(0.66f, 0.33f, 1f, 0.66f),
type = NavigationRegion.NEXT,
),
Region(
rectF = RectF(0f, 0.66f, 1f, 1f),
type = NavigationRegion.NEXT,
),
)
}
| apache-2.0 | 384d77a0758b80a92dd0ed8c2a788845 | 25.166667 | 60 | 0.508493 | 3.425455 | false | false | false | false |
bluelinelabs/Conductor | conductor-modules/viewpager2/src/main/java/com/bluelinelabs/conductor/viewpager2/RouterViewHolder.kt | 1 | 938 | package com.bluelinelabs.conductor.viewpager2
import android.view.ViewGroup
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.bluelinelabs.conductor.ChangeHandlerFrameLayout
import com.bluelinelabs.conductor.Router
class RouterViewHolder private constructor(val container: ChangeHandlerFrameLayout) : ViewHolder(container) {
var currentRouter: Router? = null
var currentItemPosition = 0
var currentItemId = 0L
var attached = false
companion object {
operator fun invoke(parent: ViewGroup): RouterViewHolder {
val container = ChangeHandlerFrameLayout(parent.context)
container.id = ViewCompat.generateViewId()
container.layoutParams = ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
container.isSaveEnabled = false
return RouterViewHolder(container)
}
}
} | apache-2.0 | 519935021f987e1f0c691ead3a3f2a48 | 33.777778 | 109 | 0.779318 | 5.043011 | false | false | false | false |
bajdcc/jMiniLang | src/main/kotlin/com/bajdcc/LALR1/interpret/module/ModuleFile.kt | 1 | 4795 | package com.bajdcc.LALR1.interpret.module
import com.bajdcc.LALR1.grammar.Grammar
import com.bajdcc.LALR1.grammar.runtime.*
import com.bajdcc.util.ResourceLoader
/**
* 【模块】文件模块
*
* @author bajdcc
*/
class ModuleFile : IInterpreterModule {
private var runtimeCodePage: RuntimeCodePage? = null
override val moduleName: String
get() = "sys.file"
override val moduleCode: String
get() = ResourceLoader.load(javaClass)
override val codePage: RuntimeCodePage
@Throws(Exception::class)
get() {
if (runtimeCodePage != null)
return runtimeCodePage!!
val base = ResourceLoader.load(javaClass)
val grammar = Grammar(base)
val page = grammar.codePage
val info = page.info
buildMethod(info)
runtimeCodePage = page
return page
}
private fun buildMethod(info: IRuntimeDebugInfo) {
info.addExternalFunc("g_create_file_internal",
RuntimeDebugExec("创建文件", arrayOf(RuntimeObjectType.kString, RuntimeObjectType.kInt, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val name = args[0].string
val mode = args[1].int
val encoding = args[2].string
RuntimeObject(status.service.fileService.create(name, mode, encoding, status.page))
}
})
info.addExternalFunc("g_destroy_file_internal",
RuntimeDebugExec("关闭文件", arrayOf(RuntimeObjectType.kPtr))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val handle = args[0].int
RuntimeObject(status.service.fileService.destroy(handle))
}
})
info.addExternalFunc("g_write_file_internal",
RuntimeDebugExec("写文件", arrayOf(RuntimeObjectType.kPtr, RuntimeObjectType.kChar))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val handle = args[0].int
val ch = args[1].char
RuntimeObject(status.service.fileService.write(handle, ch))
}
})
info.addExternalFunc("g_write_file_string_internal",
RuntimeDebugExec("写文件(字串)", arrayOf(RuntimeObjectType.kPtr, RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val handle = args[0].int
val str = args[1].string
RuntimeObject(status.service.fileService.writeString(handle, str))
}
})
info.addExternalFunc("g_read_file_internal",
RuntimeDebugExec("读文件", arrayOf(RuntimeObjectType.kPtr))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val handle = args[0].int
val ch = status.service.fileService.read(handle)
if (ch == -1) null else RuntimeObject(ch.toChar())
}
})
info.addExternalFunc("g_read_file_string_internal",
RuntimeDebugExec("读文件(行)", arrayOf(RuntimeObjectType.kPtr))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val handle = args[0].int
val str = status.service.fileService.readString(handle)
RuntimeObject(str)
}
})
info.addExternalFunc("g_query_file",
RuntimeDebugExec("判断文件是否存在", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val filename = args[0].string
RuntimeObject(status.service.fileService.exists(filename))
}
})
info.addExternalFunc("g_read_file_vfs_utf8",
RuntimeDebugExec("读文件(一次性),限VFS", arrayOf(RuntimeObjectType.kString))
{ args: List<RuntimeObject>, status: IRuntimeStatus ->
run {
val filename = args[0].string
RuntimeObject(status.service.fileService.readAll(filename))
}
})
}
companion object {
val instance = ModuleFile()
}
}
| mit | 289e5ba85fc7cb57d90df76c3500ce21 | 39.773913 | 127 | 0.525059 | 5.458673 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/accounts/login/jetpack/LoginNoSitesViewModel.kt | 1 | 3918 | package org.wordpress.android.ui.accounts.login.jetpack
import android.os.Bundle
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.withContext
import org.wordpress.android.WordPress
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.accounts.LoginNavigationEvents
import org.wordpress.android.ui.accounts.LoginNavigationEvents.ShowInstructions
import org.wordpress.android.ui.accounts.LoginNavigationEvents.ShowSignInForResultJetpackOnly
import org.wordpress.android.ui.accounts.UnifiedLoginTracker
import org.wordpress.android.ui.accounts.UnifiedLoginTracker.Step
import org.wordpress.android.ui.accounts.login.jetpack.LoginNoSitesViewModel.State.NoUser
import org.wordpress.android.ui.accounts.login.jetpack.LoginNoSitesViewModel.State.ShowUser
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ScopedViewModel
import java.io.Serializable
import javax.inject.Inject
import javax.inject.Named
const val KEY_STATE = "key_state"
@HiltViewModel
class LoginNoSitesViewModel @Inject constructor(
private val unifiedLoginTracker: UnifiedLoginTracker,
private val accountStore: AccountStore,
@Named(UI_THREAD) mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) val bgDispatcher: CoroutineDispatcher
) : ScopedViewModel(mainDispatcher) {
private val _navigationEvents = MediatorLiveData<Event<LoginNavigationEvents>>()
val navigationEvents: LiveData<Event<LoginNavigationEvents>> = _navigationEvents
private val _uiModel = MediatorLiveData<UiModel>()
val uiModel: LiveData<UiModel> = _uiModel
private var isStarted = false
fun start(application: WordPress, savedInstanceState: Bundle?) {
if (isStarted) return
isStarted = true
init(savedInstanceState)
signOutWordPress(application)
}
private fun init(savedInstanceState: Bundle?) {
val state = if (savedInstanceState != null) {
buildStateFromSavedInstanceState(savedInstanceState)
} else {
buildStateFromAccountStore()
}
_uiModel.postValue(UiModel(state = state))
}
private fun buildStateFromSavedInstanceState(savedInstanceState: Bundle) =
savedInstanceState.getSerializable(KEY_STATE) as State
private fun buildStateFromAccountStore() =
accountStore.account?.let {
ShowUser(
it.avatarUrl.orEmpty(),
it.userName,
it.displayName
)
} ?: NoUser
private fun signOutWordPress(application: WordPress) {
launch {
withContext(bgDispatcher) {
application.wordPressComSignOut()
}
}
}
fun onSeeInstructionsPressed() {
_navigationEvents.postValue(Event(ShowInstructions()))
}
fun onTryAnotherAccountPressed() {
_navigationEvents.postValue(Event(ShowSignInForResultJetpackOnly))
}
fun onFragmentResume() {
unifiedLoginTracker.track(step = Step.NO_JETPACK_SITES)
}
fun onBackPressed() {
_navigationEvents.postValue(Event(ShowSignInForResultJetpackOnly))
}
fun writeToBundle(outState: Bundle) {
requireNotNull(outState.putSerializable(KEY_STATE, uiModel.value?.state))
}
data class UiModel(
val state: State
)
@Suppress("SerialVersionUIDInSerializableClass")
sealed class State : Serializable {
object NoUser : State()
data class ShowUser(
val accountAvatarUrl: String,
val userName: String,
val displayName: String
) : State()
}
}
| gpl-2.0 | aef462d8031e442adebd4f5df1e89682 | 33.368421 | 93 | 0.720521 | 4.991083 | false | false | false | false |
c4gnv/things-android | app/src/main/java/c4gnv/com/thingsregistry/net/model/Thing.kt | 1 | 873 | package c4gnv.com.thingsregistry.net.model
import java.io.Serializable
import java.util.*
data class Thing(var id: String = "",
var serialNumber: String = "",
var name: String = "",
var description: String = "",
var icon: String = "",
var typeId: String = "",
var pieceId: List<Int> = ArrayList<Int>(),
var pieces: MutableList<Piece> = ArrayList<Piece>())
: Serializable {
companion object {
private const val serialVersionUID: Long = 1
}
override fun toString(): String {
return this.name
}
fun addPiece(piece: Piece) {
this.pieces.add(piece)
}
fun generateSerial() {
if (serialNumber.isNullOrEmpty()) {
this.serialNumber = UUID.randomUUID().toString()
}
}
}
| mit | fbbb9bc9aeb6330d6900c6ccebc0e284 | 25.454545 | 69 | 0.54181 | 4.619048 | false | false | false | false |
DanielGrech/anko | dsl/testData/functional/21s/ComplexListenerClassTest.kt | 6 | 12236 | class __GestureOverlayView_OnGestureListener : android.gesture.GestureOverlayView.OnGestureListener {
private var _onGestureStarted: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
private var _onGesture: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
private var _onGestureEnded: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
private var _onGestureCancelled: ((android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit)? = null
override fun onGestureStarted(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) = _onGestureStarted?.invoke(overlay, event)
public fun onGestureStarted(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureStarted = listener
}
override fun onGesture(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) = _onGesture?.invoke(overlay, event)
public fun onGesture(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGesture = listener
}
override fun onGestureEnded(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) = _onGestureEnded?.invoke(overlay, event)
public fun onGestureEnded(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureEnded = listener
}
override fun onGestureCancelled(overlay: android.gesture.GestureOverlayView?, event: android.view.MotionEvent?) = _onGestureCancelled?.invoke(overlay, event)
public fun onGestureCancelled(listener: (android.gesture.GestureOverlayView?, android.view.MotionEvent?) -> Unit) {
_onGestureCancelled = listener
}
}
class __GestureOverlayView_OnGesturingListener : android.gesture.GestureOverlayView.OnGesturingListener {
private var _onGesturingStarted: ((android.gesture.GestureOverlayView?) -> Unit)? = null
private var _onGesturingEnded: ((android.gesture.GestureOverlayView?) -> Unit)? = null
override fun onGesturingStarted(overlay: android.gesture.GestureOverlayView?) = _onGesturingStarted?.invoke(overlay)
public fun onGesturingStarted(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingStarted = listener
}
override fun onGesturingEnded(overlay: android.gesture.GestureOverlayView?) = _onGesturingEnded?.invoke(overlay)
public fun onGesturingEnded(listener: (android.gesture.GestureOverlayView?) -> Unit) {
_onGesturingEnded = listener
}
}
class __ViewPagerSupport_OnPageChangeListener : android.support.v4.view.ViewPager.OnPageChangeListener {
private var _onPageScrolled: ((Int, Float, Int) -> Unit)? = null
private var _onPageSelected: ((Int) -> Unit)? = null
private var _onPageScrollStateChanged: ((Int) -> Unit)? = null
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) = _onPageScrolled?.invoke(position, positionOffset, positionOffsetPixels)
public fun onPageScrolled(listener: (Int, Float, Int) -> Unit) {
_onPageScrolled = listener
}
override fun onPageSelected(position: Int) = _onPageSelected?.invoke(position)
public fun onPageSelected(listener: (Int) -> Unit) {
_onPageSelected = listener
}
override fun onPageScrollStateChanged(state: Int) = _onPageScrollStateChanged?.invoke(state)
public fun onPageScrollStateChanged(listener: (Int) -> Unit) {
_onPageScrollStateChanged = listener
}
}
class __SearchViewSupport_OnQueryTextListener : android.support.v7.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: ((String?) -> Boolean)? = null
private var _onQueryTextChange: ((String?) -> Boolean)? = null
override fun onQueryTextSubmit(query: String?) = _onQueryTextSubmit?.invoke(query) ?: false
public fun onQueryTextSubmit(listener: (String?) -> Boolean) {
_onQueryTextSubmit = listener
}
override fun onQueryTextChange(newText: String?) = _onQueryTextChange?.invoke(newText) ?: false
public fun onQueryTextChange(listener: (String?) -> Boolean) {
_onQueryTextChange = listener
}
}
class __SearchViewSupport_OnSuggestionListener : android.support.v7.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: ((Int) -> Boolean)? = null
private var _onSuggestionClick: ((Int) -> Boolean)? = null
override fun onSuggestionSelect(position: Int) = _onSuggestionSelect?.invoke(position) ?: false
public fun onSuggestionSelect(listener: (Int) -> Boolean) {
_onSuggestionSelect = listener
}
override fun onSuggestionClick(position: Int) = _onSuggestionClick?.invoke(position) ?: false
public fun onSuggestionClick(listener: (Int) -> Boolean) {
_onSuggestionClick = listener
}
}
class __View_OnAttachStateChangeListener : android.view.View.OnAttachStateChangeListener {
private var _onViewAttachedToWindow: ((android.view.View) -> Unit)? = null
private var _onViewDetachedFromWindow: ((android.view.View) -> Unit)? = null
override fun onViewAttachedToWindow(v: android.view.View) = _onViewAttachedToWindow?.invoke(v)
public fun onViewAttachedToWindow(listener: (android.view.View) -> Unit) {
_onViewAttachedToWindow = listener
}
override fun onViewDetachedFromWindow(v: android.view.View) = _onViewDetachedFromWindow?.invoke(v)
public fun onViewDetachedFromWindow(listener: (android.view.View) -> Unit) {
_onViewDetachedFromWindow = listener
}
}
class __ViewGroup_OnHierarchyChangeListener : android.view.ViewGroup.OnHierarchyChangeListener {
private var _onChildViewAdded: ((android.view.View?, android.view.View?) -> Unit)? = null
private var _onChildViewRemoved: ((android.view.View?, android.view.View?) -> Unit)? = null
override fun onChildViewAdded(parent: android.view.View?, child: android.view.View?) = _onChildViewAdded?.invoke(parent, child)
public fun onChildViewAdded(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewAdded = listener
}
override fun onChildViewRemoved(parent: android.view.View?, child: android.view.View?) = _onChildViewRemoved?.invoke(parent, child)
public fun onChildViewRemoved(listener: (android.view.View?, android.view.View?) -> Unit) {
_onChildViewRemoved = listener
}
}
class __AbsListView_OnScrollListener : android.widget.AbsListView.OnScrollListener {
private var _onScrollStateChanged: ((android.widget.AbsListView?, Int) -> Unit)? = null
private var _onScroll: ((android.widget.AbsListView, Int, Int, Int) -> Unit)? = null
override fun onScrollStateChanged(view: android.widget.AbsListView?, scrollState: Int) = _onScrollStateChanged?.invoke(view, scrollState)
public fun onScrollStateChanged(listener: (android.widget.AbsListView?, Int) -> Unit) {
_onScrollStateChanged = listener
}
override fun onScroll(view: android.widget.AbsListView, firstVisibleItem: Int, visibleItemCount: Int, totalItemCount: Int) = _onScroll?.invoke(view, firstVisibleItem, visibleItemCount, totalItemCount)
public fun onScroll(listener: (android.widget.AbsListView, Int, Int, Int) -> Unit) {
_onScroll = listener
}
}
class __AdapterView_OnItemSelectedListener : android.widget.AdapterView.OnItemSelectedListener {
private var _onItemSelected: ((android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit)? = null
private var _onNothingSelected: ((android.widget.AdapterView<*>?) -> Unit)? = null
override fun onItemSelected(p0: android.widget.AdapterView<*>?, p1: android.view.View?, p2: Int, p3: Long) = _onItemSelected?.invoke(p0, p1, p2, p3)
public fun onItemSelected(listener: (android.widget.AdapterView<*>?, android.view.View?, Int, Long) -> Unit) {
_onItemSelected = listener
}
override fun onNothingSelected(p0: android.widget.AdapterView<*>?) = _onNothingSelected?.invoke(p0)
public fun onNothingSelected(listener: (android.widget.AdapterView<*>?) -> Unit) {
_onNothingSelected = listener
}
}
class __SearchView_OnQueryTextListener : android.widget.SearchView.OnQueryTextListener {
private var _onQueryTextSubmit: ((String?) -> Boolean)? = null
private var _onQueryTextChange: ((String?) -> Boolean)? = null
override fun onQueryTextSubmit(query: String?) = _onQueryTextSubmit?.invoke(query) ?: false
public fun onQueryTextSubmit(listener: (String?) -> Boolean) {
_onQueryTextSubmit = listener
}
override fun onQueryTextChange(newText: String?) = _onQueryTextChange?.invoke(newText) ?: false
public fun onQueryTextChange(listener: (String?) -> Boolean) {
_onQueryTextChange = listener
}
}
class __SearchView_OnSuggestionListener : android.widget.SearchView.OnSuggestionListener {
private var _onSuggestionSelect: ((Int) -> Boolean)? = null
private var _onSuggestionClick: ((Int) -> Boolean)? = null
override fun onSuggestionSelect(position: Int) = _onSuggestionSelect?.invoke(position) ?: false
public fun onSuggestionSelect(listener: (Int) -> Boolean) {
_onSuggestionSelect = listener
}
override fun onSuggestionClick(position: Int) = _onSuggestionClick?.invoke(position) ?: false
public fun onSuggestionClick(listener: (Int) -> Boolean) {
_onSuggestionClick = listener
}
}
class __SeekBar_OnSeekBarChangeListener : android.widget.SeekBar.OnSeekBarChangeListener {
private var _onProgressChanged: ((android.widget.SeekBar, Int, Boolean) -> Unit)? = null
private var _onStartTrackingTouch: ((android.widget.SeekBar?) -> Unit)? = null
private var _onStopTrackingTouch: ((android.widget.SeekBar) -> Unit)? = null
override fun onProgressChanged(seekBar: android.widget.SeekBar, progress: Int, fromUser: Boolean) = _onProgressChanged?.invoke(seekBar, progress, fromUser)
public fun onProgressChanged(listener: (android.widget.SeekBar, Int, Boolean) -> Unit) {
_onProgressChanged = listener
}
override fun onStartTrackingTouch(seekBar: android.widget.SeekBar?) = _onStartTrackingTouch?.invoke(seekBar)
public fun onStartTrackingTouch(listener: (android.widget.SeekBar?) -> Unit) {
_onStartTrackingTouch = listener
}
override fun onStopTrackingTouch(seekBar: android.widget.SeekBar) = _onStopTrackingTouch?.invoke(seekBar)
public fun onStopTrackingTouch(listener: (android.widget.SeekBar) -> Unit) {
_onStopTrackingTouch = listener
}
}
class __SlidingDrawer_OnDrawerScrollListener : android.widget.SlidingDrawer.OnDrawerScrollListener {
private var _onScrollStarted: (() -> Unit)? = null
private var _onScrollEnded: (() -> Unit)? = null
override fun onScrollStarted() = _onScrollStarted?.invoke()
public fun onScrollStarted(listener: () -> Unit) {
_onScrollStarted = listener
}
override fun onScrollEnded() = _onScrollEnded?.invoke()
public fun onScrollEnded(listener: () -> Unit) {
_onScrollEnded = listener
}
}
class __TextWatcher : android.text.TextWatcher {
private var _beforeTextChanged: ((CharSequence?, Int, Int, Int) -> Unit)? = null
private var _onTextChanged: ((CharSequence, Int, Int, Int) -> Unit)? = null
private var _afterTextChanged: ((android.text.Editable?) -> Unit)? = null
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) = _beforeTextChanged?.invoke(s, start, count, after)
public fun beforeTextChanged(listener: (CharSequence?, Int, Int, Int) -> Unit) {
_beforeTextChanged = listener
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) = _onTextChanged?.invoke(s, start, before, count)
public fun onTextChanged(listener: (CharSequence, Int, Int, Int) -> Unit) {
_onTextChanged = listener
}
override fun afterTextChanged(s: android.text.Editable?) = _afterTextChanged?.invoke(s)
public fun afterTextChanged(listener: (android.text.Editable?) -> Unit) {
_afterTextChanged = listener
}
} | apache-2.0 | 6c99593dfe18badce73d8f24744cb88c | 41.786713 | 204 | 0.720987 | 4.836364 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/editor/KotlinSmartEnterHandler.kt | 1 | 5962 | // 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.editor
import com.intellij.lang.SmartEnterProcessorWithFixers
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.tree.TokenSet
import com.intellij.util.text.CharArrayUtil
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.idea.editor.fixers.*
import org.jetbrains.kotlin.idea.formatter.kotlinCommonSettings
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class KotlinSmartEnterHandler : SmartEnterProcessorWithFixers() {
init {
addFixers(
KotlinIfConditionFixer(),
KotlinMissingIfBranchFixer(),
KotlinWhileConditionFixer(),
KotlinForConditionFixer(),
KotlinMissingForOrWhileBodyFixer(),
KotlinWhenSubjectCaretFixer(),
KotlinMissingWhenBodyFixer(),
KotlinMissingWhenEntryBodyFixer(),
KotlinDoWhileFixer(),
KotlinFunctionParametersFixer(),
KotlinFunctionDeclarationBodyFixer(),
KotlinPropertySetterParametersFixer(),
KotlinPropertyAccessorBodyFixer(),
KotlinTryBodyFixer(),
KotlinCatchParameterFixer(),
KotlinCatchBodyFixer(),
KotlinFinallyBodyFixer(),
KotlinLastLambdaParameterFixer(),
KotlinClassInitializerFixer(),
KotlinClassBodyFixer(),
KotlinValueArgumentListFixer()
)
addEnterProcessors(KotlinPlainEnterProcessor())
}
override fun getStatementAtCaret(editor: Editor?, psiFile: PsiFile?): PsiElement? {
var atCaret = super.getStatementAtCaret(editor, psiFile)
if (atCaret is PsiWhiteSpace) return null
while (atCaret != null) {
when {
atCaret.isKotlinStatement() -> return atCaret
atCaret.parent is KtFunctionLiteral -> return atCaret
atCaret is KtDeclaration -> {
val declaration = atCaret
when {
declaration is KtParameter && !declaration.isInLambdaExpression() -> {/* proceed to function declaration */
}
declaration.parent is KtForExpression -> {/* skip variable declaration in 'for' expression */
}
else -> return atCaret
}
}
}
atCaret = atCaret.parent
}
return null
}
override fun moveCaretInsideBracesIfAny(editor: Editor, file: PsiFile) {
var caretOffset = editor.caretModel.offset
val chars = editor.document.charsSequence
if (CharArrayUtil.regionMatches(chars, caretOffset, "{}")) {
caretOffset += 2
} else {
if (CharArrayUtil.regionMatches(chars, caretOffset, "{\n}")) {
caretOffset += 3
}
}
caretOffset = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t") + 1
if (CharArrayUtil.regionMatches(chars, caretOffset - "{}".length, "{}") ||
CharArrayUtil.regionMatches(chars, caretOffset - "{\n}".length, "{\n}")
) {
commit(editor)
val settings = file.kotlinCommonSettings
val old = settings.KEEP_LINE_BREAKS
settings.KEEP_LINE_BREAKS = true
file.findElementAt(caretOffset - 1)?.getStrictParentOfType<KtBlockExpression>()?.let(::reformat)
settings.KEEP_LINE_BREAKS = old
editor.caretModel.moveToOffset(caretOffset - 1)
}
}
private fun PsiElement.isKotlinStatement() = when {
parent is KtBlockExpression && node?.elementType !in BRACES -> true
parent?.node?.elementType in BRANCH_CONTAINERS && this !is KtBlockExpression -> true
else -> false
}
class KotlinPlainEnterProcessor : SmartEnterProcessorWithFixers.FixEnterProcessor() {
private fun getControlStatementBlock(caret: Int, element: PsiElement): KtExpression? {
when (element) {
is KtDeclarationWithBody -> return element.bodyExpression
is KtIfExpression -> {
if (element.then.isWithCaret(caret)) return element.then
if (element.`else`.isWithCaret(caret)) return element.`else`
}
is KtLoopExpression -> return element.body
}
return null
}
override fun doEnter(atCaret: PsiElement, file: PsiFile?, editor: Editor, modified: Boolean): Boolean {
if (modified && atCaret is KtCallExpression) return true
val block = getControlStatementBlock(editor.caretModel.offset, atCaret) as? KtBlockExpression
if (block != null) {
val firstElement = block.firstChild?.nextSibling
val offset = if (firstElement != null) {
firstElement.textRange!!.startOffset - 1
} else {
block.textRange!!.endOffset
}
editor.caretModel.moveToOffset(offset)
}
plainEnter(editor)
return true
}
}
override fun processDefaultEnter(project: Project, editor: Editor, file: PsiFile) {
plainEnter(editor)
}
}
private val BRANCH_CONTAINERS = TokenSet.create(KtNodeTypes.THEN, KtNodeTypes.ELSE, KtNodeTypes.BODY)
private val BRACES = TokenSet.create(KtTokens.RBRACE, KtTokens.LBRACE)
private fun KtParameter.isInLambdaExpression() = this.parent.parent is KtFunctionLiteral
| apache-2.0 | 554f4e4bc21aa37551366db6d9622aa0 | 35.802469 | 158 | 0.626635 | 5.619227 | false | false | false | false |
square/picasso | picasso/src/main/java/com/squareup/picasso3/Request.kt | 1 | 16911 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.picasso3
import android.graphics.Bitmap.Config
import android.net.Uri
import android.os.Looper
import android.view.Gravity
import androidx.annotation.DrawableRes
import androidx.annotation.Px
import com.squareup.picasso3.Picasso.Priority
import com.squareup.picasso3.Picasso.Priority.NORMAL
import okhttp3.Headers
import java.util.concurrent.TimeUnit.NANOSECONDS
import java.util.concurrent.TimeUnit.SECONDS
/** Immutable data about an image and the transformations that will be applied to it. */
class Request internal constructor(builder: Builder) {
/** A unique ID for the request. */
@JvmField var id = 0
/** The time that the request was first submitted (in nanos). */
@JvmField var started: Long = 0
/** The [MemoryPolicy] to use for this request. */
@JvmField val memoryPolicy: Int = builder.memoryPolicy
/** The [NetworkPolicy] to use for this request. */
@JvmField val networkPolicy: Int = builder.networkPolicy
/** HTTP headers for the request */
@JvmField val headers: Headers? = builder.headers
/**
* The image URI.
*
* This is mutually exclusive with [.resourceId].
*/
@JvmField val uri: Uri? = builder.uri
/**
* The image resource ID.
*
* This is mutually exclusive with [.uri].
*/
@JvmField val resourceId: Int = builder.resourceId
/**
* Optional stable key for this request to be used instead of the URI or resource ID when
* caching. Two requests with the same value are considered to be for the same resource.
*/
val stableKey: String? = builder.stableKey
/** List of custom transformations to be applied after the built-in transformations. */
@JvmField var transformations: List<Transformation> =
if (builder.transformations == null) {
emptyList()
} else {
builder.transformations!!.toList()
}
/** Target image width for resizing. */
@JvmField val targetWidth: Int = builder.targetWidth
/** Target image height for resizing. */
@JvmField val targetHeight: Int = builder.targetHeight
/**
* True if the final image should use the 'centerCrop' scale technique.
*
* This is mutually exclusive with [.centerInside].
*/
@JvmField val centerCrop: Boolean = builder.centerCrop
/** If centerCrop is set, controls alignment of centered image */
@JvmField val centerCropGravity: Int = builder.centerCropGravity
/**
* True if the final image should use the 'centerInside' scale technique.
*
* This is mutually exclusive with [.centerCrop].
*/
@JvmField val centerInside: Boolean = builder.centerInside
@JvmField val onlyScaleDown: Boolean = builder.onlyScaleDown
/** Amount to rotate the image in degrees. */
@JvmField val rotationDegrees: Float = builder.rotationDegrees
/** Rotation pivot on the X axis. */
@JvmField val rotationPivotX: Float = builder.rotationPivotX
/** Rotation pivot on the Y axis. */
@JvmField val rotationPivotY: Float = builder.rotationPivotY
/** Whether or not [.rotationPivotX] and [.rotationPivotY] are set. */
@JvmField val hasRotationPivot: Boolean = builder.hasRotationPivot
/** Target image config for decoding. */
@JvmField val config: Config? = builder.config
/** The priority of this request. */
@JvmField val priority: Priority = checkNotNull(builder.priority)
/** The cache key for this request. */
@JvmField var key: String =
if (Looper.myLooper() == Looper.getMainLooper()) {
createKey()
} else {
createKey(StringBuilder())
}
/** User-provided value to track this request. */
val tag: Any? = builder.tag
override fun toString() =
buildString {
append("Request{")
if (resourceId > 0) {
append(resourceId)
} else {
append(uri)
}
for (transformation in transformations) {
append(' ')
append(transformation.key())
}
if (stableKey != null) {
append(" stableKey(")
append(stableKey)
append(')')
}
if (targetWidth > 0) {
append(" resize(")
append(targetWidth)
append(',')
append(targetHeight)
append(')')
}
if (centerCrop) {
append(" centerCrop")
}
if (centerInside) {
append(" centerInside")
}
if (rotationDegrees != 0f) {
append(" rotation(")
append(rotationDegrees)
if (hasRotationPivot) {
append(" @ ")
append(rotationPivotX)
append(',')
append(rotationPivotY)
}
append(')')
}
if (config != null) {
append(' ')
append(config)
}
append('}')
}
// TODO make internal
fun logId(): String {
val delta = System.nanoTime() - started
return if (delta > TOO_LONG_LOG) {
"${plainId()}+${NANOSECONDS.toSeconds(delta)}s"
} else {
"${plainId()}+${NANOSECONDS.toMillis(delta)}ms"
}
}
// TODO make internal
fun plainId() = "[R$id]"
// TODO make internal
val name: String
get() = uri?.path ?: Integer.toHexString(resourceId)
// TODO make internal
fun hasSize(): Boolean = targetWidth != 0 || targetHeight != 0
// TODO make internal
fun needsMatrixTransform(): Boolean = hasSize() || rotationDegrees != 0f
fun newBuilder(): Builder = Builder(this)
private fun createKey(): String {
val result = createKey(Utils.MAIN_THREAD_KEY_BUILDER)
Utils.MAIN_THREAD_KEY_BUILDER.setLength(0)
return result
}
private fun createKey(builder: StringBuilder): String {
val data = this
if (data.stableKey != null) {
builder.ensureCapacity(data.stableKey.length + KEY_PADDING)
builder.append(data.stableKey)
} else if (data.uri != null) {
val path = data.uri.toString()
builder.ensureCapacity(path.length + KEY_PADDING)
builder.append(path)
} else {
builder.ensureCapacity(KEY_PADDING)
builder.append(data.resourceId)
}
builder.append(KEY_SEPARATOR)
if (data.rotationDegrees != 0f) {
builder
.append("rotation:")
.append(data.rotationDegrees)
if (data.hasRotationPivot) {
builder
.append('@')
.append(data.rotationPivotX)
.append('x')
.append(data.rotationPivotY)
}
builder.append(KEY_SEPARATOR)
}
if (data.hasSize()) {
builder
.append("resize:")
.append(data.targetWidth)
.append('x')
.append(data.targetHeight)
builder.append(KEY_SEPARATOR)
}
if (data.centerCrop) {
builder
.append("centerCrop:")
.append(data.centerCropGravity)
.append(KEY_SEPARATOR)
} else if (data.centerInside) {
builder
.append("centerInside")
.append(KEY_SEPARATOR)
}
for (i in data.transformations.indices) {
builder.append(data.transformations[i].key())
builder.append(KEY_SEPARATOR)
}
return builder.toString()
}
/** Builder for creating [Request] instances. */
class Builder {
var uri: Uri? = null
var resourceId = 0
var stableKey: String? = null
var targetWidth = 0
var targetHeight = 0
var centerCrop = false
var centerCropGravity = 0
var centerInside = false
var onlyScaleDown = false
var rotationDegrees = 0f
var rotationPivotX = 0f
var rotationPivotY = 0f
var hasRotationPivot = false
var transformations: MutableList<Transformation>? = null
var config: Config? = null
var priority: Priority? = null
/** Internal use only. Used by [DeferredRequestCreator]. */
var tag: Any? = null
var memoryPolicy = 0
var networkPolicy = 0
var headers: Headers? = null
/** Start building a request using the specified [Uri]. */
constructor(uri: Uri) {
setUri(uri)
}
/** Start building a request using the specified resource ID. */
constructor(@DrawableRes resourceId: Int) {
setResourceId(resourceId)
}
internal constructor(
uri: Uri?,
resourceId: Int,
bitmapConfig: Config?
) {
this.uri = uri
this.resourceId = resourceId
config = bitmapConfig
}
internal constructor(request: Request) {
uri = request.uri
resourceId = request.resourceId
stableKey = request.stableKey
targetWidth = request.targetWidth
targetHeight = request.targetHeight
centerCrop = request.centerCrop
centerInside = request.centerInside
centerCropGravity = request.centerCropGravity
rotationDegrees = request.rotationDegrees
rotationPivotX = request.rotationPivotX
rotationPivotY = request.rotationPivotY
hasRotationPivot = request.hasRotationPivot
onlyScaleDown = request.onlyScaleDown
transformations = request.transformations.toMutableList()
config = request.config
priority = request.priority
memoryPolicy = request.memoryPolicy
networkPolicy = request.networkPolicy
}
fun hasImage(): Boolean {
return uri != null || resourceId != 0
}
fun hasSize(): Boolean {
return targetWidth != 0 || targetHeight != 0
}
fun hasPriority(): Boolean {
return priority != null
}
/**
* Set the target image Uri.
*
* This will clear an image resource ID if one is set.
*/
fun setUri(uri: Uri) = apply {
this.uri = uri
resourceId = 0
}
/**
* Set the target image resource ID.
*
* This will clear an image Uri if one is set.
*/
fun setResourceId(@DrawableRes resourceId: Int) = apply {
require(resourceId != 0) { "Image resource ID may not be 0." }
this.resourceId = resourceId
uri = null
}
/**
* Set the stable key to be used instead of the URI or resource ID when caching.
* Two requests with the same value are considered to be for the same resource.
*/
fun stableKey(stableKey: String?) = apply {
this.stableKey = stableKey
}
/**
* Assign a tag to this request.
*/
fun tag(tag: Any) = apply {
check(this.tag == null) { "Tag already set." }
this.tag = tag
}
/** Internal use only. Used by [DeferredRequestCreator]. */
fun clearTag() = apply {
tag = null
}
/**
* Resize the image to the specified size in pixels.
* Use 0 as desired dimension to resize keeping aspect ratio.
*/
fun resize(@Px targetWidth: Int, @Px targetHeight: Int) = apply {
require(targetWidth >= 0) { "Width must be positive number or 0." }
require(targetHeight >= 0) { "Height must be positive number or 0." }
require(
!(targetHeight == 0 && targetWidth == 0)
) { "At least one dimension has to be positive number." }
this.targetWidth = targetWidth
this.targetHeight = targetHeight
}
/** Clear the resize transformation, if any. This will also clear center crop/inside if set. */
fun clearResize() = apply {
targetWidth = 0
targetHeight = 0
centerCrop = false
centerInside = false
}
/**
* Crops an image inside of the bounds specified by [resize] rather than
* distorting the aspect ratio. This cropping technique scales the image so that it fills the
* requested bounds and then crops the extra.
*/
@JvmOverloads
fun centerCrop(alignGravity: Int = Gravity.CENTER) = apply {
check(!centerInside) { "Center crop can not be used after calling centerInside" }
centerCrop = true
centerCropGravity = alignGravity
}
/** Clear the center crop transformation flag, if set. */
fun clearCenterCrop() = apply {
centerCrop = false
centerCropGravity = Gravity.CENTER
}
/**
* Centers an image inside of the bounds specified by [resize]. This scales
* the image so that both dimensions are equal to or less than the requested bounds.
*/
fun centerInside() = apply {
check(!centerCrop) { "Center inside can not be used after calling centerCrop" }
centerInside = true
}
/** Clear the center inside transformation flag, if set. */
fun clearCenterInside() = apply {
centerInside = false
}
/**
* Only resize an image if the original image size is bigger than the target size
* specified by [resize].
*/
fun onlyScaleDown() = apply {
check(!(targetHeight == 0 && targetWidth == 0)) {
"onlyScaleDown can not be applied without resize"
}
onlyScaleDown = true
}
/** Clear the onlyScaleUp flag, if set. */
fun clearOnlyScaleDown() = apply {
onlyScaleDown = false
}
/** Rotate the image by the specified degrees. */
fun rotate(degrees: Float) = apply {
rotationDegrees = degrees
}
/** Rotate the image by the specified degrees around a pivot point. */
fun rotate(
degrees: Float,
pivotX: Float,
pivotY: Float
) = apply {
rotationDegrees = degrees
rotationPivotX = pivotX
rotationPivotY = pivotY
hasRotationPivot = true
}
/** Clear the rotation transformation, if any. */
fun clearRotation() = apply {
rotationDegrees = 0f
rotationPivotX = 0f
rotationPivotY = 0f
hasRotationPivot = false
}
/** Decode the image using the specified config. */
fun config(config: Config) = apply {
this.config = config
}
/** Execute request using the specified priority. */
fun priority(priority: Priority) = apply {
check(this.priority == null) { "Priority already set." }
this.priority = priority
}
/**
* Add a custom transformation to be applied to the image.
*
* Custom transformations will always be run after the built-in transformations.
*/
fun transform(transformation: Transformation) = apply {
requireNotNull(transformation.key()) { "Transformation key must not be null." }
if (transformations == null) {
transformations = ArrayList(2)
}
transformations!!.add(transformation)
}
/**
* Add a list of custom transformations to be applied to the image.
*
*
* Custom transformations will always be run after the built-in transformations.
*/
fun transform(transformations: List<Transformation>) = apply {
for (i in transformations.indices) {
transform(transformations[i])
}
}
/**
* Specifies the [MemoryPolicy] to use for this request. You may specify additional policy
* options using the varargs parameter.
*/
fun memoryPolicy(
policy: MemoryPolicy,
vararg additional: MemoryPolicy
) = apply {
memoryPolicy = memoryPolicy or policy.index
for (i in additional.indices) {
this.memoryPolicy = this.memoryPolicy or additional[i].index
}
}
/**
* Specifies the [NetworkPolicy] to use for this request. You may specify additional
* policy options using the varargs parameter.
*/
fun networkPolicy(
policy: NetworkPolicy,
vararg additional: NetworkPolicy
) = apply {
networkPolicy = networkPolicy or policy.index
for (i in additional.indices) {
this.networkPolicy = this.networkPolicy or additional[i].index
}
}
fun addHeader(
name: String,
value: String
) = apply {
this.headers = (headers?.newBuilder() ?: Headers.Builder())
.add(name, value)
.build()
}
/** Create the immutable [Request] object. */
fun build(): Request {
check(!(centerInside && centerCrop)) {
"Center crop and center inside can not be used together."
}
check(!(centerCrop && targetWidth == 0 && targetHeight == 0)) {
"Center crop requires calling resize with positive width and height."
}
check(!(centerInside && targetWidth == 0 && targetHeight == 0)) {
"Center inside requires calling resize with positive width and height."
}
if (priority == null) {
priority = NORMAL
}
return Request(this)
}
}
internal companion object {
private val TOO_LONG_LOG = SECONDS.toNanos(5)
private const val KEY_PADDING = 50 // Determined by exact science.
const val KEY_SEPARATOR = '\n'
}
}
| apache-2.0 | e7cc5669033eacbe48e87d4283c35f1b | 28.106713 | 100 | 0.637337 | 4.624282 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.