repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
wix/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/ReactImageMatrixAnimator.kt | 1 | 2970 | package com.reactnativenavigation.views.element.animators
import android.animation.Animator
import android.animation.ObjectAnimator
import android.graphics.PointF
import android.graphics.Rect
import android.view.View
import com.facebook.drawee.drawable.ScalingUtils
import com.facebook.drawee.drawable.ScalingUtils.InterpolatingScaleType
import com.facebook.react.views.image.ImageResizeMode
import com.facebook.react.views.image.ReactImageView
import com.reactnativenavigation.options.SharedElementTransitionOptions
import com.reactnativenavigation.utils.ViewUtils
import kotlin.math.max
import kotlin.math.roundToInt
class ReactImageMatrixAnimator(from: View, to: View) : PropertyAnimatorCreator<ReactImageView>(from, to) {
override fun shouldAnimateProperty(fromChild: ReactImageView, toChild: ReactImageView): Boolean {
return !ViewUtils.areDimensionsEqual(from, to)
}
override fun create(options: SharedElementTransitionOptions): Animator {
from as ReactImageView
with(to as ReactImageView) {
to.hierarchy.fadeDuration = 0
val parentScaleX = (from.parent as View).scaleX
val parentScalyY = (from.parent as View).scaleY
val fromBounds = calculateBounds(from, parentScaleX, parentScalyY)
hierarchy.actualImageScaleType = InterpolatingScaleType(
getScaleType(from),
getScaleType(to),
fromBounds,
calculateBounds(to),
PointF(from.width * parentScaleX / 2f, from.height * parentScalyY / 2f),
PointF(to.width / 2f, to.height / 2f)
)
to.layoutParams.width = max(from.width, to.width)
to.layoutParams.height = max(from.height, to.height)
return ObjectAnimator.ofObject({ fraction: Float, _: Any, _: Any ->
hierarchy.actualImageScaleType?.let {
(hierarchy.actualImageScaleType as? InterpolatingScaleType)?.let {
it.value = fraction
to.invalidate()
}
}
null
}, 0f, 1f)
}
}
private fun getScaleType(child: View): ScalingUtils.ScaleType {
return getScaleType(
child as ReactImageView, child.hierarchy.actualImageScaleType ?: ImageResizeMode.defaultValue()
)
}
private fun getScaleType(child: ReactImageView, scaleType: ScalingUtils.ScaleType): ScalingUtils.ScaleType {
if (scaleType is InterpolatingScaleType) return getScaleType(child, scaleType.scaleTypeTo)
return scaleType
}
private fun calculateBounds(view: View, parentScaleX: Float = 1f, parentScaleY: Float = 1f) =
Rect(
0,
0,
(view.width * parentScaleX).roundToInt(),
(view.height * parentScaleY).roundToInt()
)
}
| mit | 03f1fa2d9a9a3946fc9fd639cc406a83 | 40.830986 | 112 | 0.648485 | 5.068259 | false | false | false | false |
ShadwLink/Shadow-Mapper | src/main/java/nl/shadowlink/tools/shadowlib/water/WaterPoint.kt | 1 | 782 | package nl.shadowlink.tools.shadowlib.water
import nl.shadowlink.tools.io.Vector3D
/**
* @author Shadow-Link
*/
class WaterPoint(line: String) {
@JvmField
var coord: Vector3D
var speedX: Float
var speedY: Float
var unknown: Float
var waveHeight: Float
init {
val split = line.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
coord = Vector3D(
java.lang.Float.valueOf(split[0]), java.lang.Float.valueOf(split[1]), java.lang.Float.valueOf(
split[2]
)
)
speedX = java.lang.Float.valueOf(split[3])
speedY = java.lang.Float.valueOf(split[4])
unknown = java.lang.Float.valueOf(split[5])
waveHeight = java.lang.Float.valueOf(split[6])
}
} | gpl-2.0 | 7fd59946cfee1a711c0f2f9146f0d508 | 26.964286 | 106 | 0.617647 | 3.637209 | false | false | false | false |
da1z/intellij-community | platform/projectModel-api/src/com/intellij/openapi/module/ModuleGrouper.kt | 4 | 4960 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.module
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.annotations.ApiStatus
import java.util.*
/**
* Use this class to determine how modules show by organized in a tree. It supports the both ways of module grouping: the old one where
* groups are specified explicitly and the new one where modules are grouped accordingly to their qualified names.
*
* @author nik
*/
@ApiStatus.Experimental
abstract class ModuleGrouper {
/**
* Returns names of parent groups for a module
*/
abstract fun getGroupPath(module: Module): List<String>
/**
* Returns names of parent groups for a module
*/
abstract fun getGroupPath(description: ModuleDescription): List<String>
/**
* Returns name which should be used for a module when it's shown under its group
*/
abstract fun getShortenedName(module: Module): String
abstract fun getShortenedNameByFullModuleName(name: String): String
abstract fun getGroupPathByModuleName(name: String): List<String>
/**
* If [module] itself can be considered as a group, returns its groups. Otherwise returns null.
*/
abstract fun getModuleAsGroupPath(module: Module): List<String>?
/**
* If [description] itself can be considered as a group, returns its groups. Otherwise returns null.
*/
abstract fun getModuleAsGroupPath(description: ModuleDescription): List<String>?
abstract fun getAllModules(): Array<Module>
companion object {
@JvmStatic
@JvmOverloads
fun instanceFor(project: Project, moduleModel: ModifiableModuleModel? = null): ModuleGrouper {
val hasGroups = moduleModel?.hasModuleGroups() ?: ModuleManager.getInstance(project).hasModuleGroups()
if (!isQualifiedModuleNamesEnabled(project) || hasGroups) {
return ExplicitModuleGrouper(project, moduleModel)
}
return QualifiedNameGrouper(project, moduleModel)
}
}
}
fun isQualifiedModuleNamesEnabled(project: Project) = Registry.`is`("project.qualified.module.names") &&
!ModuleManager.getInstance(project).hasModuleGroups()
private abstract class ModuleGrouperBase(protected val project: Project, protected val model: ModifiableModuleModel?) : ModuleGrouper() {
override fun getAllModules(): Array<Module> = model?.modules ?: ModuleManager.getInstance(project).modules
protected fun getModuleName(module: Module) = model?.getNewName(module) ?: module.name
override fun getShortenedName(module: Module) = getShortenedNameByFullModuleName(getModuleName(module))
}
private class QualifiedNameGrouper(project: Project, model: ModifiableModuleModel?) : ModuleGrouperBase(project, model) {
override fun getGroupPath(module: Module): List<String> {
return getGroupPathByModuleName(getModuleName(module))
}
override fun getGroupPath(description: ModuleDescription) = getGroupPathByModuleName(description.name)
override fun getShortenedNameByFullModuleName(name: String) = StringUtil.getShortName(name)
override fun getGroupPathByModuleName(name: String) = name.split('.').dropLast(1)
override fun getModuleAsGroupPath(module: Module) = getModuleName(module).split('.')
override fun getModuleAsGroupPath(description: ModuleDescription) = description.name.split('.')
}
private class ExplicitModuleGrouper(project: Project, model: ModifiableModuleModel?): ModuleGrouperBase(project, model) {
override fun getGroupPath(module: Module): List<String> {
val path = if (model != null) model.getModuleGroupPath(module) else ModuleManager.getInstance(project).getModuleGroupPath(module)
return if (path != null) Arrays.asList(*path) else emptyList()
}
override fun getGroupPath(description: ModuleDescription) = when (description) {
is LoadedModuleDescription -> getGroupPath(description.module)
is UnloadedModuleDescription -> description.groupPath
else -> throw IllegalArgumentException(description.javaClass.name)
}
override fun getShortenedNameByFullModuleName(name: String) = name
override fun getGroupPathByModuleName(name: String): List<String> = emptyList()
override fun getModuleAsGroupPath(module: Module) = null
override fun getModuleAsGroupPath(description: ModuleDescription) = null
}
| apache-2.0 | ed0a78e5e5b60aad4d9bde2fa3ffafb6 | 39.655738 | 137 | 0.758266 | 4.8867 | false | false | false | false |
Heiner1/AndroidAPS | wear/src/main/java/info/nightscout/androidaps/complications/BrCobIobComplication.kt | 1 | 2012 | @file:Suppress("DEPRECATION")
package info.nightscout.androidaps.complications
import android.app.PendingIntent
import android.support.wearable.complications.ComplicationData
import android.support.wearable.complications.ComplicationText
import dagger.android.AndroidInjection
import info.nightscout.androidaps.data.RawDisplayData
import info.nightscout.androidaps.interaction.utils.DisplayFormat
import info.nightscout.androidaps.interaction.utils.SmallestDoubleString
import info.nightscout.shared.logging.LTag
import kotlin.math.max
/*
* Created by dlvoy on 2019-11-12
*/
class BrCobIobComplication : BaseComplicationProviderService() {
// Not derived from DaggerService, do injection here
override fun onCreate() {
AndroidInjection.inject(this)
super.onCreate()
}
override fun buildComplicationData(dataType: Int, raw: RawDisplayData, complicationPendingIntent: PendingIntent): ComplicationData? {
var complicationData: ComplicationData? = null
if (dataType == ComplicationData.TYPE_SHORT_TEXT) {
val cob = SmallestDoubleString(raw.status.cob, SmallestDoubleString.Units.USE).minimise(DisplayFormat.MIN_FIELD_LEN_COB)
val iob = SmallestDoubleString(raw.status.iobSum, SmallestDoubleString.Units.USE).minimise(max(DisplayFormat.MIN_FIELD_LEN_IOB, DisplayFormat.MAX_FIELD_LEN_SHORT - 1 - cob.length))
val builder = ComplicationData.Builder(ComplicationData.TYPE_SHORT_TEXT)
.setShortText(ComplicationText.plainText(displayFormat.basalRateSymbol() + raw.status.currentBasal))
.setShortTitle(ComplicationText.plainText("$cob $iob"))
.setTapAction(complicationPendingIntent)
complicationData = builder.build()
} else {
aapsLogger.warn(LTag.WEAR, "Unexpected complication type $dataType")
}
return complicationData
}
override fun getProviderCanonicalName(): String = BrCobIobComplication::class.java.canonicalName!!
}
| agpl-3.0 | 490dc32837940610ebdb63774469a3c3 | 45.790698 | 192 | 0.752982 | 4.67907 | false | false | false | false |
jkcclemens/khttp | src/test/kotlin/khttp/extensions/ExtensionsSpec.kt | 1 | 2165 | /*
* 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 khttp.extensions
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class ExtensionsSpec : Spek({
describe("a ByteArray") {
val string = "\"Goddammit\", he said\nThis is a load of bullshit.\r\nPlease, just kill me now.\r"
val byteArray = string.toByteArray()
context("splitting by lines") {
val split = byteArray.splitLines().map { it.toString(Charsets.UTF_8) }
val expected = string.split(Regex("(\r\n|\r|\n)"))
it("should be split by lines") {
assertEquals(expected, split)
}
}
context("splitting by the letter e") {
val splitBy = "e"
val split = byteArray.split(splitBy.toByteArray()).map { it.toString(Charsets.UTF_8) }
val expected = string.split(splitBy)
it("should be split correctly") {
assertEquals(expected, split)
}
}
context("splitting by is") {
val splitBy = "is"
val split = byteArray.split(splitBy.toByteArray()).map { it.toString(Charsets.UTF_8) }
val expected = string.split(splitBy)
it("should be split correctly") {
assertEquals(expected, split)
}
}
}
describe("an empty ByteArray") {
val empty = ByteArray(0)
context("splitting by lines") {
val split = empty.splitLines()
it("should be empty") {
assertEquals(0, split.size)
}
}
context("splitting by anything") {
val split = empty.split(ByteArray(0))
it("should have one element") {
assertEquals(1, split.size)
}
it("the element should be empty") {
assertTrue(split[0].isEmpty())
}
}
}
})
| mpl-2.0 | c7e63f40790834de869456477dce585e | 35.694915 | 105 | 0.565358 | 4.356137 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/ReactActivityDelegateWrapper.kt | 2 | 4597 | package abi43_0_0.expo.modules
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.KeyEvent
import androidx.collection.ArrayMap
import abi43_0_0.com.facebook.react.ReactActivity
import abi43_0_0.com.facebook.react.ReactActivityDelegate
import abi43_0_0.com.facebook.react.ReactInstanceManager
import abi43_0_0.com.facebook.react.ReactNativeHost
import abi43_0_0.com.facebook.react.ReactRootView
import abi43_0_0.com.facebook.react.modules.core.PermissionListener
import java.lang.reflect.Method
class ReactActivityDelegateWrapper(
private val activity: ReactActivity,
private val delegate: ReactActivityDelegate
) : ReactActivityDelegate(activity, null) {
private val reactActivityLifecycleListeners = ExpoModulesPackage.packageList
.flatMap { it.createReactActivityLifecycleListeners(activity) }
private val methodMap: ArrayMap<String, Method> = ArrayMap()
//region ReactActivityDelegate
override fun getLaunchOptions(): Bundle? {
return invokeDelegateMethod("getLaunchOptions")
}
override fun createRootView(): ReactRootView {
return invokeDelegateMethod("createRootView")
}
override fun getReactNativeHost(): ReactNativeHost {
return invokeDelegateMethod("getReactNativeHost")
}
override fun getReactInstanceManager(): ReactInstanceManager {
return delegate.reactInstanceManager
}
override fun getMainComponentName(): String {
return delegate.mainComponentName
}
override fun loadApp(appKey: String?) {
return invokeDelegateMethod("loadApp", arrayOf(String::class.java), arrayOf(appKey))
}
override fun onCreate(savedInstanceState: Bundle?) {
invokeDelegateMethod<Unit, Bundle?>("onCreate", arrayOf(Bundle::class.java), arrayOf(savedInstanceState))
reactActivityLifecycleListeners.forEach { listener ->
listener.onCreate(activity, savedInstanceState)
}
}
override fun onResume() {
invokeDelegateMethod<Unit>("onResume")
reactActivityLifecycleListeners.forEach { listener ->
listener.onResume(activity)
}
}
override fun onPause() {
reactActivityLifecycleListeners.forEach { listener ->
listener.onPause(activity)
}
return invokeDelegateMethod("onPause")
}
override fun onDestroy() {
reactActivityLifecycleListeners.forEach { listener ->
listener.onDestroy(activity)
}
return invokeDelegateMethod("onDestroy")
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
delegate.onActivityResult(requestCode, resultCode, data)
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
return delegate.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
return delegate.onKeyUp(keyCode, event)
}
override fun onKeyLongPress(keyCode: Int, event: KeyEvent?): Boolean {
return delegate.onKeyLongPress(keyCode, event)
}
override fun onBackPressed(): Boolean {
return delegate.onBackPressed()
}
override fun onNewIntent(intent: Intent?): Boolean {
return delegate.onNewIntent(intent)
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
delegate.onWindowFocusChanged(hasFocus)
}
override fun requestPermissions(permissions: Array<out String>?, requestCode: Int, listener: PermissionListener?) {
delegate.requestPermissions(permissions, requestCode, listener)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>?, grantResults: IntArray?) {
delegate.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
override fun getContext(): Context {
return invokeDelegateMethod("getContext")
}
override fun getPlainActivity(): Activity {
return invokeDelegateMethod("getPlainActivity")
}
//endregion
//region Internals
private fun <T> invokeDelegateMethod(name: String): T {
var method = methodMap[name]
if (method == null) {
method = ReactActivityDelegate::class.java.getDeclaredMethod(name)
method.isAccessible = true
methodMap[name] = method
}
return method!!.invoke(delegate) as T
}
private fun <T, A> invokeDelegateMethod(
name: String,
argTypes: Array<Class<*>>,
args: Array<A>
): T {
var method = methodMap[name]
if (method == null) {
method = ReactActivityDelegate::class.java.getDeclaredMethod(name, *argTypes)
method.isAccessible = true
methodMap[name] = method
}
return method!!.invoke(delegate, *args) as T
}
//endregion
}
| bsd-3-clause | 9bd4116ad790528146ae8198ae33e6d8 | 29.243421 | 119 | 0.745051 | 4.874867 | false | false | false | false |
realm/realm-java | library-build-transformer/src/main/kotlin/io/realm/buildtransformer/util/Stopwatch.kt | 1 | 1941 | /*
* Copyright 2018 Realm Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.realm.buildtransformer.util
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
class Stopwatch {
val logger: Logger = LoggerFactory.getLogger("realm-stopwatch")
var start: Long = -1L
var lastSplit: Long = -1L
lateinit var label: String
/**
* Start the stopwatch.
*/
fun start(label: String) {
if (start != -1L) {
throw IllegalStateException("Stopwatch was already started");
}
this.label = label
start = System.nanoTime();
lastSplit = start;
}
/**
* Reports the split time.
*
* @param label Label to use when printing split time
* @param reportDiffFromLastSplit if `true` report the time from last split instead of the start
*/
fun splitTime(label: String, reportDiffFromLastSplit: Boolean = true) {
val split = System.nanoTime()
val diff = if (reportDiffFromLastSplit) { split - lastSplit } else { split - start }
lastSplit = split;
logger.debug("$label: ${TimeUnit.NANOSECONDS.toMillis(diff)} ms.")
}
/**
* Stops the timer and report the result.
*/
fun stop() {
val stop = System.nanoTime()
val diff = stop - start
logger.debug("$label: ${TimeUnit.NANOSECONDS.toMillis(diff)} ms.")
}
} | apache-2.0 | ad28fc142cd2d7f1c2bd5e945086a1ea | 29.825397 | 100 | 0.657393 | 4.210412 | false | false | false | false |
k9mail/k-9 | app/storage/src/main/java/com/fsck/k9/preferences/migrations/StorageMigrationTo12.kt | 2 | 2700 | package com.fsck.k9.preferences.migrations
import android.database.sqlite.SQLiteDatabase
import com.fsck.k9.ServerSettingsSerializer
import com.fsck.k9.mail.filter.Base64
import com.fsck.k9.preferences.migrations.migration12.ImapStoreUriDecoder
import com.fsck.k9.preferences.migrations.migration12.Pop3StoreUriDecoder
import com.fsck.k9.preferences.migrations.migration12.SmtpTransportUriDecoder
import com.fsck.k9.preferences.migrations.migration12.WebDavStoreUriDecoder
/**
* Convert server settings from the old URI format to the new JSON format
*/
class StorageMigrationTo12(
private val db: SQLiteDatabase,
private val migrationsHelper: StorageMigrationsHelper
) {
private val serverSettingsSerializer = ServerSettingsSerializer()
fun removeStoreAndTransportUri() {
val accountUuidsListValue = migrationsHelper.readValue(db, "accountUuids")
if (accountUuidsListValue == null || accountUuidsListValue.isEmpty()) {
return
}
val accountUuids = accountUuidsListValue.split(",")
for (accountUuid in accountUuids) {
convertStoreUri(accountUuid)
convertTransportUri(accountUuid)
}
}
private fun convertStoreUri(accountUuid: String) {
val storeUri = migrationsHelper.readValue(db, "$accountUuid.storeUri")?.base64Decode() ?: return
val serverSettings = when {
storeUri.startsWith("imap") -> ImapStoreUriDecoder.decode(storeUri)
storeUri.startsWith("pop3") -> Pop3StoreUriDecoder.decode(storeUri)
storeUri.startsWith("webdav") -> WebDavStoreUriDecoder.decode(storeUri)
else -> error("Unsupported account type")
}
val json = serverSettingsSerializer.serialize(serverSettings)
migrationsHelper.insertValue(db, "$accountUuid.incomingServerSettings", json)
migrationsHelper.writeValue(db, "$accountUuid.storeUri", null)
}
private fun convertTransportUri(accountUuid: String) {
val transportUri = migrationsHelper.readValue(db, "$accountUuid.transportUri")?.base64Decode() ?: return
val serverSettings = when {
transportUri.startsWith("smtp") -> SmtpTransportUriDecoder.decodeSmtpUri(transportUri)
transportUri.startsWith("webdav") -> WebDavStoreUriDecoder.decode(transportUri)
else -> error("Unsupported account type")
}
val json = serverSettingsSerializer.serialize(serverSettings)
migrationsHelper.insertValue(db, "$accountUuid.outgoingServerSettings", json)
migrationsHelper.writeValue(db, "$accountUuid.transportUri", null)
}
private fun String.base64Decode() = Base64.decode(this)
}
| apache-2.0 | 781d9e8fddbd3605f3f046296cf2c543 | 40.538462 | 112 | 0.726667 | 4.918033 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/builder/application/ModifierSupportBuilder.kt | 1 | 1789 | package org.hexworks.zircon.api.builder.application
import org.hexworks.zircon.api.application.ModifierSupport
import org.hexworks.zircon.api.builder.Builder
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.modifier.TextureTransformModifier
import org.hexworks.zircon.api.tileset.TextureTransformer
import org.hexworks.zircon.api.tileset.TileTexture
import org.hexworks.zircon.internal.dsl.ZirconDsl
import org.hexworks.zircon.internal.tileset.impl.DefaultTextureTransformer
import kotlin.reflect.KClass
import kotlin.jvm.JvmStatic
@ZirconDsl
class ModifierSupportBuilder<T : Any> private constructor(
var modifierType: KClass<out TextureTransformModifier>? = null,
var targetType: KClass<T>? = null,
var transformerFunction: ((texture: TileTexture<T>, tile: Tile) -> TileTexture<T>)? = null,
var transformer: TextureTransformer<T>? = null
) : Builder<ModifierSupport<T>> {
override fun createCopy() = ModifierSupportBuilder(
modifierType = modifierType,
targetType = targetType,
transformerFunction = transformerFunction
)
override fun build(): ModifierSupport<T> {
requireNotNull(targetType) {
"Target type is missing."
}
requireNotNull(modifierType) {
"Modifier type is missing"
}
require(transformerFunction != null || transformer != null) {
"Transformer is missing."
}
return ModifierSupport(
modifierType = modifierType!!,
targetType = targetType!!,
transformer = transformer ?: DefaultTextureTransformer(targetType!!, transformerFunction!!)
)
}
companion object {
@JvmStatic
fun <T : Any> newBuilder() = ModifierSupportBuilder<T>()
}
}
| apache-2.0 | 3f19b5ebf7b2c1a4684d642809df6429 | 34.078431 | 103 | 0.703745 | 4.848238 | false | false | false | false |
blindpirate/gradle | subprojects/kotlin-dsl-plugins/src/integTest/kotlin/org/gradle/kotlin/dsl/plugins/dsl/KotlinDslPluginTest.kt | 1 | 10985 | package org.gradle.kotlin.dsl.plugins.dsl
import org.gradle.kotlin.dsl.fixtures.AbstractPluginTest
import org.gradle.kotlin.dsl.fixtures.containsMultiLineString
import org.gradle.kotlin.dsl.fixtures.normalisedPath
import org.gradle.kotlin.dsl.support.expectedKotlinDslPluginsVersion
import org.gradle.test.fixtures.file.LeaksFileHandles
import org.hamcrest.CoreMatchers.containsString
import org.hamcrest.CoreMatchers.not
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
@LeaksFileHandles("Kotlin Compiler Daemon working directory")
class KotlinDslPluginTest : AbstractPluginTest() {
@Test
fun `warns on unexpected kotlin-dsl plugin version`() {
// The test applies the in-development version of the kotlin-dsl
// which, by convention, it is always ahead of the version expected by
// the in-development version of Gradle
// (see publishedKotlinDslPluginsVersion in kotlin-dsl.gradle.kts)
withKotlinDslPlugin()
withDefaultSettings().appendText(
"""
rootProject.name = "forty-two"
"""
)
val appliedKotlinDslPluginsVersion = futurePluginVersions["org.gradle.kotlin.kotlin-dsl"]
build("help").apply {
assertOutputContains(
"This version of Gradle expects version '$expectedKotlinDslPluginsVersion' of the `kotlin-dsl` plugin but version '$appliedKotlinDslPluginsVersion' has been applied to root project 'forty-two'."
)
}
}
@Test
fun `gradle kotlin dsl api dependency is added`() {
withKotlinDslPlugin()
withFile(
"src/main/kotlin/code.kt",
"""
// src/main/kotlin
import org.gradle.kotlin.dsl.GradleDsl
// src/generated
import org.gradle.kotlin.dsl.embeddedKotlinVersion
"""
)
val result = build("classes")
result.assertTaskExecuted(":compileKotlin")
}
@Test
fun `gradle kotlin dsl api is available for test implementation`() {
assumeNonEmbeddedGradleExecuter() // Requires a Gradle distribution on the test-under-test classpath, but gradleApi() does not offer the full distribution
ignoreKotlinDaemonJvmDeprecationWarningsOnJdk16()
withBuildScript(
"""
plugins {
`kotlin-dsl`
}
$repositoriesBlock
dependencies {
testImplementation("junit:junit:4.13")
}
"""
)
withFile(
"src/main/kotlin/code.kt",
"""
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.embeddedKotlinVersion
class MyPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.run {
println("Plugin Using Embedded Kotlin " + embeddedKotlinVersion)
}
}
}
"""
)
withFile(
"src/test/kotlin/test.kt",
"""
import org.gradle.testfixtures.ProjectBuilder
import org.junit.Test
import org.gradle.kotlin.dsl.*
class MyTest {
@Test
fun `my test`() {
ProjectBuilder.builder().build().run {
apply<MyPlugin>()
}
}
}
"""
)
assertThat(
outputOf("test", "-i"),
containsString("Plugin Using Embedded Kotlin ")
)
}
@Test
fun `gradle kotlin dsl api is available in test-kit injected plugin classpath`() {
assumeNonEmbeddedGradleExecuter() // requires a full distribution to run tests with test kit
ignoreKotlinDaemonJvmDeprecationWarningsOnJdk16()
withBuildScript(
"""
plugins {
`kotlin-dsl`
}
$repositoriesBlock
dependencies {
testImplementation("junit:junit:4.13")
testImplementation("org.hamcrest:hamcrest-library:1.3")
testImplementation(gradleTestKit())
}
gradlePlugin {
plugins {
register("myPlugin") {
id = "my-plugin"
implementationClass = "my.MyPlugin"
}
}
}
"""
)
withFile(
"src/main/kotlin/my/code.kt",
"""
package my
import org.gradle.api.*
import org.gradle.kotlin.dsl.*
class MyPlugin : Plugin<Project> {
override fun apply(project: Project) {
println("Plugin Using Embedded Kotlin " + embeddedKotlinVersion)
}
}
"""
)
withFile(
"src/test/kotlin/test.kt",
"""
import java.io.File
import org.gradle.testkit.runner.GradleRunner
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class MyTest {
@JvmField @Rule val temporaryFolder = TemporaryFolder()
val projectRoot by lazy {
File(temporaryFolder.root, "test").apply { mkdirs() }
}
@Test
fun `my test`() {
// given:
File(projectRoot, "build.gradle.kts")
.writeText("plugins { id(\"my-plugin\") }")
// and:
System.setProperty("org.gradle.daemon.idletimeout", "1000")
System.setProperty("org.gradle.daemon.registry.base", "${existing("daemons-registry").normalisedPath}")
File(projectRoot, "gradle.properties").writeText("org.gradle.jvmargs=-Xmx128m")
// and:
val runner = GradleRunner.create()
.withGradleInstallation(File("${distribution.gradleHomeDir.normalisedPath}"))
.withTestKitDir(File("${executer.gradleUserHomeDir.normalisedPath}"))
.withProjectDir(projectRoot)
.withPluginClasspath()
.forwardOutput()
// when:
val result = runner.withArguments("help").build()
// then:
require("Plugin Using Embedded Kotlin " in result.output)
}
}
"""
)
assertThat(
outputOf("test", "-i"),
containsString("Plugin Using Embedded Kotlin ")
)
}
@Test
fun `sam-with-receiver kotlin compiler plugin is applied to production code`() {
withKotlinDslPlugin()
withFile(
"src/main/kotlin/code.kt",
"""
import org.gradle.api.Plugin
import org.gradle.api.Project
class MyPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.run {
copy {
from("build.gradle.kts")
into("build/build.gradle.kts.copy")
}
}
}
}
"""
)
val result = build("classes")
result.assertTaskExecuted(":compileKotlin")
}
@Test
fun `can use SAM conversions for Kotlin functions without warnings`() {
withBuildExercisingSamConversionForKotlinFunctions()
build("test").apply {
assertThat(
output.also(::println),
containsMultiLineString(
"""
STRING
foo
bar
"""
)
)
assertThat(
output,
not(containsString(samConversionForKotlinFunctions))
)
}
}
@Test
fun `nags user about experimentalWarning deprecation`() {
withBuildExercisingSamConversionForKotlinFunctions(
"kotlinDslPluginOptions.experimentalWarning.set(false)"
)
executer.expectDeprecationWarning(
"The KotlinDslPluginOptions.experimentalWarning property has been deprecated. " +
"This is scheduled to be removed in Gradle 8.0. " +
"Flag has no effect since `kotlin-dsl` no longer relies on experimental features."
)
build("test").apply {
assertThat(
output.also(::println),
containsMultiLineString(
"""
STRING
foo
bar
"""
)
)
assertThat(
output,
not(containsString(samConversionForKotlinFunctions))
)
}
}
private
fun withBuildExercisingSamConversionForKotlinFunctions(buildSrcScript: String = "") {
withDefaultSettingsIn("buildSrc")
withBuildScriptIn(
"buildSrc",
"""
plugins {
`kotlin-dsl`
}
$repositoriesBlock
$buildSrcScript
"""
)
withFile(
"buildSrc/src/main/kotlin/my.kt",
"""
package my
// Action<T> is a SAM with receiver
fun <T : Any> applyActionTo(value: T, action: org.gradle.api.Action<T>) = action.execute(value)
// NamedDomainObjectFactory<T> is a regular SAM
fun <T> create(name: String, factory: org.gradle.api.NamedDomainObjectFactory<T>): T = factory.create(name)
fun <T : Any> createK(type: kotlin.reflect.KClass<T>, factory: org.gradle.api.NamedDomainObjectFactory<T>): T = factory.create(type.simpleName!!)
fun test() {
// Implicit SAM conversion in regular source
println(createK(String::class) { it.toUpperCase() })
println(create("FOO") { it.toLowerCase() })
// Implicit SAM with receiver conversion in regular source
applyActionTo("BAR") {
println(toLowerCase())
}
}
"""
)
withBuildScript(
"""
task("test") {
doLast { my.test() }
}
"""
)
}
private
fun outputOf(vararg arguments: String) =
build(*arguments).output
}
private
const val samConversionForKotlinFunctions = "-XXLanguage:+SamConversionForKotlinFunctions"
| apache-2.0 | f71e5a0c811da375463abf611bdc5656 | 27.458549 | 210 | 0.515703 | 5.598879 | false | true | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/component/data/CommonComponentProperties.kt | 1 | 2215 | package org.hexworks.zircon.internal.component.data
import org.hexworks.cobalt.databinding.api.extension.toProperty
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.zircon.api.ComponentAlignments
import org.hexworks.zircon.api.component.AlignmentStrategy
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.ComponentStyleSet
import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer
import org.hexworks.zircon.api.component.renderer.ComponentPostProcessor
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.internal.component.renderer.NoOpComponentRenderer
/**
* Contains all the common data for component builders.
*/
data class CommonComponentProperties<T : Component>(
var name: String = "",
var alignmentStrategy: AlignmentStrategy = ComponentAlignments.positionalAlignment(0, 0),
var decorationRenderers: List<ComponentDecorationRenderer> = listOf(),
var preferredContentSize: Size = Size.unknown(),
var preferredSize: Size = Size.unknown(),
var componentRenderer: ComponentRenderer<out T> = NoOpComponentRenderer(),
var postProcessors: List<ComponentPostProcessor<T>> = listOf(),
var updateOnAttach: Boolean = true,
// can be changed runtime
val themeProperty: Property<ColorTheme> = ColorTheme.unknown().toProperty(),
val componentStyleSetProperty: Property<ComponentStyleSet> = ComponentStyleSet.unknown().toProperty(),
val tilesetProperty: Property<TilesetResource> = TilesetResource.unknown().toProperty(),
val hiddenProperty: Property<Boolean> = false.toProperty(),
val disabledProperty: Property<Boolean> = false.toProperty()
) {
var theme: ColorTheme by themeProperty.asDelegate()
var componentStyleSet: ComponentStyleSet by componentStyleSetProperty.asDelegate()
var tileset: TilesetResource by tilesetProperty.asDelegate()
var isHidden: Boolean by hiddenProperty.asDelegate()
var isDisabled: Boolean by disabledProperty.asDelegate()
}
| apache-2.0 | d136c34af4b55dd5c423c419cf0f6232 | 53.02439 | 106 | 0.804515 | 4.825708 | false | false | false | false |
leantechstacks/jcart-backoffice-service | src/main/kotlin/com/leantechstacks/jcart/bo/entities/Vendor.kt | 1 | 535 | package com.leantechstacks.jcart.bo.entities
import javax.persistence.*
@Entity
@Table(name = "vendors")
class Vendor()
{
@Id
@SequenceGenerator(name = "vendor_generator", sequenceName = "vendor_sequence", initialValue = 100)
@GeneratedValue(generator = "vendor_generator")
var id: Long = 0
@Column(nullable = false)
var name: String = ""
constructor(id: Long) :this() {
this.id = id
}
constructor(id: Long, name: String) :this() {
this.id = id
this.name = name
}
}
| apache-2.0 | fbb86bfb7ceea9b5d55c7c9776e2dcbd | 20.4 | 103 | 0.62243 | 3.639456 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/mysite/items/listitem/SiteListItemBuilder.kt | 1 | 9827 | package org.wordpress.android.ui.mysite.items.listitem
import android.text.TextUtils
import org.wordpress.android.R
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.store.AccountStore
import org.wordpress.android.ui.mysite.MySiteCardAndItem
import org.wordpress.android.ui.mysite.MySiteCardAndItem.Item.ListItem
import org.wordpress.android.ui.mysite.MySiteViewModel
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.ACTIVITY_LOG
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.ADMIN
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.BACKUP
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.DOMAINS
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.JETPACK_SETTINGS
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.PAGES
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.PEOPLE
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.PLAN
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.PLUGINS
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.SCAN
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.SHARING
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.SITE_SETTINGS
import org.wordpress.android.ui.mysite.items.listitem.ListItemAction.THEMES
import org.wordpress.android.ui.plugins.PluginUtilsWrapper
import org.wordpress.android.ui.themes.ThemeBrowserUtils
import org.wordpress.android.ui.utils.ListItemInteraction
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.ui.utils.UiString.UiStringText
import org.wordpress.android.util.BuildConfigWrapper
import org.wordpress.android.util.DateTimeUtils
import org.wordpress.android.util.SiteUtilsWrapper
import org.wordpress.android.util.config.SiteDomainsFeatureConfig
import java.util.GregorianCalendar
import java.util.TimeZone
import javax.inject.Inject
class SiteListItemBuilder @Inject constructor(
private val accountStore: AccountStore,
private val pluginUtilsWrapper: PluginUtilsWrapper,
private val siteUtilsWrapper: SiteUtilsWrapper,
private val buildConfigWrapper: BuildConfigWrapper,
private val themeBrowserUtils: ThemeBrowserUtils,
private val siteDomainsFeatureConfig: SiteDomainsFeatureConfig
) {
fun buildActivityLogItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
val isWpComOrJetpack = siteUtilsWrapper.isAccessedViaWPComRest(
site
) || site.isJetpackConnected
return if (site.hasCapabilityManageOptions && isWpComOrJetpack && !site.isWpForTeamsSite) {
ListItem(
R.drawable.ic_gridicons_clipboard_white_24dp,
UiStringRes(R.string.activity_log),
onClick = ListItemInteraction.create(ACTIVITY_LOG, onClick)
)
} else null
}
fun buildBackupItemIfAvailable(onClick: (ListItemAction) -> Unit, isBackupAvailable: Boolean = false): ListItem? {
return if (isBackupAvailable) {
ListItem(
R.drawable.ic_gridicons_cloud_upload_white_24dp,
UiStringRes(R.string.backup),
onClick = ListItemInteraction.create(BACKUP, onClick)
)
} else null
}
fun buildScanItemIfAvailable(onClick: (ListItemAction) -> Unit, isScanAvailable: Boolean = false): ListItem? {
return if (isScanAvailable) {
ListItem(
R.drawable.ic_baseline_security_white_24dp,
UiStringRes(R.string.scan),
onClick = ListItemInteraction.create(SCAN, onClick)
)
} else null
}
fun buildJetpackItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
val jetpackSettingsVisible = site.isJetpackConnected && // jetpack is installed and connected
!site.isWPComAtomic &&
siteUtilsWrapper.isAccessedViaWPComRest(site) && // is using .com login
site.hasCapabilityManageOptions // has permissions to manage the site
return if (jetpackSettingsVisible) {
ListItem(
R.drawable.ic_cog_white_24dp,
UiStringRes(R.string.my_site_btn_jetpack_settings),
onClick = ListItemInteraction.create(JETPACK_SETTINGS, onClick)
)
} else null
}
@Suppress("ComplexCondition")
fun buildPlanItemIfAvailable(
site: SiteModel,
showFocusPoint: Boolean,
onClick: (ListItemAction) -> Unit
): ListItem? {
val planShortName = site.planShortName
return if (!TextUtils.isEmpty(planShortName) &&
site.hasCapabilityManageOptions &&
!site.isWpForTeamsSite &&
(site.isWPCom || site.isAutomatedTransfer)) {
ListItem(
R.drawable.ic_plans_white_24dp,
UiStringRes(R.string.plan),
secondaryText = UiStringText(planShortName),
onClick = ListItemInteraction.create(PLAN, onClick),
showFocusPoint = showFocusPoint
)
} else null
}
fun buildPagesItemIfAvailable(
site: SiteModel,
onClick: (ListItemAction) -> Unit,
showFocusPoint: Boolean
): ListItem? {
return if (site.isSelfHostedAdmin || site.hasCapabilityEditPages) {
ListItem(
R.drawable.ic_pages_white_24dp,
UiStringRes(R.string.my_site_btn_site_pages),
onClick = ListItemInteraction.create(PAGES, onClick),
showFocusPoint = showFocusPoint
)
} else null
}
fun buildAdminItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (shouldShowWPAdmin(site)) {
ListItem(
R.drawable.ic_wordpress_white_24dp,
UiStringRes(R.string.my_site_btn_view_admin),
secondaryIcon = R.drawable.ic_external_white_24dp,
onClick = ListItemInteraction.create(ADMIN, onClick)
)
} else null
}
fun buildPeopleItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (site.hasCapabilityListUsers) {
ListItem(
R.drawable.ic_user_white_24dp,
UiStringRes(R.string.people),
onClick = ListItemInteraction.create(PEOPLE, onClick)
)
} else null
}
fun buildPluginItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (pluginUtilsWrapper.isPluginFeatureAvailable(site)) {
ListItem(
R.drawable.ic_plugins_white_24dp,
UiStringRes(R.string.my_site_btn_plugins),
onClick = ListItemInteraction.create(PLUGINS, onClick)
)
} else null
}
fun buildShareItemIfAvailable(
site: SiteModel,
onClick: (ListItemAction) -> Unit,
showFocusPoint: Boolean = false
): ListItem? {
return if (site.supportsSharing()) {
ListItem(
R.drawable.ic_share_white_24dp,
UiStringRes(R.string.my_site_btn_sharing),
showFocusPoint = showFocusPoint,
onClick = ListItemInteraction.create(SHARING, onClick)
)
} else null
}
fun buildDomainsItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (
buildConfigWrapper.isJetpackApp &&
siteDomainsFeatureConfig.isEnabled() &&
site.hasCapabilityManageOptions
) {
ListItem(
R.drawable.ic_domains_white_24dp,
UiStringRes(R.string.my_site_btn_domains),
onClick = ListItemInteraction.create(DOMAINS, onClick)
)
} else null
}
fun buildSiteSettingsItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): ListItem? {
return if (site.hasCapabilityManageOptions || !siteUtilsWrapper.isAccessedViaWPComRest(site)) {
ListItem(
R.drawable.ic_cog_white_24dp,
UiStringRes(R.string.my_site_btn_site_settings),
onClick = ListItemInteraction.create(SITE_SETTINGS, onClick)
)
} else null
}
private fun shouldShowWPAdmin(site: SiteModel): Boolean {
return if (!site.isWPCom) {
true
} else {
val dateCreated = DateTimeUtils.dateFromIso8601(
accountStore.account
.date
)
val calendar = GregorianCalendar(HIDE_WP_ADMIN_YEAR, HIDE_WP_ADMIN_MONTH, HIDE_WP_ADMIN_DAY)
calendar.timeZone = TimeZone.getTimeZone(MySiteViewModel.HIDE_WP_ADMIN_GMT_TIME_ZONE)
dateCreated == null || dateCreated.before(calendar.time)
}
}
fun buildThemesItemIfAvailable(site: SiteModel, onClick: (ListItemAction) -> Unit): MySiteCardAndItem? {
return if (themeBrowserUtils.isAccessible(site)) {
ListItem(
R.drawable.ic_themes_white_24dp,
UiStringRes(R.string.themes),
onClick = ListItemInteraction.create(THEMES, onClick)
)
} else null
}
companion object {
const val HIDE_WP_ADMIN_YEAR = 2015
const val HIDE_WP_ADMIN_MONTH = 9
const val HIDE_WP_ADMIN_DAY = 7
}
}
| gpl-2.0 | bde40c79cb11a72bac0b01d4bc52e169 | 42.482301 | 118 | 0.646382 | 4.848051 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddNamesToFollowingArgumentsIntention.kt | 1 | 3733 | // 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.k2.codeinsight.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.AbstractKotlinApplicatorBasedIntention
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.applicator
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.inputProvider
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddArgumentNamesApplicators
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtLambdaArgument
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
internal class AddNamesToFollowingArgumentsIntention :
AbstractKotlinApplicatorBasedIntention<KtValueArgument, AddArgumentNamesApplicators.MultipleArgumentsInput>(KtValueArgument::class),
LowPriorityAction {
override fun getApplicabilityRange() = ApplicabilityRanges.VALUE_ARGUMENT_EXCLUDING_LAMBDA
override fun getApplicator() = applicator<KtValueArgument, AddArgumentNamesApplicators.MultipleArgumentsInput> {
familyAndActionName(KotlinBundle.lazyMessage("add.names.to.this.argument.and.following.arguments"))
isApplicableByPsi { element ->
// Not applicable when lambda is trailing lambda after argument list (e.g., `run { }`); element is a KtLambdaArgument.
// May be applicable when lambda is inside an argument list (e.g., `run({ })`); element is a KtValueArgument in this case.
if (element.isNamed() || element is KtLambdaArgument) {
return@isApplicableByPsi false
}
val argumentList = element.parent as? KtValueArgumentList ?: return@isApplicableByPsi false
// Shadowed by HLAddNamesToCallArgumentsIntention
if (argumentList.arguments.firstOrNull() == element) return@isApplicableByPsi false
// Shadowed by HLAddNameToArgumentIntention
if (argumentList.arguments.lastOrNull { !it.isNamed() } == element) return@isApplicableByPsi false
true
}
applyTo { element, input, project, editor ->
val callElement = element.parent?.safeAs<KtValueArgumentList>()?.parent as? KtCallElement
callElement?.let { AddArgumentNamesApplicators.multipleArgumentsApplicator.applyTo(it, input, project, editor) }
}
}
override fun getInputProvider() = inputProvider { element: KtValueArgument ->
val argumentList = element.parent as? KtValueArgumentList ?: return@inputProvider null
val callElement = argumentList.parent as? KtCallElement ?: return@inputProvider null
val resolvedCall = callElement.resolveCall().singleFunctionCallOrNull() ?: return@inputProvider null
if (!resolvedCall.symbol.hasStableParameterNames) {
return@inputProvider null
}
val argumentsExcludingPrevious =
callElement.valueArgumentList?.arguments?.dropWhile { it != element } ?: return@inputProvider null
AddArgumentNamesApplicators.MultipleArgumentsInput(argumentsExcludingPrevious.associateWith {
getArgumentNameIfCanBeUsedForCalls(it, resolvedCall) ?: return@inputProvider null
})
}
} | apache-2.0 | 49d981920992cadf729c283a93dec7f3 | 56.446154 | 158 | 0.760782 | 5.295035 | false | false | false | false |
florent37/Flutter-AssetsAudioPlayer | android/src/main/kotlin/com/github/florent37/assets_audio_player/Resolver.kt | 1 | 1630 | package com.github.florent37.assets_audio_player
import android.content.Context
import android.net.Uri
import android.provider.MediaStore
class UriResolver(private val context: Context) {
companion object {
const val PREFIX_CONTENT = "content://media"
}
private fun contentPath(uri: Uri, columnName: String): String? {
return context.contentResolver?.query(
uri,
arrayOf(
columnName
),
null,
null,
null)
?.use { cursor ->
cursor.takeIf { it.count == 1 }?.let {
it.moveToFirst()
it.getString(cursor.getColumnIndex(columnName))
}
}
}
fun audioPath(uri: String?): String? {
if(uri != null) {
try {
if (uri.startsWith(PREFIX_CONTENT)) {
val uriParsed = Uri.parse(uri)
return contentPath(uriParsed, MediaStore.Audio.Media.DATA) ?: uri
}
} catch (t: Throwable) {
//print(t)
}
}
return uri
}
fun imagePath(uri: String?): String? {
if(uri != null) {
try {
if (uri.startsWith(PREFIX_CONTENT)) {
val uriParsed = Uri.parse(uri)
return contentPath(uriParsed, MediaStore.Images.Media.DATA) ?: uri
}
} catch (t: Throwable) {
//print(t)
}
}
return uri
}
} | apache-2.0 | c88942257129ebdc718edf757fe57337 | 27.614035 | 86 | 0.462577 | 4.969512 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/ide/bookmark/actions/GotoBookmarkTypeAction.kt | 2 | 4327 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.bookmark.actions
import com.intellij.ide.bookmark.BookmarkBundle.messagePointer
import com.intellij.ide.bookmark.BookmarkType
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.project.DumbAwareAction
internal open class GotoBookmarkTypeAction(private val type: BookmarkType, private val checkSpeedSearch: Boolean = false)
: DumbAwareAction(messagePointer("goto.bookmark.type.action.text", type.mnemonic)/*, type.icon*/) {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.BGT
private fun canNavigate(event: AnActionEvent) = event.bookmarksManager?.getBookmark(type)?.canNavigate() ?: false
override fun update(event: AnActionEvent) {
event.presentation.isEnabledAndVisible =
(!checkSpeedSearch || event.getData(PlatformDataKeys.SPEED_SEARCH_TEXT) == null) &&
canNavigate(event)
}
override fun actionPerformed(event: AnActionEvent) {
event.bookmarksManager?.getBookmark(type)?.navigate(true)
}
init {
isEnabledInModalContext = true
}
}
internal class GotoBookmark1Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_1)
internal class GotoBookmark2Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_2)
internal class GotoBookmark3Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_3)
internal class GotoBookmark4Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_4)
internal class GotoBookmark5Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_5)
internal class GotoBookmark6Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_6)
internal class GotoBookmark7Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_7)
internal class GotoBookmark8Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_8)
internal class GotoBookmark9Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_9)
internal class GotoBookmark0Action : GotoBookmarkTypeAction(BookmarkType.DIGIT_0)
internal class GotoBookmarkAAction : GotoBookmarkTypeAction(BookmarkType.LETTER_A)
internal class GotoBookmarkBAction : GotoBookmarkTypeAction(BookmarkType.LETTER_B)
internal class GotoBookmarkCAction : GotoBookmarkTypeAction(BookmarkType.LETTER_C)
internal class GotoBookmarkDAction : GotoBookmarkTypeAction(BookmarkType.LETTER_D)
internal class GotoBookmarkEAction : GotoBookmarkTypeAction(BookmarkType.LETTER_E)
internal class GotoBookmarkFAction : GotoBookmarkTypeAction(BookmarkType.LETTER_F)
internal class GotoBookmarkGAction : GotoBookmarkTypeAction(BookmarkType.LETTER_G)
internal class GotoBookmarkHAction : GotoBookmarkTypeAction(BookmarkType.LETTER_H)
internal class GotoBookmarkIAction : GotoBookmarkTypeAction(BookmarkType.LETTER_I)
internal class GotoBookmarkJAction : GotoBookmarkTypeAction(BookmarkType.LETTER_J)
internal class GotoBookmarkKAction : GotoBookmarkTypeAction(BookmarkType.LETTER_K)
internal class GotoBookmarkLAction : GotoBookmarkTypeAction(BookmarkType.LETTER_L)
internal class GotoBookmarkMAction : GotoBookmarkTypeAction(BookmarkType.LETTER_M)
internal class GotoBookmarkNAction : GotoBookmarkTypeAction(BookmarkType.LETTER_N)
internal class GotoBookmarkOAction : GotoBookmarkTypeAction(BookmarkType.LETTER_O)
internal class GotoBookmarkPAction : GotoBookmarkTypeAction(BookmarkType.LETTER_P)
internal class GotoBookmarkQAction : GotoBookmarkTypeAction(BookmarkType.LETTER_Q)
internal class GotoBookmarkRAction : GotoBookmarkTypeAction(BookmarkType.LETTER_R)
internal class GotoBookmarkSAction : GotoBookmarkTypeAction(BookmarkType.LETTER_S)
internal class GotoBookmarkTAction : GotoBookmarkTypeAction(BookmarkType.LETTER_T)
internal class GotoBookmarkUAction : GotoBookmarkTypeAction(BookmarkType.LETTER_U)
internal class GotoBookmarkVAction : GotoBookmarkTypeAction(BookmarkType.LETTER_V)
internal class GotoBookmarkWAction : GotoBookmarkTypeAction(BookmarkType.LETTER_W)
internal class GotoBookmarkXAction : GotoBookmarkTypeAction(BookmarkType.LETTER_X)
internal class GotoBookmarkYAction : GotoBookmarkTypeAction(BookmarkType.LETTER_Y)
internal class GotoBookmarkZAction : GotoBookmarkTypeAction(BookmarkType.LETTER_Z)
| apache-2.0 | af372660c72f222c215b81e0e63b5788 | 61.710145 | 158 | 0.852092 | 5.270402 | false | false | false | false |
KotlinBy/bkug.by | data/src/main/kotlin/by/bkug/data/Calendar.kt | 1 | 1365 | package by.bkug.data
import by.bkug.data.model.Calendar
import by.bkug.data.model.CalendarEvent
import by.bkug.data.model.minskDateTime
import java.time.ZonedDateTime
val calendar = Calendar(
name = "Belarus Kotlin User Group Events",
url = "https://bkug.by/",
events = listOf(
CalendarEvent(
id = "02b3710f-f3ce-43e9-8134-60d6f3a64726",
name = "Belarus Kotlin User Group Meetup #7",
start = minskDateTime("2017-12-19", "19:00"),
end = minskDateTime("2017-12-19", "21:00"),
description = "https://bkug.by/2017/12/17/anons-bkug-7/",
location = "Event Space, Вход через ул. Октябрьскую, 10б, vulica Kastryčnickaja 16А, Minsk, Belarus"
),
CalendarEvent(
id = "a39b0fa6-0add-4745-98c2-157878c24305",
name = "Belarus Kotlin User Group Meetup #8",
start = minskDateTime("2017-02-21", "19:00"),
end = minskDateTime("2017-02-21", "21:00"),
description = "https://bkug.by/2018/02/08/anons-bkug-8/",
location = "Event Space, Вход через ул. Октябрьскую, 10б, vulica Kastryčnickaja 16А, Minsk, Belarus"
),
)
)
val internalCalendar = Calendar(
name = "Internal BKUG Events",
url = "https://bkug.by/",
events = listOf()
)
| gpl-3.0 | 08e8fe318239093e8987cee5261b4a03 | 36.571429 | 112 | 0.612167 | 3.161058 | false | false | false | false |
codebutler/farebot | farebot-app/src/main/java/com/codebutler/farebot/app/core/sample/SampleTrip.kt | 1 | 2035 | /*
* SampleTrip.kt
*
* This file is part of FareBot.
* Learn more at: https://codebutler.github.io/farebot/
*
* Copyright (C) 2017 Eric Butler <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.codebutler.farebot.app.core.sample
import android.content.res.Resources
import com.codebutler.farebot.transit.Station
import com.codebutler.farebot.transit.Trip
import java.util.Date
class SampleTrip(private val date: Date) : Trip() {
override fun getTimestamp(): Long = date.time / 1000
override fun getExitTimestamp(): Long = date.time / 1000
override fun getRouteName(resources: Resources): String? = "Route Name"
override fun getAgencyName(resources: Resources): String? = "Agency"
override fun getShortAgencyName(resources: Resources): String? = "Agency"
override fun getBalanceString(): String? = "$42.000"
override fun getStartStationName(resources: Resources): String? = "Start Station"
override fun getStartStation(): Station? = Station.create("Name", "Name", "", "")
override fun hasFare(): Boolean = true
override fun getFareString(resources: Resources): String? = "$4.20"
override fun getEndStationName(resources: Resources): String? = "End Station"
override fun getEndStation(): Station? = Station.create("Name", "Name", "", "")
override fun getMode(): Mode? = Mode.METRO
override fun hasTime(): Boolean = true
}
| gpl-3.0 | d6d9a4169ea079eabf16cbc6afcc7cdd | 33.491525 | 85 | 0.722359 | 4.136179 | false | false | false | false |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/data/preference/PreferenceKeys.kt | 1 | 2851 | package eu.kanade.tachiyomi.data.preference
/**
* This class stores the keys for the preferences in the application.
*/
object PreferenceKeys {
const val confirmExit = "pref_confirm_exit"
const val showReadingMode = "pref_show_reading_mode"
const val defaultReadingMode = "pref_default_reading_mode_key"
const val defaultOrientationType = "pref_default_orientation_type_key"
const val jumpToChapters = "jump_to_chapters"
const val autoUpdateTrack = "pref_auto_update_manga_sync_key"
const val downloadOnlyOverWifi = "pref_download_only_over_wifi_key"
const val folderPerManga = "create_folder_per_manga"
const val removeAfterReadSlots = "remove_after_read_slots"
const val removeAfterMarkedAsRead = "pref_remove_after_marked_as_read_key"
const val removeBookmarkedChapters = "pref_remove_bookmarked"
const val filterDownloaded = "pref_filter_library_downloaded"
const val filterUnread = "pref_filter_library_unread"
const val filterStarted = "pref_filter_library_started"
const val filterCompleted = "pref_filter_library_completed"
const val filterTracked = "pref_filter_library_tracked"
const val librarySortingMode = "library_sorting_mode"
const val librarySortingDirection = "library_sorting_ascending"
const val migrationSortingMode = "pref_migration_sorting"
const val migrationSortingDirection = "pref_migration_direction"
const val startScreen = "start_screen"
const val hideNotificationContent = "hide_notification_content"
const val autoUpdateMetadata = "auto_update_metadata"
const val autoUpdateTrackers = "auto_update_trackers"
const val dateFormat = "app_date_format"
const val defaultCategory = "default_category"
const val skipRead = "skip_read"
const val skipFiltered = "skip_filtered"
const val searchPinnedSourcesOnly = "search_pinned_sources_only"
const val dohProvider = "doh_provider"
const val defaultChapterFilterByRead = "default_chapter_filter_by_read"
const val defaultChapterFilterByDownloaded = "default_chapter_filter_by_downloaded"
const val defaultChapterFilterByBookmarked = "default_chapter_filter_by_bookmarked"
const val defaultChapterSortBySourceOrNumber = "default_chapter_sort_by_source_or_number" // and upload date
const val defaultChapterSortByAscendingOrDescending = "default_chapter_sort_by_ascending_or_descending"
const val defaultChapterDisplayByNameOrNumber = "default_chapter_display_by_name_or_number"
const val verboseLogging = "verbose_logging"
const val autoClearChapterCache = "auto_clear_chapter_cache"
fun trackUsername(syncId: Int) = "pref_mangasync_username_$syncId"
fun trackPassword(syncId: Int) = "pref_mangasync_password_$syncId"
fun trackToken(syncId: Int) = "track_token_$syncId"
}
| apache-2.0 | 44936279c220af26a7c72adcd8cef0f2 | 31.770115 | 112 | 0.752718 | 4.236256 | false | false | false | false |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/GL40Core.kt | 4 | 31372 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val GL40C = "GL40C".nativeClassGL("GL40C") {
extends = GL33C
documentation =
"""
The OpenGL functionality up to version 4.0. Includes only Core Profile symbols.
OpenGL 4.0 implementations support revision 4.00 of the OpenGL Shading Language.
Extensions promoted to core in this release:
${ul(
registryLinkTo("ARB", "texture_query_lod"),
registryLinkTo("ARB", "draw_buffers_blend"),
registryLinkTo("ARB", "draw_indirect"),
registryLinkTo("ARB", "gpu_shader5"),
registryLinkTo("ARB", "gpu_shader_fp64"),
registryLinkTo("ARB", "sample_shading"),
registryLinkTo("ARB", "shader_subroutine"),
registryLinkTo("ARB", "tessellation_shader"),
registryLinkTo("ARB", "texture_buffer_object_rgb32"),
registryLinkTo("ARB", "texture_cube_map_array"),
registryLinkTo("ARB", "texture_gather"),
registryLinkTo("ARB", "transform_feedback2"),
registryLinkTo("ARB", "transform_feedback3")
)}
"""
// ARB_draw_buffers_blend
val blendEquations = "#FUNC_ADD #FUNC_SUBTRACT #FUNC_REVERSE_SUBTRACT #MIN #MAX"
void(
"BlendEquationi",
"Specifies the equation used for both the RGB blend equation and the Alpha blend equation for the specified draw buffer.",
GLuint("buf", "the index of the draw buffer for which to set the blend equation"),
GLenum("mode", "how source and destination colors are combined", blendEquations)
)
void(
"BlendEquationSeparatei",
"Sets the RGB blend equation and the alpha blend equation separately for the specified draw buffer.",
GLuint("buf", "the index of the draw buffer for which to set the blend equations"),
GLenum("modeRGB", "the RGB blend equation, how the red, green, and blue components of the source and destination colors are combined", blendEquations),
GLenum("modeAlpha", "the alpha blend equation, how the alpha component of the source and destination colors are combined", blendEquations)
)
void(
"BlendFunci",
"Specifies pixel arithmetic for the specified draw buffer.",
GLuint("buf", "the index of the draw buffer for which to set the blend function"),
GLenum("sfactor", "how the red, green, blue, and alpha source blending factors are computed"),
GLenum("dfactor", "how the red, green, blue, and alpha destination blending factors are computed")
)
void(
"BlendFuncSeparatei",
"Specifies pixel arithmetic for RGB and alpha components separately for the specified draw buffer.",
GLuint("buf", "the index of the draw buffer for which to set the blend functions"),
GLenum("srcRGB", "how the red, green, and blue blending factors are computed"),
GLenum("dstRGB", "how the red, green, and blue destination blending factors are computed"),
GLenum("srcAlpha", "how the alpha source blending factor is computed"),
GLenum("dstAlpha", "how the alpha destination blending factor is computed")
)
// ARB_draw_indirect
IntConstant(
"""
Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, GetBufferPointerv,
MapBufferRange, FlushMappedBufferRange, GetBufferParameteriv, and CopyBufferSubData.
""",
"DRAW_INDIRECT_BUFFER"..0x8F3F
)
IntConstant(
"Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.",
"DRAW_INDIRECT_BUFFER_BINDING"..0x8F43
)
void(
"DrawArraysIndirect",
"""
Renders primitives from array data, taking parameters from memory.
{@code glDrawArraysIndirect} behaves similarly to #DrawArraysInstancedBaseInstance(), except that the parameters to
glDrawArraysInstancedBaseInstance are stored in memory at the address given by {@code indirect}.
The parameters addressed by {@code indirect} are packed into a structure that takes the form (in C):
${codeBlock("""
typedef struct {
uint count;
uint primCount;
uint first;
uint baseInstance; // must be 0 unless OpenGL 4.2 is supported
} DrawArraysIndirectCommand;
const DrawArraysIndirectCommand *cmd = (const DrawArraysIndirectCommand *)indirect;
glDrawArraysInstancedBaseInstance(mode, cmd->first, cmd->count, cmd->primCount, cmd->baseInstance);
""")}
""",
GLenum("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
Check("4 * 4")..MultiType(
PointerMapping.DATA_INT
)..RawPointer..void.const.p("indirect", "a structure containing the draw parameters")
)
void(
"DrawElementsIndirect",
"""
Renders indexed primitives from array data, taking parameters from memory.
{@code glDrawElementsIndirect} behaves similarly to #DrawElementsInstancedBaseVertexBaseInstance(), execpt that the parameters to
glDrawElementsInstancedBaseVertexBaseInstance are stored in memory at the address given by {@code indirect}.
The parameters addressed by {@code indirect} are packed into a structure that takes the form (in C):
${codeBlock("""
typedef struct {
uint count;
uint primCount;
uint firstIndex;
uint baseVertex;
uint baseInstance;
} DrawElementsIndirectCommand;
""")}
{@code glDrawElementsIndirect} is equivalent to:
${codeBlock("""
void glDrawElementsIndirect(GLenum mode, GLenum type, const void *indirect) {
const DrawElementsIndirectCommand *cmd = (const DrawElementsIndirectCommand *)indirect;
glDrawElementsInstancedBaseVertexBaseInstance(
mode,
cmd->count,
type,
cmd->firstIndex + size-of-type,
cmd->primCount,
cmd->baseVertex,
cmd->baseInstance
);
}
""")}
""",
GLenum("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
GLenum(
"type",
"the type of data in the buffer bound to the #ELEMENT_ARRAY_BUFFER binding",
"#UNSIGNED_BYTE #UNSIGNED_SHORT #UNSIGNED_INT"
),
Check("5 * 4")..MultiType(
PointerMapping.DATA_INT
)..RawPointer..void.const.p("indirect", "the address of a structure containing the draw parameters")
)
// ARB_gpu_shader5
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"GEOMETRY_SHADER_INVOCATIONS"..0x887F
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev, and GetInteger64v.",
"MAX_GEOMETRY_SHADER_INVOCATIONS"..0x8E5A,
"MIN_FRAGMENT_INTERPOLATION_OFFSET"..0x8E5B,
"MAX_FRAGMENT_INTERPOLATION_OFFSET"..0x8E5C,
"FRAGMENT_INTERPOLATION_OFFSET_BITS"..0x8E5D
)
// ARB_gpu_shader_fp64
IntConstant(
"Returned in the {@code type} parameter of GetActiveUniform, and GetTransformFeedbackVarying.",
"DOUBLE_VEC2"..0x8FFC,
"DOUBLE_VEC3"..0x8FFD,
"DOUBLE_VEC4"..0x8FFE,
"DOUBLE_MAT2"..0x8F46,
"DOUBLE_MAT3"..0x8F47,
"DOUBLE_MAT4"..0x8F48,
"DOUBLE_MAT2x3"..0x8F49,
"DOUBLE_MAT2x4"..0x8F4A,
"DOUBLE_MAT3x2"..0x8F4B,
"DOUBLE_MAT3x4"..0x8F4C,
"DOUBLE_MAT4x2"..0x8F4D,
"DOUBLE_MAT4x3"..0x8F4E
)
// Uniform functions javadoc
val uniformLocation = "the location of the uniform variable to be modified"
val uniformX = "the uniform x value"
val uniformY = "the uniform y value"
val uniformZ = "the uniform z value"
val uniformW = "the uniform w value"
val uniformArrayCount = "the number of elements that are to be modified. This should be 1 if the targeted uniform variable is not an array, and 1 or more if it is an array."
val uniformArrayValue = "a pointer to an array of {@code count} values that will be used to update the specified uniform variable"
val uniformMatrixCount = "the number of matrices that are to be modified. This should be 1 if the targeted uniform variable is not an array of matrices, and 1 or more if it is an array of matrices."
val uniformMatrixTranspose = "whether to transpose the matrix as the values are loaded into the uniform variable"
val uniformMatrixValue = "a pointer to an array of {@code count} values that will be used to update the specified uniform matrix variable"
void(
"Uniform1d",
"Specifies the value of a double uniform variable for the current program object.",
GLint("location", uniformLocation),
GLdouble("x", uniformX)
)
void(
"Uniform2d",
"Specifies the value of a dvec2 uniform variable for the current program object.",
GLint("location", uniformLocation),
GLdouble("x", uniformX),
GLdouble("y", uniformY)
)
void(
"Uniform3d",
"Specifies the value of a dvec3 uniform variable for the current program object.",
GLint("location", uniformLocation),
GLdouble("x", uniformX),
GLdouble("y", uniformY),
GLdouble("z", uniformZ)
)
void(
"Uniform4d",
"Specifies the value of a dvec4 uniform variable for the current program object.",
GLint("location", uniformLocation),
GLdouble("x", uniformX),
GLdouble("y", uniformY),
GLdouble("z", uniformZ),
GLdouble("w", uniformW)
)
void(
"Uniform1dv",
"Specifies the value of a single double uniform variable or a double uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize("value")..GLsizei("count", uniformArrayCount),
GLdouble.const.p("value", uniformArrayValue)
)
void(
"Uniform2dv",
"Specifies the value of a single dvec2 uniform variable or a dvec2 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(2, "value")..GLsizei("count", uniformArrayCount),
GLdouble.const.p("value", uniformArrayValue)
)
void(
"Uniform3dv",
"Specifies the value of a single dvec3 uniform variable or a dvec3 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(3, "value")..GLsizei("count", uniformArrayCount),
GLdouble.const.p("value", uniformArrayValue)
)
void(
"Uniform4dv",
"Specifies the value of a single dvec4 uniform variable or a dvec4 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(4, "value")..GLsizei("count", uniformArrayCount),
GLdouble.const.p("value", uniformArrayValue)
)
void(
"UniformMatrix2dv",
"Specifies the value of a single dmat2 uniform variable or a dmat2 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(2 x 2, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix3dv",
"Specifies the value of a single dmat3 uniform variable or a dmat3 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(3 x 3, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix4dv",
"Specifies the value of a single dmat4 uniform variable or a dmat4 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(4 x 4, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix2x3dv",
"Specifies the value of a single dmat2x3 uniform variable or a dmat2x3 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(2 x 3, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix2x4dv",
"Specifies the value of a single dmat2x4 uniform variable or a dmat2x4 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(2 x 4, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix3x2dv",
"Specifies the value of a single dmat3x2 uniform variable or a dmat3x2 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(3 x 2, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix3x4dv",
"Specifies the value of a single dmat3x4 uniform variable or a dmat3x4 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(3 x 4, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix4x2dv",
"Specifies the value of a single dmat4x2 uniform variable or a dmat4x2 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(4 x 2, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"UniformMatrix4x3dv",
"Specifies the value of a single dmat4x3 uniform variable or a dmat4x3 uniform variable array for the current program object.",
GLint("location", uniformLocation),
AutoSize(4 x 3, "value")..GLsizei("count", uniformMatrixCount),
GLboolean("transpose", uniformMatrixTranspose),
GLdouble.const.p("value", uniformMatrixValue)
)
void(
"GetUniformdv",
"Returns the double value(s) of a uniform variable.",
GLuint("program", "the program object to be queried"),
GLint("location", "the location of the uniform variable to be queried"),
Check(1)..ReturnParam..GLdouble.p("params", "the value of the specified uniform variable")
)
// ARB_sample_shading
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, and by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev.
""",
"SAMPLE_SHADING"..0x8C36
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"MIN_SAMPLE_SHADING_VALUE"..0x8C37
)
void(
"MinSampleShading",
"Specifies the minimum rate at which sample shading takes place.",
GLfloat("value", "the rate at which samples are shaded within each covered pixel")
)
// ARB_shader_subroutine
val ProgramStageProperties = IntConstant(
"Accepted by the {@code pname} parameter of GetProgramStageiv.",
"ACTIVE_SUBROUTINES"..0x8DE5,
"ACTIVE_SUBROUTINE_UNIFORMS"..0x8DE6,
"ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS"..0x8E47,
"ACTIVE_SUBROUTINE_MAX_LENGTH"..0x8E48,
"ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH"..0x8E49
).javaDocLinks
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, GetDoublev, and GetInteger64v.",
"MAX_SUBROUTINES"..0x8DE7,
"MAX_SUBROUTINE_UNIFORM_LOCATIONS"..0x8DE8
)
IntConstant(
"Accepted by the {@code pname} parameter of GetActiveSubroutineUniformiv.",
"NUM_COMPATIBLE_SUBROUTINES"..0x8E4A,
"COMPATIBLE_SUBROUTINES"..0x8E4B
)
GLint(
"GetSubroutineUniformLocation",
"Retrieves the location of a subroutine uniform of a given shader stage within a program.",
GLuint("program", "the name of the program containing shader stage"),
GLenum("shadertype", "the shader stage from which to query for subroutine uniform index", SHADER_TYPES),
GLcharASCII.const.p("name", "the name of the subroutine uniform whose index to query.")
)
GLuint(
"GetSubroutineIndex",
"Retrieves the index of a subroutine function of a given shader stage within a program.",
GLuint("program", "the name of the program containing shader stage"),
GLenum("shadertype", "the shader stage from which to query for subroutine function index", SHADER_TYPES),
GLcharASCII.const.p("name", "the name of the subroutine function whose index to query")
)
void(
"GetActiveSubroutineUniformiv",
"Queries a property of an active shader subroutine uniform.",
GLuint("program", "the name of the program containing the subroutine"),
GLenum("shadertype", "the shader stage from which to query for the subroutine parameter", SHADER_TYPES),
GLuint("index", "the index of the shader subroutine uniform"),
GLenum(
"pname",
"the parameter of the shader subroutine uniform to query",
"#NUM_COMPATIBLE_SUBROUTINES #COMPATIBLE_SUBROUTINES #UNIFORM_SIZE #UNIFORM_NAME_LENGTH"
),
Check(1)..ReturnParam..GLint.p("values", "the address of a buffer into which the queried value or values will be placed")
)
void(
"GetActiveSubroutineUniformName",
"Queries the name of an active shader subroutine uniform.",
GLuint("program", "the name of the program containing the subroutine"),
GLenum("shadertype", "the shader stage from which to query for the subroutine parameter", SHADER_TYPES),
GLuint("index", "the index of the shader subroutine uniform"),
AutoSize("name")..GLsizei("bufsize", "the size of the buffer whose address is given in {@code name}"),
Check(1)..nullable..GLsizei.p("length", "the address of a variable into which is written the number of characters copied into {@code name}"),
Return(
"length", "glGetActiveSubroutineUniformi(program, shadertype, index, GL31.GL_UNIFORM_NAME_LENGTH)"
)..GLcharASCII.p("name", "the address of a buffer that will receive the name of the specified shader subroutine uniform")
)
void(
"GetActiveSubroutineName",
"Queries the name of an active shader subroutine.",
GLuint("program", "the name of the program containing the subroutine"),
GLenum("shadertype", "the shader stage from which to query the subroutine name", SHADER_TYPES),
GLuint("index", "the index of the shader subroutine uniform"),
AutoSize("name")..GLsizei("bufsize", "the size of the buffer whose address is given in {@code name}"),
Check(1)..nullable..GLsizei.p("length", "a variable which is to receive the length of the shader subroutine uniform name"),
Return(
"length", "glGetProgramStagei(program, shadertype, GL_ACTIVE_SUBROUTINE_MAX_LENGTH)"
)..GLcharASCII.p("name", "an array into which the name of the shader subroutine uniform will be written")
)
void(
"UniformSubroutinesuiv",
"Loads active subroutine uniforms.",
GLenum("shadertype", "the shader stage to update", SHADER_TYPES),
AutoSize("indices")..GLsizei("count", "the number of uniform indices stored in {@code indices}"),
SingleValue("index")..GLuint.const.p("indices", "an array holding the indices to load into the shader subroutine variables")
)
void(
"GetUniformSubroutineuiv",
"Retrieves the value of a subroutine uniform of a given shader stage of the current program.",
GLenum("shadertype", "the shader stage from which to query for subroutine uniform index", SHADER_TYPES),
GLint("location", "the location of the subroutine uniform"),
Check(1)..ReturnParam..GLuint.p("params", "a variable to receive the value or values of the subroutine uniform")
)
void(
"GetProgramStageiv",
"Retrieves properties of a program object corresponding to a specified shader stage.",
GLuint("program", "the name of the program containing shader stage"),
GLenum("shadertype", "the shader stage from which to query for the subroutine parameter", SHADER_TYPES),
GLenum("pname", "the parameter of the shader to query", ProgramStageProperties),
Check(1)..ReturnParam..GLint.p("values", "a variable into which the queried value or values will be placed")
)
// ARB_tesselation_shader
IntConstant(
"Accepted by the {@code mode} parameter of Begin and all vertex array functions that implicitly call Begin.",
"PATCHES"..0xE
)
IntConstant(
"Accepted by the {@code pname} parameter of PatchParameteri, GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, and GetInteger64v.",
"PATCH_VERTICES"..0x8E72
)
IntConstant(
"Accepted by the {@code pname} parameter of PatchParameterfv, GetBooleanv, GetDoublev, GetFloatv, and GetIntegerv, and GetInteger64v.",
"PATCH_DEFAULT_INNER_LEVEL"..0x8E73,
"PATCH_DEFAULT_OUTER_LEVEL"..0x8E74
)
IntConstant(
"Accepted by the {@code pname} parameter of GetProgramiv.",
"TESS_CONTROL_OUTPUT_VERTICES"..0x8E75,
"TESS_GEN_MODE"..0x8E76,
"TESS_GEN_SPACING"..0x8E77,
"TESS_GEN_VERTEX_ORDER"..0x8E78,
"TESS_GEN_POINT_MODE"..0x8E79
)
IntConstant(
"Returned by GetProgramiv when {@code pname} is TESS_GEN_MODE.",
"ISOLINES"..0x8E7A
)
IntConstant(
"Returned by GetProgramiv when {@code pname} is TESS_GEN_SPACING.",
"FRACTIONAL_ODD"..0x8E7B,
"FRACTIONAL_EVEN"..0x8E7C
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetFloatv, GetIntegerv, and GetInteger64v.",
"MAX_PATCH_VERTICES"..0x8E7D,
"MAX_TESS_GEN_LEVEL"..0x8E7E,
"MAX_TESS_CONTROL_UNIFORM_COMPONENTS"..0x8E7F,
"MAX_TESS_EVALUATION_UNIFORM_COMPONENTS"..0x8E80,
"MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS"..0x8E81,
"MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS"..0x8E82,
"MAX_TESS_CONTROL_OUTPUT_COMPONENTS"..0x8E83,
"MAX_TESS_PATCH_COMPONENTS"..0x8E84,
"MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS"..0x8E85,
"MAX_TESS_EVALUATION_OUTPUT_COMPONENTS"..0x8E86,
"MAX_TESS_CONTROL_UNIFORM_BLOCKS"..0x8E89,
"MAX_TESS_EVALUATION_UNIFORM_BLOCKS"..0x8E8A,
"MAX_TESS_CONTROL_INPUT_COMPONENTS"..0x886C,
"MAX_TESS_EVALUATION_INPUT_COMPONENTS"..0x886D,
"MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS"..0x8E1E,
"MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS"..0x8E1F
)
IntConstant(
"Accepted by the {@code pname} parameter of GetActiveUniformBlockiv.",
"UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER"..0x84F0,
"UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER"..0x84F1
)
IntConstant(
"Accepted by the {@code type} parameter of CreateShader and returned by the {@code params} parameter of GetShaderiv.",
"TESS_EVALUATION_SHADER"..0x8E87,
"TESS_CONTROL_SHADER"..0x8E88
)
void(
"PatchParameteri",
"Specifies the integer value of the specified parameter for patch primitives.",
GLenum("pname", "the name of the parameter to set", "#PATCH_VERTICES"),
GLint("value", "the new value for the parameter given by {@code pname}")
)
void(
"PatchParameterfv",
"Specifies an array of float values for the specified parameter for patch primitives.",
GLenum("pname", "the name of the parameter to set", "#PATCH_DEFAULT_OUTER_LEVEL #PATCH_DEFAULT_INNER_LEVEL"),
Check(
expression = "GL11.glGetInteger(GL_PATCH_VERTICES)", debug = true
)..GLfloat.const.p("values", "an array containing the new values for the parameter given by {@code pname}")
)
// ARB_texture_cube_map_array
IntConstant(
"Accepted by the {@code target} parameter of TexParameteri, TexParameteriv, TexParameterf, TexParameterfv, BindTexture, and GenerateMipmap.",
"TEXTURE_CUBE_MAP_ARRAY"..0x9009
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv and GetFloatv.",
"TEXTURE_BINDING_CUBE_MAP_ARRAY"..0x900A
)
IntConstant(
"Accepted by the {@code target} parameter of TexImage3D, TexSubImage3D, CompressedTeximage3D, CompressedTexSubImage3D and CopyTexSubImage3D.",
"PROXY_TEXTURE_CUBE_MAP_ARRAY"..0x900B
)
IntConstant(
"Returned by the {@code type} parameter of GetActiveUniform.",
"SAMPLER_CUBE_MAP_ARRAY"..0x900C,
"SAMPLER_CUBE_MAP_ARRAY_SHADOW"..0x900D,
"INT_SAMPLER_CUBE_MAP_ARRAY"..0x900E,
"UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY"..0x900F
)
// ARB_texture_gather
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and GetDoublev.",
"MIN_PROGRAM_TEXTURE_GATHER_OFFSET"..0x8E5E,
"MAX_PROGRAM_TEXTURE_GATHER_OFFSET"..0x8E5F
)
// ARB_transform_feedback2
IntConstant(
"Accepted by the {@code target} parameter of BindTransformFeedback.",
"TRANSFORM_FEEDBACK"..0x8E22
)
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"TRANSFORM_FEEDBACK_BUFFER_PAUSED"..0x8E23,
"TRANSFORM_FEEDBACK_BUFFER_ACTIVE"..0x8E24,
"TRANSFORM_FEEDBACK_BINDING"..0x8E25
)
void(
"BindTransformFeedback",
"Binds a transform feedback object.",
GLenum("target", "the target to which to bind the transform feedback object {@code id}", "#TRANSFORM_FEEDBACK"),
GLuint("id", "the name of a transform feedback object")
)
void(
"DeleteTransformFeedbacks",
"Deletes transform feedback objects.",
AutoSize("ids")..GLsizei("n", "the number of transform feedback objects to delete"),
SingleValue("id")..GLuint.const.p("ids", "an array of names of transform feedback objects to delete")
)
void(
"GenTransformFeedbacks",
"Reserves transform feedback object names.",
AutoSize("ids")..GLsizei("n", "the number of transform feedback object names to reserve"),
ReturnParam..GLuint.p("ids", "an array of into which the reserved names will be written")
)
GLboolean(
"IsTransformFeedback",
"Determines if a name corresponds to a transform feedback object.",
GLuint("id", "a value that may be the name of a transform feedback object")
)
void(
"PauseTransformFeedback",
"""
Pauses transform feedback operations for the currently bound transform feedback object.
When transform feedback operations are paused, transform feedback is still considered active and changing most transform feedback state related to the
object results in an error. However, a new transform feedback object may be bound while transform feedback is paused. The error #INVALID_OPERATION
is generated by PauseTransformFeedback if the currently bound transform feedback is not active or is paused.
When transform feedback is active and not paused, all geometric primitives generated must be compatible with the value of {@code primitiveMode} passed
to #BeginTransformFeedback(). The error #INVALID_OPERATION is generated by #Begin() or any operation that implicitly calls #Begin()
(such as #DrawElements()) if {@code mode} is not one of the allowed modes. If a geometry shader is active, its output primitive type is used instead
of the {@code mode} parameter passed to #Begin() for the purposes of this error check. Any primitive type may be used while transform feedback is
paused.
"""
)
void(
"ResumeTransformFeedback",
"""
Resumes transform feedback operations for the currently bound transform feedback object.
The error #INVALID_OPERATION is generated by #ResumeTransformFeedback() if the currently bound transform feedback is not active or is not paused.
"""
)
void(
"DrawTransformFeedback",
"Render primitives using a count derived from a transform feedback object.",
GLenum("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
GLuint("id", "the name of a transform feedback object from which to retrieve a primitive count")
)
// ARB_transform_feedback3
IntConstant(
"Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.",
"MAX_TRANSFORM_FEEDBACK_BUFFERS"..0x8E70,
"MAX_VERTEX_STREAMS"..0x8E71
)
void(
"DrawTransformFeedbackStream",
"Renders primitives using a count derived from a specifed stream of a transform feedback object.",
GLenum("mode", "what kind of primitives to render", PRIMITIVE_TYPES),
GLuint("id", "the name of a transform feedback object from which to retrieve a primitive count"),
GLuint("stream", "the index of the transform feedback stream from which to retrieve a primitive count")
)
void(
"BeginQueryIndexed",
"Begins a query object on an indexed target",
GLenum(
"target",
"the target type of query object established between {@code glBeginQueryIndexed} and the subsequent #EndQueryIndexed()",
QUERY_TARGETS
),
GLuint("index", "the index of the query target upon which to begin the query"),
GLuint("id", "the name of a query object")
)
void(
"EndQueryIndexed",
"Ends a query object on an indexed target",
GLenum("target", "the target type of query object to be concluded", QUERY_TARGETS),
GLuint("index", "the index of the query target upon which to end the query")
)
void(
"GetQueryIndexediv",
"Returns parameters of an indexed query object target.",
GLenum("target", "a query object target", QUERY_TARGETS),
GLuint("index", "the index of the query object target"),
GLenum("pname", "the symbolic name of a query object target parameter"),
Check(1)..ReturnParam..GLint.p("params", "the requested data")
)
} | bsd-3-clause | 340dc1f3fb4fdceac52ad0c56675a5f4 | 38.21625 | 202 | 0.66384 | 4.576513 | false | false | false | false |
martijn-heil/wac-core | src/main/kotlin/tk/martijn_heil/wac_core/general/MaxOfItemListener.kt | 1 | 7608 | /*
* wac-core
* Copyright (C) 2016 Martijn Heil
*
* 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 tk.martijn_heil.wac_core.general
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.inventory.ClickType
import org.bukkit.event.inventory.InventoryClickEvent
import org.bukkit.event.inventory.InventoryDragEvent
import org.bukkit.event.player.PlayerPickupItemEvent
import org.bukkit.inventory.Inventory
import tk.martijn_heil.wac_core.WacCore
import tk.martijn_heil.wac_core.getStringWithArgs
class MaxOfItemListener() : Listener {
private val maxPerPlayerInventory: Map<Material, Int> = mapOf(
Pair(Material.TNT, 1)
)
/**
* Prevent a player from having more than 1 TNT block in their inventory.
*/
@EventHandler(ignoreCancelled = true)
fun onDragAndDrop(e: InventoryClickEvent) {
// All drag & drop actions.
// If the player tries to drag and drop a single item into their inventory, or if they drag and drop an entire stack into their inventory.
// So, if the player has no TNT in his inventory yet, but tries to put an entire stack in at once, that is also prevented.
if(e.inventory == e.whoClicked.inventory && !e.whoClicked.hasPermission(WacCore.Permission.BYPASS__ITEM_LIMIT.str)) {
maxPerPlayerInventory.forEach {
val m = it.key
val maxAmount = it.value
if (
((e.cursor.type == m && (e.cursor.amount + countItemsOfTypeInInventory(m, e.whoClicked.inventory) > maxAmount)) && (e.click == ClickType.LEFT))
|| (e.cursor.type == m && e.click == ClickType.RIGHT && countItemsOfTypeInInventory(m, e.whoClicked.inventory) >= maxAmount)
|| (e.click == ClickType.LEFT && e.cursor.amount > maxAmount && e.cursor.type == m)
) {
e.isCancelled = true
e.whoClicked.sendMessage(ChatColor.RED.toString() + getStringWithArgs(WacCore.messages,
arrayOf(maxAmount.toString(), m.toString()), "error.event.cancelled.inventory.moreOfItemThanAllowed"))
}
}
}
}
@EventHandler(ignoreCancelled = true)
fun onInventoryDrag(e: InventoryDragEvent) {
// Drag/distribution actions.
maxPerPlayerInventory.forEach {
val m = it.key
val maxAmount = it.value
if(itemsPlacedByInventoryDragContain(m, e) && (e.whoClicked.inventory.contains(m, maxAmount) ||
(countItemsPlacedByInventoryDrag(e) + countItemsOfTypeInInventory(m, e.whoClicked.inventory)) > maxAmount)) {
e.isCancelled = true
e.whoClicked.sendMessage(ChatColor.RED.toString() + getStringWithArgs(WacCore.messages,
arrayOf(maxAmount.toString(), m.toString()), "error.event.cancelled.inventory.moreOfItemThanAllowed"))
}
}
}
/**
* Prevent a player from having more than 1 TNT block in their inventory.
*/
@EventHandler(ignoreCancelled = true)
fun onPlayerShiftClickItemIntoPlayerInventory(e: InventoryClickEvent) {
maxPerPlayerInventory.forEach {
val m = it.key
val maxAmount = it.value
// If the player is trying to shift click TNT into their inventory.
if(e.inventory != e.whoClicked.inventory && (e.click == ClickType.SHIFT_LEFT || e.click == ClickType.SHIFT_RIGHT)
&& e.currentItem.type == m && (e.whoClicked.inventory.contains(m, maxAmount) || (e.currentItem.amount + e.currentItem.amount) > maxAmount)
&& !e.whoClicked.hasPermission(WacCore.Permission.BYPASS__ITEM_LIMIT.str)) {
e.isCancelled = true
e.whoClicked.sendMessage(ChatColor.RED.toString() + getStringWithArgs(WacCore.messages,
arrayOf(maxAmount.toString(), m.toString()), "error.event.cancelled.inventory.moreOfItemThanAllowed"))
}
}
}
/**
* Prevent a player from having more than 1 TNT block in their inventory.
*/
@EventHandler(ignoreCancelled = true)
fun onPlayerPickupItem(e: PlayerPickupItemEvent) {
maxPerPlayerInventory.forEach {
val m = it.key
val maxAmount = it.value
// If the player tries to pick up this item type from the ground.
if(!e.player.hasPermission(WacCore.Permission.BYPASS__ITEM_LIMIT.str) && e.item.itemStack.type == m) {
// If the player already has the max amount of this item type in his inventory, cancel the event.
if(e.player.inventory.contains(m, maxAmount)) {
e.isCancelled = true
} else if(e.item.itemStack.amount > maxAmount && !e.player.inventory.contains(m, maxAmount)) {
// if it is maxAmount, just allow the player to pick it up normally.
// If the player does not yet have this item type in his inventory,
// let him pick up maxAmount of this item type from the stack, but leave the rest lying on the ground
e.isCancelled = true // If we don't cancel it, the player will pick up the whole item stack.
val i = e.item.itemStack.clone()
i.amount = maxAmount
val result = e.player.inventory.addItem(i)
if(result.isEmpty()) { // successfully added maxAmount of this item type to the player's inventory.
// remove the maxAmount items we just added to the player's inventory from the ground.
// Decrementing the amount directly via chunkPropagateSkylightOcclusion.item.itemStack.amount-- does apperantly not work..
val i2 = e.item.itemStack.clone()
i2.amount -= maxAmount
e.item.itemStack = i2
}
}
}
}
}
fun countItemsPlacedByInventoryDrag(e: InventoryDragEvent): Int {
var count: Int = 0
e.newItems.forEach {
count += it.value.amount
}
return count
}
fun itemsPlacedByInventoryDragContain(m: Material, e: InventoryDragEvent): Boolean {
e.newItems.forEach {
if(it.value.type == m) return true
}
return false;
}
fun countItemsOfTypeInInventory(m: Material, i: Inventory): Int {
var count = 0
i.contents.forEach {
if(it != null && it.type == m) {
count += it.amount
}
}
return count
}
} | gpl-3.0 | 3348cf4e1ed099a3171ad61bf9590ff4 | 42.244186 | 159 | 0.602918 | 4.67035 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/ui/dsl/builder/impl/PlaceholderBaseImpl.kt | 2 | 3338 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.ui.dsl.builder.impl
import com.intellij.openapi.ui.DialogPanel
import com.intellij.ui.dsl.builder.CellBase
import com.intellij.ui.dsl.builder.SpacingConfiguration
import com.intellij.ui.dsl.gridLayout.Constraints
import org.jetbrains.annotations.ApiStatus
import javax.swing.JComponent
@ApiStatus.Internal
internal abstract class PlaceholderBaseImpl<T : CellBase<T>>(private val parent: RowImpl) : CellBaseImpl<T>() {
protected var placeholderCellData: PlaceholderCellData? = null
private set
private var visible = true
private var enabled = true
var component: JComponent? = null
set(value) {
reinstallComponent(field, value)
field = value
}
override fun enabledFromParent(parentEnabled: Boolean) {
doEnabled(parentEnabled && enabled)
}
override fun enabled(isEnabled: Boolean): CellBase<T> {
enabled = isEnabled
if (parent.isEnabled()) {
doEnabled(enabled)
}
return this
}
override fun visibleFromParent(parentVisible: Boolean) {
doVisible(parentVisible && visible)
}
override fun visible(isVisible: Boolean): CellBase<T> {
visible = isVisible
if (parent.isVisible()) {
doVisible(visible)
}
component?.isVisible = isVisible
return this
}
open fun init(panel: DialogPanel, constraints: Constraints, spacing: SpacingConfiguration) {
placeholderCellData = PlaceholderCellData(panel, constraints, spacing)
if (component != null) {
reinstallComponent(null, component)
}
}
private fun reinstallComponent(oldComponent: JComponent?, newComponent: JComponent?) {
var invalidate = false
if (oldComponent != null) {
placeholderCellData?.let {
if (oldComponent is DialogPanel) {
it.panel.unregisterIntegratedPanel(oldComponent)
}
it.panel.remove(oldComponent)
invalidate = true
}
}
if (newComponent != null) {
newComponent.isVisible = visible && parent.isVisible()
newComponent.isEnabled = enabled && parent.isEnabled()
placeholderCellData?.let {
val gaps = customGaps ?: getComponentGaps(it.constraints.gaps.left, it.constraints.gaps.right, newComponent, it.spacing)
it.constraints = it.constraints.copy(
gaps = gaps,
visualPaddings = prepareVisualPaddings(newComponent.origin)
)
it.panel.add(newComponent, it.constraints)
if (newComponent is DialogPanel) {
it.panel.registerIntegratedPanel(newComponent)
}
invalidate = true
}
}
if (invalidate) {
invalidate()
}
}
private fun doVisible(isVisible: Boolean) {
component?.let {
if (it.isVisible != isVisible) {
it.isVisible = isVisible
invalidate()
}
}
}
private fun doEnabled(isEnabled: Boolean) {
component?.let {
it.isEnabled = isEnabled
}
}
private fun invalidate() {
placeholderCellData?.let {
// Force parent to re-layout
it.panel.revalidate()
it.panel.repaint()
}
}
}
@ApiStatus.Internal
internal data class PlaceholderCellData(val panel: DialogPanel, var constraints: Constraints, val spacing: SpacingConfiguration)
| apache-2.0 | f001f06b0b759d9c7942794b8ba4e965 | 27.288136 | 128 | 0.685141 | 4.681627 | false | false | false | false |
JonathanxD/CodeAPI | src/main/kotlin/com/github/jonathanxd/kores/base/VariableDeclaration.kt | 1 | 3840 | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]>
* Copyright (c) contributors
*
*
* 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.github.jonathanxd.kores.base
import com.github.jonathanxd.kores.Instruction
import com.github.jonathanxd.kores.common.KoresNothing
import java.lang.reflect.Type
/**
* Declares a variable of type [variableType] and name [name] with default value [value] (null does not
* mean that you declared a variable with null value, it means that you declared a variable without a default value,
* for null values use `Literals.NULL`).
*/
data class VariableDeclaration(
override val modifiers: Set<KoresModifier>,
override val variableType: Type,
override val name: String,
override val value: Instruction
) : VariableBase, ValueHolder, TypedInstruction, ModifiersHolder {
override fun builder(): Builder = Builder(this)
class Builder() :
VariableBase.Builder<VariableDeclaration, Builder>,
ValueHolder.Builder<VariableDeclaration, Builder>,
ModifiersHolder.Builder<VariableDeclaration, Builder> {
lateinit var name: String
lateinit var variableType: Type
var value: Instruction = KoresNothing
var modifiers: Set<KoresModifier> = emptySet()
constructor(defaults: VariableDeclaration) : this() {
this.name = defaults.name
this.variableType = defaults.variableType
this.value = defaults.value
this.modifiers = defaults.modifiers
}
override fun name(value: String): Builder {
this.name = value
return this
}
override fun variableType(value: Type): Builder {
this.variableType = value
return this
}
override fun value(value: Instruction): Builder {
this.value = value
return this
}
override fun modifiers(value: Set<KoresModifier>): Builder {
this.modifiers = value
return this
}
/**
* Removes value definition.
*/
fun withoutValue(): Builder = this.value(KoresNothing)
override fun build(): VariableDeclaration =
VariableDeclaration(this.modifiers, this.variableType, this.name, this.value)
companion object {
@JvmStatic
fun builder(): Builder = Builder()
@JvmStatic
fun builder(defaults: VariableDeclaration): Builder = Builder(defaults)
}
}
}
| mit | 4f3e65ba1827442c10c3f63ebbb9bef9 | 37.019802 | 118 | 0.667448 | 4.916773 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/tree/visitors/JKVisitorWithCommentsPrinting.kt | 5 | 43201 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.nj2k.tree.visitors
import org.jetbrains.kotlin.nj2k.tree.*
abstract class JKVisitorWithCommentsPrinting : JKVisitor() {
abstract fun printLeftNonCodeElements(element: JKFormattingOwner)
abstract fun printRightNonCodeElements(element: JKFormattingOwner)
override fun visitTreeElement(treeElement: JKElement) {
if (treeElement is JKFormattingOwner) {
printLeftNonCodeElements(treeElement)
}
visitTreeElementRaw(treeElement)
if (treeElement is JKFormattingOwner) {
printRightNonCodeElements(treeElement)
}
}
abstract fun visitTreeElementRaw(treeElement: JKElement)
override fun visitDeclaration(declaration: JKDeclaration) {
printLeftNonCodeElements(declaration)
visitDeclarationRaw(declaration)
printRightNonCodeElements(declaration)
}
open fun visitDeclarationRaw(declaration: JKDeclaration) = visitTreeElementRaw(declaration)
override fun visitClass(klass: JKClass) {
printLeftNonCodeElements(klass)
visitClassRaw(klass)
printRightNonCodeElements(klass)
}
open fun visitClassRaw(klass: JKClass) = visitDeclarationRaw(klass)
override fun visitVariable(variable: JKVariable) {
printLeftNonCodeElements(variable)
visitVariableRaw(variable)
printRightNonCodeElements(variable)
}
open fun visitVariableRaw(variable: JKVariable) = visitDeclarationRaw(variable)
override fun visitLocalVariable(localVariable: JKLocalVariable) {
printLeftNonCodeElements(localVariable)
visitLocalVariableRaw(localVariable)
printRightNonCodeElements(localVariable)
}
open fun visitLocalVariableRaw(localVariable: JKLocalVariable) = visitVariableRaw(localVariable)
override fun visitForLoopVariable(forLoopVariable: JKForLoopVariable) {
printLeftNonCodeElements(forLoopVariable)
visitForLoopVariableRaw(forLoopVariable)
printRightNonCodeElements(forLoopVariable)
}
open fun visitForLoopVariableRaw(forLoopVariable: JKForLoopVariable) = visitVariableRaw(forLoopVariable)
override fun visitParameter(parameter: JKParameter) {
printLeftNonCodeElements(parameter)
visitParameterRaw(parameter)
printRightNonCodeElements(parameter)
}
open fun visitParameterRaw(parameter: JKParameter) = visitVariableRaw(parameter)
override fun visitEnumConstant(enumConstant: JKEnumConstant) {
printLeftNonCodeElements(enumConstant)
visitEnumConstantRaw(enumConstant)
printRightNonCodeElements(enumConstant)
}
open fun visitEnumConstantRaw(enumConstant: JKEnumConstant) = visitVariableRaw(enumConstant)
override fun visitTypeParameter(typeParameter: JKTypeParameter) {
printLeftNonCodeElements(typeParameter)
visitTypeParameterRaw(typeParameter)
printRightNonCodeElements(typeParameter)
}
open fun visitTypeParameterRaw(typeParameter: JKTypeParameter) = visitDeclarationRaw(typeParameter)
override fun visitMethod(method: JKMethod) {
printLeftNonCodeElements(method)
visitMethodRaw(method)
printRightNonCodeElements(method)
}
open fun visitMethodRaw(method: JKMethod) = visitDeclarationRaw(method)
override fun visitMethodImpl(methodImpl: JKMethodImpl) {
printLeftNonCodeElements(methodImpl)
visitMethodImplRaw(methodImpl)
printRightNonCodeElements(methodImpl)
}
open fun visitMethodImplRaw(methodImpl: JKMethodImpl) = visitMethodRaw(methodImpl)
override fun visitConstructor(constructor: JKConstructor) {
printLeftNonCodeElements(constructor)
visitConstructorRaw(constructor)
printRightNonCodeElements(constructor)
}
open fun visitConstructorRaw(constructor: JKConstructor) = visitMethodRaw(constructor)
override fun visitConstructorImpl(constructorImpl: JKConstructorImpl) {
printLeftNonCodeElements(constructorImpl)
visitConstructorImplRaw(constructorImpl)
printRightNonCodeElements(constructorImpl)
}
open fun visitConstructorImplRaw(constructorImpl: JKConstructorImpl) = visitConstructorRaw(constructorImpl)
override fun visitKtPrimaryConstructor(ktPrimaryConstructor: JKKtPrimaryConstructor) {
printLeftNonCodeElements(ktPrimaryConstructor)
visitKtPrimaryConstructorRaw(ktPrimaryConstructor)
printRightNonCodeElements(ktPrimaryConstructor)
}
open fun visitKtPrimaryConstructorRaw(ktPrimaryConstructor: JKKtPrimaryConstructor) = visitConstructorRaw(ktPrimaryConstructor)
override fun visitField(field: JKField) {
printLeftNonCodeElements(field)
visitFieldRaw(field)
printRightNonCodeElements(field)
}
open fun visitFieldRaw(field: JKField) = visitVariableRaw(field)
override fun visitKtInitDeclaration(ktInitDeclaration: JKKtInitDeclaration) {
printLeftNonCodeElements(ktInitDeclaration)
visitKtInitDeclarationRaw(ktInitDeclaration)
printRightNonCodeElements(ktInitDeclaration)
}
open fun visitKtInitDeclarationRaw(ktInitDeclaration: JKKtInitDeclaration) = visitDeclarationRaw(ktInitDeclaration)
override fun visitJavaStaticInitDeclaration(javaStaticInitDeclaration: JKJavaStaticInitDeclaration) {
printLeftNonCodeElements(javaStaticInitDeclaration)
visitJavaStaticInitDeclarationRaw(javaStaticInitDeclaration)
printRightNonCodeElements(javaStaticInitDeclaration)
}
open fun visitJavaStaticInitDeclarationRaw(javaStaticInitDeclaration: JKJavaStaticInitDeclaration) =
visitDeclarationRaw(javaStaticInitDeclaration)
override fun visitTreeRoot(treeRoot: JKTreeRoot) {
printLeftNonCodeElements(treeRoot)
visitTreeRootRaw(treeRoot)
printRightNonCodeElements(treeRoot)
}
open fun visitTreeRootRaw(treeRoot: JKTreeRoot) = visitTreeElementRaw(treeRoot)
override fun visitFile(file: JKFile) {
printLeftNonCodeElements(file)
visitFileRaw(file)
printRightNonCodeElements(file)
}
open fun visitFileRaw(file: JKFile) = visitTreeElementRaw(file)
override fun visitTypeElement(typeElement: JKTypeElement) {
printLeftNonCodeElements(typeElement)
visitTypeElementRaw(typeElement)
printRightNonCodeElements(typeElement)
}
open fun visitTypeElementRaw(typeElement: JKTypeElement) = visitTreeElementRaw(typeElement)
override fun visitBlock(block: JKBlock) {
printLeftNonCodeElements(block)
visitBlockRaw(block)
printRightNonCodeElements(block)
}
open fun visitBlockRaw(block: JKBlock) = visitTreeElementRaw(block)
override fun visitInheritanceInfo(inheritanceInfo: JKInheritanceInfo) {
printLeftNonCodeElements(inheritanceInfo)
visitInheritanceInfoRaw(inheritanceInfo)
printRightNonCodeElements(inheritanceInfo)
}
open fun visitInheritanceInfoRaw(inheritanceInfo: JKInheritanceInfo) = visitTreeElementRaw(inheritanceInfo)
override fun visitPackageDeclaration(packageDeclaration: JKPackageDeclaration) {
printLeftNonCodeElements(packageDeclaration)
visitPackageDeclarationRaw(packageDeclaration)
printRightNonCodeElements(packageDeclaration)
}
open fun visitPackageDeclarationRaw(packageDeclaration: JKPackageDeclaration) = visitTreeElementRaw(packageDeclaration)
override fun visitLabel(label: JKLabel) {
printLeftNonCodeElements(label)
visitLabelRaw(label)
printRightNonCodeElements(label)
}
open fun visitLabelRaw(label: JKLabel) = visitTreeElementRaw(label)
override fun visitLabelEmpty(labelEmpty: JKLabelEmpty) {
printLeftNonCodeElements(labelEmpty)
visitLabelEmptyRaw(labelEmpty)
printRightNonCodeElements(labelEmpty)
}
open fun visitLabelEmptyRaw(labelEmpty: JKLabelEmpty) = visitLabelRaw(labelEmpty)
override fun visitLabelText(labelText: JKLabelText) {
printLeftNonCodeElements(labelText)
visitLabelTextRaw(labelText)
printRightNonCodeElements(labelText)
}
open fun visitLabelTextRaw(labelText: JKLabelText) = visitLabelRaw(labelText)
override fun visitImportStatement(importStatement: JKImportStatement) {
printLeftNonCodeElements(importStatement)
visitImportStatementRaw(importStatement)
printRightNonCodeElements(importStatement)
}
open fun visitImportStatementRaw(importStatement: JKImportStatement) = visitTreeElementRaw(importStatement)
override fun visitImportList(importList: JKImportList) {
printLeftNonCodeElements(importList)
visitImportListRaw(importList)
printRightNonCodeElements(importList)
}
open fun visitImportListRaw(importList: JKImportList) = visitTreeElementRaw(importList)
override fun visitAnnotationParameter(annotationParameter: JKAnnotationParameter) {
printLeftNonCodeElements(annotationParameter)
visitAnnotationParameterRaw(annotationParameter)
printRightNonCodeElements(annotationParameter)
}
open fun visitAnnotationParameterRaw(annotationParameter: JKAnnotationParameter) = visitTreeElementRaw(annotationParameter)
override fun visitAnnotationParameterImpl(annotationParameterImpl: JKAnnotationParameterImpl) {
printLeftNonCodeElements(annotationParameterImpl)
visitAnnotationParameterImplRaw(annotationParameterImpl)
printRightNonCodeElements(annotationParameterImpl)
}
open fun visitAnnotationParameterImplRaw(annotationParameterImpl: JKAnnotationParameterImpl) =
visitAnnotationParameterRaw(annotationParameterImpl)
override fun visitAnnotationNameParameter(annotationNameParameter: JKAnnotationNameParameter) {
printLeftNonCodeElements(annotationNameParameter)
visitAnnotationNameParameterRaw(annotationNameParameter)
printRightNonCodeElements(annotationNameParameter)
}
open fun visitAnnotationNameParameterRaw(annotationNameParameter: JKAnnotationNameParameter) =
visitAnnotationParameterRaw(annotationNameParameter)
override fun visitArgument(argument: JKArgument) {
printLeftNonCodeElements(argument)
visitArgumentRaw(argument)
printRightNonCodeElements(argument)
}
open fun visitArgumentRaw(argument: JKArgument) = visitTreeElementRaw(argument)
override fun visitNamedArgument(namedArgument: JKNamedArgument) {
printLeftNonCodeElements(namedArgument)
visitNamedArgumentRaw(namedArgument)
printRightNonCodeElements(namedArgument)
}
open fun visitNamedArgumentRaw(namedArgument: JKNamedArgument) = visitArgumentRaw(namedArgument)
override fun visitArgumentImpl(argumentImpl: JKArgumentImpl) {
printLeftNonCodeElements(argumentImpl)
visitArgumentImplRaw(argumentImpl)
printRightNonCodeElements(argumentImpl)
}
open fun visitArgumentImplRaw(argumentImpl: JKArgumentImpl) = visitArgumentRaw(argumentImpl)
override fun visitArgumentList(argumentList: JKArgumentList) {
printLeftNonCodeElements(argumentList)
visitArgumentListRaw(argumentList)
printRightNonCodeElements(argumentList)
}
open fun visitArgumentListRaw(argumentList: JKArgumentList) = visitTreeElementRaw(argumentList)
override fun visitTypeParameterList(typeParameterList: JKTypeParameterList) {
printLeftNonCodeElements(typeParameterList)
visitTypeParameterListRaw(typeParameterList)
printRightNonCodeElements(typeParameterList)
}
open fun visitTypeParameterListRaw(typeParameterList: JKTypeParameterList) = visitTreeElementRaw(typeParameterList)
override fun visitAnnotationList(annotationList: JKAnnotationList) {
printLeftNonCodeElements(annotationList)
visitAnnotationListRaw(annotationList)
printRightNonCodeElements(annotationList)
}
open fun visitAnnotationListRaw(annotationList: JKAnnotationList) = visitTreeElementRaw(annotationList)
override fun visitAnnotation(annotation: JKAnnotation) {
printLeftNonCodeElements(annotation)
visitAnnotationRaw(annotation)
printRightNonCodeElements(annotation)
}
open fun visitAnnotationRaw(annotation: JKAnnotation) = visitTreeElementRaw(annotation)
override fun visitTypeArgumentList(typeArgumentList: JKTypeArgumentList) {
printLeftNonCodeElements(typeArgumentList)
visitTypeArgumentListRaw(typeArgumentList)
printRightNonCodeElements(typeArgumentList)
}
open fun visitTypeArgumentListRaw(typeArgumentList: JKTypeArgumentList) = visitTreeElementRaw(typeArgumentList)
override fun visitNameIdentifier(nameIdentifier: JKNameIdentifier) {
printLeftNonCodeElements(nameIdentifier)
visitNameIdentifierRaw(nameIdentifier)
printRightNonCodeElements(nameIdentifier)
}
open fun visitNameIdentifierRaw(nameIdentifier: JKNameIdentifier) = visitTreeElementRaw(nameIdentifier)
override fun visitBlockImpl(blockImpl: JKBlockImpl) {
printLeftNonCodeElements(blockImpl)
visitBlockImplRaw(blockImpl)
printRightNonCodeElements(blockImpl)
}
open fun visitBlockImplRaw(blockImpl: JKBlockImpl) = visitBlockRaw(blockImpl)
override fun visitKtWhenCase(ktWhenCase: JKKtWhenCase) {
printLeftNonCodeElements(ktWhenCase)
visitKtWhenCaseRaw(ktWhenCase)
printRightNonCodeElements(ktWhenCase)
}
open fun visitKtWhenCaseRaw(ktWhenCase: JKKtWhenCase) = visitTreeElementRaw(ktWhenCase)
override fun visitKtWhenLabel(ktWhenLabel: JKKtWhenLabel) {
printLeftNonCodeElements(ktWhenLabel)
visitKtWhenLabelRaw(ktWhenLabel)
printRightNonCodeElements(ktWhenLabel)
}
open fun visitKtWhenLabelRaw(ktWhenLabel: JKKtWhenLabel) = visitTreeElementRaw(ktWhenLabel)
override fun visitKtElseWhenLabel(ktElseWhenLabel: JKKtElseWhenLabel) {
printLeftNonCodeElements(ktElseWhenLabel)
visitKtElseWhenLabelRaw(ktElseWhenLabel)
printRightNonCodeElements(ktElseWhenLabel)
}
open fun visitKtElseWhenLabelRaw(ktElseWhenLabel: JKKtElseWhenLabel) = visitKtWhenLabelRaw(ktElseWhenLabel)
override fun visitKtValueWhenLabel(ktValueWhenLabel: JKKtValueWhenLabel) {
printLeftNonCodeElements(ktValueWhenLabel)
visitKtValueWhenLabelRaw(ktValueWhenLabel)
printRightNonCodeElements(ktValueWhenLabel)
}
open fun visitKtValueWhenLabelRaw(ktValueWhenLabel: JKKtValueWhenLabel) = visitKtWhenLabelRaw(ktValueWhenLabel)
override fun visitClassBody(classBody: JKClassBody) {
printLeftNonCodeElements(classBody)
visitClassBodyRaw(classBody)
printRightNonCodeElements(classBody)
}
open fun visitClassBodyRaw(classBody: JKClassBody) = visitTreeElementRaw(classBody)
override fun visitJavaTryCatchSection(javaTryCatchSection: JKJavaTryCatchSection) {
printLeftNonCodeElements(javaTryCatchSection)
visitJavaTryCatchSectionRaw(javaTryCatchSection)
printRightNonCodeElements(javaTryCatchSection)
}
open fun visitJavaTryCatchSectionRaw(javaTryCatchSection: JKJavaTryCatchSection) = visitStatementRaw(javaTryCatchSection)
override fun visitJavaSwitchCase(javaSwitchCase: JKJavaSwitchCase) {
printLeftNonCodeElements(javaSwitchCase)
visitJavaSwitchCaseRaw(javaSwitchCase)
printRightNonCodeElements(javaSwitchCase)
}
open fun visitJavaSwitchCaseRaw(javaSwitchCase: JKJavaSwitchCase) = visitTreeElementRaw(javaSwitchCase)
override fun visitJavaDefaultSwitchCase(javaDefaultSwitchCase: JKJavaDefaultSwitchCase) {
printLeftNonCodeElements(javaDefaultSwitchCase)
visitJavaDefaultSwitchCaseRaw(javaDefaultSwitchCase)
printRightNonCodeElements(javaDefaultSwitchCase)
}
open fun visitJavaDefaultSwitchCaseRaw(javaDefaultSwitchCase: JKJavaDefaultSwitchCase) = visitJavaSwitchCaseRaw(javaDefaultSwitchCase)
override fun visitJavaLabelSwitchCase(javaLabelSwitchCase: JKJavaLabelSwitchCase) {
printLeftNonCodeElements(javaLabelSwitchCase)
visitJavaLabelSwitchCaseRaw(javaLabelSwitchCase)
printRightNonCodeElements(javaLabelSwitchCase)
}
open fun visitJavaLabelSwitchCaseRaw(javaLabelSwitchCase: JKJavaLabelSwitchCase) = visitJavaSwitchCaseRaw(javaLabelSwitchCase)
override fun visitExpression(expression: JKExpression) {
printLeftNonCodeElements(expression)
visitExpressionRaw(expression)
printRightNonCodeElements(expression)
}
open fun visitExpressionRaw(expression: JKExpression) = visitTreeElementRaw(expression)
override fun visitOperatorExpression(operatorExpression: JKOperatorExpression) {
printLeftNonCodeElements(operatorExpression)
visitOperatorExpressionRaw(operatorExpression)
printRightNonCodeElements(operatorExpression)
}
open fun visitOperatorExpressionRaw(operatorExpression: JKOperatorExpression) = visitExpressionRaw(operatorExpression)
override fun visitBinaryExpression(binaryExpression: JKBinaryExpression) {
printLeftNonCodeElements(binaryExpression)
visitBinaryExpressionRaw(binaryExpression)
printRightNonCodeElements(binaryExpression)
}
open fun visitBinaryExpressionRaw(binaryExpression: JKBinaryExpression) = visitOperatorExpressionRaw(binaryExpression)
override fun visitUnaryExpression(unaryExpression: JKUnaryExpression) {
printLeftNonCodeElements(unaryExpression)
visitUnaryExpressionRaw(unaryExpression)
printRightNonCodeElements(unaryExpression)
}
open fun visitUnaryExpressionRaw(unaryExpression: JKUnaryExpression) = visitOperatorExpressionRaw(unaryExpression)
override fun visitPrefixExpression(prefixExpression: JKPrefixExpression) {
printLeftNonCodeElements(prefixExpression)
visitPrefixExpressionRaw(prefixExpression)
printRightNonCodeElements(prefixExpression)
}
open fun visitPrefixExpressionRaw(prefixExpression: JKPrefixExpression) = visitUnaryExpressionRaw(prefixExpression)
override fun visitPostfixExpression(postfixExpression: JKPostfixExpression) {
printLeftNonCodeElements(postfixExpression)
visitPostfixExpressionRaw(postfixExpression)
printRightNonCodeElements(postfixExpression)
}
open fun visitPostfixExpressionRaw(postfixExpression: JKPostfixExpression) = visitUnaryExpressionRaw(postfixExpression)
override fun visitQualifiedExpression(qualifiedExpression: JKQualifiedExpression) {
printLeftNonCodeElements(qualifiedExpression)
visitQualifiedExpressionRaw(qualifiedExpression)
printRightNonCodeElements(qualifiedExpression)
}
open fun visitQualifiedExpressionRaw(qualifiedExpression: JKQualifiedExpression) = visitExpressionRaw(qualifiedExpression)
override fun visitParenthesizedExpression(parenthesizedExpression: JKParenthesizedExpression) {
printLeftNonCodeElements(parenthesizedExpression)
visitParenthesizedExpressionRaw(parenthesizedExpression)
printRightNonCodeElements(parenthesizedExpression)
}
open fun visitParenthesizedExpressionRaw(parenthesizedExpression: JKParenthesizedExpression) = visitExpressionRaw(parenthesizedExpression)
override fun visitTypeCastExpression(typeCastExpression: JKTypeCastExpression) {
printLeftNonCodeElements(typeCastExpression)
visitTypeCastExpressionRaw(typeCastExpression)
printRightNonCodeElements(typeCastExpression)
}
open fun visitTypeCastExpressionRaw(typeCastExpression: JKTypeCastExpression) = visitExpressionRaw(typeCastExpression)
override fun visitLiteralExpression(literalExpression: JKLiteralExpression) {
printLeftNonCodeElements(literalExpression)
visitLiteralExpressionRaw(literalExpression)
printRightNonCodeElements(literalExpression)
}
open fun visitLiteralExpressionRaw(literalExpression: JKLiteralExpression) = visitExpressionRaw(literalExpression)
override fun visitStubExpression(stubExpression: JKStubExpression) {
printLeftNonCodeElements(stubExpression)
visitStubExpressionRaw(stubExpression)
printRightNonCodeElements(stubExpression)
}
open fun visitStubExpressionRaw(stubExpression: JKStubExpression) = visitExpressionRaw(stubExpression)
override fun visitThisExpression(thisExpression: JKThisExpression) {
printLeftNonCodeElements(thisExpression)
visitThisExpressionRaw(thisExpression)
printRightNonCodeElements(thisExpression)
}
open fun visitThisExpressionRaw(thisExpression: JKThisExpression) = visitExpressionRaw(thisExpression)
override fun visitSuperExpression(superExpression: JKSuperExpression) {
printLeftNonCodeElements(superExpression)
visitSuperExpressionRaw(superExpression)
printRightNonCodeElements(superExpression)
}
open fun visitSuperExpressionRaw(superExpression: JKSuperExpression) = visitExpressionRaw(superExpression)
override fun visitIfElseExpression(ifElseExpression: JKIfElseExpression) {
printLeftNonCodeElements(ifElseExpression)
visitIfElseExpressionRaw(ifElseExpression)
printRightNonCodeElements(ifElseExpression)
}
open fun visitIfElseExpressionRaw(ifElseExpression: JKIfElseExpression) = visitExpressionRaw(ifElseExpression)
override fun visitLambdaExpression(lambdaExpression: JKLambdaExpression) {
printLeftNonCodeElements(lambdaExpression)
visitLambdaExpressionRaw(lambdaExpression)
printRightNonCodeElements(lambdaExpression)
}
open fun visitLambdaExpressionRaw(lambdaExpression: JKLambdaExpression) = visitExpressionRaw(lambdaExpression)
override fun visitCallExpression(callExpression: JKCallExpression) {
printLeftNonCodeElements(callExpression)
visitCallExpressionRaw(callExpression)
printRightNonCodeElements(callExpression)
}
open fun visitCallExpressionRaw(callExpression: JKCallExpression) = visitExpressionRaw(callExpression)
override fun visitDelegationConstructorCall(delegationConstructorCall: JKDelegationConstructorCall) {
printLeftNonCodeElements(delegationConstructorCall)
visitDelegationConstructorCallRaw(delegationConstructorCall)
printRightNonCodeElements(delegationConstructorCall)
}
open fun visitDelegationConstructorCallRaw(delegationConstructorCall: JKDelegationConstructorCall) =
visitCallExpressionRaw(delegationConstructorCall)
override fun visitCallExpressionImpl(callExpressionImpl: JKCallExpressionImpl) {
printLeftNonCodeElements(callExpressionImpl)
visitCallExpressionImplRaw(callExpressionImpl)
printRightNonCodeElements(callExpressionImpl)
}
open fun visitCallExpressionImplRaw(callExpressionImpl: JKCallExpressionImpl) = visitCallExpressionRaw(callExpressionImpl)
override fun visitNewExpression(newExpression: JKNewExpression) {
printLeftNonCodeElements(newExpression)
visitNewExpressionRaw(newExpression)
printRightNonCodeElements(newExpression)
}
open fun visitNewExpressionRaw(newExpression: JKNewExpression) = visitExpressionRaw(newExpression)
override fun visitFieldAccessExpression(fieldAccessExpression: JKFieldAccessExpression) {
printLeftNonCodeElements(fieldAccessExpression)
visitFieldAccessExpressionRaw(fieldAccessExpression)
printRightNonCodeElements(fieldAccessExpression)
}
open fun visitFieldAccessExpressionRaw(fieldAccessExpression: JKFieldAccessExpression) = visitExpressionRaw(fieldAccessExpression)
override fun visitPackageAccessExpression(packageAccessExpression: JKPackageAccessExpression) {
printLeftNonCodeElements(packageAccessExpression)
visitPackageAccessExpressionRaw(packageAccessExpression)
printRightNonCodeElements(packageAccessExpression)
}
open fun visitPackageAccessExpressionRaw(packageAccessExpression: JKPackageAccessExpression) =
visitExpressionRaw(packageAccessExpression)
override fun visitMethodAccessExpression(methodAccessExpression: JKMethodAccessExpression) {
printLeftNonCodeElements(methodAccessExpression)
visitMethodAccessExpressionRaw(methodAccessExpression)
printRightNonCodeElements(methodAccessExpression)
}
open fun visitMethodAccessExpressionRaw(methodAccessExpression: JKMethodAccessExpression) = visitExpressionRaw(methodAccessExpression)
override fun visitClassAccessExpression(classAccessExpression: JKClassAccessExpression) {
printLeftNonCodeElements(classAccessExpression)
visitClassAccessExpressionRaw(classAccessExpression)
printRightNonCodeElements(classAccessExpression)
}
open fun visitClassAccessExpressionRaw(classAccessExpression: JKClassAccessExpression) = visitExpressionRaw(classAccessExpression)
override fun visitMethodReferenceExpression(methodReferenceExpression: JKMethodReferenceExpression) {
printLeftNonCodeElements(methodReferenceExpression)
visitMethodReferenceExpressionRaw(methodReferenceExpression)
printRightNonCodeElements(methodReferenceExpression)
}
open fun visitMethodReferenceExpressionRaw(methodReferenceExpression: JKMethodReferenceExpression) =
visitExpressionRaw(methodReferenceExpression)
override fun visitLabeledExpression(labeledExpression: JKLabeledExpression) {
printLeftNonCodeElements(labeledExpression)
visitLabeledExpressionRaw(labeledExpression)
printRightNonCodeElements(labeledExpression)
}
open fun visitLabeledExpressionRaw(labeledExpression: JKLabeledExpression) = visitExpressionRaw(labeledExpression)
override fun visitClassLiteralExpression(classLiteralExpression: JKClassLiteralExpression) {
printLeftNonCodeElements(classLiteralExpression)
visitClassLiteralExpressionRaw(classLiteralExpression)
printRightNonCodeElements(classLiteralExpression)
}
open fun visitClassLiteralExpressionRaw(classLiteralExpression: JKClassLiteralExpression) = visitExpressionRaw(classLiteralExpression)
override fun visitKtAssignmentChainLink(ktAssignmentChainLink: JKKtAssignmentChainLink) {
printLeftNonCodeElements(ktAssignmentChainLink)
visitKtAssignmentChainLinkRaw(ktAssignmentChainLink)
printRightNonCodeElements(ktAssignmentChainLink)
}
open fun visitKtAssignmentChainLinkRaw(ktAssignmentChainLink: JKKtAssignmentChainLink) = visitExpressionRaw(ktAssignmentChainLink)
override fun visitAssignmentChainAlsoLink(assignmentChainAlsoLink: JKAssignmentChainAlsoLink) {
printLeftNonCodeElements(assignmentChainAlsoLink)
visitAssignmentChainAlsoLinkRaw(assignmentChainAlsoLink)
printRightNonCodeElements(assignmentChainAlsoLink)
}
open fun visitAssignmentChainAlsoLinkRaw(assignmentChainAlsoLink: JKAssignmentChainAlsoLink) =
visitKtAssignmentChainLinkRaw(assignmentChainAlsoLink)
override fun visitAssignmentChainLetLink(assignmentChainLetLink: JKAssignmentChainLetLink) {
printLeftNonCodeElements(assignmentChainLetLink)
visitAssignmentChainLetLinkRaw(assignmentChainLetLink)
printRightNonCodeElements(assignmentChainLetLink)
}
open fun visitAssignmentChainLetLinkRaw(assignmentChainLetLink: JKAssignmentChainLetLink) =
visitKtAssignmentChainLinkRaw(assignmentChainLetLink)
override fun visitIsExpression(isExpression: JKIsExpression) {
printLeftNonCodeElements(isExpression)
visitIsExpressionRaw(isExpression)
printRightNonCodeElements(isExpression)
}
open fun visitIsExpressionRaw(isExpression: JKIsExpression) = visitExpressionRaw(isExpression)
override fun visitKtThrowExpression(ktThrowExpression: JKKtThrowExpression) {
printLeftNonCodeElements(ktThrowExpression)
visitKtThrowExpressionRaw(ktThrowExpression)
printRightNonCodeElements(ktThrowExpression)
}
open fun visitKtThrowExpressionRaw(ktThrowExpression: JKKtThrowExpression) = visitExpressionRaw(ktThrowExpression)
override fun visitKtItExpression(ktItExpression: JKKtItExpression) {
printLeftNonCodeElements(ktItExpression)
visitKtItExpressionRaw(ktItExpression)
printRightNonCodeElements(ktItExpression)
}
open fun visitKtItExpressionRaw(ktItExpression: JKKtItExpression) = visitExpressionRaw(ktItExpression)
override fun visitKtAnnotationArrayInitializerExpression(ktAnnotationArrayInitializerExpression: JKKtAnnotationArrayInitializerExpression) {
printLeftNonCodeElements(ktAnnotationArrayInitializerExpression)
visitKtAnnotationArrayInitializerExpressionRaw(ktAnnotationArrayInitializerExpression)
printRightNonCodeElements(ktAnnotationArrayInitializerExpression)
}
open fun visitKtAnnotationArrayInitializerExpressionRaw(ktAnnotationArrayInitializerExpression: JKKtAnnotationArrayInitializerExpression) =
visitExpressionRaw(ktAnnotationArrayInitializerExpression)
override fun visitKtTryExpression(ktTryExpression: JKKtTryExpression) {
printLeftNonCodeElements(ktTryExpression)
visitKtTryExpressionRaw(ktTryExpression)
printRightNonCodeElements(ktTryExpression)
}
open fun visitKtTryExpressionRaw(ktTryExpression: JKKtTryExpression) = visitExpressionRaw(ktTryExpression)
override fun visitKtTryCatchSection(ktTryCatchSection: JKKtTryCatchSection) {
printLeftNonCodeElements(ktTryCatchSection)
visitKtTryCatchSectionRaw(ktTryCatchSection)
printRightNonCodeElements(ktTryCatchSection)
}
open fun visitKtTryCatchSectionRaw(ktTryCatchSection: JKKtTryCatchSection) = visitTreeElementRaw(ktTryCatchSection)
override fun visitJavaNewEmptyArray(javaNewEmptyArray: JKJavaNewEmptyArray) {
printLeftNonCodeElements(javaNewEmptyArray)
visitJavaNewEmptyArrayRaw(javaNewEmptyArray)
printRightNonCodeElements(javaNewEmptyArray)
}
open fun visitJavaNewEmptyArrayRaw(javaNewEmptyArray: JKJavaNewEmptyArray) = visitExpressionRaw(javaNewEmptyArray)
override fun visitJavaNewArray(javaNewArray: JKJavaNewArray) {
printLeftNonCodeElements(javaNewArray)
visitJavaNewArrayRaw(javaNewArray)
printRightNonCodeElements(javaNewArray)
}
open fun visitJavaNewArrayRaw(javaNewArray: JKJavaNewArray) = visitExpressionRaw(javaNewArray)
override fun visitJavaAssignmentExpression(javaAssignmentExpression: JKJavaAssignmentExpression) {
printLeftNonCodeElements(javaAssignmentExpression)
visitJavaAssignmentExpressionRaw(javaAssignmentExpression)
printRightNonCodeElements(javaAssignmentExpression)
}
open fun visitJavaAssignmentExpressionRaw(javaAssignmentExpression: JKJavaAssignmentExpression) = visitExpressionRaw(javaAssignmentExpression)
override fun visitModifierElement(modifierElement: JKModifierElement) {
printLeftNonCodeElements(modifierElement)
visitModifierElementRaw(modifierElement)
printRightNonCodeElements(modifierElement)
}
open fun visitModifierElementRaw(modifierElement: JKModifierElement) = visitTreeElementRaw(modifierElement)
override fun visitMutabilityModifierElement(mutabilityModifierElement: JKMutabilityModifierElement) {
printLeftNonCodeElements(mutabilityModifierElement)
visitMutabilityModifierElementRaw(mutabilityModifierElement)
printRightNonCodeElements(mutabilityModifierElement)
}
open fun visitMutabilityModifierElementRaw(mutabilityModifierElement: JKMutabilityModifierElement) =
visitModifierElementRaw(mutabilityModifierElement)
override fun visitModalityModifierElement(modalityModifierElement: JKModalityModifierElement) {
printLeftNonCodeElements(modalityModifierElement)
visitModalityModifierElementRaw(modalityModifierElement)
printRightNonCodeElements(modalityModifierElement)
}
open fun visitModalityModifierElementRaw(modalityModifierElement: JKModalityModifierElement) =
visitModifierElementRaw(modalityModifierElement)
override fun visitVisibilityModifierElement(visibilityModifierElement: JKVisibilityModifierElement) {
printLeftNonCodeElements(visibilityModifierElement)
visitVisibilityModifierElementRaw(visibilityModifierElement)
printRightNonCodeElements(visibilityModifierElement)
}
open fun visitVisibilityModifierElementRaw(visibilityModifierElement: JKVisibilityModifierElement) =
visitModifierElementRaw(visibilityModifierElement)
override fun visitOtherModifierElement(otherModifierElement: JKOtherModifierElement) {
printLeftNonCodeElements(otherModifierElement)
visitOtherModifierElementRaw(otherModifierElement)
printRightNonCodeElements(otherModifierElement)
}
open fun visitOtherModifierElementRaw(otherModifierElement: JKOtherModifierElement) = visitModifierElementRaw(otherModifierElement)
override fun visitStatement(statement: JKStatement) {
printLeftNonCodeElements(statement)
visitStatementRaw(statement)
printRightNonCodeElements(statement)
}
open fun visitStatementRaw(statement: JKStatement) = visitTreeElementRaw(statement)
override fun visitEmptyStatement(emptyStatement: JKEmptyStatement) {
printLeftNonCodeElements(emptyStatement)
visitEmptyStatementRaw(emptyStatement)
printRightNonCodeElements(emptyStatement)
}
open fun visitEmptyStatementRaw(emptyStatement: JKEmptyStatement) = visitStatementRaw(emptyStatement)
override fun visitLoopStatement(loopStatement: JKLoopStatement) {
printLeftNonCodeElements(loopStatement)
visitLoopStatementRaw(loopStatement)
printRightNonCodeElements(loopStatement)
}
open fun visitLoopStatementRaw(loopStatement: JKLoopStatement) = visitStatementRaw(loopStatement)
override fun visitWhileStatement(whileStatement: JKWhileStatement) {
printLeftNonCodeElements(whileStatement)
visitWhileStatementRaw(whileStatement)
printRightNonCodeElements(whileStatement)
}
open fun visitWhileStatementRaw(whileStatement: JKWhileStatement) = visitLoopStatementRaw(whileStatement)
override fun visitDoWhileStatement(doWhileStatement: JKDoWhileStatement) {
printLeftNonCodeElements(doWhileStatement)
visitDoWhileStatementRaw(doWhileStatement)
printRightNonCodeElements(doWhileStatement)
}
open fun visitDoWhileStatementRaw(doWhileStatement: JKDoWhileStatement) = visitLoopStatementRaw(doWhileStatement)
override fun visitForInStatement(forInStatement: JKForInStatement) {
printLeftNonCodeElements(forInStatement)
visitForInStatementRaw(forInStatement)
printRightNonCodeElements(forInStatement)
}
open fun visitForInStatementRaw(forInStatement: JKForInStatement) = visitStatementRaw(forInStatement)
override fun visitIfElseStatement(ifElseStatement: JKIfElseStatement) {
printLeftNonCodeElements(ifElseStatement)
visitIfElseStatementRaw(ifElseStatement)
printRightNonCodeElements(ifElseStatement)
}
open fun visitIfElseStatementRaw(ifElseStatement: JKIfElseStatement) = visitStatementRaw(ifElseStatement)
override fun visitBreakStatement(breakStatement: JKBreakStatement) {
printLeftNonCodeElements(breakStatement)
visitBreakStatementRaw(breakStatement)
printRightNonCodeElements(breakStatement)
}
open fun visitBreakStatementRaw(breakStatement: JKBreakStatement) = visitStatementRaw(breakStatement)
override fun visitContinueStatement(continueStatement: JKContinueStatement) {
printLeftNonCodeElements(continueStatement)
visitContinueStatementRaw(continueStatement)
printRightNonCodeElements(continueStatement)
}
open fun visitContinueStatementRaw(continueStatement: JKContinueStatement) = visitStatementRaw(continueStatement)
override fun visitBlockStatement(blockStatement: JKBlockStatement) {
printLeftNonCodeElements(blockStatement)
visitBlockStatementRaw(blockStatement)
printRightNonCodeElements(blockStatement)
}
open fun visitBlockStatementRaw(blockStatement: JKBlockStatement) = visitStatementRaw(blockStatement)
override fun visitBlockStatementWithoutBrackets(blockStatementWithoutBrackets: JKBlockStatementWithoutBrackets) {
printLeftNonCodeElements(blockStatementWithoutBrackets)
visitBlockStatementWithoutBracketsRaw(blockStatementWithoutBrackets)
printRightNonCodeElements(blockStatementWithoutBrackets)
}
open fun visitBlockStatementWithoutBracketsRaw(blockStatementWithoutBrackets: JKBlockStatementWithoutBrackets) =
visitStatementRaw(blockStatementWithoutBrackets)
override fun visitExpressionStatement(expressionStatement: JKExpressionStatement) {
printLeftNonCodeElements(expressionStatement)
visitExpressionStatementRaw(expressionStatement)
printRightNonCodeElements(expressionStatement)
}
open fun visitExpressionStatementRaw(expressionStatement: JKExpressionStatement) = visitStatementRaw(expressionStatement)
override fun visitDeclarationStatement(declarationStatement: JKDeclarationStatement) {
printLeftNonCodeElements(declarationStatement)
visitDeclarationStatementRaw(declarationStatement)
printRightNonCodeElements(declarationStatement)
}
open fun visitDeclarationStatementRaw(declarationStatement: JKDeclarationStatement) = visitStatementRaw(declarationStatement)
override fun visitKtWhenStatement(ktWhenStatement: JKKtWhenStatement) {
printLeftNonCodeElements(ktWhenStatement)
visitKtWhenStatementRaw(ktWhenStatement)
printRightNonCodeElements(ktWhenStatement)
}
open fun visitKtWhenStatementRaw(ktWhenStatement: JKKtWhenStatement) = visitStatementRaw(ktWhenStatement)
override fun visitKtWhenExpression(ktWhenExpression: JKKtWhenExpression) {
printLeftNonCodeElements(ktWhenExpression)
visitKtWhenExpressionRaw(ktWhenExpression)
printRightNonCodeElements(ktWhenExpression)
}
open fun visitKtWhenExpressionRaw(ktWhenExpression: JKKtWhenExpression) = visitExpressionRaw(ktWhenExpression)
override fun visitKtWhenBlock(ktWhenBlock: JKKtWhenBlock) {
printLeftNonCodeElements(ktWhenBlock)
visitKtWhenBlockRaw(ktWhenBlock)
printRightNonCodeElements(ktWhenBlock)
}
open fun visitKtWhenBlockRaw(ktWhenBlock: JKKtWhenBlock) = visitTreeElementRaw(ktWhenBlock)
override fun visitKtConvertedFromForLoopSyntheticWhileStatement(ktConvertedFromForLoopSyntheticWhileStatement: JKKtConvertedFromForLoopSyntheticWhileStatement) {
printLeftNonCodeElements(ktConvertedFromForLoopSyntheticWhileStatement)
visitKtConvertedFromForLoopSyntheticWhileStatementRaw(ktConvertedFromForLoopSyntheticWhileStatement)
printRightNonCodeElements(ktConvertedFromForLoopSyntheticWhileStatement)
}
open fun visitKtConvertedFromForLoopSyntheticWhileStatementRaw(ktConvertedFromForLoopSyntheticWhileStatement: JKKtConvertedFromForLoopSyntheticWhileStatement) =
visitStatementRaw(ktConvertedFromForLoopSyntheticWhileStatement)
override fun visitKtAssignmentStatement(ktAssignmentStatement: JKKtAssignmentStatement) {
printLeftNonCodeElements(ktAssignmentStatement)
visitKtAssignmentStatementRaw(ktAssignmentStatement)
printRightNonCodeElements(ktAssignmentStatement)
}
open fun visitKtAssignmentStatementRaw(ktAssignmentStatement: JKKtAssignmentStatement) = visitStatementRaw(ktAssignmentStatement)
override fun visitReturnStatement(returnStatement: JKReturnStatement) {
printLeftNonCodeElements(returnStatement)
visitReturnStatementRaw(returnStatement)
printRightNonCodeElements(returnStatement)
}
open fun visitReturnStatementRaw(returnStatement: JKReturnStatement) = visitStatementRaw(returnStatement)
override fun visitJavaSwitchStatement(javaSwitchStatement: JKJavaSwitchStatement) {
printLeftNonCodeElements(javaSwitchStatement)
visitJavaSwitchStatementRaw(javaSwitchStatement)
printRightNonCodeElements(javaSwitchStatement)
}
open fun visitJavaSwitchStatementRaw(javaSwitchStatement: JKJavaSwitchStatement) = visitStatementRaw(javaSwitchStatement)
override fun visitJavaThrowStatement(javaThrowStatement: JKJavaThrowStatement) {
printLeftNonCodeElements(javaThrowStatement)
visitJavaThrowStatementRaw(javaThrowStatement)
printRightNonCodeElements(javaThrowStatement)
}
open fun visitJavaThrowStatementRaw(javaThrowStatement: JKJavaThrowStatement) = visitStatementRaw(javaThrowStatement)
override fun visitJavaTryStatement(javaTryStatement: JKJavaTryStatement) {
printLeftNonCodeElements(javaTryStatement)
visitJavaTryStatementRaw(javaTryStatement)
printRightNonCodeElements(javaTryStatement)
}
open fun visitJavaTryStatementRaw(javaTryStatement: JKJavaTryStatement) = visitStatementRaw(javaTryStatement)
override fun visitJavaSynchronizedStatement(javaSynchronizedStatement: JKJavaSynchronizedStatement) {
printLeftNonCodeElements(javaSynchronizedStatement)
visitJavaSynchronizedStatementRaw(javaSynchronizedStatement)
printRightNonCodeElements(javaSynchronizedStatement)
}
open fun visitJavaSynchronizedStatementRaw(javaSynchronizedStatement: JKJavaSynchronizedStatement) = visitStatementRaw(javaSynchronizedStatement)
override fun visitJavaAssertStatement(javaAssertStatement: JKJavaAssertStatement) {
printLeftNonCodeElements(javaAssertStatement)
visitJavaAssertStatementRaw(javaAssertStatement)
printRightNonCodeElements(javaAssertStatement)
}
open fun visitJavaAssertStatementRaw(javaAssertStatement: JKJavaAssertStatement) = visitStatementRaw(javaAssertStatement)
override fun visitJavaForLoopStatement(javaForLoopStatement: JKJavaForLoopStatement) {
printLeftNonCodeElements(javaForLoopStatement)
visitJavaForLoopStatementRaw(javaForLoopStatement)
printRightNonCodeElements(javaForLoopStatement)
}
open fun visitJavaForLoopStatementRaw(javaForLoopStatement: JKJavaForLoopStatement) = visitLoopStatementRaw(javaForLoopStatement)
override fun visitJavaAnnotationMethod(javaAnnotationMethod: JKJavaAnnotationMethod) {
printLeftNonCodeElements(javaAnnotationMethod)
visitJavaAnnotationMethodRaw(javaAnnotationMethod)
printRightNonCodeElements(javaAnnotationMethod)
}
open fun visitJavaAnnotationMethodRaw(javaAnnotationMethod: JKJavaAnnotationMethod) = visitMethodRaw(javaAnnotationMethod)
}
| apache-2.0 | 8e9979ab1739b665120753765ddc3017 | 43.127681 | 165 | 0.801301 | 7.671994 | false | false | false | false |
DreierF/MyTargets | app/src/main/java/de/dreier/mytargets/views/selector/EnvironmentSelector.kt | 1 | 7381 | /*
* Copyright (C) 2018 Florian Dreier
*
* This file is part of MyTargets.
*
* MyTargets is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* MyTargets is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
package de.dreier.mytargets.views.selector
import android.Manifest.permission.ACCESS_COARSE_LOCATION
import android.Manifest.permission.ACCESS_FINE_LOCATION
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.location.Geocoder
import android.location.Location
import androidx.annotation.RequiresPermission
import androidx.fragment.app.Fragment
import androidx.core.content.ContextCompat
import android.util.AttributeSet
import android.view.View
import de.dreier.mytargets.R
import de.dreier.mytargets.databinding.SelectorItemImageDetailsBinding
import de.dreier.mytargets.features.settings.SettingsManager
import de.dreier.mytargets.features.training.environment.CurrentWeather
import de.dreier.mytargets.features.training.environment.Locator
import de.dreier.mytargets.features.training.environment.WeatherService
import de.dreier.mytargets.shared.models.Environment
import de.dreier.mytargets.utils.Utils
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.io.IOException
class EnvironmentSelector @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null
) : SelectorBase<Environment, SelectorItemImageDetailsBinding>(
context,
attrs,
R.layout.selector_item_image_details,
ENVIRONMENT_REQUEST_CODE
) {
override var selectedItem: Environment?
get() = if (super.selectedItem == null) {
Environment.getDefault(SettingsManager.indoor)
} else super.selectedItem
set(value) {
super.selectedItem = value
}
override fun bindView(item: Environment) {
if (item.indoor) {
view.name.setText(de.dreier.mytargets.shared.R.string.indoor)
view.image.setImageResource(R.drawable.ic_house_24dp)
} else {
view.name.text = item.weather.getName()
view.image.setImageResource(item.weather.drawable)
}
view.details.visibility = View.VISIBLE
view.details.text = getDetails(context, item)
view.title.visibility = View.VISIBLE
view.title.setText(R.string.environment)
}
private fun getDetails(context: Context, item: Environment): String {
var description: String
if (item.indoor) {
description = ""
if (!item.location.isEmpty()) {
description += "${context.getString(de.dreier.mytargets.shared.R.string.location)}: ${item.location}"
}
} else {
description =
"${context.getString(de.dreier.mytargets.shared.R.string.wind)}: ${item.getWindSpeed(
context
)}"
if (!item.location.isEmpty()) {
description += "\n${context.getString(de.dreier.mytargets.shared.R.string.location)}: ${item.location}"
}
}
return description
}
fun queryWeather(fragment: Fragment, requestCode: Int) {
if (isTestMode) {
setDefaultWeather()
return
}
if (ContextCompat.checkSelfPermission(
fragment.context!!,
ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED
) {
setDefaultWeather()
fragment.requestPermissions(arrayOf(ACCESS_FINE_LOCATION), requestCode)
} else {
queryWeatherInfo(fragment.context!!)
}
}
@SuppressLint("MissingPermission")
fun onPermissionResult(activity: Activity, grantResult: IntArray) {
if (grantResult.isNotEmpty() && grantResult[0] == PackageManager.PERMISSION_GRANTED) {
queryWeatherInfo(activity)
} else {
setDefaultWeather()
}
}
// Start getting weather for current location
@SuppressLint("MissingPermission", "SupportAnnotationUsage")
@RequiresPermission(anyOf = [ACCESS_COARSE_LOCATION, ACCESS_FINE_LOCATION])
private fun queryWeatherInfo(context: Context) {
setItem(null)
Locator(context).getLocation(Locator.Method.NETWORK_THEN_GPS, object : Locator.Listener {
override fun onLocationFound(location: Location) {
val locationStr = getAddressFromLocation(location.latitude, location.longitude)
val weatherService = WeatherService()
val weatherCall = weatherService
.fetchCurrentWeather(location.longitude, location.latitude)
weatherCall.enqueue(object : Callback<CurrentWeather> {
override fun onResponse(
call: Call<CurrentWeather>,
response: Response<CurrentWeather>
) {
if (response.isSuccessful && response.body()!!.httpCode == 200) {
val toEnvironment = response.body()!!.toEnvironment()
setItem(
toEnvironment.copy(
location = locationStr
?: toEnvironment.location
)
)
} else {
setDefaultWeather()
}
}
override fun onFailure(call: Call<CurrentWeather>, t: Throwable) {
setDefaultWeather()
}
})
}
override fun onLocationNotFound() {
setDefaultWeather()
}
})
}
private fun getAddressFromLocation(latitude: Double, longitude: Double): String? {
val geoCoder = Geocoder(context, Utils.getCurrentLocale(context))
return try {
val addresses = geoCoder.getFromLocation(latitude, longitude, 1)
if (addresses.size > 0) {
val fetchedAddress = addresses[0]
var address = fetchedAddress.locality
if (fetchedAddress.subLocality != null) {
address += ", ${fetchedAddress.subLocality}"
}
address
} else {
null
}
} catch (e: IOException) {
e.printStackTrace()
null
}
}
private fun setDefaultWeather() {
setItem(Environment.getDefault(SettingsManager.indoor))
}
companion object {
const val ENVIRONMENT_REQUEST_CODE = 9
private val isTestMode: Boolean
get() {
return try {
Class.forName("de.dreier.mytargets.test.base.InstrumentedTestBase")
true
} catch (e: Exception) {
false
}
}
}
}
| gpl-2.0 | 60ba184b36c9bf225b3be1480d642dc7 | 35.721393 | 119 | 0.605338 | 5.219943 | false | false | false | false |
Virtlink/aesi | aesi-intellij/src/main/kotlin/com/virtlink/editorservices/intellij/resources/IntellijResourceManager.kt | 1 | 11755 | package com.virtlink.editorservices.intellij.resources
import com.intellij.openapi.editor.Document
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtil
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.virtlink.editorservices.resources.IContent
import com.virtlink.editorservices.resources.IResourceManager
import java.net.URI
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import com.intellij.testFramework.LightVirtualFile
import com.virtlink.editorservices.Offset
import com.virtlink.editorservices.Position
import com.virtlink.editorservices.content.StringContent
import com.virtlink.editorservices.resources.IAesiContent
/**
* IntelliJ resource manager.
*/
@Suppress("PrivatePropertyName", "unused")
class IntellijResourceManager: IResourceManager {
private val INTELLIJ_SCHEME = "intellij"
private val MEM_SCHEME = "mem"
// An IntelliJ URI is:
// intellij:///project/module!/filepath
// An in-memory URI is:
// mem:///myfile
// An absolute URI is, for example:
// file:///myfolder/myfile
fun getUri(document: Document, project: Project): URI {
val psiFile = getPsiFile(document, project)
if (psiFile != null) {
return getUri(psiFile)
} else {
TODO()
}
}
fun getUri(file: PsiFile): URI {
val module = getModule(file)
if (module != null) {
return getUri(file.originalFile.virtualFile, module)
} else {
TODO()
}
}
fun getUri(file: VirtualFile, project: Project): URI {
val module = getModule(file, project)
if (module != null) {
return getUri(file, module)
} else {
TODO()
}
}
fun getUri(module: Module): URI {
val projectName = module.project.name
val moduleName = module.name
return URI("$INTELLIJ_SCHEME:///$projectName/$moduleName")
}
fun getUri(file: VirtualFile, module: Module): URI {
val modulePath = ModuleUtil.getModuleDirPath(module)
val moduleVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(modulePath)!!
val relativeFilePath = VfsUtil.getRelativePath(file, moduleVirtualFile)
return if (relativeFilePath != null) {
// Path relative to the module.
URI(getUri(module).toString() + "!/$relativeFilePath")
} else {
// Absolute path.
URI(file.url)
}
}
/**
* Gets the PSI file for the specified document in the specified project.
*
* @param document The document.
* @param project The project.
* @return The PSI file; or null when it could not be determined.
*/
fun getPsiFile(document: Document, project: Project): PsiFile? {
return PsiDocumentManager.getInstance(project).getPsiFile(document)
}
/**
* Gets the PSI file for the specified URI.
*
* @param uri The URI.
* @return The PSI file; or null when it could not be determined.
*/
fun getPsiFile(uri: URI): PsiFile? {
val result = parseUri(uri)
if (result.module == null || result.file == null) {
return null
}
return PsiManager.getInstance(result.module.project).findFile(result.file)
}
/**
* Gets the virtual file for the specified URI.
*
* @param uri The URI.
* @return The virtual file; or null when it could not be determined.
*/
fun getFile(uri: URI): VirtualFile? {
val result = parseUri(uri)
return result.file
}
/**
* Gets the module for the specified virtual file in the specified project.
*
* @param file The virtual file.
* @param project The project.
* @return The module; or null when it could not be determined.
*/
fun getModule(file: VirtualFile, project: Project): Module? {
var module = ModuleUtil.findModuleForFile(file, project)
if (module == null && file is LightVirtualFile && file.originalFile != null) {
module = ModuleUtil.findModuleForFile(file.originalFile, project)
}
return module
}
/**
* Gets the module for the specified PSI file.
*
* @param psiFile The PSI file.
* @return The module; or null when it could not be determined.
*/
fun getModule(psiFile: PsiFile): Module? {
return ModuleUtilCore.findModuleForPsiElement(psiFile)
// From > IDEA 2017.2.5:
// return ModuleUtilCore.findModuleForFile(psiFile)
}
/**
* Gets the module for the specified PSI element.
*
* @param element The PSI element.
* @return The module; or null when it could not be determined.
*/
fun getModule(element: PsiElement): Module? {
return ModuleUtil.findModuleForPsiElement(element)
}
/**
* Gets the module that contains (or is) the specified URI.
*
* @param uri The URI.
* @return The module; or null when it could not be determined.
*/
fun getModule(uri: URI): Module? {
val result = parseUri(uri)
return result.module
}
/**
* Gets the content roots of the specified module.
*
* Content roots won't overlap.
*
* @param module The module.
* @return A list of virtual files representing the content roots of the module.
*/
fun getContentRoots(module: Module): List<VirtualFile> {
return ModuleRootManager.getInstance(module).contentRoots.toList()
}
/**
* Parses the specified URI.
*
* @param uri The URI to parse.
* @return The resulting components.
*/
private fun parseUri(uri: URI): ParsedUrl {
val module: Module?
val file: VirtualFile?
if (uri.scheme == INTELLIJ_SCHEME) {
// intellij:///project/module/!/filepath
val path = uri.path
val modulePathSeparator = path.indexOf('!')
val projectModulePart: String
val filePart: String?
if (modulePathSeparator >= 0) {
// /project/module/!/filepath
// A file or folder in a module.
projectModulePart = path.substring(0, modulePathSeparator)
filePart = path.substring(modulePathSeparator + 1).trimStart('/')
} else {
// /project/module/
// A module a project
projectModulePart = path
filePart = null
}
module = parseModule(projectModulePart)
file = getFileInModule(filePart, module)
} else if (uri.scheme == MEM_SCHEME) {
TODO()
} else {
module = null
file = getFileInModule(uri.toString(), null)
}
return ParsedUrl(module, file)
}
/**
* Parses the Project/Module combination.
*
* @param path The path, in the form `/projectname/modulename/`.
*/
private fun parseModule(path: String): Module? {
val trimmedPath = path.trim('/')
val projectModuleSeparator = trimmedPath.indexOf('/')
val projectName: String
val moduleName: String?
if (projectModuleSeparator > 0) {
projectName = trimmedPath.substring(0, projectModuleSeparator)
moduleName = trimmedPath.substring(projectModuleSeparator + 1)
} else {
projectName = trimmedPath
moduleName = null
}
val project = getProjectByName(projectName)
val module = if (project != null) getModuleByName(moduleName, project) else null
return module
}
/**
* Parses the file path.
*
* @param uri The relative path or absolute URI, in the form `/myfolder/myfile`.
* @param module The module.
* @return The virtual file; or null when not found.
*/
private fun getFileInModule(uri: String?, module: Module?): VirtualFile? {
if (uri == null) return null
val moduleVirtualFile: VirtualFile?
if (module != null) {
val modulePath = ModuleUtil.getModuleDirPath(module)
moduleVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByPath(modulePath)
} else {
moduleVirtualFile = null
}
return VfsUtil.findRelativeFile(uri, moduleVirtualFile)
}
/**
* Gets a project by name.
*
* @param name The project name.
* @return The project; or null when not found.
*/
private fun getProjectByName(name: String?): Project? {
if (name == null) return null
return ProjectManager.getInstance().openProjects.singleOrNull { p -> p.name == name }
}
/**
* Gets a module by name.
*
* @param name The name to look for.
* @param project The project that contains the module.
* @return The module; or null when not found.
*/
private fun getModuleByName(name: String?, project: Project): Module? {
if (name == null) return null
return ModuleManager.getInstance(project).findModuleByName(name)
}
override fun getProjectOf(uri: URI): URI? {
val module = getModule(uri)
return if (module != null) getUri(module) else module
}
override fun isProject(uri: URI): Boolean {
val (module, file) = parseUri(uri)
return module != null && file == null
}
override fun isFolder(uri: URI): Boolean {
val virtualFile = getFile(uri)
return virtualFile != null && virtualFile.isDirectory
}
override fun isFile(uri: URI): Boolean {
val virtualFile = getFile(uri)
return virtualFile != null && !virtualFile.isDirectory
}
override fun exists(uri: URI): Boolean {
val virtualFile = getFile(uri)
return virtualFile != null && virtualFile.exists()
}
override fun getChildren(uri: URI): Iterable<URI>? {
val (module, file) = parseUri(uri)
if (module == null || file == null) return null
return file.children.map { f -> getUri(f, module) }
}
override fun getParent(uri: URI): URI? {
// This is probably not correct in all situations.
return if (uri.path.endsWith("/")) uri.resolve("..") else uri.resolve(".")
}
override fun getContent(uri: URI): IContent? {
val psiFile = getPsiFile(uri)
val document: Document?
if (psiFile != null) {
document = PsiDocumentManager.getInstance(psiFile.project).getDocument(psiFile)
} else {
val virtualFile = getFile(uri) ?: return null
document = if (virtualFile != null) FileDocumentManager.getInstance().getDocument(virtualFile) else null
}
return if (document != null) StringContent(document.text, document.modificationStamp) else null
}
override fun getOffset(content: IContent, position: Position): Offset? {
return (content as? IAesiContent)?.getOffset(position)
}
override fun getPosition(content: IContent, offset: Offset): Position? {
return (content as? IAesiContent)?.getPosition(offset)
}
private data class ParsedUrl(
val module: Module?,
val file: VirtualFile?
)
} | apache-2.0 | 7cfbe6afe4ff4100242c0be5024b775e | 32.20904 | 116 | 0.628073 | 4.694489 | false | false | false | false |
RuneSuite/client | plugins-dev/src/main/java/org/runestar/client/plugins/dev/Transmog.kt | 1 | 1399 | package org.runestar.client.plugins.dev
import org.runestar.client.api.plugins.DisposablePlugin
import org.runestar.client.api.game.live.Game
import org.runestar.client.api.game.live.Players
import org.runestar.client.raw.access.XPlayer
import org.runestar.client.raw.CLIENT
import org.runestar.client.api.plugins.PluginSettings
class Transmog : DisposablePlugin<Transmog.Settings>() {
override val defaultSettings = Settings()
override fun onStart() {
add(Game.ticks.subscribe {
Players.local?.accessor?.let { transmog(it, settings.npcId) }
})
}
override fun onStop() {
Players.local?.appearance?.accessor?.npcTransformId = -1
}
private fun transmog(player: XPlayer, npcId: Int) {
val appearance = player.appearance ?: return
val def = CLIENT.getNPCType(npcId) ?: return
appearance.npcTransformId = npcId
player.walkSequence = def.walkanim
player.walkBackSequence = def.walkbackanim
player.walkLeftSequence = def.walkleftanim
player.walkRightSequence = def.walkrightanim
player.readySequence = def.readyanim
player.turnLeftSequence = def.turnleftanim
player.turnRightSequence = def.turnrightanim
// npcs can't run
player.runSequence = def.walkanim
}
class Settings(
val npcId: Int = 7530
) : PluginSettings()
} | mit | 8ee15662cdcc344903c1de9dd38f0efa | 31.55814 | 73 | 0.694782 | 4.008596 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/base/code-insight/src/org/jetbrains/kotlin/idea/util/CommentSaver.kt | 1 | 20719 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.util
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.lexer.KtToken
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtFunctionLiteral
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.psiUtil.*
import java.util.*
import kotlin.properties.Delegates
class CommentSaver(originalElements: PsiChildRange, private val saveLineBreaks: Boolean = false/*TODO?*/) {
constructor(originalElement: PsiElement, saveLineBreaks: Boolean = false/*TODO?*/) : this(
PsiChildRange.singleElement(originalElement),
saveLineBreaks
)
private val SAVED_TREE_KEY = Key<TreeElement>("SAVED_TREE")
private val psiFactory = KtPsiFactory(originalElements.first!!.project)
private abstract class TreeElement {
companion object {
fun create(element: PsiElement): TreeElement? {
val tokenType = element.tokenType
return when {
element is PsiWhiteSpace -> if (element.textContains('\n')) LineBreakTreeElement() else null
element is PsiComment -> CommentTreeElement.create(element)
tokenType != null -> TokenTreeElement(tokenType)
else -> if (element.textLength > 0) StandardTreeElement() else null // don't save empty elements
}
}
}
var parent: TreeElement? = null
var prev: TreeElement? = null
var next: TreeElement? = null
var firstChild: TreeElement? = null
var lastChild: TreeElement? = null
val children: Sequence<TreeElement>
get() = generateSequence({ firstChild }, { it.next })
val reverseChildren: Sequence<TreeElement>
get() = generateSequence({ lastChild }, { it.prev })
val prevSiblings: Sequence<TreeElement>
get() = generateSequence({ prev }, { it.prev })
val nextSiblings: Sequence<TreeElement>
get() = generateSequence({ next }, { it.next })
val parents: Sequence<TreeElement>
get() = generateSequence({ parent }, { it.parent })
val parentsWithSelf: Sequence<TreeElement>
get() = generateSequence(this) { it.parent }
val firstLeafInside: TreeElement
get() {
var result = this
while (true) {
result = result.firstChild ?: break
}
return result
}
val lastLeafInside: TreeElement
get() {
var result = this
while (true) {
result = result.lastChild ?: break
}
return result
}
val prevLeaf: TreeElement?
get() {
return (prev ?: return parent?.prevLeaf).lastLeafInside
}
val nextLeaf: TreeElement?
get() {
return (next ?: return parent?.nextLeaf).firstLeafInside
}
val prevLeafs: Sequence<TreeElement>
get() = generateSequence({ prevLeaf }, { it.prevLeaf })
val nextLeafs: Sequence<TreeElement>
get() = generateSequence({ nextLeaf }, { it.nextLeaf })
fun withDescendants(leftToRight: Boolean): Sequence<TreeElement> {
val children = if (leftToRight) children else reverseChildren
return sequenceOf(this) + children.flatMap { it.withDescendants(leftToRight) }
}
val prevElements: Sequence<TreeElement>
get() = prevSiblings.flatMap { it.withDescendants(leftToRight = false) }
val nextElements: Sequence<TreeElement>
get() = nextSiblings.flatMap { it.withDescendants(leftToRight = true) }
// var debugText: String? = null
}
private class StandardTreeElement() : TreeElement()
private class TokenTreeElement(val tokenType: KtToken) : TreeElement()
private class LineBreakTreeElement() : TreeElement()
private class CommentTreeElement(
val commentText: String,
val spaceBefore: String,
val spaceAfter: String
) : TreeElement() {
companion object {
fun create(comment: PsiComment): CommentTreeElement {
val spaceBefore = (comment.prevLeaf(skipEmptyElements = true) as? PsiWhiteSpace)?.text ?: ""
val spaceAfter = (comment.nextLeaf(skipEmptyElements = true) as? PsiWhiteSpace)?.text ?: ""
return CommentTreeElement(comment.text, spaceBefore, spaceAfter)
}
}
}
private val commentsToRestore = ArrayList<CommentTreeElement>()
private val lineBreaksToRestore = ArrayList<LineBreakTreeElement>()
private var toNewPsiElementMap by Delegates.notNull<MutableMap<TreeElement, MutableCollection<PsiElement>>>()
private var needAdjustIndentAfterRestore = false
init {
if (saveLineBreaks || originalElements.any { it.anyDescendantOfType<PsiComment>() }) {
originalElements.save(null)
}
}
private fun PsiChildRange.save(parentTreeElement: TreeElement?) {
var first: TreeElement? = null
var last: TreeElement? = null
for (child in this) {
assert(child.savedTreeElement == null)
val savedChild = TreeElement.create(child) ?: continue
savedChild.parent = parentTreeElement
savedChild.prev = last
if (child !is PsiWhiteSpace) { // we don't try to anchor comments to whitespaces
child.savedTreeElement = savedChild
}
last?.next = savedChild
last = savedChild
if (first == null) {
first = savedChild
}
when (savedChild) {
is CommentTreeElement -> commentsToRestore.add(savedChild)
is LineBreakTreeElement -> if (saveLineBreaks) lineBreaksToRestore.add(savedChild)
}
child.allChildren.save(savedChild)
}
parentTreeElement?.firstChild = first
parentTreeElement?.lastChild = last
}
private var PsiElement.savedTreeElement: TreeElement?
get() = getCopyableUserData(SAVED_TREE_KEY)
set(value) = putCopyableUserData(SAVED_TREE_KEY, value)
private var isFinished = false
private set
private fun deleteCommentsInside(element: PsiElement) {
assert(!isFinished)
element.accept(object : PsiRecursiveElementVisitor() {
override fun visitComment(comment: PsiComment) {
val treeElement = comment.savedTreeElement
if (treeElement != null) {
commentsToRestore.remove(treeElement)
}
}
})
}
fun elementCreatedByText(createdElement: PsiElement, original: PsiElement, rangeInOriginal: TextRange) {
assert(!isFinished)
assert(createdElement.textLength == rangeInOriginal.length)
assert(createdElement.text == original.text.substring(rangeInOriginal.startOffset, rangeInOriginal.endOffset))
createdElement.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
if (element is PsiWhiteSpace) return
val token = original.findElementAt(element.getStartOffsetIn(createdElement) + rangeInOriginal.startOffset)
if (token != null) {
val elementLength = element.textLength
for (originalElement in token.parentsWithSelf) {
val length = originalElement.textLength
if (length < elementLength) continue
if (length == elementLength) {
element.savedTreeElement = originalElement.savedTreeElement
}
break
}
}
super.visitElement(element)
}
})
}
private fun putNewElementIntoMap(psiElement: PsiElement, treeElement: TreeElement) {
toNewPsiElementMap.getOrPut(treeElement) { ArrayList(1) }.add(psiElement)
}
private fun bindNewElement(newPsiElement: PsiElement, treeElement: TreeElement) {
newPsiElement.savedTreeElement = treeElement
putNewElementIntoMap(newPsiElement, treeElement)
}
fun restore(
resultElement: PsiElement,
isCommentBeneathSingleLine: Boolean,
isCommentInside: Boolean,
forceAdjustIndent: Boolean
) {
restore(PsiChildRange.singleElement(resultElement), forceAdjustIndent, isCommentBeneathSingleLine, isCommentInside)
}
fun restore(resultElement: PsiElement, forceAdjustIndent: Boolean = false) {
restore(PsiChildRange.singleElement(resultElement), forceAdjustIndent)
}
fun restore(
resultElements: PsiChildRange,
forceAdjustIndent: Boolean = false,
isCommentBeneathSingleLine: Boolean = false,
isCommentInside: Boolean = false
) {
assert(!isFinished)
assert(!resultElements.isEmpty)
if (commentsToRestore.isNotEmpty() || lineBreaksToRestore.isNotEmpty()) {
// remove comments that present inside resultElements from commentsToRestore
resultElements.forEach { deleteCommentsInside(it) }
if (commentsToRestore.isNotEmpty() || lineBreaksToRestore.isNotEmpty()) {
toNewPsiElementMap = HashMap<TreeElement, MutableCollection<PsiElement>>()
for (element in resultElements) {
element.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
val treeElement = element.savedTreeElement
if (treeElement != null) {
putNewElementIntoMap(element, treeElement)
}
super.visitElement(element)
}
})
}
restoreComments(resultElements, isCommentBeneathSingleLine, isCommentInside)
restoreLineBreaks()
// clear user data
resultElements.forEach {
it.accept(object : PsiRecursiveElementVisitor() {
override fun visitElement(element: PsiElement) {
element.savedTreeElement = null
super.visitElement(element)
}
})
}
}
}
if (needAdjustIndentAfterRestore || forceAdjustIndent) {
val file = resultElements.first().containingFile
val project = file.project
val psiDocumentManager = PsiDocumentManager.getInstance(project)
val document = psiDocumentManager.getDocument(file)
if (document != null) {
psiDocumentManager.doPostponedOperationsAndUnblockDocument(document)
psiDocumentManager.commitDocument(document)
}
CodeStyleManager.getInstance(project).adjustLineIndent(file, resultElements.textRange)
}
isFinished = true
}
private fun restoreComments(
resultElements: PsiChildRange,
isCommentBeneathSingleLine: Boolean = false,
isCommentInside: Boolean = false
) {
var putAbandonedCommentsAfter = resultElements.last!!
for (commentTreeElement in commentsToRestore) {
val comment = psiFactory.createComment(commentTreeElement.commentText)
val anchorBefore = findAnchor(commentTreeElement, before = true)
val anchorAfter = findAnchor(commentTreeElement, before = false)
val anchor = chooseAnchor(anchorBefore, anchorAfter)
val restored: PsiComment
if (anchor != null) {
val anchorElement = findFinalAnchorElement(anchor, comment)
val parent = anchorElement.parent
if (anchor.before) {
restored = parent.addAfter(comment, anchorElement) as PsiComment
if (commentTreeElement.spaceBefore.isNotEmpty()) {
parent.addAfter(psiFactory.createWhiteSpace(commentTreeElement.spaceBefore), anchorElement)
}
// make sure that there is a line break after EOL_COMMENT
if (restored.tokenType == KtTokens.EOL_COMMENT) {
val whiteSpace = restored.nextLeaf(skipEmptyElements = true) as? PsiWhiteSpace
if (whiteSpace == null) {
parent.addAfter(psiFactory.createWhiteSpace("\n"), restored)
} else if (!whiteSpace.textContains('\n')) {
val newWhiteSpace = psiFactory.createWhiteSpace("\n" + whiteSpace.text)
whiteSpace.replace(newWhiteSpace)
}
}
} else {
restored = parent.addBefore(comment, anchorElement) as PsiComment
if (commentTreeElement.spaceAfter.isNotEmpty()) {
parent.addBefore(psiFactory.createWhiteSpace(commentTreeElement.spaceAfter), anchorElement)
}
val functionLiteral = restored.parent as? KtFunctionLiteral
if (functionLiteral != null && commentTreeElement.spaceBefore.isNotEmpty()) {
functionLiteral.addBefore(psiFactory.createWhiteSpace(commentTreeElement.spaceBefore), restored)
}
}
} else {
restored = putAbandonedCommentsAfter.parent.addBefore(comment, putAbandonedCommentsAfter) as PsiComment
if (isCommentInside) {
val element = resultElements.first
val innerExpression = element?.lastChild?.getPrevSiblingIgnoringWhitespace()
innerExpression?.add(psiFactory.createWhiteSpace())
innerExpression?.add(restored)
restored.delete()
}
putAbandonedCommentsAfter = restored
}
// shift (possible contained) comment in expression underneath braces
if (isCommentBeneathSingleLine && resultElements.count() == 1) {
val element = resultElements.first
element?.add(psiFactory.createWhiteSpace("\n"))
element?.add(restored)
restored.delete()
}
bindNewElement(restored, commentTreeElement) // will be used when restoring line breaks
if (restored.tokenType == KtTokens.EOL_COMMENT) {
needAdjustIndentAfterRestore = true // TODO: do we really need it?
}
}
}
private fun restoreLineBreaks() {
for (lineBreakElement in lineBreaksToRestore) {
if (toNewPsiElementMap[lineBreakElement] != null) continue
val lineBreakParent = lineBreakElement.parent
fun findRestored(leaf: TreeElement): PsiElement? {
if (leaf is LineBreakTreeElement) return null
return leaf.parentsWithSelf
.takeWhile { it != lineBreakParent }
.mapNotNull { toNewPsiElementMap[it]?.first() } //TODO: what about multiple?
.firstOrNull()
}
val tokensToMatch = arrayListOf<KtToken>()
for (leaf in lineBreakElement.prevLeafs) {
var psiElement = findRestored(leaf)
if (psiElement != null) {
psiElement = skipTokensForward(psiElement, tokensToMatch.asReversed())
psiElement?.restoreLineBreakAfter()
break
} else {
if (leaf !is TokenTreeElement) break
tokensToMatch.add(leaf.tokenType)
}
}
}
}
private fun skipTokensForward(psiElement: PsiElement, tokensToMatch: List<KtToken>): PsiElement? {
var currentPsiElement = psiElement
for (token in tokensToMatch) {
currentPsiElement = currentPsiElement.nextLeaf(nonSpaceAndNonEmptyFilter) ?: return null
if (currentPsiElement.tokenType != token) return null
}
return currentPsiElement
}
private fun PsiElement.restoreLineBreakAfter() {
val addAfter = shiftNewLineAnchor(this).anchorToAddCommentOrSpace(before = false)
var whitespace = addAfter.nextSibling as? PsiWhiteSpace
//TODO: restore blank lines
if (whitespace != null && whitespace.text.contains('\n')) return // line break is already there
if (whitespace == null) {
addAfter.parent.addAfter(psiFactory.createNewLine(), addAfter)
} else {
whitespace.replace(psiFactory.createWhiteSpace("\n" + whitespace.text))
}
needAdjustIndentAfterRestore = true
}
private class Anchor(val element: PsiElement, val treeElementsBetween: Collection<TreeElement>, val before: Boolean)
private fun findAnchor(commentTreeElement: CommentTreeElement, before: Boolean): Anchor? {
val treeElementsBetween = ArrayList<TreeElement>()
val sequence = if (before) commentTreeElement.prevElements else commentTreeElement.nextElements
for (treeElement in sequence) {
val newPsiElements = toNewPsiElementMap[treeElement]
if (newPsiElements != null) {
val psiElement = newPsiElements.first().anchorToAddCommentOrSpace(!before) //TODO: should we restore multiple?
return Anchor(psiElement, treeElementsBetween, before)
}
if (treeElement.firstChild == null) { // we put only leafs into treeElementsBetween
treeElementsBetween.add(treeElement)
}
}
return null
}
private fun PsiElement.anchorToAddCommentOrSpace(before: Boolean): PsiElement {
return parentsWithSelf
.dropWhile { it.parent !is PsiFile && (if (before) it.prevSibling else it.nextSibling) == null }
.first()
}
private fun chooseAnchor(anchorBefore: Anchor?, anchorAfter: Anchor?): Anchor? {
if (anchorBefore == null) return anchorAfter
if (anchorAfter == null) return anchorBefore
val elementsBefore = anchorBefore.treeElementsBetween
val elementsAfter = anchorAfter.treeElementsBetween
val lineBreakBefore = elementsBefore.any { it is LineBreakTreeElement }
val lineBreakAfter = elementsAfter.any { it is LineBreakTreeElement }
if (lineBreakBefore && !lineBreakAfter) return anchorAfter
if (elementsBefore.isNotEmpty() && elementsAfter.isEmpty()) return anchorAfter
return anchorBefore //TODO: more analysis?
}
private fun findFinalAnchorElement(anchor: Anchor, comment: PsiComment): PsiElement {
val tokensBetween = anchor.treeElementsBetween.filterIsInstance<TokenTreeElement>()
fun PsiElement.next(): PsiElement? {
return if (anchor.before) nextLeaf(nonSpaceAndNonEmptyFilter) else prevLeaf(nonSpaceAndNonEmptyFilter)
}
var psiElement = anchor.element
for (token in tokensBetween.asReversed()) {
val next = psiElement.next() ?: break
if (next.tokenType != token.tokenType) break
psiElement = next
}
// don't put end of line comment right before comma
if (anchor.before && comment.tokenType == KtTokens.EOL_COMMENT) {
psiElement = shiftNewLineAnchor(psiElement)
}
return psiElement
}
// don't put line break right before comma
private fun shiftNewLineAnchor(putAfter: PsiElement): PsiElement {
val next = putAfter.nextLeaf(nonSpaceAndNonEmptyFilter)
return if (next?.tokenType == KtTokens.COMMA) next!! else putAfter
}
private val nonSpaceAndNonEmptyFilter = { element: PsiElement -> element !is PsiWhiteSpace && element.textLength > 0 }
companion object {
//TODO: making it private causes error on runtime (KT-7874?)
val PsiElement.tokenType: KtToken?
get() = node.elementType as? KtToken
}
} | apache-2.0 | 308a33c505e96a65fcae65c7d80924ab | 40.44 | 126 | 0.612337 | 5.872732 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/KotlinMoveDirectoryWithClassesHelper.kt | 1 | 5788 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.move.moveFilesOrDirectories
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesHelper
import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.Function
import com.intellij.util.containers.MultiMap
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded
import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix
import org.jetbrains.kotlin.idea.core.getPackage
import org.jetbrains.kotlin.idea.refactoring.invokeOnceOnCommandFinish
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsProcessor
import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.analyzeConflictsInFile
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtFile
class KotlinMoveDirectoryWithClassesHelper : MoveDirectoryWithClassesHelper() {
private data class FileUsagesWrapper(
val psiFile: KtFile,
val usages: List<UsageInfo>,
val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor?
) : UsageInfo(psiFile)
private class MoveContext(
val newParent: PsiDirectory,
val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor?
)
private val fileHandler = MoveKotlinFileHandler()
private var fileToMoveContext: MutableMap<PsiFile, MoveContext>? = null
private fun getOrCreateMoveContextMap(): MutableMap<PsiFile, MoveContext> {
return fileToMoveContext ?: HashMap<PsiFile, MoveContext>().apply {
fileToMoveContext = this
invokeOnceOnCommandFinish { fileToMoveContext = null }
}
}
override fun findUsages(
filesToMove: MutableCollection<out PsiFile>,
directoriesToMove: Array<out PsiDirectory>,
result: MutableCollection<in UsageInfo>,
searchInComments: Boolean,
searchInNonJavaFiles: Boolean,
project: Project
) {
filesToMove
.filterIsInstance<KtFile>()
.mapTo(result) { FileUsagesWrapper(it, fileHandler.findUsages(it, null, false), null) }
}
override fun preprocessUsages(
project: Project,
files: MutableSet<PsiFile>,
infos: Array<UsageInfo>,
directory: PsiDirectory?,
conflicts: MultiMap<PsiElement, String>
) {
val psiPackage = directory?.getPackage() ?: return
val moveTarget = KotlinDirectoryMoveTarget(FqName(psiPackage.qualifiedName), directory.virtualFile)
for ((index, usageInfo) in infos.withIndex()) {
if (usageInfo !is FileUsagesWrapper) continue
ProgressManager.getInstance().progressIndicator?.text2 = KotlinBundle.message("text.processing.file.0", usageInfo.psiFile.name)
runReadAction {
analyzeConflictsInFile(usageInfo.psiFile, usageInfo.usages, moveTarget, files, conflicts) {
infos[index] = usageInfo.copy(usages = it)
}
}
}
}
override fun beforeMove(psiFile: PsiFile) {
}
// Actual move logic is implemented in postProcessUsages since usages are not available here
override fun move(
file: PsiFile,
moveDestination: PsiDirectory,
oldToNewElementsMapping: MutableMap<PsiElement, PsiElement>,
movedFiles: MutableList<in PsiFile>,
listener: RefactoringElementListener?
): Boolean {
if (file !is KtFile) return false
val moveDeclarationsProcessor = fileHandler.initMoveProcessor(file, moveDestination, false)
val moveContextMap = getOrCreateMoveContextMap()
moveContextMap[file] = MoveContext(moveDestination, moveDeclarationsProcessor)
if (moveDeclarationsProcessor != null) {
moveDestination.getFqNameWithImplicitPrefix()?.quoteIfNeeded()?.let {
file.packageDirective?.fqName = it
}
}
return true
}
override fun afterMove(newElement: PsiElement) {
}
override fun postProcessUsages(usages: Array<out UsageInfo>, newDirMapper: Function<in PsiDirectory, out PsiDirectory>) {
val fileToMoveContext = fileToMoveContext ?: return
try {
val usagesToProcess = ArrayList<FileUsagesWrapper>()
usages
.filterIsInstance<FileUsagesWrapper>()
.forEach body@{
val file = it.psiFile
val moveContext = fileToMoveContext[file] ?: return@body
MoveFilesOrDirectoriesUtil.doMoveFile(file, moveContext.newParent)
val moveDeclarationsProcessor = moveContext.moveDeclarationsProcessor ?: return@body
val movedFile = moveContext.newParent.findFile(file.name) ?: return@body
usagesToProcess += FileUsagesWrapper(movedFile as KtFile, it.usages, moveDeclarationsProcessor)
}
usagesToProcess.forEach { fileHandler.retargetUsages(it.usages, it.moveDeclarationsProcessor!!) }
} finally {
this.fileToMoveContext = null
}
}
} | apache-2.0 | 5c428c12da7ded34b91cdb42a0d46e4a | 41.255474 | 158 | 0.716828 | 5.512381 | false | false | false | false |
JetBrains/intellij-community | plugins/github/src/org/jetbrains/plugins/github/api/GHGQLRequests.kt | 1 | 21623 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.api
import com.intellij.collaboration.api.data.GraphQLRequestPagination
import com.intellij.collaboration.api.dto.GraphQLConnectionDTO
import com.intellij.collaboration.api.dto.GraphQLCursorPageInfoDTO
import com.intellij.collaboration.api.dto.GraphQLNodesDTO
import com.intellij.collaboration.api.dto.GraphQLPagedResponseDataDTO
import com.intellij.diff.util.Side
import org.jetbrains.plugins.github.api.GithubApiRequest.Post.GQLQuery
import org.jetbrains.plugins.github.api.data.*
import org.jetbrains.plugins.github.api.data.graphql.query.GHGQLSearchQueryResponse
import org.jetbrains.plugins.github.api.data.pullrequest.*
import org.jetbrains.plugins.github.api.data.pullrequest.timeline.GHPRTimelineItem
import org.jetbrains.plugins.github.api.data.request.GHPullRequestDraftReviewComment
import org.jetbrains.plugins.github.api.data.request.GHPullRequestDraftReviewThread
import org.jetbrains.plugins.github.api.util.GHSchemaPreview
object GHGQLRequests {
object User {
fun find(server: GithubServerPath, login: String): GQLQuery<GHUser?> {
return GQLQuery.OptionalTraversedParsed(server.toGraphQLUrl(), GHGQLQueries.findUser,
mapOf("login" to login),
GHUser::class.java,
"user")
}
}
object Organization {
object Team {
fun findAll(server: GithubServerPath, organization: String,
pagination: GraphQLRequestPagination? = null): GQLQuery<GraphQLPagedResponseDataDTO<GHTeam>> {
return GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.findOrganizationTeams,
mapOf("organization" to organization,
"pageSize" to pagination?.pageSize,
"cursor" to pagination?.afterCursor),
TeamsConnection::class.java,
"organization", "teams")
}
fun findByUserLogins(server: GithubServerPath, organization: String, logins: List<String>,
pagination: GraphQLRequestPagination? = null): GQLQuery<GraphQLPagedResponseDataDTO<GHTeam>> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.findOrganizationTeams,
mapOf("organization" to organization,
"logins" to logins,
"pageSize" to pagination?.pageSize,
"cursor" to pagination?.afterCursor),
TeamsConnection::class.java,
"organization", "teams")
private class TeamsConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHTeam>)
: GraphQLConnectionDTO<GHTeam>(pageInfo, nodes)
}
}
object Repo {
fun find(repository: GHRepositoryCoordinates): GQLQuery<GHRepository?> {
return GQLQuery.OptionalTraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.findRepository,
mapOf("repoOwner" to repository.repositoryPath.owner,
"repoName" to repository.repositoryPath.repository),
GHRepository::class.java,
"repository")
}
fun getProtectionRules(repository: GHRepositoryCoordinates,
pagination: GraphQLRequestPagination? = null): GQLQuery<GraphQLPagedResponseDataDTO<GHBranchProtectionRule>> {
return GQLQuery.TraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.getProtectionRules,
mapOf("repoOwner" to repository.repositoryPath.owner,
"repoName" to repository.repositoryPath.repository,
"pageSize" to pagination?.pageSize,
"cursor" to pagination?.afterCursor),
ProtectedRulesConnection::class.java,
"repository", "branchProtectionRules")
}
private class ProtectedRulesConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHBranchProtectionRule>)
: GraphQLConnectionDTO<GHBranchProtectionRule>(pageInfo, nodes)
}
object Comment {
fun updateComment(server: GithubServerPath, commentId: String, newText: String): GQLQuery<GHComment> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.updateIssueComment,
mapOf("id" to commentId,
"body" to newText),
GHComment::class.java,
"updateIssueComment", "issueComment")
fun deleteComment(server: GithubServerPath, commentId: String): GQLQuery<Any?> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.deleteIssueComment,
mapOf("id" to commentId),
Any::class.java)
}
object PullRequest {
fun create(repository: GHRepositoryCoordinates,
repositoryId: String,
baseRefName: String,
headRefName: String,
title: String,
body: String? = null,
draft: Boolean? = false): GQLQuery<GHPullRequestShort> {
return GQLQuery.TraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.createPullRequest,
mapOf("repositoryId" to repositoryId,
"baseRefName" to baseRefName,
"headRefName" to headRefName,
"title" to title,
"body" to body,
"draft" to draft),
GHPullRequestShort::class.java,
"createPullRequest", "pullRequest").apply {
acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType
}
}
fun findOne(repository: GHRepositoryCoordinates, number: Long): GQLQuery<GHPullRequest?> {
return GQLQuery.OptionalTraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.findPullRequest,
mapOf("repoOwner" to repository.repositoryPath.owner,
"repoName" to repository.repositoryPath.repository,
"number" to number),
GHPullRequest::class.java,
"repository", "pullRequest").apply {
acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType
}
}
fun findByBranches(repository: GHRepositoryCoordinates, baseBranch: String, headBranch: String)
: GQLQuery<GraphQLPagedResponseDataDTO<GHPullRequest>> =
GQLQuery.TraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.findOpenPullRequestsByBranches,
mapOf("repoOwner" to repository.repositoryPath.owner,
"repoName" to repository.repositoryPath.repository,
"baseBranch" to baseBranch,
"headBranch" to headBranch),
PullRequestsConnection::class.java,
"repository", "pullRequests").apply {
acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType
}
private class PullRequestsConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPullRequest>)
: GraphQLConnectionDTO<GHPullRequest>(pageInfo, nodes)
fun update(repository: GHRepositoryCoordinates, pullRequestId: String, title: String?, description: String?): GQLQuery<GHPullRequest> {
val parameters = mutableMapOf<String, Any>("pullRequestId" to pullRequestId)
if (title != null) parameters["title"] = title
if (description != null) parameters["body"] = description
return GQLQuery.TraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.updatePullRequest, parameters,
GHPullRequest::class.java,
"updatePullRequest", "pullRequest").apply {
acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType
}
}
fun markReadyForReview(repository: GHRepositoryCoordinates, pullRequestId: String): GQLQuery<Any?> =
GQLQuery.Parsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.markPullRequestReadyForReview,
mutableMapOf<String, Any>("pullRequestId" to pullRequestId),
Any::class.java).apply {
acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType
}
fun mergeabilityData(repository: GHRepositoryCoordinates, number: Long): GQLQuery<GHPullRequestMergeabilityData?> =
GQLQuery.OptionalTraversedParsed(repository.serverPath.toGraphQLUrl(), GHGQLQueries.pullRequestMergeabilityData,
mapOf("repoOwner" to repository.repositoryPath.owner,
"repoName" to repository.repositoryPath.repository,
"number" to number),
GHPullRequestMergeabilityData::class.java,
"repository", "pullRequest").apply {
acceptMimeType = "${GHSchemaPreview.CHECKS.mimeType},${GHSchemaPreview.PR_MERGE_INFO.mimeType}"
}
fun search(server: GithubServerPath, query: String, pagination: GraphQLRequestPagination? = null)
: GQLQuery<GHGQLSearchQueryResponse<GHPullRequestShort>> {
return GQLQuery.Parsed(server.toGraphQLUrl(), GHGQLQueries.issueSearch,
mapOf("query" to query,
"pageSize" to pagination?.pageSize,
"cursor" to pagination?.afterCursor),
PRSearch::class.java).apply {
acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType
}
}
private class PRSearch(search: SearchConnection<GHPullRequestShort>)
: GHGQLSearchQueryResponse<GHPullRequestShort>(search)
fun reviewThreads(
repository: GHRepositoryCoordinates,
number: Long,
pagination: GraphQLRequestPagination? = null
): GQLQuery<GraphQLPagedResponseDataDTO<GHPullRequestReviewThread>> =
GQLQuery.TraversedParsed(
repository.serverPath.toGraphQLUrl(), GHGQLQueries.pullRequestReviewThreads,
parameters(repository, number, pagination),
ThreadsConnection::class.java, "repository", "pullRequest", "reviewThreads"
)
private class ThreadsConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPullRequestReviewThread>)
: GraphQLConnectionDTO<GHPullRequestReviewThread>(pageInfo, nodes)
fun commits(
repository: GHRepositoryCoordinates,
number: Long,
pagination: GraphQLRequestPagination? = null
): GQLQuery<GraphQLPagedResponseDataDTO<GHPullRequestCommit>> =
GQLQuery.TraversedParsed(
repository.serverPath.toGraphQLUrl(), GHGQLQueries.pullRequestCommits,
parameters(repository, number, pagination),
CommitsConnection::class.java, "repository", "pullRequest", "commits"
)
private class CommitsConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPullRequestCommit>)
: GraphQLConnectionDTO<GHPullRequestCommit>(pageInfo, nodes)
fun files(
repository: GHRepositoryCoordinates,
number: Long,
pagination: GraphQLRequestPagination
): GQLQuery<GraphQLPagedResponseDataDTO<GHPullRequestChangedFile>> =
GQLQuery.TraversedParsed(
repository.serverPath.toGraphQLUrl(), GHGQLQueries.pullRequestFiles,
parameters(repository, number, pagination),
FilesConnection::class.java, "repository", "pullRequest", "files"
)
private class FilesConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPullRequestChangedFile>) :
GraphQLConnectionDTO<GHPullRequestChangedFile>(pageInfo, nodes)
fun markFileAsViewed(server: GithubServerPath, pullRequestId: String, path: String): GQLQuery<Unit> =
GQLQuery.TraversedParsed(
server.toGraphQLUrl(), GHGQLQueries.markFileAsViewed,
mapOf("pullRequestId" to pullRequestId, "path" to path),
Unit::class.java
)
fun unmarkFileAsViewed(server: GithubServerPath, pullRequestId: String, path: String): GQLQuery<Unit> =
GQLQuery.TraversedParsed(
server.toGraphQLUrl(), GHGQLQueries.unmarkFileAsViewed,
mapOf("pullRequestId" to pullRequestId, "path" to path),
Unit::class.java
)
object Timeline {
fun items(server: GithubServerPath, repoOwner: String, repoName: String, number: Long,
pagination: GraphQLRequestPagination? = null)
: GQLQuery<GraphQLPagedResponseDataDTO<GHPRTimelineItem>> {
return GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.pullRequestTimeline,
mapOf("repoOwner" to repoOwner,
"repoName" to repoName,
"number" to number,
"pageSize" to pagination?.pageSize,
"cursor" to pagination?.afterCursor,
"since" to pagination?.since),
TimelineConnection::class.java,
"repository", "pullRequest", "timelineItems").apply {
acceptMimeType = GHSchemaPreview.PR_DRAFT.mimeType
}
}
private class TimelineConnection(pageInfo: GraphQLCursorPageInfoDTO, nodes: List<GHPRTimelineItem>)
: GraphQLConnectionDTO<GHPRTimelineItem>(pageInfo, nodes)
}
object Review {
fun create(server: GithubServerPath, pullRequestId: String,
event: GHPullRequestReviewEvent?, body: String?, commitSha: String?,
comments: List<GHPullRequestDraftReviewComment>?,
threads: List<GHPullRequestDraftReviewThread>?): GQLQuery<GHPullRequestPendingReview> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.createReview,
mapOf("pullRequestId" to pullRequestId,
"event" to event,
"commitOid" to commitSha,
"comments" to comments,
"threads" to threads,
"body" to body),
GHPullRequestPendingReview::class.java,
"addPullRequestReview", "pullRequestReview")
fun submit(server: GithubServerPath, reviewId: String, event: GHPullRequestReviewEvent, body: String?): GQLQuery<Any> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.submitReview,
mapOf("reviewId" to reviewId,
"event" to event,
"body" to body),
Any::class.java)
fun updateBody(server: GithubServerPath, reviewId: String, newText: String): GQLQuery<GHPullRequestReview> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.updateReview,
mapOf("reviewId" to reviewId,
"body" to newText),
GHPullRequestReview::class.java,
"updatePullRequestReview", "pullRequestReview")
fun delete(server: GithubServerPath, reviewId: String): GQLQuery<Any> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.deleteReview,
mapOf("reviewId" to reviewId),
Any::class.java)
fun pendingReviews(server: GithubServerPath, pullRequestId: String): GQLQuery<GraphQLNodesDTO<GHPullRequestPendingReview>> {
return GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.pendingReview,
mapOf("pullRequestId" to pullRequestId),
PendingReviewNodes::class.java,
"node", "reviews")
}
private class PendingReviewNodes(nodes: List<GHPullRequestPendingReview>) :
GraphQLNodesDTO<GHPullRequestPendingReview>(nodes)
fun addComment(server: GithubServerPath,
reviewId: String,
body: String, commitSha: String, fileName: String, diffLine: Int)
: GQLQuery<GHPullRequestReviewCommentWithPendingReview> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.addReviewComment,
mapOf("reviewId" to reviewId,
"body" to body,
"commit" to commitSha,
"file" to fileName,
"position" to diffLine),
GHPullRequestReviewCommentWithPendingReview::class.java,
"addPullRequestReviewComment", "comment")
fun addComment(server: GithubServerPath,
reviewId: String,
inReplyTo: String,
body: String)
: GQLQuery<GHPullRequestReviewCommentWithPendingReview> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.addReviewComment,
mapOf("reviewId" to reviewId,
"inReplyTo" to inReplyTo,
"body" to body),
GHPullRequestReviewCommentWithPendingReview::class.java,
"addPullRequestReviewComment", "comment")
fun deleteComment(server: GithubServerPath, commentId: String): GQLQuery<GHPullRequestPendingReview> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.deleteReviewComment,
mapOf("id" to commentId),
GHPullRequestPendingReview::class.java,
"deletePullRequestReviewComment", "pullRequestReview")
fun updateComment(server: GithubServerPath, commentId: String, newText: String): GQLQuery<GHPullRequestReviewComment> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.updateReviewComment,
mapOf("id" to commentId,
"body" to newText),
GHPullRequestReviewComment::class.java,
"updatePullRequestReviewComment", "pullRequestReviewComment")
fun addThread(server: GithubServerPath, reviewId: String,
body: String, line: Int, side: Side, startLine: Int, fileName: String): GQLQuery<GHPullRequestReviewThread> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.addPullRequestReviewThread,
mapOf("body" to body,
"line" to line,
"path" to fileName,
"pullRequestReviewId" to reviewId,
"side" to side.name,
"startSide" to side.name,
"startLine" to startLine),
GHPullRequestReviewThread::class.java,
"addPullRequestReviewThread", "thread")
fun resolveThread(server: GithubServerPath, threadId: String): GQLQuery<GHPullRequestReviewThread> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.resolveReviewThread,
mapOf("threadId" to threadId),
GHPullRequestReviewThread::class.java,
"resolveReviewThread", "thread")
fun unresolveThread(server: GithubServerPath, threadId: String): GQLQuery<GHPullRequestReviewThread> =
GQLQuery.TraversedParsed(server.toGraphQLUrl(), GHGQLQueries.unresolveReviewThread,
mapOf("threadId" to threadId),
GHPullRequestReviewThread::class.java,
"unresolveReviewThread", "thread")
}
}
}
private fun parameters(
repository: GHRepositoryCoordinates,
pullRequestNumber: Long,
pagination: GraphQLRequestPagination?
): Map<String, Any?> =
mapOf(
"repoOwner" to repository.repositoryPath.owner,
"repoName" to repository.repositoryPath.repository,
"number" to pullRequestNumber,
"pageSize" to pagination?.pageSize,
"cursor" to pagination?.afterCursor
) | apache-2.0 | 7e23cbd33fe9608601cb28e083e14a2d | 54.875969 | 158 | 0.590297 | 6.532628 | false | false | false | false |
StepicOrg/stepik-android | app/src/main/java/org/stepik/android/presentation/course_list/mapper/CourseListQueryStateMapper.kt | 1 | 2055 | package org.stepik.android.presentation.course_list.mapper
import ru.nobird.app.core.model.PagedList
import org.stepik.android.domain.base.DataSourceType
import org.stepik.android.domain.course.model.SourceTypeComposition
import org.stepik.android.domain.course_list.model.CourseListItem
import org.stepik.android.domain.course_list.model.CourseListQuery
import org.stepik.android.presentation.course_list.CourseListQueryView
import org.stepik.android.presentation.course_list.CourseListView
import ru.nobird.app.core.model.safeCast
import javax.inject.Inject
class CourseListQueryStateMapper
@Inject
constructor() {
fun mapToCourseListLoadedSuccess(query: CourseListQuery, items: PagedList<CourseListItem.Data>, source: SourceTypeComposition): CourseListQueryView.State.Data =
CourseListQueryView.State.Data(
query,
courseListViewState =
if (items.isNotEmpty()) {
CourseListView.State.Content(
courseListDataItems = items,
courseListItems = items
)
} else {
CourseListView.State.Empty
},
source.generalSourceType
)
/**
* Если мы находились в кеше, то при скролле до следующей страницы мы добавили фейковый [CourseListItem.PlaceHolder] в конец
* Теперь, когда мы скачали страницу из сети мы можем проверить на наличие фейкового итема и скачать вторую страницу
*/
fun isNeedLoadNextPage(state: CourseListQueryView.State): Boolean {
state as CourseListQueryView.State.Data
val lastItem = state.courseListViewState
.safeCast<CourseListView.State.Content>()
?.courseListItems
?.lastOrNull()
return state.sourceType == DataSourceType.CACHE && lastItem is CourseListItem.PlaceHolder
}
} | apache-2.0 | 28f8a3309b5293a3a00932cc72e94793 | 40.888889 | 164 | 0.699575 | 4.583942 | false | false | false | false |
exercism/xkotlin | exercises/practice/bob/.meta/src/reference/kotlin/Bob.kt | 1 | 889 | object Bob {
fun hey(input: String): String {
val trimmedInput = input.trim()
return when {
isSilence(trimmedInput) -> "Fine. Be that way!"
isShoutedQuestion(trimmedInput) -> "Calm down, I know what I'm doing!"
isShout(trimmedInput) -> "Whoa, chill out!"
isQuestion(trimmedInput) -> "Sure."
else -> "Whatever."
}
}
private fun isSilence(input: String) = input.isBlank()
private fun isQuestion(input: String) = input.endsWith("?")
private fun isShout(input: String): Boolean {
val isOnlyUppercase = input == input.uppercase()
val hasLetter = input.contains(Regex("[A-Z]"))
return hasLetter && isOnlyUppercase
}
private fun isShoutedQuestion(input: String) = isShout(input) && isQuestion(input)
}
| mit | bb5f4856ee9f5e207836487e33829c27 | 33.192308 | 86 | 0.570304 | 4.336585 | false | false | false | false |
BartoszJarocki/Design-patterns-in-Kotlin | src/behavioral/Observer.kt | 1 | 2399 | package behavioral
import kotlin.properties.ObservableProperty
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
/**
* Returns a property delegate for a read/write property that calls a specified callback function when changed.
* @param initialValue the initial value of the property.
* @param beforeChange the callback which is called before the change of the property.
* @param afterChange the callback which is called after the change of the property is made. The value of the property
* has already been changed when this callback is invoked.
*/
inline fun <T> observable(initialValue: T,
crossinline beforeChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Boolean,
crossinline afterChange: (property: KProperty<*>, oldValue: T, newValue: T) -> Unit): ReadWriteProperty<Any?, T> = object : ObservableProperty<T>(initialValue) {
override fun afterChange(property: KProperty<*>, oldValue: T, newValue: T) = afterChange(property, oldValue, newValue)
override fun beforeChange(property: KProperty<*>, oldValue: T, newValue: T) = beforeChange(property, oldValue, newValue)
}
interface PropertyObserver {
fun willChange(propertyName: String, newPropertyValue: Any?)
fun didChange(propertyName: String, oldPropertyValue: Any?)
}
class Observer : PropertyObserver {
override fun willChange(propertyName: String, newPropertyValue: Any?) {
if (newPropertyValue is String && newPropertyValue == "test") {
println("Okay. Look. We both said a lot of things that you're going to regret.")
}
}
override fun didChange(propertyName: String, oldPropertyValue: Any?) {
if (oldPropertyValue is String && oldPropertyValue == "<no name>") {
println("Sorry about the mess. I've really let the place go since you killed me.")
}
}
}
class User(val propertyObserver: PropertyObserver?) {
var name: String by observable("<no name>", { prop, old, new ->
println("Before change: $old -> $new")
propertyObserver?.willChange(name, new)
return@observable true
}, { prop, old, new ->
propertyObserver?.didChange(name, old)
println("After change: $old -> $new")
})
}
fun main(args: Array<String>) {
val observer = Observer()
val user = User(observer)
user.name = "test"
} | apache-2.0 | ca4d7d20f3028a5c8fb91ef6cb5b1656 | 40.37931 | 187 | 0.690288 | 4.543561 | false | false | false | false |
allotria/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/FeatureUsageData.kt | 2 | 11669 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.eventLog
import com.intellij.codeWithMe.ClientId
import com.intellij.internal.statistic.collectors.fus.ActionPlaceHolder
import com.intellij.internal.statistic.eventLog.StatisticsEventEscaper.escapeFieldName
import com.intellij.internal.statistic.utils.PluginInfo
import com.intellij.internal.statistic.utils.StatisticsUtil
import com.intellij.internal.statistic.utils.addPluginInfoTo
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.lang.Language
import com.intellij.openapi.actionSystem.ActionPlaces
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Version
import com.intellij.openapi.util.text.StringUtil
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.annotations.NonNls
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import java.util.*
private val LOG = logger<FeatureUsageData>()
/**
* <p>FeatureUsageData represents additional data for reported event.</p>
*
* <h3>Example</h3>
*
* <p>My usage collector collects actions invocations. <i>"my.foo.action"</i> could be invoked from one of the following contexts:
* "main.menu", "context.menu", "my.dialog", "all-actions-run".</p>
*
* <p>If I write {@code FUCounterUsageLogger.logEvent("my.foo.action", "bar")}, I'll know how many times the action "bar" was invoked (e.g. 239)</p>
*
* <p>If I write {@code FUCounterUsageLogger.logEvent("my.foo.action", "bar", new FeatureUsageData().addPlace(place))}, I'll get the same
* total count of action invocations (239), but I'll also know that the action was called 3 times from "main.menu", 235 times from "my.dialog" and only once from "context.menu".
* <br/>
* </p>
*/
@ApiStatus.Internal
class FeatureUsageData(private val recorderId: String) {
constructor() : this("FUS")
private var data: MutableMap<String, Any> = HashMap()
init {
val clientId = ClientId.currentOrNull
if (clientId != null && clientId != ClientId.defaultLocalId) {
addClientId(clientId.value)
}
}
companion object {
// don't list "version" as "platformDataKeys" because it format depends a lot on the tool
val platformDataKeys: List<String> = listOf("plugin", "project", "os", "plugin_type", "lang", "current_file", "input_event", "place",
"file_path", "anonymous_id", "client_id")
}
fun addClientId(clientId: String?): FeatureUsageData {
clientId?.let {
val permanentClientId = parsePermanentClientId(clientId)
data["client_id"] = EventLogConfiguration.getOrCreate(recorderId).anonymize(permanentClientId)
}
return this
}
private fun parsePermanentClientId(clientId: String): String {
val separator = clientId.indexOf('-')
if (separator > 0) {
return clientId.substring(0, separator)
}
return clientId
}
/**
* Project data is added automatically for project state collectors and project-wide counter events.
*
* @see com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
* @see com.intellij.internal.statistic.eventLog.events.EventId.log(Project)
*/
fun addProject(project: Project?): FeatureUsageData {
if (project != null) {
data["project"] = StatisticsUtil.getProjectId(project, recorderId)
}
return this
}
fun addVersionByString(@NonNls version: String?): FeatureUsageData {
if (version == null) {
data["version"] = "unknown"
}
else {
addVersion(Version.parseVersion(version))
}
return this
}
fun addVersion(@NonNls version: Version?): FeatureUsageData {
data["version"] = if (version != null) "${version.major}.${version.minor}" else "unknown.format"
return this
}
fun addPluginInfo(info: PluginInfo?): FeatureUsageData {
info?.let {
addPluginInfoTo(info, data)
}
return this
}
fun addLanguage(@NonNls id: String?): FeatureUsageData {
id?.let {
addLanguage(Language.findLanguageByID(id))
}
return this
}
fun addLanguage(language: Language?): FeatureUsageData {
return addLanguageInternal("lang", language)
}
fun addCurrentFile(language: Language?): FeatureUsageData {
return addLanguageInternal("current_file", language)
}
private fun addLanguageInternal(fieldName: String, language: Language?): FeatureUsageData {
language?.let {
val type = getPluginInfo(language.javaClass)
if (type.isSafeToReport()) {
data[fieldName] = language.id
}
else {
data[fieldName] = "third.party"
}
}
return this
}
fun addInputEvent(event: InputEvent?, @NonNls place: String?): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getInputEventText(event, place)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addInputEvent(event: AnActionEvent?): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getActionEventText(event)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addInputEvent(event: KeyEvent): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getKeyEventText(event)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addInputEvent(event: MouseEvent): FeatureUsageData {
val inputEvent = ShortcutDataProvider.getMouseEventText(event)
if (inputEvent != null && StringUtil.isNotEmpty(inputEvent)) {
data["input_event"] = inputEvent
}
return this
}
fun addPlace(@NonNls place: String?): FeatureUsageData {
if (place == null) return this
var reported = ActionPlaces.UNKNOWN
if (isCommonPlace(place) || ActionPlaceHolder.isCustomActionPlace(place)) {
reported = place
}
else if (ActionPlaces.isPopupPlace(place)) {
reported = ActionPlaces.POPUP
}
data["place"] = reported
return this
}
private fun isCommonPlace(place: String): Boolean {
return ActionPlaces.isCommonPlace(place) || ActionPlaces.TOOLWINDOW_POPUP == place
}
fun addAnonymizedPath(@NonNls path: String?): FeatureUsageData {
data["file_path"] = path?.let { EventLogConfiguration.getOrCreate(recorderId).anonymize(path) } ?: "undefined"
return this
}
fun addAnonymizedId(@NonNls id: String): FeatureUsageData {
data["anonymous_id"] = EventLogConfiguration.getOrCreate(recorderId).anonymize(id)
return this
}
fun addAnonymizedValue(@NonNls key: String, @NonNls value: String?): FeatureUsageData {
data[key] = value?.let { EventLogConfiguration.getOrCreate(recorderId).anonymize(value) } ?: "undefined"
return this
}
fun addValue(value: Any): FeatureUsageData {
if (value is String || value is Boolean || value is Int || value is Long || value is Float || value is Double) {
return addDataInternal("value", value)
}
return addData("value", value.toString())
}
fun addEnabled(enabled: Boolean): FeatureUsageData {
return addData("enabled", enabled)
}
fun addCount(count: Int): FeatureUsageData {
return addData("count", count)
}
/**
* @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
*/
fun addData(@NonNls key: String, value: Boolean): FeatureUsageData {
return addDataInternal(key, value)
}
/**
* @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
*/
fun addData(@NonNls key: String, value: Int): FeatureUsageData {
return addDataInternal(key, value)
}
/**
* @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
*/
fun addData(@NonNls key: String, value: Long): FeatureUsageData {
return addDataInternal(key, value)
}
/**
* @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
*/
fun addData(@NonNls key: String, value: Float): FeatureUsageData {
return addDataInternal(key, value)
}
/**
* @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
*/
fun addData(@NonNls key: String, value: Double): FeatureUsageData {
return addDataInternal(key, value)
}
/**
* @param key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
* @param value can contain "-", "_", ".", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
*/
fun addData(@NonNls key: String, @NonNls value: String): FeatureUsageData {
return addDataInternal(key, value)
}
/**
* The data reported by this method will be available ONLY for ad-hoc analysis.
*
* @param key key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
*/
fun addData(@NonNls key: String, value: List<String>): FeatureUsageData {
return addDataInternal(key, value)
}
/**
* The data reported by this method will be available ONLY for ad-hoc analysis.
*
* @param key key can contain "-", "_", latin letters or digits. All not allowed symbols will be replaced with "_" or "?".
*/
internal fun addListLongData(@NonNls key: String, value: List<Long>): FeatureUsageData {
return addDataInternal(key, value)
}
internal fun addObjectData(@NonNls key: String, value: Map<String, Any>): FeatureUsageData {
return addDataInternal(key, value)
}
internal fun addListObjectData(@NonNls key: String, value: List<Map<String, Any>>): FeatureUsageData {
return addDataInternal(key, value)
}
private fun addDataInternal(key: String, value: Any): FeatureUsageData {
if (!ApplicationManager.getApplication().isUnitTestMode && platformDataKeys.contains(key)) {
LOG.warn("Collectors should not reuse platform keys: $key")
return this
}
val escapedKey = escapeFieldName(key)
if (escapedKey != key) {
LOG.warn("Key contains invalid symbols, they will be escaped: '$key' -> '$escapedKey'")
}
data[escapedKey] = value
return this
}
fun build(): Map<String, Any> {
if (data.isEmpty()) {
return Collections.emptyMap()
}
return data
}
fun addAll(from: FeatureUsageData) : FeatureUsageData{
data.putAll(from.data)
return this
}
fun merge(next: FeatureUsageData, @NonNls prefix: String): FeatureUsageData {
for ((key, value) in next.build()) {
val newKey = if (key.startsWith("data_")) "$prefix$key" else key
data[newKey] = value
}
return this
}
fun copy(): FeatureUsageData {
val result = FeatureUsageData()
for ((key, value) in data) {
result.data[key] = value
}
return result
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as FeatureUsageData
if (data != other.data) return false
return true
}
override fun hashCode(): Int {
return data.hashCode()
}
override fun toString(): String {
return data.toString()
}
} | apache-2.0 | 6732ab071b9ddb348cdc36ad51cb2c06 | 32.342857 | 177 | 0.689605 | 4.385194 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/lang/java/JavaSearch.kt | 1 | 2755 | package com.aemtools.lang.java
import com.aemtools.common.constant.const.java.POJO_USE
import com.aemtools.common.constant.const.java.USE_INTERFACE
import com.aemtools.common.constant.const.java.WCM_USE_CLASS
import com.aemtools.service.IJavaSearchService
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.project.Project
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiClass
import com.intellij.psi.search.searches.AnnotatedElementsSearch
import com.intellij.psi.search.searches.ClassInheritorsSearch
/**
* Utility object for java search.
*
* @author Dmytro Troynikov
*/
object JavaSearch {
val USE_CLASSES = listOf(USE_INTERFACE, WCM_USE_CLASS, POJO_USE)
/**
* Search for [PsiClass] by qualified name with predefined "allScope".
*
* Shortcut for [JavaPsiFacade.findClass]
* @param qualifiedName the full qualified name of class
* @param project the project
* @see JavaPsiFacade
* @return [PsiClass] instance, __null__ if no instance was found
*/
fun findClass(qualifiedName: String, project: Project)
: PsiClass? =
service()
?.findClass(qualifiedName, project)
/**
* Search for inheritors of given [PsiClass].
*
* Shortcut for [ClassInheritorsSearch.search]
* @see ClassInheritorsSearch
* @param psiClass the base class
* @param project the project
* @return list of inheritors of given class
*/
fun findInheritors(psiClass: PsiClass, project: Project): List<PsiClass> =
service()
?.findInheritors(psiClass, project)
?: emptyList()
/**
* Search classes annotated by given annotation.
*
* Shortcut for [AnnotatedElementsSearch.searchPsiClasses]
* @see AnnotatedElementsSearch
* @param annotation the type of annotation
* @param project the project
* @return list of annotated classes
*/
fun findAnnotatedClasses(annotation: PsiClass, project: Project): List<PsiClass> =
service()
?.findAnnotatedClasses(annotation, project)
?: emptyList()
/**
* Find all sling models in the project.
* @param project the project
* @return list of sling models
*/
fun findSlingModels(project: Project): List<PsiClass> =
service()
?.findSlingModels(project)
?: emptyList()
/**
* Find all __io.sightly.java.api.Use__ and __com.adobe.cq.sightly.WCMUse__
* inheritors in given project.
* @param project the project
* @return list of inheritors
*/
fun findWcmUseClasses(project: Project): List<PsiClass> =
service()
?.findWcmUseClasses(project)
?: emptyList()
private fun service(): IJavaSearchService? = ServiceManager.getService(IJavaSearchService::class.java)
}
| gpl-3.0 | 25df422fbe14014c60291a128e8578f8 | 30.306818 | 104 | 0.705263 | 4.331761 | false | false | false | false |
ParaskP7/sample-code-posts-kotlin | app/src/main/java/io/petros/posts/kotlin/model/Post.kt | 1 | 589 | package io.petros.posts.kotlin.model
import android.arch.persistence.room.*
@Entity(tableName = "post",
foreignKeys = arrayOf(
ForeignKey(entity = User::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("user_id"),
onDelete = ForeignKey.CASCADE)),
indices = arrayOf(Index(value = "user_id")))
data class Post(@PrimaryKey val id: String,
@ColumnInfo(name = "user_id") val userId: String,
val title: String,
val body: String)
| apache-2.0 | 807018374bb947616eda0e336affe152 | 38.266667 | 65 | 0.548387 | 4.827869 | false | false | false | false |
code-helix/slatekit | src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/SampleApi.kt | 1 | 2041 | package test.setup
import slatekit.apis.*
import slatekit.apis.AuthModes
import slatekit.apis.Verbs
import slatekit.apis.ApiBase
import slatekit.context.Context
import slatekit.common.Sources
import slatekit.connectors.entities.AppEntContext
@Api(area = "app", name = "tests", desc = "sample to test features of Slate Kit APIs",
auth = AuthModes.TOKEN, roles= ["admin"], verb = Verbs.AUTO, sources = [Sources.ALL])
class SampleApi(context: AppEntContext): ApiBase(context) {
@Action(desc = "accepts supplied basic data types from send")
fun defaultAnnotationValues(string1: String): String {
return "$string1"
}
@Action(desc = "test partial override", auth = AuthModes.KEYED, roles= ["user"])
fun overridePartial(string1: String): String {
return "$string1"
}
@Action(desc = "test overrides", auth = AuthModes.KEYED, roles= ["user"], sources = [Sources.CLI], access = AccessLevel.INTERNAL)
fun overrideFull(string1: String): String {
return "$string1"
}
}
@Api(area = "app", name = "tests", desc = "sample to test features of Slate Kit APIs", roles= ["admin"])
class SampleApi1(val context: Context) {
@Action(desc = "test simple action with inputs")
@Documented(path = "docs/apis", key = "actions.tests.repeat")
fun repeat(word: String, count:Int): String {
return (0 until count).map { word }.joinToString(" ")
}
}
@Api(area = "app", name = "tests", desc = "sample to test features of Slate Kit APIs", roles= ["admin"],
auth = AuthModes.TOKEN, verb = Verbs.AUTO, access = AccessLevel.PUBLIC, sources = [Sources.ALL])
class SampleApi2(val context: Context) {
@Action(desc = "test simple action with inputs")
@Input(name = "word" , desc = "word to return back", required = true, examples = ["hello"])
@Input(name = "count", desc = "number of times to repeat", required = true, examples = ["3"])
fun repeat(word: String, count:Int): String {
return (0 until count).map { word }.joinToString(" ")
}
}
| apache-2.0 | 632eddd35a8599fff40f3c15e41bb9dc | 33.016667 | 133 | 0.66732 | 3.77963 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/classes/extensionOnNamedClassObject.kt | 5 | 191 | class C() {
companion object Foo
}
fun C.Foo.create() = 3
fun box(): String {
val c1 = C.Foo.create()
val c2 = C.create()
return if (c1 == 3 && c2 == 3) "OK" else "fail"
}
| apache-2.0 | 93057fcbf9c2addefca3b75184135e34 | 14.916667 | 51 | 0.528796 | 2.652778 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/when/switchOptimizationStatement.kt | 2 | 608 | // WITH_RUNTIME
fun exhaustive(x: Int): Int {
var r: Int
when (x) {
1 -> r = 1
2 -> r = 2
3 -> r = 3
else -> r = 4
}
return r
}
fun nonExhaustive(x: Int): Int {
var r: Int = 4
when (x) {
1 -> r = 1
2 -> r = 2
3 -> r = 3
}
return r
}
fun box(): String {
var result = (0..3).map(::exhaustive).joinToString()
if (result != "4, 1, 2, 3") return "exhaustive:" + result
result = (0..3).map(::nonExhaustive).joinToString()
if (result != "4, 1, 2, 3") return "non-exhaustive:" + result
return "OK"
}
| apache-2.0 | 962af56ac109c5222db3a63a544dc252 | 16.371429 | 65 | 0.460526 | 3.150259 | false | false | false | false |
AndroidX/androidx | compose/runtime/runtime/src/commonTest/kotlin/androidx/compose/runtime/collection/MutableVectorTest.kt | 3 | 26825 | /*
* 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.runtime.collection
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertFalse
import kotlin.test.assertNull
import kotlin.test.assertTrue
class MutableVectorTest {
val list: MutableVector<Int> = mutableVectorOf(1, 2, 3, 4, 5)
@Test
fun emptyConstruction() {
val l = mutableVectorOf<String>()
assertEquals(0, l.size)
assertEquals(16, l.content.size)
repeat(16) {
assertNull(l.content[it])
}
}
@Test
fun sizeConstruction() {
val l = MutableVector<String>(4)
assertEquals(4, l.content.size)
repeat(4) {
assertNull(l.content[it])
}
}
@Test
fun contentConstruction() {
val l = mutableVectorOf("a", "b", "c")
assertEquals(3, l.size)
assertEquals("a", l[0])
assertEquals("b", l[1])
assertEquals("c", l[2])
assertEquals(3, l.content.size)
repeat(2) {
val l2 = mutableVectorOf(1, 2, 3, 4, 5)
assertTrue(list.contentEquals(l2))
l2.removeAt(0)
}
}
@Test
fun initConstruction() {
val l = MutableVector(5) { it + 1 }
assertTrue(l.contentEquals(list))
}
@Test
fun get() {
assertEquals(1, list[0])
assertEquals(5, list[4])
}
@Test
fun isEmpty() {
assertFalse(list.isEmpty())
assertTrue(mutableVectorOf<String>().isEmpty())
}
@Test
fun isNotEmpty() {
assertTrue(list.isNotEmpty())
assertFalse(mutableVectorOf<String>().isNotEmpty())
}
@Test
fun any() {
assertTrue(list.any { it == 5 })
assertTrue(list.any { it == 1 })
assertFalse(list.any { it == 0 })
}
@Test
fun reversedAny() {
val reversedList = mutableListOf<Int>()
assertFalse(
list.reversedAny {
reversedList.add(it)
false
}
)
assertEquals(reversedList, list.asMutableList().reversed())
val reversedSublist = mutableListOf<Int>()
assertTrue(
list.reversedAny {
reversedSublist.add(it)
reversedSublist.size == 2
}
)
assertEquals(reversedSublist, listOf(5, 4))
}
@Test
fun forEach() {
val copy = mutableVectorOf<Int>()
list.forEach { copy += it }
assertTrue(copy.contentEquals(list))
}
@Test
fun forEachReversed() {
val copy = mutableVectorOf<Int>()
list.forEachReversed { copy += it }
assertTrue(copy.contentEquals(mutableVectorOf(5, 4, 3, 2, 1)))
}
@Test
fun forEachIndexed() {
val copy = mutableVectorOf<Int>()
val indices = mutableVectorOf<Int>()
list.forEachIndexed { index, item ->
copy += item
indices += index
}
assertTrue(copy.contentEquals(list))
assertTrue(indices.contentEquals(mutableVectorOf(0, 1, 2, 3, 4)))
}
@Test
fun forEachReversedIndexed() {
val copy = mutableVectorOf<Int>()
val indices = mutableVectorOf<Int>()
list.forEachReversedIndexed { index, item ->
copy += item
indices += index
}
assertTrue(copy.contentEquals(mutableVectorOf(5, 4, 3, 2, 1)))
assertTrue(indices.contentEquals(mutableVectorOf(4, 3, 2, 1, 0)))
}
@Test
fun indexOfFirst() {
assertEquals(0, list.indexOfFirst { it == 1 })
assertEquals(4, list.indexOfFirst { it == 5 })
assertEquals(-1, list.indexOfFirst { it == 0 })
assertEquals(0, mutableVectorOf("a", "a").indexOfFirst { it == "a" })
}
@Test
fun indexOfLast() {
assertEquals(0, list.indexOfLast { it == 1 })
assertEquals(4, list.indexOfLast { it == 5 })
assertEquals(-1, list.indexOfLast { it == 0 })
assertEquals(1, mutableVectorOf("a", "a").indexOfLast { it == "a" })
}
@Test
fun contains() {
assertTrue(list.contains(5))
assertTrue(list.contains(1))
assertFalse(list.contains(0))
}
@Test
fun containsAllList() {
assertTrue(list.containsAll(listOf(2, 3, 1)))
assertFalse(list.containsAll(listOf(2, 3, 6)))
}
@Test
fun containsAllVector() {
assertTrue(list.containsAll(mutableVectorOf(2, 3, 1)))
assertFalse(list.containsAll(mutableVectorOf(2, 3, 6)))
}
@Test
fun containsAllCollection() {
assertTrue(list.containsAll(setOf(2, 3, 1)))
assertFalse(list.containsAll(setOf(2, 3, 6)))
}
@Test
fun lastIndexOf() {
assertEquals(4, list.lastIndexOf(5))
assertEquals(1, list.lastIndexOf(2))
val copy = mutableVectorOf<Int>()
copy.addAll(list)
copy.addAll(list)
assertEquals(5, copy.lastIndexOf(1))
}
@Test
fun map() {
val mapped = list.map { it - 1 }
repeat(5) {
assertEquals(it, mapped[it])
}
assertEquals(5, mapped.size)
}
@Test
fun mapIndexed() {
val mapped = list.mapIndexed { index, item ->
index + item
}
assertEquals(5, mapped.size)
repeat(5) {
assertEquals(it * 2 + 1, mapped[it])
}
}
@Test
fun mapIndexedNotNull() {
val mapped = list.mapIndexedNotNull { index, item ->
if (item == 5) null else index + item
}
assertEquals(4, mapped.size)
repeat(4) {
assertEquals(it * 2 + 1, mapped[it])
}
}
@Test
fun mapNotNull() {
val mapped = list.mapNotNull { item ->
if (item == 5) null else item - 1
}
assertEquals(4, mapped.size)
repeat(4) {
assertEquals(it, mapped[it])
}
}
@Test
fun first() {
assertEquals(1, list.first())
}
@Test
fun firstException() {
assertFailsWith(NoSuchElementException::class) {
mutableVectorOf<String>().first()
}
}
@Test
fun firstOrNull() {
assertEquals(1, list.firstOrNull())
assertNull(mutableVectorOf<Int>().firstOrNull())
}
@Test
fun firstWithPredicate() {
assertEquals(5, list.first { it == 5 })
assertEquals(1, mutableVectorOf(1, 5).first { it != 0 })
}
@Test
fun firstWithPredicateException() {
assertFailsWith(NoSuchElementException::class) {
mutableVectorOf<String>().first { it == "Hello" }
}
}
@Test
fun firstOrNullWithPredicate() {
assertEquals(5, list.firstOrNull { it == 5 })
assertNull(list.firstOrNull { it == 0 })
}
@Test
fun last() {
assertEquals(5, list.last())
}
@Test
fun lastException() {
assertFailsWith(NoSuchElementException::class) {
mutableVectorOf<String>().last()
}
}
@Test
fun lastOrNull() {
assertEquals(5, list.lastOrNull())
assertNull(mutableVectorOf<Int>().lastOrNull())
}
@Test
fun lastWithPredicate() {
assertEquals(1, list.last { it == 1 })
assertEquals(5, mutableVectorOf(1, 5).last { it != 0 })
}
@Test
fun lastWithPredicateException() {
assertFailsWith(NoSuchElementException::class) {
mutableVectorOf<String>().last { it == "Hello" }
}
}
@Test
fun lastOrNullWithPredicate() {
assertEquals(1, list.lastOrNull { it == 1 })
assertNull(list.lastOrNull { it == 0 })
}
@Test
fun sumBy() {
assertEquals(15, list.sumBy { it })
}
@Test
fun fold() {
assertEquals("12345", list.fold("") { acc, i -> acc + i.toString() })
}
@Test
fun foldIndexed() {
assertEquals(
"01-12-23-34-45-",
list.foldIndexed("") { index, acc, i ->
"$acc$index$i-"
}
)
}
@Test
fun foldRight() {
assertEquals("54321", list.foldRight("") { i, acc -> acc + i.toString() })
}
@Test
fun foldRightIndexed() {
assertEquals(
"45-34-23-12-01-",
list.foldRightIndexed("") { index, i, acc ->
"$acc$index$i-"
}
)
}
@Test
fun add() {
val l = mutableVectorOf(1, 2, 3)
l += 4
l.add(5)
assertTrue(l.contentEquals(list))
}
@Test
fun addAtIndex() {
val l = mutableVectorOf(2, 4)
l.add(2, 5)
l.add(0, 1)
l.add(2, 3)
assertTrue(l.contentEquals(list))
}
@Test
fun addAllListAtIndex() {
val l = listOf(4)
val l2 = listOf(1, 2)
val l3 = listOf(5)
val l4 = mutableVectorOf(3)
assertTrue(l4.addAll(1, l3))
assertTrue(l4.addAll(0, l2))
assertTrue(l4.addAll(3, l))
assertFalse(l4.addAll(0, emptyList()))
assertTrue(l4.contentEquals(list))
}
@Test
fun addAllVectorAtIndex() {
val l = mutableVectorOf(4)
val l2 = mutableVectorOf(1, 2)
val l3 = mutableVectorOf(5)
val l4 = mutableVectorOf(3)
assertTrue(l4.addAll(1, l3))
assertTrue(l4.addAll(0, l2))
assertTrue(l4.addAll(3, l))
assertFalse(l4.addAll(0, mutableVectorOf()))
assertTrue(l4.contentEquals(list))
}
@Test
fun addAllList() {
val l = listOf(3, 4, 5)
val l2 = mutableVectorOf(1, 2)
assertTrue(l2.addAll(l))
assertFalse(l2.addAll(emptyList()))
}
@Test
fun addAllVector() {
val l = MutableVector<Int>()
l.add(3)
l.add(4)
l.add(5)
val l2 = mutableVectorOf(1, 2)
assertTrue(l2.addAll(l))
assertFalse(l2.addAll(mutableVectorOf()))
}
@Test
fun addAllCollectionAtIndex() {
val l = listOf(4) as Collection<Int>
val l2 = listOf(1, 2) as Collection<Int>
val l3 = listOf(5) as Collection<Int>
val l4 = mutableVectorOf(3)
assertTrue(l4.addAll(1, l3))
assertTrue(l4.addAll(0, l2))
assertTrue(l4.addAll(3, l))
assertFalse(l4.addAll(0, emptyList()))
assertTrue(l4.contentEquals(list))
}
@Test
fun addAllCollection() {
val l = listOf(3, 4, 5) as Collection<Int>
val l2 = mutableVectorOf(1, 2)
assertTrue(l2.addAll(l))
assertFalse(l2.addAll(emptyList()))
}
@Test
fun addAllArray() {
val a = arrayOf(3, 4, 5)
val v = mutableVectorOf(1, 2)
v.addAll(a)
assertEquals(5, v.size)
assertEquals(3, v[2])
assertEquals(4, v[3])
assertEquals(5, v[4])
}
@Test
fun clear() {
val l = mutableVectorOf<Int>()
l.addAll(list)
assertTrue(l.isNotEmpty())
l.clear()
assertTrue(l.isEmpty())
repeat(5) {
assertNull(l.content[it])
}
}
@Test
fun remove() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
l.remove(3)
assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5)))
assertNull(l.content[4])
}
@Test
fun removeAt() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
l.removeAt(2)
assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5)))
assertNull(l.content[4])
}
@Test
fun set() {
val l = mutableVectorOf(0, 0, 0, 0, 0)
l[0] = 1
l[4] = 5
l[2] = 3
l[1] = 2
l[3] = 4
assertTrue(l.contentEquals(list))
}
@Test
fun ensureCapacity() {
val l = mutableVectorOf(1)
assertEquals(1, l.content.size)
l.ensureCapacity(5)
assertEquals(5, l.content.size)
}
@Test
fun removeAllList() {
assertFalse(list.removeAll(listOf(0, 10, 15)))
val l = mutableVectorOf(0, 1, 15, 10, 2, 3, 4, 5, 20, 5)
assertTrue(l.removeAll(listOf(20, 0, 15, 10, 5)))
assertTrue(l.contentEquals(list))
}
@Test
fun removeAllVector() {
assertFalse(list.removeAll(mutableVectorOf(0, 10, 15)))
val l = mutableVectorOf(0, 1, 15, 10, 2, 3, 4, 5, 20, 5)
assertTrue(l.removeAll(mutableVectorOf(20, 0, 15, 10, 5)))
assertTrue(l.contentEquals(list))
}
@Test
fun removeAllCollection() {
assertFalse(list.removeAll(setOf(0, 10, 15)))
val l = mutableVectorOf(0, 1, 15, 10, 2, 3, 4, 5, 20, 5)
assertTrue(l.removeAll(setOf(20, 0, 15, 10, 5)))
assertTrue(l.contentEquals(list))
}
@Test
fun retainAll() {
assertFalse(list.retainAll(setOf(1, 2, 3, 4, 5, 6)))
val l = mutableVectorOf(0, 1, 15, 10, 2, 3, 4, 5, 20)
assertTrue(l.retainAll(setOf(1, 2, 3, 4, 5, 6)))
assertTrue(l.contentEquals(list))
}
@Test
fun contentEquals() {
assertTrue(list.contentEquals(mutableVectorOf(1, 2, 3, 4, 5)))
assertFalse(list.contentEquals(mutableVectorOf(2, 1, 3, 4, 5)))
assertFalse(list.contentEquals(mutableVectorOf(1, 2, 3, 4, 5, 6)))
}
@Test
fun iterator() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
val iterator = l.asMutableList().iterator()
assertTrue(iterator.hasNext())
assertEquals(1, iterator.next())
assertTrue(iterator.hasNext())
assertEquals(2, iterator.next())
assertTrue(iterator.hasNext())
assertEquals(3, iterator.next())
assertTrue(iterator.hasNext())
iterator.remove()
assertTrue(iterator.hasNext())
assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5)))
assertEquals(4, iterator.next())
assertTrue(iterator.hasNext())
assertEquals(5, iterator.next())
assertFalse(iterator.hasNext())
iterator.remove()
assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4)))
}
@Test
fun listIterator() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
val iterator = l.asMutableList().listIterator()
assertEquals(1, iterator.next())
assertEquals(1, iterator.previous())
assertEquals(0, iterator.nextIndex())
iterator.add(6)
assertEquals(1, iterator.nextIndex())
assertEquals(0, iterator.previousIndex())
assertEquals(6, iterator.previous())
assertTrue(l.contentEquals(mutableVectorOf(6, 1, 2, 3, 4, 5)))
}
@Test
fun listIteratorInitialIndex() {
val iterator = list.asMutableList().listIterator(2)
assertEquals(2, iterator.nextIndex())
}
@Test
fun subList() {
val l = list.asMutableList().subList(1, 4)
assertEquals(3, l.size)
assertEquals(2, l[0])
assertEquals(3, l[1])
assertEquals(4, l[2])
}
@Test
fun subListContains() {
val l = list.asMutableList().subList(1, 4)
assertTrue(l.contains(2))
assertTrue(l.contains(3))
assertTrue(l.contains(4))
assertFalse(l.contains(5))
assertFalse(l.contains(1))
}
@Test
fun subListContainsAll() {
val l = list.asMutableList().subList(1, 4)
val smallList = listOf(2, 3, 4)
assertTrue(l.containsAll(smallList))
val largeList = listOf(3, 4, 5)
assertFalse(l.containsAll(largeList))
}
@Test
fun subListIndexOf() {
val l = list.asMutableList().subList(1, 4)
assertEquals(0, l.indexOf(2))
assertEquals(2, l.indexOf(4))
assertEquals(-1, l.indexOf(1))
val l2 = mutableVectorOf(2, 1, 1, 3).asMutableList().subList(1, 2)
assertEquals(0, l2.indexOf(1))
}
@Test
fun subListIsEmpty() {
val l = list.asMutableList().subList(1, 4)
assertFalse(l.isEmpty())
assertTrue(list.asMutableList().subList(4, 4).isEmpty())
}
@Test
fun subListIterator() {
val l = list.asMutableList().subList(1, 4)
val l2 = mutableListOf<Int>()
l.forEach { l2 += it }
assertEquals(3, l2.size)
assertEquals(2, l2[0])
assertEquals(3, l2[1])
assertEquals(4, l2[2])
}
@Test
fun subListLastIndexOf() {
val l = list.asMutableList().subList(1, 4)
assertEquals(0, l.lastIndexOf(2))
assertEquals(2, l.lastIndexOf(4))
assertEquals(-1, l.lastIndexOf(1))
val l2 = mutableVectorOf(2, 1, 1, 3).asMutableList().subList(1, 3)
assertEquals(1, l2.lastIndexOf(1))
}
@Test
fun subListAdd() {
val v = mutableVectorOf(1, 2, 3)
val l = v.asMutableList().subList(1, 2)
assertTrue(l.add(4))
assertEquals(2, l.size)
assertEquals(4, v.size)
assertEquals(2, l[0])
assertEquals(4, l[1])
assertEquals(2, v[1])
assertEquals(4, v[2])
assertEquals(3, v[3])
}
@Test
fun subListAddIndex() {
val v = mutableVectorOf(6, 1, 2, 3)
val l = v.asMutableList().subList(1, 3)
l.add(1, 4)
assertEquals(3, l.size)
assertEquals(5, v.size)
assertEquals(1, l[0])
assertEquals(4, l[1])
assertEquals(2, l[2])
assertEquals(1, v[1])
assertEquals(4, v[2])
assertEquals(2, v[3])
}
@Test
fun subListAddAllAtIndex() {
val v = mutableVectorOf(6, 1, 2, 3)
val l = v.asMutableList().subList(1, 3)
l.addAll(1, listOf(4, 5))
assertEquals(4, l.size)
assertEquals(6, v.size)
assertEquals(1, l[0])
assertEquals(4, l[1])
assertEquals(5, l[2])
assertEquals(2, l[3])
assertEquals(1, v[1])
assertEquals(4, v[2])
assertEquals(5, v[3])
assertEquals(2, v[4])
}
@Test
fun subListAddAll() {
val v = mutableVectorOf(6, 1, 2, 3)
val l = v.asMutableList().subList(1, 3)
l.addAll(listOf(4, 5))
assertEquals(4, l.size)
assertEquals(6, v.size)
assertEquals(1, l[0])
assertEquals(2, l[1])
assertEquals(4, l[2])
assertEquals(5, l[3])
assertEquals(1, v[1])
assertEquals(2, v[2])
assertEquals(4, v[3])
assertEquals(5, v[4])
assertEquals(3, v[5])
}
@Test
fun subListClear() {
val v = mutableVectorOf(1, 2, 3, 4, 5)
val l = v.asMutableList().subList(1, 4)
l.clear()
assertEquals(0, l.size)
assertEquals(2, v.size)
assertEquals(1, v[0])
assertEquals(5, v[1])
assertNull(v.content[2])
assertNull(v.content[3])
assertNull(v.content[4])
}
@Test
fun subListListIterator() {
val l = list.asMutableList().subList(1, 4)
val listIterator = l.listIterator()
assertTrue(listIterator.hasNext())
assertFalse(listIterator.hasPrevious())
assertEquals(0, listIterator.nextIndex())
assertEquals(2, listIterator.next())
}
@Test
fun subListListIteratorWithIndex() {
val l = list.asMutableList().subList(1, 4)
val listIterator = l.listIterator(1)
assertTrue(listIterator.hasNext())
assertTrue(listIterator.hasPrevious())
assertEquals(1, listIterator.nextIndex())
assertEquals(3, listIterator.next())
}
@Test
fun subListRemove() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
val l2 = l.asMutableList().subList(1, 4)
assertTrue(l2.remove(3))
assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5)))
assertEquals(2, l2.size)
assertEquals(2, l2[0])
assertEquals(4, l2[1])
assertFalse(l2.remove(3))
assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5)))
assertEquals(2, l2.size)
}
@Test
fun subListRemoveAll() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
val l2 = l.asMutableList().subList(1, 4)
assertFalse(l2.removeAll(listOf(1, 5, -1)))
assertEquals(5, l.size)
assertEquals(3, l2.size)
assertTrue(l2.removeAll(listOf(3, 4, 5)))
assertEquals(3, l.size)
assertEquals(1, l2.size)
}
@Test
fun subListRemoveAt() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
val l2 = l.asMutableList().subList(1, 4)
assertEquals(3, l2.removeAt(1))
assertEquals(4, l.size)
assertEquals(2, l2.size)
assertEquals(4, l2.removeAt(1))
assertEquals(1, l2.size)
}
@Test
fun subListRetainAll() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
val l2 = l.asMutableList().subList(1, 4)
assertFalse(l2.retainAll(list.asMutableList()))
assertFalse(l2.retainAll(listOf(2, 3, 4)))
assertEquals(3, l2.size)
assertEquals(5, l.size)
assertTrue(l2.retainAll(setOf(1, 2, 4)))
assertEquals(4, l.size)
assertEquals(2, l2.size)
assertTrue(l.contentEquals(mutableVectorOf(1, 2, 4, 5)))
}
@Test
fun subListSet() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
val l2 = l.asMutableList().subList(1, 4)
l2[1] = 10
assertEquals(10, l2[1])
assertEquals(3, l2.size)
assertEquals(10, l[2])
}
@Test
fun subListSubList() {
val l = list.asMutableList().subList(1, 5)
val l2 = l.subList(1, 3)
assertEquals(2, l2.size)
assertEquals(3, l2[0])
}
@Test
fun removeRange() {
val l = mutableVectorOf(1, 2, 3, 4, 5)
l.removeRange(1, 4)
assertNull(l.content[2])
assertNull(l.content[3])
assertNull(l.content[4])
assertTrue(l.contentEquals(mutableVectorOf(1, 5)))
val l2 = mutableVectorOf(1, 2, 3, 4, 5)
l2.removeRange(3, 5)
assertTrue(l2.contentEquals(mutableVectorOf(1, 2, 3)))
l2.removeRange(3, 3)
assertTrue(l2.contentEquals(mutableVectorOf(1, 2, 3)))
}
@Test
fun sortWith() {
val l = mutableVectorOf(1, 4, 2, 5, 3)
l.sortWith(Comparator { p0, p1 -> p0 - p1 })
assertTrue(l.contentEquals(list))
}
@Test
fun list_outOfBounds_Get_Below() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(1, 2, 3, 4).asMutableList()
l[-1]
}
}
@Test
fun sublist_outOfBounds_Get_Below() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(1, 2, 3, 4).asMutableList().subList(1, 2)
l[-1]
}
}
@Test
fun list_outOfBounds_Get_Above() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(1, 2, 3, 4).asMutableList()
l[4]
}
}
@Test
fun sublist_outOfBounds_Get_Above() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(1, 2, 3, 4).asMutableList().subList(1, 2)
l[1]
}
}
@Test
fun list_outOfBounds_RemoveAt_Below() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList()
l.removeAt(-1)
}
}
@Test
fun sublist_outOfBounds_RemoveAt_Below() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2)
l.removeAt(-1)
}
}
@Test
fun list_outOfBounds_RemoveAt_Above() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList()
l.removeAt(4)
}
}
@Test
fun sublist_outOfBounds_RemoveAt_Above() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2)
l.removeAt(1)
}
}
@Test
fun list_outOfBounds_Set_Below() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList()
l[-1] = 1
}
}
@Test
fun sublist_outOfBounds_Set_Below() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2)
l[-1] = 1
}
}
@Test
fun list_outOfBounds_Set_Above() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList()
l[4] = 1
}
}
@Test
fun sublist_outOfBounds_Set_Above() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2)
l[1] = 1
}
}
@Test
fun list_outOfBounds_SubList_Below() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList()
l.subList(-1, 1)
}
}
@Test
fun sublist_outOfBounds_SubList_Below() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2)
l.subList(-1, 1)
}
}
@Test
fun list_outOfBounds_SubList_Above() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList()
l.subList(5, 5)
}
}
@Test
fun sublist_outOfBounds_SubList_Above() {
assertFailsWith(IndexOutOfBoundsException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2)
l.subList(1, 2)
}
}
@Test
fun list_outOfBounds_SubList_Order() {
assertFailsWith(IllegalArgumentException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList()
l.subList(3, 2)
}
}
@Test
fun sublist_outOfBounds_SubList_Order() {
assertFailsWith(IllegalArgumentException::class) {
val l = mutableVectorOf(0, 1, 2, 3).asMutableList().subList(1, 2)
l.subList(1, 0)
}
}
}
| apache-2.0 | 18d656fc06b64409e80bc9b8b1311ab8 | 26.484631 | 82 | 0.557204 | 3.908641 | false | true | false | false |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/api/choices/Choice.kt | 1 | 2997 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.api.choices
/**
* Simple utility for making choices.
*/
open class Choice<T> {
companion object {
/**
* Constructs a [Choice] for the given [option].
*
* @param option Option(s) for choice.
* @return constructed choice
*/
@JvmStatic
fun <T> between(vararg option: T): Choice<T> = between(option.asIterable())
/**
* Constructs a [Choice] for the given [option].
*
* @param option Option(s) for choice.
* @return constructed choice
*/
@JvmStatic
fun <T> between(options: Iterable<T>): Choice<T> = Choice<T>().also { it.addOptions(options) }
}
protected val options = mutableSetOf<T>()
/**
* Adds an option to the available options when choosing.
*
* @param option Option to add
* @return if adding was successful
*/
fun addOption(option: T) = options.add(option)
/**
* Adds options to the available options when choosing.
*
* @param option Option to add
* @return if adding was successful
*/
fun addOptions(vararg option: T) = options.addAll(option)
/**
* Adds options to the available options when choosing.
*
* @param pOptions Options to add
* @return if adding was successful
*/
fun addOptions(pOptions: Iterable<T>) = options.addAll(pOptions)
/**
* Chooses one of the available options and returns it.
*
* @param block Extra block to execute to determine if option is selectable
* @return chosen option or null if one cannot be chosen
*/
open fun choose(): T? {
if (options.isEmpty()) {
return null
}
return options.random()
}
}
| mit | 8dce66f31f52de8796cfd90cdb8d30cd | 33.848837 | 105 | 0.658992 | 4.466468 | false | false | false | false |
smmribeiro/intellij-community | plugins/built-in-help/src/com/jetbrains/builtInHelp/search/HelpComplete.kt | 10 | 2531 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.builtInHelp.search
import com.google.gson.Gson
import com.intellij.openapi.diagnostic.Logger
import org.apache.commons.compress.utils.IOUtils
import org.apache.lucene.analysis.standard.StandardAnalyzer
import org.apache.lucene.index.DirectoryReader
import org.apache.lucene.search.spell.LuceneDictionary
import org.apache.lucene.search.suggest.analyzing.BlendedInfixSuggester
import org.apache.lucene.store.FSDirectory
import org.jetbrains.annotations.NotNull
import java.io.FileOutputStream
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import org.jetbrains.annotations.NonNls
class HelpComplete {
companion object {
val resources = arrayOf("_0.cfe", "_0.cfs", "_0.si", "segments_1")
@NonNls
val PREFIX = "/search/"
@NonNls
val NOT_FOUND = "[]"
private val analyzer: StandardAnalyzer = StandardAnalyzer()
@NotNull
fun complete(query: String, maxHits: Int): String {
val indexDir: Path? = Files.createTempDirectory("search-index")
var indexDirectory: FSDirectory? = null
var reader: DirectoryReader? = null
var suggester: BlendedInfixSuggester? = null
if (indexDir != null)
try {
for (resourceName in resources) {
val input = HelpSearch::class.java.getResourceAsStream(
PREFIX + resourceName)
val fos: FileOutputStream = FileOutputStream(Paths.get(indexDir.toAbsolutePath().toString(), resourceName).toFile())
IOUtils.copy(input, fos)
fos.flush()
fos.close()
input.close()
}
indexDirectory = FSDirectory.open(indexDir)
reader = DirectoryReader.open(indexDirectory)
suggester = BlendedInfixSuggester(indexDirectory, analyzer)
suggester.build(LuceneDictionary(reader, "contents"))
val completionResults = suggester.lookup(query, maxHits, false, true)
return Gson().toJson(completionResults)
}
catch (e: Exception) {
Logger.getInstance(HelpComplete::class.java).error("Error searching help for $query", e)
}
finally {
suggester?.close()
indexDirectory?.close()
reader?.close()
for (f in indexDir.toFile().listFiles()) f.delete()
Files.delete(indexDir)
}
return NOT_FOUND
}
}
} | apache-2.0 | a41f78933f5b76fcc547680815efb569 | 33.684932 | 140 | 0.679178 | 4.356282 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/java/findJavaPropertyUsages/javaPropertySetterUsagesKJ.1.kt | 18 | 287 | open class A {
open var p: Int = 1
}
class AA : A() {
override var p: Int = 1
}
class B : J() {
override var p: Int = 1
}
fun test() {
val t = A().p
A().p = 1
val t2 = AA().p
AA().p = 1
val t3 = J().p
J().p = 1
val t4 = B().p
B().p = 1
} | apache-2.0 | 6e7409d53e4354b093af2a0b7c9030f1 | 10.52 | 27 | 0.407666 | 2.539823 | false | false | false | false |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/general/persistentNotification/DummyServiceHelper.kt | 1 | 2833 | package info.nightscout.androidaps.plugins.general.persistentNotification
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Build
import android.os.IBinder
import androidx.annotation.RequiresApi
import info.nightscout.androidaps.interfaces.NotificationHolderInterface
import javax.inject.Inject
import javax.inject.Singleton
/*
This code replaces following
val alarm = Intent(context, DummyService::class.java)
alarm.putExtra("soundid", n.soundId)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) context.startForegroundService(alarm) else context.startService(alarm)
it fails randomly with error
Context.startForegroundService() did not then call Service.startForeground(): ServiceRecord{e317f7e u0 info.nightscout.nsclient/info.nightscout.androidaps.services.DummyService}
*/
@RequiresApi(Build.VERSION_CODES.O)
@Singleton
class DummyServiceHelper @Inject constructor(
private val notificationHolder: NotificationHolderInterface
) {
fun startService(context: Context) {
val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
// The binder of the service that returns the instance that is created.
val binder: DummyService.LocalBinder = service as DummyService.LocalBinder
val dummyService: DummyService = binder.getService()
context.startForegroundService(Intent(context, DummyService::class.java))
// This is the key: Without waiting Android Framework to call this method
// inside Service.onCreate(), immediately call here to post the notification.
dummyService.startForeground(notificationHolder.notificationID, notificationHolder.notification)
// Release the connection to prevent leaks.
context.unbindService(this)
}
override fun onServiceDisconnected(name: ComponentName?) {
}
}
try {
context.bindService(Intent(context, DummyService::class.java), connection, Context.BIND_AUTO_CREATE)
} catch (ignored: RuntimeException) {
// This is probably a broadcast receiver context even though we are calling getApplicationContext().
// Just call startForegroundService instead since we cannot bind a service to a
// broadcast receiver context. The service also have to call startForeground in
// this case.
context.startForegroundService(Intent(context, DummyService::class.java))
}
}
fun stopService(context: Context) {
context.stopService(Intent(context, DummyService::class.java))
}
} | agpl-3.0 | 8e0e36542cf917ab97d192887b1893f3 | 41.939394 | 181 | 0.716908 | 5.285448 | false | false | false | false |
TonicArtos/SuperSLiM | library/src/main/kotlin/com/tonicartos/superslim/internal/layout/padding.kt | 1 | 6936 | package com.tonicartos.superslim.internal.layout
import com.tonicartos.superslim.LayoutHelper
import com.tonicartos.superslim.SectionLayoutManager
import com.tonicartos.superslim.internal.SectionState
import com.tonicartos.superslim.internal.SectionState.LayoutState
import com.tonicartos.superslim.internal.SectionState.PaddingLayoutState
import com.tonicartos.superslim.internal.SectionState.PaddingLayoutState.Companion.BOTTOM_ADDED
import com.tonicartos.superslim.internal.SectionState.PaddingLayoutState.Companion.TOP_ADDED
internal object PaddingLayoutManager : SectionLayoutManager<SectionState> {
override fun isAtTop(section: SectionState, layoutState: LayoutState): Boolean {
val state = layoutState as PaddingLayoutState
return state.overdraw == 0 && state.paddingTop > 0 || section.atTop
}
override fun onLayout(helper: LayoutHelper, section: SectionState, layoutState: LayoutState) {
val state = layoutState as PaddingLayoutState
state.paddingTop = helper.paddingTop
state.paddingBottom = helper.paddingBottom
if (state.paddingTop > 0) {
if (state.onScreen && state flagUnset TOP_ADDED && state.overdraw > 0) {
// Must be in a layout pass with requested position.
state set TOP_ADDED
} else if (!state.onScreen) {
state.overdraw = 0
state set TOP_ADDED
}
}
state.onScreen = true
var y = if (state flagSet TOP_ADDED) state.paddingTop - state.overdraw else 0
section.layout(helper, section.leftGutter { 0 }, y, helper.layoutWidth - section.rightGutter { 0 })
state.disappearedOrRemovedHeight += section.disappearedHeight
y += section.height
helper.filledArea += section.height
if (state.paddingBottom > 0 && y < helper.layoutLimit) {
state set BOTTOM_ADDED
y += helper.paddingBottom
}
state.bottom = y
}
override fun onFillTop(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int {
val state = layoutState as PaddingLayoutState
var toFill = dy - state.overdraw
if (state.paddingBottom > 0 && !state.onScreen) {
state.paddingTop = helper.paddingTop
state.paddingBottom = helper.paddingBottom
// Add bottom padding.
val filled = state.paddingBottom
state.overdraw += filled
toFill -= filled
state set BOTTOM_ADDED
}
state.onScreen = true
// Add content.
state.overdraw += section.fillTop(Math.max(0, toFill), section.leftGutter { 0 }, -state.overdraw,
helper.layoutWidth - section.rightGutter { 0 }, helper)
if (state.paddingTop > 0 && state flagUnset TOP_ADDED && state.overdraw < dy) {
// Add top padding.
state.overdraw += state.paddingTop
state set TOP_ADDED
}
val filled = Math.min(dy, state.overdraw)
state.overdraw -= filled
state.bottom += filled
return filled
}
override fun onFillBottom(dy: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int {
val state = layoutState as PaddingLayoutState
var filled = 0
if (state.paddingTop > 0 && !state.onScreen) {
state.paddingBottom = helper.paddingBottom
state.paddingTop = helper.paddingTop
// Add top padding.
filled += state.paddingTop
state.bottom = state.paddingTop
state.overdraw = 0
state set TOP_ADDED
}
state.onScreen = true
val y = if (state flagSet TOP_ADDED) state.paddingTop - state.overdraw else 0
// Add content
val before = section.height
filled += section.fillBottom(dy, section.leftGutter { 0 }, y, helper.layoutWidth - section.rightGutter { 0 },
helper)
state.bottom += section.height - before
if (state.paddingBottom > 0 && filled < dy) {
if (state flagUnset BOTTOM_ADDED) {
// Add bottom padding.
filled += state.paddingBottom
state.bottom += state.paddingBottom
state set BOTTOM_ADDED
} else {
filled += Math.max(0, state.bottom - helper.layoutLimit)
}
}
return Math.min(dy, filled)
}
override fun onTrimTop(scrolled: Int, helper: LayoutHelper, section: SectionState, layoutState: LayoutState): Int {
val state = layoutState as PaddingLayoutState
var removedHeight = 0
var contentTop = 0
if (state flagSet TOP_ADDED) {
val before = state.overdraw
state.overdraw = Math.min(state.paddingTop, state.overdraw + scrolled)
removedHeight += state.overdraw - before
// Do padding top.
if (state.overdraw >= state.paddingTop) {
state.overdraw = 0
state unset TOP_ADDED
} else {
contentTop = state.paddingTop - state.overdraw
}
}
removedHeight += section.trimTop(scrolled, contentTop, helper)
if (helper.numViews == 0 && state flagSet BOTTOM_ADDED) {
val before = state.overdraw
state.overdraw = Math.min(state.paddingBottom, state.overdraw + (scrolled - removedHeight))
removedHeight += state.overdraw - before
// Do padding bottom.
if (state.bottom < 0) {
state.overdraw = 0
state unset BOTTOM_ADDED
state.onScreen = false
}
}
state.bottom -= removedHeight
return removedHeight
}
override fun onTrimBottom(scrolled: Int, helper: LayoutHelper, section: SectionState,
layoutState: LayoutState): Int {
val state = layoutState as PaddingLayoutState
var removedHeight = 0
if (state flagSet BOTTOM_ADDED) {
// Do padding bottom.
if (state.bottom - state.paddingBottom > helper.layoutLimit) {
removedHeight += state.paddingBottom
state unset BOTTOM_ADDED
}
}
val contentTop = if (state flagSet TOP_ADDED) state.paddingTop - state.overdraw else 0
// Do content.
removedHeight += section.trimBottom(scrolled - removedHeight, contentTop, helper)
if (state flagSet TOP_ADDED) {
// Do padding top.
if (helper.layoutLimit < 0) {
removedHeight += state.paddingBottom
state unset TOP_ADDED
state.onScreen = false
}
}
state.bottom -= removedHeight
return removedHeight
}
}
| apache-2.0 | 4b2be4fb3b7f011f302ca973230149ce | 36.290323 | 119 | 0.602941 | 5.14922 | false | false | false | false |
JordyLangen/vaultbox | app/src/main/java/com/jlangen/vaultbox/vaults/vault/VaultEntryAdapter.kt | 1 | 1629 | package com.jlangen.vaultbox.vaults.vault
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.jlangen.vaultbox.R
class VaultEntryAdapter(var vaultEntries: List<VaultEntry>) : RecyclerView.Adapter<VaultEntryAdapter.VaultEntryViewHolder>() {
override fun getItemCount(): Int {
return vaultEntries.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): VaultEntryViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.row_vault_entry, parent, false)
return VaultEntryViewHolder(view)
}
override fun onBindViewHolder(holder: VaultEntryViewHolder, position: Int) {
val entry = vaultEntries[position]
if (entry.icon != null) {
Glide.with(holder.itemView.context)
.asBitmap()
.load(entry.icon)
.into(holder.groupIconView)
} else {
holder.groupIconView.setImageResource(entry.vaultIcon.iconId)
}
holder.titleView.text = entry.title
holder.groupView.text = entry.group
}
class VaultEntryViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val groupIconView = itemView.findViewById(R.id.vault_entry_group_icon) as ImageView
val titleView = itemView.findViewById(R.id.vault_entry_title) as TextView
val groupView = itemView.findViewById(R.id.vault_entry_group) as TextView
}
} | apache-2.0 | be1f55a713d75c14c03e7696a6f04335 | 36.045455 | 126 | 0.706568 | 4.45082 | false | false | false | false |
mdaniel/intellij-community | platform/collaboration-tools/src/com/intellij/collaboration/ui/codereview/list/search/ReviewListSearchPanelFactory.kt | 1 | 6171 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.collaboration.ui.codereview.list.search
import com.intellij.collaboration.messages.CollaborationToolsBundle
import com.intellij.collaboration.ui.codereview.InlineIconButton
import com.intellij.collaboration.ui.codereview.list.search.ChooserPopupUtil.showAndAwaitListSubmission
import com.intellij.icons.AllIcons
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.actionSystem.Separator
import com.intellij.openapi.actionSystem.Toggleable
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.ui.*
import com.intellij.ui.components.GradientViewport
import com.intellij.ui.components.JBThinOverlappingScrollBar
import com.intellij.ui.components.panels.HorizontalLayout
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.JBUI
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.jetbrains.annotations.Nls
import java.awt.*
import java.awt.event.ActionListener
import java.awt.geom.Ellipse2D
import javax.swing.Icon
import javax.swing.JComponent
import javax.swing.JPanel
import javax.swing.ScrollPaneConstants
abstract class ReviewListSearchPanelFactory<S : ReviewListSearchValue, VM : ReviewListSearchPanelViewModel<S>>(
protected val vm: VM
) {
fun create(viewScope: CoroutineScope, quickFilters: List<Pair<@Nls String, S>>): JComponent {
val searchField = ReviewListSearchTextFieldFactory(vm.queryState).create(viewScope, chooseFromHistory = { point ->
val value = JBPopupFactory.getInstance()
.createPopupChooserBuilder(vm.getSearchHistory().reversed())
.setRenderer(SimpleListCellRenderer.create { label, value, _ ->
label.text = getShortText(value)
})
.createPopup()
.showAndAwaitListSubmission<S>(point)
if (value != null) {
vm.searchState.update { value }
}
})
val filters = createFilters(viewScope)
val filtersPanel = JPanel(HorizontalLayout(4)).apply {
isOpaque = false
filters.forEach { add(it, HorizontalLayout.LEFT) }
}.let {
ScrollPaneFactory.createScrollPane(it, true).apply {
viewport = GradientViewport(it, JBUI.insets(0, 10), false)
verticalScrollBarPolicy = ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER
horizontalScrollBarPolicy = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_ALWAYS
horizontalScrollBar = JBThinOverlappingScrollBar(Adjustable.HORIZONTAL)
}
}
val quickFilterButton = QuickFilterButtonFactory().create(viewScope, quickFilters)
val filterPanel = JPanel(BorderLayout()).apply {
border = JBUI.Borders.emptyTop(10)
isOpaque = false
add(quickFilterButton, BorderLayout.WEST)
add(filtersPanel, BorderLayout.CENTER)
}
val searchPanel = JPanel(BorderLayout()).apply {
border = JBUI.Borders.compound(IdeBorderFactory.createBorder(SideBorder.BOTTOM), JBUI.Borders.empty(8, 10, 0, 10))
add(searchField, BorderLayout.CENTER)
add(filterPanel, BorderLayout.SOUTH)
}
return searchPanel
}
protected abstract fun getShortText(searchValue: S): @Nls String
protected abstract fun createFilters(viewScope: CoroutineScope): List<JComponent>
private inner class QuickFilterButtonFactory {
fun create(viewScope: CoroutineScope, quickFilters: List<Pair<String, S>>): JComponent {
val button = InlineIconButton(AllIcons.General.Filter).apply {
border = JBUI.Borders.empty(3)
}.also {
it.actionListener = ActionListener { _ ->
showQuickFiltersPopup(it, quickFilters)
}
}
viewScope.launch {
vm.searchState.collect {
button.icon = if (it.filterCount == 0) AllIcons.General.Filter else IconWithNotifyDot(AllIcons.General.Filter)
}
}
return button
}
private fun showQuickFiltersPopup(parentComponent: JComponent, quickFilters: List<Pair<@Nls String, S>>) {
val quickFiltersActions =
quickFilters.map { (name, search) -> QuickFilterAction(name, search) } +
Separator() +
ClearFiltersAction()
JBPopupFactory.getInstance()
.createActionGroupPopup(CollaborationToolsBundle.message("review.list.filter.quick.title"), DefaultActionGroup(quickFiltersActions),
DataManager.getInstance().getDataContext(parentComponent),
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
false)
.showUnderneathOf(parentComponent)
}
private inner class QuickFilterAction(name: @Nls String, private val search: S)
: DumbAwareAction(name), Toggleable {
override fun update(e: AnActionEvent) = Toggleable.setSelected(e.presentation, vm.searchState.value == search)
override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { search }
}
private inner class ClearFiltersAction
: DumbAwareAction(CollaborationToolsBundle.message("review.list.filter.quick.clear", vm.searchState.value.filterCount)) {
override fun update(e: AnActionEvent) {
e.presentation.isEnabledAndVisible = vm.searchState.value.filterCount > 0
}
override fun actionPerformed(e: AnActionEvent) = vm.searchState.update { vm.emptySearch }
}
//TODO: request a ready-made icon from UI and also a proper icon for old UI
private inner class IconWithNotifyDot(private val originalIcon: Icon) : Icon by originalIcon {
override fun paintIcon(c: Component?, g: Graphics?, x: Int, y: Int) {
originalIcon.paintIcon(c, g, x, y)
g as Graphics2D
val dotSize = JBUIScale.scale(6)
val notifyDotShape = Ellipse2D.Float((iconWidth - dotSize).toFloat(), 0f, dotSize.toFloat(), dotSize.toFloat())
g.color = ColorUtil.fromHex("#3574F0")
g.fill(notifyDotShape)
}
}
}
} | apache-2.0 | 80bae366981ed4c1538992beeb8a92d3 | 40.146667 | 140 | 0.727921 | 4.743274 | false | false | false | false |
mdaniel/intellij-community | platform/workspaceModel/codegen/test/testData/finalProperty/before/entity.kt | 1 | 1207 | package com.intellij.workspaceModel.test.api
import com.intellij.workspaceModel.deft.api.annotations.Default
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.EntitySource
import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion
import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity
import com.intellij.workspaceModel.storage.MutableEntityStorage
import org.jetbrains.deft.ObjBuilder
import org.jetbrains.deft.Type
interface FinalFieldsEntity: WorkspaceEntity {
val descriptor: AnotherDataClass
val version: Int get() = descriptor.version
val source: Boolean get() = descriptor.source
val displayName: String? get() = descriptor.displayName
val gitUrl: String? get() = descriptor.url
val gitRevision: String? get() = descriptor.revision
fun isEditable(): Boolean {
return descriptor.source && displayName != null
}
fun isReadOnly(): Boolean {
return !isEditable() && descriptor.url != null
}
}
data class AnotherDataClass(val name: String, val version: Int, val source: Boolean, val displayName: String? = null, val url: String? = null,
val revision: String? = null) | apache-2.0 | f191eb5112ff885e561530acc7e98078 | 36.75 | 142 | 0.770505 | 4.751969 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/codeInsight/AbstractRenderingKDocTest.kt | 1 | 1371 | // 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.codeInsight
import com.intellij.testFramework.UsefulTestCase
import org.jetbrains.kotlin.idea.KotlinDocumentationProvider
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.idea.test.KotlinWithJdkAndRuntimeLightProjectDescriptor
import org.jetbrains.kotlin.test.InTextDirectivesUtils
//BUNCH 201
abstract class AbstractRenderingKDocTest : KotlinLightCodeInsightFixtureTestCase() {
override fun getProjectDescriptor() = KotlinWithJdkAndRuntimeLightProjectDescriptor.INSTANCE
protected fun doTest(path: String) {
myFixture.configureByFile(fileName())
val file = myFixture.file
val kDocProvider = KotlinDocumentationProvider()
val comments = mutableListOf<String>()
kDocProvider.collectDocComments(file) {
val rendered = kDocProvider.generateRenderedDoc(it)
if (rendered != null) {
comments.add(rendered.replace("\n", ""))
}
}
val expectedRenders = InTextDirectivesUtils.findLinesWithPrefixesRemoved(file.text, "// RENDER: ")
UsefulTestCase.assertOrderedEquals(comments, expectedRenders)
}
}
| apache-2.0 | 2db4fec64e46f79149266cb1236f9d29 | 40.545455 | 158 | 0.752735 | 5.376471 | false | true | false | false |
3sidedcube/react-native-navigation | lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/ReactViewRotationAnimator.kt | 1 | 1200 | package com.reactnativenavigation.views.element.animators
import android.animation.Animator
import android.animation.ObjectAnimator
import android.graphics.Rect
import android.view.View
import androidx.core.animation.doOnEnd
import com.facebook.react.views.view.ReactViewGroup
import com.reactnativenavigation.options.SharedElementTransitionOptions
import com.reactnativenavigation.utils.areDimensionsWithInheritedScaleEqual
import com.reactnativenavigation.utils.computeInheritedScale
import kotlin.math.roundToInt
class ReactViewRotationAnimator(from: View, to: View) : PropertyAnimatorCreator<ReactViewGroup>(from, to) {
private val fromRotation = from.rotation
private val toRotation = to.rotation
override fun shouldAnimateProperty(fromChild: ReactViewGroup, toChild: ReactViewGroup): Boolean {
return fromRotation != toRotation &&
fromChild.childCount == 0 &&
toChild.childCount == 0
}
override fun create(options: SharedElementTransitionOptions): Animator {
to.rotation = fromRotation
to.pivotX = 0f
to.pivotY = 0f
return ObjectAnimator.ofFloat(to, View.ROTATION, fromRotation, toRotation)
}
} | mit | 3bf41bd59e6dcdc0c36c1270f0dcc1ed | 39.033333 | 107 | 0.775 | 4.958678 | false | false | false | false |
loxal/FreeEthereum | free-ethereum-core/src/test/java/org/ethereum/jsontestsuite/suite/model/BlockHeaderTck.kt | 1 | 2851 | /*
* The MIT License (MIT)
*
* Copyright 2017 Alexander Orlov <[email protected]>. All rights reserved.
* Copyright (c) [2016] [ <ether.camp> ]
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package org.ethereum.jsontestsuite.suite.model
class BlockHeaderTck {
var bloom: String? = null
var coinbase: String? = null
var difficulty: String? = null
var extraData: String? = null
var gasLimit: String? = null
var gasUsed: String? = null
var hash: String? = null
var mixHash: String? = null
var nonce: String? = null
var number: String? = null
var parentHash: String? = null
var receiptTrie: String? = null
var seedHash: String? = null
var stateRoot: String? = null
var timestamp: String? = null
var transactionsTrie: String? = null
var uncleHash: String? = null
override fun toString(): String {
return "BlockHeader{" +
"bloom='" + bloom + '\'' +
", coinbase='" + coinbase + '\'' +
", difficulty='" + difficulty + '\'' +
", extraData='" + extraData + '\'' +
", gasLimit='" + gasLimit + '\'' +
", gasUsed='" + gasUsed + '\'' +
", hash='" + hash + '\'' +
", mixHash='" + mixHash + '\'' +
", nonce='" + nonce + '\'' +
", number='" + number + '\'' +
", parentHash='" + parentHash + '\'' +
", receiptTrie='" + receiptTrie + '\'' +
", seedHash='" + seedHash + '\'' +
", stateRoot='" + stateRoot + '\'' +
", timestamp='" + timestamp + '\'' +
", transactionsTrie='" + transactionsTrie + '\'' +
", uncleHash='" + uncleHash + '\'' +
'}'
}
}
| mit | 13998be9925d8b091c9c3e43225b875f | 39.728571 | 83 | 0.588215 | 4.539809 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/compiler-plugins/sam-with-receiver/maven/src/org/jetbrains/kotlin/idea/compilerPlugin/samWithReceiver/maven/SamWithReceiverMavenProjectImportHandler.kt | 1 | 2194 | // 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.compilerPlugin.samWithReceiver.maven
import org.jetbrains.idea.maven.project.MavenProject
import org.jetbrains.kotlin.idea.maven.compilerPlugin.AbstractMavenImportHandler
import org.jetbrains.kotlin.idea.compilerPlugin.CompilerPluginSetup.PluginOption
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.compilerPlugin.toJpsVersionAgnosticKotlinBundledPath
import org.jetbrains.kotlin.samWithReceiver.SamWithReceiverCommandLineProcessor
class SamWithReceiverMavenProjectImportHandler : AbstractMavenImportHandler() {
private companion object {
val ANNOTATION_PARAMETER_PREFIX = "sam-with-receiver:${SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName}="
}
override val compilerPluginId = SamWithReceiverCommandLineProcessor.PLUGIN_ID
override val pluginName = "samWithReceiver"
override val mavenPluginArtifactName = "kotlin-maven-sam-with-receiver"
override val pluginJarFileFromIdea = KotlinArtifacts.instance.samWithReceiverCompilerPlugin.toJpsVersionAgnosticKotlinBundledPath()
override fun getOptions(
mavenProject: MavenProject,
enabledCompilerPlugins: List<String>,
compilerPluginOptions: List<String>
): List<PluginOption>? {
if ("sam-with-receiver" !in enabledCompilerPlugins) {
return null
}
val annotations = mutableListOf<String>()
for ((presetName, presetAnnotations) in SamWithReceiverCommandLineProcessor.SUPPORTED_PRESETS) {
if (presetName in enabledCompilerPlugins) {
annotations.addAll(presetAnnotations)
}
}
annotations.addAll(compilerPluginOptions.mapNotNull { text ->
if (!text.startsWith(ANNOTATION_PARAMETER_PREFIX)) return@mapNotNull null
text.substring(ANNOTATION_PARAMETER_PREFIX.length)
})
return annotations.map { PluginOption(SamWithReceiverCommandLineProcessor.ANNOTATION_OPTION.optionName, it) }
}
}
| apache-2.0 | 48d40f0e9183fd59aa94012f17f95b63 | 46.695652 | 158 | 0.765725 | 5.390663 | false | false | false | false |
ngthtung2805/dalatlaptop | app/src/main/java/com/tungnui/abccomputer/activity/NotificationActivity.kt | 1 | 3955 | package com.tungnui.abccomputer.activity
import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TextView
import com.google.android.gms.ads.AdView
import com.tungnui.abccomputer.adapter.NotificationAdapter
import com.tungnui.abccomputer.data.constant.AppConstants
import com.tungnui.abccomputer.data.sqlite.NotificationDBController
import com.tungnui.abccomputer.listener.OnItemClickListener
import com.tungnui.abccomputer.model.NotificationModel
import com.tungnui.abccomputer.R
import com.tungnui.abccomputer.utils.ActivityUtils
import com.tungnui.abccomputer.utils.AdUtils
import java.util.ArrayList
class NotificationActivity : AppCompatActivity() {
private var mToolbar: Toolbar? = null
private var recyclerView: RecyclerView? = null
private var mAdapter: NotificationAdapter? = null
private var dataList: ArrayList<NotificationModel>? = null
private var emptyView: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
initVars()
initialView()
initFunctionality()
initialListener()
}
private fun initVars() {
dataList = ArrayList()
}
private fun initialView() {
setContentView(R.layout.activity_notification)
mToolbar = findViewById<View>(R.id.toolbar) as Toolbar
emptyView = findViewById<View>(R.id.emptyView) as TextView
setSupportActionBar(mToolbar)
supportActionBar?.title = getString(R.string.notifications)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setDisplayShowHomeEnabled(true)
//productList
recyclerView = findViewById<View>(R.id.recycler_view) as RecyclerView
mAdapter = NotificationAdapter(this@NotificationActivity, dataList)
recyclerView!!.layoutManager = LinearLayoutManager(this@NotificationActivity)
recyclerView!!.adapter = mAdapter
}
private fun initFunctionality() {
val notifyController = NotificationDBController(applicationContext)
notifyController.open()
dataList?.addAll(notifyController.allNotification)
notifyController.close()
if (dataList != null && !dataList!!.isEmpty()) {
emptyView?.visibility = View.GONE
mAdapter?.notifyDataSetChanged()
} else {
emptyView?.visibility = View.VISIBLE
}
}
private fun initialListener() {
mToolbar?.setNavigationOnClickListener { finish() }
mAdapter?.setItemClickListener { view, position ->
when(dataList!![position].notificationType){
AppConstants.NOTIFY_TYPE_MESSAGE ->
ActivityUtils.instance.invokeNotifyContentActivity(this@NotificationActivity,dataList!![position].title, dataList!![position].message)
AppConstants.NOTIFY_TYPE_PRODUCT->
ActivityUtils.instance.invokeProductDetails(this@NotificationActivity, dataList!![position].productId)
AppConstants.NOTIFY_TYPE_URL ->
if (dataList!![position].url != null && !dataList!![position].url.isEmpty()) {
ActivityUtils.instance.invokeWebPageActivity(this@NotificationActivity, resources.getString(R.string.app_name), dataList!![position].url)
}
}
updateStatus(dataList!![position].id)
}
}
private fun updateStatus(id: Int) {
val notifyController = NotificationDBController(applicationContext)
notifyController.open()
notifyController.updateStatus(id, true)
notifyController.close()
}
override fun onResume() {
super.onResume()
}
}
| mit | f63569bcd1389d740fd34eefb3357430 | 37.398058 | 158 | 0.708976 | 5.238411 | false | false | false | false |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/keyvalue/StorySend.kt | 1 | 1126 | package org.thoughtcrime.securesms.keyvalue
import org.thoughtcrime.securesms.database.model.DistributionListId
import org.thoughtcrime.securesms.groups.GroupId
import org.thoughtcrime.securesms.recipients.Recipient
data class StorySend(
val timestamp: Long,
val identifier: Identifier
) {
companion object {
@JvmStatic
fun newSend(recipient: Recipient): StorySend {
return if (recipient.isGroup) {
StorySend(System.currentTimeMillis(), Identifier.Group(recipient.requireGroupId()))
} else {
StorySend(System.currentTimeMillis(), Identifier.DistributionList(recipient.requireDistributionListId()))
}
}
}
sealed class Identifier {
data class Group(val groupId: GroupId) : Identifier() {
override fun matches(recipient: Recipient) = recipient.groupId.orElse(null) == groupId
}
data class DistributionList(val distributionListId: DistributionListId) : Identifier() {
override fun matches(recipient: Recipient) = recipient.distributionListId.orElse(null) == distributionListId
}
abstract fun matches(recipient: Recipient): Boolean
}
}
| gpl-3.0 | 274f0f5d4fe17aa95cc083b7e5a8bb82 | 33.121212 | 114 | 0.745115 | 4.960352 | false | false | false | false |
matt-richardson/TeamCity.Node | common/src/com/jonnyzzz/teamcity/plugins/node/common/NVMBean.kt | 2 | 1214 | /*
* Copyright 2013-2013 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.node.common
/**
* @author Eugene Petrenko ([email protected])
* Date: 16.08.13 21:42
*/
public class NVMBean {
public val NVMUsed : String = "Use_NodeJS_Install_Runner"
public val NVMAvailable : String = "node.js.nvm"
public val NVMFeatureType: String = "jonnyzzz.nvm"
public val NVMVersion : String = "version"
public val NVMSource : String = "fromSource"
public val NVMURL : String = "fromURL"
public val NVM_Creatonix : String = "https://github.com/creationix/nvm/archive/v0.7.0.zip"
//"https://github.com/creationix/nvm/archive/master.zip"
}
| apache-2.0 | c85a71f6d3e31fcfdaacb49b5c4719d5 | 35.787879 | 92 | 0.73229 | 3.667674 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database/src/main/kotlin/com/onyx/extension/IManagedEntity$Validate.kt | 1 | 1643 | package com.onyx.extension
import com.onyx.exception.AttributeNonNullException
import com.onyx.exception.AttributeSizeException
import com.onyx.exception.IdentifierRequiredException
import com.onyx.exception.OnyxException
import com.onyx.extension.common.ClassMetadata
import com.onyx.persistence.IManagedEntity
import com.onyx.persistence.annotations.values.IdentifierGenerator
import com.onyx.persistence.context.SchemaContext
/**
* Checks an entity to to see if it is valid within a context
*
* @param context Context to verify entity against
*
* @throws OnyxException The entity is invalid
* @return true if it is valid
* @since 2.0.0
*/
@Throws(OnyxException::class)
fun IManagedEntity.isValid(context:SchemaContext):Boolean {
val descriptor = descriptor(context)
descriptor.attributes.values.forEach {
val attributeValue:Any? = this[context, descriptor, it.name]
// Nullable
if(!it.isNullable && attributeValue == null) throw AttributeNonNullException(AttributeNonNullException.ATTRIBUTE_NULL_EXCEPTION, it.name)
// Size
if(it.type.isAssignableFrom(ClassMetadata.STRING_TYPE) && attributeValue != null && (attributeValue as String).length > it.size && it.size > -1)
throw AttributeSizeException(AttributeSizeException.ATTRIBUTE_SIZE_EXCEPTION, it.name)
}
// Null Identifier if not auto generated
if(descriptor.identifier!!.generator === IdentifierGenerator.NONE){
if(identifier(context) == null) throw IdentifierRequiredException(IdentifierRequiredException.IDENTIFIER_REQUIRED_EXCEPTION, descriptor.identifier!!.name)
}
return true
} | agpl-3.0 | 6bafb6ea1e7c8d6e81d39801973ddba4 | 38.142857 | 162 | 0.765064 | 4.526171 | false | false | false | false |
TeamNewPipe/NewPipe | app/src/main/java/org/schabi/newpipe/database/feed/dao/FeedDAO.kt | 1 | 6914 | package org.schabi.newpipe.database.feed.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Maybe
import org.schabi.newpipe.database.feed.model.FeedEntity
import org.schabi.newpipe.database.feed.model.FeedGroupEntity
import org.schabi.newpipe.database.feed.model.FeedLastUpdatedEntity
import org.schabi.newpipe.database.stream.StreamWithState
import org.schabi.newpipe.database.stream.model.StreamStateEntity
import org.schabi.newpipe.database.subscription.NotificationMode
import org.schabi.newpipe.database.subscription.SubscriptionEntity
import java.time.OffsetDateTime
@Dao
abstract class FeedDAO {
@Query("DELETE FROM feed")
abstract fun deleteAll(): Int
/**
* @param groupId the group id to get feed streams of; use
* [FeedGroupEntity.GROUP_ALL_ID] to not filter by group
* @param includePlayed if false, only return all of the live, never-played or non-finished
* feed streams (see `@see` items); if true no filter is applied
* @param uploadDateBefore get only streams uploaded before this date (useful to filter out
* future streams); use null to not filter by upload date
* @return the feed streams filtered according to the conditions provided in the parameters
* @see StreamStateEntity.isFinished()
* @see StreamStateEntity.PLAYBACK_FINISHED_END_MILLISECONDS
*/
@Query(
"""
SELECT s.*, sst.progress_time
FROM streams s
LEFT JOIN stream_state sst
ON s.uid = sst.stream_id
LEFT JOIN stream_history sh
ON s.uid = sh.stream_id
INNER JOIN feed f
ON s.uid = f.stream_id
LEFT JOIN feed_group_subscription_join fgs
ON (
:groupId <> ${FeedGroupEntity.GROUP_ALL_ID}
AND fgs.subscription_id = f.subscription_id
)
WHERE (
:groupId = ${FeedGroupEntity.GROUP_ALL_ID}
OR fgs.group_id = :groupId
)
AND (
:includePlayed
OR sh.stream_id IS NULL
OR sst.stream_id IS NULL
OR sst.progress_time < s.duration * 1000 - ${StreamStateEntity.PLAYBACK_FINISHED_END_MILLISECONDS}
OR sst.progress_time < s.duration * 1000 * 3 / 4
OR s.stream_type = 'LIVE_STREAM'
OR s.stream_type = 'AUDIO_LIVE_STREAM'
)
AND (
:uploadDateBefore IS NULL
OR s.upload_date IS NULL
OR s.upload_date < :uploadDateBefore
)
ORDER BY s.upload_date IS NULL DESC, s.upload_date DESC, s.uploader ASC
LIMIT 500
"""
)
abstract fun getStreams(
groupId: Long,
includePlayed: Boolean,
uploadDateBefore: OffsetDateTime?
): Maybe<List<StreamWithState>>
@Query(
"""
DELETE FROM feed WHERE
feed.stream_id IN (
SELECT s.uid FROM streams s
INNER JOIN feed f
ON s.uid = f.stream_id
WHERE s.upload_date < :offsetDateTime
)
"""
)
abstract fun unlinkStreamsOlderThan(offsetDateTime: OffsetDateTime)
@Query(
"""
DELETE FROM feed
WHERE feed.subscription_id = :subscriptionId
AND feed.stream_id IN (
SELECT s.uid FROM streams s
INNER JOIN feed f
ON s.uid = f.stream_id
WHERE s.stream_type = "LIVE_STREAM" OR s.stream_type = "AUDIO_LIVE_STREAM"
)
"""
)
abstract fun unlinkOldLivestreams(subscriptionId: Long)
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(feedEntity: FeedEntity)
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insertAll(entities: List<FeedEntity>): List<Long>
@Insert(onConflict = OnConflictStrategy.IGNORE)
internal abstract fun insertLastUpdated(lastUpdatedEntity: FeedLastUpdatedEntity): Long
@Update(onConflict = OnConflictStrategy.IGNORE)
internal abstract fun updateLastUpdated(lastUpdatedEntity: FeedLastUpdatedEntity)
@Transaction
open fun setLastUpdatedForSubscription(lastUpdatedEntity: FeedLastUpdatedEntity) {
val id = insertLastUpdated(lastUpdatedEntity)
if (id == -1L) {
updateLastUpdated(lastUpdatedEntity)
}
}
@Query(
"""
SELECT MIN(lu.last_updated) FROM feed_last_updated lu
INNER JOIN feed_group_subscription_join fgs
ON fgs.subscription_id = lu.subscription_id AND fgs.group_id = :groupId
"""
)
abstract fun oldestSubscriptionUpdate(groupId: Long): Flowable<List<OffsetDateTime>>
@Query("SELECT MIN(last_updated) FROM feed_last_updated")
abstract fun oldestSubscriptionUpdateFromAll(): Flowable<List<OffsetDateTime>>
@Query("SELECT COUNT(*) FROM feed_last_updated WHERE last_updated IS NULL")
abstract fun notLoadedCount(): Flowable<Long>
@Query(
"""
SELECT COUNT(*) FROM subscriptions s
INNER JOIN feed_group_subscription_join fgs
ON s.uid = fgs.subscription_id AND fgs.group_id = :groupId
LEFT JOIN feed_last_updated lu
ON s.uid = lu.subscription_id
WHERE lu.last_updated IS NULL
"""
)
abstract fun notLoadedCountForGroup(groupId: Long): Flowable<Long>
@Query(
"""
SELECT s.* FROM subscriptions s
LEFT JOIN feed_last_updated lu
ON s.uid = lu.subscription_id
WHERE lu.last_updated IS NULL OR lu.last_updated < :outdatedThreshold
"""
)
abstract fun getAllOutdated(outdatedThreshold: OffsetDateTime): Flowable<List<SubscriptionEntity>>
@Query(
"""
SELECT s.* FROM subscriptions s
INNER JOIN feed_group_subscription_join fgs
ON s.uid = fgs.subscription_id AND fgs.group_id = :groupId
LEFT JOIN feed_last_updated lu
ON s.uid = lu.subscription_id
WHERE lu.last_updated IS NULL OR lu.last_updated < :outdatedThreshold
"""
)
abstract fun getAllOutdatedForGroup(groupId: Long, outdatedThreshold: OffsetDateTime): Flowable<List<SubscriptionEntity>>
@Query(
"""
SELECT s.* FROM subscriptions s
LEFT JOIN feed_last_updated lu
ON s.uid = lu.subscription_id
WHERE
(lu.last_updated IS NULL OR lu.last_updated < :outdatedThreshold)
AND s.notification_mode = :notificationMode
"""
)
abstract fun getOutdatedWithNotificationMode(
outdatedThreshold: OffsetDateTime,
@NotificationMode notificationMode: Int
): Flowable<List<SubscriptionEntity>>
}
| gpl-3.0 | f9f2e30596af36f583344dbe0a2be00b | 31.308411 | 125 | 0.644779 | 4.516003 | false | false | false | false |
fvasco/pinpoi | app/src/main/java/io/github/fvasco/pinpoi/importer/AbstractImporter.kt | 1 | 2018 | package io.github.fvasco.pinpoi.importer
import android.util.Log
import io.github.fvasco.pinpoi.BuildConfig
import io.github.fvasco.pinpoi.model.Placemark
import java.io.InputStream
/**
* Abstract base importer.
* @author Francesco Vasco
*/
abstract class AbstractImporter {
var consumer: ((Placemark) -> Unit)? = null
var collectionId: Long = 0
var fileFormatFilter: FileFormatFilter = FileFormatFilter.NONE
/**
* Import data
*
* @param inputStream data source
*/
fun importPlacemarks(inputStream: InputStream) {
requireNotNull(consumer) { "No consumer" }
require(collectionId > 0) { "Collection id not valid: $collectionId" }
// do import
importImpl(inputStream)
}
fun importPlacemark(placemark: Placemark) {
val (latitude, longitude) = placemark.coordinates
if (latitude >= -90f && latitude <= 90f
&& longitude >= -180f && longitude <= 180f
) {
val name = placemark.name.trim()
var description: String = placemark.description.trim()
if (description == name) description = ""
placemark.name = name
placemark.description = description
placemark.collectionId = collectionId
if (BuildConfig.DEBUG) {
Log.d(AbstractImporter::class.java.simpleName, "importPlacemark $placemark")
}
consumer!!(placemark)
} else if (BuildConfig.DEBUG) {
Log.d(AbstractImporter::class.java.simpleName, "importPlacemark skip $placemark")
}
}
/**
* Configure importer from another
*/
fun configureFrom(importer: AbstractImporter) {
collectionId = importer.collectionId
consumer = importer.consumer
fileFormatFilter = importer.fileFormatFilter
}
/**
* Read datas, use [importPlacemark] to persistence it
* @param inputStream data source
*/
abstract fun importImpl(inputStream: InputStream)
}
| gpl-3.0 | a1f1066f195e02c16f3165d9f7847667 | 30.046154 | 93 | 0.635282 | 4.886199 | false | true | false | false |
GunoH/intellij-community | uast/uast-tests/test/org/jetbrains/uast/test/java/JavaUJumpExpressionTest.kt | 2 | 4673 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.test.java
import com.intellij.psi.JavaPsiFacade
import com.intellij.testFramework.UsefulTestCase
import com.intellij.util.asSafely
import junit.framework.TestCase
import org.jetbrains.uast.*
abstract class JavaUJumpExpressionBase : AbstractJavaUastLightTest() {
protected inline fun <reified TElement : UElement, reified TJumpFromElement> doTest(fileSource: String) {
val file = myFixture.configureByText("File.java", fileSource)
val element = file.findElementAt(myFixture.editor.caretModel.offset)?.parent?.toUElementOfType<TElement>()
?: fail("cannot find element")
UsefulTestCase.assertInstanceOf((element as? UJumpExpression)?.jumpTarget, TJumpFromElement::class.java)
}
protected inline fun <reified TElement : UJumpExpression> doTestWithNullTarget(fileSource: String) {
val file = myFixture.configureByText("File.java", fileSource)
val element = file.findElementAt(myFixture.editor.caretModel.offset)?.parent?.toUElementOfType<TElement>()
?: fail("cannot find element")
TestCase.assertNull(element.jumpTarget)
}
}
class JavaUJumpExpressionTest : JavaUJumpExpressionBase() {
fun `test break`() = doTest<UBreakExpression, UForExpression>("""
class Break {
static void a() {
while (true) {
for (int i = 0; i < 10; i++) {
brea<caret>k;
}
}
}
}
""")
fun `test break with label`() = doTest<UBreakExpression, UWhileExpression>("""
class Break {
static void a() {
a: while (true) {
for (int i = 0; i < 10; i++) {
brea<caret>k a;
}
}
}
}
""")
fun `test break in switch`() = doTest<UBreakExpression, USwitchExpression>("""
class Break {
static void a() {
while (true) {
switch (1) {
case 2: bre<caret>ak;
}
}
}
}
""")
fun `test continue`() = doTest<UContinueExpression, UForExpression>("""
class Break {
static void a() {
while (true) {
for (int i = 0; i < 10; i++) {
con<caret>tinue;
}
}
}
}
""")
fun `test continue with label`() = doTest<UContinueExpression, UWhileExpression>("""
class Break {
static void a() {
a: while (true) {
for (int i = 0; i < 10; i++) {
con<caret>tinue a;
}
}
}
}
""")
fun `test return`() = doTest<UReturnExpression, UMethod>("""
class Break {
static void a() {
ret<caret>urn;
}
}
""")
fun `test return from lambda`() = doTest<UReturnExpression, ULambdaExpression>("""
class Break {
static void a() {
Supplier a = () -> {
ret<caret>urn a;
}
}
}
""")
fun `test return from inner method`() = doTest<UReturnExpression, UMethod>("""
class Break {
static Consumer a = (b) -> {
new Object() {
Object kek() {
ret<caret>urn b;
}
};
};
}
""")
fun `test implicit return`() {
val lambda = JavaPsiFacade.getElementFactory(project).createExpressionFromText("() -> 10", null)
.toUElementOfType<ULambdaExpression>() ?: fail("cannot create lambda")
val returnExpr = (lambda.body as? UBlockExpression)?.expressions?.singleOrNull()?.asSafely<UReturnExpression>()
TestCase.assertEquals((returnExpr as? UJumpExpression)?.jumpTarget, lambda)
}
fun `test strange break`() = doTestWithNullTarget<UBreakExpression>("""
class Break {
static void a() {
while (true) {
for (int i = 0; i < 10; i++) {
a: brea<caret>k a;
}
}
}
}
""")
fun `test strange continue`() = doTestWithNullTarget<UContinueExpression>("""
class Break {
static void a() {
while (true) {
for (int i = 0; i < 10; i++) {
a: continu<caret>e a;
}
}
}
}
""")
}
class Java13UJumpExpressionTest : JavaUJumpExpressionBase() {
fun `test break in switch`() = doTest<UYieldExpression, USwitchExpression>("""
class Break {
static void a() {
while (true) {
int a = switch (1) {
case 2: yie<caret>ld 10;
default: yield 15;
}
}
}
}
""")
}
| apache-2.0 | b60a4633bab5ea3109e473efee7763f1 | 27.493902 | 140 | 0.552322 | 4.506268 | false | true | false | false |
android/compose-samples | Jetcaster/app/src/main/java/com/example/jetcaster/ui/player/PlayerViewModel.kt | 1 | 3429 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.jetcaster.ui.player
import android.net.Uri
import android.os.Bundle
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.AbstractSavedStateViewModelFactory
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.savedstate.SavedStateRegistryOwner
import com.example.jetcaster.Graph
import com.example.jetcaster.data.EpisodeStore
import com.example.jetcaster.data.PodcastStore
import java.time.Duration
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
data class PlayerUiState(
val title: String = "",
val subTitle: String = "",
val duration: Duration? = null,
val podcastName: String = "",
val author: String = "",
val summary: String = "",
val podcastImageUrl: String = ""
)
/**
* ViewModel that handles the business logic and screen state of the Player screen
*/
class PlayerViewModel(
episodeStore: EpisodeStore,
podcastStore: PodcastStore,
savedStateHandle: SavedStateHandle
) : ViewModel() {
// episodeUri should always be present in the PlayerViewModel.
// If that's not the case, fail crashing the app!
private val episodeUri: String = Uri.decode(savedStateHandle.get<String>("episodeUri")!!)
var uiState by mutableStateOf(PlayerUiState())
private set
init {
viewModelScope.launch {
val episode = episodeStore.episodeWithUri(episodeUri).first()
val podcast = podcastStore.podcastWithUri(episode.podcastUri).first()
uiState = PlayerUiState(
title = episode.title,
duration = episode.duration,
podcastName = podcast.title,
summary = episode.summary ?: "",
podcastImageUrl = podcast.imageUrl ?: ""
)
}
}
/**
* Factory for PlayerViewModel that takes EpisodeStore and PodcastStore as a dependency
*/
companion object {
fun provideFactory(
episodeStore: EpisodeStore = Graph.episodeStore,
podcastStore: PodcastStore = Graph.podcastStore,
owner: SavedStateRegistryOwner,
defaultArgs: Bundle? = null,
): AbstractSavedStateViewModelFactory =
object : AbstractSavedStateViewModelFactory(owner, defaultArgs) {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(
key: String,
modelClass: Class<T>,
handle: SavedStateHandle
): T {
return PlayerViewModel(episodeStore, podcastStore, handle) as T
}
}
}
}
| apache-2.0 | 03d87122e936724ca1cb2586ee632880 | 34.350515 | 93 | 0.678915 | 4.976778 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/fileRanking/topLevel.kt | 9 | 214 | // WITH_STDLIB
//FILE: a/a.kt
package a
val a = run {
val a = 5
val b = run {
val c = 2
}
5
}
fun x() {
println("")
}
//FILE: b/a.kt
package b
val b = 5
fun y() {
println("")
} | apache-2.0 | 777bc62c00ed9eab784ab1d143355d16 | 7.6 | 17 | 0.439252 | 2.45977 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/ui/badge/BadgeProxy.kt | 2 | 4612 | /*
* Copyright 2019 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package im.vector.ui.badge
import android.content.Context
import android.os.Build
import im.vector.Matrix
import me.leolin.shortcutbadger.ShortcutBadger
import org.matrix.androidsdk.MXDataHandler
import org.matrix.androidsdk.MXSession
import org.matrix.androidsdk.core.Log
import org.matrix.androidsdk.data.Room
import java.util.*
/**
* Manage application badge (displayed in the launcher)
*/
object BadgeProxy {
private const val LOG_TAG = "BadgeProxy"
/**
* Badge is now managed by notification channel, so no need to use compatibility library in recent versions
*
* @return true if library ShortcutBadger can be used
*/
private fun useShortcutBadger() = Build.VERSION.SDK_INT < Build.VERSION_CODES.O
/**
* Update the application badge value.
*
* @param context the context
* @param badgeValue the new badge value
*/
fun updateBadgeCount(context: Context, badgeValue: Int) {
if (!useShortcutBadger()) {
return
}
try {
ShortcutBadger.setBadge(context, badgeValue)
} catch (e: Exception) {
Log.e(LOG_TAG, "## updateBadgeCount(): Exception Msg=" + e.message, e)
}
}
/**
* Refresh the badge count for specific configurations.<br></br>
* The refresh is only effective if the device is:
* * offline * does not support FCM
* * FCM registration failed
* <br></br>Notifications rooms are parsed to track the notification count value.
*
* @param aSession session value
* @param aContext App context
*/
fun specificUpdateBadgeUnreadCount(aSession: MXSession?, aContext: Context?) {
if (!useShortcutBadger()) {
return
}
val dataHandler: MXDataHandler
// sanity check
if (null == aContext || null == aSession) {
Log.w(LOG_TAG, "## specificUpdateBadgeUnreadCount(): invalid input null values")
} else {
dataHandler = aSession.dataHandler
if (dataHandler == null) {
Log.w(LOG_TAG, "## specificUpdateBadgeUnreadCount(): invalid DataHandler instance")
} else {
if (aSession.isAlive) {
var isRefreshRequired: Boolean
val pushManager = Matrix.getInstance(aContext)!!.pushManager
// update the badge count if the device is offline, FCM is not supported or FCM registration failed
isRefreshRequired = !Matrix.getInstance(aContext)!!.isConnected
isRefreshRequired = isRefreshRequired or (null != pushManager && (!pushManager.useFcm() || !pushManager.hasRegistrationToken()))
if (isRefreshRequired) {
updateBadgeCount(aContext, dataHandler)
}
}
}
}
}
/**
* Update the badge count value according to the rooms content.
*
* @param aContext App context
* @param aDataHandler data handler instance
*/
private fun updateBadgeCount(aContext: Context?, aDataHandler: MXDataHandler?) {
if (!useShortcutBadger()) {
return
}
//sanity check
if (null == aContext || null == aDataHandler) {
Log.w(LOG_TAG, "## updateBadgeCount(): invalid input null values")
} else if (null == aDataHandler.store) {
Log.w(LOG_TAG, "## updateBadgeCount(): invalid store instance")
} else {
val roomCompleteList = aDataHandler.store?.rooms?.toList().orEmpty()
var unreadRoomsCount = 0
for (room in roomCompleteList) {
if (room.notificationCount > 0) {
unreadRoomsCount++
}
}
// update the badge counter
Log.d(LOG_TAG, "## updateBadgeCount(): badge update count=$unreadRoomsCount")
updateBadgeCount(aContext, unreadRoomsCount)
}
}
}
| apache-2.0 | 9c4f7fbd1b4cae1de624017ab62e1479 | 33.41791 | 148 | 0.617303 | 4.829319 | false | false | false | false |
aosp-mirror/platform_frameworks_support | core/ktx/src/main/java/androidx/core/util/AtomicFile.kt | 1 | 2405 | /*
* Copyright (C) 2017 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.
*/
@file:Suppress("NOTHING_TO_INLINE") // Aliases to other public API.
package androidx.core.util
import android.util.AtomicFile
import androidx.annotation.RequiresApi
import java.io.FileOutputStream
import java.nio.charset.Charset
/**
* Perform the write operations inside [block] on this file. If [block] throws an exception the
* write will be failed. Otherwise the write will be applied atomically to the file.
*/
@RequiresApi(17)
inline fun AtomicFile.tryWrite(block: (out: FileOutputStream) -> Unit) {
val stream = startWrite()
var success = false
try {
block(stream)
success = true
} finally {
if (success) {
finishWrite(stream)
} else {
failWrite(stream)
}
}
}
/**
* Sets the content of this file as an [array] of bytes.
*/
@RequiresApi(17)
fun AtomicFile.writeBytes(array: ByteArray) {
tryWrite {
it.write(array)
}
}
/**
* Sets the content of this file as [text] encoded using UTF-8 or specified [charset].
* If this file exists, it becomes overwritten.
*/
@RequiresApi(17)
fun AtomicFile.writeText(text: String, charset: Charset = Charsets.UTF_8) {
writeBytes(text.toByteArray(charset))
}
/**
* Gets the entire content of this file as a byte array.
*
* This method is not recommended on huge files. It has an internal limitation of 2 GB file size.
*/
@RequiresApi(17)
inline fun AtomicFile.readBytes(): ByteArray = readFully()
/**
* Gets the entire content of this file as a String using UTF-8 or specified [charset].
*
* This method is not recommended on huge files. It has an internal limitation of 2 GB file size.
*/
@RequiresApi(17)
fun AtomicFile.readText(charset: Charset = Charsets.UTF_8): String {
return readFully().toString(charset)
}
| apache-2.0 | e1046536a193619721fc4ef0aff38162 | 28.691358 | 97 | 0.703119 | 3.981788 | false | false | false | false |
aosp-mirror/platform_frameworks_support | core/ktx/src/main/java/androidx/core/os/PersistableBundle.kt | 1 | 3066 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.os
import android.os.Build
import android.os.PersistableBundle
import androidx.annotation.RequiresApi
/**
* Returns a new [PersistableBundle] with the given key/value pairs as elements.
*
* @throws IllegalArgumentException When a value is not a supported type of [PersistableBundle].
*/
@RequiresApi(21)
fun persistableBundleOf(vararg pairs: Pair<String, Any?>) = PersistableBundle(pairs.size).apply {
for ((key, value) in pairs) {
when (value) {
null -> putString(key, null) // Any nullable type will suffice.
// Scalars
is Boolean -> {
if (Build.VERSION.SDK_INT >= 22) {
putBoolean(key, value)
} else {
throw IllegalArgumentException("Illegal value type boolean for key \"$key\"")
}
}
is Double -> putDouble(key, value)
is Int -> putInt(key, value)
is Long -> putLong(key, value)
// References
is String -> putString(key, value)
// Scalar arrays
is BooleanArray -> {
if (Build.VERSION.SDK_INT >= 22) {
putBooleanArray(key, value)
} else {
throw IllegalArgumentException("Illegal value type boolean[] for key \"$key\"")
}
}
is DoubleArray -> putDoubleArray(key, value)
is IntArray -> putIntArray(key, value)
is LongArray -> putLongArray(key, value)
// Reference arrays
is Array<*> -> {
val componentType = value::class.java.componentType
@Suppress("UNCHECKED_CAST") // Checked by reflection.
when {
String::class.java.isAssignableFrom(componentType) -> {
putStringArray(key, value as Array<String>)
}
else -> {
val valueType = componentType.canonicalName
throw IllegalArgumentException(
"Illegal value array type $valueType for key \"$key\"")
}
}
}
else -> {
val valueType = value.javaClass.canonicalName
throw IllegalArgumentException("Illegal value type $valueType for key \"$key\"")
}
}
}
}
| apache-2.0 | fb4ddc075c039cd9ec5fa2919d3ce966 | 35.939759 | 99 | 0.562622 | 5.12709 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/rest/resource/RestResourceNode.kt | 1 | 35195 | package org.evomaster.core.problem.rest.resource
import org.evomaster.core.Lazy
import org.evomaster.core.database.DbAction
import org.evomaster.core.problem.rest.*
import org.evomaster.core.problem.rest.param.BodyParam
import org.evomaster.core.problem.api.service.param.Param
import org.evomaster.core.problem.enterprise.EnterpriseActionGroup
import org.evomaster.core.problem.rest.param.PathParam
import org.evomaster.core.problem.rest.resource.dependency.*
import org.evomaster.core.problem.util.ParamUtil
import org.evomaster.core.problem.rest.util.ParserUtil
import org.evomaster.core.problem.util.RestResourceTemplateHandler
import org.evomaster.core.search.ActionFilter
import org.evomaster.core.search.ActionResult
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.ObjectGene
import org.evomaster.core.search.gene.sql.SqlForeignKeyGene
import org.evomaster.core.search.gene.sql.SqlPrimaryKeyGene
import org.evomaster.core.search.service.Randomness
import org.slf4j.Logger
import org.slf4j.LoggerFactory
/**
* @property path resource path
* @property actions actions under the resource, with references of tables
* @property initMode configurable option to init resource with additional info, e.g., related tables
* @property employNLP specified whether to employ natural language parser
*/
open class RestResourceNode(
val path : RestPath,
val actions: MutableList<RestCallAction> = mutableListOf(),
val initMode : InitMode,
val employNLP : Boolean
) {
companion object {
private const val PROB_EXTRA_PATCH = 0.8
val log: Logger = LoggerFactory.getLogger(RestResourceNode::class.java)
}
/**
* key is original text of the token
* value is PathRToken which contains more analysis info about the original text
*/
private val tokens : MutableMap<String, PathRToken> = mutableMapOf()
/**
* segments of a path
* since a token may be a combined word, the word can be separator by processing text analysis,
* the [segments] can be a flatten list of words for the path (at index 1) or a list of original tokens (at index 0).
*/
private val segments : MutableList<List<String>> = mutableListOf()
init {
when(initMode){
InitMode.WITH_TOKEN, InitMode.WITH_DERIVED_DEPENDENCY, InitMode.WITH_DEPENDENCY ->{
if(path.getNonParameterTokens().isNotEmpty()){
tokens.clear()
ParserUtil.parsePathTokens(this.path, tokens, employNLP && initMode != InitMode.WITH_DEPENDENCY)
}
initSegments()
}
else ->{
//do nothing
}
}
}
/**
* [ancestors] is ordered, first is closest ancestor, and last is deepest one.
*/
private val ancestors : MutableList<RestResourceNode> = mutableListOf()
/**
* possible solutions to prepare resources
*/
private val creations : MutableList<CreationChain> = mutableListOf()
/**
* key is id of param which is [getLastTokensOfPath] + [Param.name]
* value is detailed info [ParamInfo] including
* e.g., whether the param is required to be bound with existing resource (i.e., POST action or table),
*/
val paramsInfo : MutableMap<String, ParamInfo> = mutableMapOf()
/**
* collect related tables
*/
val resourceToTable : ResourceRelatedToTable = ResourceRelatedToTable(path.toString())
/**
* HTTP methods under the resource, including possible POST in its ancestors'
* last means if there are post actions in its ancestors
*/
private val verbs : Array<Boolean> = Array(RestResourceTemplateHandler.getSizeOfHandledVerb() + 1){false}
/**
* key is template with string format
* value is template info
*/
private val templates : MutableMap<String, CallsTemplate> = mutableMapOf()
/**
* In REST, params of the action might be modified, e.g., for WebRequest
* In this case, we modify the [actions] with updated action with new params if there exist,
* and backup its original form with [originalActions]
*/
private val originalActions : MutableList<RestCallAction> = mutableListOf()
/**
* this init occurs after actions and ancestors are set up
*/
fun init(){
initVerbs()
initCreationPoints()
when(initMode){
InitMode.WITH_TOKEN, InitMode.WITH_DERIVED_DEPENDENCY, InitMode.WITH_DEPENDENCY -> initParamInfo()
else -> { }
}
}
/**
* init ancestors of [this] resource node
*/
fun initAncestors(resources : List<RestResourceNode>){
resources.forEach {r ->
if(!r.path.isEquivalent(this.path) && r.path.isAncestorOf(this.path))
ancestors.add(r)
}
}
/**
* @return resource node based on [path]
*/
fun getResourceNode(path: RestPath) : RestResourceNode?{
if (path.toString() == path.toString()) return this
return ancestors.find { it.path.toString() == path.toString() }
}
/**
* @return mutable genes in [dbactions] and they do not bind with rest actions.
*/
fun getMutableSQLGenes(dbactions: List<DbAction>, template: String, is2POST : Boolean) : List<out Gene>{
val related = getPossiblyBoundParams(template, is2POST).map {
resourceToTable.paramToTable[it.key]
}
return dbactions.filterNot { it.representExistingData }.flatMap { db->
val exclude = related.flatMap { r-> r?.getRelatedColumn(db.table.name)?.toList()?:listOf() }
db.seeGenesForInsertion(exclude)
}.filter{it.isMutable() && it !is SqlForeignKeyGene && it !is SqlPrimaryKeyGene}
}
/**
* @return mutable genes in [actions] which perform action on current [this] resource node
* with [callsTemplate] template, e.g., POST-GET
*/
private fun getMutableRestGenes(actions: List<RestCallAction>, template: String) : List<out Gene>{
if (!RestResourceTemplateHandler.isNotSingleAction(template)) return actions.flatMap(RestCallAction::seeTopGenes).filter(Gene::isMutable)
val missing = getPossiblyBoundParams(template, false)
val params = mutableListOf<Param>()
(actions.indices).forEach { i ->
val a = actions[i]
if (i != actions.size-1 && (i == 0 || a.verb == HttpVerb.POST)) {
params.addAll(a.parameters)
} else{
//add the parameters which does not bind with POST if exist
params.addAll(a.parameters.filter { p->
missing.none { m->
m.key == getParamId(a.parameters, p)
}
})
}
}
return params.flatMap(Param::seeGenes).filter(Gene::isMutable)
}
private fun initVerbs(){
actions.forEach { a->
RestResourceTemplateHandler.getIndexOfHttpVerb(a.verb).let {
if(it == -1)
throw IllegalArgumentException("cannot handle the action with ${a.verb}")
else
verbs[it] = true
}
}
verbs[verbs.size - 1] = verbs[RestResourceTemplateHandler.getIndexOfHttpVerb(HttpVerb.POST)]
if (!verbs[verbs.size - 1]){
if(ancestors.isNotEmpty())
verbs[verbs.size - 1] = ancestors.any { a -> a.actions.any { ia-> ia.verb == HttpVerb.POST } }
}
RestResourceTemplateHandler.initSampleSpaceOnlyPOST(verbs, templates)
assert(templates.isNotEmpty())
}
//if only get
fun isIndependent() : Boolean{
return templates.all { it.value.independent } && (creations.none { c->c.isComplete() } && resourceToTable.paramToTable.isEmpty())
}
// if only post, the resource does not contain any independent action
fun hasIndependentAction() : Boolean{
return (1 until (verbs.size - 1)).find { verbs[it]} != null
}
/************************** creation manage*********************************/
/**
* @return related table for creating resource for [this] node with sql
*/
fun getSqlCreationPoints() : List<String>{
if (resourceToTable.confirmedSet.isNotEmpty()) return resourceToTable.confirmedSet.keys.toList()
return resourceToTable.derivedMap.keys.toList()
}
/**
* @return whether there exist POST action (either from [this] node or its [ancestors]) to create the resource
*/
fun hasPostCreation() = creations.any { it is PostCreationChain && it.actions.isNotEmpty() } || verbs.first()
private fun initCreationPoints(){
val postCreation = PostCreationChain(mutableListOf())
val posts = actions.filter { it.verb == HttpVerb.POST}
val post : RestCallAction? = when {
posts.isEmpty() -> {
chooseClosestAncestor(path, listOf(HttpVerb.POST))
}
posts.size == 1 -> {
posts[0]
}
else -> null
}?.copy() as? RestCallAction
if(post != null){
postCreation.actions.add(0, post)
if ((post).path.hasVariablePathParameters() &&
(!post.path.isLastElementAParameter()) ||
post.path.getVariableNames().size >= 2) {
nextCreationPoints(post.path, postCreation)
}else
postCreation.confirmComplete()
}else{
if(path.hasVariablePathParameters()) {
postCreation.confirmIncomplete(path.toString())
}else
postCreation.confirmComplete()
}
if (postCreation.actions.isNotEmpty())
creations.add(postCreation)
}
private fun nextCreationPoints(path:RestPath, postCreationChain: PostCreationChain){
val post = chooseClosestAncestor(path, listOf(HttpVerb.POST))?.copy() as? RestCallAction
if(post != null){
postCreationChain.actions.add(0, post)
if (post.path.hasVariablePathParameters() &&
(!post.path.isLastElementAParameter()) ||
post.path.getVariableNames().size >= 2) {
nextCreationPoints(post.path, postCreationChain)
}else
postCreationChain.confirmComplete()
}else{
postCreationChain.confirmIncomplete(path.toString())
}
}
private fun getCreation(predicate: (CreationChain) -> Boolean) : CreationChain?{
return creations.find(predicate)
}
fun getPostChain() : PostCreationChain?{
return getCreation { creationChain : CreationChain -> (creationChain is PostCreationChain) }?.run {
this as PostCreationChain
}
}
/***********************************************************/
/**
* generated another resource calls which differs from [calls]
*/
fun generateAnother(calls : RestResourceCalls, randomness: Randomness, maxTestSize: Int) : RestResourceCalls?{
val current = calls.template?.template?: RestResourceTemplateHandler.getStringTemplateByActions(calls.seeActions(ActionFilter.NO_SQL).filterIsInstance<RestCallAction>())
val rest = templates.filter { it.value.template != current}
if(rest.isEmpty()) return null
val selected = randomness.choose(rest.keys)
return createRestResourceCallBasedOnTemplate(selected,randomness, maxTestSize)
}
/**
* @return a number of dependent templates in [this] resource node
*/
fun numOfDepTemplate() : Int{
return templates.values.count { !it.independent }
}
/**
* @return a number of templates in [this] resource node
*/
fun numOfTemplates() : Int{
return templates.size
}
/**
* @return a rest resource call at random
*/
fun randomRestResourceCalls(randomness: Randomness, maxTestSize: Int): RestResourceCalls{
val randomTemplates = templates.filter { e->
e.value.size in 1..maxTestSize
}.map { it.key }
if(randomTemplates.isEmpty()) return sampleOneAction(null, randomness)
return createRestResourceCallBasedOnTemplate(randomness.choose(randomTemplates), randomness, maxTestSize)
}
/**
* sample an independent rest resource call, i.e., with an independent template
*/
fun sampleIndResourceCall(randomness: Randomness, maxTestSize: Int) : RestResourceCalls{
selectTemplate({ call : CallsTemplate -> call.independent || (call.template == HttpVerb.POST.toString() && call.size > 1)}, randomness)?.let {
return createRestResourceCallBasedOnTemplate(it.template, randomness, maxTestSize)
}
return createRestResourceCallBasedOnTemplate(HttpVerb.POST.toString(), randomness,maxTestSize)
}
/**
* sample a rest resource with one action based on the specified [verb]
* if [verb] is null, select an action at random from available [actions] in this node
*/
fun sampleOneAction(verb : HttpVerb? = null, randomness: Randomness) : RestResourceCalls{
val al = if(verb != null) getActionByHttpVerb(actions, verb) else randomness.choose(actions)
return sampleOneAction(al!!.copy() as RestCallAction, randomness)
}
/**
* sample a rest resource call with given [action].
* The return action is initialized
*/
fun sampleOneAction(action : RestCallAction, randomness: Randomness) : RestResourceCalls{
val copy = action.copy() as RestCallAction
if(copy.isInitialized()){
copy.randomize(randomness,false)
} else {
copy.doInitialize(randomness)
}
val template = templates[copy.verb.toString()]
?: throw IllegalArgumentException("${copy.verb} is not one of templates of ${this.path}")
val call = RestResourceCalls(template, this, mutableListOf(EnterpriseActionGroup(copy)))
if(action.verb == HttpVerb.POST){
getCreation { c : CreationChain -> (c is PostCreationChain) }.let {
if(it != null && (it as PostCreationChain).actions.size == 1 && it.isComplete()){
call.status = ResourceStatus.CREATED_REST
}else{
call.status = ResourceStatus.NOT_FOUND_DEPENDENT
}
}
}else
call.status = ResourceStatus.NOT_NEEDED
return call
}
/**
* sample a rest resource call
* @param randomness
* @param maxTestSize specified the max size of rest actions in this call
* @param prioriDependent specified whether it is perferred to sample an independent call
* @param prioriIndependent specified whether it is perferred to sample a dependent call
*/
fun sampleAnyRestResourceCalls(randomness: Randomness, maxTestSize: Int, prioriIndependent : Boolean = false, prioriDependent : Boolean = false) : RestResourceCalls{
if (maxTestSize < 1 && prioriDependent == prioriIndependent && prioriDependent){
throw IllegalArgumentException("unaccepted args")
}
val fchosen = templates.filter { it.value.size <= maxTestSize }
if(fchosen.isEmpty())
return sampleOneAction(null,randomness)
val chosen =
if (prioriDependent) fchosen.filter { !it.value.independent }
else if (prioriIndependent) fchosen.filter { it.value.independent }
else fchosen
if (chosen.isEmpty())
return createRestResourceCallBasedOnTemplate(randomness.choose(fchosen).template,randomness, maxTestSize)
return createRestResourceCallBasedOnTemplate(randomness.choose(chosen).template,randomness, maxTestSize)
}
/**
* sample a resource call with the specified [template]
*/
fun sampleRestResourceCalls(template: String, randomness: Randomness, maxTestSize: Int) : RestResourceCalls{
assert(maxTestSize > 0)
return createRestResourceCallBasedOnTemplate(template,randomness, maxTestSize)
}
/**
* @return creation chain with POST
*/
fun genPostChain(randomness: Randomness, maxTestSize: Int) : RestResourceCalls?{
val template = templates["POST"]?:
return null
return createRestResourceCallBasedOnTemplate(template.template, randomness, maxTestSize)
}
private fun handleHeadLocation(actions: List<RestCallAction>) : RestCallAction{
if (actions.size == 1) return actions.first()
(1 until actions.size).forEach { i->
handleHeaderLocation(actions[i-1], actions[i])
}
return actions.last()
}
private fun handleHeaderLocation(post: RestCallAction, target: RestCallAction){
/*
Once the POST is fully initialized, need to fix
links with target
*/
if (!post.path.isEquivalent(target.path)) {
/*
eg
POST /x
GET /x/{id}
*/
post.saveLocation = true
target.locationId = post.path.lastElement()
} else {
/*
eg
POST /x
POST /x/{id}/y
GET /x/{id}/y
*/
//not going to save the position of last POST, as same as target
post.saveLocation = false
// the target (eg GET) needs to use the location of first POST, or more correctly
// the same location used for the last POST (in case there is a deeper chain)
target.locationId = post.locationId
}
}
/**
* create rest resource call based on the specified [template]
*/
fun createRestResourceCallBasedOnTemplate(template: String, randomness: Randomness, maxTestSize: Int): RestResourceCalls{
if(!templates.containsKey(template))
throw IllegalArgumentException("$template does not exist in $path")
val ats = RestResourceTemplateHandler.parseTemplate(template)
// POST-*, *
val results = mutableListOf<RestCallAction>()
var status = ResourceStatus.NOT_NEEDED
val first = ats.first()
var lastPost:RestCallAction? = null
if (first == HttpVerb.POST){
val post = getPostChain()
if (post == null)
status = ResourceStatus.NOT_FOUND
else{
results.addAll(post.createPostChain(randomness))
// handle header location
lastPost = handleHeadLocation(results)
if (!post.isComplete())
status = ResourceStatus.NOT_FOUND_DEPENDENT
else{
status = ResourceStatus.CREATED_REST
}
}
}else{
results.add(createActionByVerb(first, randomness))
}
if (ats.size == 2){
val action = createActionByVerb(ats[1], randomness)
if (lastPost != null)
handleHeaderLocation(lastPost, action)
results.add(action)
}else if (ats.size > 2){
throw IllegalStateException("the size of action with $template should be less than 2, but it is ${ats.size}")
}
//append extra patch
if (ats.last() == HttpVerb.PATCH && results.size +1 <= maxTestSize && randomness.nextBoolean(PROB_EXTRA_PATCH)){
val second = results.last().copy() as RestCallAction
if (lastPost != null)
handleHeaderLocation(lastPost, second)
results.add(second)
}
if (results.size > maxTestSize){
log.info("the size (${results.size}) of actions exceeds the max size ($maxTestSize) in resource node $path")
val removeFirst = results.size - maxTestSize
results.drop(removeFirst)
status = ResourceStatus.NOT_ENOUGH_LENGTH
}
//TODO unsure about this one
results.forEach { if(!it.isInitialized()) it.doInitialize(randomness) }
return RestResourceCalls(
templates[template]!!,
this,
results.map { EnterpriseActionGroup(it) }.toMutableList(),
withBinding= true,
randomness = randomness
).apply { this.status = status }
}
private fun createActionByVerb(verb : HttpVerb, randomness: Randomness) : RestCallAction{
val action = (getActionByHttpVerb(actions, verb)
?:throw IllegalStateException("cannot get $verb action in the resource $path"))
.copy() as RestCallAction
if(action.isInitialized())
action.randomize(randomness, false)
else
action.doInitialize(randomness)
return action
}
private fun templateSelected(callsTemplate: CallsTemplate){
templates.getValue(callsTemplate.template).times += 1
}
private fun selectTemplate(predicate: (CallsTemplate) -> Boolean, randomness: Randomness, chosen : Map<String, CallsTemplate>?=null, chooseLessVisit : Boolean = false) : CallsTemplate?{
val ts = if(chosen == null) templates.filter { predicate(it.value) } else chosen.filter { predicate(it.value) }
if(ts.isEmpty())
return null
val template = if(chooseLessVisit) ts.asSequence().sortedBy { it.value.times }.first().value
else randomness.choose(ts.values)
templateSelected(template)
return template
}
private fun getActionByHttpVerb(actions : List<RestCallAction>, verb : HttpVerb) : RestCallAction? {
return actions.find { a -> a.verb == verb }
}
private fun chooseLongestPath(actions: List<RestCallAction>, randomness: Randomness? = null): RestCallAction {
if (actions.isEmpty()) {
throw IllegalArgumentException("Cannot choose from an empty collection")
}
val candidates = ParamUtil.selectLongestPathAction(actions)
if(randomness == null){
return candidates.first()
}else
return randomness.choose(candidates).copy() as RestCallAction
}
private fun chooseClosestAncestor(path: RestPath, verbs: List<HttpVerb>): RestCallAction? {
val ar = if(path.toString() == this.path.toString()){
this
}else{
ancestors.find { it.path.toString() == path.toString() }
}
ar?.let{
val others = hasWithVerbs(it.ancestors.flatMap { it.actions }, verbs)
if(others.isEmpty()) return null
return chooseLongestPath(others)
}
return null
}
private fun hasWithVerbs(actions: List<RestCallAction>, verbs: List<HttpVerb>): List<RestCallAction> {
return actions.filter { a ->
verbs.contains(a.verb)
}
}
/********************** utility *************************/
/**
* during the search, params of the Rest Action might be updated,
* this method is to update [actions] in this node based on the updated [action]
*/
open fun updateActionsWithAdditionalParams(action: RestCallAction){
val org = actions.find { it.verb == action.verb }
org?:throw IllegalStateException("cannot find the action (${action.getName()}) in the node $path")
if (action.parameters.size > org.parameters.size){
originalActions.add(org)
actions.remove(org)
val example = action.copy() as RestCallAction
example.resetLocalId()
example.resetProperties()
actions.add(example)
}
}
/**
* @return whether the [text] is part of static tokens in the path of [this] resource node
*/
fun isPartOfStaticTokens(text : String) : Boolean{
return tokens.any { token ->
token.equals(text)
}
}
/**
* @return derived tables
*/
fun getDerivedTables() : Set<String> = resourceToTable.derivedMap.flatMap { it.value.map { m->m.targetMatched } }.toHashSet()
/**
* @return is any POST, GET, PATCH, DELETE, PUT action?
*/
fun isAnyAction() : Boolean{
verbs.forEach {
if (it) return true
}
return false
}
/**
* @return name of the resource node
*/
fun getName() : String = path.toString()
/**
* @return tokens map
*/
fun getTokenMap() : Map<String, PathRToken> = tokens.toMap()
/**
* @return flatten tokens
*/
fun getFlatViewOfTokens(excludeStar : Boolean = true) : List<PathRToken>
= tokens.values.filter { !excludeStar || !it.isStar()}.flatMap { p -> if(p.subTokens.isNotEmpty()) p.subTokens else mutableListOf(p) }.toList()
/******************** manage param *************************/
/**
* @return param id of [param] with given [params]
*/
fun getParamId(params: List<Param>, param : Param) : String = "${param::class.java.simpleName}:${getParamName(params, param)}"
private fun getParamName(params: List<Param>, param : Param) : String = ParamUtil.appendParam(getSegment(false, params, param), param.name)
/*
e.g., /A/{a}/B/c/{b} return B@c
*/
private fun getLastSegment() : String = if(tokens.isNotEmpty()) tokens.values.last().segment else ""
private fun getLastSegment(flatten : Boolean) : String {
if(tokens.isEmpty()) return ""
return getSegment(flatten, tokens.values.last())
}
private fun getSegment(flatten : Boolean, level: Int) : String{
if(tokens.isEmpty()) return ""
val target = tokens.values.find { it.level == level }?:tokens.values.last()
return getSegment(flatten, target)
}
private fun getSegment(flatten : Boolean, target: PathRToken) : String{
if (!flatten) return target.segment
val nearLevel = target.nearestParamLevel
val array = tokens.values.filter { it.level > nearLevel && (if(target.isParameter) it.level < target.level else it.level <= target.level)}
.flatMap { if(it.subTokens.isNotEmpty()) it.subTokens.map { s->s.getKey() } else mutableListOf(it.getKey()) }.toTypedArray()
return ParamUtil.generateParamId(array)
}
private fun getParamLevel(params: List<Param>, param: Param) : Int{
if (param !is PathParam) return tokens.size
tokens.values.filter { it.isParameter && it.originalText.equals(param.name, ignoreCase = true) }.let {
if(it.isEmpty()){
//log.warn(("cannot find the path param ${param.name} in the path of the resource ${getName()}"))
if(params.any { p-> param.name.equals(p.name, ignoreCase = true) }) return tokens.size
}
if(it.size == 1)
return it.first().level
val index = params.filter { p->p.name == param.name }.indexOf(param)
return it[index].level
}
}
private fun getSegment(flatten: Boolean, params: List<Param>, param: Param) : String{
val level = getParamLevel(params, param)
return getSegment(flatten, level)
}
/**
* @return all segments of the path
* @param flatten specified whether to return flatten segments or not
*/
fun getAllSegments(flatten: Boolean) : List<String>{
assert(segments.size == 2)
return if(flatten) segments[1] else segments[0]
}
private fun initSegments(){
val levels = mutableSetOf<Int>()
tokens.values.filter { it.isParameter }.forEach { levels.add(it.level) }
if (!path.isLastElementAParameter()) levels.add(tokens.size)
segments.add(0, levels.toList().sorted().map { getSegment(false, it) })
segments.add(1, levels.toList().sorted().map { getSegment(true, it) })
assert(segments.size == 2)
}
/**
* @return reference types in [this] resource node
*/
fun getRefTypes() : Set<String>{
return paramsInfo.filter { it.value.referParam is BodyParam && it.value.referParam.gene is ObjectGene && (it.value.referParam.gene as ObjectGene).refType != null}.map {
((it.value.referParam as BodyParam).gene as ObjectGene).refType!!
}.toSet()
}
/**
* @return is any parameter different with the given [action]?
* Note that here the difference does not mean the value, and it means e.g., whether there exist a new parameter
*/
fun anyParameterChanged(action : RestCallAction) : Boolean{
val target = actions.find { it.getName() == action.getName() }
?: throw IllegalArgumentException("cannot find the action ${action.getName()} in the resource ${getName()}")
return action.parameters.size != target.parameters.size
}
/**
* @return whether there exists any additional parameters by comparing with [action]?
*/
fun updateAdditionalParams(action: RestCallAction) : Map<String, ParamInfo>?{
(actions.find { it.getName() == action.getName() }
?: throw IllegalArgumentException("cannot find the action ${action.getName()} in the resource ${getName()}")) as RestCallAction
val additionParams = action.parameters.filter { p-> paramsInfo[getParamId(action.parameters, p)] == null}
if(additionParams.isEmpty()) return null
return additionParams.map { p-> Pair(getParamId(action.parameters, p), initParamInfo(action.verb, action.parameters, p)) }.toMap()
}
/**
* update param info of [param] based on [action] and [param]
*/
fun updateAdditionalParam(action: RestCallAction, param: Param) : ParamInfo{
return initParamInfo(action.verb, action.parameters, param).also { it.fromAdditionInfo = true }
}
private fun initParamInfo(){
paramsInfo.clear()
/*
parameter that is required to bind with post action, or row of tables
1) path parameter in the middle of the path, i.e., /A/{a}/B/{b}, {a} is required to bind
2) GET, DELETE, PATCH, PUT(-prob), if the parameter refers to "id", it is required to bind, in most case, the parameter is either PathParam or QueryParam
3) other parameter, it is not necessary to bind, but it helps if it is bound.
e.g., Request to get a list of data whose value is less than "parameter", if bind with an existing data, the requests make more sentence than a random data
*/
if (tokens.isEmpty()) return
actions.forEach { a ->
a.parameters.forEach{p->
initParamInfo(a.verb, a.parameters, p)
}
}
}
private fun initParamInfo(verb: HttpVerb, params: List<Param>, param: Param) : ParamInfo{
val key = getParamId(params,param)
val segment = getSegment(flatten = true, params = params,param = param)
val level = getAllSegments(true).indexOf(segment)
val doesReferToOther = when(param){
/*
if has POST, ignore the last path param, otherwise all path param
*/
is PathParam->{
!verbs[RestResourceTemplateHandler.getIndexOfHttpVerb(HttpVerb.POST)] || getParamLevel(params, param) < tokens.size - 1
}else->{
false
}
}
val paramInfo = paramsInfo.getOrPut(key){
ParamInfo(param.name, key, segment, level, param, doesReferToOther)
}
paramInfo.involvedAction.add(verb)
return paramInfo
}
/**
* @return params in a [RestResourceCalls] that are not bounded with POST actions if there exist based on the template [actionTemplate]
*
*/
open fun getPossiblyBoundParams(actionTemplate: String, withSql : Boolean) : List<ParamInfo>{
val actions = RestResourceTemplateHandler.parseTemplate(actionTemplate)
Lazy.assert {
actions.isNotEmpty()
}
when(actions[0]){
HttpVerb.POST->{
if (withSql) return paramsInfo.values.toList()
return paramsInfo.values.filter { it.doesReferToOther }
}
HttpVerb.PATCH, HttpVerb.PUT->{
return paramsInfo.values.filter { it.involvedAction.contains(actions[0]) && (it.referParam is PathParam || it.name.toLowerCase().contains("id"))}
}
HttpVerb.GET, HttpVerb.DELETE->{
return paramsInfo.values.filter { it.involvedAction.contains(actions[0]) }
}
else ->{
return listOf()
}
}
}
/**
* @return template based on the [key]
*/
fun getTemplate(key: String) : CallsTemplate{
if (templates.containsKey(key)) return templates.getValue(key)
throw IllegalArgumentException("cannot find $key template in the node $path")
}
/**
* @return all templates
*/
fun getTemplates() : Map<String, CallsTemplate> = templates.toMap()
/**
* collect feedbacks of prepared resources based on the execution
*/
fun confirmFailureCreationByPost(calls: RestResourceCalls, action: RestCallAction, result: ActionResult){
if (result !is RestCallResult) return
val fail = action.verb.run { this == HttpVerb.POST || this == HttpVerb.PUT} &&
calls.status == ResourceStatus.CREATED_REST && result.getStatusCode().run { this !in 200..299}
if (fail && creations.isNotEmpty()){
creations.filter { it is PostCreationChain && calls.seeActions(ActionFilter.NO_SQL).map { a->a.getName() }.containsAll(it.actions.map { a-> a.getName() }) }.apply {
if (size == 1)
(first() as PostCreationChain).confirmFailure()
}
}
}
override fun toString(): String {
return getName()
}
}
enum class InitMode{
NONE,
WITH_TOKEN,
/**
* [WITH_DERIVED_DEPENDENCY] subsume [WITH_TOKEN]
*/
WITH_DERIVED_DEPENDENCY,
WITH_DEPENDENCY
}
/**
* extract info for a parm
*
* @property name a name of param
* @property key is generated based on [getParamId]
* @property preSegment refers to the segment of the param in the path
* @property segmentLevel refers to the level of param
* @property referParam refers to the instance of Param in the cluster
* @property doesReferToOther indicates whether the param is required to refer to a resource,
* e.g., GET /foo/{id}, with GET, {id} refers to a resource which cannot be created by the current action
* @property involvedAction indicates the actions which exists such param,
* e.g., GET, PATCH might have the same param named id
* @property fromAdditionInfo indicates whether the param is added later,
* e.g., during the search
*/
data class ParamInfo(
val name : String,
val key : String,
val preSegment : String, //by default is flatten segment
val segmentLevel : Int,
val referParam : Param,
val doesReferToOther : Boolean,
val involvedAction : MutableSet<HttpVerb> = mutableSetOf(),
var fromAdditionInfo : Boolean = false
) | lgpl-3.0 | 5ed879f7f754bc1a83d7e507624d5f37 | 37.804851 | 189 | 0.622958 | 4.724161 | false | false | false | false |
RocketChat/Rocket.Chat.Android | suggestions/src/main/java/chat/rocket/android/suggestions/ui/PopupRecyclerView.kt | 2 | 1419 | package chat.rocket.android.suggestions.ui
import android.content.Context
import android.util.AttributeSet
import android.util.DisplayMetrics
import android.view.WindowManager
import androidx.recyclerview.widget.RecyclerView
import chat.rocket.android.suggestions.R
internal class PopupRecyclerView : RecyclerView {
private var displayWidth: Int = 0
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
context,
attrs,
defStyle
) {
val wm = context.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val display = wm.defaultDisplay
val size = DisplayMetrics()
display.getMetrics(size)
val screenWidth = size.widthPixels
displayWidth = screenWidth
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
val hSpec = MeasureSpec.makeMeasureSpec(
resources.getDimensionPixelSize(
R.dimen.popup_max_height
), MeasureSpec.AT_MOST
)
val wSpec = MeasureSpec.makeMeasureSpec(displayWidth, MeasureSpec.EXACTLY)
super.onMeasure(wSpec, hSpec)
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
super.onLayout(changed, l + 40, t, r - 40, b)
}
}
| mit | bb18348f9e8f7e399b997a0bbc28937d | 33.609756 | 82 | 0.684989 | 4.533546 | false | false | false | false |
premnirmal/StockTicker | app/src/main/kotlin/com/github/premnirmal/ticker/base/BaseGraphActivity.kt | 1 | 4810 | package com.github.premnirmal.ticker.base
import android.graphics.Color
import android.os.Build
import android.view.View
import androidx.core.content.ContextCompat
import androidx.viewbinding.ViewBinding
import com.github.mikephil.charting.charts.LineChart
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.github.mikephil.charting.data.LineData
import com.github.mikephil.charting.data.LineDataSet
import com.github.premnirmal.ticker.model.HistoryProvider.Range
import com.github.premnirmal.ticker.network.data.DataPoint
import com.github.premnirmal.ticker.network.data.Quote
import com.github.premnirmal.ticker.ui.DateAxisFormatter
import com.github.premnirmal.ticker.ui.HourAxisFormatter
import com.github.premnirmal.ticker.ui.MultilineXAxisRenderer
import com.github.premnirmal.ticker.ui.TextMarkerView
import com.github.premnirmal.ticker.ui.ValueAxisFormatter
import com.github.premnirmal.tickerwidget.R
abstract class BaseGraphActivity<T : ViewBinding> : BaseActivity<T>() {
protected var dataPoints: List<DataPoint>? = null
protected abstract var range: Range
protected fun setupGraphView() {
val graphView: LineChart = findViewById(R.id.graphView)
graphView.isDoubleTapToZoomEnabled = false
graphView.axisLeft.setDrawGridLines(false)
graphView.axisLeft.setDrawAxisLine(false)
graphView.axisLeft.isEnabled = false
graphView.axisRight.setDrawGridLines(false)
graphView.axisRight.setDrawAxisLine(true)
graphView.axisRight.isEnabled = true
graphView.xAxis.setDrawGridLines(false)
graphView.setXAxisRenderer(
MultilineXAxisRenderer(
graphView.viewPortHandler, graphView.xAxis,
graphView.getTransformer(YAxis.AxisDependency.RIGHT)
)
)
graphView.extraBottomOffset = resources.getDimension(R.dimen.graph_bottom_offset)
graphView.legend.isEnabled = false
graphView.description = null
val colorAccent = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
ContextCompat.getColor(this, android.R.color.system_accent1_600)
} else {
ContextCompat.getColor(this, R.color.accent_fallback)
}
graphView.setNoDataText("")
graphView.setNoDataTextColor(colorAccent)
graphView.marker = TextMarkerView(this)
}
protected fun loadGraph(ticker: String, quote: Quote) {
val graphView: LineChart = findViewById(R.id.graphView)
if (dataPoints == null || dataPoints!!.isEmpty()) {
onNoGraphData(graphView)
graphView.setNoDataText(getString(R.string.no_data))
graphView.invalidate()
return
}
graphView.setNoDataText("")
graphView.lineData?.clearValues()
val series = LineDataSet(dataPoints, ticker)
series.setDrawHorizontalHighlightIndicator(false)
series.setDrawValues(false)
val colorAccent = if (quote.changeInPercent >= 0) {
ContextCompat.getColor(this, R.color.positive_green_dark)
} else {
ContextCompat.getColor(this, R.color.negative_red)
}
series.setDrawFilled(true)
series.color = colorAccent
series.fillColor = colorAccent
series.fillAlpha = 150
series.setDrawCircles(true)
series.mode = LineDataSet.Mode.CUBIC_BEZIER
series.cubicIntensity = 0.07f
series.lineWidth = 2f
series.setDrawCircles(false)
series.highLightColor = Color.GRAY
val lineData = LineData(series)
graphView.data = lineData
val xAxis: XAxis = graphView.xAxis
val yAxis: YAxis = graphView.axisRight
if (range == Range.ONE_DAY) {
xAxis.valueFormatter = HourAxisFormatter()
} else {
xAxis.valueFormatter = DateAxisFormatter()
}
yAxis.valueFormatter = ValueAxisFormatter()
xAxis.position = XAxis.XAxisPosition.BOTTOM
xAxis.textSize = 10f
yAxis.textSize = 10f
xAxis.textColor = Color.GRAY
yAxis.textColor = Color.GRAY
xAxis.setLabelCount(5, true)
yAxis.setLabelCount(5, true)
yAxis.setPosition(YAxis.YAxisLabelPosition.OUTSIDE_CHART)
xAxis.setDrawAxisLine(true)
yAxis.setDrawAxisLine(true)
xAxis.setDrawGridLines(false)
yAxis.setDrawGridLines(false)
graphView.invalidate()
onGraphDataAdded(graphView)
}
/**
* xml OnClick
* @param v
*/
fun updateRange(v: View) {
when (v.id) {
R.id.one_day -> range = Range.ONE_DAY
R.id.two_weeks -> range = Range.TWO_WEEKS
R.id.one_month -> range = Range.ONE_MONTH
R.id.three_month -> range = Range.THREE_MONTH
R.id.one_year -> range = Range.ONE_YEAR
R.id.five_years -> range = Range.FIVE_YEARS
R.id.max -> range = Range.MAX
}
fetchGraphData()
}
protected abstract fun fetchGraphData()
protected abstract fun onGraphDataAdded(graphView: LineChart)
protected abstract fun onNoGraphData(graphView: LineChart)
} | gpl-3.0 | d66bdb1bbf159444874cf921f15eac99 | 34.902985 | 85 | 0.739085 | 4.193548 | false | false | false | false |
googlecodelabs/android-compose-codelabs | MigrationCodelab/app/src/main/java/com/google/samples/apps/sunflower/plantdetail/PlantDetailFragment.kt | 1 | 5752 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.sunflower.plantdetail
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.app.ShareCompat
import androidx.core.widget.NestedScrollView
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.navigation.findNavController
import androidx.navigation.fragment.navArgs
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.google.android.material.snackbar.Snackbar
import com.google.samples.apps.sunflower.R
import com.google.samples.apps.sunflower.data.Plant
import com.google.samples.apps.sunflower.databinding.FragmentPlantDetailBinding
import com.google.samples.apps.sunflower.utilities.InjectorUtils
import com.google.samples.apps.sunflower.viewmodels.PlantDetailViewModel
/**
* A fragment representing a single Plant detail screen.
*/
class PlantDetailFragment : Fragment() {
private val args: PlantDetailFragmentArgs by navArgs()
private val plantDetailViewModel: PlantDetailViewModel by viewModels {
InjectorUtils.providePlantDetailViewModelFactory(requireActivity(), args.plantId)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val binding = DataBindingUtil.inflate<FragmentPlantDetailBinding>(
inflater, R.layout.fragment_plant_detail, container, false
).apply {
viewModel = plantDetailViewModel
lifecycleOwner = viewLifecycleOwner
callback = object : Callback {
override fun add(plant: Plant?) {
plant?.let {
hideAppBarFab(fab)
plantDetailViewModel.addPlantToGarden()
Snackbar.make(root, R.string.added_plant_to_garden, Snackbar.LENGTH_LONG)
.show()
}
}
}
var isToolbarShown = false
// scroll change listener begins at Y = 0 when image is fully collapsed
plantDetailScrollview.setOnScrollChangeListener(
NestedScrollView.OnScrollChangeListener { _, _, scrollY, _, _ ->
// User scrolled past image to height of toolbar and the title text is
// underneath the toolbar, so the toolbar should be shown.
val shouldShowToolbar = scrollY > toolbar.height
// The new state of the toolbar differs from the previous state; update
// appbar and toolbar attributes.
if (isToolbarShown != shouldShowToolbar) {
isToolbarShown = shouldShowToolbar
// Use shadow animator to add elevation if toolbar is shown
appbar.isActivated = shouldShowToolbar
// Show the plant name if toolbar is shown
toolbarLayout.isTitleEnabled = shouldShowToolbar
}
}
)
toolbar.setNavigationOnClickListener { view ->
view.findNavController().navigateUp()
}
toolbar.setOnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_share -> {
createShareIntent()
true
}
else -> false
}
}
}
setHasOptionsMenu(true)
return binding.root
}
// Helper function for calling a share functionality.
// Should be used when user presses a share button/menu item.
@Suppress("DEPRECATION")
private fun createShareIntent() {
val shareText = plantDetailViewModel.plant.value.let { plant ->
if (plant == null) {
""
} else {
getString(R.string.share_text_plant, plant.name)
}
}
val shareIntent = ShareCompat.IntentBuilder.from(requireActivity())
.setText(shareText)
.setType("text/plain")
.createChooserIntent()
.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT or Intent.FLAG_ACTIVITY_MULTIPLE_TASK)
startActivity(shareIntent)
}
// FloatingActionButtons anchored to AppBarLayouts have their visibility controlled by the scroll position.
// We want to turn this behavior off to hide the FAB when it is clicked.
//
// This is adapted from Chris Banes' Stack Overflow answer: https://stackoverflow.com/a/41442923
private fun hideAppBarFab(fab: FloatingActionButton) {
val params = fab.layoutParams as CoordinatorLayout.LayoutParams
val behavior = params.behavior as FloatingActionButton.Behavior
behavior.isAutoHideEnabled = false
fab.hide()
}
interface Callback {
fun add(plant: Plant?)
}
}
| apache-2.0 | 1c05b19e35d8e908d6e94773678e933d | 37.864865 | 111 | 0.644645 | 5.431539 | false | false | false | false |
nickthecoder/tickle | tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/tabs/ShapeEditorParameter.kt | 1 | 13109 | /*
Tickle
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.tickle.editor.tabs
import javafx.application.Platform
import javafx.scene.Node
import javafx.scene.canvas.Canvas
import javafx.scene.input.MouseEvent
import javafx.scene.paint.Color
import javafx.scene.shape.StrokeLineCap
import org.joml.Matrix3x2d
import org.joml.Vector2d
import uk.co.nickthecoder.paratask.AbstractTask
import uk.co.nickthecoder.paratask.TaskDescription
import uk.co.nickthecoder.paratask.parameters.AbstractParameter
import uk.co.nickthecoder.paratask.parameters.DoubleParameter
import uk.co.nickthecoder.paratask.parameters.fields.ParameterField
import uk.co.nickthecoder.tickle.Pose
import uk.co.nickthecoder.tickle.editor.util.AngleParameter
import uk.co.nickthecoder.tickle.editor.util.Vector2dParameter
import uk.co.nickthecoder.tickle.editor.util.cachedImage
import uk.co.nickthecoder.tickle.physics.BoxDef
import uk.co.nickthecoder.tickle.physics.CircleDef
import uk.co.nickthecoder.tickle.physics.PolygonDef
import uk.co.nickthecoder.tickle.physics.ShapeDef
class ShapeEditorParameter(name: String, val pose: Pose, val fixtureParameter: CostumeTab.PhysicsTask.FixtureParameter)
: AbstractParameter(name, label = "", description = "") {
override fun errorMessage(): String? = null
override fun copy() = ShapeEditorParameter(name, pose, fixtureParameter)
override fun isStretchy(): Boolean = true
private var field = ShapeEditorField(this)
override fun createField(): ParameterField {
field.build()
return field
}
fun update(shapedDef: ShapeDef?) {
field.update(shapedDef)
}
}
class ShapeEditorTask(pose: Pose, val fixtureParameter: CostumeTab.PhysicsTask.FixtureParameter)
: AbstractTask() {
val shapeEditorP = ShapeEditorParameter("shapeEditor", pose, fixtureParameter)
override val taskD = TaskDescription("editShape")
.addParameters(shapeEditorP)
override fun run() {}
}
class ShapeEditorField(shapeEditorParameter: ShapeEditorParameter) : ParameterField(shapeEditorParameter) {
val fixtureParameter = shapeEditorParameter.fixtureParameter
val pose = shapeEditorParameter.pose
val poseWidth = pose.rect.width
val poseHeight = pose.rect.height
val margin = 10.0
val borderColor = Color(0.0, 0.0, 0.0, 0.3)
val shapeColor = Color(1.0, 0.0, 0.0, 1.0)
val handleColor = Color(0.0, 0.0, 1.0, 1.0)
val currentHandleColor = Color(1.0, 1.0, 1.0, 1.0)
val canvas = Canvas(poseWidth.toDouble() + margin * 2, poseHeight.toDouble() + margin * 2)
val handles = mutableListOf<Handle>()
init {
//println("Creating SEP")
with(canvas) {
graphicsContext2D.transform(1.0, 0.0, 0.0, -1.0, 0.0, canvas.height)
addEventHandler(MouseEvent.MOUSE_PRESSED) { onMousePressed(it) }
addEventHandler(MouseEvent.MOUSE_MOVED) { onMouseMoved(it) }
addEventHandler(MouseEvent.MOUSE_DRAGGED) { onMouseDragged(it) }
addEventHandler(MouseEvent.MOUSE_RELEASED) { dragging = false }
}
}
override fun createControl(): Node {
return canvas
}
var dirty = false
set(v) {
if (v && !field) {
Platform.runLater {
redraw()
}
}
field = v
}
var currentHandle: Handle? = null
set(v) {
if (field != v) {
field = v
dirty = true
}
}
var dragging = false
var currentShapedDef: ShapeDef? = null
fun closestHandle(event: MouseEvent): Handle? {
val offsetX = event.x - margin - pose.offsetX
val offsetY = canvas.height - margin - event.y - pose.offsetY
var result: Handle? = null
var minDist = Double.MAX_VALUE
handles.forEach { handle ->
val position = handle.position()
val dx = Math.abs(position.x - offsetX)
val dy = Math.abs(position.y - offsetY)
if (dx <= 6.0 && dy <= 6) {
val dist = dx * dx + dy * dy
if (dist < minDist) {
minDist = dist
result = handle
}
}
}
return result
}
fun onMousePressed(event: MouseEvent) {
currentHandle = closestHandle(event)
dragging = currentHandle != null
}
fun onMouseMoved(event: MouseEvent) {
// println("onMouseMoved")
currentHandle = closestHandle(event)
}
fun onMouseDragged(event: MouseEvent) {
//println("onMouseDragged")
val offsetX = event.x - margin - pose.offsetX
val offsetY = canvas.height - margin - event.y - pose.offsetY
currentHandle?.moveTo(offsetX, offsetY)
}
fun update(shapeDef: ShapeDef?) {
//println("Update using : $shapeDef")
currentShapedDef = shapeDef
if (!dragging) {
//println("Creating drag handles")
handles.clear()
when (shapeDef) {
is CircleDef -> {
handles.add(RadiusHandle(fixtureParameter.circleCenterP.xP, fixtureParameter.circleCenterP.yP, fixtureParameter.circleRadiusP))
handles.add(PositionHandle(fixtureParameter.circleCenterP))
}
is BoxDef -> {
val corner1 = CornerHandle(fixtureParameter.boxCenterP, fixtureParameter.boxSizeP.xP, fixtureParameter.boxSizeP.yP, fixtureParameter.boxAngleP, null)
val corner2 = CornerHandle(fixtureParameter.boxCenterP, fixtureParameter.boxSizeP.xP, fixtureParameter.boxSizeP.yP, fixtureParameter.boxAngleP, corner1)
handles.add(corner1)
handles.add(corner2)
}
is PolygonDef -> {
fixtureParameter.polygonPointsP.innerParameters.forEach { pointP ->
handles.add(PositionHandle(pointP))
}
}
}
}
dirty = true
}
fun redraw() {
dirty = false
//println("Redraw")
val shapeDef = currentShapedDef
with(canvas.graphicsContext2D) {
save()
clearRect(0.0, 0.0, canvas.width, canvas.height)
lineWidth = 1.0
stroke = borderColor
translate(margin, margin)
strokeRect(0.0, 0.0, poseWidth.toDouble(), poseHeight.toDouble())
save()
translate(pose.offsetX, pose.offsetY)
save()
when (shapeDef) {
is CircleDef -> {
drawOutlined(shapeColor) {
strokeOval(shapeDef.center.x - shapeDef.radius, shapeDef.center.y - shapeDef.radius, shapeDef.radius * 2, shapeDef.radius * 2)
}
}
is BoxDef -> {
translate(shapeDef.center.x, shapeDef.center.y)
rotate(shapeDef.angle.degrees)
drawOutlined(shapeColor) {
strokeRect(-shapeDef.width / 2, -shapeDef.height / 2, shapeDef.width, shapeDef.height)
}
}
is PolygonDef -> {
lineCap = StrokeLineCap.ROUND
drawOutlined(shapeColor) {
val xs = DoubleArray(shapeDef.points.size, { i -> shapeDef.points.map { it.x }[i] })
val ys = DoubleArray(shapeDef.points.size, { i -> shapeDef.points.map { it.y }[i] })
strokePolygon(xs, ys, shapeDef.points.size)
}
}
}
restore()
handles.forEach { it.draw() }
restore()
this.globalAlpha = 0.5
drawImage(pose.texture.cachedImage(),
pose.rect.left.toDouble(), pose.rect.bottom.toDouble(), pose.rect.width.toDouble(), -pose.rect.height.toDouble(),
0.0, 0.0, pose.rect.width.toDouble(), pose.rect.height.toDouble())
this.globalAlpha = 1.0
restore()
}
}
fun drawOutlined(color: Color, shape: () -> Unit) {
with(canvas.graphicsContext2D) {
stroke = Color.BLACK
lineCap = StrokeLineCap.ROUND
lineWidth = 2.0
shape()
stroke = color
lineWidth = 1.0
shape()
}
}
inner abstract class Handle {
abstract fun position(): Vector2d
fun draw() {
with(canvas.graphicsContext2D) {
save()
val position = position()
translate(position.x, position.y)
drawOutlined(if (this@Handle == currentHandle) currentHandleColor else handleColor) {
strokeRect(-3.0, -3.0, 6.0, 6.0)
}
restore()
}
}
abstract fun moveTo(x: Double, y: Double)
}
inner class PositionHandle(val parameter: Vector2dParameter) : Handle() {
override fun position() = Vector2d(parameter.x ?: 0.0, parameter.y ?: 0.0)
override fun moveTo(x: Double, y: Double) {
parameter.xP.value = x
parameter.yP.value = y
}
}
inner class RadiusHandle(val centerXP: DoubleParameter, val centerYP: DoubleParameter, val radiusParameter: DoubleParameter) : Handle() {
override fun position() = Vector2d((centerXP.value ?: 0.0) + (radiusParameter.value ?: 0.0), (centerYP.value
?: 0.0))
override fun moveTo(x: Double, y: Double) {
radiusParameter.value = x - (centerXP.value ?: 0.0)
}
}
inner class CornerHandle(
val centerParameter: Vector2dParameter,
val widthParameter: DoubleParameter,
val heightParameter: DoubleParameter,
val angleParameter: AngleParameter,
other: CornerHandle?)
: Handle() {
lateinit var other: CornerHandle
var plusX: Boolean = true
var plusY: Boolean = true
init {
if (other != null) {
this.other = other
this.other.other = this
plusX = false
plusY = false
}
}
override fun position(): Vector2d {
with(canvas.graphicsContext2D) {
val scaleX = if (plusX) 0.5 else -0.5
val scaleY = if (plusY) 0.5 else -0.5
val width = widthParameter.value ?: 0.0
val height = heightParameter.value ?: 0.0
val cos = Math.cos(angleParameter.value.radians)
val sin = Math.sin(angleParameter.value.radians)
val dx = width * scaleX * cos - height * scaleY * sin
val dy = height * scaleY * cos + width * scaleX * sin
return Vector2d((centerParameter.x ?: 0.0) + dx, (centerParameter.y ?: 0.0) + dy)
}
}
override fun moveTo(x: Double, y: Double) {
val rotate = Matrix3x2d().rotate(-angleParameter.value.radians)
val rotated = Vector2d(x - (centerParameter.x ?: 0.0), y - (centerParameter.y ?: 0.0))
rotate.transformPosition(rotated)
val otherRotated = other.position()
otherRotated.x -= (centerParameter.x ?: 0.0)
otherRotated.y -= (centerParameter.y ?: 0.0)
rotate.transformPosition(otherRotated)
val oldWidth = widthParameter.value ?: 0.0
val oldHeight = heightParameter.value ?: 0.0
var width = Math.round(rotated.x - otherRotated.x).toDouble() * if (plusX) 1 else -1
var height = Math.round(rotated.y - otherRotated.y).toDouble() * if (plusY) 1 else -1
if (width < 0) {
width = -width
plusX = !plusX
other.plusX = !plusX
}
if (height < 0) {
height = -height
plusY = !plusY
other.plusY = !plusY
}
centerParameter.x = (centerParameter.x ?: 0.0) + (width - oldWidth) / 2 * if (plusX) 1 else -1
centerParameter.y = (centerParameter.y ?: 0.0) + (height - oldHeight) / 2 * if (plusY) 1 else -1
widthParameter.value = width
heightParameter.value = height
}
}
}
| gpl-3.0 | f08922f6bce733ec921ed0d62aefec99 | 32.96114 | 172 | 0.581204 | 4.484776 | false | false | false | false |
futuresimple/android-db-commons | library/src/androidTest/java/com/getbase/android/db/cursors/ComposedCursorLoaderTest.kt | 1 | 12415 | package com.getbase.android.db.cursors
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.SystemClock
import androidx.loader.app.LoaderManager
import androidx.loader.content.Loader
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import com.getbase.android.db.loaders.CursorLoaderBuilder
import com.getbase.android.db.test.AsyncTasksMonitor
import com.getbase.android.db.test.TestActivity
import com.getbase.android.db.test.TestContentProvider
import com.getbase.android.db.test.TestContract
import com.google.common.truth.Truth
import org.junit.Assert
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.*
import java.util.concurrent.CountDownLatch
import java.util.concurrent.LinkedBlockingDeque
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
@RunWith(AndroidJUnit4::class)
class ComposedCursorLoaderTest {
@Rule
@JvmField
val rule = ActivityTestRule(TestActivity::class.java)
private val asyncTasksMonitor = AsyncTasksMonitor()
@Test
fun shouldGracefullyHandleTransformationsYieldingTheSameInstance() {
val initialLoad = TransformData(1, pauseWhenExecuting = false)
val firstReload = TransformData(2)
val secondReload = TransformData(2)
// Check preconditions for this scenario: the reloads have to use the same
// instance of transformation output object and it has to be different than
// the result of initial load to trigger onNewDataDelivered callback.
Truth.assertThat(firstReload.result).isSameAs(secondReload.result)
Truth.assertThat(initialLoad.result).isNotSameAs(firstReload.result)
val results = LinkedBlockingDeque<Int>()
val transforms = LinkedList<TransformData>().apply {
add(initialLoad)
add(firstReload)
add(secondReload)
}
// Start the loader on TestContract.BASE_URI. The returned Cursor will be transformed using
// TransformData objects enqueued in transforms queue.
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.initLoader(0, Bundle.EMPTY, object : LoaderManager.LoaderCallbacks<Int> {
override fun onCreateLoader(id: Int, args: Bundle?): Loader<Int> =
CursorLoaderBuilder
.forUri(TestContract.BASE_URI)
.transform { transforms.removeFirst().perform() }
.build(rule.activity)
override fun onLoadFinished(loader: Loader<Int>, data: Int) = results.putLast(data)
override fun onLoaderReset(loader: Loader<Int>) = Unit
})
}
// Wait until the initial load is completed. We do this to ensure the content observers
// are registered on TestContract.BASE_URI and we can trigger Loader reload with
// ContentResolver.notifyChange call.
Truth.assertThat(results.takeFirst()).isEqualTo(1)
// The reloads are scheduled on the main Looper.
scheduleLoaderReload()
// Let's wait until the async task used by our Loader is started.
firstReload.waitUntilStarted()
// Now the things get tricky. We have to switch to the main thread to properly
// orchestrate all threads.
rule.runOnUiThread {
// The first reload is paused. We schedule yet another reload on the main Looper. Note
// that we're on the main thread here, so the reload will be processed *after* everything
// we do in this runnable.
scheduleLoaderReload()
// We want to complete the second reload before the result of first reload are
// delivered and processed on the main thread. To do that, we schedule yet another
// task that will be processed on the main thread after the second reload trigger.
scheduleMainLooperTask {
// At this point we're after the second reload trigger. The first reload is still
// waiting in the cursor transformation. We synchronously wait until the task is
// started...
secondReload.waitUntilStarted()
// ...and finished.
secondReload.proceed()
asyncTasksMonitor.waitUntilIdle()
// Again, we synchronously wait for the task to finish. We want to be sure that
// the results of the first reload are not processed yet. At this point we'll have:
// - Two delivery tasks for both reloads enqueued in main Looper.
// - Two pending result entries for the same result in the ComposedCursorLoader
// internals.
// - The first reload results should be cancelled; the second reload results should be
// delivered to onLoadFinished callback.
}
// We resume the first reload execution on the background thread.
firstReload.proceed()
// We synchronously wait until the first reload on the background thread
// is completed, because we don't want the first reload task to be added as
// mCancellingTask in the guts of AsyncTaskLoader.onCancelLoad. Instead, we
// want the results from this task to go through the branch that "cancels"
// the results delivered from an old task.
asyncTasksMonitor.waitUntilIdle()
// At this point the background tasks are completed and we have the following
// queue on the main Looper:
// - reload triggered by ContentResolver.notifyChange call
// - a task that waits for a second reload
// - result delivery from first reload.
}
// The whole machinery is in motion right now, we just need to wait.
// If everything goes well, the first reload will be cancelled, and the
// second reload will be successfully delivered.
Truth.assertThat(results.takeFirst()).isEqualTo(2)
}
@Test
fun shouldNotInvokeTransformationWhenLoaderDestroyedDuringQuery() {
val asyncTaskIdleLatch = CountDownLatch(1)
//As throwing exception on background loader thread do not fail test we need flag to ensure
//that transformation was never invoked
val transformationInvoked = AtomicBoolean(false)
//Prepare TestContentProvider to wait when loader start query for data
TestContentProvider.blockOnQuery()
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.initLoader(1, Bundle.EMPTY, object : LoaderManager.LoaderCallbacks<Nothing> {
override fun onCreateLoader(id: Int, args: Bundle?) =
CursorLoaderBuilder
.forUri(TestContract.BASE_URI)
.transform {
transformationInvoked.set(true)
throw AssertionError("This transformation should never be invoked")
}
.build(rule.activity)
override fun onLoadFinished(loader: Loader<Nothing>, data: Nothing?) {
throw AssertionError("This loader should be cancelled so result should never be returned")
}
override fun onLoaderReset(loader: Loader<Nothing>) {}
})
}
//Now when loader is scheduled, test thread should wait until
//Loader is created and initialized by LoaderManager
TestContentProvider.waitUntilQueryStarted()
//As loader is busy querying for data we cancel load in background.
//Then we allow it to finish query and move forward. In the meantime
//test thread is waiting until asyncTaskMonitor will be idle.
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.destroyLoader(1)
TestContentProvider.proceedQuery()
asyncTasksMonitor.waitUntilIdle()
asyncTaskIdleLatch.countDown()
}
//After all background work is done and check if transformation will not be invoked
asyncTaskIdleLatch.await()
Truth.assertThat(transformationInvoked.get()).isFalse()
}
@Test
fun shouldNotInvokeSecondTransformationWhenLoaderDestroyedDuringFirstTransformation() {
val firstTransformation = TransformData(1)
val secondTransformationInvoked = AtomicBoolean(false)
val asyncTaskIdleLatch = CountDownLatch(1)
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.initLoader(1, Bundle.EMPTY, object : LoaderManager.LoaderCallbacks<Nothing> {
override fun onCreateLoader(id: Int, args: Bundle?) =
CursorLoaderBuilder
.forUri(TestContract.BASE_URI)
.transform { firstTransformation.perform() }
.transform {
secondTransformationInvoked.set(true)
throw AssertionError("This transformation should never be invoked")
}
.build(rule.activity)
override fun onLoadFinished(loader: Loader<Nothing>, data: Nothing?) {
throw AssertionError("This loader should be cancelled so result should never be returned")
}
override fun onLoaderReset(loader: Loader<Nothing>) {}
})
}
firstTransformation.waitUntilStarted()
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.destroyLoader(1)
firstTransformation.proceed()
asyncTasksMonitor.waitUntilIdle()
asyncTaskIdleLatch.countDown()
}
asyncTaskIdleLatch.await()
Truth.assertThat(secondTransformationInvoked.get()).isFalse()
}
interface RowTransformation {
fun transform(): Int;
}
@Test
fun shouldNotInvokeTransformationForSecondRowWhenLoaderDestroyedDuringTransformationOfFirstRow() {
val secondTransformationInvoked = AtomicBoolean(false)
val asyncTaskIdleLatch = CountDownLatch(1)
TestContentProvider.setDataForQuery(mutableListOf(1, 2))
val firstTransformation = TransformData(1)
val transformations = mutableListOf(
object : RowTransformation {
override fun transform(): Int = firstTransformation.perform()
},
object : RowTransformation {
override fun transform(): Int {
secondTransformationInvoked.set(true)
return 2
}
}
)
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.initLoader(1, Bundle.EMPTY, object : LoaderManager.LoaderCallbacks<List<Int>> {
override fun onCreateLoader(id: Int, args: Bundle?) =
CursorLoaderBuilder
.forUri(TestContract.BASE_URI)
.transformRow {
val transformation = transformations.first()
transformations.remove(transformation)
transformation.transform()
}
.build(rule.activity)
override fun onLoadFinished(loader: Loader<List<Int>>, data: List<Int>?) {
throw AssertionError("This loader should be cancelled so result should never be returned")
}
override fun onLoaderReset(loader: Loader<List<Int>>) {}
})
}
firstTransformation.waitUntilStarted()
//Data is loaded and loader is blocked on first row transformation
rule.runOnUiThread {
rule
.activity
.supportLoaderManager
.destroyLoader(1)
firstTransformation.proceed()
asyncTasksMonitor.waitUntilIdle()
asyncTaskIdleLatch.countDown()
}
asyncTaskIdleLatch.await()
Truth.assertThat(secondTransformationInvoked.get()).isFalse()
}
private fun scheduleMainLooperTask(task: () -> Unit) = Handler(Looper.getMainLooper()).post(task)
private fun scheduleLoaderReload() = rule.activity.contentResolver.notifyChange(TestContract.BASE_URI, null)
private fun AsyncTasksMonitor.waitUntilIdle() {
while (!isIdleNow) {
SystemClock.sleep(10)
}
}
class TransformData(val result: Int, pauseWhenExecuting: Boolean = true) {
private val startLatch = CountDownLatch(if (pauseWhenExecuting) 1 else 0)
private val proceedLatch = CountDownLatch(if (pauseWhenExecuting) 1 else 0)
fun perform(): Int {
startLatch.countDown()
proceedLatch.awaitOrFail()
return result
}
fun waitUntilStarted() = startLatch.awaitOrFail()
fun proceed() = proceedLatch.countDown()
private fun CountDownLatch.awaitOrFail(): Unit {
if (!await(3, TimeUnit.SECONDS)) {
Assert.fail()
}
}
}
}
| apache-2.0 | 4b59748cb2569c57451ce96de7b36cda | 37.676012 | 110 | 0.680226 | 5.251692 | false | true | false | false |
t-yoshi/peca-android | libpeercast/src/main/java/org/peercast/core/lib/PeerCastRpcClient.kt | 1 | 7002 | package org.peercast.core.lib
import android.net.Uri
import kotlinx.serialization.json.*
import org.peercast.core.lib.internal.BaseJsonRpcConnection
import org.peercast.core.lib.rpc.*
import org.peercast.core.lib.rpc.io.*
import org.peercast.core.lib.rpc.io.JsonRpcResponse
import org.peercast.core.lib.rpc.io.decodeRpcResponse
import org.peercast.core.lib.rpc.io.decodeRpcResponseOnlyErrorCheck
import java.io.IOException
/**
* PeerCastController経由でRPCコマンドを実行する。
*
* @licenses Dual licensed under the MIT or GPL licenses.
* @author (c) 2019-2020, T Yoshizawa
* @see <a href=https://github.com/kumaryu/peercaststation/wiki/JSON-RPC-API-%E3%83%A1%E3%83%A2>JSON RPC API メモ</a>
* @version 4.0.0
*/
class PeerCastRpcClient(private val conn: BaseJsonRpcConnection) {
/**@param endPoint RPC接続へのURL*/
constructor(endPoint: String) : this(JsonRpcConnection(endPoint))
constructor(controller: PeerCastController) : this(controller.rpcEndPoint)
/**RPC接続へのURL*/
val rpcEndPoint: Uri get() = Uri.parse(conn.endPoint)
private suspend inline fun <reified T> JsonObject.sendCommand(): T {
return conn.post(this.toString()){
decodeRpcResponse(it)
}
}
//result=nullしか帰ってこない場合
private suspend fun JsonObject.sendVoidCommand() {
conn.post(this.toString()){
decodeRpcResponseOnlyErrorCheck(it)
}
}
/**
* 稼働時間、ポート開放状態、IPアドレスなどの情報の取得。
* @throws IOException
* **/
suspend fun getStatus(): Status {
return buildRpcRequest("getStatus").sendCommand()
}
/**
* チャンネルに再接続。
* @throws IOException
* @return なし
* */
suspend fun bumpChannel(channelId: String) {
return buildRpcRequest("bumpChannel", channelId).sendVoidCommand()
}
/**
* チャンネルを停止する。
* @throws IOException
* @return 成功か
* */
suspend fun stopChannel(channelId: String) {
buildRpcRequest("stopChannel", channelId)
.sendVoidCommand()
}
/**
* チャンネルに関して特定の接続を停止する。成功すれば true、失敗すれば false を返す。
* @throws IOException
* @return 成功か
* */
suspend fun stopChannelConnection(channelId: String, connectionId: Int): Boolean {
return buildRpcRequestArrayParams("stopChannelConnection") {
add(channelId)
add(connectionId)
}.sendCommand()
}
/**
* チャンネルの接続情報。
* @throws IOException
* */
suspend fun getChannelConnections(channelId: String): List<ChannelConnection> {
return buildRpcRequest("getChannelConnections", channelId).sendCommand()
}
/**
* リレーツリー情報。ルートは自分自身。
* @throws IOException
* */
suspend fun getChannelRelayTree(channelId: String): List<ChannelRelayTree> {
return buildRpcRequest("getChannelRelayTree", channelId)
.sendCommand()
}
suspend fun getChannelInfo(channelId: String): ChannelInfoResult {
return buildRpcRequest("getChannelInfo", channelId).sendCommand()
}
/**
* バージョン情報の取得。
* @throws IOException
* */
suspend fun getVersionInfo(): VersionInfo {
return buildRpcRequest("getVersionInfo").sendCommand()
}
/**
* 特定のチャンネルの情報。
* @throws IOException
* */
suspend fun getChannelStatus(channelId: String): ChannelStatus {
return buildRpcRequest("getChannelStatus", channelId).sendCommand()
}
/**
* すべてのチャンネルの情報。
* @throws IOException
* */
suspend fun getChannels(): List<Channel> {
return buildRpcRequest("getChannels").sendCommand()
}
/**
* リレーに関する設定の取得。
* @throws IOException
* */
suspend fun getSettings(): Settings {
return buildRpcRequest("getSettings").sendCommand()
}
/**
* リレーに関する設定を変更。
* @throws IOException
* */
suspend fun setSettings(settings: Settings) {
buildRpcRequestObjectParams("setSettings") {
put("settings", Json.encodeToJsonElement(settings))
}.sendVoidCommand()
}
/**
* ログをクリア。
* @throws IOException
* */
suspend fun clearLog() {
buildRpcRequest("clearLog").sendVoidCommand()
}
/**
* ログバッファーの内容の取得
* @throws IOException
* @since YT22
* */
suspend fun getLog(from: Int? = null, maxLines: Int? = null): List<Log> {
return buildRpcRequestObjectParams("getLog") {
put("from", from)
put("maxLines", maxLines)
}.sendCommand()
}
/**
* ログレベルの取得。
* @throws IOException
* @since YT22
* */
suspend fun getLogSettings(): LogSettings {
return buildRpcRequest("getLogSettings").sendCommand()
}
/**
* ログレベルの設定。
* @throws IOException
* @since YT22
* */
suspend fun setLogSettings(settings: LogSettings) {
buildRpcRequest("setLogSettings",
Json.encodeToJsonElement(settings)
).sendVoidCommand()
}
/**
* 外部サイトの index.txtから取得されたチャンネル一覧。YPブラウザでの表示用。
* @throws IOException
* */
suspend fun getYPChannels(): List<YpChannel> {
return buildRpcRequest("getYPChannels").sendCommand()
}
/**
* 登録されているイエローページの取得。
* @throws IOException
* */
suspend fun getYellowPages(): List<YellowPage> {
return buildRpcRequest("getYellowPages").sendCommand()
}
/**
* イエローページを追加。
* @throws IOException
* */
suspend fun addYellowPage(
protocol: String, name: String,
uri: String = "", announceUri: String = "", channelsUri: String = "",
) {
throw NotImplementedError("Not implemented yet in jrpc.cpp")
}
/**
* イエローページを削除。
* @throws IOException
* */
suspend fun removeYellowPage(yellowPageId: Int) {
buildRpcRequest("removeYellowPage", yellowPageId).sendVoidCommand()
}
/**
* YP から index.txt を取得する。
* @throws IOException
* */
suspend fun updateYPChannels() {
throw NotImplementedError("Not implemented yet in jrpc.cpp")
}
override fun hashCode(): Int {
return javaClass.hashCode() * 31 + conn.hashCode()
}
override fun equals(other: Any?): Boolean {
return other is PeerCastRpcClient &&
other.javaClass == javaClass &&
other.conn == conn
}
} | gpl-3.0 | 3f0370af624ad3c28d43e3cd8186624b | 25.420833 | 115 | 0.624606 | 4.07455 | false | false | false | false |
lunabox/leetcode | kotlin/problems/src/solution/LinkProblems.kt | 1 | 10550 | package solution
import data.structure.ListNode
class LinkProblems {
/**
* https://leetcode-cn.com/problems/merge-k-sorted-lists/
*/
fun mergeKLists(lists: Array<ListNode?>): ListNode? {
var currentNode = Array<ListNode?>(lists.size) { null }
var result: ListNode? = null
var current: ListNode? = null
lists.forEachIndexed { index, listNode ->
currentNode[index] = listNode
}
currentNode = currentNode.filterNotNull().toTypedArray()
while (currentNode.isNotEmpty()) {
var m = currentNode[0]
var minIndex = 0
currentNode.forEachIndexed { index, listNode ->
if (listNode!!.`val` < m!!.`val`) {
m = listNode
minIndex = index
}
}
if (current == null) {
result = m
current = result
} else {
current.next = m
current = current.next
}
currentNode[minIndex] = currentNode[minIndex]?.next
currentNode = currentNode.filterNotNull().toTypedArray()
current?.next = null
}
return result
}
/**
* https://leetcode-cn.com/problems/add-two-numbers-ii/
*/
fun addTwoNumbers(l1: ListNode?, l2: ListNode?): ListNode? {
val h1 = ListNode(0)
h1.next = l1
val h2 = ListNode(0)
h2.next = l2
val reverseList: (ListNode) -> Unit = {
var current = it.next
it.next = null
while (current != null) {
val pointer = current
current = current.next
if (it.next == null) {
it.next = pointer
pointer.next = null
} else {
pointer.next = it.next
it.next = pointer
}
}
}
reverseList(h1)
reverseList(h2)
var n1 = h1.next
var n2 = h2.next
val ans = ListNode(0)
var cur: ListNode? = null
var carry = 0
while (n1 != null && n2 != null) {
val n = n1.`val` + n2.`val` + carry
carry = n / 10
if (ans.next == null) {
ans.next = ListNode(n % 10)
cur = ans.next
} else {
cur!!.next = ListNode(n % 10)
cur = cur.next
}
n1 = n1.next
n2 = n2.next
}
while (n1 != null) {
cur!!.next = ListNode((n1.`val` + carry) % 10)
carry = (n1.`val` + carry) / 10
cur = cur.next
n1 = n1.next
}
while (n2 != null) {
cur!!.next = ListNode((n2.`val` + carry) % 10)
carry = (n2.`val` + carry) / 10
cur = cur.next
n2 = n2.next
}
if (carry > 0) {
cur!!.next = ListNode(carry)
}
reverseList(ans)
return ans.next
}
/**
* https://leetcode-cn.com/problems/shan-chu-lian-biao-de-jie-dian-lcof/
*/
fun deleteNode(head: ListNode?, `val`: Int): ListNode? {
val ans = ListNode(0)
ans.next = head
var before = ans
var current = ans.next
while (current != null) {
if (current.`val` == `val`) {
before.next = current.next
current.next = null
break
}
before = current
current = current.next
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/convert-binary-number-in-a-linked-list-to-integer/
*/
fun getDecimalValue(head: ListNode?): Int {
var len = 0
var cur = head
var ans = 0
while (cur != null) {
len++
cur = cur.next
}
cur = head
var carry = (1).shl(len - 1)
while (cur != null) {
ans += carry * cur.`val`
carry = carry.shr(1)
cur = cur.next
}
return ans
}
/**
*
*/
fun addTwoNumbers2(l1: ListNode?, l2: ListNode?): ListNode? {
val h1 = ListNode(0)
h1.next = l1
val h2 = ListNode(0)
h2.next = l2
var n1 = h1.next
var n2 = h2.next
val ans = ListNode(0)
var cur: ListNode? = null
var carry = 0
while (n1 != null && n2 != null) {
val n = n1.`val` + n2.`val` + carry
carry = n / 10
if (ans.next == null) {
ans.next = ListNode(n % 10)
cur = ans.next
} else {
cur!!.next = ListNode(n % 10)
cur = cur.next
}
n1 = n1.next
n2 = n2.next
}
while (n1 != null) {
cur!!.next = ListNode((n1.`val` + carry) % 10)
carry = (n1.`val` + carry) / 10
cur = cur.next
n1 = n1.next
}
while (n2 != null) {
cur!!.next = ListNode((n2.`val` + carry) % 10)
carry = (n2.`val` + carry) / 10
cur = cur.next
n2 = n2.next
}
if (carry > 0) {
cur!!.next = ListNode(carry)
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/partition-list/
*/
fun partition(head: ListNode?, x: Int): ListNode? {
val littleList = ListNode(0)
val bigList = ListNode(0)
var current = head
var littleCurrent = littleList
var bigCurrent = bigList
while (current != null) {
val temp = current
current = current.next
temp.next = null
if (temp.`val` < x) {
littleCurrent.next = temp
littleCurrent = littleCurrent.next!!
} else {
bigCurrent.next = temp
bigCurrent = bigCurrent.next!!
}
}
littleCurrent.next = bigList.next
return littleList.next
}
/**
* https://leetcode-cn.com/problems/fan-zhuan-lian-biao-lcof/
*/
fun reverseList(head: ListNode?): ListNode? {
val ans: ListNode = ListNode(0)
var current = head
while (current != null) {
val temp = current
current = current.next
temp.next = ans.next
ans.next = temp
}
return ans.next
}
/**
* https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
*/
fun mergeTwoLists(l1: ListNode?, l2: ListNode?): ListNode? {
var cur1 = l1
var cur2 = l2
val ans = ListNode(0)
var cur: ListNode = ans
while (cur1 != null || cur2 != null) {
if (cur2 == null || (cur1 != null && cur1.`val` <= cur2.`val`)) {
cur.next = cur1
cur1 = cur1!!.next
cur = cur.next!!
cur.next = null
} else if (cur1 == null || cur1.`val` > cur2.`val`) {
cur.next = cur2
cur2 = cur2.next
cur = cur.next!!
cur.next = null
}
}
return ans.next
}
/**
<<<<<<< HEAD
* https://leetcode-cn.com/problems/palindrome-linked-list-lcci/
*/
fun isPalindrome(head: ListNode?): Boolean {
var cur = head
var listLength = 0
while (cur != null) {
listLength++
cur = cur.next
}
cur = head
var count = listLength / 2
val left = ListNode(0)
while (count > 0 && cur != null) {
count--
val temp = cur
cur = cur.next
temp.next = left.next
left.next = temp
}
var curLeft = left.next
var curRight = cur
if (listLength % 2 == 1) {
curRight = cur!!.next
}
while (curLeft != null && curRight != null) {
if (curLeft.`val` != curRight.`val`) {
return false
}
curLeft = curLeft.next
curRight = curRight.next
}
return true
}
/**
* https://leetcode-cn.com/problems/kth-node-from-end-of-list-lcci/
*/
fun kthToLast(head: ListNode?, k: Int): Int {
var cur = head
var listLength = 0
while (cur != null) {
listLength++
cur = cur.next
}
val pos = listLength - k + 1
cur = head
listLength = 0
while (cur != null) {
listLength++
if (listLength == pos) {
return cur.`val`
}
cur = cur.next
}
return 0
}
/**
* https://leetcode-cn.com/problems/middle-of-the-linked-list/
*/
fun middleNode(head: ListNode?): ListNode? {
var listLength = 0
var current = head
while (current != null) {
listLength++
current = current.next
}
val middle = listLength / 2 + 1
current = head
listLength = 0
while (current != null) {
listLength++
if (listLength == middle) {
return current
}
current = current.next
}
return null
}
/**
* https://leetcode-cn.com/problems/linked-list-components/
*/
fun numComponents(head: ListNode?, G: IntArray): Int {
var ans = 0
var current = head
var inList = false
while (current != null) {
if (current.`val` in G) {
if (!inList) {
inList = true
ans++
}
} else {
inList = false
}
current = current.next
}
return ans
}
/**
* https://leetcode-cn.com/problems/remove-duplicate-node-lcci/
*/
fun removeDuplicateNodes(head: ListNode?): ListNode? {
val buffer = HashSet<Int>()
var current = head
var before: ListNode? = null
while (current != null) {
if (current.`val` in buffer) {
before!!.next = current.next
current = before
} else {
buffer.add(current.`val`)
}
before = current
current = current.next
}
return head
}
} | apache-2.0 | 4f2a7e207882db4747ef50c48d9bfee3 | 26.986737 | 90 | 0.44654 | 4.226763 | false | false | false | false |
j2ghz/tachiyomi-extensions | src/it/hentaifantasy/src/eu/kanade/tachiyomi/extension/it/hentaifantasy/HentaiFantasy.kt | 1 | 7809 | package eu.kanade.tachiyomi.extension.it.hentaifantasy
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.network.POST
import eu.kanade.tachiyomi.source.model.*
import eu.kanade.tachiyomi.source.online.ParsedHttpSource
import okhttp3.*
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.regex.Pattern
class HentaiFantasy : ParsedHttpSource() {
override val name = "HentaiFantasy"
override val baseUrl = "http://www.hentaifantasy.it/index.php"
override val lang = "it"
override val supportsLatest = true
override val client: OkHttpClient = network.cloudflareClient
companion object {
val pagesUrlPattern by lazy {
Pattern.compile("""\"url\":\"(.*?)\"""")
}
val dateFormat by lazy {
SimpleDateFormat("yyyy.MM.dd")
}
}
override fun popularMangaSelector() = "div.list > div.group > div.title > a"
override fun popularMangaRequest(page: Int)
= GET("$baseUrl/most_downloaded/$page/", headers)
override fun popularMangaFromElement(element: Element): SManga {
val manga = SManga.create()
manga.setUrlWithoutDomain(element.attr("href"))
manga.title = element.text().trim()
return manga
}
override fun popularMangaNextPageSelector() = "div.next > a.gbutton:contains(»):last-of-type"
override fun latestUpdatesSelector() = popularMangaSelector()
override fun latestUpdatesRequest(page: Int)
= GET("$baseUrl/latest/$page/", headers)
override fun latestUpdatesFromElement(element: Element): SManga {
return popularMangaFromElement(element)
}
override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector()
override fun searchMangaSelector() = popularMangaSelector()
override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request {
var tags = mutableListOf<String>()
var paths = mutableListOf<String>()
for (filter in if (filters.isEmpty()) getFilterList() else filters) {
when (filter) {
is TagList -> filter.state
.filter { it.state }
.map {
paths.add(it.name.toLowerCase().replace(" ", "_"));
it.id.toString()
}
.forEach { tags.add(it) }
}
}
var searchTags = tags.size > 0
if (!searchTags && query.length < 3) {
throw Exception("Inserisci almeno tre caratteri")
}
val form = FormBody.Builder().apply {
if (!searchTags) {
add("search", query)
} else {
tags.forEach {
add("tag[]", it)
}
}
}
var searchPath = if (!searchTags) {
"search"
} else if (paths.size == 1) {
"tag/${paths[0]}/${page}"
} else {
"search_tags"
}
return POST("${baseUrl}/${searchPath}", headers, form.build())
}
override fun searchMangaFromElement(element: Element): SManga {
return popularMangaFromElement(element)
}
override fun searchMangaNextPageSelector() = popularMangaNextPageSelector()
override fun mangaDetailsParse(document: Document): SManga {
val manga = SManga.create()
var genres = mutableListOf<String>()
document.select("div#tablelist > div.row").forEach { row ->
when (row.select("div.cell > b").first().text().trim()) {
"Autore" -> manga.author = row.select("div.cell > a").text().trim()
"Genere", "Tipo" -> row.select("div.cell > a > span.label").forEach {
genres.add(it.text().trim())
}
"Descrizione" -> manga.description = row.select("div.cell").last().text().trim()
}
}
manga.genre = genres.joinToString(", ")
manga.status = SManga.UNKNOWN
manga.thumbnail_url = document.select("div.thumbnail > img")?.attr("src")
return manga
}
override fun mangaDetailsRequest(manga: SManga) = POST(baseUrl + manga.url, headers)
override fun chapterListSelector() = "div.list > div.group div.element"
override fun chapterFromElement(element: Element): SChapter {
val chapter = SChapter.create()
element.select("div.title > a").let {
chapter.setUrlWithoutDomain(it.attr("href"))
chapter.name = it.text().trim()
}
chapter.date_upload = element.select("div.meta_r").first()?.ownText()?.substringAfterLast(", ")?.trim()?.let {
parseChapterDate(it)
} ?: 0L
return chapter
}
private fun parseChapterDate(date: String): Long {
return if (date == "Oggi") {
Calendar.getInstance().timeInMillis
} else if (date == "Ieri") {
Calendar.getInstance().apply {
add(Calendar.DAY_OF_YEAR, -1)
}.timeInMillis
} else {
try {
dateFormat.parse(date).time
} catch (e: ParseException) {
0L
}
}
}
override fun pageListRequest(chapter: SChapter) = POST(baseUrl + chapter.url, headers)
override fun pageListParse(response: Response): List<Page> {
val body = response.body()!!.string()
val pages = mutableListOf<Page>()
val p = pagesUrlPattern
val m = p.matcher(body)
var i = 0
while (m.find()) {
pages.add(Page(i++, "", m.group(1).replace("""\\""", "")))
}
return pages
}
override fun pageListParse(document: Document): List<Page> {
throw Exception("Not used")
}
override fun imageUrlRequest(page: Page) = GET(page.url)
override fun imageUrlParse(document: Document) = ""
private class Tag(name: String, val id: Int) : Filter.CheckBox(name)
private class TagList(title: String, tags: List<Tag>) : Filter.Group<Tag>(title, tags)
override fun getFilterList() = FilterList(
TagList("Generi", getTagList())
)
// Tags: 47
// $("select[name='tag[]']:eq(0) > option").map((i, el) => `Tag("${$(el).text().trim()}", ${$(el).attr("value")})`).get().sort().join(",\n")
// on http://www.hentaifantasy.it/search/
private fun getTagList() = listOf(
Tag("Ahegao", 56),
Tag("Anal", 28),
Tag("Ashikoki", 12),
Tag("Bestiality", 24),
Tag("Bizzare", 44),
Tag("Bondage", 30),
Tag("Cheating", 33),
Tag("Chubby", 57),
Tag("Dark Skin", 39),
Tag("Demon Girl", 43),
Tag("Femdom", 38),
Tag("Forced", 46),
Tag("Full color", 52),
Tag("Furry", 36),
Tag("Futanari", 18),
Tag("Group", 34),
Tag("Guro", 8),
Tag("Harem", 41),
Tag("Housewife", 51),
Tag("Incest", 11),
Tag("Lolicon", 20),
Tag("Maid", 55),
Tag("Milf", 31),
Tag("Monster Girl", 15),
Tag("Nurse", 49),
Tag("Oppai", 25),
Tag("Paizuri", 42),
Tag("Pettanko", 35),
Tag("Pissing", 32),
Tag("Public", 53),
Tag("Rape", 21),
Tag("Schoolgirl", 27),
Tag("Shotacon", 26),
Tag("Stockings", 40),
Tag("Swimsuit", 47),
Tag("Tanlines", 48),
Tag("Teacher", 50),
Tag("Tentacle", 23),
Tag("Toys", 45),
Tag("Trap", 29),
Tag("Tsundere", 54),
Tag("Uncensored", 59),
Tag("Vanilla", 19),
Tag("Yandere", 58),
Tag("Yaoi", 22),
Tag("Yuri", 14)
)
}
| apache-2.0 | eddedb6ce0fe9c11f1f74908a83e32fa | 31.264463 | 144 | 0.558402 | 4.268999 | false | false | false | false |
cketti/okhttp | okhttp-tls/src/main/kotlin/okhttp3/tls/HeldCertificate.kt | 1 | 21734 | /*
* Copyright (C) 2016 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 okhttp3.tls
import java.math.BigInteger
import java.net.InetAddress
import java.security.GeneralSecurityException
import java.security.KeyFactory
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.PrivateKey
import java.security.PublicKey
import java.security.SecureRandom
import java.security.Security
import java.security.Signature
import java.security.cert.X509Certificate
import java.security.interfaces.ECPublicKey
import java.security.interfaces.RSAPrivateKey
import java.security.interfaces.RSAPublicKey
import java.security.spec.PKCS8EncodedKeySpec
import java.util.UUID
import java.util.concurrent.TimeUnit
import okhttp3.internal.canParseAsIpAddress
import okhttp3.tls.internal.der.AlgorithmIdentifier
import okhttp3.tls.internal.der.AttributeTypeAndValue
import okhttp3.tls.internal.der.BasicConstraints
import okhttp3.tls.internal.der.BitString
import okhttp3.tls.internal.der.Certificate
import okhttp3.tls.internal.der.CertificateAdapters
import okhttp3.tls.internal.der.CertificateAdapters.generalNameDnsName
import okhttp3.tls.internal.der.CertificateAdapters.generalNameIpAddress
import okhttp3.tls.internal.der.Extension
import okhttp3.tls.internal.der.ObjectIdentifiers
import okhttp3.tls.internal.der.ObjectIdentifiers.basicConstraints
import okhttp3.tls.internal.der.ObjectIdentifiers.organizationalUnitName
import okhttp3.tls.internal.der.ObjectIdentifiers.sha256WithRSAEncryption
import okhttp3.tls.internal.der.ObjectIdentifiers.sha256withEcdsa
import okhttp3.tls.internal.der.ObjectIdentifiers.subjectAlternativeName
import okhttp3.tls.internal.der.TbsCertificate
import okhttp3.tls.internal.der.Validity
import okio.ByteString
import okio.ByteString.Companion.decodeBase64
import okio.ByteString.Companion.toByteString
import org.bouncycastle.jce.provider.BouncyCastleProvider
/**
* A certificate and its private key. These are some properties of certificates that are used with
* TLS:
*
* * **A common name.** This is a string identifier for the certificate. It usually describes the
* purpose of the certificate like "Entrust Root Certification Authority - G2" or
* "www.squareup.com".
*
* * **A set of hostnames.** These are in the certificate's subject alternative name (SAN)
* extension. A subject alternative name is either a literal hostname (`squareup.com`), a literal
* IP address (`74.122.190.80`), or a hostname pattern (`*.api.squareup.com`).
*
* * **A validity interval.** A certificate should not be used before its validity interval starts
* or after it ends.
*
* * **A public key.** This cryptographic key is used for asymmetric encryption digital signatures.
* Note that the private key is not a part of the certificate!
*
* * **A signature issued by another certificate's private key.** This mechanism allows a trusted
* third-party to endorse a certificate. Third parties should only endorse certificates once
* they've confirmed that the owner of the private key is also the owner of the certificate's
* other properties.
*
* Certificates are signed by other certificates and a sequence of them is called a certificate
* chain. The chain terminates in a self-signed "root" certificate. Signing certificates in the
* middle of the chain are called "intermediates". Organizations that offer certificate signing are
* called certificate authorities (CAs).
*
* Browsers and other HTTP clients need a set of trusted root certificates to authenticate their
* peers. Sets of root certificates are managed by either the HTTP client (like Firefox), or the
* host platform (like Android). In July 2018 Android had 134 trusted root certificates for its HTTP
* clients to trust.
*
* For example, in order to establish a secure connection to `https://www.squareup.com/`,
* these three certificates are used.
*
* ```
* www.squareup.com certificate:
*
* Common Name: www.squareup.com
* Subject Alternative Names: www.squareup.com, squareup.com, account.squareup.com...
* Validity: 2018-07-03T20:18:17Z – 2019-08-01T20:48:15Z
* Public Key: d107beecc17325f55da976bcbab207ba4df68bd3f8fce7c3b5850311128264fd53e1baa342f58d93...
* Signature: 1fb0e66fac05322721fe3a3917f7c98dee1729af39c99eab415f22d8347b508acdf0bab91781c3720...
*
* signed by intermediate certificate:
*
* Common Name: Entrust Certification Authority - L1M
* Subject Alternative Names: none
* Validity: 2014-12-15T15:25:03Z – 2030-10-15T15:55:03Z
* Public Key: d081c13923c2b1d1ecf757dd55243691202248f7fcca520ab0ab3f33b5b08407f6df4e7ab0fb9822...
* Signature: b487c784221a29c0a478ecf54f1bb484976f77eed4cf59afa843962f1d58dea6f3155b2ed9439c4c4...
*
* signed by root certificate:
*
* Common Name: Entrust Root Certification Authority - G2
* Subject Alternative Names: none
* Validity: 2009-07-07T17:25:54Z – 2030-12-07T17:55:54Z
* Public Key: ba84b672db9e0c6be299e93001a776ea32b895411ac9da614e5872cffef68279bf7361060aa527d8...
* Self-signed Signature: 799f1d96c6b6793f228d87d3870304606a6b9a2e59897311ac43d1f513ff8d392bc0f...
* ```
*
* In this example the HTTP client already knows and trusts the last certificate, "Entrust Root
* Certification Authority - G2". That certificate is used to verify the signature of the
* intermediate certificate, "Entrust Certification Authority - L1M". The intermediate certificate
* is used to verify the signature of the "www.squareup.com" certificate.
*
* This roles are reversed for client authentication. In that case the client has a private key and
* a chain of certificates. The server uses a set of trusted root certificates to authenticate the
* client. Subject alternative names are not used for client authentication.
*/
@Suppress("DEPRECATION")
class HeldCertificate(
@get:JvmName("keyPair") val keyPair: KeyPair,
@get:JvmName("certificate") val certificate: X509Certificate
) {
@JvmName("-deprecated_certificate")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "certificate"),
level = DeprecationLevel.ERROR)
fun certificate(): X509Certificate = certificate
@JvmName("-deprecated_keyPair")
@Deprecated(
message = "moved to val",
replaceWith = ReplaceWith(expression = "keyPair"),
level = DeprecationLevel.ERROR)
fun keyPair(): KeyPair = keyPair
/**
* Returns the certificate encoded in [PEM format][rfc_7468].
*
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun certificatePem(): String = certificate.certificatePem()
/**
* Returns the RSA private key encoded in [PKCS #8][rfc_5208] [PEM format][rfc_7468].
*
* [rfc_5208]: https://tools.ietf.org/html/rfc5208
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun privateKeyPkcs8Pem(): String {
return buildString {
append("-----BEGIN PRIVATE KEY-----\n")
encodeBase64Lines(keyPair.private.encoded.toByteString())
append("-----END PRIVATE KEY-----\n")
}
}
/**
* Returns the RSA private key encoded in [PKCS #1][rfc_8017] [PEM format][rfc_7468].
*
* [rfc_8017]: https://tools.ietf.org/html/rfc8017
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
*/
fun privateKeyPkcs1Pem(): String {
check(keyPair.private is RSAPrivateKey) { "PKCS1 only supports RSA keys" }
return buildString {
append("-----BEGIN RSA PRIVATE KEY-----\n")
encodeBase64Lines(pkcs1Bytes())
append("-----END RSA PRIVATE KEY-----\n")
}
}
private fun pkcs1Bytes(): ByteString {
val decoded = CertificateAdapters.privateKeyInfo.fromDer(keyPair.private.encoded.toByteString())
return decoded.privateKey
}
/** Build a held certificate with reasonable defaults. */
class Builder {
private var notBefore = -1L
private var notAfter = -1L
private var commonName: String? = null
private var organizationalUnit: String? = null
private val altNames = mutableListOf<String>()
private var serialNumber: BigInteger? = null
private var keyPair: KeyPair? = null
private var signedBy: HeldCertificate? = null
private var maxIntermediateCas = -1
private var keyAlgorithm: String? = null
private var keySize: Int = 0
init {
ecdsa256()
}
/**
* Sets the certificate to be valid in ```[notBefore..notAfter]```. Both endpoints are specified
* in the format of [System.currentTimeMillis]. Specify -1L for both values to use the default
* interval, 24 hours starting when the certificate is created.
*/
fun validityInterval(notBefore: Long, notAfter: Long) = apply {
require(notBefore <= notAfter && notBefore == -1L == (notAfter == -1L)) {
"invalid interval: $notBefore..$notAfter"
}
this.notBefore = notBefore
this.notAfter = notAfter
}
/**
* Sets the certificate to be valid immediately and until the specified duration has elapsed.
* The precision of this field is seconds; further precision will be truncated.
*/
fun duration(duration: Long, unit: TimeUnit) = apply {
val now = System.currentTimeMillis()
validityInterval(now, now + unit.toMillis(duration))
}
/**
* Adds a subject alternative name (SAN) to the certificate. This is usually a literal hostname,
* a literal IP address, or a hostname pattern. If no subject alternative names are added that
* extension will be omitted.
*/
fun addSubjectAlternativeName(altName: String) = apply {
altNames += altName
}
/**
* Set this certificate's common name (CN). Historically this held the hostname of TLS
* certificate, but that practice was deprecated by [RFC 2818][rfc_2818] and replaced with
* [addSubjectAlternativeName]. If unset a random string will be used.
*
* [rfc_2818]: https://tools.ietf.org/html/rfc2818
*/
fun commonName(cn: String) = apply {
this.commonName = cn
}
/** Sets the certificate's organizational unit (OU). If unset this field will be omitted. */
fun organizationalUnit(ou: String) = apply {
this.organizationalUnit = ou
}
/** Sets this certificate's serial number. If unset the serial number will be 1. */
fun serialNumber(serialNumber: BigInteger) = apply {
this.serialNumber = serialNumber
}
/** Sets this certificate's serial number. If unset the serial number will be 1. */
fun serialNumber(serialNumber: Long) = apply {
serialNumber(BigInteger.valueOf(serialNumber))
}
/**
* Sets the public/private key pair used for this certificate. If unset a key pair will be
* generated.
*/
fun keyPair(keyPair: KeyPair) = apply {
this.keyPair = keyPair
}
/**
* Sets the public/private key pair used for this certificate. If unset a key pair will be
* generated.
*/
fun keyPair(publicKey: PublicKey, privateKey: PrivateKey) = apply {
keyPair(KeyPair(publicKey, privateKey))
}
/**
* Set the certificate that will issue this certificate. If unset the certificate will be
* self-signed.
*/
fun signedBy(signedBy: HeldCertificate?) = apply {
this.signedBy = signedBy
}
/**
* Set this certificate to be a signing certificate, with up to `maxIntermediateCas`
* intermediate signing certificates beneath it.
*
* By default this certificate cannot not sign other certificates. Set this to 0 so this
* certificate can sign other certificates (but those certificates cannot themselves sign
* certificates). Set this to 1 so this certificate can sign intermediate certificates that can
* themselves sign certificates. Add one for each additional layer of intermediates to permit.
*/
fun certificateAuthority(maxIntermediateCas: Int) = apply {
require(maxIntermediateCas >= 0) {
"maxIntermediateCas < 0: $maxIntermediateCas"
}
this.maxIntermediateCas = maxIntermediateCas
}
/**
* Configure the certificate to generate a 256-bit ECDSA key, which provides about 128 bits of
* security. ECDSA keys are noticeably faster than RSA keys.
*
* This is the default configuration and has been since this API was introduced in OkHttp
* 3.11.0. Note that the default may change in future releases.
*/
fun ecdsa256() = apply {
keyAlgorithm = "EC"
keySize = 256
}
/**
* Configure the certificate to generate a 2048-bit RSA key, which provides about 112 bits of
* security. RSA keys are interoperable with very old clients that don't support ECDSA.
*/
fun rsa2048() = apply {
keyAlgorithm = "RSA"
keySize = 2048
}
fun build(): HeldCertificate {
// Subject keys & identity.
val subjectKeyPair = keyPair ?: generateKeyPair()
val subjectPublicKeyInfo = CertificateAdapters.subjectPublicKeyInfo.fromDer(
subjectKeyPair.public.encoded.toByteString()
)
val subject: List<List<AttributeTypeAndValue>> = subject()
// Issuer/signer keys & identity. May be the subject if it is self-signed.
val issuerKeyPair: KeyPair
val issuer: List<List<AttributeTypeAndValue>>
if (signedBy != null) {
issuerKeyPair = signedBy!!.keyPair
issuer = CertificateAdapters.rdnSequence.fromDer(
signedBy!!.certificate.subjectX500Principal.encoded.toByteString()
)
} else {
issuerKeyPair = subjectKeyPair
issuer = subject
}
val signatureAlgorithm = signatureAlgorithm(issuerKeyPair)
// Subset of certificate data that's covered by the signature.
val tbsCertificate = TbsCertificate(
version = 2L, // v3.
serialNumber = serialNumber ?: BigInteger.ONE,
signature = signatureAlgorithm,
issuer = issuer,
validity = validity(),
subject = subject,
subjectPublicKeyInfo = subjectPublicKeyInfo,
issuerUniqueID = null,
subjectUniqueID = null,
extensions = extensions()
)
// Signature.
val signature = Signature.getInstance(tbsCertificate.signatureAlgorithmName).run {
initSign(issuerKeyPair.private)
update(CertificateAdapters.tbsCertificate.toDer(tbsCertificate).toByteArray())
sign().toByteString()
}
// Complete signed certificate.
val certificate = Certificate(
tbsCertificate = tbsCertificate,
signatureAlgorithm = signatureAlgorithm,
signatureValue = BitString(
byteString = signature,
unusedBitsCount = 0
)
)
return HeldCertificate(subjectKeyPair, certificate.toX509Certificate())
}
private fun subject(): List<List<AttributeTypeAndValue>> {
val result = mutableListOf<List<AttributeTypeAndValue>>()
if (organizationalUnit != null) {
result += listOf(AttributeTypeAndValue(
type = organizationalUnitName,
value = organizationalUnit
))
}
result += listOf(AttributeTypeAndValue(
type = ObjectIdentifiers.commonName,
value = commonName ?: UUID.randomUUID().toString()
))
return result
}
private fun validity(): Validity {
val notBefore = if (notBefore != -1L) notBefore else System.currentTimeMillis()
val notAfter = if (notAfter != -1L) notAfter else notBefore + DEFAULT_DURATION_MILLIS
return Validity(
notBefore = notBefore,
notAfter = notAfter
)
}
private fun extensions(): MutableList<Extension> {
val result = mutableListOf<Extension>()
if (maxIntermediateCas != -1) {
result += Extension(
id = basicConstraints,
critical = true,
value = BasicConstraints(
ca = true,
maxIntermediateCas = maxIntermediateCas.toLong()
)
)
}
if (altNames.isNotEmpty()) {
val extensionValue = altNames.map {
when {
it.canParseAsIpAddress() -> {
generalNameIpAddress to InetAddress.getByName(it).address.toByteString()
}
else -> {
generalNameDnsName to it
}
}
}
result += Extension(
id = subjectAlternativeName,
critical = true,
value = extensionValue
)
}
return result
}
private fun signatureAlgorithm(signedByKeyPair: KeyPair): AlgorithmIdentifier {
return when (signedByKeyPair.private) {
is RSAPrivateKey -> AlgorithmIdentifier(
algorithm = sha256WithRSAEncryption,
parameters = null
)
else -> AlgorithmIdentifier(
algorithm = sha256withEcdsa,
parameters = ByteString.EMPTY
)
}
}
private fun generateKeyPair(): KeyPair {
return KeyPairGenerator.getInstance(keyAlgorithm).run {
initialize(keySize, SecureRandom())
generateKeyPair()
}
}
companion object {
private const val DEFAULT_DURATION_MILLIS = 1000L * 60 * 60 * 24 // 24 hours.
init {
Security.addProvider(BouncyCastleProvider())
}
}
}
companion object {
private val PEM_REGEX = Regex("""-----BEGIN ([!-,.-~ ]*)-----([^-]*)-----END \1-----""")
/**
* Decodes a multiline string that contains both a [certificate][certificatePem] and a
* [private key][privateKeyPkcs8Pem], both [PEM-encoded][rfc_7468]. A typical input string looks
* like this:
*
* ```
* -----BEGIN CERTIFICATE-----
* MIIBYTCCAQegAwIBAgIBKjAKBggqhkjOPQQDAjApMRQwEgYDVQQLEwtlbmdpbmVl
* cmluZzERMA8GA1UEAxMIY2FzaC5hcHAwHhcNNzAwMTAxMDAwMDA1WhcNNzAwMTAx
* MDAwMDEwWjApMRQwEgYDVQQLEwtlbmdpbmVlcmluZzERMA8GA1UEAxMIY2FzaC5h
* cHAwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASda8ChkQXxGELnrV/oBnIAx3dD
* ocUOJfdz4pOJTP6dVQB9U3UBiW5uSX/MoOD0LL5zG3bVyL3Y6pDwKuYvfLNhoyAw
* HjAcBgNVHREBAf8EEjAQhwQBAQEBgghjYXNoLmFwcDAKBggqhkjOPQQDAgNIADBF
* AiAyHHg1N6YDDQiY920+cnI5XSZwEGhAtb9PYWO8bLmkcQIhAI2CfEZf3V/obmdT
* yyaoEufLKVXhrTQhRfodTeigi4RX
* -----END CERTIFICATE-----
* -----BEGIN PRIVATE KEY-----
* MEECAQAwEwYHKoZIzj0CAQYIKoZIzj0DAQcEJzAlAgEBBCA7ODT0xhGSNn4ESj6J
* lu/GJQZoU9lDrCPeUcQ28tzOWw==
* -----END PRIVATE KEY-----
* ```
*
* The string should contain exactly one certificate and one private key in [PKCS #8][rfc_5208]
* format. It should not contain any other PEM-encoded blocks, but it may contain other text
* which will be ignored.
*
* Encode a held certificate into this format by concatenating the results of
* [certificatePem()][certificatePem] and [privateKeyPkcs8Pem()][privateKeyPkcs8Pem].
*
* [rfc_7468]: https://tools.ietf.org/html/rfc7468
* [rfc_5208]: https://tools.ietf.org/html/rfc5208
*/
@JvmStatic
fun decode(certificateAndPrivateKeyPem: String): HeldCertificate {
var certificatePem: String? = null
var pkcs8Base64: String? = null
for (match in PEM_REGEX.findAll(certificateAndPrivateKeyPem)) {
when (val label = match.groups[1]!!.value) {
"CERTIFICATE" -> {
require(certificatePem == null) { "string includes multiple certificates" }
certificatePem = match.groups[0]!!.value // Keep --BEGIN-- and --END-- for certificates.
}
"PRIVATE KEY" -> {
require(pkcs8Base64 == null) { "string includes multiple private keys" }
pkcs8Base64 = match.groups[2]!!.value // Include the contents only for PKCS8.
}
else -> {
throw IllegalArgumentException("unexpected type: $label")
}
}
}
require(certificatePem != null) { "string does not include a certificate" }
require(pkcs8Base64 != null) { "string does not include a private key" }
return decode(certificatePem, pkcs8Base64)
}
private fun decode(certificatePem: String, pkcs8Base64Text: String): HeldCertificate {
val certificate = certificatePem.decodeCertificatePem()
val pkcs8Bytes = pkcs8Base64Text.decodeBase64()
?: throw IllegalArgumentException("failed to decode private key")
// The private key doesn't tell us its type but it's okay because the certificate knows!
val keyType = when (certificate.publicKey) {
is ECPublicKey -> "EC"
is RSAPublicKey -> "RSA"
else -> throw IllegalArgumentException("unexpected key type: ${certificate.publicKey}")
}
val privateKey = decodePkcs8(pkcs8Bytes, keyType)
val keyPair = KeyPair(certificate.publicKey, privateKey)
return HeldCertificate(keyPair, certificate)
}
private fun decodePkcs8(data: ByteString, keyAlgorithm: String): PrivateKey {
try {
val keyFactory = KeyFactory.getInstance(keyAlgorithm)
return keyFactory.generatePrivate(PKCS8EncodedKeySpec(data.toByteArray()))
} catch (e: GeneralSecurityException) {
throw IllegalArgumentException("failed to decode private key", e)
}
}
}
}
| apache-2.0 | 6b11d65572d114351c31d96765b2a7d2 | 37.661922 | 100 | 0.692286 | 4.238783 | false | false | false | false |
DataDozer/DataDozer | core/src/test/kotlin/org/datadozer/index/TransactionLogTests.kt | 1 | 3847 | package org.datadozer.index
import org.datadozer.SingleInstancePerThreadObjectPool
import org.datadozer.models.Document
import org.datadozer.models.FieldValue
import org.datadozer.models.TransactionLogEntryType
import org.datadozer.threadPoolExecutorProvider
import org.junit.AfterClass
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import java.nio.file.Files
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicLong
/*
* Licensed to DataDozer under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. DataDozer 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.
*/
class TransactionLogTests {
private val settings = WriterSettings(syncFlush = true)
private val threadPool = threadPoolExecutorProvider()
private val path = Files.createTempDirectory(null)
private val pool = SingleInstancePerThreadObjectPool({ TransactionWriter(path.toFile(), settings) })
private var transactionId = AtomicLong(1)
@Test
fun `Can read write transactions using multiple threads`() {
val runnable = Runnable {
val value = pool.borrowObject()
val doc = Document.newBuilder()
.setId(FieldValue.newBuilder().setStringValue("1"))
.setIndexName("index1")
.build()
val txEntry = transactionLogEntryFactory(1, transactionId.getAndIncrement(),
TransactionLogEntryType.DOC_DELETE, doc)
value.appendEntry(txEntry, 1)
pool.returnObject(value)
}
val tasks = List(999, { _ -> Executors.callable(runnable) })
val result = threadPool.invokeAll(tasks)
for (res in result) {
res.get()
}
val sut = TransactionReader(0L, path.toAbsolutePath().toString())
var txId = 1L
for (t in sut.replayTransactionsByIndex(1)) {
assertEquals(txId, t.modifyIndex)
txId++
}
// We started with x transactions so we should get back x transactions
assertEquals(999, sut.totalTransactionsCount)
}
@Test
fun `Can read back the data from a transaction`() {
val path = Files.createTempDirectory(null)
val sut = TransactionWriter(path.toFile(), settings)
for (i in 1 until 100) {
val doc = Document.newBuilder()
.setId(FieldValue.newBuilder().setIntegerValue(i))
.setIndexName("index1")
.build()
val entry = transactionLogEntryFactory(1, i.toLong(),
TransactionLogEntryType.DOC_DELETE, doc)
sut.appendEntry(entry, 1)
}
// Let read all the data from the transactions
var txId = 1L
val tr = TransactionReader(1, path.toAbsolutePath().toString())
for (t in tr.replayTransactionsByIndex(1)) {
val data = tr.getDataForEntry(t)
assertEquals(txId, data.id.longValue)
assertEquals("index1", data.indexName)
txId++
}
}
@AfterClass
fun cleanup() {
Files.delete(path)
}
} | apache-2.0 | b89c75eb79557d51c52077be18333d25 | 36 | 104 | 0.649857 | 4.702934 | false | false | false | false |
jean79/yested_fw | src/commonMain/kotlin/net/yested/core/utils/OperableList.kt | 1 | 2481 | package net.yested.core.utils
/**
* A list that can be operated upon to clarify what kinds of animations should happen when updating it in a UI.
* @author Eric Pabst ([email protected])
* Date: 4/4/2017
* Time: 11:49 PM
*/
interface OperableList<T> {
fun size(): Int
fun get(index: Int): T
fun add(index: Int, item: T)
fun removeAt(index: Int): T
fun move(fromIndex: Int, toIndex: Int)
fun indexOf(item: T): Int {
var index = size() - 1
while (index >= 0 && get(index) != item) {
index--
}
return index
}
fun contains(item: T): Boolean = indexOf(item) >= 0
}
fun <T> OperableList<T>.toList(): List<T> = range().map { get(it) }
fun <T> OperableList<T>.range() = (0..(size() - 1))
fun <T> OperableList<T>.reconcileTo(desiredList: List<T>) {
// delete anything that isn't in desiredList
range().reversed().forEach { if (!desiredList.contains(get(it))) removeAt(it) }
val (desiredListWithoutNew, newItems) = desiredList.partition { contains(it) }
var countMovingRight = 0
var countMovingLeft = 0
range().forEach { index ->
val desiredIndex = desiredListWithoutNew.indexOf(get(index))
if (desiredIndex > index) {
countMovingRight++
} else if (desiredIndex < index) {
countMovingLeft++
}
}
val desiredIndices = if (countMovingLeft <= countMovingRight) {
0..(desiredListWithoutNew.size - 1)
} else {
(0..(desiredListWithoutNew.size - 1)).reversed()
}
desiredIndices.forEach { desiredIndex ->
val desiredItem = desiredListWithoutNew[desiredIndex]
val indexToMove = indexOf(desiredItem)
if (indexToMove != desiredIndex) {
move(indexToMove, desiredIndex)
}
}
for (newItem in newItems) {
add(desiredList.indexOf(newItem), newItem)
}
}
open class InMemoryOperableList<T>(val list: MutableList<T>) : OperableList<T> {
var modificationCount = 0
override fun size(): Int = list.size
override fun get(index: Int): T = list[index]
override fun add(index: Int, item: T) {
modificationCount++
list.add(index, item)
}
override fun removeAt(index: Int): T {
modificationCount++
return list.removeAt(index)
}
override fun move(fromIndex: Int, toIndex: Int) {
modificationCount++
val item = list.removeAt(fromIndex)
list.add(toIndex, item)
}
}
| mit | fc5663a494a85bab9aede36b246b44e9 | 28.188235 | 111 | 0.61709 | 3.913249 | false | false | false | false |
carlphilipp/chicago-commutes | android-app/src/googleplay/kotlin/fr/cph/chicago/rx/BusFollowObserver.kt | 1 | 2590 | /**
* Copyright 2021 Carl-Philipp Harmant
*
*
* 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 fr.cph.chicago.rx
import android.view.View
import android.widget.ListView
import android.widget.TextView
import fr.cph.chicago.R
import fr.cph.chicago.core.activity.map.BusMapActivity
import fr.cph.chicago.core.adapter.BusMapSnippetAdapter
import fr.cph.chicago.core.model.BusArrival
import fr.cph.chicago.util.Util
import io.reactivex.rxjava3.core.SingleObserver
import io.reactivex.rxjava3.disposables.Disposable
import org.apache.commons.lang3.StringUtils
import timber.log.Timber
import java.util.Date
class BusFollowObserver(private val activity: BusMapActivity, private val layout: View, private val view: View, private val loadAll: Boolean) : SingleObserver<List<BusArrival>> {
companion object {
private val util = Util
}
override fun onSubscribe(d: Disposable) {}
override fun onSuccess(busArrivalsParam: List<BusArrival>) {
var busArrivals = busArrivalsParam.toMutableList()
if (!loadAll && busArrivals.size > 7) {
busArrivals = busArrivals.subList(0, 6)
val busArrival = BusArrival(Date(), "added bus", view.context.getString(R.string.bus_all_results), 0, 0, StringUtils.EMPTY, StringUtils.EMPTY, StringUtils.EMPTY, Date(), false)
busArrivals.add(busArrival)
}
val arrivals = view.findViewById<ListView>(R.id.arrivalsTextView)
val error = view.findViewById<TextView>(R.id.error)
if (busArrivals.isNotEmpty()) {
val ada = BusMapSnippetAdapter(busArrivals)
arrivals.adapter = ada
arrivals.visibility = ListView.VISIBLE
error.visibility = TextView.GONE
} else {
arrivals.visibility = ListView.GONE
error.visibility = TextView.VISIBLE
}
activity.refreshInfoWindow()
}
override fun onError(throwable: Throwable) {
util.handleConnectOrParserException(throwable, layout)
Timber.e(throwable, "Error while loading bus follow")
}
}
| apache-2.0 | ba32e5bf11dffc32f29cd45d8f5999f1 | 36.536232 | 188 | 0.714286 | 4.273927 | false | false | false | false |
thomasvolk/alkali | src/main/kotlin/net/t53k/alkali/ActorSystem.kt | 1 | 6049 | /*
* Copyright 2017 Thomas Volk
*
* 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 net.t53k.alkali
import java.util.concurrent.*
object PoisonPill
object Terminated
object Watch
data class Forward(val message: Any)
data class DeadLetter(val message: Any)
internal class AskingActor(private val returnChannel: LinkedBlockingQueue<Any>, private val target: ActorReference, val message: Any): Actor() {
override fun receive(message: Any) = returnChannel.put(message)
override fun before() {
target send message
}
}
class AskTimeoutException(msg: String): RuntimeException(msg)
internal class NameSpace(val name: String) {
companion object {
val system = NameSpace("_system")
}
fun name(actorName: String) = "$name/$actorName"
fun hasNameSpace(actorName: String) = actorName.startsWith(name)
}
class ActorSystemBuilder {
private var defaultActorHandler: ActorSystem.(Any) -> Unit = {}
private var deadLetterHandler: (Any) -> Unit = {}
fun onDefaultActorMessage(defaultActorHandler: ActorSystem.(Any) -> Unit): ActorSystemBuilder {
this.defaultActorHandler = defaultActorHandler
return this
}
fun onDeadLetterMessage(deadLetterHandler: (Any) -> Unit): ActorSystemBuilder {
this.deadLetterHandler = deadLetterHandler
return this
}
fun build(): ActorSystem = ActorSystem(defaultActorHandler, deadLetterHandler)
}
class ActorSystem(defaultActorHandler: ActorSystem.(Any) -> Unit = {}, deadLetterHandler: (Any) -> Unit = {}): ActorFactory {
private class DefaultActor(val defaultActorHandler: ActorSystem.(Any) -> Unit): Actor() {
override fun receive(message: Any) {
defaultActorHandler(system(), message)
}
}
private class DeadLetterActor(val deadLetterHandler: (Any) -> Unit): Actor() {
override fun receive(message: Any) {
deadLetterHandler((message as DeadLetter).message)
}
}
private data class ActorWrapper(val reference: ActorReference, private val actor: Actor){
fun waitForShutdown() {
actor.waitForShutdown()
}
}
private val _actors = mutableMapOf<String, ActorWrapper>()
private val _currentActor = ThreadLocal<ActorReference>()
private var _active = true
private var _deadLetterActor: ActorWrapper
private val MAIN_ACTOR_NAME = NameSpace.system.name("main")
private val DEAD_LETTER_ACTOR_NAME = NameSpace.system.name("deadLetter")
private val WAIT_FOR_SHUTDOWN_INTERVALL = 10L
init {
currentActor(_actor(MAIN_ACTOR_NAME, DefaultActor(defaultActorHandler)))
val deadLetterActor = DeadLetterActor(deadLetterHandler)
_deadLetterActor = ActorWrapper(_start(DEAD_LETTER_ACTOR_NAME, deadLetterActor), deadLetterActor)
}
@Synchronized
override fun <T> actor(name: String, actor: T): ActorReference where T : Actor {
require(!NameSpace.system.hasNameSpace(name)) { "actor name can not start with '${NameSpace.system.name}' !" }
return _actor(name, actor)
}
@Synchronized
private fun <T> _actor(name: String, actor: T): ActorReference where T : Actor {
require (!_actors.contains(name)) { "actor '$name' already exists" }
val actorRef = _start(name, actor)
_actors.put(name, ActorWrapper(actorRef, actor))
return actorRef
}
private fun <T> _start(name: String, actor: T): ActorReference where T : Actor {
passIfActive()
return actor.start(name, this)
}
@Synchronized
internal fun <T> actor(actor: T): ActorReference where T : Actor {
return _start(NameSpace.system.name("anonymous"), actor)
}
@Synchronized
fun find(name: String): ActorReference? = _actors[name]?.reference
internal fun ask(target: ActorReference, message: Any, timeout: Long): Any {
val returnChannel = LinkedBlockingQueue<Any>()
val askingActor = actor(AskingActor(returnChannel, target, message))
try {
return returnChannel.poll(timeout, TimeUnit.MILLISECONDS) ?: throw AskTimeoutException("timeout $timeout ms reached!")
}
finally {
askingActor send PoisonPill
}
}
fun currentActor(): ActorReference = _currentActor.get()
internal fun currentActor(actor: ActorReference) {
_currentActor.set(actor)
}
fun waitForShutdown() {
if(currentActor().name != MAIN_ACTOR_NAME) { throw IllegalStateException("an actor from the same system can not wait system shutdown")}
while (isActive()) {
Thread.sleep(WAIT_FOR_SHUTDOWN_INTERVALL)
}
_actors.forEach { it.value.waitForShutdown() }
_deadLetterActor.waitForShutdown()
}
@Synchronized
fun shutdown() {
passIfActive()
_actors.forEach { it.value.reference send PoisonPill }
_deadLetterActor.reference send PoisonPill
_active = false
}
private fun passIfActive() {
if(!isActive()) { throw IllegalStateException("ActorSystem is not active!") }
}
fun isActive() = _active
internal fun deadLetter(message: Any) {
if(message !is DeadLetter) {
_deadLetterActor.reference send DeadLetter(message)
}
}
}
| apache-2.0 | 277fc4f25444da8535fa684556b28afb | 34.792899 | 144 | 0.681766 | 4.544703 | false | false | false | false |
kharchenkovitaliypt/AndroidMvp | mvp-utils/src/main/java/com/idapgroup/android/rx_mvp/RxBasePresenter.kt | 1 | 10719 | package com.idapgroup.android.rx_mvp
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import com.idapgroup.android.mvp.impl.Action
import com.idapgroup.android.mvp.impl.BasePresenter
import io.reactivex.*
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.internal.functions.Functions
import io.reactivex.subjects.CompletableSubject
import java.util.*
open class RxBasePresenter<V> : BasePresenter<V>() {
// Optimization for safe subscribe
private val ERROR_CONSUMER: (Throwable) -> Unit = { Functions.ERROR_CONSUMER.accept(it) }
private val EMPTY_ACTION: Action = {}
private val mainHandler = Handler(Looper.getMainLooper())
private val activeTasks = LinkedHashMap<String, Task>()
private val resetTaskStateActionMap = LinkedHashMap<String, Action>()
private var isSavedState = false
private val onDetachViewActionList = mutableListOf<Action>()
private val onSaveStateActionList = mutableListOf<Action>()
inner class Task(val key: String) {
private val subTaskList = ArrayList<Disposable>()
private var subTaskCount = 0
private var cancelled = false
private var completable = CompletableSubject.create()
fun safeAddSubTask(subTask: Disposable) {
runOnUiThread { addSubTask(subTask) }
}
private fun addSubTask(subTask: Disposable) {
checkMainThread()
subTaskList.add(subTask)
++subTaskCount
if(cancelled) subTask.dispose()
}
fun removeSubTask() {
checkMainThread()
--subTaskCount
if(subTaskCount == 0) {
activeTasks.remove(key)
completable.onComplete()
}
}
fun cancel(): Completable {
checkMainThread()
val activeSubTaskList = subTaskList.filter { !it.isDisposed }
val awaitState = await(activeSubTaskList)
activeSubTaskList.forEach { it.dispose() }
cancelled = true
return awaitState
}
fun await(): Completable {
val activeSubTaskList = subTaskList.filter { !it.isDisposed }
return await(activeSubTaskList)
}
fun await(activeSubTaskList: List<Disposable>): Completable {
return if(activeSubTaskList.isEmpty()) Completable.complete() else completable
}
}
override fun onSaveState(savedState: Bundle) {
super.onSaveState(savedState)
onSaveStateActionList.forEach { it() }
onSaveStateActionList.clear()
savedState.putStringArrayList("task_keys", ArrayList(activeTasks.keys))
isSavedState = true
}
override fun onRestoreState(savedState: Bundle) {
super.onRestoreState(savedState)
// Reset tasks only if presenter was destroyed
if(!isSavedState) {
val taskKeyList = savedState.getStringArrayList("task_keys")
taskKeyList.forEach { resetTaskState(it) }
}
isSavedState = false
}
override fun onDetachedView() {
super.onDetachedView()
onDetachViewActionList.forEach { it() }
onDetachViewActionList.clear()
}
/** Preserves link for task by key while it's running */
protected fun <T> taskTracker(taskKey: String): ObservableTransformer<T, T> {
return ObservableTransformer { it.taskTracker(taskKey) }
}
/** Preserves link for task by key while it's running */
protected fun <T> Observable<T>.taskTracker(taskKey: String): Observable<T> {
val task = addTask(taskKey)
return doFinally { task.removeSubTask() }
.doOnSubscribe { disposable -> task.safeAddSubTask(disposable) }
}
/** Preserves link for task by key while it's running */
protected fun <T> singleTaskTracker(taskKey: String): SingleTransformer<T, T> {
return SingleTransformer { it.taskTracker(taskKey) }
}
/** Preserves link for task by key while it's running */
protected fun <T> Single<T>.taskTracker(taskKey: String): Single<T> {
val task = addTask(taskKey)
return doFinally { task.removeSubTask() }
.doOnSubscribe { disposable -> task.safeAddSubTask(disposable) }
}
/** Preserves link for task by key while it's running */
protected fun completableTaskTracker(taskKey: String): CompletableTransformer {
return CompletableTransformer { it.taskTracker(taskKey) }
}
/** Preserves link for task by key while it's running */
protected fun Completable.taskTracker(taskKey: String): Completable {
val task = addTask(taskKey)
return doFinally { task.removeSubTask() }
.doOnSubscribe { disposable -> task.safeAddSubTask(disposable) }
}
/** Preserves link for task by key while it's running */
protected fun <T> maybeTaskTracker(taskKey: String): MaybeTransformer<T, T> {
return MaybeTransformer { it.taskTracker(taskKey) }
}
/** Preserves link for task by key while it's running */
protected fun <T> Maybe<T>.taskTracker(taskKey: String): Maybe<T> {
val task = addTask(taskKey)
return doFinally { task.removeSubTask() }
.doOnSubscribe { disposable -> task.safeAddSubTask(disposable) }
}
private fun addTask(taskKey: String): Task {
checkMainThread()
if(activeTasks.containsKey(taskKey)) {
throw IllegalStateException("'$taskKey' is already tracked")
}
val task = Task(taskKey)
activeTasks[taskKey] = task
return task
}
protected fun setResetTaskStateAction(key: String, resetAction: Action) {
resetTaskStateActionMap.put(key, resetAction)
}
protected fun cancelTask(taskKey: String): Completable {
checkMainThread()
val task = activeTasks[taskKey] ?: return Completable.complete()
activeTasks.remove(taskKey)
val completable = task.cancel()
resetTaskState(taskKey)
return completable
}
protected fun awaitTask(taskKey: String): Completable {
return activeTasks[taskKey]?.await() ?: return Completable.complete()
}
protected fun isTaskActive(taskKey: String): Boolean {
checkMainThread()
return activeTasks[taskKey] != null
}
/** Calls preliminarily set a reset task state action */
private fun resetTaskState(taskKey: String) {
val resetTaskAction = resetTaskStateActionMap[taskKey]
if (resetTaskAction == null) {
Log.w(javaClass.simpleName, "Reset task action is not set for task key: " + taskKey)
} else {
execute(resetTaskAction)
}
}
fun <T> Observable<T>.safeSubscribe(
onNext: (T) -> Unit,
onError: (Throwable) -> Unit = ERROR_CONSUMER,
onComplete: Action = EMPTY_ACTION
): Disposable {
return subscribe(safeOnItem(onNext), safeOnError(onError), safeOnComplete(onComplete))
}
fun <T> Flowable<T>.safeSubscribe(
onNext: (T) -> Unit,
onError: (Throwable) -> Unit = ERROR_CONSUMER,
onComplete: Action = EMPTY_ACTION
): Disposable {
return subscribe(safeOnItem(onNext), safeOnError(onError), safeOnComplete(onComplete))
}
fun <T> Single<T>.safeSubscribe(
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit = ERROR_CONSUMER
): Disposable {
return subscribe(safeOnItem(onSuccess), safeOnError(onError))
}
fun Completable.safeSubscribe(
onComplete: Action,
onError: (Throwable) -> Unit = ERROR_CONSUMER
): Disposable {
return subscribe({ execute(onComplete) }, safeOnError(onError))
}
fun <T> Maybe<T>.safeSubscribe(
onSuccess: (T) -> Unit,
onError: (Throwable) -> Unit = ERROR_CONSUMER,
onComplete: Action = EMPTY_ACTION
): Disposable {
return subscribe(safeOnItem(onSuccess), safeOnError(onError), safeOnComplete(onComplete))
}
fun <T> safeOnItem(onItem: (T) -> Unit): (T) -> Unit {
return { item -> execute { onItem(item) } }
}
fun safeOnComplete(onComplete: Action): () -> Unit {
if(onComplete == EMPTY_ACTION) {
return EMPTY_ACTION
} else {
return { execute(onComplete) }
}
}
fun safeOnError(onError: (Throwable) -> Unit): (Throwable) -> Unit {
if(onError == ERROR_CONSUMER) {
return ERROR_CONSUMER
} else {
return { error: Throwable -> execute { onError(error) } }
}
}
fun <T> Observable<T>.cancelOnDetachView(onSaveState: Boolean = false): Observable<T> {
return doOnSubscribe { cancelOnDetachView(it, onSaveState) }
}
fun <T> Flowable<T>.cancelOnDetachView(onSaveState: Boolean = false): Flowable<T> {
return doOnSubscribe {
cancelOnDetachView(object : Disposable {
override fun isDisposed() = throw RuntimeException("Unsupported")
override fun dispose() = it.cancel()
}, onSaveState)
}
}
fun <T> Single<T>.cancelOnDetachView(onSaveState: Boolean = false): Single<T> {
return doOnSubscribe { cancelOnDetachView(it, onSaveState) }
}
fun <T> Maybe<T>.cancelOnDetachView(onSaveState: Boolean = false): Maybe<T> {
return doOnSubscribe { cancelOnDetachView(it, onSaveState) }
}
fun Completable.cancelOnDetachView(onSaveState: Boolean = false): Completable {
return doOnSubscribe { cancelOnDetachView(it, onSaveState) }
}
private fun cancelOnDetachView(disposable: Disposable, onSaveState: Boolean) {
runOnUiThread {
if(view == null || (onSaveState && isSavedState)) {
disposable.dispose()
} else {
if(onSaveState) {
onSaveStateActionList.add({
disposable.dispose()
})
}
onDetachViewActionList.add({
disposable.dispose()
})
}
}
}
private fun checkMainThread(message: String = "Must be call after observeOn(AndroidSchedulers.mainThread())") {
if(!isMainThread()) {
throw IllegalStateException(message)
}
}
private fun runOnUiThread(action: Action) {
if(isMainThread()) {
action()
} else {
mainHandler.post(action)
}
}
private fun isMainThread() = Looper.myLooper() == Looper.getMainLooper()
}
| apache-2.0 | 6e15384a7e084def8526915d0d47a7cf | 34.029412 | 115 | 0.625618 | 4.948753 | false | false | false | false |
robinverduijn/gradle | .teamcity/Gradle_Check/projects/StageProject.kt | 1 | 3912 | package projects
import configurations.FunctionalTest
import configurations.PerformanceTestCoordinator
import configurations.SanityCheck
import configurations.buildReportTab
import jetbrains.buildServer.configs.kotlin.v2018_2.AbsoluteId
import jetbrains.buildServer.configs.kotlin.v2018_2.FailureAction
import jetbrains.buildServer.configs.kotlin.v2018_2.IdOwner
import jetbrains.buildServer.configs.kotlin.v2018_2.Project
import model.BuildTypeBucket
import model.CIBuildModel
import model.SpecificBuild
import model.Stage
import model.TestType
class StageProject(model: CIBuildModel, stage: Stage, containsDeferredTests: Boolean, rootProjectUuid: String) : Project({
this.uuid = "${model.projectPrefix}Stage_${stage.stageName.uuid}"
this.id = AbsoluteId("${model.projectPrefix}Stage_${stage.stageName.id}")
this.name = stage.stageName.stageName
this.description = stage.stageName.description
features {
if (stage.specificBuilds.contains(SpecificBuild.SanityCheck)) {
buildReportTab("API Compatibility Report", "report-distributions-binary-compatibility-report.html")
buildReportTab("Incubating APIs Report", "incubation-reports/all-incubating.html")
}
if (!stage.performanceTests.isEmpty()) {
buildReportTab("Performance", "report-performance-performance-tests.zip!report/index.html")
}
}
val specificBuildTypes = stage.specificBuilds.map {
it.create(model, stage)
}
specificBuildTypes.forEach { buildType(it) }
stage.performanceTests.forEach {
buildType(PerformanceTestCoordinator(model, it, stage))
}
stage.functionalTests.forEach { testCoverage ->
val isSoakTest = testCoverage.testType == TestType.soak
if (isSoakTest) {
buildType(FunctionalTest(model, testCoverage, stage = stage))
} else {
val functionalTests = FunctionalTestProject(model, testCoverage, stage)
subProject(functionalTests)
if (stage.functionalTestsDependOnSpecificBuilds) {
specificBuildTypes.forEach { specificBuildType ->
functionalTests.addDependencyForAllBuildTypes(specificBuildType)
}
}
if (!(stage.functionalTestsDependOnSpecificBuilds && stage.specificBuilds.contains(SpecificBuild.SanityCheck)) && stage.dependsOnSanityCheck) {
functionalTests.addDependencyForAllBuildTypes(AbsoluteId(SanityCheck.buildTypeId(model)))
}
}
}
if (containsDeferredTests) {
val deferredTestsProject = Project {
uuid = "${rootProjectUuid}_deferred_tests"
id = AbsoluteId(uuid)
name = "Test coverage deferred from Quick Feedback and Ready for Merge"
model.buildTypeBuckets
.filter(BuildTypeBucket::containsSlowTests)
.forEach { bucket ->
FunctionalTestProject.missingTestCoverage
.filter { testConfig ->
bucket.hasTestsOf(testConfig.testType)
}
.forEach { testConfig ->
bucket.forTestType(testConfig.testType).forEach {
buildType(FunctionalTest(model, testConfig, it.getSubprojectNames(), stage, it.name))
}
}
}
}
subProject(deferredTestsProject)
}
})
private fun Project.addDependencyForAllBuildTypes(dependency: IdOwner) {
buildTypes.forEach { functionalTestBuildType ->
functionalTestBuildType.dependencies {
dependency(dependency) {
snapshot {
onDependencyFailure = FailureAction.CANCEL
onDependencyCancel = FailureAction.CANCEL
}
}
}
}
}
| apache-2.0 | 939efb083aff5b241911fa36d1423742 | 40.617021 | 155 | 0.652863 | 5.272237 | false | true | false | false |
toastkidjp/Jitte | app/src/test/java/jp/toastkid/yobidashi/main/OnBackPressedUseCaseTest.kt | 1 | 4907 | package jp.toastkid.yobidashi.main
import androidx.fragment.app.FragmentManager
import io.mockk.MockKAnnotations
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.just
import io.mockk.mockk
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.yobidashi.browser.BrowserFragment
import jp.toastkid.yobidashi.browser.floating.FloatingPreview
import jp.toastkid.yobidashi.browser.page_search.PageSearcherModule
import jp.toastkid.yobidashi.menu.MenuViewModel
import jp.toastkid.yobidashi.tab.TabAdapter
import org.junit.After
import org.junit.Before
import org.junit.Test
/**
* @author toastkidjp
*/
class OnBackPressedUseCaseTest {
private lateinit var onBackPressedUseCase: OnBackPressedUseCase
@MockK
private lateinit var tabListUseCase: TabListUseCase
@MockK
private lateinit var menuVisibility: () -> Boolean
@MockK
private lateinit var menuViewModel: MenuViewModel
@MockK
private lateinit var pageSearcherModule: PageSearcherModule
@MockK
private lateinit var floatingPreview: FloatingPreview
@MockK
private lateinit var tabs: TabAdapter
@MockK
private lateinit var onEmptyTabs: () -> Unit
@MockK
private lateinit var replaceToCurrentTab: TabReplacingUseCase
@MockK
private lateinit var supportFragmentManager: FragmentManager
@Before
fun setUp() {
MockKAnnotations.init(this)
onBackPressedUseCase = OnBackPressedUseCase(
tabListUseCase,
menuVisibility,
menuViewModel,
pageSearcherModule,
{ floatingPreview },
tabs,
onEmptyTabs,
replaceToCurrentTab,
supportFragmentManager
)
every { menuViewModel.close() }.just(Runs)
}
@Test
fun testTabListUseCaseIsTrue() {
every { tabListUseCase.onBackPressed() }.returns(true)
every { menuVisibility.invoke() }.returns(true)
onBackPressedUseCase.invoke()
verify (exactly = 1) { tabListUseCase.onBackPressed() }
verify (exactly = 0) { menuVisibility.invoke() }
verify (exactly = 0) { menuViewModel.close() }
}
@Test
fun testMenuIsVisible() {
every { tabListUseCase.onBackPressed() }.returns(false)
every { menuVisibility.invoke() }.returns(true)
every { pageSearcherModule.isVisible() }.returns(false)
onBackPressedUseCase.invoke()
verify (exactly = 1) { tabListUseCase.onBackPressed() }
verify (exactly = 1) { menuVisibility.invoke() }
verify (exactly = 1) { menuViewModel.close() }
verify (exactly = 0) { pageSearcherModule.isVisible() }
}
@Test
fun testPageSearcherModuleIsVisible() {
every { tabListUseCase.onBackPressed() }.returns(false)
every { menuVisibility.invoke() }.returns(false)
every { pageSearcherModule.isVisible() }.returns(true)
every { pageSearcherModule.hide() }.just(Runs)
every { floatingPreview.onBackPressed() }.answers { true }
onBackPressedUseCase.invoke()
verify (exactly = 1) { tabListUseCase.onBackPressed() }
verify (exactly = 1) { menuVisibility.invoke() }
verify (exactly = 0) { menuViewModel.close() }
verify (exactly = 1) { pageSearcherModule.isVisible() }
verify (exactly = 1) { pageSearcherModule.hide() }
verify (exactly = 0) { floatingPreview.onBackPressed() }
}
@Test
fun testFloatingPreviewIsVisible() {
every { tabListUseCase.onBackPressed() }.returns(false)
every { menuVisibility.invoke() }.returns(false)
every { pageSearcherModule.isVisible() }.returns(false)
every { pageSearcherModule.hide() }.just(Runs)
every { floatingPreview.onBackPressed() }.answers { false }
every { floatingPreview.hide() }.just(Runs)
val fragment = mockk<BrowserFragment>()
every { supportFragmentManager.findFragmentById(any()) }.answers { fragment }
every { fragment.pressBack() }.returns(true)
every { tabs.closeTab(any()) }.just(Runs)
onBackPressedUseCase.invoke()
verify (exactly = 1) { tabListUseCase.onBackPressed() }
verify (exactly = 1) { menuVisibility.invoke() }
verify (exactly = 0) { menuViewModel.close() }
verify (exactly = 1) { pageSearcherModule.isVisible() }
verify (exactly = 0) { pageSearcherModule.hide() }
verify (exactly = 1) { floatingPreview.onBackPressed() }
verify (exactly = 0) { floatingPreview.hide() }
verify (exactly = 1) { supportFragmentManager.findFragmentById(any()) }
verify (exactly = 1) { fragment.pressBack() }
verify (exactly = 0) { tabs.closeTab(any()) }
}
@After
fun tearDown() {
unmockkAll()
}
} | epl-1.0 | ff6ba6b7f40e4805a4bd45ffb28a1f71 | 31.72 | 85 | 0.661504 | 4.981726 | false | true | false | false |
inorichi/tachiyomi | app/src/main/java/eu/kanade/tachiyomi/source/model/Page.kt | 1 | 1744 | package eu.kanade.tachiyomi.source.model
import android.net.Uri
import eu.kanade.tachiyomi.network.ProgressListener
import rx.subjects.Subject
import tachiyomi.source.model.PageUrl
open class Page(
val index: Int,
val url: String = "",
var imageUrl: String? = null,
@Transient var uri: Uri? = null // Deprecated but can't be deleted due to extensions
) : ProgressListener {
val number: Int
get() = index + 1
@Transient
@Volatile
var status: Int = 0
set(value) {
field = value
statusSubject?.onNext(value)
statusCallback?.invoke(this)
}
@Transient
@Volatile
var progress: Int = 0
set(value) {
field = value
statusCallback?.invoke(this)
}
@Transient
private var statusSubject: Subject<Int, Int>? = null
@Transient
private var statusCallback: ((Page) -> Unit)? = null
override fun update(bytesRead: Long, contentLength: Long, done: Boolean) {
progress = if (contentLength > 0) {
(100 * bytesRead / contentLength).toInt()
} else {
-1
}
}
fun setStatusSubject(subject: Subject<Int, Int>?) {
this.statusSubject = subject
}
fun setStatusCallback(f: ((Page) -> Unit)?) {
statusCallback = f
}
companion object {
const val QUEUE = 0
const val LOAD_PAGE = 1
const val DOWNLOAD_IMAGE = 2
const val READY = 3
const val ERROR = 4
}
}
fun Page.toPageUrl(): PageUrl {
return PageUrl(
url = this.imageUrl ?: this.url
)
}
fun PageUrl.toPage(index: Int): Page {
return Page(
index = index,
imageUrl = this.url
)
}
| apache-2.0 | 72e042d06bba4264a6f78f2ce397caa8 | 21.649351 | 88 | 0.583716 | 4.23301 | false | false | false | false |
consp1racy/android-commons | commons-services/src/main/java/net/xpece/android/app/SystemServiceDelegates.kt | 1 | 1139 | //@file:Suppress("unused")
//
//package net.xpece.android.app
//
//import android.content.Context
//import android.support.annotation.RequiresApi
//import java.lang.ref.WeakReference
//import java.util.*
//import kotlin.reflect.KProperty
//
//private val systemServiceDelegates = object :
// ThreadLocal<WeakHashMap<Context, SystemServiceDelegate>>() {
// override fun initialValue() = WeakHashMap<Context, SystemServiceDelegate>()
//}
//
//val Context.systemServiceDelegate: SystemServiceDelegate
// get() {
// val delegates = systemServiceDelegates.get()
// var delegate = delegates[this]
// if (delegate == null) {
// delegate = SystemServiceDelegate(this)
// delegates[this] = delegate
// }
// return delegate
// }
//
//class SystemServiceDelegate internal constructor(context: Context) {
// private val contextRef = WeakReference(context)
// val context = contextRef.get()!!
//
// @RequiresApi(23)
// inline operator fun <reified S> getValue(thisRef: Any?, property: KProperty<*>): S {
// return context.getSystemServiceOrThrow()
// }
//}
| apache-2.0 | 8b6f30a78eb2a776eab39f8dd5197568 | 31.542857 | 90 | 0.669886 | 4.298113 | false | false | false | false |
scymex/IntervalTimer | app/src/main/java/verseczi/intervaltimer/Main.kt | 1 | 17800 | package verseczi.intervaltimer
import android.app.Activity
import android.app.AlertDialog
import android.content.*
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.os.IBinder
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.text.SpannableStringBuilder
import android.view.MotionEvent
import android.view.View
import android.view.View.OnClickListener
import android.widget.*
import java.util.concurrent.TimeUnit
import android.text.Editable
import android.text.TextWatcher
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.CompoundButton
import android.widget.CompoundButton.OnCheckedChangeListener
import verseczi.intervaltimer.backgroundTask.appChooser
import verseczi.intervaltimer.backgroundTask.rootAccess
import verseczi.intervaltimer.data.Database
import verseczi.intervaltimer.helpers.bindView
class Main : AppCompatActivity() {
// Views
// @content_main_timelapse_calc.xml
private val etImgQty: EditText by bindView(R.id.etIMG_NUM)
private val etFPS: EditText by bindView(R.id.etFPS)
private val etInterval: EditText by bindView(R.id.etInterval)
// @content_main_infocard
private val tvImgQty: TextView by bindView(R.id.tvImg_num)
private val tvClipLength: TextView by bindView(R.id.tvCliplength)
private val tvDuration: TextView by bindView(R.id.tvDuration)
// @content_main_coordinate
private val tvCoordX: TextView by bindView(R.id.tv_CoordX)
private val tvCoordY: TextView by bindView(R.id.tv_CoordY)
// @content_main_delay
private val etDelay: EditText by bindView(R.id.etDelay)
private val swDelay: Switch by bindView(R.id.delayed_switch)
// @content_main_repeat
private val swEndlessrepeat: Switch by bindView(R.id.endless_switch)
// @content_main_app_chooser
private val ivAppIcon: ImageView by bindView(R.id.app_icon_n)
private val tvAppName: TextView by bindView(R.id.app_name_n)
private val tvAppPackageName: TextView by bindView(R.id.package_name_n)
// Buttons
private val bnStart: Button by bindView(R.id.start_button)
private val bnCoordinates: Button by bindView(R.id.getcoordinates)
private val bnChooseApp: Button by bindView(R.id.choose_app)
private val bnDelayMinus: Button by bindView(R.id.delay_minus)
private val bnDelayPlus: Button by bindView(R.id.delay_plus)
// Text of the views
var _ImgQty: Int
get() = etImgQty.text.toString().toInt()
set(value) {
etImgQty.text = SpannableStringBuilder("$value")
}
var _Interval: Int
get() = etInterval.text.toString().toInt()
set(value) {
etInterval.text = SpannableStringBuilder("$value")
}
var _FPS: Int
get() = etFPS.text.toString().toInt()
set(value) {
etFPS.text = SpannableStringBuilder("$value")
}
var _tvImgQty: Int
get() = tvImgQty.text.toString().toInt()
set(value) {
tvImgQty.text = value.toString()
}
var _ClipLength: Int
get() {
val durationRegex = tvClipLength.text.toString().split(":".toRegex())
return durationRegex[0].toInt() * 3600 + durationRegex[1].toInt() * 60 + durationRegex[2].toInt()
}
set(value) {
tvClipLength.text = formatTime(value)
}
var _Duration: Int
get() {
val durationRegex = tvDuration.text.toString().split(":".toRegex())
return durationRegex[0].toInt() * 3600 + durationRegex[1].toInt() * 60 + durationRegex[2].toInt()
}
set(value) {
tvDuration.text = formatTime(value)
}
var _coordX: Int
get() = tvCoordX.text.toString().toInt()
set(value) {
tvCoordX.text = SpannableStringBuilder("$value")
}
var _coordY: Int
get() = tvCoordY.text.toString().toInt()
set(value) {
tvCoordY.text = SpannableStringBuilder("$value")
}
var _delay: Int
get() = etDelay.text.toString().toInt()
set(value) {
etDelay.text = SpannableStringBuilder("$value")
}
var _delayed: Boolean
get() = swDelay.isChecked
set(value) {
swDelay.isChecked = value
}
var _endlessRepeat: Boolean
get() = swEndlessrepeat.isChecked
set(value) {
swEndlessrepeat.isChecked = value
}
var _appIcon: Drawable
get() = ivAppIcon.drawable
set(value) {
ivAppIcon.setImageDrawable(value)
}
var _appName: String
get() = tvAppName.text.toString()
set(value) {
tvAppName.text = value
}
var _appPackageName: String
get() = tvAppPackageName.text.toString()
set(value) {
tvAppPackageName.text = value
}
// Database
private lateinit var db: Database
// PackageManager
private lateinit var pm:PackageManager
// Context @Main
private lateinit var mContext: Context
private lateinit var _intentService: Intent
private var _clickingService: clickingService? = null
private var isCancelled: Boolean = false
private var currentProgressstate: Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(findViewById(R.id.toolbar) as Toolbar)
db = Database(this)
pm = packageManager
mContext = this
// Init
_ImgQty = db.imgQty
_Interval = db.interval
_coordX = db.coordinateX
_coordY = db.coordinateY
_delay = db.delay
_delayed = db.delayed
if(!db.delayed) {
_delay = 0
etDelay.isEnabled = false
bnDelayMinus.isEnabled = false
bnDelayPlus.isEnabled = false
bnDelayMinus.background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
bnDelayPlus.background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
}
_tvImgQty = db.imgQty
_FPS = db.FPS
_ClipLength = db.imgQty / db.FPS
_Duration = db.interval * db.imgQty
_endlessRepeat = db.endlessRepeat
try {
val appinfo: ApplicationInfo = pm.getApplicationInfo(db.packageName, 0)
_appIcon = pm.getApplicationIcon(appinfo)
_appName = pm.getApplicationLabel(appinfo).toString()
_appPackageName = db.packageName
} catch (e: PackageManager.NameNotFoundException) {
// :(
}
val clickListener: OnClickListener = OnClickListener { v ->
when (v.id) {
R.id.start_button -> startClickingService()
R.id.getcoordinates -> {
val intent = Intent(mContext, GetCoordinates::class.java)
startActivityForResult(intent, 1)
}
R.id.choose_app -> appChooser(this@Main, ivAppIcon, tvAppName, tvAppPackageName).execute()
}
}
class GenericTextWatcher(val view: View) : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
when (view) {
etImgQty -> {
if (etImgQty.text.toString() == "")
_ImgQty = 0
db.imgQty = _ImgQty
updateInfoBox(db.imgQty, db.FPS, db.interval)
}
etFPS -> {
if (etFPS.text.toString() == "")
_FPS = 0
db.FPS = _FPS
updateInfoBox(db.imgQty, db.FPS, db.interval)
}
etInterval -> {
if (etInterval.text.toString() == "")
_Interval = 0
db.interval = _Interval
updateInfoBox(db.imgQty, db.FPS, db.interval)
}
etDelay -> {
if (etDelay.text.toString() == "")
_delay = 0
if(_delay == 0) {
_delayed = false
db.delayed = false
db.delay = 0
} else
db.delay = _delay
}
}
}
}
class isCheckedListener(val view: View) : OnCheckedChangeListener {
override fun onCheckedChanged(buttonView: CompoundButton?, isChecked: Boolean) {
when (view) {
swDelay -> {
if (isChecked) {
db.delayed = true
if(_delay == 0)
db.delay = db.defaultValue(db._DELAY) as Int
_delay = db.delay
etDelay.isEnabled = true
bnDelayMinus.isEnabled = true
bnDelayPlus.isEnabled = true
bnDelayMinus.background.clearColorFilter()
bnDelayPlus.background.clearColorFilter()
} else {
db.delayed = false
_delay = 0
etDelay.isEnabled = false
bnDelayMinus.isEnabled = false
bnDelayPlus.isEnabled = false
bnDelayMinus.background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
bnDelayPlus.background.setColorFilter(Color.GRAY, PorterDuff.Mode.MULTIPLY)
}
}
}
}
}
etImgQty.addTextChangedListener(GenericTextWatcher(etImgQty))
etFPS.addTextChangedListener(GenericTextWatcher(etFPS))
etInterval.addTextChangedListener(GenericTextWatcher(etInterval))
etDelay.addTextChangedListener(GenericTextWatcher(etDelay))
swDelay.setOnCheckedChangeListener(isCheckedListener(swDelay))
swEndlessrepeat.setOnCheckedChangeListener(isCheckedListener(swEndlessrepeat))
bnStart.setOnClickListener(clickListener)
bnCoordinates.setOnClickListener(clickListener)
bnChooseApp.setOnClickListener(clickListener)
_intentService = Intent(this@Main, clickingService::class.java)
bindService(_intentService, mConnection, 0)
if (savedInstanceState == null) {
val extras = intent.extras
if (extras == null) {
isCancelled = false
} else {
isCancelled = extras.getBoolean("cancelled")
}
} else {
isCancelled = savedInstanceState.getSerializable("cancalled") as Boolean
}
}
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
val v: View = currentFocus
if ((ev.action == MotionEvent.ACTION_UP || ev.action == MotionEvent.ACTION_MOVE) && v is EditText && !v.javaClass.name.startsWith("android.webkit.")) {
val scrcoords: IntArray = IntArray(2)
v.getLocationOnScreen(scrcoords)
val x: Float = ev.rawX + v.getLeft() - scrcoords[0]
val y: Float = ev.rawY + v.getTop() - scrcoords[1]
if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
v.clearFocus()
hideKeyboard((this))
}
}
return super.dispatchTouchEvent(ev)
}
fun hideKeyboard(activity: Activity) {
if (activity.window != null && activity.window.decorView != null) {
val imm: InputMethodManager = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(activity.window.decorView.windowToken, 0)
}
}
val mConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceDisconnected(name: ComponentName) {
_clickingService = null
}
override fun onServiceConnected(name: ComponentName, service: IBinder) {
val mLocalBinder = service as clickingService.LocalBinder
_clickingService = mLocalBinder.getServerInstance()
if(!isCancelled)
_clickingService?.startClicking()
if (isCancelled) {
db.cancelled = false
isCancelled = false
currentProgressstate = _clickingService?.getProgress() as Int
_clickingService?.stopClicking()
val builder = AlertDialog.Builder(mContext)
builder.setTitle("Result")
builder.setMessage("Progress: " + currentProgressstate + " / " + db.imgQty + "\n " +
"Do you want to continue?")
builder.setPositiveButton("Yes") { dialog, id ->
_clickingService?.resumeClicking()
startChoosedApp()
}
builder.setNegativeButton("No") { dialog, id ->
_clickingService?.stopService()
dialog.cancel()
}
builder.setOnCancelListener {
_clickingService?.stopService()
}
val dialog = builder.create()
dialog.show()
}
}
}
val receiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
context.unregisterReceiver(this)
val access = intent.getBooleanExtra("accessGranted", false)
if (access) {
if(isCancelled)
startClickingService(db.imgQty - currentProgressstate, false, true)
else
startClickingService(db.imgQty, db.delayed, true)
} else {
rootDenied()
}
}
}
fun rootDenied() {
val builder = AlertDialog.Builder(mContext)
builder.setTitle("Root access denied!")
builder.setMessage("You need to have root access for your device!")
builder.setPositiveButton("Ok") { dialog, id -> dialog.cancel() }
builder.create().show()
}
fun didntChooseApp() {
val builder = AlertDialog.Builder(mContext)
builder.setTitle("Wrong settings!")
builder.setMessage("You didn't choose any app!")
builder.setPositiveButton("Ok") { dialog, id -> dialog.cancel() }
builder.create().show()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
if (requestCode == 1) {
if (resultCode == 1) {
db.coordinateX = data.getIntExtra("coordx", 0)
db.coordinateY = data.getIntExtra("coordy", 0)
tvCoordX.text = Integer.toString(db.coordinateX)
tvCoordY.text = Integer.toString(db.coordinateY)
}
}
}//onActivityResult
fun startClickingService(_imqty: Int = db.imgQty, delayed: Boolean = db.delayed, rootGranted: Boolean = false) {
if(pm.getLaunchIntentForPackage(db.packageName) != null) {
// Getting root access
if (!rootGranted) {
val rootaccess = rootAccess(this@Main)
val filtera = IntentFilter()
filtera.addAction(rootaccess.rootaccess)
registerReceiver(receiver, filtera)
rootaccess.execute()
}
// Start and bind service if we have root access
if (rootGranted) {
bindService(_intentService, mConnection, 0)
_intentService.putExtra("imgqty", _imqty)
_intentService.putExtra("delayed", delayed)
startService(_intentService)
startChoosedApp()
}
} else
didntChooseApp()
}
fun startChoosedApp () {
try {
pm = packageManager
var LaunchIntent: Intent = pm.getLaunchIntentForPackage(db.packageName)
startActivity( LaunchIntent )
} catch (e: PackageManager.NameNotFoundException) {
e.printStackTrace()
}
}
fun updateInfoBox(imgQty: Int, fps: Int, interval: Int) {
_tvImgQty = imgQty
_ClipLength = imgQty / fps
_Duration = interval * imgQty
}
fun formatTime(value: Int): String {
val durationS = value.toLong()
return String.format("%02d:%02d:%02d", TimeUnit.SECONDS.toHours(durationS),
TimeUnit.SECONDS.toMinutes(durationS) - TimeUnit.HOURS.toMinutes(TimeUnit.SECONDS.toHours(durationS)),
durationS - TimeUnit.MINUTES.toSeconds(TimeUnit.SECONDS.toMinutes(durationS)))
}
fun increaseInteger(view: View) {
var tv: TextView = findViewById(view.labelFor) as TextView
tv.text = (tv.text.toString().toInt() + 1).toString()
}
fun decreaseInteger(view: View) {
var tv: TextView = findViewById(view.labelFor) as TextView
tv.text = (tv.text.toString().toInt() - 1).toString()
}
} | mit | 82016eb7f4717ead010aead0f27ffb53 | 37.036325 | 159 | 0.577528 | 4.955457 | false | false | false | false |
Kotlin/dokka | runners/gradle-plugin/src/main/kotlin/org/jetbrains/dokka/gradle/DokkaMultiModuleFileLayout.kt | 1 | 3319 | package org.jetbrains.dokka.gradle
import org.jetbrains.dokka.DokkaException
import java.io.File
/**
* @see DokkaMultiModuleFileLayout.targetChildOutputDirectory
* @see NoCopy
* @see CompactInParent
*/
fun interface DokkaMultiModuleFileLayout {
/**
* @param parent: The [DokkaMultiModuleTask] that is initiating a composite documentation run
* @param child: Some child task registered in [parent]
* @return The target output directory of the [child] dokka task referenced by [parent]. This should
* be unique for all registered child tasks.
*/
fun targetChildOutputDirectory(parent: DokkaMultiModuleTask, child: AbstractDokkaTask): File
/**
* Will link to the original [AbstractDokkaTask.outputDirectory]. This requires no copying of the output files.
*/
object NoCopy : DokkaMultiModuleFileLayout {
override fun targetChildOutputDirectory(parent: DokkaMultiModuleTask, child: AbstractDokkaTask): File =
child.outputDirectory.getSafe()
}
/**
* Will point to a subfolder inside the output directory of the parent.
* The subfolder will follow the structure of the gradle project structure
* e.g.
* :parentProject:firstAncestor:secondAncestor will be be resolved to
* {parent output directory}/firstAncestor/secondAncestor
*/
object CompactInParent : DokkaMultiModuleFileLayout {
override fun targetChildOutputDirectory(parent: DokkaMultiModuleTask, child: AbstractDokkaTask): File {
val relativeProjectPath = parent.project.relativeProjectPath(child.project.path)
val relativeFilePath = relativeProjectPath.replace(":", File.separator)
check(!File(relativeFilePath).isAbsolute) { "Unexpected absolute path $relativeFilePath" }
return parent.outputDirectory.getSafe().resolve(relativeFilePath)
}
}
}
internal fun DokkaMultiModuleTask.targetChildOutputDirectory(
child: AbstractDokkaTask
): File = fileLayout.get().targetChildOutputDirectory(this, child)
internal fun DokkaMultiModuleTask.copyChildOutputDirectories() {
childDokkaTasks.forEach { child ->
this.copyChildOutputDirectory(child)
}
}
internal fun DokkaMultiModuleTask.copyChildOutputDirectory(child: AbstractDokkaTask) {
val targetChildOutputDirectory = project.file(fileLayout.get().targetChildOutputDirectory(this, child))
val sourceChildOutputDirectory = child.outputDirectory.getSafe()
/* Pointing to the same directory -> No copy necessary */
if (sourceChildOutputDirectory.absoluteFile == targetChildOutputDirectory.absoluteFile) {
return
}
/* Cannot target *inside* the original folder */
if (targetChildOutputDirectory.absoluteFile.startsWith(sourceChildOutputDirectory.absoluteFile)) {
throw DokkaException(
"Cannot re-locate output directory into itself.\n" +
"sourceChildOutputDirectory=${sourceChildOutputDirectory.path}\n" +
"targetChildOutputDirectory=${targetChildOutputDirectory.path}"
)
}
/* Source output directory is empty -> No copy necessary */
if (!sourceChildOutputDirectory.exists()) {
return
}
sourceChildOutputDirectory.copyRecursively(targetChildOutputDirectory, overwrite = true)
}
| apache-2.0 | e827aef455682cbe6d7068fea4a8b60c | 39.47561 | 115 | 0.731244 | 5.550167 | false | false | false | false |
spinnaker/keiko | keiko-redis-spring/src/main/kotlin/com/netflix/spinnaker/config/RedisQueueConfiguration.kt | 1 | 7051 | /*
* 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 com.netflix.spinnaker.config
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.netflix.spinnaker.q.metrics.EventPublisher
import com.netflix.spinnaker.q.migration.SerializationMigrator
import com.netflix.spinnaker.q.redis.RedisClusterDeadMessageHandler
import com.netflix.spinnaker.q.redis.RedisClusterQueue
import com.netflix.spinnaker.q.redis.RedisDeadMessageHandler
import com.netflix.spinnaker.q.redis.RedisQueue
import java.net.URI
import java.time.Clock
import java.time.Duration
import java.util.Optional
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import redis.clients.jedis.HostAndPort
import redis.clients.jedis.Jedis
import redis.clients.jedis.JedisCluster
import redis.clients.jedis.JedisPool
import redis.clients.jedis.Protocol
import redis.clients.jedis.util.Pool
@Configuration
@EnableConfigurationProperties(RedisQueueProperties::class)
@ConditionalOnProperty(
value = ["keiko.queue.redis.enabled"],
havingValue = "true",
matchIfMissing = true
)
class RedisQueueConfiguration {
@Bean
@ConditionalOnMissingBean(GenericObjectPoolConfig::class)
fun redisPoolConfig() = GenericObjectPoolConfig<Any>().apply {
blockWhenExhausted = false
maxWaitMillis = 2000
}
@Bean
@ConditionalOnMissingBean(name = ["queueRedisPool"])
@ConditionalOnProperty(
value = ["redis.cluster-enabled"],
havingValue = "false",
matchIfMissing = true
)
fun queueRedisPool(
@Value("\${redis.connection:redis://localhost:6379}") connection: String,
@Value("\${redis.timeout:2000}") timeout: Int,
redisPoolConfig: GenericObjectPoolConfig<Any>
) =
URI.create(connection).let { cx ->
val port = if (cx.port == -1) Protocol.DEFAULT_PORT else cx.port
val db = if (cx.path.isNullOrEmpty()) {
Protocol.DEFAULT_DATABASE
} else {
cx.path.substringAfter("/").toInt()
}
val password = cx.userInfo?.substringAfter(":")
JedisPool(redisPoolConfig, cx.host, port, timeout, password, db)
}
@Bean
@ConditionalOnMissingBean(name = ["queue"])
@ConditionalOnProperty(
value = ["redis.cluster-enabled"],
havingValue = "false",
matchIfMissing = true
)
fun queue(
@Qualifier("queueRedisPool") redisPool: Pool<Jedis>,
redisQueueProperties: RedisQueueProperties,
clock: Clock,
deadMessageHandler: RedisDeadMessageHandler,
publisher: EventPublisher,
redisQueueObjectMapper: ObjectMapper,
serializationMigrator: Optional<SerializationMigrator>
) =
RedisQueue(
queueName = redisQueueProperties.queueName,
pool = redisPool,
clock = clock,
mapper = redisQueueObjectMapper,
deadMessageHandlers = listOf(deadMessageHandler),
publisher = publisher,
ackTimeout = Duration.ofSeconds(redisQueueProperties.ackTimeoutSeconds.toLong()),
serializationMigrator = serializationMigrator
)
@Bean
@ConditionalOnMissingBean(name = ["redisDeadMessageHandler"])
@ConditionalOnProperty(
value = ["redis.cluster-enabled"],
havingValue = "false",
matchIfMissing = true
)
fun redisDeadMessageHandler(
@Qualifier("queueRedisPool") redisPool: Pool<Jedis>,
redisQueueProperties: RedisQueueProperties,
clock: Clock
) =
RedisDeadMessageHandler(
deadLetterQueueName = redisQueueProperties.deadLetterQueueName,
pool = redisPool,
clock = clock
)
@Bean
@ConditionalOnMissingBean(name = ["queueRedisCluster"])
@ConditionalOnProperty(value = ["redis.cluster-enabled"])
fun queueRedisCluster(
@Value("\${redis.connection:redis://localhost:6379}") connection: String,
@Value("\${redis.timeout:2000}") timeout: Int,
@Value("\${redis.maxattempts:4}") maxAttempts: Int,
redisPoolConfig: GenericObjectPoolConfig<Any>
): JedisCluster {
URI.create(connection).let { cx ->
val port = if (cx.port == -1) Protocol.DEFAULT_PORT else cx.port
val password = cx.userInfo?.substringAfter(":")
return JedisCluster(
HostAndPort(cx.host, port),
timeout,
timeout,
maxAttempts,
password,
redisPoolConfig
)
}
}
@Bean
@ConditionalOnMissingBean(name = ["queue", "clusterQueue"])
@ConditionalOnProperty(value = ["redis.cluster-enabled"])
fun clusterQueue(
@Qualifier("queueRedisCluster") cluster: JedisCluster,
redisQueueProperties: RedisQueueProperties,
clock: Clock,
deadMessageHandler: RedisClusterDeadMessageHandler,
publisher: EventPublisher,
redisQueueObjectMapper: ObjectMapper,
serializationMigrator: Optional<SerializationMigrator>
) =
RedisClusterQueue(
queueName = redisQueueProperties.queueName,
jedisCluster = cluster,
clock = clock,
mapper = redisQueueObjectMapper,
deadMessageHandlers = listOf(deadMessageHandler),
publisher = publisher,
ackTimeout = Duration.ofSeconds(redisQueueProperties.ackTimeoutSeconds.toLong()),
serializationMigrator = serializationMigrator
)
@Bean
@ConditionalOnMissingBean(name = ["redisClusterDeadMessageHandler"])
@ConditionalOnProperty(value = ["redis.cluster-enabled"])
fun redisClusterDeadMessageHandler(
@Qualifier("queueRedisCluster") cluster: JedisCluster,
redisQueueProperties: RedisQueueProperties,
clock: Clock
) = RedisClusterDeadMessageHandler(
deadLetterQueueName = redisQueueProperties.deadLetterQueueName,
jedisCluster = cluster,
clock = clock
)
@Bean
@ConditionalOnMissingBean
fun redisQueueObjectMapper(properties: Optional<ObjectMapperSubtypeProperties>): ObjectMapper =
ObjectMapper().apply {
registerModule(KotlinModule())
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
SpringObjectMapperConfigurer(
properties.orElse(ObjectMapperSubtypeProperties())
).registerSubtypes(this)
}
}
| apache-2.0 | 13cc11b8c7dcf06262fe661d03f33d32 | 34.079602 | 97 | 0.746277 | 4.986563 | false | true | false | false |
adelnizamutdinov/headphone-reminder | app/src/test/kotlin/common/view/RecyclerViewTest.kt | 1 | 1356 | package common.view
import android.view.View
import android.widget.FrameLayout
import common.robolectric
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class RecyclerViewTest {
@Test fun testClicks() {
var clicks = 0
val v = View(robolectric)
val a = RecyclerViewAdapter({ 1 },
{ 1 },
{ p, type -> v },
{ vh, pos -> },
{ clicks++ })
a.onCreateViewHolder(FrameLayout(robolectric), 1)
v.performClick()
assertThat(clicks).isEqualTo(1)
v.performClick()
v.performClick()
assertThat(clicks).isEqualTo(3)
}
@Test fun testBinds() {
var binds = 0
val a = RecyclerViewAdapter({ 1 },
{ 1 },
{ p, type -> View(robolectric) },
{ vh, pos -> binds++ },
{ })
val vh = a.onCreateViewHolder(FrameLayout(robolectric), 1)
a.onBindViewHolder(vh, 1)
assertThat(binds).isEqualTo(1)
a.onBindViewHolder(vh, 2)
a.onBindViewHolder(vh, 3)
assertThat(binds).isEqualTo(3)
}
@Test fun testInflates() {
}
} | mit | 973310c5df21f58aee3a32a57e06d1b3 | 27.87234 | 65 | 0.553835 | 4.59661 | false | true | false | false |
jponge/vertx-gradle-plugin | src/main/kotlin/io/vertx/gradle/VertxExtension.kt | 1 | 2059 | /*
* Copyright 2017-2019 Red Hat, 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.vertx.gradle
import org.gradle.api.Project
/**
* Vertx Gradle extension.
*
* @author [Julien Ponge](https://julien.ponge.org/)
*/
open class VertxExtension(private val project: Project) {
var vertxVersion = "4.1.2"
var launcher = "io.vertx.core.Launcher"
var mainVerticle = ""
var args = listOf<String>()
var config = ""
var workDirectory = project.projectDir.absolutePath
var jvmArgs = listOf<String>()
var redeploy = true
var watch = listOf("${project.projectDir.absolutePath}/src/**/*")
var onRedeploy = listOf("classes")
var redeployScanPeriod = 1000L
var redeployGracePeriod = 1000L
var redeployTerminationPeriod = 1000L
var debugPort = 5005L
var debugSuspend = false
override fun toString(): String {
return "VertxExtension(project=$project, vertxVersion='$vertxVersion', launcher='$launcher', mainVerticle='$mainVerticle', args=$args, config='$config', workDirectory='$workDirectory', jvmArgs=$jvmArgs, redeploy=$redeploy, watch=$watch, onRedeploy='$onRedeploy', redeployScanPeriod=$redeployScanPeriod, redeployGracePeriod=$redeployGracePeriod, redeployTerminationPeriod=$redeployTerminationPeriod, debugPort=$debugPort, debugSuspend=$debugSuspend)"
}
}
/**
* Extension method to make easier the configuration of the plugin when used with the Gradle Kotlin DSL
*/
fun Project.vertx(configure: VertxExtension.() -> Unit) =
extensions.configure(VertxExtension::class.java, configure)
| apache-2.0 | 28aab2ba3b115c513e54f74d58c11918 | 35.122807 | 453 | 0.743079 | 4.168016 | false | true | false | false |
tutao/tutanota | app-android/app/src/main/java/de/tutao/tutanota/push/LocalNotificationsFacade.kt | 1 | 14114 | package de.tutao.tutanota.push
import android.annotation.TargetApi
import android.app.*
import android.content.ClipData
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.media.AudioAttributes
import android.media.RingtoneManager
import android.os.Build
import android.util.Log
import androidx.annotation.ColorInt
import androidx.annotation.StringRes
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.core.content.FileProvider
import androidx.core.net.toUri
import de.tutao.tutanota.*
import java.io.File
import java.util.concurrent.ConcurrentHashMap
const val NOTIFICATION_DISMISSED_ADDR_EXTRA = "notificationDismissed"
private const val EMAIL_NOTIFICATION_CHANNEL_ID = "notifications"
private val VIBRATION_PATTERN = longArrayOf(100, 200, 100, 200)
private const val NOTIFICATION_EMAIL_GROUP = "de.tutao.tutanota.email"
private const val SUMMARY_NOTIFICATION_ID = 45
private const val PERSISTENT_NOTIFICATION_CHANNEL_ID = "service_intent"
private const val ALARM_NOTIFICATION_CHANNEL_ID = "alarms"
private const val DOWNLOAD_NOTIFICATION_CHANNEL_ID = "downloads"
class LocalNotificationsFacade(private val context: Context) {
private val notificationManager: NotificationManager
get() = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
private val aliasNotification: MutableMap<String, LocalNotificationInfo> = ConcurrentHashMap()
fun makeConnectionNotification(): Notification {
return NotificationCompat.Builder(context, PERSISTENT_NOTIFICATION_CHANNEL_ID)
.setContentTitle("Notification service")
.setContentText("Syncing notifications")
.setSmallIcon(R.drawable.ic_status)
.setProgress(0, 0, true)
.build()
}
fun notificationDismissed(dismissAdders: List<String>?, isSummary: Boolean) {
if (isSummary) {
// If the user clicked on summary directly, reset counter for all notifications
aliasNotification.clear()
} else {
if (dismissAdders != null) {
for (addr in dismissAdders) {
aliasNotification.remove(addr)
notificationManager.cancel(makeNotificationId(addr))
}
}
}
if (aliasNotification.isEmpty()) {
notificationManager.cancel(SUMMARY_NOTIFICATION_ID)
} else {
var allAreZero = true
for (info in aliasNotification.values) {
if (info.counter > 0) {
allAreZero = false
break
}
}
if (allAreZero) {
notificationManager.cancel(SUMMARY_NOTIFICATION_ID)
} else {
for (info in aliasNotification.values) {
if (info.counter > 0) {
sendSummaryNotification(
notificationManager,
info.message, info.notificationInfo, false
)
break
}
}
}
}
}
fun sendEmailNotifications(notificationInfos: List<NotificationInfo>) {
if (notificationInfos.isEmpty()) {
return
}
val title = context.getString(R.string.pushNewMail_msg)
for (notificationInfo in notificationInfos) {
val counterPerAlias = aliasNotification[notificationInfo.mailAddress]?.incremented(notificationInfo.counter)
?: LocalNotificationInfo(
title,
notificationInfo.counter, notificationInfo
)
aliasNotification[notificationInfo.mailAddress] = counterPerAlias
val notificationId = makeNotificationId(notificationInfo.mailAddress)
@ColorInt val redColor = context.resources.getColor(R.color.red, context.theme)
val notificationBuilder = NotificationCompat.Builder(context, EMAIL_NOTIFICATION_CHANNEL_ID)
.setLights(redColor, 1000, 1000)
notificationBuilder.setContentTitle(title)
.setColor(redColor)
.setContentText(notificationContent(notificationInfo.mailAddress))
.setNumber(counterPerAlias.counter)
.setSmallIcon(R.drawable.ic_status)
.setDeleteIntent(intentForDelete(arrayListOf(notificationInfo.mailAddress)))
.setContentIntent(intentOpenMailbox(notificationInfo, false))
.setGroup(NOTIFICATION_EMAIL_GROUP)
.setAutoCancel(true)
.setGroupAlertBehavior(if (atLeastNougat()) NotificationCompat.GROUP_ALERT_CHILDREN else NotificationCompat.GROUP_ALERT_SUMMARY)
.setDefaults(Notification.DEFAULT_ALL)
notificationManager.notify(notificationId, notificationBuilder.build())
}
sendSummaryNotification(
notificationManager, title,
notificationInfos[0], true
)
}
@TargetApi(Build.VERSION_CODES.Q)
fun sendDownloadFinishedNotification(fileName: String?) {
val notificationManager = NotificationManagerCompat.from(context)
val channel = NotificationChannel(
"downloads",
"Downloads",
NotificationManager.IMPORTANCE_DEFAULT
)
notificationManager.createNotificationChannel(channel)
val pendingIntent = PendingIntent.getActivity(
context,
1,
Intent(DownloadManager.ACTION_VIEW_DOWNLOADS),
PendingIntent.FLAG_IMMUTABLE
)
val notification = Notification.Builder(context, channel.id)
.setContentIntent(pendingIntent)
.setContentTitle(fileName)
.setContentText(context.getText(R.string.downloadCompleted_msg))
.setSmallIcon(R.drawable.ic_download)
.setAutoCancel(true)
.build()
notificationManager.notify(makeNotificationId("downloads"), notification)
}
private fun sendSummaryNotification(
notificationManager: NotificationManager,
title: String,
notificationInfo: NotificationInfo,
sound: Boolean,
) {
var summaryCounter = 0
val addresses = arrayListOf<String>()
val inboxStyle = NotificationCompat.InboxStyle()
for ((key, value) in aliasNotification) {
val count = value.counter
if (count > 0) {
summaryCounter += count
inboxStyle.addLine(notificationContent(key))
addresses.add(key)
}
}
val builder = NotificationCompat.Builder(context, EMAIL_NOTIFICATION_CHANNEL_ID)
.setBadgeIconType(NotificationCompat.BADGE_ICON_SMALL)
@ColorInt val red = context.resources.getColor(R.color.red, context.theme)
val notification = builder.setContentTitle(title)
.setContentText(notificationContent(notificationInfo.mailAddress))
.setSmallIcon(R.drawable.ic_status)
.setGroup(NOTIFICATION_EMAIL_GROUP)
.setGroupSummary(true)
.setColor(red)
.setNumber(summaryCounter)
.setStyle(inboxStyle)
.setContentIntent(intentOpenMailbox(notificationInfo, true))
.setDeleteIntent(intentForDelete(addresses))
.setAutoCancel(true) // We need to update summary without sound when one of the alarms is cancelled
// but we need to use sound if it's API < N because GROUP_ALERT_CHILDREN doesn't
// work with sound there (pehaps summary consumes it somehow?) and we must do
// summary with sound instead on the old versions.
.setDefaults(if (sound) NotificationCompat.DEFAULT_SOUND or NotificationCompat.DEFAULT_VIBRATE else 0)
.setGroupAlertBehavior(if (atLeastNougat()) NotificationCompat.GROUP_ALERT_CHILDREN else NotificationCompat.GROUP_ALERT_SUMMARY)
.build()
notificationManager.notify(SUMMARY_NOTIFICATION_ID, notification)
}
fun showErrorNotification(@StringRes message: Int, exception: Throwable?) {
val intent = Intent(context, MainActivity::class.java)
.setAction(Intent.ACTION_SEND)
.setType("text/plain")
.putExtra(Intent.EXTRA_SUBJECT, "Alarm error v" + BuildConfig.VERSION_NAME)
if (exception != null) {
val stackTrace = Log.getStackTraceString(exception)
val errorString = "${exception.message}\n$stackTrace"
intent.clipData = ClipData.newPlainText("error", errorString)
}
val notification: Notification =
NotificationCompat.Builder(context, ALARM_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_status)
.setContentTitle(context.getString(R.string.app_name))
.setContentText(context.getString(message))
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setStyle(NotificationCompat.BigTextStyle())
.setContentIntent(
PendingIntent.getActivity(
context,
(Math.random() * 20000).toInt(),
intent,
PendingIntent.FLAG_UPDATE_CURRENT
)
)
.setAutoCancel(true)
.build()
notificationManager.notify(1000, notification)
}
@TargetApi(Build.VERSION_CODES.O)
fun createNotificationChannels() {
val mailNotificationChannel = NotificationChannel(
EMAIL_NOTIFICATION_CHANNEL_ID,
context.getString(R.string.pushNewMail_msg),
NotificationManager.IMPORTANCE_DEFAULT
).default()
notificationManager.createNotificationChannel(mailNotificationChannel)
val serviceNotificationChannel = NotificationChannel(
PERSISTENT_NOTIFICATION_CHANNEL_ID, context.getString(R.string.notificationSync_msg),
NotificationManager.IMPORTANCE_LOW
)
notificationManager.createNotificationChannel(serviceNotificationChannel)
val alarmNotificationsChannel = NotificationChannel(
ALARM_NOTIFICATION_CHANNEL_ID,
context.getString(R.string.reminder_label),
NotificationManager.IMPORTANCE_HIGH
).default()
notificationManager.createNotificationChannel(alarmNotificationsChannel)
val downloadNotificationsChannel = NotificationChannel(
DOWNLOAD_NOTIFICATION_CHANNEL_ID,
context.getString(R.string.downloadCompleted_msg),
NotificationManager.IMPORTANCE_DEFAULT
)
downloadNotificationsChannel.setShowBadge(false)
notificationManager.createNotificationChannel(downloadNotificationsChannel)
}
@TargetApi(Build.VERSION_CODES.O)
private fun NotificationChannel.default(): NotificationChannel {
val ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION)
val att = AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_NOTIFICATION)
.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
.build()
setShowBadge(true)
setSound(ringtoneUri, att)
enableLights(true)
vibrationPattern = VIBRATION_PATTERN
lightColor = Color.RED
return this
}
private fun notificationContent(address: String): String {
return aliasNotification[address]!!.counter.toString() + " " + address
}
private fun makeNotificationId(address: String): Int {
return Math.abs(1 + address.hashCode())
}
private fun intentForDelete(addresses: ArrayList<String>): PendingIntent {
val deleteIntent = Intent(context, PushNotificationService::class.java)
deleteIntent.putStringArrayListExtra(NOTIFICATION_DISMISSED_ADDR_EXTRA, addresses)
return PendingIntent.getService(
context.applicationContext,
makeNotificationId("dismiss${addresses.joinToString("+")}"),
deleteIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
private fun intentOpenMailbox(
notificationInfo: NotificationInfo,
isSummary: Boolean,
): PendingIntent {
val openMailboxIntent = Intent(context, MainActivity::class.java)
openMailboxIntent.action = MainActivity.OPEN_USER_MAILBOX_ACTION
openMailboxIntent.putExtra(
MainActivity.OPEN_USER_MAILBOX_MAIL_ADDRESS_KEY,
notificationInfo.mailAddress
)
openMailboxIntent.putExtra(
MainActivity.OPEN_USER_MAILBOX_USERID_KEY,
notificationInfo.userId
)
openMailboxIntent.putExtra(MainActivity.IS_SUMMARY_EXTRA, isSummary)
return PendingIntent.getActivity(
context.applicationContext,
makeNotificationId(notificationInfo.mailAddress + "@isSummary" + isSummary),
openMailboxIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
}
fun notificationDismissedIntent(
context: Context,
emailAddresses: ArrayList<String>,
sender: String,
isSummary: Boolean,
): Intent {
val deleteIntent = Intent(context, PushNotificationService::class.java)
deleteIntent.putStringArrayListExtra(NOTIFICATION_DISMISSED_ADDR_EXTRA, emailAddresses)
deleteIntent.putExtra("sender", sender)
deleteIntent.putExtra(MainActivity.IS_SUMMARY_EXTRA, isSummary)
return deleteIntent
}
fun showAlarmNotification(context: Context, timestamp: Long, summary: String, intent: Intent) {
val contentText = String.format("%tR %s", timestamp, summary)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
@ColorInt val red = context.resources.getColor(R.color.red, context.theme)
notificationManager.notify(
System.currentTimeMillis().toInt(),
NotificationCompat.Builder(context, ALARM_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_status)
.setContentTitle(context.getString(R.string.reminder_label))
.setContentText(contentText)
.setDefaults(NotificationCompat.DEFAULT_ALL)
.setColor(red)
.setContentIntent(openCalendarIntent(context, intent))
.setAutoCancel(true)
.build()
)
}
private fun openCalendarIntent(context: Context, alarmIntent: Intent): PendingIntent {
val userId = alarmIntent.getStringExtra(MainActivity.OPEN_USER_MAILBOX_USERID_KEY)
val openCalendarEventIntent = Intent(context, MainActivity::class.java)
openCalendarEventIntent.action = MainActivity.OPEN_CALENDAR_ACTION
openCalendarEventIntent.putExtra(MainActivity.OPEN_USER_MAILBOX_USERID_KEY, userId)
return PendingIntent.getActivity(
context,
alarmIntent.data.toString().hashCode(),
openCalendarEventIntent,
PendingIntent.FLAG_UPDATE_CURRENT
)
}
/**
* create a notification that starts a new task and gives it access to the downloaded file
* to view it.
*/
fun showDownloadNotification(context: Context, file: File) {
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val uri = FileProvider.getUriForFile(context, BuildConfig.FILE_PROVIDER_AUTHORITY, file)
val mimeType = getMimeType(file.toUri(), context)
val intent = Intent(Intent.ACTION_VIEW).apply {
flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_GRANT_READ_URI_PERMISSION
setDataAndType(uri, mimeType)
}
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_IMMUTABLE);
notificationManager.notify(System.currentTimeMillis().toInt(),
NotificationCompat.Builder(context, DOWNLOAD_NOTIFICATION_CHANNEL_ID)
.setSmallIcon(R.drawable.ic_download)
.setContentTitle(context.getString(R.string.downloadCompleted_msg))
.setContentText(file.name)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.build()
)
} | gpl-3.0 | d31cff0a0cbfecbee553196c631420b3 | 35.950262 | 133 | 0.76952 | 4.233353 | false | false | false | false |
jpmoreto/play-with-robots | android/app/src/main/java/jpm/android/robot/RobotDimensions.kt | 1 | 2518 | package jpm.android.robot
/**
* Created by jm on 17/01/17.
*
*
* see drawings:
* /opt/docs/ARDUINO/myStufs/robot/openscad/robot_diagram.dxf
* /opt/docs/ARDUINO/myStufs/robot/openscad/robot_diagram_symbols.dxf
* /opt/docs/ARDUINO/myStufs/robot/openscad/trignometria.dxf
*
* resume:
* - Y axis aligned with length positive angle to front
* - X axis aligned with width positive angle to right
* - 0 º angle aligned with front, rotate clockwise
*/
object RobotDimensions {
data class SonarInfo(val angleDeg: Int, val angleRad: Double, val x: Double, val y: Double)
// units meters:
//
val robotCircleRadius = 0.07 // BW / 2
val robotRectLength = 0.056 // BSd
val bodyWidth = 2 * robotCircleRadius // BW
val bodyTotalLength = 2 * robotCircleRadius + robotRectLength // Bl
val wheelBodyDistance = 0.005 //
val wheelRadius = 0.0325 // Wd / 2
val wheelWidth = 0.026 // Ww
val distanceWheel = bodyWidth + wheelWidth + 2 * wheelBodyDistance // BWw
val wheelAxisLenght = 0.075 // BWl
val robotTotalWidth = bodyWidth + 2 * (wheelBodyDistance + wheelWidth)
val sonarAngle = 30 // usDelta
val wheelSensorTicksPerRotation = 100
val sonarSensors = Array(12) { i ->
val angleDeg = i * sonarAngle
val angleRad = Math.toRadians(angleDeg.toDouble())
val (x,y) = when(i) {
9 -> Pair(-robotCircleRadius, 0.0) // left
3 -> Pair( robotCircleRadius, 0.0) // right
0 -> Pair(0.0, robotRectLength / 2.0 + robotCircleRadius) // front
6 -> Pair(0.0, -robotRectLength / 2.0 - robotCircleRadius) // back
4,5,7,8 -> Pair(robotCircleRadius * Math.sin(angleRad), -robotRectLength / 2.0 + robotCircleRadius * Math.cos(angleRad)) // negative Y
else -> Pair(robotCircleRadius * Math.sin(angleRad), robotRectLength / 2.0 + robotCircleRadius * Math.cos(angleRad)) // positive Y (1,2,10,11)
}
SonarInfo(angleDeg, angleRad, x, y)
}
/*
init {
var i = 0
sonarSensors.forEach { s ->
println("Sendor($i) \t= $s\n")
i += 1
}
}
*/
} | mit | 95a4d84e4afb79b846cd021178378626 | 38.34375 | 158 | 0.534764 | 3.945141 | false | false | false | false |
empros-gmbh/kmap | data/src/main/kotlin/ch/empros/kmap/Query.kt | 1 | 748 | package ch.empros.kmap
interface Query {
val pagedQuery: String
val pageSize: Int
val startPage: Int
fun nextPage(): Query
}
/**
* A [SqlQuery] object can be used to create pageable data sources, see [KMap.pageObservableFrom].
* Note: [startPage] is zero-based, ie. the first page is at index 0.
*/
data class SqlQuery(private val query: String, override val pageSize: Int = 50, override val startPage: Int = 0) : Query {
init {
require(pageSize > 0, { "PageSize must be > 0, but got: $pageSize" })
require(startPage > -1, { "StartPage must >= 0, but got: $startPage" })
}
override val pagedQuery = "$query LIMIT $pageSize OFFSET ${startPage * pageSize}"
override fun nextPage() = copy(startPage = startPage + 1)
}
| mit | db886301deb4b59be00ff0404c49bc16 | 28.92 | 122 | 0.683155 | 3.64878 | false | false | false | false |
blackbbc/Tucao | app/src/main/kotlin/me/sweetll/tucao/business/home/fragment/AnimationFragment.kt | 1 | 6497 | package me.sweetll.tucao.business.home.fragment
import android.annotation.TargetApi
import androidx.databinding.DataBindingUtil
import android.os.Build
import android.os.Bundle
import androidx.core.app.ActivityOptionsCompat
import androidx.core.util.Pair
import android.transition.ArcMotion
import android.transition.ChangeBounds
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.transition.TransitionManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import me.sweetll.tucao.R
import me.sweetll.tucao.base.BaseFragment
import me.sweetll.tucao.business.channel.ChannelDetailActivity
import me.sweetll.tucao.business.home.adapter.AnimationAdapter
import me.sweetll.tucao.business.home.viewmodel.AnimationViewModel
import me.sweetll.tucao.business.video.VideoActivity
import me.sweetll.tucao.databinding.FragmentAnimationBinding
import me.sweetll.tucao.databinding.HeaderAnimationBinding
import me.sweetll.tucao.model.raw.Animation
class AnimationFragment : BaseFragment() {
lateinit var binding: FragmentAnimationBinding
val viewModel = AnimationViewModel(this)
val animationAdapter = AnimationAdapter(null)
var isLoad = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_animation, container, false)
binding.viewModel = viewModel
binding.loading.show()
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.swipeRefresh.isEnabled = false
binding.swipeRefresh.setColorSchemeResources(R.color.colorPrimary)
binding.swipeRefresh.setOnRefreshListener {
viewModel.loadData()
}
binding.errorStub.setOnInflateListener {
_, inflated ->
inflated.setOnClickListener {
viewModel.loadData()
}
}
setupRecyclerView()
loadWhenNeed()
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
initTransition()
}
}
fun setupRecyclerView() {
val headerBinding: HeaderAnimationBinding = DataBindingUtil.inflate(LayoutInflater.from(activity), R.layout.header_animation, binding.root as ViewGroup, false)
headerBinding.viewModel = viewModel
animationAdapter.addHeaderView(headerBinding.root)
binding.animationRecycler.layoutManager = LinearLayoutManager(activity)
binding.animationRecycler.adapter = animationAdapter
binding.animationRecycler.addOnItemTouchListener(object: OnItemChildClickListener() {
override fun onSimpleItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
when (view.id) {
R.id.card_more -> {
ChannelDetailActivity.intentTo(activity!!, view.tag as Int)
}
R.id.card1, R.id.card2, R.id.card3, R.id.card4 -> {
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
val coverImg = (((view as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0) as ViewGroup).getChildAt(0)
val titleText = (view.getChildAt(0) as ViewGroup).getChildAt(1)
val p1: Pair<View, String> = Pair.create(coverImg, "cover")
val p2: Pair<View, String> = Pair.create(titleText, "bg")
val cover = titleText.tag as String
val options = ActivityOptionsCompat
.makeSceneTransitionAnimation(activity!!, p1, p2)
VideoActivity.intentTo(activity!!, view.tag as String, cover, options.toBundle())
} else {
VideoActivity.intentTo(activity!!, view.tag as String)
}
}
}
}
})
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
fun initTransition() {
val changeBounds = ChangeBounds()
val arcMotion = ArcMotion()
changeBounds.pathMotion = arcMotion
activity!!.window.sharedElementExitTransition = changeBounds
activity!!.window.sharedElementReenterTransition = null
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
loadWhenNeed()
}
fun loadWhenNeed() {
if (isVisible && userVisibleHint && !isLoad && !binding.swipeRefresh.isRefreshing) {
viewModel.loadData()
}
}
fun loadAnimation(animation: Animation) {
if (!isLoad) {
isLoad = true
TransitionManager.beginDelayedTransition(binding.swipeRefresh)
binding.swipeRefresh.isEnabled = true
binding.loading.visibility = View.GONE
if (binding.errorStub.isInflated) {
binding.errorStub.root.visibility = View.GONE
}
binding.animationRecycler.visibility = View.VISIBLE
}
animationAdapter.setNewData(animation.recommends)
}
fun loadError() {
if (!isLoad) {
TransitionManager.beginDelayedTransition(binding.swipeRefresh)
binding.loading.visibility = View.GONE
if (!binding.errorStub.isInflated) {
binding.errorStub.viewStub!!.visibility = View.VISIBLE
} else {
binding.errorStub.root.visibility = View.VISIBLE
}
}
}
fun setRefreshing(isRefreshing: Boolean) {
if (isLoad) {
binding.swipeRefresh.isRefreshing = isRefreshing
} else {
TransitionManager.beginDelayedTransition(binding.swipeRefresh)
binding.loading.visibility = if (isRefreshing) View.VISIBLE else View.GONE
if (isRefreshing) {
if (!binding.errorStub.isInflated) {
binding.errorStub.viewStub!!.visibility = View.GONE
} else {
binding.errorStub.root.visibility = View.GONE
}
}
}
}
} | mit | 2d3fb187555c1eb174260c7e21ed956f | 38.621951 | 167 | 0.646144 | 5.176892 | false | false | false | false |
googlecodelabs/android-paging | advanced/end/app/src/main/java/com/example/android/codelabs/paging/ui/SearchRepositoriesActivity.kt | 1 | 8057 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.codelabs.paging.ui
import android.os.Bundle
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import androidx.paging.PagingData
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.RecyclerView
import com.example.android.codelabs.paging.Injection
import com.example.android.codelabs.paging.databinding.ActivitySearchRepositoriesBinding
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
class SearchRepositoriesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivitySearchRepositoriesBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
// get the view model
val viewModel = ViewModelProvider(
this, Injection.provideViewModelFactory(
context = this,
owner = this
)
)
.get(SearchRepositoriesViewModel::class.java)
// add dividers between RecyclerView's row items
val decoration = DividerItemDecoration(this, DividerItemDecoration.VERTICAL)
binding.list.addItemDecoration(decoration)
// bind the state
binding.bindState(
uiState = viewModel.state,
pagingData = viewModel.pagingDataFlow,
uiActions = viewModel.accept
)
}
/**
* Binds the [UiState] provided by the [SearchRepositoriesViewModel] to the UI,
* and allows the UI to feed back user actions to it.
*/
private fun ActivitySearchRepositoriesBinding.bindState(
uiState: StateFlow<UiState>,
pagingData: Flow<PagingData<UiModel>>,
uiActions: (UiAction) -> Unit
) {
val repoAdapter = ReposAdapter()
val header = ReposLoadStateAdapter { repoAdapter.retry() }
list.adapter = repoAdapter.withLoadStateHeaderAndFooter(
header = header,
footer = ReposLoadStateAdapter { repoAdapter.retry() }
)
bindSearch(
uiState = uiState,
onQueryChanged = uiActions
)
bindList(
header = header,
repoAdapter = repoAdapter,
uiState = uiState,
pagingData = pagingData,
onScrollChanged = uiActions
)
}
private fun ActivitySearchRepositoriesBinding.bindSearch(
uiState: StateFlow<UiState>,
onQueryChanged: (UiAction.Search) -> Unit
) {
searchRepo.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_GO) {
updateRepoListFromInput(onQueryChanged)
true
} else {
false
}
}
searchRepo.setOnKeyListener { _, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
updateRepoListFromInput(onQueryChanged)
true
} else {
false
}
}
lifecycleScope.launch {
uiState
.map { it.query }
.distinctUntilChanged()
.collect(searchRepo::setText)
}
}
private fun ActivitySearchRepositoriesBinding.updateRepoListFromInput(onQueryChanged: (UiAction.Search) -> Unit) {
searchRepo.text.trim().let {
if (it.isNotEmpty()) {
list.scrollToPosition(0)
onQueryChanged(UiAction.Search(query = it.toString()))
}
}
}
private fun ActivitySearchRepositoriesBinding.bindList(
header: ReposLoadStateAdapter,
repoAdapter: ReposAdapter,
uiState: StateFlow<UiState>,
pagingData: Flow<PagingData<UiModel>>,
onScrollChanged: (UiAction.Scroll) -> Unit
) {
retryButton.setOnClickListener { repoAdapter.retry() }
list.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy != 0) onScrollChanged(UiAction.Scroll(currentQuery = uiState.value.query))
}
})
val notLoading = repoAdapter.loadStateFlow
.asRemotePresentationState()
.map { it == RemotePresentationState.PRESENTED }
val hasNotScrolledForCurrentSearch = uiState
.map { it.hasNotScrolledForCurrentSearch }
.distinctUntilChanged()
val shouldScrollToTop = combine(
notLoading,
hasNotScrolledForCurrentSearch,
Boolean::and
)
.distinctUntilChanged()
lifecycleScope.launch {
pagingData.collectLatest(repoAdapter::submitData)
}
lifecycleScope.launch {
shouldScrollToTop.collect { shouldScroll ->
if (shouldScroll) list.scrollToPosition(0)
}
}
lifecycleScope.launch {
repoAdapter.loadStateFlow.collect { loadState ->
// Show a retry header if there was an error refreshing, and items were previously
// cached OR default to the default prepend state
header.loadState = loadState.mediator
?.refresh
?.takeIf { it is LoadState.Error && repoAdapter.itemCount > 0 }
?: loadState.prepend
val isListEmpty = loadState.refresh is LoadState.NotLoading && repoAdapter.itemCount == 0
// show empty list
emptyList.isVisible = isListEmpty
// Only show the list if refresh succeeds, either from the the local db or the remote.
list.isVisible = loadState.source.refresh is LoadState.NotLoading || loadState.mediator?.refresh is LoadState.NotLoading
// Show loading spinner during initial load or refresh.
progressBar.isVisible = loadState.mediator?.refresh is LoadState.Loading
// Show the retry state if initial load or refresh fails.
retryButton.isVisible = loadState.mediator?.refresh is LoadState.Error && repoAdapter.itemCount == 0
// Toast on any error, regardless of whether it came from RemoteMediator or PagingSource
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
errorState?.let {
Toast.makeText(
this@SearchRepositoriesActivity,
"\uD83D\uDE28 Wooops ${it.error}",
Toast.LENGTH_LONG
).show()
}
}
}
}
}
| apache-2.0 | a657a8714fb35f0fe66c92420ab50117 | 37.735577 | 137 | 0.631749 | 5.484683 | false | false | false | false |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/ichi2/utils/ImportUtils.kt | 1 | 22912 | /****************************************************************************************
* Copyright (c) 2018 Mike Hardy <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.utils
import android.app.Activity
import android.content.ContentResolver
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Message
import android.provider.OpenableColumns
import android.text.TextUtils
import android.webkit.MimeTypeMap
import androidx.annotation.CheckResult
import com.afollestad.materialdialogs.MaterialDialog
import com.ichi2.anki.AnkiActivity
import com.ichi2.anki.AnkiDroidApp
import com.ichi2.anki.CrashReportService
import com.ichi2.anki.R
import com.ichi2.anki.dialogs.DialogHandler
import com.ichi2.compat.CompatHelper
import org.apache.commons.compress.archivers.zip.ZipFile
import org.jetbrains.annotations.Contract
import timber.log.Timber
import java.io.File
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStream
import java.net.URLDecoder
import java.net.URLEncoder
import java.util.*
import java.util.zip.ZipException
import java.util.zip.ZipInputStream
import kotlin.collections.ArrayList
object ImportUtils {
/* A filename should be shortened if over this threshold */
private const val fileNameShorteningThreshold = 100
/**
* This code is used in multiple places to handle package imports
*
* @param context for use in resource resolution and path finding
* @param intent contains the file to import
* @return null if successful, otherwise error message
*/
fun handleFileImport(context: Context, intent: Intent): ImportResult {
return FileImporter().handleFileImport(context, intent)
}
/**
* Makes a cached copy of the file selected on [intent] and returns its path
*/
fun getFileCachedCopy(context: Context, intent: Intent): String? {
return FileImporter().getFileCachedCopy(context, intent)
}
fun showImportUnsuccessfulDialog(activity: Activity, errorMessage: String?, exitActivity: Boolean) {
FileImporter().showImportUnsuccessfulDialog(activity, errorMessage, exitActivity)
}
fun isCollectionPackage(filename: String?): Boolean {
return filename != null && (filename.lowercase(Locale.ROOT).endsWith(".colpkg") || "collection.apkg" == filename)
}
/** @return Whether the file is either a deck, or a collection package */
@Contract("null -> false")
fun isValidPackageName(filename: String?): Boolean {
return FileImporter.isDeckPackage(filename) || isCollectionPackage(filename)
}
/**
* Whether importUtils can handle the given intent
* Caused by #6312 - A launcher was sending ACTION_VIEW instead of ACTION_MAIN
*/
fun isInvalidViewIntent(intent: Intent): Boolean {
return intent.data == null && intent.clipData == null
}
fun isFileAValidDeck(fileName: String): Boolean {
return FileImporter.hasExtension(fileName, "apkg") || FileImporter.hasExtension(fileName, "colpkg")
}
@SuppressWarnings("WeakerAccess")
open class FileImporter {
/**
* This code is used in multiple places to handle package imports
*
* @param context for use in resource resolution and path finding
* @param intent contains the file to import
* @return null if successful, otherwise error message
*/
fun handleFileImport(context: Context, intent: Intent): ImportResult {
// This intent is used for opening apkg package files
// We want to go immediately to DeckPicker, clearing any history in the process
Timber.i("IntentHandler/ User requested to view a file")
val extras = if (intent.extras == null) "none" else TextUtils.join(", ", intent.extras!!.keySet())
Timber.i("Intent: %s. Data: %s", intent, extras)
return try {
handleFileImportInternal(context, intent)
} catch (e: Exception) {
CrashReportService.sendExceptionReport(e, "handleFileImport")
Timber.e(e, "failed to handle import intent")
ImportResult.fromErrorString(context.getString(R.string.import_error_handle_exception, e.localizedMessage))
}
}
private fun handleFileImportInternal(context: Context, intent: Intent): ImportResult {
val dataList = getUris(intent)
return if (dataList != null) {
handleContentProviderFile(context, intent, dataList)
} else {
ImportResult.fromErrorString(context.getString(R.string.import_error_handle_exception))
}
}
/**
* Makes a cached copy of the file selected on [intent] and returns its path
*/
fun getFileCachedCopy(context: Context, intent: Intent): String? {
val uri = getUris(intent)?.get(0) ?: return null
val filename = ensureValidLength(getFileNameFromContentProvider(context, uri) ?: return null)
val tempPath = Uri.fromFile(File(context.cacheDir, filename)).encodedPath!!
return if (copyFileToCache(context, uri, tempPath)) {
tempPath
} else {
null
}
}
private fun handleContentProviderFile(context: Context, intent: Intent, dataList: ArrayList<Uri>): ImportResult {
// Note: intent.getData() can be null. Use data instead.
validateImportTypes(context, dataList)?.let { errorMessage ->
return ImportResult.fromErrorString(errorMessage)
}
val tempOutDirList: ArrayList<String> = ArrayList()
for (data in dataList) {
// Get the original filename from the content provider URI
var filename = getFileNameFromContentProvider(context, data)
// Hack to fix bug where ContentResolver not returning filename correctly
if (filename == null) {
if (intent.type != null && ("application/apkg" == intent.type || hasValidZipFile(context, data))) {
// Set a dummy filename if MIME type provided or is a valid zip file
filename = "unknown_filename.apkg"
Timber.w("Could not retrieve filename from ContentProvider, but was valid zip file so we try to continue")
} else {
Timber.e("Could not retrieve filename from ContentProvider or read content as ZipFile")
CrashReportService.sendExceptionReport(RuntimeException("Could not import apkg from ContentProvider"), "IntentHandler.java", "apkg import failed")
return ImportResult.fromErrorString(AnkiDroidApp.appResources.getString(R.string.import_error_content_provider, AnkiDroidApp.manualUrl + "#importing"))
}
}
if (!isValidPackageName(filename)) {
return if (isAnkiDatabase(filename)) {
// .anki2 files aren't supported by Anki Desktop, we should eventually support them, because we can
// but for now, show a "nice" error.
ImportResult.fromErrorString(context.resources.getString(R.string.import_error_load_imported_database))
} else {
// Don't import if file doesn't have an Anki package extension
ImportResult.fromErrorString(context.resources.getString(R.string.import_error_not_apkg_extension, filename))
}
} else {
// Copy to temporary file
filename = ensureValidLength(filename)
val tempOutDir = Uri.fromFile(File(context.cacheDir, filename)).encodedPath!!
val errorMessage = if (copyFileToCache(context, data, tempOutDir)) null else context.getString(R.string.import_error_copy_to_cache)
// Show import dialog
if (errorMessage != null) {
CrashReportService.sendExceptionReport(RuntimeException("Error importing apkg file"), "IntentHandler.java", "apkg import failed")
return ImportResult.fromErrorString(errorMessage)
}
val validateZipResult = validateZipFile(context, tempOutDir)
if (validateZipResult != null) {
File(tempOutDir).delete()
return validateZipResult
}
tempOutDirList.add(tempOutDir)
}
sendShowImportFileDialogMsg(tempOutDirList)
}
return ImportResult.fromSuccess()
}
private fun validateZipFile(ctx: Context, filePath: String): ImportResult? {
val file = File(filePath)
var zf: ZipFile? = null
try {
zf = ZipFile(file)
} catch (e: Exception) {
Timber.w(e, "Failed to validate zip")
return ImportResult.fromInvalidZip(ctx, file, e)
} finally {
if (zf != null) {
try {
zf.close()
} catch (e: IOException) {
Timber.w(e, "Failed to close zip")
}
}
}
return null
}
private fun validateImportTypes(context: Context, dataList: ArrayList<Uri>): String? {
var apkgCount = 0
var colpkgCount = 0
for (data in dataList) {
var fileName = getFileNameFromContentProvider(context, data)
when {
isDeckPackage(fileName) -> {
apkgCount += 1
}
isCollectionPackage(fileName) -> {
colpkgCount += 1
}
}
}
if (apkgCount > 0 && colpkgCount > 0) {
Timber.i("Both apkg & colpkg selected.")
return context.resources.getString(R.string.import_error_colpkg_apkg)
} else if (colpkgCount > 1) {
Timber.i("Multiple colpkg files selected.")
return context.resources.getString(R.string.import_error_multiple_colpkg)
}
return null
}
private fun isAnkiDatabase(filename: String?): Boolean {
return filename != null && hasExtension(filename, "anki2")
}
private fun ensureValidLength(fileName: String): String {
// #6137 - filenames can be too long when URLEncoded
return try {
val encoded = URLEncoder.encode(fileName, "UTF-8")
if (encoded.length <= fileNameShorteningThreshold) {
Timber.d("No filename truncation necessary")
fileName
} else {
Timber.d("Filename was longer than %d, shortening", fileNameShorteningThreshold)
// take 90 instead of 100 so we don't get the extension
val substringLength = fileNameShorteningThreshold - 10
val shortenedFileName = encoded.substring(0, substringLength) + "..." + getExtension(fileName)
Timber.d("Shortened filename '%s' to '%s'", fileName, shortenedFileName)
// if we don't decode, % is double-encoded
URLDecoder.decode(shortenedFileName, "UTF-8")
}
} catch (e: Exception) {
Timber.w(e, "Failed to shorten file: %s", fileName)
fileName
}
}
@CheckResult
private fun getExtension(fileName: String): String {
val file = Uri.fromFile(File(fileName))
return MimeTypeMap.getFileExtensionFromUrl(file.toString())
}
protected open fun getFileNameFromContentProvider(context: Context, data: Uri): String? {
var filename: String? = null
context.contentResolver.query(data, arrayOf(OpenableColumns.DISPLAY_NAME), null, null, null).use { cursor ->
if (cursor != null && cursor.moveToFirst()) {
filename = cursor.getString(0)
Timber.d("handleFileImport() Importing from content provider: %s", filename)
}
}
return filename
}
fun showImportUnsuccessfulDialog(activity: Activity, errorMessage: String?, exitActivity: Boolean) {
Timber.e("showImportUnsuccessfulDialog() message %s", errorMessage)
val title = activity.resources.getString(R.string.import_title_error)
MaterialDialog(activity).show {
title(text = title)
message(text = errorMessage!!)
positiveButton(R.string.dialog_ok) {
if (exitActivity) {
AnkiActivity.finishActivityWithFade(activity)
}
}
}
}
/**
* Copy the data from the intent to a temporary file
* @param data intent from which to get input stream
* @param tempPath temporary path to store the cached file
* @return whether or not copy was successful
*/
protected open fun copyFileToCache(context: Context, data: Uri?, tempPath: String): Boolean {
// Get an input stream to the data in ContentProvider
val inputStream: InputStream? = try {
context.contentResolver.openInputStream(data!!)
} catch (e: FileNotFoundException) {
Timber.e(e, "Could not open input stream to intent data")
return false
}
// Check non-null
@Suppress("FoldInitializerAndIfToElvis")
if (inputStream == null) {
return false
}
try {
CompatHelper.compat.copyFile(inputStream, tempPath)
} catch (e: IOException) {
Timber.e(e, "Could not copy file to %s", tempPath)
return false
} finally {
try {
inputStream.close()
} catch (e: IOException) {
Timber.e(e, "Error closing input stream")
}
}
return true
}
companion object {
fun getUris(intent: Intent): ArrayList<Uri>? {
if (intent.data == null) {
Timber.i("No intent data. Attempting to read clip data.")
if (intent.clipData == null || intent.clipData!!.itemCount == 0) {
return null
}
val clipUriList: ArrayList<Uri> = ArrayList()
// Iterate over clipUri & create clipUriList
// Pass clipUri list.
for (i in 0 until intent.clipData!!.itemCount) {
intent.clipData?.getItemAt(i)?.let { clipUriList.add(it.uri) }
}
return clipUriList
}
// If Uri is of scheme which is supported by ContentResolver, read the contents
val intentUriScheme = intent.data!!.scheme
return if (intentUriScheme == ContentResolver.SCHEME_CONTENT || intentUriScheme == ContentResolver.SCHEME_FILE || intentUriScheme == ContentResolver.SCHEME_ANDROID_RESOURCE) {
Timber.i("Attempting to read content from intent.")
arrayListOf(intent.data!!)
} else {
null
}
}
/**
* Send a Message to AnkiDroidApp so that the DialogMessageHandler shows the Import apkg dialog.
* @param pathList list of path(s) to apkg file which will be imported
*/
private fun sendShowImportFileDialogMsg(pathList: ArrayList<String>) {
// Get the filename from the path
val f = File(pathList.first())
val filename = f.name
// Create a new message for DialogHandler so that we see the appropriate import dialog in DeckPicker
val handlerMessage = Message.obtain()
val msgData = Bundle()
msgData.putStringArrayList("importPath", pathList)
handlerMessage.data = msgData
if (isCollectionPackage(filename)) {
// Show confirmation dialog asking to confirm import with replace when file called "collection.apkg"
handlerMessage.what = DialogHandler.MSG_SHOW_COLLECTION_IMPORT_REPLACE_DIALOG
} else {
// Otherwise show confirmation dialog asking to confirm import with add
handlerMessage.what = DialogHandler.MSG_SHOW_COLLECTION_IMPORT_ADD_DIALOG
}
// Store the message in AnkiDroidApp message holder, which is loaded later in AnkiActivity.onResume
DialogHandler.storeMessage(handlerMessage)
}
internal fun isDeckPackage(filename: String?): Boolean {
return filename != null && filename.lowercase(Locale.ROOT).endsWith(".apkg") && "collection.apkg" != filename
}
fun hasExtension(filename: String, extension: String?): Boolean {
val fileParts = filename.split("\\.".toRegex()).toTypedArray()
if (fileParts.size < 2) {
return false
}
val extensionSegment = fileParts[fileParts.size - 1]
// either "apkg", or "apkg (1)".
// COULD_BE_BETTE: accepts .apkgaa"
return extensionSegment.lowercase(Locale.ROOT).startsWith(extension!!)
}
/**
* Check if the InputStream is to a valid non-empty zip file
* @param data uri from which to get input stream
* @return whether or not valid zip file
*/
private fun hasValidZipFile(context: Context, data: Uri?): Boolean {
// Get an input stream to the data in ContentProvider
var inputStream: InputStream? = null
try {
inputStream = context.contentResolver.openInputStream(data!!)
} catch (e: FileNotFoundException) {
Timber.e(e, "Could not open input stream to intent data")
}
// Make sure it's not null
if (inputStream == null) {
Timber.e("Could not open input stream to intent data")
return false
}
// Open zip input stream
val zis = ZipInputStream(inputStream)
var ok = false
try {
try {
val ze = zis.nextEntry
if (ze != null) {
// set ok flag to true if there are any valid entries in the zip file
ok = true
}
} catch (e: Exception) {
// don't set ok flag
Timber.d(e, "Error checking if provided file has a zip entry")
}
} finally {
// close the input streams
try {
zis.close()
inputStream.close()
} catch (e: Exception) {
Timber.d(e, "Error closing the InputStream")
}
}
return ok
}
}
}
class ImportResult(val humanReadableMessage: String?) {
val isSuccess: Boolean
get() = humanReadableMessage == null
companion object {
fun fromErrorString(message: String?): ImportResult {
return ImportResult(message)
}
fun fromSuccess(): ImportResult {
return ImportResult(null)
}
fun fromInvalidZip(ctx: Context, file: File, e: Exception): ImportResult {
return fromErrorString(getInvalidZipException(ctx, file, e))
}
private fun getInvalidZipException(ctx: Context, @Suppress("UNUSED_PARAMETER") file: File, e: Exception): String {
// This occurs when there is random corruption in a zip file
if (e is IOException && "central directory is empty, can't expand corrupt archive." == e.message) {
return ctx.getString(R.string.import_error_corrupt_zip, e.getLocalizedMessage())
}
// 7050 - this occurs when a file is truncated at the end (partial download/corrupt).
if (e is ZipException && "archive is not a ZIP archive" == e.message) {
return ctx.getString(R.string.import_error_corrupt_zip, e.getLocalizedMessage())
}
// If we don't have a good string, send a silent exception that we can better handle this in the future
CrashReportService.sendExceptionReport(e, "Import - invalid zip", "improve UI message here", true)
return ctx.getString(R.string.import_log_failed_unzip, e.localizedMessage)
}
}
}
}
| gpl-3.0 | 48d2083691dcad5799f8765a567c37ad | 46.047228 | 191 | 0.55783 | 5.465649 | false | false | false | false |
SergeySave/SpaceGame | desktop/src/com/sergey/spacegame/client/ui/scene2d/MinimapDrawable.kt | 1 | 7307 | package com.sergey.spacegame.client.ui.scene2d
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.utils.ImmutableArray
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.graphics.g2d.TextureRegion
import com.badlogic.gdx.math.Matrix3
import com.badlogic.gdx.math.Rectangle
import com.badlogic.gdx.math.Vector2
import com.badlogic.gdx.scenes.scene2d.utils.Drawable
import com.badlogic.gdx.scenes.scene2d.utils.ScissorStack
import com.sergey.spacegame.common.ecs.component.PositionComponent
import com.sergey.spacegame.common.ecs.component.SizeComponent
import com.sergey.spacegame.common.ecs.component.Team1Component
import com.sergey.spacegame.common.ecs.component.Team2Component
import com.sergey.spacegame.common.ecs.component.VisualComponent
import com.sergey.spacegame.common.game.Level
/**
* A class that represents a drawable for a minimap
*
* @author sergeys
*
* @constructor Creates a new MinimapDrawable
* @property team1 - the texture region used to represent something from team 1
* @property team2 - the texture region used to represent something from team 2
* @property neutral - the texture region used to represent something not on a team
* @property white - a texture region representing a white pixel
* @property level - the level that this minimap should represent
* @property screen - a rectangle representing the area of the world that the screen covers
*/
class MinimapDrawable(val team1: TextureRegion, val team2: TextureRegion, val neutral: TextureRegion,
val white: TextureRegion,
val level: Level, val screen: Rectangle) : Drawable {
private var _minHeight: Float = 1f
private var _minWidth: Float = 1f
private var _rightWidth: Float = 0f
private var _leftWidth: Float = 0f
private var _bottomHeight: Float = 0f
private var _topHeight: Float = 0f
private val team1Entities = level.ecs.getEntitiesFor(Family.all(Team1Component::class.java, VisualComponent::class.java, PositionComponent::class.java).get())
private val team2Entities = level.ecs.getEntitiesFor(Family.all(Team2Component::class.java, VisualComponent::class.java, PositionComponent::class.java).get())
private val neutralEntities = level.ecs.getEntitiesFor(Family.all(VisualComponent::class.java, PositionComponent::class.java).exclude(Team1Component::class.java, Team2Component::class.java).get())
private val projection = Matrix3()
private val invProjection = Matrix3()
private val VEC = Vector2()
private var scaleX: Float = 1f
private var scaleY: Float = 1f
private var dragging: Boolean = false
override fun draw(batch: Batch, x: Float, y: Float, width: Float, height: Float) {
//Create our projection matrix
projection.setToTranslation(x - level.limits.minX, y - level.limits.minY)
scaleX = width / level.limits.width
scaleY = height / level.limits.height
projection.scale(scaleX, scaleY)
//Create the inverse of the projection matrix
invProjection.set(projection).inv()
//Calculate the position of the camera as of this frame
val x1 = VEC.set(screen.x - screen.width / 2, screen.y - screen.height / 2).mul(projection).x
val y1 = VEC.y
val x2 = VEC.set(screen.x + screen.width / 2, screen.y + screen.height / 2).mul(projection).x
val y2 = VEC.y
//Render the camera's position
batch.draw(white, x1, y1, x2 - x1, 1f) //Bottom
batch.draw(white, x1, y1, 1f, y2 - y1) //Left
batch.draw(white, x1, y2, x2 - x1, 1f) //Top
batch.draw(white, x2, y1, 1f, y2 - y1) //Right
//Border
batch.draw(white, x, y, width, 1f) //Bottom
batch.draw(white, x, y, 1f, height) //Left
batch.draw(white, x, y + height, width, 1f) //Top
batch.draw(white, x + width, y, 1f, height) //Right
//If it is controllable then allow the user to click to move the camera
if (level.viewport.viewportControllable) {
if (Gdx.input.justTouched() && Gdx.input.isTouched && Gdx.input.x in x..(x + width) && (Gdx.graphics.height - Gdx.input.y) in y..(y + height)) {
dragging = true
}
//Allow the user to drag around the position of the camera (invalid locaitons will be corrected in GameScreen#render
if (dragging && Gdx.input.isTouched && Gdx.input.x in x..(x + width) && (Gdx.graphics.height - Gdx.input.y) in y..(y + height)) {
VEC.set(Gdx.input.x.toFloat(), (Gdx.graphics.height - Gdx.input.y).toFloat()).mul(invProjection)
screen.x = VEC.x
screen.y = VEC.y
} else {
dragging = false
}
} else {
dragging = false
}
//Draw the previous things with clipping
batch.flush()
//Enable clipping
val pushed = ScissorStack.pushScissors(Rectangle(x, y, width, height))
//Draw all of the entities
drawEntities(neutralEntities, batch, neutral, scaleX, scaleY)
drawEntities(team2Entities, batch, team2, scaleX, scaleY)
drawEntities(team1Entities, batch, team1, scaleX, scaleY)
//Push it to the screen
batch.flush()
//Remove the clipping
if (pushed) ScissorStack.popScissors()
}
private fun drawEntities(array: ImmutableArray<Entity>,
batch: Batch,
region: TextureRegion, scaleX: Float, scaleY: Float) {
for (entity in array) {
PositionComponent.MAPPER.get(entity).setVector(VEC).mul(projection)
val sizeComponent = SizeComponent.MAPPER.get(entity)
if (sizeComponent == null) {
batch.draw(region, VEC.x - defaultWidth * scaleX / 2, VEC.y - defaultHeight * scaleY / 2, defaultWidth * scaleX, defaultWidth * scaleY)
} else {
batch.draw(region, VEC.x - sizeComponent.w * scaleX / 2, VEC.y - sizeComponent.h * scaleY / 2, sizeComponent.w * scaleX, sizeComponent.h * scaleY)
}
}
}
override fun setRightWidth(rightWidth: Float) {
_rightWidth = rightWidth
}
override fun getLeftWidth(): Float = _leftWidth
override fun setMinHeight(minHeight: Float) {
_minHeight = minHeight
}
override fun setBottomHeight(bottomHeight: Float) {
_bottomHeight = bottomHeight
}
override fun setTopHeight(topHeight: Float) {
_topHeight = topHeight
}
override fun getBottomHeight(): Float = _bottomHeight
override fun getRightWidth(): Float = _rightWidth
override fun getMinWidth(): Float = _minWidth
override fun getTopHeight(): Float = _topHeight
override fun setMinWidth(minWidth: Float) {
_minWidth = minWidth
}
override fun setLeftWidth(leftWidth: Float) {
_leftWidth = leftWidth
}
override fun getMinHeight(): Float = _minHeight
private companion object {
val defaultWidth = 10f
val defaultHeight = 10f
}
} | mit | 2fb603634f55455f83dd0964a2c1f2cb | 40.522727 | 200 | 0.651704 | 4.146992 | false | false | false | false |
pdvrieze/ProcessManager | accountmgr/src/main/kotlin/uk/ac/bournemouth.darwin.html/AccountController.kt | 1 | 35410 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package uk.ac.bournemouth.darwin.html
import io.github.pdvrieze.darwin.servlet.support.ServletRequestInfo
import io.github.pdvrieze.darwin.servlet.support.darwinError
import io.github.pdvrieze.darwin.servlet.support.darwinResponse
import io.github.pdvrieze.darwin.servlet.support.htmlAccepted
import kotlinx.html.*
import net.devrieze.util.nullIfNot
import net.devrieze.util.overrideIf
import nl.adaptivity.xmlutil.XmlStreaming
import nl.adaptivity.xmlutil.XmlWriter
import nl.adaptivity.xmlutil.smartStartTag
import nl.adaptivity.xmlutil.writeAttribute
import uk.ac.bournemouth.darwin.accounts.*
import uk.ac.bournemouth.darwin.sharedhtml.darwinDialog
import uk.ac.bournemouth.darwin.sharedhtml.loginDialog
import uk.ac.bournemouth.darwin.sharedhtml.setAliasDialog
import java.net.URI
import java.net.URLEncoder
import java.security.MessageDigest
import java.security.Principal
import java.text.DateFormat
import java.util.*
import java.util.logging.Level
import java.util.logging.Logger
import javax.mail.Message
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeMessage
import javax.servlet.ServletConfig
import javax.servlet.ServletException
import javax.servlet.annotation.MultipartConfig
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServlet
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
//internal const val MAXTOKENLIFETIME = 864000 /* Ten days */
//internal const val MAXCHALLENGELIFETIME = 60 /* 60 seconds */
//internal const val MAX_RESET_VALIDITY = 1800 /* 12 hours */
/*
* This file contains the functionality needed for managing accounts on darwin. This includes the underlying database
* interaction through [AccountDb] as well as web interaction through [AccountController].
*/
/** Create a SHA1 digest of the source */
internal fun sha1(src: ByteArray): ByteArray = MessageDigest.getInstance("SHA1").digest(src)
const val DBRESOURCE = "java:comp/env/jdbc/webauthadm"
@MultipartConfig
class AccountController : HttpServlet() {
companion object {
private val log = Logger.getLogger(AccountController::class.java.name)
const val FIELD_USERNAME = "username"
const val FIELD_PASSWORD = "password"
const val FIELD_PUBKEY = "pubkey"
const val FIELD_REDIRECT = "redirect"
const val FIELD_KEYID = "keyid"
const val FIELD_ALIAS = "alias"
const val FIELD_APPNAME = "app"
const val FIELD_RESPONSE = "response"
const val FIELD_RESETTOKEN = "resettoken"
const val FIELD_NEWPASSWORD1 = "newpassword1"
const val FIELD_NEWPASSWORD2 = "newpassword2"
const val SC_UNPROCESSIBLE_ENTITY = 422
const val CHALLENGE_VERSION = "2"
const val HEADER_CHALLENGE_VERSION = "X-Challenge-version"
const val MIN_RESET_DELAY = 60 * 1000 // 60 seconds between reset requests
}
private inline fun <R> accountDb(block: AccountDb.() -> R): R = accountDb(DBRESOURCE, block)
private val logger = Logger.getLogger(AccountController::class.java.name)
override fun init(config: ServletConfig?) {
super.init(config)
logger.info("Initialising AccountController (ensuring that the required database tables are available)")
accountDb { this.ensureTables() }
}
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
val realPath = if (req.requestURI.startsWith(req.contextPath)) {
req.requestURI.substring(req.contextPath.length)
} else req.pathInfo
when (realPath) {
"/login" -> tryLogin(req, resp)
"/logout" -> logout(req, resp)
"/challenge" -> challenge(req, resp)
"/chpasswd" -> chpasswd(req, resp)
"/regkey" -> resp.darwinError(req, "HTTP method GET is not supported by this URL",
HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Get not supported")
"/forget" -> forgetKey(req, resp)
"/", null, "/myaccount" -> myAccount(req, resp)
"/setAliasForm" -> setAliasForm(req, resp)
"/resetpasswd" -> resetPassword(req, resp)
"/js/main.js" -> mainJs(req, resp)
else -> resp.darwinError(req, "The resource ${req.contextPath}${req.pathInfo
?: ""} was not found",
HttpServletResponse.SC_NOT_FOUND, "Not Found")
}
}
override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
when (req.pathInfo) {
"/login" -> tryCredentials(req, resp)
"/challenge" -> challenge(req, resp)
"/chpasswd" -> chpasswd(req, resp)
"/regkey" -> registerkey(req, resp)
"/forget" -> forgetKey(req, resp)
else -> resp.darwinError(req, "The resource ${req.contextPath}${req.pathInfo} was not found",
HttpServletResponse.SC_NOT_FOUND, "Not Found")
}
}
private fun setAliasForm(req: HttpServletRequest, resp: HttpServletResponse) {
authenticatedResponse(req, resp) {
val user: String = req.userPrincipal.name
val oldAlias: String? = req.getParameter(FIELD_ALIAS).nullIfNot { length > 0 }
val displayName: String = oldAlias.overrideIf { isBlank() } by user
resp.darwinResponse(req, "My Account", "My Account - $displayName") {
setAliasDialog(oldAlias)
}
}
}
private fun mainJs(req: HttpServletRequest, resp: HttpServletResponse) {
resp.contentType = "text/javascript"
resp.writer.use { out ->
out.println("""
require.config({
baseUrl:"/js",
paths: {
"accountmgr": "${req.contextPath}/js/accountmgr"
}
});
requirejs(['accountmgr'], function (accountmgr){
accountmgr.updateLinks()
})
""".trimIndent())
}
}
private data class AccountInfo(
val username: String,
val alias: String?,
val fullname: String?,
val isLocalPassword: Boolean,
val keys: List<KeyInfo>) {
fun toXmlWriter(writer: XmlWriter) {
writer.smartStartTag(null, "account") {
writeAttribute("username", username)
alias?.let { writeAttribute("alias", it) }
fullname?.let { writeAttribute("fullname", it) }
writeAttribute("isLocalPassword", if(isLocalPassword) "yes" else "no")
for (key in keys) {
key.toXmlWriter(writer)
}
}
}
}
private fun myAccount(req: HttpServletRequest, resp: HttpServletResponse) {
authenticatedResponse(req, resp) {
val user: String = req.userPrincipal.name
val info = accountDb {
val alias = alias(user)
val fullname = fullname(user)
val isLocal = isLocalAccount(user)
val keys = keyInfo(user)
AccountInfo(user, alias, fullname, isLocal, keys)
}
if (req.htmlAccepted) {
val displayName = if (info.alias.isNullOrBlank()) (info.fullname ?: user) else info.alias
resp.darwinResponse(req, "My Account", "My Account - $displayName") {
section {
h1 { +"Account" }
p {
if (info.alias == null) {
val encodedDisplayName = URLEncoder.encode(displayName, "UTF-8")
a(href = "${context.accountMgrPath}setAliasForm?$FIELD_ALIAS=$encodedDisplayName") {
id = "accountmgr.setAlias"
attributes["alias"] = displayName
+"Set alias"
}
} else {
+"Alias: ${info.alias} "
a(href = "${context.accountMgrPath}setAliasForm?$FIELD_ALIAS=${info.alias}") {
id = "accountmgr.setAlias"
attributes["alias"] = info.alias
+"change"
}
}
}
if (info.isLocalPassword) p { a(href = "chpasswd") { +"change password" } }
}
val keys = info.keys
if (keys.isNotEmpty()) {
section {
h1 { +"Authorizations" }
table {
thead {
tr { th { +"Application" }; th { +"Last use" }; th {} }
}
tbody {
for (key in keys) {
tr {
classes += "authkey"
td { +(key.appname ?: "<unknown>") }
td {
+(key.lastUse?.let { DateFormat.getDateTimeInstance().format(it) }
?: "never")
}
td {
a(href = "${context.accountMgrPath}forget?$FIELD_KEYID=${key.keyId}",
classes = "forget_key_class") {
attributes["keyid"] = key.keyId.toString()
+"forget"
}
}
}
}
}
}
}
}
}
} else {
resp.contentType = "text/xml"
resp.characterEncoding="UTF8"
resp.outputStream.use {
XmlStreaming.newWriter(it, "UTF8").use { writer ->
writer.startDocument(null, null, null)
info.toXmlWriter(writer)
writer.endDocument()
}
}
}
}
}
private fun registerkey(req: HttpServletRequest, resp: HttpServletResponse) {
val username = req.getParameter(FIELD_USERNAME)
val password = req.getParameter(FIELD_PASSWORD)
val keyid = req.getParameter(FIELD_KEYID)
log.finer("registerkey called with username: $username password: ${"?".repeat(password.length)} keyid: $keyid")
if (username.isNullOrEmpty() || password.isNullOrEmpty()) {
resp.darwinError(req, "Missing credentials", HttpServletResponse.SC_FORBIDDEN, "Missing credentials")
log.warning("Missing credentials attempting to register key")
} else {
val pubkey = req.getParameter(FIELD_PUBKEY)
val appname: String? = req.getParameter(FIELD_APPNAME)
log.finer("registerkey: appname=$appname pubkey.length=${pubkey.length}")
accountDb(DBRESOURCE) {
if (verifyCredentials(username, password)) {
if (pubkey.isNullOrBlank()) {
resp.contentType = "text/plain"
resp.writer.use {
it.append("authenticated:").appendLine(username)
log.warning("registerkey: User authenticated but missing public key to register")
}
} else {
try {
val newKeyId = registerkey(username, pubkey, appname, keyid?.toInt())
resp.contentType = "text/plain"
resp.writer.use { it.append("key:").appendLine(newKeyId.toString()) }
log.fine("registerkey: registered key with id: $newKeyId")
} catch (e: NumberFormatException) {
resp.darwinError(
req, "Invalid key format", SC_UNPROCESSIBLE_ENTITY, "UNPROCESSIBLE ENTITY",
e
)
}
}
} else {
resp.darwinError(req, "Invalid credentials", HttpServletResponse.SC_FORBIDDEN,
"Invalid credentials")
log.info("Invalid authentication for user $username")
}
}
}
}
private fun forgetKey(req: HttpServletRequest, resp: HttpServletResponse) {
authenticatedResponse(req, resp) {
val user = req.userPrincipal.name
val keyid: Int = try {
req.getParameter(FIELD_KEYID)?.toInt() ?: throw NumberFormatException("Missing keyId")
} catch (e: NumberFormatException) {
resp.darwinError(req,
"Invalid or missing key id (id:${req.getParameter(FIELD_KEYID)}, error:${e.message})",
SC_UNPROCESSIBLE_ENTITY, "UNPROCESSIBEL ENTITY")
return
}
try {
accountDb {
this.forgetKey(user, keyid)
}
} catch (e: IllegalArgumentException) {
resp.darwinError(req, "Key not owned", HttpServletResponse.SC_FORBIDDEN, "FORBIDDEN", e)
return
}
if (req.htmlAccepted) { // Just display the account manager dialog
resp.sendRedirect("${RequestServiceContext(ServletRequestInfo(req)).accountMgrPath}myaccount")
} else {
resp.status = HttpServletResponse.SC_NO_CONTENT
resp.writer.close()
}
}
}
private fun tryCredentials(req: HttpServletRequest, resp: HttpServletResponse) {
logger.info("Received username and password for login")
val username = req.getParameter(FIELD_USERNAME)
val password = req.getParameter(FIELD_PASSWORD)
val redirect = req.getParameter(FIELD_REDIRECT)
if (username == null || password == null) {
tryLogin(req, resp)
} else {
try {
if (req.authType != null || req.remoteUser != null || req.userPrincipal != null) {
// already authenticated
req.logout() // first log out. Then log in again
}
req.login(username, password) // this throws on failure
logger.fine("Login successful")
accountDb {
if (redirect != null) {
resp.sendRedirect(resp.encodeRedirectURL(redirect))
} else {
if (req.htmlAccepted) {
loginSuccess(req, resp)
} else {
resp.writer.use { it.append("login:").appendLine(username) }
}
}
}
} catch (e: ServletException) {
logger.log(Level.WARNING, "Failure in authentication", e)
invalidCredentials(req, resp)
}
}
}
private fun createAuthCookie(authtoken: String) = Cookie(DARWINCOOKIENAME,
authtoken).let { it.maxAge = MAXTOKENLIFETIME; it.path = "/"; it }
private fun HttpServletRequest.isAuthenticated(resp: HttpServletResponse): Boolean {
if (userPrincipal != null) {
return true
} else {
if (pathInfo != "/login") {
if (authenticate(resp)) {
if (userPrincipal != null) {
return true
}
}
}
}
return false
}
private inline fun authenticatedResponse(req: HttpServletRequest, resp: HttpServletResponse, block: () -> Unit) {
if (req.isAuthenticated(resp)) {
// if (req.userPrincipal!=null || (req.pathInfo!="/login" && req.authenticate(resp) && req.userPrincipal!=null)) {
block()
} else {
if (req.htmlAccepted) {
loginScreen(req, resp)
} else {
resp.status = HttpServletResponse.SC_UNAUTHORIZED
resp.writer.use { it.appendLine("error:Login is required\n") }
}
}
}
private inline fun authenticatedResponse(req: HttpServletRequest,
resp: HttpServletResponse,
condition: (HttpServletRequest) -> Boolean,
block: () -> Unit) {
if (req.isAuthenticated(resp) && condition(req)) {
block()
} else {
if (req.htmlAccepted) {
loginScreen(req, resp)
} else {
resp.status = HttpServletResponse.SC_UNAUTHORIZED
resp.writer.use { it.appendLine("error:Login is required\n") }
}
}
}
private fun tryLogin(req: HttpServletRequest, resp: HttpServletResponse) {
authenticatedResponse(req, resp) {
accountDb {
val redirect = req.getParameter(FIELD_REDIRECT)
if (redirect != null) {
resp.sendRedirect(resp.encodeRedirectURL(redirect))
} else {
loginSuccess(req, resp)
}
}
}
}
private fun logout(req: HttpServletRequest, resp: HttpServletResponse) {
req.logout()
if (req.htmlAccepted) {
loginScreen(req, resp)
} else {
resp.contentType = "text/plain"
resp.writer.use { it.appendLine("logout") }
}
}
private fun challenge(req: HttpServletRequest, resp: HttpServletResponse) {
val keyId = req.getParameter(FIELD_KEYID)?.toInt()
if (keyId == null) {
resp.darwinError(req, "Insufficient credentials", 403, "Forbidden"); return
}
val responseParam = req.getParameter(FIELD_RESPONSE)
if (responseParam == null) {
issueChallenge(req, resp, keyId)
} else {
val response = try {
Base64.getUrlDecoder().decode(responseParam)
} catch (e: IllegalArgumentException) {
Base64.getDecoder().decode(responseParam)
}
handleResponse(req, resp, keyId, response)
}
}
private fun handleResponse(req: HttpServletRequest, resp: HttpServletResponse, keyId: Int, response: ByteArray) {
try {
accountDb {
val user = userFromChallengeResponse(keyId, req.remoteAddr, response)
if (user != null) {
val authtoken = createAuthtoken(user, req.remoteAddr, keyId)
resp.addHeader("Content-type", "text/plain")
resp.addCookie(createAuthCookie(authtoken))
resp.writer.use { it.append(authtoken) }
} else {
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED)
}
}
} catch (e: AuthException) {
resp.darwinError(request = req, message = e.message, code = e.errorCode, cause = e)
}
}
private fun issueChallenge(req: HttpServletRequest, resp: HttpServletResponse, keyid: Int) {
accountDb {
cleanChallenges()
val challenge: String
try {
challenge = newChallenge(
keyid,
req.remoteAddr
) // This should fail on an incorrect keyid due to integrity constraints
} catch (e: AuthException) {
resp.contentType = "text/plain"
resp.status = e.errorCode
resp.writer.use { it.appendLine("INVALID REQUEST") }
if (e.errorCode == HttpServletResponse.SC_NOT_FOUND) { // missing code
return
}
throw e
}
resp.contentType = "text/plain"
resp.setHeader(HEADER_CHALLENGE_VERSION, CHALLENGE_VERSION)
resp.writer.use { it.appendLine(challenge) }
}
}
private class wrapUser(val req: HttpServletRequest, val username: String) : HttpServletRequest by req {
override fun getUserPrincipal(): Principal {
return Principal { username }
}
override fun isUserInRole(role: String): Boolean {
return accountDb { isUserInRole(username, role) }
}
override fun getAuthType() = HttpServletRequest.FORM_AUTH
}
private fun showChangeScreen(req: HttpServletRequest,
resp: HttpServletResponse,
message: String? = null,
resetToken: String? = null,
changedUser: String? = null) {
resp.darwinResponse(request = req, windowTitle = "Change password") {
darwinDialog("Change password") {
if (message != null) div("warning") { +message }
form(method = FormMethod.post) {
acceptCharset = "UTF-8"
if (resetToken != null) input(type = InputType.hidden) { value = resetToken }
table {
style = "border:none"
if (resetToken != null || req.isUserInRole("admin")) {
tr {
td { label { htmlFor = "#$FIELD_USERNAME"; +"Username:" } }
td {
input(name = FIELD_USERNAME, type = InputType.text) {
if (resetToken != null) {
disabled = true
}
if (changedUser != null) {
value = changedUser
}
}
}
}
} else {
tr {
td { label { htmlFor = "#$FIELD_PASSWORD"; +"Current password:" } }
td {
input(name = FIELD_PASSWORD, type = InputType.password)
}
}
}
tr {
td { label { htmlFor = "#$FIELD_NEWPASSWORD1"; +"New password:" } }
td { input(name = FIELD_NEWPASSWORD1, type = InputType.password) }
}
tr {
td { label { htmlFor = "#$FIELD_NEWPASSWORD2"; +"Repeat new password:" } }
td { input(name = FIELD_NEWPASSWORD2, type = InputType.password) }
}
}
span {
style = "margin-top: 1em; float:right"
input(type = InputType.submit) { value = "Change" }
}
}
}
}
}
private fun chpasswd(req: HttpServletRequest, resp: HttpServletResponse) {
val resetToken = req.getParameter(FIELD_RESETTOKEN).let { if (it.isNullOrBlank()) null else it }
if (req.userPrincipal == null && resetToken == null) {
// No user identification, require login first
resp.sendRedirect(resp.encodeRedirectURL("${req.servletPath}/login?redirect=${req.servletPath}/chpasswd"))
return
}
val changedUser: String? = req.getParameter(FIELD_USERNAME).let { if (it.isNullOrBlank()) null else it }
val origPasswd: String? = req.getParameter(FIELD_PASSWORD).let { if (it.isNullOrBlank()) null else it }
val newPasswd1: String? = req.getParameter(FIELD_NEWPASSWORD1).let { if (it.isNullOrBlank()) null else it }
val newPasswd2: String? = req.getParameter(FIELD_NEWPASSWORD2).let { if (it.isNullOrBlank()) null else it }
if (changedUser == null || newPasswd1 == null || newPasswd2 == null) {
showChangeScreen(req = req, resp = resp, resetToken = resetToken, changedUser = changedUser)
return
}
if (resetToken == null) req.login(changedUser,
origPasswd) // check the username/password again, if there is no reset token
if (newPasswd1 != newPasswd2) {
val message = if (origPasswd == null) {
"Please provide two identical copies of the new password"
} else {
"Please provide all of the current password and two copies of the new one"
}
showChangeScreen(req, resp, message = message, resetToken = resetToken)
return
}
if (newPasswd1.length < 6) {
showChangeScreen(req, resp, message = "The new passwords must be at lest 6 characters long",
resetToken = resetToken, changedUser = changedUser)
return
}
accountDb {
val requestingUser = req.userPrincipal?.name ?: changedUser
if (req.isUserInRole("admin")) {
if (updateCredentials(changedUser, newPasswd1)) {
resp.darwinResponse(req, "Password Changed") {
darwinDialog("Successs") { div { +"The password has been changed successfully" } }
}
} else {
resp.darwinError(req, "Failure updating password")
}
} else {
if (requestingUser == changedUser && resetToken != null && verifyResetToken(changedUser, resetToken)) {
if (updateCredentials(changedUser, newPasswd1)) {
resp.darwinResponse(req, "Password Changed") {
darwinDialog("Successs") { div { +"The password has been changed successfully" } }
}
} else {
resp.darwinError(req, "Failure updating password")
}
} else {
resp.darwinError(req, "The given reset token is invalid or expired")
}
}
}
}
private fun loginSuccess(req: HttpServletRequest, resp: HttpServletResponse) {
val userName = req.userPrincipal?.name
if (userName == null) {
loginScreen(req, resp)
} else {
if (req.htmlAccepted) {
resp.darwinResponse(request = req, windowTitle = "Welcome", pageTitle = "Welcome - Login successful") {
p { +"Congratulations with successfully authenticating on darwin." }
}
} else {
resp.writer.use { it.append("login:").appendLine(userName) }
}
}
}
private fun invalidCredentials(req: HttpServletRequest, resp: HttpServletResponse) {
resp.status = HttpServletResponse.SC_UNAUTHORIZED
if (req.htmlAccepted) {
loginScreen(req, resp, "Username or password not correct")
} else {
resp.writer.use { it.appendLine("invalid:Invalid credentials") }
}
}
private fun loginScreen(req: HttpServletRequest, resp: HttpServletResponse, errorMsg: String? = null) {
val redirect = req.getParameter("redirect") ?: if (req.pathInfo == "/login") null else req.requestURL.toString()
resp.darwinResponse(req, "Please log in") {
this.loginDialog(context, errorMsg, req.getParameter("username"), null, redirect, false)
/*
this.darwinDialog("Log in", positiveButton = null) {
if (errorMsg!=null) {
div("errorMsg") { +errorMsg }
}
form(action = "login", method = FormMethod.post, encType = FormEncType.applicationXWwwFormUrlEncoded) {
acceptCharset="utf8"
val redirect:String? = req.getParameter("redirect")
if(redirect!=null) {
input(name=FIELD_REDIRECT, type = InputType.hidden) { value = redirect }
}
val requestedUsername= req.getParameter("username")
table {
style = "border:none"
tr {
td {
label { for_='#'+FIELD_USERNAME
+"User name:"
}
}
td {
input(name=FIELD_USERNAME, type= InputType.text) {
if (requestedUsername!=null) { value=requestedUsername }
}
}
}
tr {
td {
label { for_='#'+FIELD_PASSWORD
+"Password:"
}
}
td {
input(name=FIELD_PASSWORD, type= InputType.password)
}
}
} // table
span {
style="margin-top: 1em; float: right;"
input(type= InputType.submit) {
value="Log in"
}
}
div { id="forgotpasswd"
a(href=req.contextPath+"/resetpasswd")
}
}
}
*/
}
}
private fun resetPassword(req: HttpServletRequest, resp: HttpServletResponse) {
val mailProperties = Properties()
val user = req.getParameter(FIELD_USERNAME)
if (user.isNullOrBlank()) {
requestResetDialog(req, resp)
} else {
accountDb {
if (!isUser(user)) throw AuthException("Unable to reset",
errorCode = HttpServletResponse.SC_BAD_REQUEST)
val lastReset = lastReset(user)?.time ?: 0
if (nowSeconds - lastReset < MIN_RESET_DELAY) throw AuthException("Too many reset attempts, try later",
errorCode = 429)
val resetToken = generateResetToken(user)
val mailSession = Session.getDefaultInstance(mailProperties)
val message = MimeMessage(mailSession)
val resetUrl = URI(req.scheme, null, req.serverName, req.serverPort, req.requestURI,
"?$FIELD_USERNAME=${URLEncoder.encode(user,
"UTF8")}&$FIELD_RESETTOKEN=${URLEncoder.encode(
resetToken, "UTF8")}", null).toString()
message.addRecipient(Message.RecipientType.TO, InternetAddress("[email protected]", user))
message.subject = "Darwin account password reset"
message.setContent("""
<html><head><title>Darwin account password reset</title></head><body>
<p>Please visit <a href="$resetUrl">$resetUrl</a> to reset your password.</p>
<p>This token will be valid for 30 minutes. If you didn't initiate the reset,
you can safely ignore this message</p>
</body></html>
""".trimIndent(), "text/html")
Transport.send(message)
}
resp.darwinResponse(req, "Reset request sent") {
darwinDialog("Reset request sent") {
p { +"A reset token has been sent to your email address. Please follow the instructions in the email." }
}
}
}
}
private fun requestResetDialog(req: HttpServletRequest,
resp: HttpServletResponse) {
resp.darwinResponse(req, "Provide username") {
darwinDialog("Give your username") {
p {
this.style = "width:22em"
+"Please provide your BU username such that a reset email can be sent to your email address."
}
form(action = "/resetpasswd", method = FormMethod.post) {
table {
tr {
th {
label { htmlFor = FIELD_USERNAME; +"User name:" }
}
td {
input(name = FIELD_USERNAME, type = InputType.text)
+"@bournemouth.ac.uk"
}
}
}
span {
style = "margin-top: 1em; float: right;"
input(type = InputType.reset) {
onClick = "window.location='/'"
}
input(type = InputType.submit) {
value = "Request reset"
}
}
}
}
}
}
}
| lgpl-3.0 | 434dc8bf700fafedb4fd9e0c87a66de7 | 42.987578 | 127 | 0.494493 | 5.474644 | false | false | false | false |
BrianLusina/MovieReel | app/src/main/kotlin/com/moviereel/utils/toolbox/MovieReelDiffTool.kt | 1 | 2548 | package com.moviereel.utils.toolbox
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import java.util.*
/**
* @author lusinabrian on 27/07/17.
* @Notes Does diffing for adapters in class
* This is a utility that allows all adapters to update their data in a background thread and
* perform asynchronous updates
* @param oldItemList old items
* @param newItemList new item list
* @param adapter adapter to update
*/
class MovieReelDiffTool<T, VH : RecyclerView.ViewHolder>(
var oldItemList: ArrayList<T>,
var pendingUpdates: ArrayDeque<ArrayList<T>>,
var adapter: RecyclerView.Adapter<VH>) {
/**
* This performs a diff on the adapter
* */
fun performDiff(newItemList: ArrayList<T>) {
pendingUpdates.add(newItemList)
if (pendingUpdates.size > 1) {
return
}
updateItemsInternal(newItemList)
}
fun updateItemsInternal(newItemList: ArrayList<T>) {
doAsync {
val diff = MovieReelDiffUtilCallback(oldItemList, newItemList)
val diffResult = DiffUtil.calculateDiff(diff)
uiThread {
applyDiffResult(newItemList, diffResult)
}
}
// val handler = Handler()
// Thread(Runnable {
// val diff = MovieReelDiffUtilCallback(oldItemList, newItemList)
// val diffResult = DiffUtil.calculateDiff(diff)
//
// handler.post({
// applyDiffResult(newItemList, diffResult)
// })
// }).start()
}
/**
* Applyes the diff result to the new items which will apply th dispatch
* to the adapter
* @param newItemList
* @param diffResult, result from Diffing of new and old items
* */
fun applyDiffResult(newItemList: ArrayList<T>, diffResult: DiffUtil.DiffResult) {
pendingUpdates.remove()
// dispatch updates
dispatchUpdates(newItemList, diffResult)
if (pendingUpdates.size > 0) {
performDiff(pendingUpdates.peek())
}
}
/**
* Dispatches updates to adapter with new items and diff result
* @param newItems new items to add to adapter
* @param diffResult diff result from callback
* */
fun dispatchUpdates(newItems: ArrayList<T>, diffResult: DiffUtil.DiffResult) {
diffResult.dispatchUpdatesTo(adapter)
oldItemList.clear()
oldItemList.addAll(newItems)
}
} | mit | 13ea35f7392130cfdbb5ac63fbbaabb2 | 29.345238 | 93 | 0.646389 | 4.615942 | false | false | false | false |
GregDick/nearby-sample | app/src/main/java/com/example/mercury/nearbysample/MessageModel.kt | 1 | 1829 | package com.example.mercury.nearbysample
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.ObjectInput
import java.io.ObjectInputStream
import java.io.ObjectOutput
import java.io.ObjectOutputStream
import java.io.Serializable
class MessageModel(val who: String?, val text: String?) : Serializable {
override fun toString(): String {
return "MessageModel{" +
"who='" + who + '\''.toString() +
", text='" + text + '\''.toString() +
'}'.toString()
}
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o == null || javaClass != o.javaClass) return false
val that = o as MessageModel?
if (if (who != null) who != that!!.who else that!!.who != null) return false
return if (text != null) text == that.text else that.text == null
}
override fun hashCode(): Int {
var result = who?.hashCode() ?: 0
result = 31 * result + (text?.hashCode() ?: 0)
return result
}
companion object {
fun empty(): MessageModel {
return MessageModel("", "")
}
@Throws(IOException::class)
fun convertToBytes(messageModel: MessageModel): ByteArray {
ByteArrayOutputStream().use { bos ->
ObjectOutputStream(bos).use { out ->
out.writeObject(messageModel)
return bos.toByteArray()
}
}
}
@Throws(IOException::class, ClassNotFoundException::class)
fun convertFromBytes(bytes: ByteArray): MessageModel {
ByteArrayInputStream(bytes).use { bis -> ObjectInputStream(bis).use { `in` -> return `in`.readObject() as MessageModel } }
}
}
}
| mit | 5e38e4954eb59437db8515881bde7a15 | 30.534483 | 134 | 0.586659 | 4.775457 | false | false | false | false |
SerCeMan/franky | franky-intellij/src/main/kotlin/me/serce/franky/ui/flame/flameTree.kt | 1 | 1091 | package me.serce.franky.ui.flame
import me.serce.franky.Protocol.CallTraceSampleInfo
import java.util.*
fun CallTraceSampleInfo.validate() {
if (frameList.isEmpty()) {
throw IllegalArgumentException("Empty trace sample $this")
}
}
/**
* Represents tree of stack traces
*/
class FlameTree(sampleInfo: List<CallTraceSampleInfo>) {
val root: FlameNode = FlameNode(0, null)
init {
for (sample in sampleInfo) {
sample.validate()
addSampleToTree(sample)
}
}
private fun addSampleToTree(sample: CallTraceSampleInfo) {
val coef = sample.callCount
root.cost += coef
var node = root
for (frame in sample.frameList.reversed()) {
val methodId = frame.jMethodId
node = node.children.computeIfAbsent(methodId, {
FlameNode(frame.jMethodId, node)
})
node.cost += coef
}
}
}
class FlameNode(val methodId: Long, val parent: FlameNode?) {
var cost: Int = 0
val children: HashMap<Long, FlameNode> = hashMapOf()
}
| apache-2.0 | f2e2b8df2001aa00d478b09947e1046e | 23.795455 | 66 | 0.620532 | 4.070896 | false | false | false | false |
ursjoss/scipamato | core/core-sync/src/main/kotlin/ch/difty/scipamato/core/sync/launcher/SyncJobResult.kt | 1 | 2446 | package ch.difty.scipamato.core.sync.launcher
import ch.difty.scipamato.common.persistence.paging.Sort
import java.io.Serializable
import kotlin.math.min
/**
* The [SyncJobResult] collects log messages for one or more job steps
* and keeps track of the entire jobs result. If all steps succeed, the jobs
* result is success. If only one step fails, the job fails.
*/
class SyncJobResult {
private val logMessages: MutableList<LogMessage> = ArrayList()
private var result = JobResult.UNKNOWN
private var running = false
val isRunning get() = running
val isSuccessful: Boolean
get() = result == JobResult.SUCCESS
val isFailed: Boolean
get() = result == JobResult.FAILURE
val messages: List<LogMessage>
get() = ArrayList(logMessages)
fun messageCount() = messages.size.toLong()
fun setSuccess(msg: String) {
running = true
if (result != JobResult.FAILURE) result = JobResult.SUCCESS
logMessages.add(LogMessage(msg, MessageLevel.INFO))
}
fun setFailure(msg: String) {
running = true
result = JobResult.FAILURE
logMessages.add(LogMessage(msg, MessageLevel.ERROR))
}
fun setWarning(msg: String) {
running = true
logMessages.add(LogMessage(msg, MessageLevel.WARNING))
}
fun setDone() {
running = false
}
fun getPagedResultMessages(first: Int, count: Int, sortProp: String, dir: Sort.Direction): Iterator<LogMessage> {
fun <T, R : Comparable<R>> List<T>.sortMethod(selector: (T) -> R?): List<T> =
if (dir == Sort.Direction.ASC) this.sortedBy(selector)
else sortedByDescending(selector)
val sorted = when (sortProp) {
"messageLevel" -> messages.sortMethod { it.messageLevel }
else -> messages.sortMethod { it.message }
}
return sorted.subList(first, min(first + count, messages.size)).iterator()
}
fun clear() {
logMessages.clear()
result = JobResult.UNKNOWN
setDone()
}
private enum class JobResult {
UNKNOWN, SUCCESS, FAILURE
}
enum class MessageLevel {
INFO, WARNING, ERROR
}
data class LogMessage(
val message: String? = null,
val messageLevel: MessageLevel = MessageLevel.INFO,
) : Serializable {
companion object {
private const val serialVersionUID = 1L
}
}
}
| bsd-3-clause | afb0dcdad79620dffc45a3443d750eff | 28.119048 | 117 | 0.639002 | 4.383513 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.