repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 53
values | size
stringlengths 2
6
| content
stringlengths 73
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
977
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ktorio/ktor | ktor-client/ktor-client-core/common/src/io/ktor/client/request/HttpRequestPipeline.kt | 1 | 2531 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.client.request
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.util.pipeline.*
/**
* An [HttpClient]'s pipeline used for executing [HttpRequest].
*/
public class HttpRequestPipeline(
override val developmentMode: Boolean = false
) : Pipeline<Any, HttpRequestBuilder>(Before, State, Transform, Render, Send) {
/**
* All interceptors accept payload as [subject] and try to convert it to [OutgoingContent].
* Last phase should proceed with [HttpClientCall].
*/
public companion object Phases {
/**
* The earliest phase that happens before any other.
*/
public val Before: PipelinePhase = PipelinePhase("Before")
/**
* Use this phase to modify a request with a shared state.
*/
public val State: PipelinePhase = PipelinePhase("State")
/**
* Transform a request body to supported render format.
*/
public val Transform: PipelinePhase = PipelinePhase("Transform")
/**
* Encode a request body to [OutgoingContent].
*/
public val Render: PipelinePhase = PipelinePhase("Render")
/**
* A phase for the [HttpSend] plugin.
*/
public val Send: PipelinePhase = PipelinePhase("Send")
}
}
/**
* An [HttpClient]'s pipeline used for sending [HttpRequest] to a remote server.
*/
public class HttpSendPipeline(
override val developmentMode: Boolean = false
) : Pipeline<Any, HttpRequestBuilder>(Before, State, Monitoring, Engine, Receive) {
public companion object Phases {
/**
* The earliest phase that happens before any other.
*/
public val Before: PipelinePhase = PipelinePhase("Before")
/**
* Use this phase to modify request with a shared state.
*/
public val State: PipelinePhase = PipelinePhase("State")
/**
* Use this phase for logging and other actions that don't modify a request or shared data.
*/
public val Monitoring: PipelinePhase = PipelinePhase("Monitoring")
/**
* Send a request to a remote server.
*/
public val Engine: PipelinePhase = PipelinePhase("Engine")
/**
* Receive a pipeline execution phase.
*/
public val Receive: PipelinePhase = PipelinePhase("Receive")
}
}
| apache-2.0 | f8b5a8fbf238cf07cc45f1f22bfa8db0 | 29.865854 | 118 | 0.629 | 4.962745 | false | false | false | false |
Flocksserver/Androidkt-CleanArchitecture-Template | data/src/main/java/de/flocksserver/data/persistence/DataStore.kt | 1 | 2249 | package de.flocksserver.data.persistence
import android.content.Context
import android.content.SharedPreferences
import de.flocksserver.data.persistence.model.ContentDataModel
import de.flocksserver.data.persistence.model.mapper.ContentMMapper
import de.flocksserver.data.service.TextService
import de.flocksserver.domain.model.ContentModel
import de.flocksserver.domain.model.ItemModel
import de.flocksserver.domain.repository.MyRepository
import io.reactivex.Completable
import io.reactivex.Single
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import javax.inject.Inject
/**
* Created by marcel on 08.08.17.
*/
class DataStore @Inject constructor(private val contentMMapper: ContentMMapper) : MyRepository {
@Inject lateinit var logger: AnkoLogger
@Inject lateinit var context: Context
@Inject lateinit var sharedPrefs: SharedPreferences
@Inject lateinit var textService: TextService
override fun getContent(): Single<ContentModel> {
logger.info { "DATASTORE -> get content" }
return Single.fromCallable {
val contentData = getContentData()
contentMMapper.transformDMtoM(contentData)
}
}
override fun addItem(): Completable {
logger.info { "DATASTORE -> add random string item" }
return Completable.fromCallable {
val contentData = getContentData()
val content = contentMMapper.transformDMtoM(contentData)
val item = ItemModel(textService.generateText())
content.items?.add(item)
sharedPrefs.edit().putStringSet("content",contentMMapper.transformMtoDM(content)?.items).apply()
}
}
override fun deleteItem(itemModel: ItemModel): Completable {
logger.info { "DATASTORE -> delete item $itemModel" }
return Completable.fromCallable {
val contentData = getContentData()
val content = contentMMapper.transformDMtoM(contentData)
content.items?.remove(itemModel)
sharedPrefs.edit().putStringSet("content",contentMMapper.transformMtoDM(content)?.items).apply()
}
}
private fun getContentData() = ContentDataModel(sharedPrefs.getStringSet("content", emptySet<String>()))
}
| apache-2.0 | 0d47a99cfc0bae42314ca5a805c507b1 | 35.274194 | 108 | 0.722988 | 4.608607 | false | false | false | false |
Frederikam/FredBoat | FredBoat/src/main/java/fredboat/sentinel/wrapperEntityInterfaces.kt | 1 | 1340 | package fredboat.sentinel
import fredboat.perms.IPermissionSet
import org.springframework.stereotype.Service
import java.time.OffsetDateTime
import java.util.*
private const val DISCORD_EPOCH = 1420070400000L
@Suppress("unused")
@Service
class SentinelProvider(sentinelParam: Sentinel) {
init {
providedSentinel = sentinelParam
}
}
private lateinit var providedSentinel: Sentinel
interface SentinelEntity {
val id: Long
val idString: String
get() = id.toString()
val sentinel: Sentinel
get() = providedSentinel
val creationTime: OffsetDateTime
get() {
// https://discord.com/developers/docs/reference#convert-snowflake-to-datetime
// Shift 22 bits right so we only have the time
val timestamp = (id ushr 22) + DISCORD_EPOCH
val gmt = Calendar.getInstance(TimeZone.getTimeZone("GMT"))
gmt.timeInMillis = timestamp
return OffsetDateTime.ofInstant(gmt.toInstant(), gmt.timeZone.toZoneId())
}
}
interface Channel : SentinelEntity {
override val id: Long
val name: String
val guild: Guild
val ourEffectivePermissions: IPermissionSet
fun checkOurPermissions(permissions: IPermissionSet) = ourEffectivePermissions has permissions
}
interface IMentionable {
val asMention: String
} | mit | 1ec8ed1dc3f0ae81452f7203a800b020 | 27.531915 | 98 | 0.707463 | 4.573379 | false | false | false | false |
dahlstrom-g/intellij-community | platform/platform-impl/src/com/intellij/ui/list/targetPopup.kt | 6 | 2548 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("TargetPopup")
package com.intellij.ui.list
import com.intellij.ide.ui.UISettings
import com.intellij.navigation.TargetPresentation
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.ui.popup.IPopupChooserBuilder
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.util.NlsContexts.PopupTitle
import com.intellij.util.concurrency.annotations.RequiresEdt
import java.util.function.Consumer
import java.util.function.Function
import javax.swing.ListCellRenderer
@RequiresEdt
fun <T> createTargetPopup(
@PopupTitle title: String,
items: List<T>,
presentations: List<TargetPresentation>,
processor: Consumer<in T>
): JBPopup {
return createTargetPopup(
title = title,
items = items.zip(presentations),
presentationProvider = { it.second },
processor = { processor.accept(it.first) }
)
}
@RequiresEdt
fun <T> createTargetPopup(
@PopupTitle title: String,
items: List<T>,
presentationProvider: Function<in T, out TargetPresentation>,
processor: Consumer<in T>
): JBPopup {
return buildTargetPopup(items, presentationProvider, processor)
.setTitle(title)
.createPopup()
}
@RequiresEdt
fun <T> buildTargetPopup(
items: List<T>,
presentationProvider: Function<in T, out TargetPresentation>,
processor: Consumer<in T>
): IPopupChooserBuilder<T> {
require(items.size > 1) {
"Attempted to build a target popup with ${items.size} elements"
}
return JBPopupFactory.getInstance()
.createPopupChooserBuilder(items)
.setRenderer(createTargetPresentationRenderer(presentationProvider))
.setFont(EditorUtil.getEditorFont())
.withHintUpdateSupply()
.setNamerForFiltering { item: T ->
presentationProvider.apply(item).speedSearchText()
}.setItemChosenCallback(processor::accept)
}
fun <T> createTargetPresentationRenderer(presentationProvider: Function<in T, out TargetPresentation>): ListCellRenderer<T> {
return if (UISettings.getInstance().showIconInQuickNavigation) {
TargetPresentationRenderer(presentationProvider)
}
else {
TargetPresentationMainRenderer(presentationProvider)
}
}
private fun TargetPresentation.speedSearchText(): String {
val presentableText = presentableText
val containerText = containerText
return if (containerText == null) presentableText else "$presentableText $containerText"
}
| apache-2.0 | 87d14337886041b2602c84d61883334e | 32.090909 | 125 | 0.775903 | 4.268007 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/intentions/elements/CreateConstructorAction.kt | 14 | 2807 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.annotator.intentions.elements
import com.intellij.codeInsight.CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement
import com.intellij.codeInsight.daemon.QuickFixBundle.message
import com.intellij.lang.jvm.JvmModifier
import com.intellij.lang.jvm.actions.CreateConstructorRequest
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.plugins.groovy.intentions.base.IntentionUtils.createTemplateForMethod
import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition
import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod
internal class CreateConstructorAction(
targetClass: GrTypeDefinition,
override val request: CreateConstructorRequest
) : CreateMemberAction(targetClass, request) {
override fun getFamilyName(): String = message("create.constructor.family")
override fun getText(): String = message("create.constructor.from.new.text")
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
ConstructorMethodRenderer(project, target, request).execute()
}
}
private class ConstructorMethodRenderer(
val project: Project,
val targetClass: GrTypeDefinition,
val request: CreateConstructorRequest
) {
val factory = GroovyPsiElementFactory.getInstance(project)
fun execute() {
var constructor = renderConstructor()
constructor = insertConstructor(constructor)
constructor = forcePsiPostprocessAndRestoreElement(constructor) ?: return
setupTemplate(constructor)
}
private fun setupTemplate(method: GrMethod) {
val parameters = request.expectedParameters
val typeExpressions = setupParameters(method, parameters).toTypedArray()
val nameExpressions = setupNameExpressions(parameters, project).toTypedArray()
createTemplateForMethod(typeExpressions, nameExpressions, method, targetClass, null, true, null)
}
private fun renderConstructor(): GrMethod {
val constructor = factory.createConstructor()
val modifiersToRender = request.modifiers.toMutableList()
modifiersToRender -= JvmModifier.PUBLIC //public by default
for (modifier in modifiersToRender) {
constructor.modifierList.setModifierProperty(modifier.toPsiModifier(), true)
}
for (annotation in request.annotations) {
constructor.modifierList.addAnnotation(annotation.qualifiedName)
}
return constructor
}
private fun insertConstructor(method: GrMethod): GrMethod {
return targetClass.add(method) as GrMethod
}
} | apache-2.0 | 7316d8a01d42151637a3c3459c03563f | 36.945946 | 140 | 0.79658 | 4.881739 | false | false | false | false |
zeapo/Android-Password-Store | app/src/main/java/com/zeapo/pwdstore/autofill/AutofillPreferenceActivity.kt | 1 | 6356 | package com.zeapo.pwdstore.autofill
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.AsyncTask
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.app.NavUtils
import androidx.core.app.TaskStackBuilder
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
import com.zeapo.pwdstore.R
import java.lang.ref.WeakReference
import java.util.ArrayList
class AutofillPreferenceActivity : AppCompatActivity() {
internal var recyclerAdapter: AutofillRecyclerAdapter? = null // let fragment have access
private var recyclerView: RecyclerView? = null
private var pm: PackageManager? = null
private var recreate: Boolean = false // flag for action on up press; origin autofill dialog? different act
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.autofill_recycler_view)
recyclerView = findViewById(R.id.autofill_recycler)
val layoutManager = LinearLayoutManager(this)
recyclerView!!.layoutManager = layoutManager
recyclerView!!.addItemDecoration(DividerItemDecoration(this, DividerItemDecoration.VERTICAL))
pm = packageManager
PopulateTask(this).execute()
// if the preference activity was started from the autofill dialog
recreate = false
val extras = intent.extras
if (extras != null) {
recreate = true
showDialog(extras.getString("packageName"), extras.getString("appName"), extras.getBoolean("isWeb"))
}
title = "Autofill Apps"
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener { showDialog("", "", true) }
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.autofill_preference, menu)
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem.actionView as SearchView
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(s: String): Boolean {
return false
}
override fun onQueryTextChange(s: String): Boolean {
if (recyclerAdapter != null) {
recyclerAdapter!!.filter(s)
}
return true
}
})
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// in service, we CLEAR_TASK. then we set the recreate flag.
// something of a hack, but w/o CLEAR_TASK, behaviour was unpredictable
if (item.itemId == android.R.id.home) {
val upIntent = NavUtils.getParentActivityIntent(this)
if (recreate) {
TaskStackBuilder.create(this)
.addNextIntentWithParentStack(upIntent!!)
.startActivities()
} else {
NavUtils.navigateUpTo(this, upIntent!!)
}
return true
}
return super.onOptionsItemSelected(item)
}
fun showDialog(packageName: String?, appName: String?, isWeb: Boolean) {
val df = AutofillFragment()
val args = Bundle()
args.putString("packageName", packageName)
args.putString("appName", appName)
args.putBoolean("isWeb", isWeb)
df.arguments = args
df.show(supportFragmentManager, "autofill_dialog")
}
companion object {
private class PopulateTask(activity: AutofillPreferenceActivity) : AsyncTask<Void, Void, Void>() {
val weakReference = WeakReference<AutofillPreferenceActivity>(activity)
override fun onPreExecute() {
weakReference.get()?.apply {
runOnUiThread { findViewById<View>(R.id.progress_bar).visibility = View.VISIBLE }
}
}
override fun doInBackground(vararg params: Void): Void? {
val pm = weakReference.get()?.pm ?: return null
val intent = Intent(Intent.ACTION_MAIN)
intent.addCategory(Intent.CATEGORY_LAUNCHER)
val allAppsResolveInfo = pm.queryIntentActivities(intent, 0)
val allApps = ArrayList<AutofillRecyclerAdapter.AppInfo>()
for (app in allAppsResolveInfo) {
allApps.add(AutofillRecyclerAdapter.AppInfo(app.activityInfo.packageName, app.loadLabel(pm).toString(), false, app.loadIcon(pm)))
}
val prefs = weakReference.get()?.getSharedPreferences("autofill_web", Context.MODE_PRIVATE)
val prefsMap = prefs!!.all
for (key in prefsMap.keys) {
try {
allApps.add(AutofillRecyclerAdapter.AppInfo(key, key, true, pm.getApplicationIcon("com.android.browser")))
} catch (e: PackageManager.NameNotFoundException) {
allApps.add(AutofillRecyclerAdapter.AppInfo(key, key, true, null))
}
}
weakReference.get()?.recyclerAdapter = AutofillRecyclerAdapter(allApps, weakReference.get()!!)
return null
}
override fun onPostExecute(ignored: Void?) {
weakReference.get()?.apply {
runOnUiThread {
findViewById<View>(R.id.progress_bar).visibility = View.GONE
recyclerView!!.adapter = recyclerAdapter
val extras = intent.extras
if (extras != null) {
recyclerView!!.scrollToPosition(recyclerAdapter!!.getPosition(extras.getString("appName")!!))
}
}
}
}
}
}
}
| gpl-3.0 | 87db5ae1101e36dedf00b92b53ca550b | 38.974843 | 149 | 0.627596 | 5.409362 | false | false | false | false |
subhalaxmin/Programming-Kotlin | Chapter07/src/main/kotlin/com/packt/chapter7/7.15.annotations.kt | 1 | 1103 | package com.packt.chapter7
@Target(AnnotationTarget.CLASS,
AnnotationTarget.FUNCTION,
AnnotationTarget.TYPE_PARAMETER,
AnnotationTarget.FIELD,
AnnotationTarget.CONSTRUCTOR,
AnnotationTarget.TYPE,
AnnotationTarget.VALUE_PARAMETER,
AnnotationTarget.PROPERTY,
AnnotationTarget.EXPRESSION,
AnnotationTarget.TYPEALIAS)
annotation class Foo
@Target(AnnotationTarget.CONSTRUCTOR)
@Retention(AnnotationRetention.SOURCE)
annotation class Woo
annotation class Ipsum(val text: String)
@Foo class MyClass
@Foo class MyInterface
@Foo object MyObject
fun bar(@Foo param: Int): Int = param
@Foo fun foo(): Int = 0
@Foo typealias MYC = MyClass
class PropertyClass {
@Foo var name: String? = null
}
class Bar @Foo constructor(name: String)
fun expressionAnnotation(): Int {
val str = @Foo "hello foo"
return (@Foo 123)
}
annotation class Description(val summary: String)
@Description("This class creates Executor instances") class Executors
fun main(args: Array<String>) {
val desc = Executors::class.annotations.first() as Description
println(desc.summary)
} | mit | 6357f180f1e3a1e981058d62e684b6c8 | 20.647059 | 69 | 0.759746 | 4.146617 | false | false | false | false |
airbnb/epoxy | epoxy-processor/src/main/java/com/airbnb/epoxy/processor/resourcescanning/ResourceValue.kt | 1 | 1990 | package com.airbnb.epoxy.processor.resourcescanning
import com.airbnb.epoxy.processor.ClassNames.ANDROID_R
import com.squareup.javapoet.ClassName
import com.squareup.javapoet.CodeBlock
/**
* Represents a resource used as an annotation parameter.
*
*
* Inspired by Butterknife. https://github.com/JakeWharton/butterknife/pull/613
*/
class ResourceValue {
val className: ClassName?
val resourceName: String?
val value: Int
val code: CodeBlock
val qualified: Boolean
val resourceType: String? get() = className?.simpleName()
val rClass: ClassName? get() = className?.topLevelClassName()
constructor(value: Int) {
this.value = value
code = CodeBlock.of("\$L", value)
qualified = false
resourceName = null
className = null
}
/**
* @param className eg com.airbnb.epoxy.R.layout
*/
constructor(
className: ClassName,
resourceName: String,
value: Int
) {
this.className = className
this.resourceName = resourceName
this.value = value
code = if (className.topLevelClassName() == ANDROID_R)
CodeBlock.of("\$L.\$N", className, resourceName)
else
CodeBlock.of("\$T.\$N", className, resourceName)
qualified = true
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as ResourceValue
if (value != other.value) return false
if (code != other.code) return false
return true
}
override fun hashCode(): Int {
var result = value
result = 31 * result + code.hashCode()
return result
}
override fun toString(): String {
throw UnsupportedOperationException("Please use value or code explicitly")
}
fun debugDetails(): String = code.toString()
fun isStringResource(): Boolean = resourceType == "string"
}
| apache-2.0 | d9f8077c6e623d341383092d518c9224 | 25.891892 | 82 | 0.632161 | 4.638695 | false | false | false | false |
paplorinc/intellij-community | platform/built-in-server/testSrc/org/jetbrains/ide/TestManager.kt | 2 | 4076 | // 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.ide
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ModuleRootModificationUtil
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.testFramework.runInEdtAndWait
import com.intellij.util.io.createFile
import com.intellij.util.io.systemIndependentPath
import org.junit.rules.TestWatcher
import org.junit.runner.Description
import java.io.File
private const val EXCLUDED_DIR_NAME = "excludedDir"
internal class TestManager(private val projectRule: ProjectRule, private val tempDirManager: TemporaryDirectory) : TestWatcher() {
var annotation: TestDescriptor? = null
var filePath: String? = null
private var fileToDelete: VirtualFile? = null
private var ioFileToDelete: File? = null
@Target(AnnotationTarget.FUNCTION)
annotation class TestDescriptor(val filePath: String,
val line: Int = -1,
val column: Int = -1,
val relativeToProject: Boolean = false,
val excluded: Boolean = false,
val doNotCreate: Boolean = false,
val status: Int = 200)
override fun starting(description: Description) {
annotation = description.getAnnotation(TestDescriptor::class.java)
if (annotation == null) {
return
}
filePath = StringUtil.nullize(annotation!!.filePath)
if (filePath == null) {
return
}
// trigger project creation
projectRule.project
if (filePath!! == "_tmp_") {
val file = tempDirManager.newPath(".txt", refreshVfs = true)
if (!annotation!!.doNotCreate) {
file.createFile()
}
filePath = file.systemIndependentPath
return
}
if (annotation!!.doNotCreate) {
return
}
runInEdtAndWait {
val normalizedFilePath = FileUtilRt.toSystemIndependentName(filePath!!)
if (annotation!!.relativeToProject) {
val root = projectRule.project.baseDir
runWriteAction {
fileToDelete = root.findOrCreateChildData(this@TestManager, normalizedFilePath)
}
}
else {
val module = projectRule.module
if (annotation!!.excluded) {
ModuleRootModificationUtil.updateModel(module) { model ->
val contentEntry = model.contentEntries[0]
val contentRoot = contentEntry.file!!
runWriteAction {
contentRoot.findChild(EXCLUDED_DIR_NAME)?.delete(this@TestManager)
fileToDelete = contentRoot.createChildDirectory(this@TestManager, EXCLUDED_DIR_NAME)
fileToDelete!!.createChildData(this@TestManager, normalizedFilePath)
}
contentEntry.addExcludeFolder(fileToDelete!!)
}
filePath = "$EXCLUDED_DIR_NAME/$filePath"
}
else {
val root = ModuleRootManager.getInstance(module).sourceRoots[0]
runWriteAction {
fileToDelete = root.findOrCreateChildData(this@TestManager, normalizedFilePath)
}
}
}
}
}
override fun finished(description: Description?) {
if (annotation!!.excluded) {
ModuleRootModificationUtil.updateModel(projectRule.module) { model -> model.contentEntries[0].removeExcludeFolder(EXCLUDED_DIR_NAME) }
}
if (fileToDelete != null) {
runInEdtAndWait { runWriteAction { fileToDelete?.delete(this@TestManager) } }
fileToDelete = null
}
if (ioFileToDelete != null && !FileUtilRt.delete(ioFileToDelete!!)) {
ioFileToDelete!!.deleteOnExit()
}
annotation = null
filePath = null
}
} | apache-2.0 | 45e8d10ca8fc129864aed305f2e203c7 | 34.146552 | 140 | 0.665604 | 5.075965 | false | true | false | false |
google/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/downloader/CodeWithMeGuestLauncher.kt | 1 | 4738 | package com.intellij.remoteDev.downloader
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task.Backgroundable
import com.intellij.openapi.project.Project
import com.intellij.openapi.rd.createLifetime
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsContexts
import com.intellij.remoteDev.RemoteDevUtilBundle
import com.intellij.remoteDev.util.UrlUtil
import com.intellij.util.application
import com.intellij.util.fragmentParameters
import com.jetbrains.rd.util.lifetime.Lifetime
import org.jetbrains.annotations.ApiStatus
import java.util.concurrent.ConcurrentHashMap
@ApiStatus.Experimental
object CodeWithMeGuestLauncher {
private val LOG = logger<CodeWithMeGuestLauncher>()
private val alreadyDownloading = ConcurrentHashMap.newKeySet<String>()
fun downloadCompatibleClientAndLaunch(project: Project?, url: String, @NlsContexts.DialogTitle product: String, onDone: (Lifetime) -> Unit) {
if (!application.isDispatchThread) {
// starting a task from background will call invokeLater, but with wrong modality, so do it ourselves
application.invokeLater({ downloadCompatibleClientAndLaunch(project, url, product, onDone) }, ModalityState.any())
return
}
val uri = UrlUtil.parseOrShowError(url, product) ?: return
if (!alreadyDownloading.add(url)) {
LOG.info("Already downloading a client for $url")
return
}
ProgressManager.getInstance().run(object : Backgroundable(project, RemoteDevUtilBundle.message("launcher.title"), true) {
private var clientLifetime : Lifetime = Lifetime.Terminated
override fun run(progressIndicator: ProgressIndicator) {
try {
val sessionInfo = when (uri.scheme) {
"tcp", "gwws" -> {
val clientBuild = uri.fragmentParameters["cb"] ?: error("there is no client build in url")
val jreBuild = uri.fragmentParameters["jb"] ?: error("there is no jre build in url")
val unattendedMode = uri.fragmentParameters["jt"] != null
CodeWithMeClientDownloader.createSessionInfo(clientBuild, jreBuild, unattendedMode)
}
"http", "https" -> {
progressIndicator.text = RemoteDevUtilBundle.message("launcher.get.client.info")
ThinClientSessionInfoFetcher.getSessionUrl(uri)
}
else -> {
error("scheme '${uri.scheme} is not supported'")
}
}
val extractedJetBrainsClientData = CodeWithMeClientDownloader.downloadClientAndJdk(sessionInfo, progressIndicator)
if (extractedJetBrainsClientData == null) return
clientLifetime = runDownloadedClient(
lifetime = project?.createLifetime() ?: Lifetime.Eternal,
extractedJetBrainsClientData = extractedJetBrainsClientData,
urlForThinClient = url,
product = product,
progressIndicator = progressIndicator
)
}
catch (t: Throwable) {
LOG.warn(t)
application.invokeLater({
Messages.showErrorDialog(
RemoteDevUtilBundle.message("error.url.issue", t.message ?: "Unknown"),
product)
}, ModalityState.any())
}
finally {
alreadyDownloading.remove(url)
}
}
override fun onSuccess() = onDone.invoke(clientLifetime)
override fun onCancel() = Unit
})
}
fun runDownloadedClient(lifetime: Lifetime, extractedJetBrainsClientData: ExtractedJetBrainsClientData, urlForThinClient: String,
@NlsContexts.DialogTitle product: String, progressIndicator: ProgressIndicator?): Lifetime {
// todo: offer to connect as-is?
try {
progressIndicator?.text = RemoteDevUtilBundle.message("launcher.launch.client")
progressIndicator?.text2 = extractedJetBrainsClientData.clientDir.toString()
val thinClientLifetime = CodeWithMeClientDownloader.runCwmGuestProcessFromDownload(lifetime, urlForThinClient, extractedJetBrainsClientData)
// Wait a bit until process will be launched and only after that finish task
Thread.sleep(3000)
return thinClientLifetime
}
catch (t: Throwable) {
Logger.getInstance(javaClass).warn(t)
application.invokeLater {
Messages.showErrorDialog(
RemoteDevUtilBundle.message("error.guest.run.issue", t.message ?: "Unknown"),
product)
}
return Lifetime.Terminated
}
}
} | apache-2.0 | 30f555acf9f156738240762eeab7ce6c | 39.853448 | 146 | 0.700295 | 5.111111 | false | false | false | false |
google/iosched | mobile/src/main/java/com/google/samples/apps/iosched/ui/onboarding/OnboardingActivity.kt | 1 | 2807 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.ui.onboarding
import android.os.Bundle
import android.widget.FrameLayout
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.google.samples.apps.iosched.R
import com.google.samples.apps.iosched.shared.util.inTransaction
import com.google.samples.apps.iosched.ui.signin.SignInDialogFragment
import com.google.samples.apps.iosched.util.doOnApplyWindowInsets
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
@AndroidEntryPoint
class OnboardingActivity : AppCompatActivity() {
private val viewModel: OnboardingViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_onboarding)
WindowCompat.setDecorFitsSystemWindows(window, false)
val container: FrameLayout = findViewById(R.id.fragment_container)
container.doOnApplyWindowInsets { v, insets, padding ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.updatePadding(top = padding.top + systemBars.top)
}
if (savedInstanceState == null) {
supportFragmentManager.inTransaction {
add(R.id.fragment_container, OnboardingFragment())
}
}
lifecycleScope.launch {
lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.navigationActions.collect { action ->
if (action == OnboardingNavigationAction.NavigateToSignInDialog) {
openSignInDialog()
}
}
}
}
}
private fun openSignInDialog() {
SignInDialogFragment().show(supportFragmentManager, DIALOG_SIGN_IN)
}
companion object {
private const val DIALOG_SIGN_IN = "dialog_sign_in"
}
}
| apache-2.0 | 134bf7665ae66a804a09c609402dcfce | 34.987179 | 86 | 0.721055 | 4.881739 | false | false | false | false |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/debugger/utils/HaskellUtils.kt | 1 | 2121 | package org.jetbrains.haskell.debugger.utils
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import org.jetbrains.haskell.fileType.HaskellFile
import com.intellij.openapi.application.ApplicationManager
import java.util.concurrent.locks.ReentrantLock
import javax.swing.JPanel
import javax.swing.JComponent
import org.jetbrains.haskell.util.gridBagConstraints
import java.awt.Insets
import javax.swing.JLabel
import org.jetbrains.haskell.util.setConstraints
import java.awt.GridBagConstraints
import javax.swing.Box
class HaskellUtils {
companion object {
fun zeroBasedToHaskellLineNumber(zeroBasedFileLineNumber: Int) = zeroBasedFileLineNumber + 1
fun haskellLineNumberToZeroBased(haskellFileLineNumber: Int) = haskellFileLineNumber - 1
fun getModuleName(project: Project, file: VirtualFile): String {
class NameReader(val project: Project, val file: VirtualFile) : Runnable {
private var read: Boolean = false
private var name: String? = null
private val lock = ReentrantLock()
private val condition = lock.newCondition()
override fun run() {
lock.lock()
val hsFile = PsiManager.getInstance(project).findFile(file) as HaskellFile
name = hsFile.getModule()!!.getModuleName()!!.text!!
read = true
condition.signalAll()
lock.unlock()
}
fun returnName(): String {
lock.lock()
while (!read) {
condition.await()
}
lock.unlock()
return name!!
}
}
val reader = NameReader(project, file)
ApplicationManager.getApplication()!!.runReadAction(reader)
return reader.returnName()
}
val HS_BOOLEAN_TYPENAME: String = "Bool"
val HS_BOOLEAN_TRUE: String = "True"
}
} | apache-2.0 | 8ace0a7112fe80cde860e4d32478e37d | 35.586207 | 100 | 0.617162 | 5.086331 | false | false | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/testing/PyQNameResolveAndSplitUtils.kt | 4 | 4757 | /*
* 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.jetbrains.python.testing
import com.intellij.navigation.NavigationItem
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.util.QualifiedName
import com.jetbrains.extensions.getQName
import com.jetbrains.extensions.QNameResolveContext
import com.jetbrains.extensions.getRelativeNameTo
import com.jetbrains.extensions.resolveToElement
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyQualifiedNameOwner
import java.util.*
/**
* Utilities to find which part of [com.intellij.psi.util.QualifiedName] resolves to file and which one to the element
* @author Ilya.Kazakevich
*/
data class QualifiedNameParts(val fileName: QualifiedName, val elementName: QualifiedName, val file: PyFile) {
override fun toString() = elementName.toString()
/**
* @param folderToGetFileRelativePathTo parts of file are relative to this folder (or filename itself if folder is null)
* @return element qname + several parts of file qname.
*/
fun getElementNamePrependingFile(folderToGetFileRelativePathTo: PsiDirectory? = null): QualifiedName {
var relativeFileName: QualifiedName? = null
if (folderToGetFileRelativePathTo != null) {
val folderQName = folderToGetFileRelativePathTo.getQName()
relativeFileName = if (folderQName != null) fileName.getRelativeNameTo(folderQName) else fileName // TODO: DOC
}
if (relativeFileName == null) {
relativeFileName = QualifiedName.fromComponents(fileName.lastComponent)
}
return relativeFileName.append(elementName)
}
}
/**
* Splits name owner's qname to [QualifiedNameParts]: filesystem part and element(symbol) part.
*
* @see [QualifiedName] extension
* @return null if no file part found
*/
internal fun PyQualifiedNameOwner.tryResolveAndSplit(context: QNameResolveContext): QualifiedNameParts? {
val qualifiedNameDottedString = this.qualifiedName ?: return getEmulatedQNameParts()
val qualifiedName = QualifiedName.fromDottedString(qualifiedNameDottedString)
val parts = qualifiedName.tryResolveAndSplit(context)
if (parts != null) {
return parts
}
val pyFile = containingFile as? PyFile ?: return null
val fileQName = pyFile.getQName() ?: return null
val relativePath = qualifiedName.getRelativeNameTo(fileQName) ?: return null
return QualifiedNameParts(fileQName, relativePath, pyFile)
}
/**
* For element containing dashes [PyQualifiedNameOwner.getQualifiedName] does not work.
* this method creates [QualifiedNameParts] with file and qname path inside of it so even files with dashes could be supported
* by test runners
*/
private fun PyQualifiedNameOwner.getEmulatedQNameParts(): QualifiedNameParts? {
val ourFile = this.containingFile as? PyFile ?: return null
val result = ArrayList<String>()
var element: PsiElement = this
while (element !is PsiFile) {
if (element is NavigationItem) {
val name = element.name
if (name != null) {
result.add(name)
}
}
element = element.parent ?: return null
}
return QualifiedNameParts(QualifiedName.fromComponents(ourFile.virtualFile.nameWithoutExtension),
QualifiedName.fromComponents(result.reversed()), ourFile)
}
/**
* Splits qname to [QualifiedNameParts]: filesystem part and element(symbol) part.
* Resolves parts sequentially until meets file. May be slow.
*
* @see [com.jetbrains.python.psi.PyQualifiedNameOwner] extensions
* @return null if no file part found
*/
internal fun QualifiedName.tryResolveAndSplit(context: QNameResolveContext): QualifiedNameParts? {
//TODO: May be slow, cache in this case
// Find first element that may be file
var i = this.componentCount
while (i > 0) {
val possibleFileName = this.subQualifiedName(0, i)
val possibleFile = possibleFileName.resolveToElement(context)
if (possibleFile is PyFile) {
return QualifiedNameParts(possibleFileName,
this.subQualifiedName(possibleFileName.componentCount, this.componentCount),
possibleFile)
}
i--
}
return null
}
| apache-2.0 | 6fcd03ee39da7c7b4d119f09695adced | 37.362903 | 126 | 0.74774 | 4.560882 | false | false | false | false |
muntasirsyed/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/NetService.kt | 1 | 4467 | package org.jetbrains.builtInWebServer
import com.intellij.execution.ExecutionException
import com.intellij.execution.filters.TextConsoleBuilder
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessAdapter
import com.intellij.execution.process.ProcessEvent
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.util.Consumer
import com.intellij.util.net.NetUtils
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.AsyncValueLoader
import org.jetbrains.concurrency.Promise
import org.jetbrains.util.concurrency.AsyncPromise as OJUCAsyncPromise
import org.jetbrains.util.concurrency.toPromise
import javax.swing.Icon
val LOG: Logger = Logger.getInstance(NetService::class.java)
public abstract class NetService @JvmOverloads protected constructor(protected val project: Project, private val consoleManager: ConsoleManager = ConsoleManager()) : Disposable {
protected val processHandler: AsyncValueLoader<OSProcessHandler> = object : AsyncValueLoader<OSProcessHandler>() {
override fun isCancelOnReject() = true
private fun doGetProcessHandler(port: Int): OSProcessHandler? {
try {
return createProcessHandler(project, port)
}
catch (e: ExecutionException) {
LOG.error(e)
return null
}
}
override fun load(promise: AsyncPromise<OSProcessHandler>): Promise<OSProcessHandler> {
val port = NetUtils.findAvailableSocketPort()
val processHandler = doGetProcessHandler(port)
if (processHandler == null) {
promise.setError("rejected")
return promise
}
promise.rejected(Consumer {
processHandler.destroyProcess()
Promise.logError(LOG, it)
})
val processListener = MyProcessAdapter()
processHandler.addProcessListener(processListener)
processHandler.startNotify()
if (promise.getState() == Promise.State.REJECTED) {
return promise
}
ApplicationManager.getApplication().executeOnPooledThread(object : Runnable {
override fun run() {
if (promise.getState() != Promise.State.REJECTED) {
try {
connectToProcess(promise.toPromise(), port, processHandler, processListener)
}
catch (e: Throwable) {
if (!promise.setError(e)) {
LOG.error(e)
}
}
}
}
})
return promise
}
override fun disposeResult(processHandler: OSProcessHandler) {
try {
closeProcessConnections()
}
finally {
processHandler.destroyProcess()
}
}
}
@Throws(ExecutionException::class)
protected abstract fun createProcessHandler(project: Project, port: Int): OSProcessHandler?
protected open fun connectToProcess(promise: OJUCAsyncPromise<OSProcessHandler>, port: Int, processHandler: OSProcessHandler, errorOutputConsumer: Consumer<String>) {
promise.setResult(processHandler)
}
protected abstract fun closeProcessConnections()
override fun dispose() {
processHandler.reset()
}
protected open fun configureConsole(consoleBuilder: TextConsoleBuilder) {
}
protected abstract fun getConsoleToolWindowId(): String
protected abstract fun getConsoleToolWindowIcon(): Icon
public open fun getConsoleToolWindowActions(): ActionGroup = DefaultActionGroup()
private inner class MyProcessAdapter : ProcessAdapter(), Consumer<String> {
override fun onTextAvailable(event: ProcessEvent, outputType: Key<*>) {
print(event.getText(), ConsoleViewContentType.getConsoleViewType(outputType))
}
private fun print(text: String, contentType: ConsoleViewContentType) {
consoleManager.getConsole(this@NetService).print(text, contentType)
}
override fun processTerminated(event: ProcessEvent) {
processHandler.reset()
print("${getConsoleToolWindowId()} terminated\n", ConsoleViewContentType.SYSTEM_OUTPUT)
}
override fun consume(message: String) {
print(message, ConsoleViewContentType.ERROR_OUTPUT)
}
}
} | apache-2.0 | a9c37a05b7aba4fba445e2be7532aad3 | 33.635659 | 178 | 0.732707 | 5.128588 | false | false | false | false |
Kiskae/DiscordKt | implementation/src/main/kotlin/net/serverpeon/discord/internal/data/model/SelfNode.kt | 1 | 1174 | package net.serverpeon.discord.internal.data.model
import net.serverpeon.discord.message.Message
import net.serverpeon.discord.model.DiscordId
import net.serverpeon.discord.model.PostedMessage
import net.serverpeon.discord.model.User
import java.util.concurrent.CompletableFuture
class SelfNode(val root: DiscordNode,
override val id: DiscordId<User>,
override var username: String,
override var discriminator: String,
override var avatar: DiscordId<User.Avatar>?,
var email: String) : UserNode {
override fun toString(): String {
return "Self(id=$id, username='$username', discriminator='$discriminator', avatar=$avatar)"
}
override fun sendMessage(message: Message): CompletableFuture<PostedMessage> {
throw IllegalStateException("Why are you trying to send a message to yourself!")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is UserNode) return false
if (id != other.id) return false
return true
}
override fun hashCode(): Int {
return id.hashCode()
}
} | mit | f4c890cbdee93dc35626341614e25f85 | 30.756757 | 99 | 0.672061 | 4.733871 | false | false | false | false |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/test/DefaultExecutorStressTest.kt | 1 | 2211 | /*
* Copyright 2016-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines
import org.junit.Test
import kotlin.test.*
class DefaultExecutorStressTest : TestBase() {
@Test
fun testDelay() = runTest {
val iterations = 100_000 * stressTestMultiplier
withContext(DefaultExecutor) {
expect(1)
var expected = 1
repeat(iterations) {
expect(++expected)
val deferred = async {
expect(++expected)
val largeArray = IntArray(10_000) { it }
delay(Long.MAX_VALUE)
println(largeArray) // consume to avoid DCE, actually unreachable
}
expect(++expected)
yield()
deferred.cancel()
try {
deferred.await()
} catch (e: CancellationException) {
expect(++expected)
}
}
}
finish(2 + iterations * 4)
}
@Test
fun testWorkerShutdown() = withVirtualTimeSource {
val iterations = 1_000 * stressTestMultiplier
// wait for the worker to shut down
suspend fun awaitWorkerShutdown() {
val executorTimeoutMs = 1000L
delay(executorTimeoutMs)
while (DefaultExecutor.isThreadPresent) { delay(10) } // hangs if the thread refuses to stop
assertFalse(DefaultExecutor.isThreadPresent) // just to make sure
}
runTest {
awaitWorkerShutdown() // so that the worker shuts down after the initial launch
repeat (iterations) {
val job = launch(Dispatchers.Unconfined) {
// this line runs in the main thread
delay(1)
// this line runs in the DefaultExecutor worker
}
delay(100) // yield the execution, allow the worker to spawn
assertTrue(DefaultExecutor.isThreadPresent) // the worker spawned
job.join()
awaitWorkerShutdown()
}
}
}
}
| apache-2.0 | d549b99953c6584ec4e1b8fdabbcad01 | 33.015385 | 104 | 0.532338 | 5.314904 | false | true | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/stdlib/collections/ArraysTest/sortByInPlace.kt | 2 | 1243 | import kotlin.test.*
fun <T: Comparable<T>> assertSorted(array: Array<out T>, message: String = "") = assertSorted(array, message, { it })
inline fun <T, R : Comparable<R>> assertSorted(array: Array<out T>, message: String = "", crossinline selector: (T) -> R) {
if (array.isEmpty() || array.size == 1) {
return
}
var prev = selector(array[0])
for (i in 1..array.lastIndex) {
val cur = selector(array[i])
assertTrue(prev.compareTo(cur) <= 0, message)
prev = cur
}
}
inline fun <T, R : Comparable<R>> assertSortedDescending(array: Array<out T>, message: String = "", crossinline selector: (T) -> R) {
if (array.isEmpty() || array.size == 1) {
return
}
var prev = selector(array[0])
for (i in 1..array.lastIndex) {
val cur = selector(array[i])
assertTrue(prev.compareTo(cur) >= 0, message)
prev = cur
}
}
fun box() {
val data = arrayOf("aa" to 20, "ab" to 3, "aa" to 3)
data.sortBy { it.second }
assertSorted(data) { it.second }
data.sortBy { it.first }
assertSorted(data) { it.first }
data.sortByDescending { (it.first + it.second).length }
assertSortedDescending(data) { (it.first + it.second).length }
}
| apache-2.0 | b243e1cade9de4f4b0f48d0ca8bd804b | 30.871795 | 133 | 0.596943 | 3.341398 | false | false | false | false |
android/compose-samples | Jetsnack/app/src/main/java/com/example/jetsnack/ui/components/GradientTintedIconButton.kt | 1 | 3855 | /*
* 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
*
* 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.jetsnack.ui.components
import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.interaction.collectIsPressedAsState
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.Icon
import androidx.compose.material.Surface
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.jetsnack.ui.theme.JetsnackTheme
@Composable
fun JetsnackGradientTintedIconButton(
imageVector: ImageVector,
onClick: () -> Unit,
contentDescription: String?,
modifier: Modifier = Modifier,
colors: List<Color> = JetsnackTheme.colors.interactiveSecondary
) {
val interactionSource = remember { MutableInteractionSource() }
// This should use a layer + srcIn but needs investigation
val border = Modifier.fadeInDiagonalGradientBorder(
showBorder = true,
colors = JetsnackTheme.colors.interactiveSecondary,
shape = CircleShape
)
val pressed by interactionSource.collectIsPressedAsState()
val background = if (pressed) {
Modifier.offsetGradientBackground(colors, 200f, 0f)
} else {
Modifier.background(JetsnackTheme.colors.uiBackground)
}
val blendMode = if (JetsnackTheme.colors.isDark) BlendMode.Darken else BlendMode.Plus
val modifierColor = if (pressed) {
Modifier.diagonalGradientTint(
colors = listOf(
JetsnackTheme.colors.textSecondary,
JetsnackTheme.colors.textSecondary
),
blendMode = blendMode
)
} else {
Modifier.diagonalGradientTint(
colors = colors,
blendMode = blendMode
)
}
Surface(
modifier = modifier
.clickable(
onClick = onClick,
interactionSource = interactionSource,
indication = null
)
.clip(CircleShape)
.then(border)
.then(background),
color = Color.Transparent
) {
Icon(
imageVector = imageVector,
contentDescription = contentDescription,
modifier = modifierColor
)
}
}
@Preview("default")
@Preview("dark theme", uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
private fun GradientTintedIconButtonPreview() {
JetsnackTheme {
JetsnackGradientTintedIconButton(
imageVector = Icons.Default.Add,
onClick = {},
contentDescription = "Demo",
modifier = Modifier.padding(4.dp)
)
}
}
| apache-2.0 | 5e28bfd088486379fc1a4a6fb4337fba | 33.72973 | 89 | 0.706096 | 4.77104 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/annotation/annotation.kt | 9 | 193 | annotation class Foo
annotation class Bar
<warning descr="SSR">@Foo</warning> val foo1 = 1
@Bar val bar1 = 1
<warning descr="SSR">@Foo</warning> fun foo2(): Int = 1
@Bar fun bar2(): Int = 2 | apache-2.0 | 0aa7ee4dc203c98f3ae4efc8e739aaa0 | 18.4 | 55 | 0.673575 | 3.063492 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/openapi/project/impl/projectLoader.kt | 4 | 3731 | // 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.
@file:JvmName("ProjectLoadHelper")
@file:ApiStatus.Internal
package com.intellij.openapi.project.impl
import com.intellij.diagnostic.Activity
import com.intellij.diagnostic.ActivityCategory
import com.intellij.diagnostic.PluginException
import com.intellij.diagnostic.StartUpMeasurer
import com.intellij.diagnostic.StartUpMeasurer.Activities
import com.intellij.diagnostic.StartUpMeasurer.startActivity
import com.intellij.ide.plugins.PluginManagerCore
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.extensions.impl.ExtensionPointImpl
import com.intellij.openapi.extensions.impl.ExtensionsAreaImpl
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.project.Project
import org.jetbrains.annotations.ApiStatus
// Code maybe located in a ProjectImpl, but it is not possible due to non-technical reasons to convert ProjectImpl into modern language.
internal fun registerComponents(project: ProjectImpl) {
var activity = createActivity(project) { "project ${Activities.REGISTER_COMPONENTS_SUFFIX}" }
// at this point of time plugins are already loaded by application - no need to pass indicator to getLoadedPlugins call
project.registerComponents()
activity = activity?.endAndStart("projectComponentRegistered")
runOnlyCorePluginExtensions(
ProjectServiceContainerCustomizer.getEp()) {
it.serviceRegistered(project)
}
activity?.end()
}
private inline fun createActivity(project: ProjectImpl, message: () -> String): Activity? {
return if (project.isDefault || !StartUpMeasurer.isEnabled()) null else startActivity(message(), ActivityCategory.DEFAULT)
}
internal inline fun <T : Any> runOnlyCorePluginExtensions(ep: ExtensionPointImpl<T>, crossinline executor: (T) -> Unit) {
ep.processWithPluginDescriptor(true) { handler, pluginDescriptor ->
if (pluginDescriptor.pluginId != PluginManagerCore.CORE_ID && pluginDescriptor.pluginId != PluginManagerCore.JAVA_PLUGIN_ID &&
// K/N Platform Deps is a repackaged Java plugin
pluginDescriptor.pluginId.idString != "com.intellij.kotlinNative.platformDeps") {
logger<ProjectImpl>().error(PluginException("Plugin $pluginDescriptor is not approved to add ${ep.name}", pluginDescriptor.pluginId))
}
try {
executor(handler)
}
catch (e: ProcessCanceledException) {
throw e
}
catch (e: PluginException) {
logger<ProjectImpl>().error(e)
}
catch (e: Throwable) {
logger<ProjectImpl>().error(PluginException(e, pluginDescriptor.pluginId))
}
}
}
/**
* Usage requires IJ Platform team approval (including plugin into white-list).
*/
@ApiStatus.Internal
interface ProjectServiceContainerCustomizer {
companion object {
@JvmStatic
fun getEp() = (ApplicationManager.getApplication().extensionArea as ExtensionsAreaImpl)
.getExtensionPoint<ProjectServiceContainerCustomizer>("com.intellij.projectServiceContainerCustomizer")
}
/**
* Invoked after implementation classes for project's components were determined (and loaded),
* but before components are instantiated.
*/
fun serviceRegistered(project: Project)
}
/**
* Usage requires IJ Platform team approval (including plugin into white-list).
*/
@ApiStatus.Internal
interface ProjectServiceContainerInitializedListener {
/**
* Invoked after implementation classes for project's components were determined (and loaded),
* but before components are instantiated.
*/
fun serviceCreated(project: Project)
} | apache-2.0 | 20c035c0df8da30c31684cdf1757364a | 40.466667 | 158 | 0.777272 | 4.758929 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/uast/uast-kotlin/tests/testData/StringTemplateComplexForUInjectionHost.kt | 19 | 407 | val muchRecur = "${"${"${"abc"}"}"}"
val case4 = "a ${"literal"} z"
val case5 = "a ${"literal"} ${"literal"} z"
val literalInLiteral = "a ${"literal$case4"} z"
val literalInLiteral2 = "a ${"literal$case4".repeat(4)} z"
val empty = ""
fun simpleForTemplate(i: Int = 0) = "$i"
fun foo() {
println("$baz")
val template1 = "${simpleForTemplate()}"
val template2 = ".${simpleForTemplate()}"
}
| apache-2.0 | da612a790fd1be71573f235099211644 | 20.421053 | 58 | 0.584767 | 2.949275 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/script/configuration/MultipleScriptDefinitionsChecker.kt | 1 | 5721 | // 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.script.configuration
import com.intellij.ide.actions.ShowSettingsUtilImpl
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileTypes.FileTypeRegistry
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.util.BaseListPopupStep
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.Ref
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.ui.HyperlinkLabel
import org.jetbrains.annotations.Nls
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinFileType
import org.jetbrains.kotlin.idea.core.script.ScriptDefinitionsManager
import org.jetbrains.kotlin.idea.core.script.StandardIdeScriptDefinition
import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings
import org.jetbrains.kotlin.parsing.KotlinParserDefinition
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition
import org.jetbrains.kotlin.scripting.resolve.KotlinScriptDefinitionFromAnnotatedTemplate
import org.jetbrains.kotlin.scripting.resolve.KtFileScriptSource
class MultipleScriptDefinitionsChecker(private val project: Project) : EditorNotifications.Provider<EditorNotificationPanel>() {
override fun getKey(): Key<EditorNotificationPanel> = KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor): EditorNotificationPanel? {
if (!FileTypeRegistry.getInstance().isFileOfType(file, KotlinFileType.INSTANCE)) return null
val ktFile = PsiManager.getInstance(project).findFile(file) as? KtFile ?: return null
if (!ktFile.isScript()) return null
if (KotlinScriptingSettings.getInstance(ktFile.project).suppressDefinitionsCheck) return null
if (!ScriptDefinitionsManager.getInstance(ktFile.project).isReady()) return null
val allApplicableDefinitions = ScriptDefinitionsManager.getInstance(project)
.getAllDefinitions()
.filter {
it.asLegacyOrNull<StandardIdeScriptDefinition>() == null && it.isScript(KtFileScriptSource(ktFile)) &&
KotlinScriptingSettings.getInstance(project).isScriptDefinitionEnabled(it)
}
.toList()
if (allApplicableDefinitions.size < 2) return null
if (areDefinitionsForGradleKts(allApplicableDefinitions)) return null
return createNotification(
ktFile,
allApplicableDefinitions
)
}
private fun areDefinitionsForGradleKts(allApplicableDefinitions: List<ScriptDefinition>): Boolean {
return allApplicableDefinitions.all {
val pattern = it.asLegacyOrNull<KotlinScriptDefinitionFromAnnotatedTemplate>()?.scriptFilePattern?.pattern
pattern == ".*\\.gradle\\.kts" || pattern == "^(settings|.+\\.settings)\\.gradle\\.kts\$" || pattern == ".+\\.init\\.gradle\\.kts"
}
}
companion object {
private val KEY = Key.create<EditorNotificationPanel>("MultipleScriptDefinitionsChecker")
private fun createNotification(psiFile: KtFile, defs: List<ScriptDefinition>): EditorNotificationPanel =
EditorNotificationPanel().apply {
text = KotlinBundle.message("script.text.multiple.script.definitions.are.applicable.for.this.script", defs.first().name)
createComponentActionLabel(
KotlinBundle.message("script.action.text.show.all")
) { label ->
val list = JBPopupFactory.getInstance().createListPopup(
object : BaseListPopupStep<ScriptDefinition>(null, defs) {
override fun getTextFor(value: ScriptDefinition): String {
@NlsSafe
val text = value.asLegacyOrNull<KotlinScriptDefinitionFromAnnotatedTemplate>()?.let {
it.name + " (${it.scriptFilePattern})"
} ?: value.asLegacyOrNull<StandardIdeScriptDefinition>()?.let {
it.name + " (${KotlinParserDefinition.STD_SCRIPT_EXT})"
} ?: (value.name + " (${value.fileExtension})")
return text
}
}
)
list.showUnderneathOf(label)
}
createComponentActionLabel(KotlinBundle.message("script.action.text.ignore")) {
KotlinScriptingSettings.getInstance(psiFile.project).suppressDefinitionsCheck = true
EditorNotifications.getInstance(psiFile.project).updateAllNotifications()
}
createComponentActionLabel(KotlinBundle.message("script.action.text.open.settings")) {
ShowSettingsUtilImpl.showSettingsDialog(psiFile.project, KotlinScriptingSettingsConfigurable.ID, "")
}
}
private fun EditorNotificationPanel.createComponentActionLabel(@Nls labelText: String, callback: (HyperlinkLabel) -> Unit) {
val label: Ref<HyperlinkLabel> = Ref.create()
label.set(createActionLabel(labelText) {
callback(label.get())
})
}
}
}
| apache-2.0 | a6f55708d4252eaba9edef96abbc79c2 | 51.486239 | 158 | 0.683097 | 5.592375 | false | false | false | false |
serssp/reakt | todo/src/main/kotlin/todo/components/TodoTextInput.kt | 3 | 1400 | package todo.components
import com.github.andrewoma.react.*
class TodoTextInputProperties(
val className: String? = null,
val id: String? = null,
val placeHolder: String? = null,
val value: String? = null,
val onSave: (String) -> Unit
)
class TodoTextInput : ComponentSpec<TodoTextInputProperties, String>() {
companion object {
val enterKeyCode = 13
val factory = react.createFactory(TodoTextInput())
}
override fun initialState(): String? {
return props.value ?: ""
}
override fun Component.render() {
log.debug("TodoTextInput.render", props, state)
input({
className = props.className
id = props.id
placeholder = props.placeHolder
onBlur = { save() }
onChange = { onChange(it) }
onKeyDown = { onKeyDown(it) }
value = state
autoFocus = true
})
}
fun save() {
props.onSave(state)
state = ""
}
fun onChange(event: FormEvent) {
state = event.currentTarget.value
}
fun onKeyDown(event: KeyboardEvent) {
if (event.keyCode == enterKeyCode) {
save()
}
}
}
fun Component.todoTextInput(props: TodoTextInputProperties): Component {
return constructAndInsert(Component({ TodoTextInput.factory(Ref(props)) }))
}
| mit | 30e19b1e8e46011c1ebdee5f4490057c | 24 | 79 | 0.582857 | 4.487179 | false | false | false | false |
kickstarter/android-oss | app/src/test/java/com/kickstarter/models/CommentTest.kt | 1 | 1281 | package com.kickstarter.models
import com.kickstarter.mock.factories.CommentFactory
import com.kickstarter.mock.factories.UserFactory
import junit.framework.TestCase
class CommentTest : TestCase() {
fun testEquals_whenSecondCommentDifferentId_returnFalse() {
val commentA = CommentFactory.comment()
val commentB = CommentFactory.comment().toBuilder().id(2).build()
assertFalse(commentA == commentB)
}
fun testEquals_whenSecondCommentDifferentUser_returnFalse() {
val commentA = CommentFactory.comment()
val commentB = CommentFactory.comment().toBuilder().author(
UserFactory.user()
.toBuilder()
.id(2)
.build()
).build()
assertFalse(commentA == commentB)
}
fun testEquals_whenSecondCommentDifferentParentId_returnFalse() {
val commentA = CommentFactory.comment()
val commentB = CommentFactory.comment()
.toBuilder()
.parentId(2)
.build()
assertFalse(commentA == commentB)
}
fun testEquals_whenCommentEquals_returnTrue() {
val commentA = CommentFactory.comment()
val commentB = CommentFactory.comment()
assertTrue(commentA == commentB)
}
}
| apache-2.0 | 0104903418bb4ec687c83fe55908f786 | 28.113636 | 73 | 0.647151 | 4.675182 | false | true | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/viewmodels/NotificationsViewModel.kt | 1 | 10542 | package com.kickstarter.viewmodels
import androidx.annotation.NonNull
import com.kickstarter.libs.ActivityViewModel
import com.kickstarter.libs.Environment
import com.kickstarter.libs.rx.transformers.Transformers.errors
import com.kickstarter.libs.rx.transformers.Transformers.neverError
import com.kickstarter.libs.rx.transformers.Transformers.takeWhen
import com.kickstarter.libs.rx.transformers.Transformers.values
import com.kickstarter.libs.utils.ListUtils
import com.kickstarter.libs.utils.ObjectUtils
import com.kickstarter.libs.utils.extensions.isZero
import com.kickstarter.models.User
import com.kickstarter.ui.activities.NotificationsActivity
import rx.Notification
import rx.Observable
import rx.subjects.BehaviorSubject
import rx.subjects.PublishSubject
interface NotificationsViewModel {
interface Inputs {
/** Call when the notify mobile of pledge activity toggle changes. */
fun notifyMobileOfBackings(checked: Boolean)
/** Call when the notify mobile of new comments toggle changes. */
fun notifyMobileOfComments(checked: Boolean)
/** Call when the notify mobile of new comments toggle changes. */
fun notifyMobileOfCreatorEdu(checked: Boolean)
/** Call when the notify mobile of new followers toggle changes. */
fun notifyMobileOfFollower(checked: Boolean)
/** Call when the notify mobile of friend backs a project toggle changes. */
fun notifyMobileOfFriendActivity(checked: Boolean)
/** Call when the notify mobile of messages toggle changes. */
fun notifyMobileOfMessages(checked: Boolean)
/** Call when the notify mobile of project updates toggle changes. */
fun notifyMobileOfPostLikes(checked: Boolean)
/** Call when the notify mobile of project updates toggle changes. */
fun notifyMobileOfUpdates(checked: Boolean)
/** Call when the notify mobile of marketing updates toggle changes. */
fun notifyMobileOfMarketingUpdate(checked: Boolean)
/** Call when the notify of pledge activity toggle changes. */
fun notifyOfBackings(checked: Boolean)
/** Call when the notify of new comments toggle changes. */
fun notifyOfComments(checked: Boolean)
/** Call when the notify of new comment reply toggle changes. */
fun notifyOfCommentReplies(checked: Boolean)
/** Call when the email frequency spinner selection changes. */
fun notifyOfCreatorDigest(checked: Boolean)
/** Call when the notify of creator tips toggle changes. */
fun notifyOfCreatorEdu(checked: Boolean)
/** Call when the notify of new followers toggle changes. */
fun notifyOfFollower(checked: Boolean)
/** Call when the notify of friend backs a project toggle changes. */
fun notifyOfFriendActivity(checked: Boolean)
/** Call when the notify of messages toggle changes. */
fun notifyOfMessages(checked: Boolean)
/** Call when the notify of project updates toggle changes. */
fun notifyOfUpdates(checked: Boolean)
}
interface Outputs {
/** Emission determines whether we should be hiding backings frequency emails settings. */
fun creatorDigestFrequencyIsGone(): Observable<Boolean>
/** Emission determines whether we should be hiding creator notification settings. */
fun creatorNotificationsAreGone(): Observable<Boolean>
/** Emits user containing settings state. */
fun user(): Observable<User>
}
interface Errors {
fun unableToSavePreferenceError(): Observable<String>
}
class ViewModel(@NonNull val environment: Environment) : ActivityViewModel<NotificationsActivity>(environment), Inputs, Outputs, Errors {
private val userInput = PublishSubject.create<User>()
private val creatorDigestFrequencyIsGone: Observable<Boolean>
private val creatorNotificationsAreGone: Observable<Boolean>
private val userOutput = BehaviorSubject.create<User>()
private val updateSuccess = PublishSubject.create<Void>()
private val unableToSavePreferenceError = PublishSubject.create<Throwable>()
val inputs: Inputs = this
val outputs: Outputs = this
val errors: Errors = this
private val client = requireNotNull(environment.apiClient())
private val currentUser = requireNotNull(environment.currentUser())
init {
this.client.fetchCurrentUser()
.retry(2)
.compose(neverError())
.compose(bindToLifecycle())
.subscribe { this.currentUser.refresh(it) }
val currentUser = this.currentUser.observable()
.filter { ObjectUtils.isNotNull(it) }
currentUser
.take(1)
.compose(bindToLifecycle())
.subscribe { this.userOutput.onNext(it) }
this.creatorDigestFrequencyIsGone = Observable.merge(currentUser, this.userInput)
.compose(bindToLifecycle())
.map { it.notifyOfBackings() != true }
.distinctUntilChanged()
this.creatorNotificationsAreGone = currentUser
.compose(bindToLifecycle())
.map { (it.createdProjectsCount() ?: 0).isZero() }
.distinctUntilChanged()
val updateSettingsNotification = this.userInput
.concatMap { this.updateSettings(it) }
updateSettingsNotification
.compose(values())
.compose(bindToLifecycle())
.subscribe { this.success(it) }
updateSettingsNotification
.compose(errors())
.compose(bindToLifecycle())
.subscribe(this.unableToSavePreferenceError)
this.userInput
.compose(bindToLifecycle())
.subscribe(this.userOutput)
this.userOutput
.window(2, 1)
.flatMap<List<User>> { it.toList() }
.map<User> { ListUtils.first(it) }
.compose<User>(takeWhen<User, Throwable>(this.unableToSavePreferenceError))
.compose(bindToLifecycle())
.subscribe(this.userOutput)
}
override fun notifyMobileOfBackings(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfBackings(checked).build())
}
override fun notifyMobileOfComments(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfComments(checked).build())
}
override fun notifyMobileOfCreatorEdu(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfCreatorEdu(checked).build())
}
override fun notifyMobileOfFollower(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfFollower(checked).build())
}
override fun notifyMobileOfFriendActivity(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfFriendActivity(checked).build())
}
override fun notifyMobileOfMessages(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfMessages(checked).build())
}
override fun notifyMobileOfPostLikes(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfPostLikes(checked).build())
}
override fun notifyMobileOfUpdates(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfUpdates(checked).build())
}
override fun notifyOfBackings(checked: Boolean) {
val userBuilder = this.userOutput.value.toBuilder().notifyOfBackings(checked)
if (!checked) {
userBuilder.notifyOfCreatorDigest(false)
}
this.userInput.onNext(userBuilder.build())
}
override fun notifyMobileOfMarketingUpdate(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyMobileOfMarketingUpdate(checked).build())
}
override fun notifyOfComments(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyOfComments(checked).build())
}
override fun notifyOfCommentReplies(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyOfCommentReplies(checked).build())
}
override fun notifyOfCreatorDigest(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyOfCreatorDigest(checked).build())
}
override fun notifyOfCreatorEdu(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyOfCreatorEdu(checked).build())
}
override fun notifyOfFollower(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyOfFollower(checked).build())
}
override fun notifyOfFriendActivity(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyOfFriendActivity(checked).build())
}
override fun notifyOfMessages(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyOfMessages(checked).build())
}
override fun notifyOfUpdates(checked: Boolean) {
this.userInput.onNext(this.userOutput.value.toBuilder().notifyOfUpdates(checked).build())
}
override fun creatorDigestFrequencyIsGone() = this.creatorDigestFrequencyIsGone
override fun creatorNotificationsAreGone() = this.creatorNotificationsAreGone
override fun user(): Observable<User> = this.userOutput
override fun unableToSavePreferenceError(): Observable<String> = this.unableToSavePreferenceError
.takeUntil(this.updateSuccess)
.map { _ -> null }
private fun success(user: User) {
this.currentUser.refresh(user)
this.updateSuccess.onNext(null)
}
private fun updateSettings(user: User): Observable<Notification<User>> {
return this.client.updateUserSettings(user)
.materialize()
.share()
}
}
}
| apache-2.0 | 109d1c8f6db748bd21a88907de11123d | 39.546154 | 141 | 0.667331 | 5.095215 | false | false | false | false |
siosio/intellij-community | platform/xdebugger-impl/src/com/intellij/xdebugger/impl/runToolbar/RunToolbarXDebuggerAction.kt | 1 | 1975 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.xdebugger.impl.runToolbar
import com.intellij.execution.runToolbar.RTBarAction
import com.intellij.execution.runToolbar.RunToolbarSlotManager
import com.intellij.execution.runToolbar.isItRunToolbarMainSlot
import com.intellij.execution.runToolbar.isOpened
import com.intellij.icons.AllIcons
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.xdebugger.impl.DebuggerSupport
import com.intellij.xdebugger.impl.actions.DebuggerActionHandler
import com.intellij.xdebugger.impl.actions.XDebuggerActionBase
import com.intellij.xdebugger.impl.actions.handlers.RunToolbarPauseActionHandler
import com.intellij.xdebugger.impl.actions.handlers.RunToolbarResumeActionHandler
abstract class RunToolbarXDebuggerAction : XDebuggerActionBase(true), RTBarAction {
override fun getRightSideType(): RTBarAction.Type = RTBarAction.Type.RIGHT_FLEXIBLE
override fun update(event: AnActionEvent) {
super.update(event)
event.presentation.isEnabledAndVisible = event.presentation.isEnabled && event.presentation.isVisible && if(event.isItRunToolbarMainSlot() && !event.isOpened()) event.project?.let {
RunToolbarSlotManager.getInstance(it).getState().isSingleMain()
} ?: false else true
}
}
class RunToolbarPauseAction : RunToolbarXDebuggerAction() {
private val handler = RunToolbarPauseActionHandler()
override fun getHandler(debuggerSupport: DebuggerSupport): DebuggerActionHandler {
return handler
}
init {
templatePresentation.icon = AllIcons.Actions.Pause
}
}
class RunToolbarResumeAction : RunToolbarXDebuggerAction() {
private val handler = RunToolbarResumeActionHandler()
override fun getHandler(debuggerSupport: DebuggerSupport): DebuggerActionHandler {
return handler
}
init {
templatePresentation.icon = AllIcons.Actions.Resume
}
}
| apache-2.0 | 1c32496aafb7bca7f98ec3c2d8f00747 | 39.306122 | 185 | 0.813165 | 4.759036 | false | false | false | false |
HenningLanghorst/fancy-kotlin-stuff | src/main/kotlin/de/henninglanghorst/kotlinstuff/db/Database.kt | 1 | 1512 | package de.henninglanghorst.kotlinstuff.db
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.ResultSet
import java.time.LocalDate
import javax.sql.DataSource
typealias UUID = String
class DatabaseContext(private val dataSource: DataSource) {
fun <T> query(sql: SQL, mapResultSet: (ResultSet) -> T): List<T> {
dataSource.connection.use {
sql.prepareStatement(it).use {
it.executeQuery().use { resultSet ->
val result = mutableListOf<T>()
while (resultSet.next()) {
result.add(mapResultSet(resultSet));
}
return result
}
}
}
}
fun <T> doInDatabase(func: DatabaseContext.() -> T): T = this.func()
}
data class SQL(val sql: String, val params: List<Any> = emptyList()) {
fun prepareStatement(connection: Connection): PreparedStatement {
return connection.prepareStatement(sql).apply {
for (i in 1..params.size) {
setObject(i, params[i - 1])
}
}
}
operator fun plus(other: SQL): SQL = SQL(this.sql + " " + other.sql, this.params + other.params)
}
infix fun String.withParams(params: List<Any>) = SQL(this, params)
infix fun String.withParam(param: Any) = SQL(this, listOf(param))
fun String.noParam() = SQL(this)
data class Person(val uuid: UUID, val firstName: String, val lastName: String, val birthday: LocalDate?)
| apache-2.0 | c6803a8159d0a575d19fabb3a8e4f0a1 | 27.528302 | 104 | 0.608466 | 4.086486 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/RedundantModalityModifierInspection.kt | 1 | 1578 | // 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.inspections
import com.intellij.codeInspection.*
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.implicitModality
import org.jetbrains.kotlin.idea.quickfix.RemoveModifierFix
import org.jetbrains.kotlin.psi.declarationVisitor
import org.jetbrains.kotlin.psi.psiUtil.modalityModifier
class RedundantModalityModifierInspection : AbstractKotlinInspection(), CleanupLocalInspectionTool {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
return declarationVisitor { declaration ->
val modalityModifier = declaration.modalityModifier() ?: return@declarationVisitor
val modalityModifierType = modalityModifier.node.elementType
val implicitModality = declaration.implicitModality()
if (modalityModifierType != implicitModality) return@declarationVisitor
holder.registerProblem(
modalityModifier,
KotlinBundle.message("redundant.modality.modifier"),
ProblemHighlightType.LIKE_UNUSED_SYMBOL,
IntentionWrapper(
RemoveModifierFix(declaration, implicitModality, isRedundant = true),
declaration.containingFile
)
)
}
}
}
| apache-2.0 | fa65f1d6a4760e4e6ac027bec66b1455 | 46.818182 | 158 | 0.729404 | 5.676259 | false | false | false | false |
rustamgaifullin/MP | app/src/main/kotlin/io/rg/mp/drive/BalanceService.kt | 1 | 1303 | package io.rg.mp.drive
import com.google.api.services.sheets.v4.Sheets
import io.reactivex.Single
import io.rg.mp.drive.data.Balance
import io.rg.mp.drive.extension.extractValue
import io.rg.mp.utils.onErrorIfNotDisposed
class BalanceService(private val googleSheetService: Sheets) {
companion object {
private const val CURRENT_BALANCE = "I15"
private const val PLANNED_EXPENSES = "C21"
private const val ACTUAL_EXPENSES = "C22"
}
fun retrieve(spreadsheetId: String): Single<Balance> {
return Single.create { emitter ->
onErrorIfNotDisposed(emitter) {
val response = googleSheetService
.spreadsheets()
.values()
.batchGet(spreadsheetId)
.setFields("valueRanges.values")
.setRanges(listOf(CURRENT_BALANCE, PLANNED_EXPENSES, ACTUAL_EXPENSES))
.execute()
val currentBalance = response.extractValue(0, 0, 0)
val plannedExpenses = response.extractValue(1, 0, 0)
val actualExpenses = response.extractValue(2, 0, 0)
emitter.onSuccess(Balance(currentBalance, actualExpenses, plannedExpenses))
}
}
}
} | mit | c98199f6fed8c593b5e8800d517cd122 | 35.222222 | 94 | 0.606293 | 4.372483 | false | false | false | false |
SimpleMobileTools/Simple-Calendar | app/src/main/kotlin/com/simplemobiletools/calendar/pro/extensions/Event.kt | 1 | 1054 | package com.simplemobiletools.calendar.pro.extensions
import com.simplemobiletools.calendar.pro.helpers.Formatter
import com.simplemobiletools.calendar.pro.helpers.TWELVE_HOURS
import com.simplemobiletools.calendar.pro.models.Event
import org.joda.time.DateTimeZone
// shifts all-day events to local timezone such that the event starts and ends on the same time as in UTC
fun Event.toLocalAllDayEvent() {
require(this.getIsAllDay()) { "Must be an all day event!" }
timeZone = DateTimeZone.getDefault().id
startTS = Formatter.getShiftedLocalTS(startTS)
endTS = Formatter.getShiftedLocalTS(endTS)
if (endTS > startTS) {
endTS -= TWELVE_HOURS
}
}
// shifts all-day events to UTC such that the event starts on the same time in UTC too
fun Event.toUtcAllDayEvent() {
require(getIsAllDay()) { "Must be an all day event!" }
if (endTS >= startTS) {
endTS += TWELVE_HOURS
}
timeZone = DateTimeZone.UTC.id
startTS = Formatter.getShiftedUtcTS(startTS)
endTS = Formatter.getShiftedUtcTS(endTS)
}
| gpl-3.0 | e3d99137f31521bb621d16ec92fb4e3e | 33 | 105 | 0.734345 | 3.711268 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ImplementAbstractMemberIntention.kt | 1 | 13008 | // 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.intentions
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.generation.OverrideImplementUtil
import com.intellij.codeInsight.intention.impl.BaseIntentionAction
import com.intellij.ide.util.PsiClassListCellRenderer
import com.intellij.ide.util.PsiClassRenderingInfo
import com.intellij.ide.util.PsiElementListCellRenderer
import com.intellij.java.JavaBundle
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.ui.popup.IPopupChooserBuilder
import com.intellij.openapi.ui.popup.PopupChooserBuilder
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.ui.components.JBList
import com.intellij.util.IncorrectOperationException
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.toLightMethods
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaClassDescriptor
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.core.overrideImplement.BodyType
import org.jetbrains.kotlin.idea.core.overrideImplement.GenerateMembersHandler
import org.jetbrains.kotlin.idea.core.overrideImplement.OverrideMemberChooserObject
import org.jetbrains.kotlin.idea.core.util.runSynchronouslyWithProgress
import org.jetbrains.kotlin.idea.refactoring.isAbstract
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.util.application.executeCommand
import org.jetbrains.kotlin.idea.util.application.isUnitTestMode
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.idea.util.getTypeSubstitution
import org.jetbrains.kotlin.idea.util.substitute
import org.jetbrains.kotlin.load.java.descriptors.JavaClassDescriptor
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.util.findCallableMemberBySignature
import javax.swing.ListSelectionModel
abstract class ImplementAbstractMemberIntentionBase : SelfTargetingRangeIntention<KtNamedDeclaration>(
KtNamedDeclaration::class.java,
KotlinBundle.lazyMessage("implement.abstract.member")
) {
companion object {
private val LOG = Logger.getInstance("#${ImplementAbstractMemberIntentionBase::class.java.canonicalName}")
}
protected fun findExistingImplementation(
subClass: ClassDescriptor,
superMember: CallableMemberDescriptor
): CallableMemberDescriptor? {
val superClass = superMember.containingDeclaration as? ClassDescriptor ?: return null
val substitution = getTypeSubstitution(superClass.defaultType, subClass.defaultType).orEmpty()
val signatureInSubClass = superMember.substitute(substitution) as? CallableMemberDescriptor ?: return null
val subMember = subClass.findCallableMemberBySignature(signatureInSubClass)
return if (subMember?.kind?.isReal == true) subMember else null
}
protected abstract fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean
private fun findClassesToProcess(member: KtNamedDeclaration): Sequence<PsiElement> {
val baseClass = member.containingClassOrObject as? KtClass ?: return emptySequence()
val memberDescriptor = member.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return emptySequence()
fun acceptSubClass(subClass: PsiElement): Boolean {
if (!BaseIntentionAction.canModify(subClass)) return false
val classDescriptor = when (subClass) {
is KtLightClass -> subClass.kotlinOrigin?.resolveToDescriptorIfAny()
is KtEnumEntry -> subClass.resolveToDescriptorIfAny()
is PsiClass -> subClass.getJavaClassDescriptor()
else -> null
} ?: return false
return acceptSubClass(classDescriptor, memberDescriptor)
}
if (baseClass.isEnum()) {
return baseClass.declarations
.asSequence()
.filterIsInstance<KtEnumEntry>()
.filter(::acceptSubClass)
}
return HierarchySearchRequest(baseClass, baseClass.useScope, false)
.searchInheritors()
.asSequence()
.filter(::acceptSubClass)
}
protected abstract fun computeText(element: KtNamedDeclaration): (() -> String)?
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (!element.isAbstract()) return null
setTextGetter(computeText(element) ?: return null)
if (!findClassesToProcess(element).any()) return null
return element.nameIdentifier?.textRange
}
protected abstract val preferConstructorParameters: Boolean
private fun implementInKotlinClass(editor: Editor?, member: KtNamedDeclaration, targetClass: KtClassOrObject) {
val subClassDescriptor = targetClass.resolveToDescriptorIfAny() ?: return
val superMemberDescriptor = member.resolveToDescriptorIfAny() as? CallableMemberDescriptor ?: return
val superClassDescriptor = superMemberDescriptor.containingDeclaration as? ClassDescriptor ?: return
val substitution = getTypeSubstitution(superClassDescriptor.defaultType, subClassDescriptor.defaultType).orEmpty()
val descriptorToImplement = superMemberDescriptor.substitute(substitution) as CallableMemberDescriptor
val chooserObject = OverrideMemberChooserObject.create(
member.project,
descriptorToImplement,
descriptorToImplement,
BodyType.FromTemplate,
preferConstructorParameters
)
GenerateMembersHandler.generateMembers(editor, targetClass, listOf(chooserObject), false)
}
private fun implementInJavaClass(member: KtNamedDeclaration, targetClass: PsiClass) {
member.toLightMethods().forEach { OverrideImplementUtil.overrideOrImplement(targetClass, it) }
}
private fun implementInClass(member: KtNamedDeclaration, targetClasses: List<PsiElement>) {
val project = member.project
project.executeCommand<Unit>(JavaBundle.message("intention.implement.abstract.method.command.name")) {
if (!FileModificationService.getInstance().preparePsiElementsForWrite(targetClasses)) return@executeCommand
runWriteAction<Unit> {
for (targetClass in targetClasses) {
try {
val descriptor = OpenFileDescriptor(project, targetClass.containingFile.virtualFile)
val targetEditor = FileEditorManager.getInstance(project).openTextEditor(descriptor, true)!!
when (targetClass) {
is KtLightClass -> targetClass.kotlinOrigin?.let { implementInKotlinClass(targetEditor, member, it) }
is KtEnumEntry -> implementInKotlinClass(targetEditor, member, targetClass)
is PsiClass -> implementInJavaClass(member, targetClass)
}
} catch (e: IncorrectOperationException) {
LOG.error(e)
}
}
}
}
}
private class ClassRenderer : PsiElementListCellRenderer<PsiElement>() {
private val psiClassRenderer = PsiClassListCellRenderer()
override fun getComparator(): Comparator<PsiElement> {
val baseComparator = psiClassRenderer.comparator
return Comparator { o1, o2 ->
when {
o1 is KtEnumEntry && o2 is KtEnumEntry -> o1.name!!.compareTo(o2.name!!)
o1 is KtEnumEntry -> -1
o2 is KtEnumEntry -> 1
o1 is PsiClass && o2 is PsiClass -> baseComparator.compare(o1, o2)
else -> 0
}
}
}
override fun getElementText(element: PsiElement?): String? {
return when (element) {
is KtEnumEntry -> element.name
is PsiClass -> psiClassRenderer.getElementText(element)
else -> null
}
}
override fun getContainerText(element: PsiElement?, name: String?): String? {
return when (element) {
is KtEnumEntry -> element.containingClassOrObject?.fqName?.asString()
is PsiClass -> PsiClassRenderingInfo.getContainerTextStatic(element)
else -> null
}
}
}
override fun startInWriteAction(): Boolean = false
override fun checkFile(file: PsiFile): Boolean {
return true
}
override fun preparePsiElementForWriteIfNeeded(target: KtNamedDeclaration): Boolean {
return true
}
override fun applyTo(element: KtNamedDeclaration, editor: Editor?) {
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val project = element.project
val classesToProcess = project.runSynchronouslyWithProgress(
JavaBundle.message("intention.implement.abstract.method.searching.for.descendants.progress"),
true
) { runReadAction { findClassesToProcess(element).toList() } } ?: return
if (classesToProcess.isEmpty()) return
classesToProcess.singleOrNull()?.let { return implementInClass(element, listOf(it)) }
val renderer = ClassRenderer()
val sortedClasses = classesToProcess.sortedWith(renderer.comparator)
if (isUnitTestMode()) return implementInClass(element, sortedClasses)
val list = JBList(sortedClasses).apply {
selectionMode = ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
cellRenderer = renderer
}
val builder = PopupChooserBuilder<PsiElement>(list)
renderer.installSpeedSearch(builder as IPopupChooserBuilder<*>)
builder
.setTitle(CodeInsightBundle.message("intention.implement.abstract.method.class.chooser.title"))
.setItemChoosenCallback {
val index = list.selectedIndex
if (index < 0) return@setItemChoosenCallback
@Suppress("UNCHECKED_CAST")
implementInClass(element, list.selectedValues.toList() as List<KtClassOrObject>)
}
.createPopup()
.showInBestPositionFor(editor)
}
}
class ImplementAbstractMemberIntention : ImplementAbstractMemberIntentionBase() {
override fun computeText(element: KtNamedDeclaration): (() -> String)? = when (element) {
is KtProperty -> KotlinBundle.lazyMessage("implement.abstract.property")
is KtNamedFunction -> KotlinBundle.lazyMessage("implement.abstract.function")
else -> null
}
override fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean {
return subClassDescriptor.kind != ClassKind.INTERFACE && findExistingImplementation(subClassDescriptor, memberDescriptor) == null
}
override val preferConstructorParameters: Boolean
get() = false
}
class ImplementAbstractMemberAsConstructorParameterIntention : ImplementAbstractMemberIntentionBase() {
override fun computeText(element: KtNamedDeclaration): (() -> String)? {
if (element !is KtProperty) return null
return KotlinBundle.lazyMessage("implement.as.constructor.parameter")
}
override fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean {
val kind = subClassDescriptor.kind
return (kind == ClassKind.CLASS || kind == ClassKind.ENUM_CLASS)
&& subClassDescriptor !is JavaClassDescriptor
&& findExistingImplementation(subClassDescriptor, memberDescriptor) == null
}
override val preferConstructorParameters: Boolean
get() = true
override fun applicabilityRange(element: KtNamedDeclaration): TextRange? {
if (element !is KtProperty) return null
return super.applicabilityRange(element)
}
} | apache-2.0 | 21e2ce786008beb338d58f8d6bb07b92 | 47.00369 | 137 | 0.717328 | 5.765957 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/EditorTabPreview.kt | 2 | 9290 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.vcs.changes
import com.intellij.diff.DiffDialogHints
import com.intellij.diff.chains.DiffRequestChain
import com.intellij.diff.chains.DiffRequestProducer
import com.intellij.diff.chains.SimpleDiffRequestChain
import com.intellij.diff.editor.DiffEditorEscapeAction
import com.intellij.diff.editor.DiffEditorTabFilesManager
import com.intellij.diff.editor.DiffVirtualFileBase
import com.intellij.diff.impl.DiffRequestProcessor
import com.intellij.diff.tools.external.ExternalDiffTool
import com.intellij.diff.util.DiffUserDataKeysEx
import com.intellij.openapi.Disposable
import com.intellij.openapi.ListSelection
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.DumbService
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Disposer.isDisposed
import com.intellij.openapi.vcs.changes.ui.ChangesTree
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.ToolWindowManager
import com.intellij.util.EditSourceOnDoubleClickHandler.isToggleEvent
import com.intellij.util.IJSwingUtilities
import com.intellij.util.Processor
import com.intellij.util.ui.update.DisposableUpdate
import com.intellij.util.ui.update.MergingUpdateQueue
import org.jetbrains.annotations.Nls
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
import javax.swing.JComponent
abstract class EditorTabPreview(private val diffProcessor: DiffRequestProcessor) :
EditorTabPreviewBase(diffProcessor.project!!, diffProcessor) {
override val previewFile: VirtualFile = EditorTabDiffPreviewVirtualFile(diffProcessor, ::getCurrentName)
override val updatePreviewProcessor: DiffPreviewUpdateProcessor get() = diffProcessor as DiffPreviewUpdateProcessor
}
abstract class EditorTabPreviewBase(protected val project: Project,
protected val parentDisposable: Disposable) : DiffPreview {
private val updatePreviewQueue =
MergingUpdateQueue("updatePreviewQueue", 100, true, null, parentDisposable).apply {
setRestartTimerOnAdd(true)
}
protected abstract val updatePreviewProcessor: DiffPreviewUpdateProcessor
protected abstract val previewFile: VirtualFile
var escapeHandler: Runnable? = null
fun installListeners(tree: ChangesTree, isOpenEditorDiffPreviewWithSingleClick: Boolean) {
installDoubleClickHandler(tree)
installEnterKeyHandler(tree)
if (isOpenEditorDiffPreviewWithSingleClick) {
//do not open file aggressively on start up, do it later
DumbService.getInstance(project).smartInvokeLater {
if (isDisposed(updatePreviewQueue)) return@smartInvokeLater
installSelectionHandler(tree, true)
}
}
else {
installSelectionHandler(tree, false)
}
}
fun installSelectionHandler(tree: ChangesTree, isOpenEditorDiffPreviewWithSingleClick: Boolean) {
installSelectionChangedHandler(tree) {
if (isOpenEditorDiffPreviewWithSingleClick) {
if (!openPreview(false)) closePreview() // auto-close editor tab if nothing to preview
}
else {
updatePreview(false)
}
}
}
fun installNextDiffActionOn(component: JComponent) {
DumbAwareAction.create { openPreview(true) }.apply {
copyShortcutFrom(ActionManager.getInstance().getAction(IdeActions.ACTION_NEXT_DIFF))
registerCustomShortcutSet(component, parentDisposable)
}
}
protected open fun isPreviewOnDoubleClickAllowed(): Boolean = true
protected open fun isPreviewOnEnterAllowed(): Boolean = true
private fun installDoubleClickHandler(tree: ChangesTree) {
val oldDoubleClickHandler = tree.doubleClickHandler
val newDoubleClickHandler = Processor<MouseEvent> { e ->
if (isToggleEvent(tree, e)) return@Processor false
isPreviewOnDoubleClickAllowed() && performDiffAction() || oldDoubleClickHandler?.process(e) == true
}
tree.doubleClickHandler = newDoubleClickHandler
Disposer.register(parentDisposable, Disposable { tree.doubleClickHandler = oldDoubleClickHandler })
}
private fun installEnterKeyHandler(tree: ChangesTree) {
val oldEnterKeyHandler = tree.enterKeyHandler
val newEnterKeyHandler = Processor<KeyEvent> { e ->
isPreviewOnEnterAllowed() && performDiffAction() || oldEnterKeyHandler?.process(e) == true
}
tree.enterKeyHandler = newEnterKeyHandler
Disposer.register(parentDisposable, Disposable { tree.enterKeyHandler = oldEnterKeyHandler })
}
private fun installSelectionChangedHandler(tree: ChangesTree, handler: () -> Unit) =
tree.addSelectionListener(
Runnable {
updatePreviewQueue.queue(DisposableUpdate.createDisposable(updatePreviewQueue, this) {
if (!skipPreviewUpdate()) handler()
})
},
updatePreviewQueue
)
protected abstract fun getCurrentName(): String?
protected abstract fun hasContent(): Boolean
protected open fun skipPreviewUpdate(): Boolean = ToolWindowManager.getInstance(project).isEditorComponentActive
override fun updatePreview(fromModelRefresh: Boolean) {
if (isPreviewOpen()) {
updatePreviewProcessor.refresh(false)
}
else {
updatePreviewProcessor.clear()
}
}
protected fun isPreviewOpen(): Boolean = FileEditorManager.getInstance(project).isFileOpenWithRemotes(previewFile)
override fun closePreview() {
FileEditorManager.getInstance(project).closeFile(previewFile)
updatePreviewProcessor.clear()
}
override fun openPreview(requestFocus: Boolean): Boolean {
if (!ensureHasContent()) return false
return openPreviewEditor(requestFocus)
}
private fun ensureHasContent(): Boolean {
updatePreviewProcessor.refresh(false)
return hasContent()
}
private fun openPreviewEditor(requestFocus: Boolean): Boolean {
escapeHandler?.let { handler -> registerEscapeHandler(previewFile, handler) }
openPreview(project, previewFile, requestFocus)
return true
}
override fun performDiffAction(): Boolean {
if (!ensureHasContent()) return false
if (ExternalDiffTool.isEnabled()) {
val processorWithProducers = updatePreviewProcessor as? DiffRequestProcessorWithProducers
if (processorWithProducers != null ) {
var diffProducers = processorWithProducers.collectDiffProducers(true)
if (diffProducers != null && diffProducers.isEmpty) {
diffProducers = processorWithProducers.collectDiffProducers(false)?.list?.firstOrNull()
?.let { ListSelection.createSingleton(it) }
}
if (showExternalToolIfNeeded(project, diffProducers)) {
return true
}
}
}
return openPreviewEditor(true)
}
internal class EditorTabDiffPreviewVirtualFile(diffProcessor: DiffRequestProcessor, tabNameProvider: () -> String?)
: PreviewDiffVirtualFile(EditorTabDiffPreviewProvider(diffProcessor, tabNameProvider)) {
init {
// EditorTabDiffPreviewProvider does not create new processor, so general assumptions of DiffVirtualFile are violated
diffProcessor.putContextUserData(DiffUserDataKeysEx.DIFF_IN_EDITOR_WITH_EXPLICIT_DISPOSABLE, true)
}
}
companion object {
fun openPreview(project: Project, file: VirtualFile, focusEditor: Boolean): Array<out FileEditor> {
return DiffEditorTabFilesManager.getInstance(project).showDiffFile(file, focusEditor)
}
fun registerEscapeHandler(file: VirtualFile, handler: Runnable) {
file.putUserData(DiffVirtualFileBase.ESCAPE_HANDLER, EditorTabPreviewEscapeAction(handler))
}
fun showExternalToolIfNeeded(project: Project?, diffProducers: ListSelection<out DiffRequestProducer>?): Boolean {
if (diffProducers == null || diffProducers.isEmpty) return false
val producers = diffProducers.explicitSelection
return ExternalDiffTool.showIfNeeded(project, producers, DiffDialogHints.DEFAULT)
}
}
}
internal class EditorTabPreviewEscapeAction(private val escapeHandler: Runnable) : DumbAwareAction(), DiffEditorEscapeAction {
override fun actionPerformed(e: AnActionEvent) = escapeHandler.run()
}
private class EditorTabDiffPreviewProvider(
private val diffProcessor: DiffRequestProcessor,
private val tabNameProvider: () -> String?
) : ChainBackedDiffPreviewProvider {
override fun createDiffRequestProcessor(): DiffRequestProcessor {
IJSwingUtilities.updateComponentTreeUI(diffProcessor.component)
return diffProcessor
}
override fun getOwner(): Any = this
override fun getEditorTabName(processor: DiffRequestProcessor?): @Nls String = tabNameProvider().orEmpty()
override fun createDiffRequestChain(): DiffRequestChain? {
if (diffProcessor is DiffRequestProcessorWithProducers) {
val producers = diffProcessor.collectDiffProducers(false) ?: return null
return SimpleDiffRequestChain.fromProducers(producers)
}
return null
}
}
| apache-2.0 | 587d91a25fa905c64a8af9a6ce217736 | 38.531915 | 126 | 0.773412 | 4.965259 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/core/src/org/jetbrains/kotlin/idea/debugger/breakpoints/KotlinFieldBreakpoint.kt | 1 | 15067 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger.breakpoints
import com.intellij.debugger.JavaDebuggerBundle
import com.intellij.debugger.DebuggerManagerEx
import com.intellij.debugger.SourcePosition
import com.intellij.debugger.engine.DebugProcessImpl
import com.intellij.debugger.engine.evaluation.EvaluationContextImpl
import com.intellij.debugger.impl.PositionUtil
import com.intellij.debugger.requests.Requestor
import com.intellij.debugger.ui.breakpoints.BreakpointCategory
import com.intellij.debugger.ui.breakpoints.BreakpointWithHighlighter
import com.intellij.debugger.ui.breakpoints.FieldBreakpoint
import com.intellij.icons.AllIcons
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.xdebugger.breakpoints.XBreakpoint
import com.sun.jdi.AbsentInformationException
import com.sun.jdi.Method
import com.sun.jdi.ReferenceType
import com.sun.jdi.event.*
import com.sun.jdi.request.EventRequest
import com.sun.jdi.request.MethodEntryRequest
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.descriptors.PropertyDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.fileClasses.JvmFileClassUtil
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.debugger.safeAllLineLocations
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtParameter
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.resolve.BindingContext
import javax.swing.Icon
class KotlinFieldBreakpoint(
project: Project,
breakpoint: XBreakpoint<KotlinPropertyBreakpointProperties>
) : BreakpointWithHighlighter<KotlinPropertyBreakpointProperties>(project, breakpoint) {
companion object {
private val LOG = Logger.getInstance("#org.jetbrains.kotlin.idea.debugger.breakpoints.KotlinFieldBreakpoint")
private val CATEGORY: Key<FieldBreakpoint> = BreakpointCategory.lookup("field_breakpoints")
}
private enum class BreakpointType {
FIELD,
METHOD
}
private var breakpointType: BreakpointType = BreakpointType.FIELD
override fun isValid(): Boolean {
if (!isPositionValid(xBreakpoint.sourcePosition)) return false
return runReadAction {
val field = getField()
field != null && field.isValid
}
}
private fun getField(): KtCallableDeclaration? {
val sourcePosition = sourcePosition
return getProperty(sourcePosition)
}
private fun getProperty(sourcePosition: SourcePosition?): KtCallableDeclaration? {
val property: KtProperty? = PositionUtil.getPsiElementAt(project, KtProperty::class.java, sourcePosition)
if (property != null) {
return property
}
val parameter: KtParameter? = PositionUtil.getPsiElementAt(project, KtParameter::class.java, sourcePosition)
if (parameter != null) {
return parameter
}
return null
}
override fun reload() {
super.reload()
val property = getProperty(sourcePosition) ?: return
val propertyName = property.name ?: return
setFieldName(propertyName)
if (property is KtProperty && property.isTopLevel) {
properties.myClassName = JvmFileClassUtil.getFileClassInfoNoResolve(property.getContainingKtFile()).fileClassFqName.asString()
} else {
val ktClass: KtClassOrObject? = PsiTreeUtil.getParentOfType(property, KtClassOrObject::class.java)
if (ktClass is KtClassOrObject) {
val fqName = ktClass.fqName
if (fqName != null) {
properties.myClassName = fqName.asString()
}
}
}
isInstanceFiltersEnabled = false
}
override fun createRequestForPreparedClass(debugProcess: DebugProcessImpl?, refType: ReferenceType?) {
if (debugProcess == null || refType == null) return
val property = getProperty(sourcePosition) ?: return
breakpointType = (computeBreakpointType(property) ?: return)
val vm = debugProcess.virtualMachineProxy
try {
if (properties.watchInitialization) {
val sourcePosition = sourcePosition
if (sourcePosition != null) {
debugProcess.positionManager
.locationsOfLine(refType, sourcePosition)
.filter { it.method().isConstructor || it.method().isStaticInitializer }
.forEach {
val request = debugProcess.requestsManager.createBreakpointRequest(this, it)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Breakpoint request added")
}
}
}
}
when (breakpointType) {
BreakpointType.FIELD -> {
val field = refType.fieldByName(getFieldName())
if (field != null) {
val manager = debugProcess.requestsManager
if (properties.watchModification && vm.canWatchFieldModification()) {
val request = manager.createModificationWatchpointRequest(this, field)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Modification request added")
}
}
if (properties.watchAccess && vm.canWatchFieldAccess()) {
val request = manager.createAccessWatchpointRequest(this, field)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Field access request added (field = ${field.name()}; refType = ${refType.name()})")
}
}
}
}
BreakpointType.METHOD -> {
val fieldName = getFieldName()
if (properties.watchAccess) {
val getter = refType.methodsByName(JvmAbi.getterName(fieldName)).firstOrNull()
if (getter != null) {
createMethodBreakpoint(debugProcess, refType, getter)
}
}
if (properties.watchModification) {
val setter = refType.methodsByName(JvmAbi.setterName(fieldName)).firstOrNull()
if (setter != null) {
createMethodBreakpoint(debugProcess, refType, setter)
}
}
}
}
} catch (ex: Exception) {
LOG.debug(ex)
}
}
private fun computeBreakpointType(property: KtCallableDeclaration): BreakpointType? {
return runReadAction {
val bindingContext = property.analyze()
var descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, property)
if (descriptor is ValueParameterDescriptor) {
descriptor = bindingContext.get(BindingContext.VALUE_PARAMETER_AS_PROPERTY, descriptor)
}
if (descriptor is PropertyDescriptor) {
if (bindingContext.get(BindingContext.BACKING_FIELD_REQUIRED, descriptor)!!) {
BreakpointType.FIELD
} else {
BreakpointType.METHOD
}
} else {
null
}
}
}
private fun createMethodBreakpoint(debugProcess: DebugProcessImpl, refType: ReferenceType, accessor: Method) {
val manager = debugProcess.requestsManager
val line = accessor.safeAllLineLocations().firstOrNull()
if (line != null) {
val request = manager.createBreakpointRequest(this, line)
debugProcess.requestsManager.enableRequest(request)
if (LOG.isDebugEnabled) {
LOG.debug("Breakpoint request added")
}
} else {
var entryRequest: MethodEntryRequest? = findRequest(debugProcess, MethodEntryRequest::class.java, this)
if (entryRequest == null) {
entryRequest = manager.createMethodEntryRequest(this)!!
if (LOG.isDebugEnabled) {
LOG.debug("Method entry request added (method = ${accessor.name()}; refType = ${refType.name()})")
}
} else {
entryRequest.disable()
}
entryRequest.addClassFilter(refType)
manager.enableRequest(entryRequest)
}
}
private inline fun <reified T : EventRequest> findRequest(
debugProcess: DebugProcessImpl,
requestClass: Class<T>,
requestor: Requestor
): T? {
val requests = debugProcess.requestsManager.findRequests(requestor)
for (eventRequest in requests) {
if (eventRequest::class.java == requestClass) {
return eventRequest as T
}
}
return null
}
override fun evaluateCondition(context: EvaluationContextImpl, event: LocatableEvent): Boolean {
if (breakpointType == BreakpointType.METHOD && !matchesEvent(event)) {
return false
}
return super.evaluateCondition(context, event)
}
fun matchesEvent(event: LocatableEvent): Boolean {
val method = event.location()?.method()
// TODO check property type
return method != null && method.name() in getMethodsName()
}
private fun getMethodsName(): List<String> {
val fieldName = getFieldName()
return listOf(JvmAbi.getterName(fieldName), JvmAbi.setterName(fieldName))
}
override fun getEventMessage(event: LocatableEvent): String {
val location = event.location()!!
val locationQName = location.declaringType().name() + "." + location.method().name()
val locationFileName = try {
location.sourceName()
} catch (e: AbsentInformationException) {
fileName
} catch (e: InternalError) {
fileName
}
val locationLine = location.lineNumber()
when (event) {
is ModificationWatchpointEvent -> {
val field = event.field()
return JavaDebuggerBundle.message(
"status.static.field.watchpoint.reached.access",
field.declaringType().name(),
field.name(),
locationQName,
locationFileName,
locationLine
)
}
is AccessWatchpointEvent -> {
val field = event.field()
return JavaDebuggerBundle.message(
"status.static.field.watchpoint.reached.access",
field.declaringType().name(),
field.name(),
locationQName,
locationFileName,
locationLine
)
}
is MethodEntryEvent -> {
val method = event.method()
return JavaDebuggerBundle.message(
"status.method.entry.breakpoint.reached",
method.declaringType().name() + "." + method.name() + "()",
locationQName,
locationFileName,
locationLine
)
}
is MethodExitEvent -> {
val method = event.method()
return JavaDebuggerBundle.message(
"status.method.exit.breakpoint.reached",
method.declaringType().name() + "." + method.name() + "()",
locationQName,
locationFileName,
locationLine
)
}
}
return JavaDebuggerBundle.message(
"status.line.breakpoint.reached",
locationQName,
locationFileName,
locationLine
)
}
fun setFieldName(fieldName: String) {
properties.myFieldName = fieldName
}
@TestOnly
fun setWatchAccess(value: Boolean) {
properties.watchAccess = value
}
@TestOnly
fun setWatchModification(value: Boolean) {
properties.watchModification = value
}
@TestOnly
fun setWatchInitialization(value: Boolean) {
properties.watchInitialization = value
}
override fun getDisabledIcon(isMuted: Boolean): Icon {
val master = DebuggerManagerEx.getInstanceEx(myProject).breakpointManager.findMasterBreakpoint(this)
return when {
isMuted && master == null -> AllIcons.Debugger.Db_muted_disabled_field_breakpoint
isMuted && master != null -> AllIcons.Debugger.Db_muted_dep_field_breakpoint
master != null -> AllIcons.Debugger.Db_dep_field_breakpoint
else -> AllIcons.Debugger.Db_disabled_field_breakpoint
}
}
override fun getSetIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
else -> AllIcons.Debugger.Db_field_breakpoint
}
}
override fun getVerifiedIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
else -> AllIcons.Debugger.Db_verified_field_breakpoint
}
}
override fun getVerifiedWarningsIcon(isMuted: Boolean): Icon = AllIcons.Debugger.Db_exception_breakpoint
override fun getCategory() = CATEGORY
override fun getDisplayName(): String {
if (!isValid) {
return JavaDebuggerBundle.message("status.breakpoint.invalid")
}
val className = className
@Suppress("HardCodedStringLiteral")
return if (className != null && className.isNotEmpty()) className + "." + getFieldName() else getFieldName()
}
private fun getFieldName(): String {
val declaration = getField()
return runReadAction { declaration?.name } ?: "unknown"
}
override fun getEvaluationElement(): PsiElement? {
return getField()
}
}
| apache-2.0 | 07e6483b1d47afd3fd66744ceba66423 | 38.65 | 158 | 0.603703 | 5.613636 | false | false | false | false |
GavinPacini/daysuntil | app/src/main/kotlin/com/gpacini/daysuntil/ui/activity/MainActivity.kt | 2 | 6487 | package com.gpacini.daysuntil.ui.activity
import android.graphics.Color
import android.os.Bundle
import android.support.design.widget.CoordinatorLayout
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.support.v7.app.AlertDialog
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.support.v7.widget.helper.ItemTouchHelper
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import butterknife.bindView
import com.gpacini.daysuntil.R
import com.gpacini.daysuntil.data.database.RealmManager
import com.gpacini.daysuntil.data.images.ImageHelper
import com.gpacini.daysuntil.data.model.Event
import com.gpacini.daysuntil.ui.adapter.EventHolder
import rx.Subscription
import rx.subscriptions.CompositeSubscription
import uk.co.ribot.easyadapter.EasyRecyclerAdapter
class MainActivity : AppCompatActivity() {
private val container: CoordinatorLayout by bindView(R.id.container_main)
private val toolbar: Toolbar by bindView(R.id.toolbar)
private val recyclerView: RecyclerView by bindView(R.id.recycler_events)
private val progressBar: ProgressBar by bindView(R.id.progress_indicator)
private val textAddEvent: TextView by bindView(R.id.text_add_event)
private val addEventFAB: FloatingActionButton by bindView(R.id.add_event_fab)
private val subscriptions: CompositeSubscription = CompositeSubscription()
private val realmManager: RealmManager = RealmManager()
private var listSubscription: Subscription? = null
private var easyRecycleAdapter: EasyRecyclerAdapter<Event>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
window.setBackgroundDrawableResource(R.color.background_material_light)
setupRecyclerView()
checkEvents()
}
override fun onDestroy() {
super.onDestroy()
subscriptions.unsubscribe()
listSubscription?.unsubscribe()
realmManager.close()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
val id = item.itemId
if (id == R.id.action_about) {
showInfoDialog()
return true
}
return super.onOptionsItemSelected(item)
}
private fun setupRecyclerView() {
recyclerView.layoutManager = LinearLayoutManager(this)
easyRecycleAdapter = EasyRecyclerAdapter<Event>(this, EventHolder::class.java)
recyclerView.adapter = easyRecycleAdapter
val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder): Boolean {
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
val event = easyRecycleAdapter?.getItem(viewHolder.layoutPosition) ?: return
handleSwipe(event)
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(recyclerView)
addEventFAB.setOnClickListener { startActivity(EventActivity.getNewIntent(this)) }
}
private fun checkEvents() {
subscriptions.add(realmManager.hasEvents()
.subscribe({ hasEvents ->
if (hasEvents) {
textAddEvent.visibility = View.GONE
loadEvents()
} else {
textAddEvent.visibility = View.VISIBLE
}
progressBar.visibility = View.GONE
})
)
}
private fun loadEvents() {
listSubscription?.unsubscribe()
listSubscription = realmManager.loadEvents()
.subscribe({ events ->
Log.d("events", "${events.size}")
easyRecycleAdapter?.items = events
})
}
private fun handleSwipe(event: Event) {
subscriptions.add(realmManager.removeEvent(event.uuid!!)
.subscribe({
if (easyRecycleAdapter?.removeItem(event) ?: false) {
showUndo(event.uuid, event.title, event.timestamp)
}
})
)
}
private fun showUndo(uuid: String?, title: String?, timestamp: Long) {
val snackBar = Snackbar
.make(container, R.string.event_successfully_removed, Snackbar.LENGTH_LONG)
.setAction(R.string.undo, {
realmManager.newEvent(uuid, title, timestamp)
})
.setCallback(object : Snackbar.Callback() {
override fun onDismissed(snackbar: Snackbar?, e: Int) {
if (e != DISMISS_EVENT_ACTION) {
subscriptions.add(ImageHelper.getInstance().deleteImage(uuid)
.subscribe({}))
}
}
})
val snackBarText = snackBar.view.findViewById(android.support.design.R.id.snackbar_text) as TextView
snackBarText.setTextColor(Color.WHITE)
snackBar.show()
}
private fun showInfoDialog() {
val informationStringResource = R.string.information_dialog
val dialog = AlertDialog.Builder(this)
.setTitle(R.string.information_heading)
.setMessage(informationStringResource)
.setPositiveButton(android.R.string.ok, { dialog, num -> dialog.dismiss() })
.show()
makeLinkClickable(dialog)
}
private fun makeLinkClickable(dialog: AlertDialog) {
val messageTextView = dialog.findViewById(android.R.id.message) as? TextView
messageTextView?.movementMethod = LinkMovementMethod.getInstance()
}
} | apache-2.0 | 9339c61b43c18edc746d4e6df23f7379 | 36.287356 | 140 | 0.659319 | 5.024787 | false | false | false | false |
dreampany/framework | frame/src/main/kotlin/com/dreampany/framework/data/source/room/dao/StoreDao.kt | 1 | 4044 | package com.dreampany.framework.data.source.room.dao
import androidx.room.Dao
import androidx.room.Query
import com.dreampany.framework.data.model.Store
import io.reactivex.Maybe
/**
* Created by Hawladar Roman on 3/6/18.
* Dreampany Ltd
* [email protected]
*/
@Dao
interface StoreDao : BaseDao<Store> {
@get:Query("select count(*) from store")
val count: Int
@get:Query("select count(*) from store")
val countRx: Maybe<Int>
@get:Query("select * from store")
val items: List<Store>?
@get:Query("select * from store")
val itemsRx: Maybe<List<Store>>
@Query("select count(*) from store where id = :id and type = :type and subtype = :subtype")
fun getCount(id: String, type: String, subtype: String): Int
@Query("select count(*) from store where id = :id and type = :type and subtype = :subtype and state = :state")
fun getCount(id: String, type: String, subtype: String, state: String): Int
@Query("select count(*) from store where type = :type and subtype = :subtype and state = :state")
fun getCountByType(type: String, subtype: String, state: String): Int
@Query("select count(*) from store where id = :id and type = :type and subtype = :subtype")
fun getCountRx(id: String, type: String, subtype: String): Maybe<Int>
@Query("select * from store where id = :id limit 1")
fun getItem(id: String): Store?
@Query("select * from store where id = :id limit 1")
fun getItemRx(id: String): Maybe<Store>
@Query("select * from store where type = :type and subtype = :subtype and state = :state limit 1")
fun getItem(type: String, subtype: String, state: String): Store?
@Query("select * from store where type = :type and subtype = :subtype and state = :state order by random() limit 1")
fun getRandomItem(type: String, subtype: String, state: String): Store?
@Query("select * from store where type = :type and subtype = :subtype and state = :state limit 1")
fun getItemRx(type: String, subtype: String, state: String): Maybe<Store>
@Query("select * from store where id = :id and type = :type and subtype = :subtype and state = :state limit 1")
fun getItem(id: String, type: String, subtype: String, state: String): Store?
@Query("select * from store where id = :id and type = :type and subtype = :subtype and state = :state limit 1")
fun getItemRx(id: String, type: String, subtype: String, state: String): Maybe<Store>
@Query("select * from store limit :limit")
fun getItems(limit: Int): List<Store>?
@Query("select * from store limit :limit")
fun getItemsRx(limit: Int): Maybe<List<Store>>
@Query("select data from store where type = :type and subtype = :subtype and state = :state order by time desc")
fun getItemsOf(type: String, subtype: String, state: String): List<String>?
@Query("select data from store where type = :type and subtype = :subtype and state = :state order by time desc")
fun getItemsOfRx(type: String, subtype: String, state: String): Maybe<List<String>>
@Query("select data from store where type = :type and subtype = :subtype and state = :state order by time desc limit :limit")
fun getItemsOfRx(type: String, subtype: String, state: String, limit: Int): Maybe<List<String>>
@Query("select * from store where type = :type and subtype = :subtype and state = :state")
fun getItems(type: String, subtype: String, state: String): List<Store>?
@Query("select * from store where type = :type and subtype = :subtype and state = :state")
fun getItemsRx(type: String, subtype: String, state: String): Maybe<List<Store>>
@Query("select * from store where type = :type and subtype = :subtype and state = :state limit :limit")
fun getItems(type: String, subtype: String, state: String, limit: Int): List<Store>?
@Query("select * from store where type = :type and subtype = :subtype and state = :state limit :limit")
fun getItemsRx(type: String, subtype: String, state: String, limit: Int): Maybe<List<Store>>
} | apache-2.0 | fb37985f2d2e9d6f6198d4f65c07771d | 44.965909 | 129 | 0.681751 | 3.779439 | false | false | false | false |
timrijckaert/LottieSwipeRefreshLayout | app/src/main/kotlin/be/rijckaert/tim/MainActivity.kt | 1 | 1646 | package be.rijckaert.tim
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.RecyclerView
import android.widget.Toast
import be.rijckaert.tim.lib.LottiePullToRefreshLayout
import be.rijckaert.tim.lib.refreshes
import java.util.*
import java.util.concurrent.TimeUnit
class MainActivity : AppCompatActivity() {
private val source: List<String>
get() {
val lowerBound = (1..100).random()
return (lowerBound..(lowerBound..101).random()).map { "This is item number $it" }
}
private val simpleAdapter = SimpleAdapter().apply { dataSource = source }
private val simulatedNetworkDelay = TimeUnit.SECONDS.toMillis(3)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<RecyclerView>(R.id.recyclerView).adapter = simpleAdapter
val lottiePullToRefreshLayout = findViewById<LottiePullToRefreshLayout>(R.id.swipe_refresh)
lottiePullToRefreshLayout.refreshes()
.subscribe {
Handler().postDelayed({
simpleAdapter.dataSource = source
lottiePullToRefreshLayout.stopRefreshing()
}, simulatedNetworkDelay)
}
lottiePullToRefreshLayout.onProgressListener {
Toast.makeText(this@MainActivity, "$it", Toast.LENGTH_SHORT).show()
}
}
}
fun ClosedRange<Int>.random() = Random(System.currentTimeMillis()).nextInt((endInclusive + 1) - start) + start
| mit | ea516ff752d670bc9b07dd8a0f9a1670 | 36.409091 | 111 | 0.681652 | 4.826979 | false | false | false | false |
vector-im/vector-android | vector/src/main/java/im/vector/fragments/terms/AcceptTermsFragment.kt | 2 | 5371 | /*
* 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.fragments.terms
import android.app.Activity
import android.os.Bundle
import android.view.ViewGroup
import android.widget.Button
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import butterknife.BindView
import butterknife.OnClick
import com.airbnb.epoxy.EpoxyRecyclerView
import im.vector.R
import im.vector.fragments.VectorBaseFragment
import im.vector.util.openUrlInExternalBrowser
import im.vector.util.state.MxAsync
import org.matrix.androidsdk.features.terms.TermsManager
class AcceptTermsFragment : VectorBaseFragment(), TermsController.Listener {
lateinit var viewModel: AcceptTermsViewModel
override fun getLayoutResId(): Int = R.layout.fragment_accept_terms
private lateinit var termsController: TermsController
@BindView(R.id.terms_recycler_view)
lateinit var termsList: EpoxyRecyclerView
@BindView(R.id.terms_bottom_accept)
lateinit var acceptButton: Button
@BindView(R.id.waitOverlay)
lateinit var waitingModalOverlay: ViewGroup
@BindView(R.id.termsBottomBar)
lateinit var bottomBar: ViewGroup
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProviders.of(requireActivity()).get(AcceptTermsViewModel::class.java)
val description = when (viewModel.termsArgs.type) {
TermsManager.ServiceType.IdentityService -> getString(R.string.terms_description_for_identity_server)
TermsManager.ServiceType.IntegrationManager -> getString(R.string.terms_description_for_integration_manager)
}
termsController = TermsController(description, this)
termsList.setController(termsController)
viewModel.loadTerms(getString(R.string.resources_language))
viewModel.termsList.observe(this, Observer { terms ->
when (terms) {
is MxAsync.Loading -> {
bottomBar.isVisible = false
waitingModalOverlay.isVisible = true
}
is MxAsync.Error -> {
waitingModalOverlay.isVisible = false
terms.stringResId.let { stringRes ->
AlertDialog.Builder(requireActivity())
.setMessage(stringRes)
.setPositiveButton(R.string.ok) { dialog, which ->
activity?.finish()
}
.show()
}
}
is MxAsync.Success -> {
updateState(terms.value)
waitingModalOverlay.isVisible = false
bottomBar.isVisible = true
acceptButton.isEnabled = terms.value.all { it.accepted }
}
else -> {
waitingModalOverlay.isVisible = false
}
}
})
viewModel.acceptTerms.observe(this, Observer { request ->
when (request) {
is MxAsync.Loading -> {
waitingModalOverlay.isVisible = true
}
is MxAsync.Error -> {
waitingModalOverlay.isVisible = false
request.stringResId.let { stringRes ->
AlertDialog.Builder(requireActivity())
.setMessage(stringRes)
.setPositiveButton(R.string.ok, null)
.show()
}
}
is MxAsync.Success -> {
waitingModalOverlay.isVisible = false
activity?.setResult(Activity.RESULT_OK)
activity?.finish()
}
else -> {
waitingModalOverlay.isVisible = false
}
}
})
}
private fun updateState(terms: List<Term>) {
termsController.setData(terms)
}
companion object {
fun newInstance(): AcceptTermsFragment {
return AcceptTermsFragment()
}
}
override fun setChecked(term: Term, isChecked: Boolean) {
viewModel.markTermAsAccepted(term.url, isChecked)
}
override fun review(term: Term) {
openUrlInExternalBrowser(this.requireContext(), term.url)
}
@OnClick(R.id.terms_bottom_accept)
fun onAcceptButton() {
viewModel.acceptTerms()
}
@OnClick(R.id.terms_bottom_decline)
fun onDeclineButton() {
activity?.finish()
}
} | apache-2.0 | 1826a0613d8057af44e3eb8fa8c48418 | 33.435897 | 120 | 0.602123 | 5.129895 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-core-bukkit/src/main/kotlin/com/rpkit/core/bukkit/util/ChatColors.kt | 1 | 3145 | /*
* Copyright 2020 Ren Binden
*
* 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.rpkit.core.bukkit.util
import org.bukkit.ChatColor
import java.awt.Color
private val BLACK = Color(0, 0, 0)
private val DARK_BLUE = Color(0, 0, 170)
private val DARK_GREEN = Color(0, 170, 0)
private val DARK_AQUA = Color(0, 170, 170)
private val DARK_RED = Color(170, 0, 0)
private val DARK_PURPLE = Color(170, 0, 170)
private val GOLD = Color(255, 170, 0)
private val GRAY = Color(170, 170, 170)
private val DARK_GRAY = Color(85, 85, 85)
private val BLUE = Color(85, 85, 255)
private val GREEN = Color(85, 255, 85)
private val AQUA = Color(85, 255, 255)
private val RED = Color(255, 85, 85)
private val LIGHT_PURPLE = Color(255, 85, 255)
private val YELLOW = Color(255, 255, 85)
private val WHITE = Color(255, 255, 255)
/**
* Gets the closest Bukkit chat color to the color.
*/
fun Color.closestChatColor(): ChatColor {
var minDistSquared = java.lang.Double.MAX_VALUE
var closest: ChatColor? = null
for (chatColor in ChatColor.values()) {
val chatColorColor = chatColor.toColor()
if (chatColorColor != null) {
val distSquared = Math.pow((red - chatColorColor.red).toDouble(), 2.0) + Math.pow((blue - chatColorColor.blue).toDouble(), 2.0) + Math.pow((green - chatColorColor.green).toDouble(), 2.0)
if (distSquared < minDistSquared) {
minDistSquared = distSquared
closest = chatColor
}
}
}
return closest!!
}
/**
* Gets the color of this chat color.
*/
fun ChatColor.toColor(): Color? {
when (this) {
ChatColor.BLACK -> return BLACK
ChatColor.DARK_BLUE -> return DARK_BLUE
ChatColor.DARK_GREEN -> return DARK_GREEN
ChatColor.DARK_AQUA -> return DARK_AQUA
ChatColor.DARK_RED -> return DARK_RED
ChatColor.DARK_PURPLE -> return DARK_PURPLE
ChatColor.GOLD -> return GOLD
ChatColor.GRAY -> return GRAY
ChatColor.DARK_GRAY -> return DARK_GRAY
ChatColor.BLUE -> return BLUE
ChatColor.GREEN -> return GREEN
ChatColor.AQUA -> return AQUA
ChatColor.RED -> return RED
ChatColor.LIGHT_PURPLE -> return LIGHT_PURPLE
ChatColor.YELLOW -> return YELLOW
ChatColor.WHITE -> return WHITE
ChatColor.MAGIC, ChatColor.BOLD, ChatColor.STRIKETHROUGH, ChatColor.UNDERLINE, ChatColor.ITALIC, ChatColor.RESET -> return null
else -> return null
}
}
operator fun ChatColor.plus(string: String) = toString() + string
operator fun ChatColor.plus(color: ChatColor) = toString() + color.toString()
| apache-2.0 | 958eac1c3cb1e7be9d921ab212992937 | 35.569767 | 198 | 0.672814 | 3.921446 | false | false | false | false |
paoloach/zdomus | temperature_monitor/app/src/main/java/it/achdjian/paolo/temperaturemonitor/rajawali/TemperatureLabel.kt | 1 | 2730 | package it.achdjian.paolo.temperaturemonitor.rajawali
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import org.rajawali3d.materials.Material
import org.rajawali3d.materials.textures.ATexture
import org.rajawali3d.materials.textures.Texture
import org.rajawali3d.math.vector.Vector3
import org.rajawali3d.primitives.Plane
import java.util.*
/**
* Created by Paolo Achdjian on 17/04/17.
*/
class TemperatureLabel(room: RoomObject) : Plane(getMaxWidth(room), getMaxHeight(room), 3, 3) {
private var previousTemp = java.lang.Float.NaN
val pos: Vector3
get() = position
init {
val name = "TempSensor" + room.name
setName(name)
setText("N.D.", Color.GREEN)
val pos = Vector3(room.mean.x, room.mean.y, room.max.z)
position = pos
isDoubleSided = true
}
fun setTemperature(temp: Float, background: Int) {
if (temp != previousTemp) {
previousTemp = temp
val strTemp = String.format(Locale.US, "%.2f", temp)
setText(strTemp, background)
}
}
private fun setText(text: String, background: Int) {
val temperatureMaterial = Material(true)
temperatureMaterial.color = background
val bitmap = textAsBitmap(text, Color.WHITE)
try {
val maxTextureName = 18
val name = name.substring(0, if (name.length > maxTextureName) maxTextureName else name.length)
temperatureMaterial.addTexture(Texture(name, bitmap))
material = temperatureMaterial
} catch (e: ATexture.TextureException) {
e.printStackTrace()
}
}
private fun textAsBitmap(text: String, textColor: Int): Bitmap {
val paint = Paint()
paint.textSize = 30f
paint.strokeWidth = 10f
paint.color = textColor
val baseline = (-paint.ascent() + 0.5f).toInt().toFloat()
val image = Bitmap.createBitmap(128, 32, Bitmap.Config.ARGB_8888)
val canvas = Canvas(image)
val widthText = paint.measureText(text).toInt()
canvas.drawText(text, ((128 - widthText) / 2).toFloat(), baseline, paint)
return image
}
companion object {
var WIDTH = 1.5f
var HEIGHT = 0.4f
private fun getMaxWidth(room: RoomObject): Float {
val minWidth = (room.max.x - room.min.x).toFloat()
return if (minWidth < WIDTH) minWidth else WIDTH
}
private fun getMaxHeight(room: RoomObject): Float {
val minHeight = (room.max.y - room.min.y).toFloat()
return if (minHeight < HEIGHT) minHeight else HEIGHT
}
}
}
| gpl-2.0 | 0ade1463091773641ca38feb83e1e99d | 30.37931 | 107 | 0.635897 | 4.050445 | false | false | false | false |
oversecio/oversec_crypto | crypto/src/main/java/io/oversec/one/crypto/gpg/ui/GpgTextEncryptionInfoFragment.kt | 1 | 15221 | package io.oversec.one.crypto.gpg.ui
import android.app.Activity
import android.content.Intent
import android.content.IntentSender
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.view.*
import android.widget.Button
import android.widget.TextView
import io.oversec.one.crypto.*
import io.oversec.one.crypto.gpg.GpgCryptoHandler
import io.oversec.one.crypto.gpg.GpgDecryptResult
import io.oversec.one.crypto.gpg.OpenKeychainConnector
import io.oversec.one.crypto.sym.SymUtil
import io.oversec.one.crypto.ui.AbstractTextEncryptionInfoFragment
import io.oversec.one.crypto.ui.EncryptionInfoActivity
import org.openintents.openpgp.OpenPgpSignatureResult
class GpgTextEncryptionInfoFragment : AbstractTextEncryptionInfoFragment() {
private lateinit var mCryptoHandler: GpgCryptoHandler
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
mView = inflater.inflate(R.layout.encryption_info_text_gpg, container, false)
super.onCreateView(inflater, container, savedInstanceState)
return mView
}
override fun setData(
activity: EncryptionInfoActivity,
encodedText: String,
tdr: BaseDecryptResult?,
uix: UserInteractionRequiredException?,
encryptionHandler: AbstractCryptoHandler
) {
super.setData(activity, encodedText, tdr, uix, encryptionHandler)
mCryptoHandler = encryptionHandler as GpgCryptoHandler
val r = tdr as GpgDecryptResult?
val lblPgpRecipients = mView.findViewById<View>(R.id.lbl_pgp_recipients) as TextView
val tvPgpRecipients = mView.findViewById<View>(R.id.tv_pgp_recipients) as TextView
val lblPgpSignatureResult =
mView.findViewById<View>(R.id.lbl_pgp_signature_result) as TextView
val tvPgpSignatureResult =
mView.findViewById<View>(R.id.tv_pgp_signature_result) as TextView
val lblPgpSignatureKey = mView.findViewById<View>(R.id.lbl_pgp_signature_key) as TextView
val tvPgpSignatureKey = mView.findViewById<View>(R.id.tv_pgp_signature_key) as TextView
lblPgpRecipients.visibility = View.GONE
tvPgpRecipients.visibility = View.GONE
lblPgpSignatureResult.visibility = View.GONE
tvPgpSignatureResult.visibility = View.GONE
lblPgpSignatureKey.visibility = View.GONE
tvPgpSignatureKey.visibility = View.GONE
val msg = CryptoHandlerFacade.getEncodedData(activity, encodedText)
if (msg!!.hasMsgTextGpgV0()) {
val pkids = msg.msgTextGpgV0.pubKeyIdV0List
setPublicKeyIds(
lblPgpRecipients,
tvPgpRecipients,
pkids,
encryptionHandler,
activity,
encodedText,
tdr,
uix
)
}
if (r == null) {
// lblPgpRecipients.setVisibility(View.GONE);
// tvPgpRecipients.setVisibility(View.GONE);
} else {
if (r.signatureResult != null) {
lblPgpSignatureResult.visibility = View.VISIBLE
tvPgpSignatureResult.visibility = View.VISIBLE
val sr = (tdr as GpgDecryptResult).signatureResult
tvPgpSignatureResult.text =
GpgCryptoHandler.signatureResultToUiText(getActivity(), sr!!)
tvPgpSignatureResult.setCompoundDrawablesWithIntrinsicBounds(
0,
0,
GpgCryptoHandler.signatureResultToUiIconRes(sr, false),
0
)
val color = ContextCompat.getColor(
getActivity(),
GpgCryptoHandler.signatureResultToUiColorResId(sr)
)
tvPgpSignatureResult.setTextColor(color)
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// tvPgpSignatureResult.setCompoundDrawableTintList(GpgCryptoHandler.getColorStateListAllStates(color));
// }
when (sr.result) {
OpenPgpSignatureResult.RESULT_INVALID_SIGNATURE, OpenPgpSignatureResult.RESULT_KEY_MISSING, OpenPgpSignatureResult.RESULT_NO_SIGNATURE -> {
lblPgpSignatureKey.visibility = View.GONE
tvPgpSignatureKey.visibility = View.GONE
}
OpenPgpSignatureResult.RESULT_INVALID_INSECURE, OpenPgpSignatureResult.RESULT_INVALID_KEY_EXPIRED, OpenPgpSignatureResult.RESULT_INVALID_KEY_REVOKED, OpenPgpSignatureResult.RESULT_VALID_UNCONFIRMED, OpenPgpSignatureResult.RESULT_VALID_CONFIRMED -> {
lblPgpSignatureKey.visibility = View.VISIBLE
tvPgpSignatureKey.visibility = View.VISIBLE
val sb = sr.primaryUserId +
"\n" +
"[" + SymUtil.longToPrettyHex(sr.keyId) + "]"
tvPgpSignatureKey.text = sb
tvPgpSignatureKey.setCompoundDrawablesWithIntrinsicBounds(
0,
0,
GpgCryptoHandler.signatureResultToUiIconRes_KeyOnly(sr, false),
0
)
val kColor = ContextCompat.getColor(
getActivity(),
GpgCryptoHandler.signatureResultToUiColorResId_KeyOnly(sr)
)
tvPgpSignatureKey.setTextColor(kColor)
// if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// tvPgpSignatureKey.setCompoundDrawableTintList(GpgCryptoHandler.getColorStateListAllStates(kColor));
// }
}
}
}
}
val btKeyDetails = mView.findViewById<View>(R.id.btnKeyDetailsGpg) as Button
btKeyDetails.visibility = View.GONE
val btKeyAction = mView.findViewById<View>(R.id.btnKeyActionGpg) as Button
btKeyAction.visibility = View.GONE
if (r != null) {
if (r.downloadMissingSignatureKeyPendingIntent != null) {
btKeyAction.visibility = View.VISIBLE
btKeyAction.setText(R.string.action_download_missing_signature_key)
btKeyAction.setOnClickListener {
try {
val xtdr = CryptoHandlerFacade.getInstance(getActivity()).decryptWithLock(
mOrigText,
null
) as GpgDecryptResult?
if (xtdr!!.isOk && xtdr.downloadMissingSignatureKeyPendingIntent != null) {
try {
activity.startIntentSenderForResult(
xtdr.downloadMissingSignatureKeyPendingIntent!!.intentSender,
EncryptionInfoActivity.REQUEST_CODE_DOWNLOAD_MISSING_KEYS,
null,
0,
0,
0
)
} catch (e1: IntentSender.SendIntentException) {
e1.printStackTrace()
//TODO: what now?
}
}
} catch (e: UserInteractionRequiredException) {
//should not happen here but well
}
}
} else if (r.showSignatureKeyPendingIntent != null) {
btKeyAction.visibility = View.VISIBLE
btKeyAction.setText(R.string.action_show_signature_key)
btKeyAction.setOnClickListener {
try {
val xtdr = CryptoHandlerFacade.getInstance(getActivity()).decryptWithLock(
mOrigText,
null
) as GpgDecryptResult?
if (xtdr!!.isOk && xtdr.showSignatureKeyPendingIntent != null) {
try {
activity.startIntentSenderForResult(
xtdr.showSignatureKeyPendingIntent!!.intentSender,
EncryptionInfoActivity.REQUEST_CODE_SHOW_SIGNATURE_KEY,
null,
0,
0,
0
)
} catch (e1: IntentSender.SendIntentException) {
e1.printStackTrace()
//TODO: what now?
}
}
} catch (e: UserInteractionRequiredException) {
//should not happen here but well
//might be an external device, so let's use existing decrypt result
if (mTdr != null) {
val pi = (mTdr as GpgDecryptResult).showSignatureKeyPendingIntent
if (pi != null) {
try {
activity.startIntentSenderForResult(
pi.intentSender,
EncryptionInfoActivity.REQUEST_CODE_SHOW_SIGNATURE_KEY,
null,
0,
0,
0
)
} catch (e1: IntentSender.SendIntentException) {
e1.printStackTrace()
}
}
}
}
}
}
btKeyDetails.setOnClickListener {
//for now we can only jump to the list of keys [i.e. the main activity] in OKC, since we're dealing with subkeys here...
GpgCryptoHandler.openOpenKeyChain(getActivity())
}
}
}
override fun onCreateOptionsMenu(activity: Activity, menu: Menu): Boolean {
activity.menuInflater.inflate(R.menu.gpg_menu_encryption_info, menu)
return true
}
override fun onPrepareOptionsMenu(menu: Menu) {
menu.findItem(R.id.action_share_gpg_ascii).isVisible = mTdr != null
}
override fun onOptionsItemSelected(activity: Activity, item: MenuItem) {
val id = item.itemId
if (id == R.id.action_share_gpg_ascii) {
share(
activity,
GpgCryptoHandler.getRawMessageAsciiArmoured(
CryptoHandlerFacade.getEncodedData(
activity,
mOrigText
)!!
)!!,
activity.getString(R.string.action_share_gpg_ascii)
)
} else {
super.onOptionsItemSelected(activity, item)
}
}
private fun setPublicKeyIds(
lblPgpRecipients: TextView,
tvPgpRecipients: TextView,
publicKeyIds: List<Long>?,
encryptionHandler: AbstractCryptoHandler,
activity: EncryptionInfoActivity,
encodedText: String,
tdr: BaseDecryptResult?,
uix: UserInteractionRequiredException?
) {
val pe = encryptionHandler as GpgCryptoHandler
val okcVersion = OpenKeychainConnector.getInstance(lblPgpRecipients.context).getVersion()
if (publicKeyIds != null) {
lblPgpRecipients.visibility = View.VISIBLE
tvPgpRecipients.visibility = View.VISIBLE
val sb = SpannableStringBuilder()
for (pkid in publicKeyIds) {
if (sb.length > 0) {
sb.append("\n\n")
}
val userName = pe.getFirstUserIDByKeyId(pkid, null)
if (userName != null) {
sb.append(userName).append("\n[").append(SymUtil.longToPrettyHex(pkid))
.append("]")
} else {
//userName might be null if OKC version < OpenKeychainConnector.V_GET_SUBKEY
//however in older versions we still don't know if the user doesn't have the key
//so best for now just show the keyId only without any additional remarks
//that might just confuse users.
if (okcVersion >= OpenKeychainConnector.V_GET_SUBKEY) {
val start = sb.length
sb.append(lblPgpRecipients.context.getString(R.string.action_download_missing_public_key))
val end = sb.length
val clickToDownloadKey = object : ClickableSpan() {
override fun onClick(view: View) {
downloadKey(pkid, null)
}
}
sb.setSpan(
clickToDownloadKey,
start,
end,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
)
sb.append("\n")
sb.append("[").append(SymUtil.longToPrettyHex(pkid)).append("]")
} else {
sb.append("[").append(SymUtil.longToPrettyHex(pkid)).append("]")
}
}
}
tvPgpRecipients.text = sb
tvPgpRecipients.movementMethod = LinkMovementMethod.getInstance()
}
}
@Synchronized
private fun downloadKey(keyId: Long, actionIntent: Intent?) {
val pi = mCryptoHandler!!.getDownloadKeyPendingIntent(keyId, actionIntent)
if (pi != null) {
try {
activity.startIntentSenderForResult(
pi.intentSender,
EncryptionInfoActivity.REQUEST_CODE_DOWNLOAD_MISSING_KEYS,
null,
0,
0,
0
)
} catch (e: IntentSender.SendIntentException) {
e.printStackTrace()
}
}
}
companion object {
fun newInstance(packagename: String?): GpgTextEncryptionInfoFragment {
val fragment = GpgTextEncryptionInfoFragment()
fragment.setArgs(packagename)
return fragment
}
}
}
| gpl-3.0 | 23abb44d1883258dd109cb79d95d510e | 40.931129 | 269 | 0.520071 | 5.557138 | false | false | false | false |
savoirfairelinux/ring-client-android | ring-android/app/src/main/java/cx/ring/fragments/LocationSharingFragment.kt | 1 | 26658 | /*
* Copyright (C) 2004-2021 Savoir-faire Linux Inc.
*
* Authors: Adrien Béraud <[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 cx.ring.fragments
import android.Manifest
import android.animation.LayoutTransition
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.icu.text.MeasureFormat
import android.icu.text.MeasureFormat.FormatWidth
import android.icu.util.Measure
import android.icu.util.MeasureUnit
import android.location.Location
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.text.format.DateUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.google.android.material.chip.ChipGroup
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import cx.ring.R
import cx.ring.databinding.FragLocationSharingBinding
import cx.ring.service.LocationSharingService
import cx.ring.service.LocationSharingService.LocalBinder
import cx.ring.utils.ConversationPath
import cx.ring.utils.TouchClickListener
import cx.ring.views.AvatarFactory
import dagger.hilt.android.AndroidEntryPoint
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.CompositeDisposable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.subjects.BehaviorSubject
import io.reactivex.rxjava3.subjects.Subject
import net.jami.services.ConversationFacade
import net.jami.model.Account
import net.jami.model.Account.ContactLocation
import net.jami.model.ContactViewModel
import net.jami.services.ContactService
import org.osmdroid.config.Configuration
import org.osmdroid.tileprovider.tilesource.TileSourceFactory
import org.osmdroid.util.BoundingBox
import org.osmdroid.util.GeoPoint
import org.osmdroid.views.CustomZoomButtonsController
import org.osmdroid.views.overlay.Marker
import org.osmdroid.views.overlay.mylocation.IMyLocationConsumer
import org.osmdroid.views.overlay.mylocation.IMyLocationProvider
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay
import java.io.File
import java.util.*
import javax.inject.Inject
@AndroidEntryPoint
class LocationSharingFragment : Fragment() {
private val mDisposableBag = CompositeDisposable()
private val mServiceDisposableBag = CompositeDisposable()
private var mCountdownDisposable: Disposable? = null
internal enum class MapState { NONE, MINI, FULL }
@Inject
lateinit var mConversationFacade: ConversationFacade
@Inject
lateinit var contactService: ContactService
private lateinit var mPath: ConversationPath
private var mContact: ContactViewModel? = null
private val mShowControlsSubject: Subject<Boolean> = BehaviorSubject.create()
private val mIsSharingSubject: Subject<Boolean> = BehaviorSubject.create()
private val mIsContactSharingSubject: Subject<Boolean> = BehaviorSubject.create()
private val mShowMapSubject = Observable.combineLatest(
mShowControlsSubject,
mIsSharingSubject,
mIsContactSharingSubject
) { showControls, isSharing, isContactSharing ->
if (showControls)
MapState.FULL
else if (isSharing || isContactSharing)
MapState.MINI
else
MapState.NONE
}.distinctUntilChanged()
private var bubbleSize = 0
private var overlay: MyLocationNewOverlay? = null
private var marker: Marker? = null
private var lastBoundingBox: BoundingBox? = null
private var trackAll = true
private var mStartSharingPending: Int? = null
private var binding: FragLocationSharingBinding? = null
private var mService: LocationSharingService? = null
private var mBound = false
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragLocationSharingBinding.inflate(inflater, container, false)
return binding!!.root
}
override fun onDestroyView() {
super.onDestroyView()
binding = null
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requireArguments().let { args ->
mPath = ConversationPath.fromBundle(args)!!
mShowControlsSubject.onNext(args.getBoolean(KEY_SHOW_CONTROLS, true))
}
val ctx = requireContext()
val osmPath = File(ctx.cacheDir, "osm")
Configuration.getInstance().apply {
osmdroidBasePath = osmPath
osmdroidTileCache = File(osmPath, "tiles")
userAgentValue = "net.jami.android"
isMapViewHardwareAccelerated = true
isMapViewRecyclerFriendly = false
}
bubbleSize = ctx.resources.getDimensionPixelSize(R.dimen.location_sharing_avatar_size)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
binding?.let { binding ->
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
binding.locationShareTime1h.text = formatDuration(DateUtils.HOUR_IN_MILLIS, FormatWidth.WIDE)
binding.locationShareTime10m.text = formatDuration(10 * DateUtils.MINUTE_IN_MILLIS, FormatWidth.WIDE)
}
binding.infoBtn.setOnClickListener { v: View ->
val padding = v.resources.getDimensionPixelSize(R.dimen.padding_large)
val textView = TextView(v.context)
textView.setText(R.string.location_share_about_message)
textView.setOnClickListener { tv -> tv.context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.location_share_about_osm_copy_url)))) }
textView.setPadding(padding, padding, padding, padding)
MaterialAlertDialogBuilder(view.context)
.setTitle(R.string.location_share_about_title)
.setView(textView)
.create().show()
}
binding.btnCenterPosition.setOnClickListener {
overlay?.let { overlay ->
trackAll = true
if (lastBoundingBox != null) binding.map.zoomToBoundingBox(lastBoundingBox, true)
else overlay.enableFollowLocation()
}
}
binding.locationShareTimeGroup.setOnCheckedChangeListener { group: ChipGroup, id: Int ->
if (id == View.NO_ID) group.check(R.id.location_share_time_1h)
}
binding.locshareToolbar.setNavigationOnClickListener { mShowControlsSubject.onNext(false) }
binding.locationShareStop.setOnClickListener { stopSharing() }
binding.map.setTileSource(TileSourceFactory.MAPNIK)
binding.map.isHorizontalMapRepetitionEnabled = false
binding.map.isTilesScaledToDpi = true
binding.map.setMapOrientation(0f, false)
binding.map.minZoomLevel = 1.0
binding.map.maxZoomLevel = 19.0
binding.map.zoomController.setVisibility(CustomZoomButtonsController.Visibility.NEVER)
binding.map.controller.setZoom(14.0)
}
(view as ViewGroup).layoutTransition.enableTransitionType(LayoutTransition.CHANGING)
}
private val onBackPressedCallback: OnBackPressedCallback =
object : OnBackPressedCallback(false) {
override fun handleOnBackPressed() {
mShowControlsSubject.onNext(false)
}
}
override fun onAttach(context: Context) {
super.onAttach(context)
requireActivity().onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
}
override fun onDestroy() {
super.onDestroy()
mShowControlsSubject.onComplete()
mIsSharingSubject.onComplete()
mIsContactSharingSubject.onComplete()
}
override fun onResume() {
super.onResume()
binding?.map?.onResume()
try {
overlay?.enableMyLocation()
} catch (e: Exception) {
Log.w(TAG, e)
}
}
override fun onPause() {
super.onPause()
binding?.map?.onPause()
overlay?.disableMyLocation()
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == REQUEST_CODE_LOCATION) {
var granted = false
for (result in grantResults) granted =
granted or (result == PackageManager.PERMISSION_GRANTED)
if (granted) {
startService()
} else {
mIsSharingSubject.onNext(false)
mShowControlsSubject.onNext(false)
}
}
}
override fun onStart() {
super.onStart()
mDisposableBag.add(mServiceDisposableBag)
mDisposableBag.add(mShowControlsSubject.subscribe { show: Boolean -> setShowControls(show) })
mDisposableBag.add(mIsSharingSubject.subscribe { sharing: Boolean -> setIsSharing(sharing) })
mDisposableBag.add(mShowMapSubject
.subscribeOn(AndroidSchedulers.mainThread())
.subscribe { state: MapState ->
val p = parentFragment
if (p is ConversationFragment) {
if (state == MapState.FULL)
p.openLocationSharing()
else
p.closeLocationSharing(state == MapState.MINI)
}
})
mDisposableBag.add(mIsContactSharingSubject
.distinctUntilChanged()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { sharing ->
binding?.let { binding ->
if (sharing) {
val sharingString =
getString(R.string.location_share_contact, mContact!!.displayName)
binding.locshareToolbar.subtitle = sharingString
binding.locshareSnipetTxt.visibility = View.VISIBLE
binding.locshareSnipetTxtShadow.visibility = View.VISIBLE
binding.locshareSnipetTxt.text = sharingString
} else {
binding.locshareToolbar.subtitle = null
binding.locshareSnipetTxt.visibility = View.GONE
binding.locshareSnipetTxtShadow.visibility = View.GONE
binding.locshareSnipetTxt.text = null
}
}
})
val contactUri = mPath.conversationUri
mDisposableBag.add(mConversationFacade
.getAccountSubject(mPath.accountId)
.flatMapObservable { account: Account ->
account.locationsUpdates
.switchMapSingle { locations -> contactService.getLoadedContact(mPath.accountId, locations.keys).map { contacts ->
val r: MutableList<Observable<LocationViewModel>> = ArrayList(locations.size)
var isContactSharing = false
for (c in contacts) {
if (c.contact === account.getContactFromCache(contactUri)) {
isContactSharing = true
mContact = c
}
locations[c.contact]?.let { location -> r.add(location.map { l -> LocationViewModel(c, l) }) }
}
mIsContactSharingSubject.onNext(isContactSharing)
r
} }
}
.flatMap { locations: List<Observable<LocationViewModel>> ->
Observable.combineLatest<LocationViewModel, List<LocationViewModel>>(locations) { locsArray: Array<Any> ->
val list: MutableList<LocationViewModel> = ArrayList(locsArray.size)
for (vm in locsArray) list.add(vm as LocationViewModel)
list
}
}
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ locations: List<LocationViewModel> ->
val context = context
if (context != null) {
binding!!.map.overlays.clear()
if (overlay != null) binding!!.map.overlays.add(overlay)
if (marker != null) binding!!.map.overlays.add(marker)
val geoLocations: MutableList<GeoPoint> = ArrayList(locations.size + 1)
overlay?.myLocation?.let { myLoc -> geoLocations.add(myLoc) }
for (vm in locations) {
val m = Marker(binding!!.map)
val position = GeoPoint(vm.location.latitude, vm.location.longitude)
m.setInfoWindow(null)
m.position = position
m.setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
geoLocations.add(position)
mDisposableBag.add(
AvatarFactory.getBitmapAvatar(context, vm.contact, bubbleSize, false)
.subscribe { avatar: Bitmap ->
val bd = BitmapDrawable(context.resources, avatar)
m.icon = bd
m.setInfoWindow(null)
binding!!.map.overlays.add(m)
})
}
if (trackAll) {
if (geoLocations.size == 1) {
lastBoundingBox = null
binding!!.map.controller.animateTo(geoLocations[0])
} else {
var bb = BoundingBox.fromGeoPointsSafe(geoLocations)
bb = bb.increaseByScale(1.5f)
lastBoundingBox = bb
binding!!.map.zoomToBoundingBox(bb, true)
}
}
}
}) { e: Throwable -> Log.w(TAG, "Error updating contact position", e) }
)
val ctx = requireContext()
if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mIsSharingSubject.onNext(false)
mDisposableBag.add(mShowControlsSubject
.firstElement()
.subscribe { showControls ->
if (showControls) {
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_CODE_LOCATION)
}
})
} else {
startService()
}
}
override fun onStop() {
super.onStop()
if (mBound) {
requireContext().unbindService(mConnection)
mConnection.onServiceDisconnected(null)
mBound = false
}
mDisposableBag.clear()
}
private fun startService() {
val ctx = requireContext()
ctx.bindService(Intent(ctx, LocationSharingService::class.java), mConnection, Context.BIND_AUTO_CREATE)
}
fun showControls() {
mShowControlsSubject.onNext(true)
}
fun hideControls() {
mShowControlsSubject.onNext(false)
}
private fun setShowControls(show: Boolean) {
binding?.let { b ->
if (show) {
onBackPressedCallback.isEnabled = true
b.locshareSnipet.visibility = View.GONE
b.shareControlsMini.visibility = View.GONE
b.shareControlsMini.postDelayed({
binding?.let { b ->
b.shareControlsMini.visibility = View.GONE
b.locshareSnipet.visibility = View.GONE
}
}, 300)
b.shareControls.visibility = View.VISIBLE
b.locshareToolbar.visibility = View.VISIBLE
b.map.setOnTouchListener(null)
b.map.setMultiTouchControls(true)
} else {
onBackPressedCallback.isEnabled = false
b.shareControls.visibility = View.GONE
b.shareControlsMini.postDelayed({
binding?.let { b ->
b.shareControlsMini.visibility = View.VISIBLE
b.locshareSnipet.visibility = View.VISIBLE
}
}, 300)
b.locshareToolbar.visibility = View.GONE
b.map.setMultiTouchControls(false)
b.map.setOnTouchListener(TouchClickListener(binding!!.map.context) { mShowControlsSubject.onNext(true) })
}
}
}
internal class RxLocationListener(private val mLocation: Observable<Location>) : IMyLocationProvider {
private val mDisposableBag = CompositeDisposable()
override fun startLocationProvider(myLocationConsumer: IMyLocationConsumer): Boolean {
mDisposableBag.add(mLocation.subscribe { loc -> myLocationConsumer.onLocationChanged(loc, this) })
return false
}
override fun stopLocationProvider() {
mDisposableBag.clear()
}
override fun getLastKnownLocation(): Location {
return mLocation.blockingFirst()
}
override fun destroy() {
mDisposableBag.dispose()
}
}
internal class LocationViewModel(var contact: ContactViewModel, var location: ContactLocation)
private val mConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName, service: IBinder) {
Log.w(TAG, "onServiceConnected")
val binder = service as LocalBinder
mService = binder.service
mBound = true
if (marker == null) {
marker = Marker(binding!!.map).apply {
setInfoWindow(null)
setAnchor(Marker.ANCHOR_CENTER, Marker.ANCHOR_CENTER)
}
mServiceDisposableBag.add(mConversationFacade
.getAccountSubject(mPath.accountId)
.flatMap { account -> AvatarFactory.getBitmapAvatar(requireContext(), account, bubbleSize) }
.subscribe { avatar ->
marker!!.icon = BitmapDrawable(requireContext().resources, avatar)
binding!!.map.overlays.add(marker)
})
}
mServiceDisposableBag.add(binder.service.contactSharing
.subscribe { location -> mIsSharingSubject.onNext(location.contains(mPath)) })
mServiceDisposableBag.add(binder.service.myLocation
.subscribe { location -> marker!!.position = GeoPoint(location) })
mServiceDisposableBag.add(binder.service.myLocation
.firstElement()
.observeOn(AndroidSchedulers.mainThread())
.subscribe { location ->
// start map on first location
binding?.let { binding ->
binding.map.setExpectedCenter(GeoPoint(location))
overlay = MyLocationNewOverlay(RxLocationListener(binder.service.myLocation), binding.map)
.apply { enableMyLocation() }
binding.map.overlays.add(overlay)
}
})
mStartSharingPending?.let { pending ->
mStartSharingPending = null
startSharing(pending)
}
}
override fun onServiceDisconnected(name: ComponentName?) {
Log.w(TAG, "onServiceDisconnected")
mBound = false
mServiceDisposableBag.clear()
mService = null
}
}
private val selectedDuration: Int
get() = when (binding!!.locationShareTimeGroup.checkedChipId) {
R.id.location_share_time_10m -> 10 * 60
R.id.location_share_time_1h -> 60 * 60
else -> 60 * 60
}
private fun setIsSharing(sharing: Boolean) {
binding?.let { binding ->
if (sharing) {
binding.btnShareLocation.setBackgroundColor(ContextCompat.getColor(binding.btnShareLocation.context, R.color.design_default_color_error))
binding.btnShareLocation.setText(R.string.location_share_action_stop)
binding.btnShareLocation.setOnClickListener { v: View? -> stopSharing() }
binding.locationShareTimeGroup.visibility = View.GONE
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mService?.let { service ->
binding.locationShareTimeRemaining.visibility = View.VISIBLE
if (mCountdownDisposable == null || mCountdownDisposable!!.isDisposed) {
mCountdownDisposable = service.getContactSharingExpiration(mPath)
.subscribe { l -> binding.locationShareTimeRemaining.text = formatDuration(l, FormatWidth.SHORT) }
mServiceDisposableBag.add(mCountdownDisposable)
}
}
}
binding.locationShareStop.visibility = View.VISIBLE
requireView().post { hideControls() }
} else {
mCountdownDisposable?.let { disposable ->
disposable.dispose()
mCountdownDisposable = null
}
binding.btnShareLocation.setBackgroundColor(ContextCompat.getColor(binding.btnShareLocation.context, R.color.colorSecondary))
binding.btnShareLocation.setText(R.string.location_share_action_start)
binding.btnShareLocation.setOnClickListener { startSharing(selectedDuration) }
binding.locationShareTimeRemaining.visibility = View.GONE
binding.locationShareTimeGroup.visibility = View.VISIBLE
binding.locationShareStop.visibility = View.GONE
}
}
}
private fun startSharing(durationSec: Int) {
val ctx = requireContext()
try {
if (ActivityCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(ctx, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mStartSharingPending = durationSec
requestPermissions(arrayOf(Manifest.permission.ACCESS_FINE_LOCATION), REQUEST_CODE_LOCATION)
} else {
val intent = Intent(LocationSharingService.ACTION_START, mPath.toUri(), ctx, LocationSharingService::class.java)
.putExtra(LocationSharingService.EXTRA_SHARING_DURATION, durationSec)
ContextCompat.startForegroundService(ctx, intent)
}
} catch (e: Exception) {
Toast.makeText(ctx, "Error starting location sharing: " + e.localizedMessage, Toast.LENGTH_SHORT).show()
}
}
private fun stopSharing() {
try {
val ctx = requireContext()
ctx.startService(Intent(LocationSharingService.ACTION_STOP, mPath.toUri(), ctx, LocationSharingService::class.java))
} catch (e: Exception) {
Log.w(TAG, "Error stopping location sharing", e)
}
}
companion object {
private val TAG = LocationSharingFragment::class.simpleName!!
private const val REQUEST_CODE_LOCATION = 47892
private const val KEY_SHOW_CONTROLS = "showControls"
fun newInstance(accountId: String, conversationId: String, showControls: Boolean): LocationSharingFragment {
val fragment = LocationSharingFragment()
val args = ConversationPath.toBundle(accountId, conversationId)
args.putBoolean(KEY_SHOW_CONTROLS, showControls)
fragment.arguments = args
return fragment
}
@RequiresApi(api = Build.VERSION_CODES.N)
private fun formatDuration(millis: Long, width: FormatWidth): CharSequence {
val formatter = MeasureFormat.getInstance(Locale.getDefault(), width)
return when {
millis >= DateUtils.HOUR_IN_MILLIS -> {
val hours = ((millis + DateUtils.HOUR_IN_MILLIS / 2) / DateUtils.HOUR_IN_MILLIS).toInt()
formatter.format(Measure(hours, MeasureUnit.HOUR))
}
millis >= DateUtils.MINUTE_IN_MILLIS -> {
val minutes = ((millis + DateUtils.MINUTE_IN_MILLIS / 2) / DateUtils.MINUTE_IN_MILLIS).toInt()
formatter.format(Measure(minutes, MeasureUnit.MINUTE))
}
else -> {
val seconds = ((millis + DateUtils.SECOND_IN_MILLIS / 2) / DateUtils.SECOND_IN_MILLIS).toInt()
formatter.format(Measure(seconds, MeasureUnit.SECOND))
}
}
}
}
} | gpl-3.0 | 695010b2e14cb7fa606326d490443f9b | 44.183051 | 172 | 0.611772 | 5.144153 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/datatypes/values/TimeofDayData.kt | 1 | 2002 | package edu.kit.iti.formal.automation.datatypes.values
/*-
* #%L
* iec61131lang
* %%
* Copyright (C) 2016 Alexander Weigl
* %%
* This program isType 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 isType 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 clone of the GNU General Public
* License along with this program. If not, see
* <http://www.gnu.org/licenses/gpl-3.0.html>.
* #L%
*/
import edu.kit.iti.formal.automation.sfclang.split
import java.util.regex.Pattern
/**
*
* TimeofDayData class.
*
* @author weigl
* @version $Id: $Id
*/
data class TimeofDayData(var hours: Int = 0, var minutes: Int = 0,
var seconds: Int = 0, var millieseconds: Int = 0) {
companion object {
fun parse(tod: String): TimeofDayData {
val pattern = Pattern.compile(
"(?<hour>\\d?\\d):(?<min>\\d?\\d)(:(?<sec>\\d?\\d))?(.(?<ms>\\d+))?")
val s = split(tod)
val matcher = pattern.matcher(s.value!!)
val parseInt = { key: String ->
val a = matcher.group(key)
if (a == null) 0 else Integer.parseInt(a)
}
if (matcher.matches()) {
val hour = parseInt("hour")
val min = parseInt("min")
val sec = parseInt("sec")
val ms = parseInt("ms")
val t = TimeofDayData(hour, min, sec, ms)
return t
} else {
throw IllegalArgumentException("Given string isType not a time of day value.")
}
}
}
}
| gpl-3.0 | dbbfbbf7b4880fa121365f16295f14e0 | 32.366667 | 94 | 0.583916 | 3.933202 | false | false | false | false |
VerifAPS/verifaps-lib | lang/src/main/kotlin/edu/kit/iti/formal/automation/datatypes/values/DateAndTimeData.kt | 1 | 1584 | package edu.kit.iti.formal.automation.datatypes.values
import edu.kit.iti.formal.automation.sfclang.split
data class DateAndTimeData(var date: DateData = DateData(),
var tod: TimeofDayData = TimeofDayData()) {
var hours: Int
get() = tod.hours
set(hours) {
tod.hours = hours
}
var minutes: Int
get() = tod.minutes
set(minutes) {
tod.minutes = minutes
}
var seconds: Int
get() = tod.seconds
set(seconds) {
tod.seconds = seconds
}
var year: Int
get() = date.year
set(year) {
date.year = year
}
var day: Int
get() = date.day
set(day) {
date.day = day
}
var month: Int
get() = date.month
set(month) {
date.month = month
}
var millieSeconds: Int
get() = tod.millieseconds
set(ms) {
tod.millieseconds = ms
}
constructor(years: Int, months: Int, days: Int, hours: Int, minutes: Int, seconds: Int)
: this(DateData(years, months, days), TimeofDayData(hours, minutes, seconds))
companion object {
fun parse(str: String): DateAndTimeData {
val (_, _, value) = split(str)
val a = value.substring(0, "yyyy-mm-dd".length)
val b = value.substring("yyyy-mm-dd-".length)
val date = DateData.parse(a)
val tod = TimeofDayData.parse(b)
return DateAndTimeData(date, tod)
}
}
}
| gpl-3.0 | 2b0afa8578ee8088fcb705409b189e3e | 24.548387 | 91 | 0.519571 | 3.78043 | false | false | false | false |
AlmasB/FXGL | fxgl-io/src/main/kotlin/com/almasb/fxgl/net/udp/UDPConnection.kt | 1 | 3683 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.net.udp
import com.almasb.fxgl.net.Connection
import com.almasb.fxgl.net.MessageHandler
import javafx.application.Platform
import java.io.*
import java.net.DatagramPacket
import java.net.DatagramSocket
import java.net.InetAddress
import java.nio.ByteBuffer
import java.util.*
import java.util.Arrays.copyOfRange
import java.util.concurrent.ArrayBlockingQueue
import java.util.function.Consumer
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class UDPConnection<T>(
private val socket: DatagramSocket,
/**
* Remote ip.
*/
val remoteIp: String,
val remotePort: Int,
/**
* This connection will never send packets with size larger than buffer size.
* Larger messages will be automatically deconstructed on this end and reconstructed on the other end.
*/
private val bufferSize: Int,
connectionNum: Int) : Connection<T>(connectionNum) {
val fullIP: String
get() = remoteIp + remotePort
private var isClosed = false
val recvQueue = ArrayBlockingQueue<ByteArray>(30)
override fun isClosedLocally(): Boolean {
return isClosed
}
override fun terminateImpl() {
isClosed = true
// send MESSAGE_CLOSE directly as it is a special message
val packet = DatagramPacket(MESSAGE_CLOSE, MESSAGE_CLOSE.size)
socket.send(packet)
}
fun sendUDP(data: ByteArray) {
// use 1st message as length (int - 4bytes) of actual 2nd message
val sizeAsByteArray = ByteBuffer.allocate(4).putInt(data.size).array()
val packet = DatagramPacket(sizeAsByteArray, 4,
InetAddress.getByName(remoteIp), remotePort
)
socket.send(packet)
if (data.size <= bufferSize) {
socket.send(
DatagramPacket(data, data.size, InetAddress.getByName(remoteIp), remotePort)
)
} else {
// deconstruct
val numChunks = data.size / bufferSize
repeat(numChunks) { index ->
val newData = copyOfRange(data, index * bufferSize, index * bufferSize + bufferSize)
socket.send(
DatagramPacket(newData, bufferSize, InetAddress.getByName(remoteIp), remotePort)
)
}
val remainderSize = data.size - numChunks * bufferSize
val remainderData = copyOfRange(data, data.size - remainderSize, data.size)
socket.send(
DatagramPacket(remainderData, remainderSize, InetAddress.getByName(remoteIp), remotePort)
)
}
}
private var messageSize = -1
private var messageBuffer = ByteArray(0)
private var currentSize = 0
internal fun receive(data: ByteArray) {
if (messageSize == -1) {
// receiving message size as a 4-byte array (aka int)
messageSize = ByteBuffer.wrap(data).int
messageBuffer = ByteArray(messageSize)
return
}
// reconstruct
// we are receiving in a fixed buffer size, but actual data size might be different
val actualDataSize = minOf(data.size, messageSize - currentSize)
System.arraycopy(data, 0, messageBuffer, currentSize, actualDataSize)
currentSize += actualDataSize
if (currentSize == messageSize) {
recvQueue.put(messageBuffer)
currentSize = 0
messageSize = -1
}
}
} | mit | 174689789df559b71918c2f85745e2ea | 26.909091 | 110 | 0.626663 | 4.69172 | false | false | false | false |
summerlly/Quiet | app/src/main/java/tech/summerly/quiet/module/common/bean/Music.kt | 1 | 3178 | /*
* Copyright (C) 2017 YangBin
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package tech.summerly.quiet.module.common.bean
import android.annotation.SuppressLint
import android.net.Uri
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import tech.summerly.quiet.extensions.CacheHelper
import java.io.File
import java.io.Serializable
/**
* author : SUMMERLY
* e-mail : [email protected]
* time : 2017/8/26
* desc : 被播放的基本单位. 所有的不管是来自本地,还是来自网络的音乐,都得转换为此对象,
* 才能被 MusicPlayerService 播放
*/
@SuppressLint("ParcelCreator")
@Suppress("unused")
@Parcelize
open class Music(
val id: Long,
val title: String,
var url: String?, //音乐的播放地址
val artist: List<Artist>,
val album: Album,
var picUrl: String?, //图片的URI地址
val type: MusicType,
var bitrate: Int = 0, //码率
val mvId: Long = 0,
val timeAdd: Long = 0,
var isFavorite: Boolean = false,
val duration: Int
) : Parcelable, Serializable, CacheHelper.CacheAble {
fun artworkUriString(): String? = when (type) {
MusicType.LOCAL -> picUrl?.let { Uri.fromFile(File(it)).toString() }
else -> Uri.parse(picUrl).toString()
}
override fun shouldCache(): Boolean = type != MusicType.LOCAL
override fun cachedName(): String {
if (type == MusicType.NETEASE) {
return requireNotNull(url.toString()?.substringAfterLast('/'))
}
TODO()
}
fun artistAlbum(): String = album.name + " - " + artistString()
fun artistString(): String = artist.joinToString(separator = Artist.separatorChar.toString()) { it.name }
fun toShortString(): String = "[$title][${artistString().replace('/', '\\')}][${album.name}]"
val picModel: Any
get() {
return url.toString()
}
@Transient
var md5: String? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other?.javaClass != javaClass) return false
other as Music
if (other.type != this.type) return false
if (other.id != this.id) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + type.hashCode()
return result
}
@Transient
var deleteAction: (() -> Boolean)? = null
} | gpl-2.0 | eb7436e873525aec16be05f9d9151172 | 28.528846 | 109 | 0.64658 | 4.039474 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/depicts/DepictEditHelper.kt | 5 | 4054 | package fr.free.nrw.commons.upload.depicts
import android.content.Context
import android.content.Intent
import android.net.Uri
import fr.free.nrw.commons.BuildConfig
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.R
import fr.free.nrw.commons.notification.NotificationHelper
import fr.free.nrw.commons.utils.ViewUtilWrapper
import fr.free.nrw.commons.wikidata.WikidataEditService
import io.reactivex.Observable
import timber.log.Timber
import javax.inject.Inject
class DepictEditHelper @Inject constructor (notificationHelper: NotificationHelper,
wikidataEditService: WikidataEditService,
viewUtilWrapper: ViewUtilWrapper) {
/**
* Class for making post operations
*/
@Inject
lateinit var wikidataEditService: WikidataEditService
/**
* Class for creating notification
*/
@Inject
lateinit var notificationHelper: NotificationHelper
/**
* Class for showing toast
*/
@Inject
lateinit var viewUtilWrapper: ViewUtilWrapper
/**
* Public interface to edit depictions
*
* @param context context
* @param media media
* @param depictions selected depictions to be added ex: ["Q12", "Q234"]
* @return Single<Boolean>
*/
fun makeDepictionEdit(
context: Context,
media: Media,
depictions: List<String>
): Observable<Boolean> {
viewUtilWrapper.showShortToast(
context,
context.getString(R.string.depictions_edit_helper_make_edit_toast)
)
return addDepiction(media, depictions)
.flatMap { result: Boolean ->
Observable.just(
showDepictionEditNotification(context, media, result)
)
}
}
/**
* Appends new depictions
*
* @param media media
* @param depictions to be added
* @return Observable<Boolean>
*/
private fun addDepiction(media: Media, depictions: List<String>): Observable<Boolean> {
Timber.d("thread is adding depiction %s", Thread.currentThread().name)
return wikidataEditService.updateDepictsProperty(media.filename, depictions)
}
/**
* Helps to create notification about condition of editing depictions
*
* @param context context
* @param media media
* @param result response of result
* @return Single<Boolean>
*/
private fun showDepictionEditNotification(
context: Context,
media: Media,
result: Boolean
): Boolean {
val message: String
var title = context.getString(R.string.depictions_edit_helper_show_edit_title)
if (result) {
title += ": " + context.getString(R.string.category_edit_helper_show_edit_title_success)
val depictsInMessage = StringBuilder()
val depictIdList = media.depictionIds
for (depiction in depictIdList) {
depictsInMessage.append(depiction)
if (depiction == depictIdList[depictIdList.size - 1]) {
continue
}
depictsInMessage.append(",")
}
message = context.resources.getQuantityString(
R.plurals.depictions_edit_helper_show_edit_message_if,
depictIdList.size,
depictsInMessage.toString()
)
} else {
title += ": " + context.getString(R.string.depictions_edit_helper_show_edit_title)
message = context.getString(R.string.depictions_edit_helper_edit_message_else)
}
val urlForFile = BuildConfig.COMMONS_URL + "/wiki/" + media.filename
val browserIntent = Intent(Intent.ACTION_VIEW, Uri.parse(urlForFile))
notificationHelper.showNotification(
context,
title,
message,
NotificationHelper.NOTIFICATION_EDIT_DEPICTIONS,
browserIntent
)
return result
}
}
| apache-2.0 | dc1ddaf95e0404da1a04b72386c24479 | 32.504132 | 100 | 0.622595 | 4.643757 | false | false | false | false |
coil-kt/coil | coil-sample-common/src/main/java/coil/sample/MainViewModel.kt | 1 | 2813 | package coil.sample
import android.app.Application
import androidx.core.graphics.toColorInt
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.viewModelScope
import coil.decode.VideoFrameDecoder.Companion.VIDEO_FRAME_MICROS_KEY
import coil.request.Parameters
import kotlin.random.Random
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okio.buffer
import okio.source
import org.json.JSONArray
class MainViewModel(application: Application) : AndroidViewModel(application) {
private val _images: MutableStateFlow<List<Image>> = MutableStateFlow(emptyList())
val images: StateFlow<List<Image>> get() = _images
val assetType: MutableStateFlow<AssetType> = MutableStateFlow(AssetType.JPG)
val screen: MutableStateFlow<Screen> = MutableStateFlow(Screen.List)
init {
viewModelScope.launch {
assetType.collect { _images.value = loadImagesAsync(it) }
}
}
fun onBackPressed() {
// Always navigate to the top-level list if this method is called.
screen.value = Screen.List
}
private suspend fun loadImagesAsync(assetType: AssetType) = withContext(Dispatchers.IO) {
if (assetType == AssetType.MP4) {
loadVideoFrames()
} else {
loadImages(assetType)
}
}
private fun loadVideoFrames(): List<Image> {
return List(200) {
val videoFrameMicros = Random.nextLong(62_000_000L)
val parameters = Parameters.Builder()
.set(VIDEO_FRAME_MICROS_KEY, videoFrameMicros)
.build()
Image(
uri = "file:///android_asset/${AssetType.MP4.fileName}",
color = randomColor(),
width = 1280,
height = 720,
parameters = parameters
)
}
}
private fun loadImages(assetType: AssetType): List<Image> {
val json = JSONArray(context.assets.open(assetType.fileName).source().buffer().readUtf8())
return List(json.length()) { index ->
val image = json.getJSONObject(index)
val url: String
val color: Int
if (assetType == AssetType.JPG) {
url = image.getJSONObject("urls").getString("regular")
color = image.getString("color").toColorInt()
} else {
url = image.getString("url")
color = randomColor()
}
Image(
uri = url,
color = color,
width = image.getInt("width"),
height = image.getInt("height")
)
}
}
}
| apache-2.0 | 13708e44996b24e6e5e0edcf99e8c971 | 31.709302 | 98 | 0.617846 | 4.719799 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/services/vip/QSTVip.kt | 1 | 2117 | package com.androidvip.hebf.services.vip
import android.annotation.TargetApi
import android.os.Build
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import com.androidvip.hebf.toast
import com.androidvip.hebf.utils.*
import com.androidvip.hebf.utils.vip.VipBatterySaverImpl
import com.androidvip.hebf.utils.vip.VipBatterySaverNutellaImpl
import com.topjohnwu.superuser.Shell
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
@TargetApi(Build.VERSION_CODES.N)
class QSTVip : TileService(), CoroutineScope {
override val coroutineContext: CoroutineContext = Dispatchers.Main + SupervisorJob()
private val vipPrefs: VipPrefs by lazy { VipPrefs(applicationContext) }
override fun onStartListening() {
val userPrefs = UserPrefs(applicationContext)
if (userPrefs.getBoolean(K.PREF.USER_HAS_ROOT, false)) {
val isEnabled = vipPrefs.getBoolean(K.PREF.VIP_ENABLED, false)
qsTile?.state = if (isEnabled) Tile.STATE_ACTIVE else Tile.STATE_INACTIVE
qsTile?.updateTile()
}
}
override fun onStopListening() {
coroutineContext[Job]?.cancelChildren()
}
override fun onClick() {
// AFTER the click, it becomes active (so, checked)
val isChecked = qsTile.state == Tile.STATE_INACTIVE
launch {
val isRooted = isRooted()
val vip = if (isRooted) {
VipBatterySaverImpl(applicationContext)
} else {
VipBatterySaverNutellaImpl(applicationContext)
}
if (isChecked) {
qsTile?.state = Tile.STATE_ACTIVE
qsTile?.updateTile()
vip.enable()
} else {
vipPrefs.putBoolean(K.PREF.VIP_SHOULD_STILL_ACTIVATE, false)
qsTile?.state = Tile.STATE_INACTIVE
qsTile?.updateTile()
vip.disable()
}
}
}
private suspend fun isRooted() = withContext(Dispatchers.Default) {
return@withContext Shell.rootAccess()
}
}
| apache-2.0 | 6ba0c0fde2ef9e7cb4c9ccf8eeeccd10 | 32.078125 | 88 | 0.653755 | 4.714922 | false | false | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/javadoc-tagargument.kt | 1 | 7250 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Javadoc.TagArgument
import org.apache.tools.ant.types.selectors.AndSelector
import org.apache.tools.ant.types.selectors.ContainsRegexpSelector
import org.apache.tools.ant.types.selectors.ContainsSelector
import org.apache.tools.ant.types.selectors.DateSelector
import org.apache.tools.ant.types.selectors.DependSelector
import org.apache.tools.ant.types.selectors.DepthSelector
import org.apache.tools.ant.types.selectors.DifferentSelector
import org.apache.tools.ant.types.selectors.ExecutableSelector
import org.apache.tools.ant.types.selectors.ExtendSelector
import org.apache.tools.ant.types.selectors.FileSelector
import org.apache.tools.ant.types.selectors.FilenameSelector
import org.apache.tools.ant.types.selectors.MajoritySelector
import org.apache.tools.ant.types.selectors.NoneSelector
import org.apache.tools.ant.types.selectors.NotSelector
import org.apache.tools.ant.types.selectors.OrSelector
import org.apache.tools.ant.types.selectors.OwnedBySelector
import org.apache.tools.ant.types.selectors.PresentSelector
import org.apache.tools.ant.types.selectors.ReadableSelector
import org.apache.tools.ant.types.selectors.SelectSelector
import org.apache.tools.ant.types.selectors.SizeSelector
import org.apache.tools.ant.types.selectors.SymlinkSelector
import org.apache.tools.ant.types.selectors.TypeSelector
import org.apache.tools.ant.types.selectors.WritableSelector
import org.apache.tools.ant.types.selectors.modifiedselector.ModifiedSelector
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
fun TagArgument._init(
dir: String?,
file: String?,
includes: String?,
excludes: String?,
includesfile: String?,
excludesfile: String?,
defaultexcludes: Boolean?,
casesensitive: Boolean?,
followsymlinks: Boolean?,
maxlevelsofsymlinks: Int?,
erroronmissingdir: Boolean?,
name: String?,
scope: String?,
enabled: Boolean?,
nested: (KTagArgument.() -> Unit)?)
{
if (dir != null)
setDir(project.resolveFile(dir))
if (file != null)
setFile(project.resolveFile(file))
if (includes != null)
setIncludes(includes)
if (excludes != null)
setExcludes(excludes)
if (includesfile != null)
setIncludesfile(project.resolveFile(includesfile))
if (excludesfile != null)
setExcludesfile(project.resolveFile(excludesfile))
if (defaultexcludes != null)
setDefaultexcludes(defaultexcludes)
if (casesensitive != null)
setCaseSensitive(casesensitive)
if (followsymlinks != null)
setFollowSymlinks(followsymlinks)
if (maxlevelsofsymlinks != null)
setMaxLevelsOfSymlinks(maxlevelsofsymlinks)
if (erroronmissingdir != null)
setErrorOnMissingDir(erroronmissingdir)
if (name != null)
setName(name)
if (scope != null)
setScope(scope)
if (enabled != null)
setEnabled(enabled)
if (nested != null)
nested(KTagArgument(this))
}
class KTagArgument(override val component: TagArgument) :
IFileSelectorNested,
ISelectSelectorNested,
IAndSelectorNested,
IOrSelectorNested,
INotSelectorNested,
INoneSelectorNested,
IMajoritySelectorNested,
IDateSelectorNested,
ISizeSelectorNested,
IDifferentSelectorNested,
IFilenameSelectorNested,
ITypeSelectorNested,
IExtendSelectorNested,
IContainsSelectorNested,
IPresentSelectorNested,
IDepthSelectorNested,
IDependSelectorNested,
IContainsRegexpSelectorNested,
IModifiedSelectorNested,
IReadableSelectorNested,
IWritableSelectorNested,
IExecutableSelectorNested,
ISymlinkSelectorNested,
IOwnedBySelectorNested
{
fun patternset(includes: String? = null, excludes: String? = null, includesfile: String? = null, excludesfile: String? = null, nested: (KPatternSet.() -> Unit)? = null) {
component.createPatternSet().apply {
component.project.setProjectReference(this)
_init(includes, excludes, includesfile, excludesfile, nested)
}
}
fun include(name: String? = null, If: String? = null, unless: String? = null) {
component.createInclude().apply {
_init(name, If, unless)
}
}
fun includesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createIncludesFile().apply {
_init(name, If, unless)
}
}
fun exclude(name: String? = null, If: String? = null, unless: String? = null) {
component.createExclude().apply {
_init(name, If, unless)
}
}
fun excludesfile(name: String? = null, If: String? = null, unless: String? = null) {
component.createExcludesFile().apply {
_init(name, If, unless)
}
}
override fun _addFileSelector(value: FileSelector) = component.add(value)
override fun _addSelectSelector(value: SelectSelector) = component.addSelector(value)
override fun _addAndSelector(value: AndSelector) = component.addAnd(value)
override fun _addOrSelector(value: OrSelector) = component.addOr(value)
override fun _addNotSelector(value: NotSelector) = component.addNot(value)
override fun _addNoneSelector(value: NoneSelector) = component.addNone(value)
override fun _addMajoritySelector(value: MajoritySelector) = component.addMajority(value)
override fun _addDateSelector(value: DateSelector) = component.addDate(value)
override fun _addSizeSelector(value: SizeSelector) = component.addSize(value)
override fun _addDifferentSelector(value: DifferentSelector) = component.addDifferent(value)
override fun _addFilenameSelector(value: FilenameSelector) = component.addFilename(value)
override fun _addTypeSelector(value: TypeSelector) = component.addType(value)
override fun _addExtendSelector(value: ExtendSelector) = component.addCustom(value)
override fun _addContainsSelector(value: ContainsSelector) = component.addContains(value)
override fun _addPresentSelector(value: PresentSelector) = component.addPresent(value)
override fun _addDepthSelector(value: DepthSelector) = component.addDepth(value)
override fun _addDependSelector(value: DependSelector) = component.addDepend(value)
override fun _addContainsRegexpSelector(value: ContainsRegexpSelector) = component.addContainsRegexp(value)
override fun _addModifiedSelector(value: ModifiedSelector) = component.addModified(value)
override fun _addReadableSelector(value: ReadableSelector) = component.addReadable(value)
override fun _addWritableSelector(value: WritableSelector) = component.addWritable(value)
override fun _addExecutableSelector(value: ExecutableSelector) = component.addExecutable(value)
override fun _addSymlinkSelector(value: SymlinkSelector) = component.addSymlink(value)
override fun _addOwnedBySelector(value: OwnedBySelector) = component.addOwnedBy(value)
}
| apache-2.0 | 3e9de7dddc9056792d3c6a00e9b20995 | 40.428571 | 171 | 0.775034 | 3.87908 | false | false | false | false |
fabmax/calculator | app/src/main/kotlin/de/fabmax/calc/Animation.kt | 1 | 4035 | package de.fabmax.calc
import de.fabmax.lightgl.util.GlMath
/**
* Helper class for animating stuff.
*/
open class Animation<T>(start: T, end: T, value: T, mix: (f: Float, a: T, b: T, value: T) -> T) {
private val mMixFun = mix
protected var mStart: T = start
protected var mEnd: T = end
protected var mValue: T = value
private var mStartT = 0L
private var mDurationT = 0f
private var mSmooth = false
var isDone = true
private set
var whenDone: (() -> Unit)? = null
/**
* Swaps start and end values. Animation is not yet started.
*/
open fun reverse(): Animation<T> {
val start = mStart
val end = mEnd
set(end, start)
return this
}
/**
* Sets the given start and end values. Animation is not yet started.
*/
open fun set(start: T, end: T): Animation<T> {
this.mStart = start
this.mEnd = end
mix(0f)
return this
}
/**
* Changes the end value.
*/
open fun change(end: T): Animation<T> {
this.mStart = this.mValue
this.mEnd = end
return this
}
/**
* Starts the animation with the given duration and without any smoothing.
*/
fun start(duration: Float): Animation<T> {
return start(duration, false)
}
/**
* Starts the animation with the given duration. If smooth is true the animation will use
* a cosine smoothing, otherwise it's linear.
*/
fun start(duration: Float, smooth: Boolean): Animation<T> {
this.mSmooth = smooth
mDurationT = duration
mStartT = System.currentTimeMillis()
isDone = false
return this
}
/**
* Updates the animated value.
*/
fun animate(): T {
if (!isDone) {
val t = System.currentTimeMillis()
val secs = (t - mStartT).toFloat() / 1000.0f
var p = 1f;
if (mDurationT > 0.001f) {
p = GlMath.clamp(secs / mDurationT, 0f, 1f)
}
if (mSmooth) {
p = (1f - Math.cos(p * Math.PI).toFloat()) / 2f
}
mix(p)
if (secs >= mDurationT) {
isDone = true
whenDone?.invoke()
}
}
return mValue
}
protected fun mix(p: Float) {
val f = GlMath.clamp(p, 0f, 1f)
mValue = mMixFun(f, mStart, mEnd, mValue)
}
}
/**
* FloatAnimation animates a scalar float value.
*/
class FloatAnimation : Animation<Float>(0f, 0f, 0f, { f, a, b, v -> a*(1-f) + b*f })
/**
* Vec3fAnimation animates a 3-dimensional float vector.
*/
class Vec3fAnimation : Animation<Vec3f>(Vec3f(), Vec3f(), Vec3f(), { f, a, b, v ->
v.x = a.x * (1-f) + b.x * f
v.y = a.y * (1-f) + b.y * f
v.z = a.z * (1-f) + b.z * f
v
}) {
fun set(startX: Float, startY: Float, startZ: Float, endX: Float, endY: Float, endZ: Float):
Vec3fAnimation {
mStart.set(startX, startY, startZ)
mEnd.set(endX, endY, endZ)
mix(0f)
return this
}
override fun set(start: Vec3f, end: Vec3f): Animation<Vec3f> {
mStart.set(start)
mEnd.set(end)
mix(0f)
return this
}
fun change(endX: Float, endY: Float, endZ: Float): Vec3fAnimation {
mStart.set(mValue)
mEnd.set(endX, endY, endZ)
return this
}
override fun change(end: Vec3f): Animation<Vec3f> {
mStart.set(mValue)
mEnd.set(end)
return this
}
override fun reverse(): Animation<Vec3f> {
mValue.set(mEnd)
mEnd.set(mStart)
mStart.set(mValue)
return this
}
}
class Vec3f(x: Float, y: Float, z: Float) {
var x = x
var y = y
var z = z
constructor() : this(0f, 0f, 0f)
fun set(v: Vec3f) {
x = v.x
y = v.y
z = v.z
}
fun set(x: Float, y: Float, z: Float) {
this.x = x;
this.y = y;
this.z = z;
}
} | apache-2.0 | 85a0c6888b2a1c59e5d0543c6ddd2ad8 | 22.465116 | 97 | 0.527881 | 3.393608 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/annotator/RsExpressionAnnotator.kt | 2 | 4235 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.psi.PsiElement
import com.intellij.util.SmartList
import org.rust.ide.annotator.fixes.AddStructFieldsFix
import org.rust.ide.intentions.RemoveParenthesesFromExprIntention
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import java.util.*
class RsExpressionAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
element.accept(RedundantParenthesisVisitor(holder))
if (element is RsStructLiteral) {
val decl = element.path.reference.resolve() as? RsFieldsOwner
if (decl != null) {
checkStructLiteral(holder, decl, element)
}
}
}
private fun checkStructLiteral(
holder: AnnotationHolder,
decl: RsFieldsOwner,
literal: RsStructLiteral
) {
val body = literal.structLiteralBody
body.structLiteralFieldList
.filter { it.reference.resolve() == null }
.forEach {
holder.createErrorAnnotation(it.identifier, "No such field")
.highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
}
for (field in body.structLiteralFieldList.findDuplicateReferences()) {
holder.createErrorAnnotation(field.identifier, "Duplicate field")
}
if (body.dotdot != null) return // functional update, no need to declare all the fields.
if (decl is RsStructItem && decl.kind == RsStructKind.UNION) {
if (body.structLiteralFieldList.size > 1) {
holder.createErrorAnnotation(body, "Union expressions should have exactly one field")
}
} else {
if (calculateMissingFields(body, decl).isNotEmpty()) {
val structNameRange = literal.descendantOfTypeStrict<RsPath>()?.textRange
if (structNameRange != null) {
val annotation = holder.createErrorAnnotation(structNameRange, "Some fields are missing")
annotation.registerFix(AddStructFieldsFix(literal), body.parent.textRange)
annotation.registerFix(AddStructFieldsFix(literal, recursive = true), body.parent.textRange)
}
}
}
}
}
private class RedundantParenthesisVisitor(private val holder: AnnotationHolder) : RsVisitor() {
override fun visitCondition(o: RsCondition) =
o.expr.warnIfParens("Predicate expression has unnecessary parentheses")
override fun visitRetExpr(o: RsRetExpr) =
o.expr.warnIfParens("Return expression has unnecessary parentheses")
override fun visitMatchExpr(o: RsMatchExpr) =
o.expr.warnIfParens("Match expression has unnecessary parentheses")
override fun visitForExpr(o: RsForExpr) =
o.expr.warnIfParens("For loop expression has unnecessary parentheses")
override fun visitParenExpr(o: RsParenExpr) =
o.expr.warnIfParens("Redundant parentheses in expression")
private fun RsExpr?.warnIfParens(message: String) {
if (this !is RsParenExpr) return
val fix = RemoveParenthesesFromExprIntention()
if (fix.isAvailable(this))
holder.createWeakWarningAnnotation(this, message)
.registerFix(RemoveParenthesesFromExprIntention())
}
}
private fun <T : RsReferenceElement> Collection<T>.findDuplicateReferences(): Collection<T> {
val names = HashSet<String>(size)
val result = SmartList<T>()
for (item in this) {
val name = item.referenceName
if (name in names) {
result += item
}
names += name
}
return result
}
fun calculateMissingFields(expr: RsStructLiteralBody, decl: RsFieldsOwner): List<RsFieldDecl> {
val declaredFields = expr.structLiteralFieldList.map { it.referenceName }.toSet()
return decl.namedFields.filter { it.name !in declaredFields && !it.queryAttributes.hasCfgAttr() }
}
| mit | 972651049c3f0b4fb2049b3dc1755caa | 37.5 | 112 | 0.676505 | 4.648738 | false | false | false | false |
ze-pequeno/okhttp | okhttp/src/jvmMain/kotlin/okhttp3/internal/http2/Http2ExchangeCodec.kt | 2 | 7044 | /*
* Copyright (C) 2012 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 okhttp3.internal.http2
import java.io.IOException
import java.net.ProtocolException
import java.util.Locale
import java.util.concurrent.TimeUnit
import okhttp3.Headers
import okhttp3.OkHttpClient
import okhttp3.Protocol
import okhttp3.Request
import okhttp3.Response
import okhttp3.internal.headersContentLength
import okhttp3.internal.http.ExchangeCodec
import okhttp3.internal.http.ExchangeCodec.Carrier
import okhttp3.internal.http.HTTP_CONTINUE
import okhttp3.internal.http.RealInterceptorChain
import okhttp3.internal.http.RequestLine
import okhttp3.internal.http.StatusLine
import okhttp3.internal.http.promisesBody
import okhttp3.internal.http2.Header.Companion.RESPONSE_STATUS_UTF8
import okhttp3.internal.http2.Header.Companion.TARGET_AUTHORITY
import okhttp3.internal.http2.Header.Companion.TARGET_AUTHORITY_UTF8
import okhttp3.internal.http2.Header.Companion.TARGET_METHOD
import okhttp3.internal.http2.Header.Companion.TARGET_METHOD_UTF8
import okhttp3.internal.http2.Header.Companion.TARGET_PATH
import okhttp3.internal.http2.Header.Companion.TARGET_PATH_UTF8
import okhttp3.internal.http2.Header.Companion.TARGET_SCHEME
import okhttp3.internal.http2.Header.Companion.TARGET_SCHEME_UTF8
import okhttp3.internal.immutableListOf
import okio.Sink
import okio.Source
/** Encode requests and responses using HTTP/2 frames. */
class Http2ExchangeCodec(
client: OkHttpClient,
override val carrier: Carrier,
private val chain: RealInterceptorChain,
private val http2Connection: Http2Connection
) : ExchangeCodec {
@Volatile private var stream: Http2Stream? = null
private val protocol: Protocol = if (Protocol.H2_PRIOR_KNOWLEDGE in client.protocols) {
Protocol.H2_PRIOR_KNOWLEDGE
} else {
Protocol.HTTP_2
}
@Volatile
private var canceled = false
override fun createRequestBody(request: Request, contentLength: Long): Sink {
return stream!!.getSink()
}
override fun writeRequestHeaders(request: Request) {
if (stream != null) return
val hasRequestBody = request.body != null
val requestHeaders = http2HeadersList(request)
stream = http2Connection.newStream(requestHeaders, hasRequestBody)
// We may have been asked to cancel while creating the new stream and sending the request
// headers, but there was still no stream to close.
if (canceled) {
stream!!.closeLater(ErrorCode.CANCEL)
throw IOException("Canceled")
}
stream!!.readTimeout().timeout(chain.readTimeoutMillis.toLong(), TimeUnit.MILLISECONDS)
stream!!.writeTimeout().timeout(chain.writeTimeoutMillis.toLong(), TimeUnit.MILLISECONDS)
}
override fun flushRequest() {
http2Connection.flush()
}
override fun finishRequest() {
stream!!.getSink().close()
}
override fun readResponseHeaders(expectContinue: Boolean): Response.Builder? {
val stream = stream ?: throw IOException("stream wasn't created")
val headers = stream.takeHeaders(callerIsIdle = expectContinue)
val responseBuilder = readHttp2HeadersList(headers, protocol)
return if (expectContinue && responseBuilder.code == HTTP_CONTINUE) {
null
} else {
responseBuilder
}
}
override fun reportedContentLength(response: Response): Long {
return when {
!response.promisesBody() -> 0L
else -> response.headersContentLength()
}
}
override fun openResponseBodySource(response: Response): Source {
return stream!!.source
}
override fun trailers(): Headers {
return stream!!.trailers()
}
override fun cancel() {
canceled = true
stream?.closeLater(ErrorCode.CANCEL)
}
companion object {
private const val CONNECTION = "connection"
private const val HOST = "host"
private const val KEEP_ALIVE = "keep-alive"
private const val PROXY_CONNECTION = "proxy-connection"
private const val TRANSFER_ENCODING = "transfer-encoding"
private const val TE = "te"
private const val ENCODING = "encoding"
private const val UPGRADE = "upgrade"
/** See http://tools.ietf.org/html/draft-ietf-httpbis-http2-09#section-8.1.3. */
private val HTTP_2_SKIPPED_REQUEST_HEADERS = immutableListOf(
CONNECTION,
HOST,
KEEP_ALIVE,
PROXY_CONNECTION,
TE,
TRANSFER_ENCODING,
ENCODING,
UPGRADE,
TARGET_METHOD_UTF8,
TARGET_PATH_UTF8,
TARGET_SCHEME_UTF8,
TARGET_AUTHORITY_UTF8)
private val HTTP_2_SKIPPED_RESPONSE_HEADERS = immutableListOf(
CONNECTION,
HOST,
KEEP_ALIVE,
PROXY_CONNECTION,
TE,
TRANSFER_ENCODING,
ENCODING,
UPGRADE)
fun http2HeadersList(request: Request): List<Header> {
val headers = request.headers
val result = ArrayList<Header>(headers.size + 4)
result.add(Header(TARGET_METHOD, request.method))
result.add(Header(TARGET_PATH, RequestLine.requestPath(request.url)))
val host = request.header("Host")
if (host != null) {
result.add(Header(TARGET_AUTHORITY, host)) // Optional.
}
result.add(Header(TARGET_SCHEME, request.url.scheme))
for (i in 0 until headers.size) {
// header names must be lowercase.
val name = headers.name(i).lowercase(Locale.US)
if (name !in HTTP_2_SKIPPED_REQUEST_HEADERS ||
name == TE && headers.value(i) == "trailers") {
result.add(Header(name, headers.value(i)))
}
}
return result
}
/** Returns headers for a name value block containing an HTTP/2 response. */
fun readHttp2HeadersList(headerBlock: Headers, protocol: Protocol): Response.Builder {
var statusLine: StatusLine? = null
val headersBuilder = Headers.Builder()
for (i in 0 until headerBlock.size) {
val name = headerBlock.name(i)
val value = headerBlock.value(i)
if (name == RESPONSE_STATUS_UTF8) {
statusLine = StatusLine.parse("HTTP/1.1 $value")
} else if (name !in HTTP_2_SKIPPED_RESPONSE_HEADERS) {
headersBuilder.addLenient(name, value)
}
}
if (statusLine == null) throw ProtocolException("Expected ':status' header not present")
return Response.Builder()
.protocol(protocol)
.code(statusLine.code)
.message(statusLine.message)
.headers(headersBuilder.build())
.trailers { error("trailers not available") }
}
}
}
| apache-2.0 | 4c3642a37667bb36ad42ad46cd04e138 | 33.529412 | 94 | 0.706417 | 4.168047 | false | false | false | false |
android/camera-samples | CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/MainActivity.kt | 1 | 3969 | /*
* 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
*
* 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.android.example.cameraxbasic
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.KeyEvent
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.WindowInsetsControllerCompat
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import com.android.example.cameraxbasic.databinding.ActivityMainBinding
import java.io.File
const val KEY_EVENT_ACTION = "key_event_action"
const val KEY_EVENT_EXTRA = "key_event_extra"
private const val IMMERSIVE_FLAG_TIMEOUT = 500L
/**
* Main entry point into our app. This app follows the single-activity pattern, and all
* functionality is implemented in the form of fragments.
*/
class MainActivity : AppCompatActivity() {
private lateinit var activityMainBinding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
activityMainBinding = ActivityMainBinding.inflate(layoutInflater)
setContentView(activityMainBinding.root)
}
override fun onResume() {
super.onResume()
// Before setting full screen flags, we must wait a bit to let UI settle; otherwise, we may
// be trying to set app to immersive mode before it's ready and the flags do not stick
activityMainBinding.fragmentContainer.postDelayed({
hideSystemUI()
}, IMMERSIVE_FLAG_TIMEOUT)
}
/** When key down event is triggered, relay it via local broadcast so fragments can handle it */
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
return when (keyCode) {
KeyEvent.KEYCODE_VOLUME_DOWN -> {
val intent = Intent(KEY_EVENT_ACTION).apply { putExtra(KEY_EVENT_EXTRA, keyCode) }
LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
true
}
else -> super.onKeyDown(keyCode, event)
}
}
override fun onBackPressed() {
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.Q) {
// Workaround for Android Q memory leak issue in IRequestFinishCallback$Stub.
// (https://issuetracker.google.com/issues/139738913)
finishAfterTransition()
} else {
super.onBackPressed()
}
}
companion object {
/** Use external media if it is available, our app's file directory otherwise */
fun getOutputDirectory(context: Context): File {
val appContext = context.applicationContext
val mediaDir = context.externalMediaDirs.firstOrNull()?.let {
File(it, appContext.resources.getString(R.string.app_name)).apply { mkdirs() } }
return if (mediaDir != null && mediaDir.exists())
mediaDir else appContext.filesDir
}
}
private fun hideSystemUI() {
WindowCompat.setDecorFitsSystemWindows(window, false)
WindowInsetsControllerCompat(window, activityMainBinding.fragmentContainer).let { controller ->
controller.hide(WindowInsetsCompat.Type.systemBars())
controller.systemBarsBehavior = WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
}
| apache-2.0 | 9aed8e27632286d3b15ab0a5bd11c2be | 38.69 | 110 | 0.702696 | 4.869939 | false | false | false | false |
CarrotCodes/Warren | src/main/kotlin/chat/willow/warren/extension/away_notify/AwayHandler.kt | 1 | 1106 | package chat.willow.warren.extension.away_notify
import chat.willow.kale.IMetadataStore
import chat.willow.kale.KaleHandler
import chat.willow.kale.irc.message.extension.away_notify.AwayMessage
import chat.willow.warren.helper.loggerFor
import chat.willow.warren.state.JoinedChannelsState
class AwayHandler(val channelsState: JoinedChannelsState) : KaleHandler<AwayMessage.Message>(AwayMessage.Message.Parser) {
private val LOGGER = loggerFor<AwayHandler>()
override fun handle(message: AwayMessage.Message, metadata: IMetadataStore) {
val nick = message.source.nick
val awayMessage = message.message
for ((name, channel) in channelsState.all) {
val user = channel.users[nick]
if (user != null) {
channel.users -= nick
channel.users += user.copy(awayMessage = awayMessage)
}
}
if (awayMessage == null) {
LOGGER.trace("user is no longer away: ${message.source}")
} else {
LOGGER.trace("user is away: ${message.source} '$awayMessage'")
}
}
} | isc | 3599e513edb9b1321339cfee447be366 | 33.59375 | 122 | 0.666365 | 4.189394 | false | false | false | false |
SUPERCILEX/Robot-Scouter | feature/templates/src/main/java/com/supercilex/robotscouter/feature/templates/viewholder/SpinnerTemplateViewHolder.kt | 1 | 9746 | package com.supercilex.robotscouter.feature.templates.viewholder
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.supercilex.robotscouter.core.LateinitVal
import com.supercilex.robotscouter.core.data.model.update
import com.supercilex.robotscouter.core.data.model.updateSelectedValueId
import com.supercilex.robotscouter.core.model.Metric
import com.supercilex.robotscouter.core.ui.RecyclerPoolHolder
import com.supercilex.robotscouter.core.ui.getDrawableCompat
import com.supercilex.robotscouter.core.ui.longSnackbar
import com.supercilex.robotscouter.core.ui.notifyItemsNoChangeAnimation
import com.supercilex.robotscouter.core.ui.showKeyboard
import com.supercilex.robotscouter.core.ui.snackbar
import com.supercilex.robotscouter.core.ui.swap
import com.supercilex.robotscouter.core.unsafeLazy
import com.supercilex.robotscouter.feature.templates.R
import com.supercilex.robotscouter.shared.scouting.MetricListFragment
import com.supercilex.robotscouter.shared.scouting.MetricViewHolderBase
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.scout_template_base_reorder.*
import kotlinx.android.synthetic.main.scout_template_spinner.*
import kotlinx.android.synthetic.main.scout_template_spinner_item.*
import java.util.Collections
import kotlin.properties.Delegates
import com.supercilex.robotscouter.R as RC
internal class SpinnerTemplateViewHolder(
itemView: View,
fragment: MetricListFragment
) : MetricViewHolderBase<Metric.List, List<Metric.List.Item>>(itemView),
MetricTemplateViewHolder<Metric.List, List<Metric.List.Item>>, View.OnClickListener {
override val reorderView: ImageView by unsafeLazy { reorder }
override val nameEditor = name as EditText
private val itemTouchCallback = ItemTouchCallback()
private val itemsAdapter = Adapter()
init {
init()
newItem.setOnClickListener(this)
items.adapter = itemsAdapter
items.setRecycledViewPool(
(fragment.requireParentFragment() as RecyclerPoolHolder).recyclerPool)
val itemTouchHelper = ItemTouchHelper(itemTouchCallback)
itemTouchCallback.itemTouchHelper = itemTouchHelper
itemTouchHelper.attachToRecyclerView(items)
}
override fun bind() {
super.bind()
itemsAdapter.notifyDataSetChanged()
}
override fun onClick(v: View) {
val position = metric.value.size
metric.update(mutableListOf(
*getLatestItems().toTypedArray(),
Metric.List.Item(metric.ref.parent.document().id, "")
))
itemTouchCallback.pendingScrollPosition = position
itemsAdapter.notifyItemInserted(position)
}
private fun getLatestItems(): List<Metric.List.Item> {
val rv = items
var items: List<Metric.List.Item> = metric.value
for (i in 0 until itemsAdapter.itemCount) {
val holder = rv.findViewHolderForAdapterPosition(i) as ItemHolder?
items = (holder ?: continue).getUpdatedItems(items)
}
return items
}
private inner class Adapter : RecyclerView.Adapter<ItemHolder>() {
override fun getItemCount() = metric.value.size
override fun getItemViewType(position: Int) = ITEM_TYPE
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = ItemHolder(
LayoutInflater.from(parent.context)
.inflate(R.layout.scout_template_spinner_item, parent, false)
)
override fun onBindViewHolder(holder: ItemHolder, position: Int) {
val item = itemTouchCallback.getItem(position)
holder.bind(this@SpinnerTemplateViewHolder, item, metric.selectedValueId == item.id)
itemTouchCallback.onBind(holder)
}
}
private class ItemHolder(
override val containerView: View
) : RecyclerView.ViewHolder(containerView), LayoutContainer,
TemplateViewHolder, View.OnClickListener {
override val reorderView: ImageView by unsafeLazy { reorder }
override val nameEditor: EditText = itemView.findViewById(RC.id.name)
private lateinit var parent: SpinnerTemplateViewHolder
private lateinit var item: Metric.List.Item
private var isDefault: Boolean by Delegates.notNull()
init {
init()
defaultView.setOnClickListener(this)
delete.setOnClickListener(this)
defaultView.setImageDrawable(itemView.context.getDrawableCompat(R.drawable.ic_default_24dp))
}
fun bind(parent: SpinnerTemplateViewHolder, item: Metric.List.Item, isDefault: Boolean) {
this.parent = parent
this.item = item
this.isDefault = isDefault
nameEditor.setText(item.name)
defaultView.isActivated = isDefault
}
override fun onClick(v: View) {
val items = parent.getLatestItems()
when (val id = v.id) {
R.id.defaultView -> updateDefaultStatus(items)
R.id.delete -> delete(items)
else -> error("Unknown id: $id")
}
}
private fun updateDefaultStatus(items: List<Metric.List.Item>) {
if (isDefault) {
itemView.snackbar(R.string.metric_spinner_item_default_required_error)
return
}
val metric = parent.metric
val oldDefaultId = metric.selectedValueId
metric.updateSelectedValueId(item.id)
parent.items.notifyItemsNoChangeAnimation {
parent.items.setHasFixedSize(true)
notifyItemChanged(items.indexOfFirst { it.id == oldDefaultId }.let {
if (it == -1) 0 else it
})
notifyItemChanged(adapterPosition)
parent.items.setHasFixedSize(false)
}
}
private fun delete(items: List<Metric.List.Item>) {
val position = items.indexOfFirst { it.id == item.id }
if (position == -1) return
parent.metric.update(items.toMutableList().apply {
removeAt(position)
})
parent.itemsAdapter.notifyItemRemoved(position)
itemView.longSnackbar(RC.string.deleted, RC.string.undo) {
parent.metric.update(parent.metric.value.toMutableList().apply {
val item = items[position]
if (position <= size) add(position, item) else add(item)
})
parent.itemsAdapter.notifyItemInserted(position)
}
}
override fun onFocusChange(v: View, hasFocus: Boolean) {
val metric = parent.metric
if (
!hasFocus && v === nameEditor && adapterPosition != -1 &&
metric.value.any { it.id == item.id }
) metric.update(getUpdatedItems(metric.value))
}
fun getUpdatedItems(
value: List<Metric.List.Item>
): List<Metric.List.Item> = value.toMutableList().apply {
this[adapterPosition] = item.copy(name = nameEditor.text.toString()).also {
item = it
}
}
}
private inner class ItemTouchCallback : ItemTouchHelper.SimpleCallback(
ItemTouchHelper.UP or ItemTouchHelper.DOWN,
0
) {
var itemTouchHelper: ItemTouchHelper by LateinitVal()
var pendingScrollPosition: Int = RecyclerView.NO_POSITION
private var localItems: MutableList<Metric.List.Item>? = null
fun getItem(position: Int): Metric.List.Item =
if (localItems == null) metric.value[position] else checkNotNull(localItems)[position]
fun onBind(viewHolder: ItemHolder) {
viewHolder.enableDragToReorder(viewHolder, itemTouchHelper)
if (viewHolder.adapterPosition == pendingScrollPosition) {
viewHolder.requestFocus()
viewHolder.nameEditor.let { it.post { it.showKeyboard() } }
pendingScrollPosition = RecyclerView.NO_POSITION
}
}
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
var localItems = localItems
if (localItems == null) {
// Force a focus on any potential text input to get the most up-to-date data
nameEditor.requestFocus()
nameEditor.clearFocus()
localItems = metric.value.toMutableList()
this.localItems = localItems
items.setHasFixedSize(true)
}
itemsAdapter.swap(viewHolder, target) { i, j ->
Collections.swap(localItems, i, j)
}
return true
}
override fun clearView(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder) {
super.clearView(recyclerView, viewHolder)
items.setHasFixedSize(false)
localItems?.let {
metric.update(it)
localItems = null
}
}
override fun isLongPressDragEnabled() = false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int): Unit =
throw UnsupportedOperationException()
}
private companion object {
const val ITEM_TYPE = 2000
}
}
| gpl-3.0 | f3d517bc43df8007437479491cb5e083 | 38.298387 | 104 | 0.647342 | 5.07076 | false | false | false | false |
drmashu/dikon | buri/src/main/kotlin/io/github/drmashu/buri/BuriRunner.kt | 1 | 1689 | package io.github.drmashu.buri
import io.github.drmashu.dikon.Dikon
import io.github.drmashu.dikon.Factory
import org.eclipse.jetty.http2.server.HTTP2CServerConnectionFactory
import org.eclipse.jetty.server.HttpConfiguration
import org.eclipse.jetty.server.HttpConnectionFactory
import org.eclipse.jetty.server.Server
import org.eclipse.jetty.server.ServerConnector
import org.eclipse.jetty.server.handler.ResourceHandler
import org.eclipse.jetty.servlet.ServletContextHandler
import org.eclipse.jetty.servlet.ServletHolder
import org.eclipse.jetty.util.resource.Resource
/**
* Buri ランナークラス.
* @author NAGASAWA Takahiro<[email protected]>
* @param buri buri本体(を設定までしたサブクラス)
*/
public class BuriRunner(val buri: Buri) {
/**
* サーバ起動
* @param portNo ポート番号
*/
public fun start(portNo: Int) {
val server = Server()
var httpConf = HttpConfiguration();
var http1 = HttpConnectionFactory(httpConf);
var http2c = HTTP2CServerConnectionFactory(httpConf);
val connector = ServerConnector(server)
connector.port = portNo
connector.addConnectionFactory(http1)
connector.addConnectionFactory(http2c)
server.connectors = arrayOf(connector)
val servletContextHandler = ServletContextHandler()
servletContextHandler.contextPath = "/"
servletContextHandler.resourceBase = "./"
val holder = ServletHolder(buri)
servletContextHandler.addServlet(holder, "/*")
server.handler = servletContextHandler
server.isDumpBeforeStop = true
server.start()
server.join()
}
}
| apache-2.0 | 4cdc50ba17904b6e6e7c5ee5575f7372 | 29.698113 | 67 | 0.72649 | 3.977995 | false | false | false | false |
tinypass/piano-sdk-for-android | composer/src/main/java/io/piano/android/composer/EventJsonAdapterFactory.kt | 1 | 8356 | package io.piano.android.composer
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import com.squareup.moshi.internal.Util
import io.piano.android.composer.model.Event
import io.piano.android.composer.model.EventExecutionContext
import io.piano.android.composer.model.EventModuleParams
import io.piano.android.composer.model.events.EventType
import io.piano.android.composer.model.events.ExperienceExecute
import io.piano.android.composer.model.events.Meter
import io.piano.android.composer.model.events.NonSite
import io.piano.android.composer.model.events.SetResponseVariable
import io.piano.android.composer.model.events.ShowForm
import io.piano.android.composer.model.events.ShowLogin
import io.piano.android.composer.model.events.ShowRecommendations
import io.piano.android.composer.model.events.ShowTemplate
import io.piano.android.composer.model.events.UserSegment
import java.lang.reflect.Type
class EventJsonAdapterFactory : JsonAdapter.Factory {
override fun create(type: Type, annotations: MutableSet<out Annotation>, moshi: Moshi): JsonAdapter<*>? =
takeIf { Event::class.java.isAssignableFrom(Types.getRawType(type)) }?.run {
EventJsonAdapter(
moshi.adapter(EventModuleParams::class.java),
moshi.adapter(EventExecutionContext::class.java),
listOf(
moshi.adapter(ExperienceExecute::class.java),
DelegateAdapter(moshi.adapter(Meter::class.java)) { copy(state = Meter.MeterState.ACTIVE) },
DelegateAdapter(moshi.adapter(Meter::class.java)) { copy(state = Meter.MeterState.EXPIRED) },
StubAdapter { NonSite },
moshi.adapter(SetResponseVariable::class.java),
moshi.adapter(ShowForm::class.java),
moshi.adapter(ShowLogin::class.java),
moshi.adapter(ShowRecommendations::class.java),
moshi.adapter(ShowTemplate::class.java),
StubAdapter { UserSegment(true) },
StubAdapter { UserSegment(false) }
)
).nullSafe()
}
private class StubAdapter<T>(private val stubFunction: () -> T) : JsonAdapter<T>() {
override fun fromJson(reader: JsonReader): T = stubFunction().also { reader.skipValue() }
override fun toJson(writer: JsonWriter, value: T?) {
TODO("Not supported")
}
}
private class DelegateAdapter<T>(
private val delegateAdapter: JsonAdapter<T>,
private val postProcessAction: T.() -> T
) : JsonAdapter<T>() {
override fun fromJson(reader: JsonReader): T? = delegateAdapter.fromJson(reader)?.run(postProcessAction)
override fun toJson(writer: JsonWriter, value: T?) = delegateAdapter.toJson(writer, value)
}
class EventJsonAdapter(
private val eventModuleParamsAdapter: JsonAdapter<EventModuleParams>,
private val eventExecutionContextAdapter: JsonAdapter<EventExecutionContext>,
private val eventDataAdapters: List<JsonAdapter<out EventType>>
) : JsonAdapter<Event<*>>() {
private val options = JsonReader.Options.of(
EVENT_MODULE_PARAMS,
EVENT_EXECUTION_CONTEXT,
EVENT_PARAMS
)
private val eventTypeKeyOptions = JsonReader.Options.of(EVENT_TYPE)
private val eventSubtypesOptions = JsonReader.Options.of(
EVENT_TYPE_EXPERIENCE_EXECUTE,
EVENT_TYPE_METER_ACTIVE,
EVENT_TYPE_METER_EXPIRED,
EVENT_TYPE_NON_SITE,
EVENT_TYPE_SET_RESPONSE_VARIABLE,
EVENT_TYPE_SHOW_FORM,
EVENT_TYPE_SHOW_LOGIN,
EVENT_TYPE_SHOW_RECOMMENDATIONS,
EVENT_TYPE_SHOW_TEMPLATE,
EVENT_TYPE_USER_SEGMENT_TRUE,
EVENT_TYPE_USER_SEGMENT_FALSE
)
override fun fromJson(reader: JsonReader): Event<*>? {
var eventModuleParams: EventModuleParams? = null
var eventExecutionContext: EventExecutionContext? = null
var eventData: EventType? = null
val eventType = reader.peekJson().use {
it.setFailOnUnknown(false)
it.findEventType()
}
return with(reader) {
beginObject()
while (hasNext()) {
when (selectName(options)) {
0 ->
eventModuleParams = eventModuleParamsAdapter.fromJson(this)
?: throw Util.unexpectedNull(
EVENT_MODULE_PARAMS,
EVENT_MODULE_PARAMS,
this
)
1 ->
eventExecutionContext = eventExecutionContextAdapter.fromJson(this)
?: throw Util.unexpectedNull(
EVENT_EXECUTION_CONTEXT,
EVENT_EXECUTION_CONTEXT,
this
)
2 ->
eventData = eventDataAdapters[eventType].fromJson(this)
?: throw Util.unexpectedNull(
EVENT_PARAMS,
EVENT_PARAMS,
this
)
-1 -> {
skipName()
skipValue()
}
}
}
endObject()
Event(
eventModuleParams ?: throw Util.missingProperty(
EVENT_MODULE_PARAMS,
EVENT_MODULE_PARAMS,
this
),
eventExecutionContext ?: throw Util.missingProperty(
EVENT_EXECUTION_CONTEXT,
EVENT_EXECUTION_CONTEXT,
this
),
eventData ?: throw Util.missingProperty(
EVENT_PARAMS,
EVENT_PARAMS,
this
)
)
}
}
private fun JsonReader.findEventType(): Int {
beginObject()
while (hasNext()) {
if (selectName(eventTypeKeyOptions) == -1) {
skipName()
skipValue()
continue
}
return selectString(eventSubtypesOptions).takeIf { it != -1 } ?: throw JsonDataException(
"Unknown event type '${nextString()}', expected one of $eventSubtypesOptions"
)
}
throw JsonDataException("Can't find key $EVENT_TYPE in json")
}
override fun toJson(writer: JsonWriter, value: Event<*>?) {
TODO("Not supported")
}
}
companion object {
private const val EVENT_MODULE_PARAMS = "eventModuleParams"
private const val EVENT_EXECUTION_CONTEXT = "eventExecutionContext"
private const val EVENT_PARAMS = "eventParams"
private const val EVENT_TYPE = "eventType"
private const val EVENT_TYPE_SHOW_LOGIN = "showLogin"
private const val EVENT_TYPE_METER_ACTIVE = "meterActive"
private const val EVENT_TYPE_METER_EXPIRED = "meterExpired"
private const val EVENT_TYPE_USER_SEGMENT_TRUE = "userSegmentTrue"
private const val EVENT_TYPE_USER_SEGMENT_FALSE = "userSegmentFalse"
private const val EVENT_TYPE_EXPERIENCE_EXECUTE = "experienceExecute"
private const val EVENT_TYPE_NON_SITE = "nonSite"
private const val EVENT_TYPE_SHOW_TEMPLATE = "showTemplate"
private const val EVENT_TYPE_SET_RESPONSE_VARIABLE = "setResponseVariable"
private const val EVENT_TYPE_SHOW_RECOMMENDATIONS = "showRecommendations"
private const val EVENT_TYPE_SHOW_FORM = "showForm"
}
}
| apache-2.0 | bec90e2d439129dac4b089c83baa4cd8 | 43.924731 | 113 | 0.565701 | 5.232311 | false | false | false | false |
vsch/idea-multimarkdown | src/main/java/com/vladsch/md/nav/editor/resources/GitHubCollapseMarkdownScriptProvider.kt | 1 | 1792 | // Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.editor.resources
import com.vladsch.md.nav.MdBundle
import com.vladsch.md.nav.MdPlugin
import com.vladsch.md.nav.editor.javafx.JavaFxHtmlPanelProvider
import com.vladsch.md.nav.editor.util.HtmlCssResource
import com.vladsch.md.nav.editor.util.HtmlScriptResource
import com.vladsch.md.nav.editor.util.HtmlScriptResourceProvider
import com.vladsch.md.nav.settings.MdPreviewSettings
object GitHubCollapseMarkdownScriptProvider : HtmlScriptResourceProvider() {
val NAME = MdBundle.message("editor.github-collapse-markdown.html.script.provider.name")
val ID = "com.vladsch.md.nav.editor.github-collapse-markdown.html.script"
override val HAS_PARENT = false
override val INFO = HtmlScriptResourceProvider.Info(ID, NAME)
override val COMPATIBILITY = JavaFxHtmlPanelProvider.COMPATIBILITY
override val scriptResource: HtmlScriptResource = GitHubCollapseMarkdownScriptResource(INFO, MdPlugin.PREVIEW_GITHUB_COLLAPSE_MARKDOWN_JS, "")
override val cssResource: HtmlCssResource = GitHubCollapseMarkdownCssProvider.cssResource
// override val cssResource: HtmlCssResource = HtmlCssResource(HtmlCssResourceProvider.Info(ID, NAME)
// , MultiMarkdownPlugin.PREVIEW_GITHUB_COLLAPSE_DARK
// , MultiMarkdownPlugin.PREVIEW_GITHUB_COLLAPSE_LIGHT
// , null)
override fun isSupportedSetting(settingName: String): Boolean {
return when (settingName) {
MdPreviewSettings.PERFORMANCE_WARNING -> true
MdPreviewSettings.EXPERIMENTAL_WARNING -> false
else -> false
}
}
}
| apache-2.0 | da6ad552ce0f99d9928ee906e0163512 | 51.705882 | 177 | 0.762277 | 4.266667 | false | false | false | false |
quarkusio/quarkus | extensions/panache/hibernate-reactive-panache-kotlin/runtime/src/test/kotlin/io/quarkus/hibernate/reactive/panache/kotlin/TestAnalogs.kt | 1 | 7258 | package io.quarkus.hibernate.reactive.panache.kotlin
import io.quarkus.gizmo.Gizmo
import io.quarkus.panache.common.deployment.ByteCodeType
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassReader.SKIP_CODE
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
import java.util.Optional
import java.util.function.Consumer
import kotlin.reflect.KClass
import io.quarkus.hibernate.reactive.panache.PanacheEntityBase as JavaPanacheEntityBase
import io.quarkus.hibernate.reactive.panache.PanacheQuery as JavaPanacheQuery
import io.quarkus.hibernate.reactive.panache.PanacheRepository as JavaPanacheRepository
import io.quarkus.hibernate.reactive.panache.PanacheRepositoryBase as JavaPanacheRepositoryBase
class TestAnalogs {
@Test
fun testPanacheQuery() {
compare(map(JavaPanacheQuery::class), map(PanacheQuery::class))
}
@Test
fun testPanacheRepository() {
compare(map(JavaPanacheRepository::class), map(PanacheRepository::class))
}
@Test
fun testPanacheRepositoryBase() {
compare(map(JavaPanacheRepositoryBase::class), map(PanacheRepositoryBase::class))
}
@Test
fun testPanacheEntityBase() {
compare(JavaPanacheEntityBase::class, PanacheEntityBase::class, PanacheCompanionBase::class)
}
private fun compare(
javaEntity: KClass<*>,
kotlinEntity: KClass<*>,
companion: KClass<*>
) {
val javaMethods = map(javaEntity).methods
val kotlinMethods = map(kotlinEntity).methods
.filterNot {
it.name.contains("getId") ||
it.name.contains("setId") ||
it.name.contains("getOperations")
}
.toMutableList()
val companionMethods = map(companion).methods
val implemented = mutableListOf<Method>()
javaMethods
.forEach {
if (!it.isStatic()) {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
} else {
if (it in companionMethods) {
companionMethods -= it
implemented += it
}
}
}
javaMethods.removeIf {
it.name == "findByIdOptional" ||
it in implemented
}
methods("javaMethods", javaMethods)
methods("kotlinMethods", kotlinMethods)
methods("companionMethods", companionMethods)
assertTrue(javaMethods.isEmpty(), "New methods not implemented: $javaMethods")
assertTrue(kotlinMethods.isEmpty(), "Old methods not removed: $kotlinMethods")
assertTrue(companionMethods.isEmpty(), "Old methods not removed: $companionMethods")
}
private fun map(type: KClass<*>): AnalogVisitor {
return AnalogVisitor().also { node ->
ClassReader(type.bytes()).accept(node, SKIP_CODE)
}
}
private fun KClass<*>.bytes() =
java.classLoader.getResourceAsStream(qualifiedName.toString().replace(".", "/") + ".class")
private fun compare(javaClass: AnalogVisitor, kotlinClass: AnalogVisitor, allowList: List<String> = listOf()) {
val javaMethods = javaClass.methods
val kotlinMethods = kotlinClass.methods
val implemented = mutableListOf<Method>()
javaMethods
.forEach {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
}
javaMethods.removeIf {
it.name in allowList ||
it in implemented
}
methods("javaMethods", javaMethods)
methods("kotlinMethods", kotlinMethods)
assertTrue(javaMethods.isEmpty(), "New methods not implemented: $javaMethods")
assertTrue(kotlinMethods.isEmpty(), "Old methods not removed: $kotlinMethods")
}
@Suppress("unused")
private fun methods(label: String, methods: List<Method>) {
if (methods.isNotEmpty()) {
println("$label: ")
methods
.forEach {
println(it)
}
println()
}
}
}
class AnalogVisitor : ClassVisitor(Gizmo.ASM_API_VERSION) {
val erasures = mapOf(
Type.getType(PanacheEntityBase::class.java).descriptor to Type.getType(Object::class.java).descriptor
)
val methods = mutableListOf<Method>()
override fun visitMethod(
access: Int,
name: String,
descriptor: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
if (name != "<clinit>" && name != "<init>" && !name.contains("lambda") && !descriptor.endsWith(ByteCodeType(Optional::class.java).descriptor())) {
val method = Method(
access,
name,
erase(Type.getReturnType(descriptor)),
erase(
Type.getArgumentTypes(
descriptor
)
)
)
methods += method
}
return super.visitMethod(access, name, descriptor, signature, exceptions)
}
private fun erase(type: Type): String {
var value = type.descriptor
erasures.entries.forEach(
Consumer {
value = value.replace(it.key, it.value)
}
)
return value
}
private fun erase(types: Array<Type>): List<String> = types.map { erase(it) }
}
class Method(val access: Int, val name: String, val type: String, val parameters: List<String>) {
fun isStatic() = access.matches(Opcodes.ACC_STATIC)
override fun toString(): String {
return (if (isStatic()) "static " else "") + "fun $name(${parameters.joinToString(", ")})" +
(if (type != Unit::class.qualifiedName) ": $type" else "")
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Method) return false
if (name != other.name) return false
if (parameters != other.parameters) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + type.hashCode()
result = 31 * result + parameters.hashCode()
return result
}
}
fun Int.matches(mask: Int) = (this and mask) == mask
fun Int.accDecode(): List<String> {
val decode: MutableList<String> = ArrayList()
val values: MutableMap<String, Int> = LinkedHashMap()
try {
for (f in Opcodes::class.java.declaredFields) {
if (f.name.startsWith("ACC_")) {
values[f.name] = f.getInt(Opcodes::class.java)
}
}
} catch (e: IllegalAccessException) {
throw RuntimeException(e.message, e)
}
for ((key, value) in values) {
if (this.matches(value)) {
decode.add(key)
}
}
return decode
}
| apache-2.0 | d6f4b6535a64bf44d625f5cd06229616 | 31.841629 | 154 | 0.59369 | 4.877688 | false | false | false | false |
backpaper0/syobotsum | core/src/syobotsum/actor/GoImage.kt | 1 | 632 | package syobotsum.actor
import com.badlogic.gdx.scenes.scene2d.Action
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.scenes.scene2d.ui.Image
import com.badlogic.gdx.scenes.scene2d.ui.Skin
class GoImage(skin: Skin, styleName: String) : Image(skin, styleName) {
var callback: Runnable? = null
fun start() {
val duration = 1f
setVisible(true)
val fadeOut = Actions.fadeOut(duration)
val run = callback.let{ Actions.run(it) }
val invisible = Actions.visible(false)
addAction(Actions.sequence(Actions.parallel(fadeOut, run), invisible))
}
}
| apache-2.0 | 2c1cc88242d6dec4d465f13893c74220 | 30.6 | 78 | 0.707278 | 3.590909 | false | false | false | false |
orbit/orbit | src/orbit-server/src/main/kotlin/orbit/server/pipeline/step/PlacementStep.kt | 1 | 1848 | /*
Copyright (C) 2015 - 2019 Electronic Arts Inc. All rights reserved.
This file is part of the Orbit Project <https://www.orbit.cloud>.
See license in LICENSE.
*/
package orbit.server.pipeline.step
import orbit.server.mesh.AddressableManager
import orbit.server.mesh.LocalNodeInfo
import orbit.server.pipeline.PipelineContext
import orbit.shared.net.InvocationReason
import orbit.shared.net.Message
import orbit.shared.net.MessageContent
import orbit.shared.net.MessageTarget
class PlacementStep(
private val addressableManager: AddressableManager,
private val localNodeInfo: LocalNodeInfo
) : PipelineStep {
override suspend fun onInbound(context: PipelineContext, msg: Message) {
when (val content = msg.content) {
is MessageContent.InvocationRequest -> {
val ineligibleNodes =
if (content.reason == InvocationReason.rerouted) listOf(context.metadata.authInfo.nodeId) else emptyList()
addressableManager.locateOrPlace(msg.source!!.namespace, content.destination, ineligibleNodes).also { location ->
msg.copy(
target = MessageTarget.Unicast(location)
).also { newMsg ->
context.next(newMsg)
}
}
}
is MessageContent.ConnectionInfoRequest ->
msg.source?.also { source ->
msg.copy(
target = MessageTarget.Unicast(source),
content = MessageContent.ConnectionInfoResponse(
nodeId = localNodeInfo.info.id
)
).also {
context.pushNew(it)
}
}
else -> context.next(msg)
}
}
} | bsd-3-clause | 03acb99f2b31553f5e27da1b4d896845 | 36.734694 | 129 | 0.589286 | 5.00813 | false | false | false | false |
Zukkari/nirdizati-training-ui | src/main/kotlin/cs/ut/ui/adapters/JobValueAdapter.kt | 1 | 8823 | package cs.ut.ui.adapters
import cs.ut.configuration.ConfigurationReader
import cs.ut.engine.JobManager
import cs.ut.engine.item.ModelParameter
import cs.ut.jobs.Job
import cs.ut.jobs.JobStatus
import cs.ut.jobs.SimulationJob
import cs.ut.providers.Dir
import cs.ut.ui.FieldComponent
import cs.ut.ui.GridValueProvider
import cs.ut.ui.Navigator
import cs.ut.ui.NirdizatiGrid
import cs.ut.ui.controllers.JobTrackerController
import cs.ut.ui.controllers.Redirectable
import cs.ut.util.Algorithm
import cs.ut.util.NirdizatiDownloader
import cs.ut.util.NirdizatiTranslator
import cs.ut.util.Page
import cs.ut.util.TRACKER_EAST
import org.zkoss.zk.ui.Component
import org.zkoss.zk.ui.Executions
import org.zkoss.zk.ui.event.Event
import org.zkoss.zk.ui.event.Events
import org.zkoss.zul.Button
import org.zkoss.zul.Hbox
import org.zkoss.zul.Hlayout
import org.zkoss.zul.Label
import org.zkoss.zul.Row
import org.zkoss.zul.Vlayout
/**
* Adapter for job tracker grid
*/
object JobValueAdapter : GridValueProvider<Job, Row>, Redirectable {
const val jobArg = "JOB"
private val AVERAGE = ConfigurationReader.findNode("defaultValues").valueWithIdentifier("average").value
override fun provide(data: Job): Pair<FieldComponent, Row> {
val status = Label(data.status.name)
val row = Row()
row.valign = "end"
val label = row.formJobLabel(data)
row.appendChild(label)
row.setValue(data)
return FieldComponent(label, status) to row
}
/**
* Create identifier label for a job
*/
private fun Job.identifierLabel(): Label {
val label = Label(this.id)
label.sclass = "extra-small"
return label
}
/**
* Create result label for a job
*
* @return hlayout component with labels
*/
private fun ModelParameter.generateResultLabel(): Hlayout {
val hlayout = Hlayout()
val label = Label(NirdizatiTranslator.localizeText("property.outcome"))
label.sclass = "param-label"
val outcome = Label(NirdizatiTranslator.localizeText(if (this.translate) this.getTranslateName() else this.id))
hlayout.appendChild(label)
hlayout.appendChild(outcome)
return hlayout
}
/**
* Create layout that contains job metadata
*
* @param job to use as datasource
*
* @return vlayout component with data
*/
private fun Row.formJobLabel(job: Job): Vlayout {
job as SimulationJob
val config = job.configuration
val encoding = config.encoding
val bucketing = config.bucketing
val learner = config.learner
val outcome = config.outcome
val label = Label(
NirdizatiTranslator.localizeText(encoding.type + "." + encoding.id) + "\n" +
NirdizatiTranslator.localizeText(bucketing.type + "." + bucketing.id) + "\n" +
NirdizatiTranslator.localizeText(learner.type + "." + learner.id)
)
label.isPre = true
label.sclass = "param-label"
val outcomeText = "" + if (outcome.id == Algorithm.OUTCOME.value) NirdizatiTranslator.localizeText("threshold.threshold_msg") + ": " +
(if (outcome.parameter == AVERAGE) NirdizatiTranslator.localizeText("threshold.avg").toLowerCase()
else outcome.parameter) + "\n"
else ""
val bottom: Label = learner.formHyperParamRow()
bottom.value = outcomeText + bottom.value
val fileLayout = job.generateFileInfo()
fileLayout.hflex = "1"
val labelsContainer = Vlayout()
labelsContainer.appendChild(fileLayout)
labelsContainer.appendChild(config.outcome.generateResultLabel())
labelsContainer.hflex = "1"
val fileContainer = Hlayout()
fileContainer.appendChild(labelsContainer)
val btnContainer = Hbox()
btnContainer.hflex = "min"
btnContainer.pack = "end"
btnContainer.appendChild(job.generateRemoveBtn(this))
fileContainer.appendChild(btnContainer)
fileContainer.hflex = "1"
val vlayout = Vlayout()
vlayout.appendChild(fileContainer)
vlayout.appendChild(job.generateStatus(label))
vlayout.appendChild(bottom)
vlayout.appendChild(job.identifierLabel())
val hlayout = Hlayout()
hlayout.appendChild(job.getVisualizeBtn())
hlayout.appendChild(job.getDeployBtn())
vlayout.appendChild(hlayout)
return vlayout
}
/**
* Create layout that hold job status
* @param label to put inside the layout
*/
private fun SimulationJob.generateStatus(label: Label): Hlayout {
val labelStatusContainer = Hlayout()
val labelContainer = Hlayout()
labelContainer.appendChild(label)
labelContainer.vflex = "1"
label.hflex = "1"
labelStatusContainer.appendChild(labelContainer)
val status = Label(this.status.name)
val statusContainer = Hbox()
statusContainer.appendChild(status)
statusContainer.hflex = "1"
statusContainer.vflex = "1"
statusContainer.pack = "end"
statusContainer.align = "center"
labelStatusContainer.appendChild(statusContainer)
return labelStatusContainer
}
/**
* Create layout with the file name
*
* @return hlayout with file name label
*/
private fun SimulationJob.generateFileInfo(): Hlayout {
val fileLabel = Label(NirdizatiTranslator.localizeText("attribute.log_file"))
fileLabel.sclass = "param-label"
val file = Label(this.logFile.name)
val fileLayout = Hlayout()
fileLayout.appendChild(fileLabel)
fileLayout.appendChild(file)
return fileLayout
}
/**
* Create job removal button
*
* @param row that will be removed when button is clicked
*
* @return button that will detach the row on click
*/
@Suppress("UNCHECKED_CAST")
private fun SimulationJob.generateRemoveBtn(row: Row): Button {
val btn = Button("x")
btn.vflex = "1"
btn.hflex = "min"
btn.sclass = "job-remove"
val client = Executions.getCurrent().desktop
btn.addEventListener(Events.ON_CLICK, { _ ->
val grid: NirdizatiGrid<Job> =
client.components.firstOrNull { it.id == JobTrackerController.GRID_ID } as NirdizatiGrid<Job>
JobManager.stopJob(this)
Executions.schedule(
client,
{ _ ->
row.detach()
if (grid.rows.getChildren<Component>().isEmpty()) {
client.components.first { it.id == TRACKER_EAST }.isVisible = false
}
},
Event("abort_job", null, null)
)
})
return btn
}
/**
* Create visualization button that will redirect user to job visualization page
*
* @return button component
*/
private fun SimulationJob.getVisualizeBtn(): Button {
val visualize = Button(NirdizatiTranslator.localizeText("job_tracker.visualize"))
visualize.sclass = "n-btn"
visualize.hflex = "1"
visualize.isDisabled = !(JobStatus.COMPLETED == this.status || JobStatus.FINISHING == this.status)
visualize.addEventListener(Events.ON_CLICK, { _ ->
Executions.getCurrent().setAttribute(jobArg, this)
setContent(Page.VALIDATION.value, Executions.getCurrent().desktop.firstPage,
Navigator.createParameters(Navigator.RequestParameter.JOB.value to this.id))
})
return visualize
}
private fun SimulationJob.getDeployBtn(): Button {
val deploy = Button(NirdizatiTranslator.localizeText("job_tracker.deploy_to_runtime"))
deploy.isDisabled = true
deploy.sclass = "n-btn"
deploy.vflex = "min"
deploy.hflex = "1"
deploy.addEventListener(Events.ON_CLICK, { _ ->
NirdizatiDownloader(Dir.PKL_DIR, this.id).execute()
})
return deploy
}
/**
* Create row based on hyper parameters
*
* @return label that contains job hyper parameter information
*/
private fun ModelParameter.formHyperParamRow(): Label {
var label = ""
val iterator = this.properties.iterator()
while (iterator.hasNext()) {
val prop = iterator.next()
label += NirdizatiTranslator.localizeText("property." + prop.id) + ": " + prop.property + "\n"
}
val res = Label(label)
res.sclass = "small-font"
res.isMultiline = true
res.isPre = true
return res
}
} | lgpl-3.0 | 17cd67b55aa2c35eb09aa17d9648d739 | 30.741007 | 142 | 0.632438 | 4.24591 | false | false | false | false |
square/moshi | moshi-kotlin-codegen/src/main/java/com/squareup/moshi/kotlin/codegen/api/PropertyGenerator.kt | 1 | 2981 | /*
* Copyright (C) 2018 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
*
* 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.squareup.moshi.kotlin.codegen.api
import com.squareup.kotlinpoet.BOOLEAN
import com.squareup.kotlinpoet.NameAllocator
import com.squareup.kotlinpoet.PropertySpec
/** Generates functions to encode and decode a property as JSON. */
@InternalMoshiCodegenApi
public class PropertyGenerator(
public val target: TargetProperty,
public val delegateKey: DelegateKey,
public val isTransient: Boolean = false
) {
public val name: String = target.name
public val jsonName: String = target.jsonName ?: target.name
public val hasDefault: Boolean = target.hasDefault
public lateinit var localName: String
public lateinit var localIsPresentName: String
public val isRequired: Boolean get() = !delegateKey.nullable && !hasDefault
public val hasConstructorParameter: Boolean get() = target.parameterIndex != -1
/**
* IsPresent is required if the following conditions are met:
* - Is not transient
* - Has a default
* - Is not a constructor parameter (for constructors we use a defaults mask)
* - Is nullable (because we differentiate absent from null)
*
* This is used to indicate that presence should be checked first before possible assigning null
* to an absent value
*/
public val hasLocalIsPresentName: Boolean = !isTransient && hasDefault && !hasConstructorParameter && delegateKey.nullable
public val hasConstructorDefault: Boolean = hasDefault && hasConstructorParameter
internal fun allocateNames(nameAllocator: NameAllocator) {
localName = nameAllocator.newName(name)
localIsPresentName = nameAllocator.newName("${name}Set")
}
internal fun generateLocalProperty(): PropertySpec {
return PropertySpec.builder(localName, target.type.copy(nullable = true))
.mutable(true)
.apply {
if (hasConstructorDefault) {
// We default to the primitive default type, as reflectively invoking the constructor
// without this (even though it's a throwaway) will fail argument type resolution in
// the reflective invocation.
initializer(target.type.defaultPrimitiveValue())
} else {
initializer("null")
}
}
.build()
}
internal fun generateLocalIsPresentProperty(): PropertySpec {
return PropertySpec.builder(localIsPresentName, BOOLEAN)
.mutable(true)
.initializer("false")
.build()
}
}
| apache-2.0 | 1238a2a327705a75204f31cbf106ae29 | 36.2625 | 124 | 0.728279 | 4.636081 | false | false | false | false |
vhromada/Catalog-Swing | src/main/kotlin/cz/vhromada/catalog/gui/common/AbstractOverviewDataPanel.kt | 1 | 14238 | package cz.vhromada.catalog.gui.common
import java.awt.event.InputEvent
import java.awt.event.KeyEvent
import javax.swing.GroupLayout
import javax.swing.JList
import javax.swing.JMenuItem
import javax.swing.JPanel
import javax.swing.JPopupMenu
import javax.swing.JScrollPane
import javax.swing.JTabbedPane
import javax.swing.JTable
import javax.swing.KeyStroke
import javax.swing.ListSelectionModel
import javax.swing.SwingUtilities
/**
* An abstract class represents overview panel with data.
*
* @param <T> type of data
* @author Vladimir Hromada
*/
abstract class AbstractOverviewDataPanel<T> : JPanel {
/**
* Popup menu
*/
private val popupMenu = JPopupMenu()
/**
* Menu item for adding data
*/
private val addPopupMenuItem = JMenuItem("Add", Picture.ADD.icon)
/**
* Menu item for updating data
*/
private val updatePopupMenuItem = JMenuItem("Update", Picture.UPDATE.icon)
/**
* Menu item for removing data
*/
private val removePopupMenuItem = JMenuItem("Remove", Picture.REMOVE.icon)
/**
* Menu item for duplicating data
*/
private val duplicatePopupMenuItem = JMenuItem("Duplicate", Picture.DUPLICATE.icon)
/**
* Menu item for moving up data
*/
private val moveUpPopupMenuItem = JMenuItem("Move up", Picture.UP.icon)
/**
* Menu item for moving down data
*/
private val moveDownPopupMenuItem = JMenuItem("Move down", Picture.DOWN.icon)
/**
* List with data
*/
private val list = JList<String>()
/**
* ScrollPane for list with data
*/
private val listScrollPane = JScrollPane(list)
/**
* Tabbed pane with data
*/
private val tabbedPane = JTabbedPane()
/**
* Table with with stats
*/
private val statsTable = JTable()
/**
* ScrollPane for table with stats
*/
private val statsTableScrollPane = JScrollPane(statsTable)
/**
* Data model for list
*/
private val listDataModel: AbstractListDataModel<T>
/**
* Data model for table with stats
*/
private val statsTableDataModel: AbstractStatsTableDataModel?
/**
* True if data is saved
*/
var saved: Boolean = true
private set
/**
* Creates a new instance of AbstractDataPanel.
*
* @param listDataModel data model for list
*/
constructor(listDataModel: AbstractListDataModel<T>) {
this.listDataModel = listDataModel
this.statsTableDataModel = null
initComponents()
}
/**
* Creates a new instance of AbstractDataPanel.
*
* @param listDataModel data model for list
* @param statsTableDataModel data model for table with stats
*/
constructor(listDataModel: AbstractListDataModel<T>, statsTableDataModel: AbstractStatsTableDataModel) {
this.listDataModel = listDataModel
this.statsTableDataModel = statsTableDataModel
initComponents()
}
/**
* Creates new data.
*/
open fun newData() {
deleteData()
listDataModel.update()
list.clearSelection()
list.updateUI()
tabbedPane.removeAll()
statsTableDataModel?.update()
statsTable.updateUI()
saved = true
}
/**
* Clears selection.
*/
open fun clearSelection() {
tabbedPane.removeAll()
list.clearSelection()
}
/**
* Saves.
*/
open fun save() {
saved = true
}
/**
* Returns info dialog.
*
* @param add true if dialog is for adding data
* @param data data
* @return info dialog
*/
protected abstract fun getInfoDialog(add: Boolean, data: T?): AbstractInfoDialog<T>
/**
* Deletes data.
*/
protected abstract fun deleteData()
/**
* Adds data.
*
* @param data data
*/
protected abstract fun addData(data: T)
/**
* Updates data.
*
* @param data data
*/
protected abstract fun updateData(data: T)
/**
* Removes data.
*
* @param data data
*/
protected abstract fun removeData(data: T)
/**
* Duplicates data.
*
* @param data data
*/
protected abstract fun duplicatesData(data: T)
/**
* Moves up data.
*
* @param data data
*/
protected abstract fun moveUpData(data: T)
/**
* Moves down data.
*
* @param data data
*/
protected abstract fun moveDownData(data: T)
/**
* Returns data panel.
*
* @param data data
* @return data panel
*/
protected abstract fun getDataPanel(data: T): JPanel
/**
* Updates data on change.
*
* @param dataPanel tabbed pane with data
* @param data data
*/
protected abstract fun updateDataOnChange(dataPanel: JTabbedPane, data: T)
/**
* Updates model.
*
* @param data data
*/
protected fun updateModel(data: T) {
listDataModel.update()
list.updateUI()
getTabbedPanelDataPanel().updateData(data)
updateState()
}
/**
* Initializes components.
*/
private fun initComponents() {
initPopupMenu(addPopupMenuItem, updatePopupMenuItem, removePopupMenuItem, duplicatePopupMenuItem, moveUpPopupMenuItem, moveDownPopupMenuItem)
addPopupMenuItem.accelerator = KeyStroke.getKeyStroke(KeyEvent.VK_INSERT, 0)
addPopupMenuItem.addActionListener { addAction() }
updatePopupMenuItem.accelerator = KeyStroke.getKeyStroke(KeyEvent.VK_F11, 0)
updatePopupMenuItem.isEnabled = false
updatePopupMenuItem.addActionListener { updateAction() }
removePopupMenuItem.accelerator = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0)
removePopupMenuItem.isEnabled = false
removePopupMenuItem.addActionListener { removeAction() }
duplicatePopupMenuItem.accelerator = KeyStroke.getKeyStroke(KeyEvent.VK_C, InputEvent.CTRL_DOWN_MASK)
duplicatePopupMenuItem.isEnabled = false
duplicatePopupMenuItem.addActionListener { duplicateAction() }
moveUpPopupMenuItem.accelerator = KeyStroke.getKeyStroke(KeyEvent.VK_U, InputEvent.CTRL_DOWN_MASK)
moveUpPopupMenuItem.isEnabled = false
moveUpPopupMenuItem.addActionListener { moveUpAction() }
moveDownPopupMenuItem.accelerator = KeyStroke.getKeyStroke(KeyEvent.VK_D, InputEvent.CTRL_DOWN_MASK)
moveDownPopupMenuItem.isEnabled = false
moveDownPopupMenuItem.addActionListener { moveDownAction() }
list.model = listDataModel
list.selectionMode = ListSelectionModel.SINGLE_SELECTION
list.componentPopupMenu = popupMenu
list.selectionModel.addListSelectionListener { listValueChangedAction() }
initStats()
val layout = GroupLayout(this)
setLayout(layout)
layout.setHorizontalGroup(createHorizontalLayout(layout))
layout.setVerticalGroup(createVerticalLayout(layout))
}
/**
* Initializes popup menu.
*
* @param menuItems popup menu items
*/
private fun initPopupMenu(vararg menuItems: JMenuItem) {
for (menuItem in menuItems) {
popupMenu.add(menuItem)
}
}
/**
* Initializes stats.
*/
private fun initStats() {
if (statsTableDataModel != null) {
statsTable.model = statsTableDataModel
statsTable.autoResizeMode = JTable.AUTO_RESIZE_ALL_COLUMNS
statsTable.isEnabled = false
statsTable.rowSelectionAllowed = false
statsTable.setDefaultRenderer(Int::class.java, StatsTableCellRenderer())
statsTable.setDefaultRenderer(String::class.java, StatsTableCellRenderer())
}
}
/**
* Performs action for button Add.
*/
private fun addAction() {
SwingUtilities.invokeLater {
val dialog = getInfoDialog(true, null)
dialog.isVisible = true
if (dialog.returnStatus === DialogResult.OK) {
addData(dialog.data!!)
listDataModel.update()
list.updateUI()
list.selectedIndex = list.model.size - 1
updateState()
}
}
}
/**
* Performs action for button Update.
*/
private fun updateAction() {
SwingUtilities.invokeLater {
val dialog = getInfoDialog(false, listDataModel.getObjectAt(list.selectedIndex))
dialog.isVisible = true
if (dialog.returnStatus === DialogResult.OK) {
val data = dialog.data!!
updateData(data)
updateModel(data)
}
}
}
/**
* Performs action for button Remove.
*/
private fun removeAction() {
removeData(listDataModel.getObjectAt(list.selectedIndex))
listDataModel.update()
list.updateUI()
list.clearSelection()
updateState()
}
/**
* Performs action for button Duplicate.
*/
private fun duplicateAction() {
val index = list.selectedIndex
duplicatesData(listDataModel.getObjectAt(index))
listDataModel.update()
list.updateUI()
list.selectedIndex = index + 1
updateState()
}
/**
* Performs action for button MoveUp.
*/
private fun moveUpAction() {
val index = list.selectedIndex
moveUpData(listDataModel.getObjectAt(index))
listDataModel.update()
list.updateUI()
list.selectedIndex = index - 1
saved = false
if (statsTableDataModel == null) {
firePropertyChange(UPDATE_PROPERTY, false, true)
}
}
/**
* Performs action for button MoveDown.
*/
private fun moveDownAction() {
val index = list.selectedIndex
moveDownData(listDataModel.getObjectAt(index))
listDataModel.update()
list.updateUI()
list.selectedIndex = index + 1
saved = false
if (statsTableDataModel == null) {
firePropertyChange(UPDATE_PROPERTY, false, true)
}
}
/**
* Performs action for change of list value.
*/
private fun listValueChangedAction() {
val isSelectedRow = list.selectedIndices.size == 1
val selectedRow = list.selectedIndex
val validRowIndex = selectedRow >= 0
val validSelection = isSelectedRow && validRowIndex
removePopupMenuItem.isEnabled = validSelection
updatePopupMenuItem.isEnabled = validSelection
duplicatePopupMenuItem.isEnabled = validSelection
tabbedPane.removeAll()
if (validSelection) {
val data = listDataModel.getObjectAt(selectedRow)
tabbedPane.add("Data", getDataPanel(data))
updateDataOnChange(tabbedPane, data)
}
moveUpPopupMenuItem.isEnabled = isSelectedRow && selectedRow > 0
moveDownPopupMenuItem.isEnabled = validSelection && selectedRow < list.model.size - 1
}
/**
* Updates state.
*/
private fun updateState() {
if (statsTableDataModel == null) {
firePropertyChange(UPDATE_PROPERTY, false, true)
} else {
statsTableDataModel.update()
statsTable.updateUI()
saved = false
}
}
/**
* Returns data panel in tabbed pane.
*
* @return data panel in tabbed pane
*/
@Suppress("UNCHECKED_CAST")
private fun getTabbedPanelDataPanel(): AbstractDataPanel<T> {
return tabbedPane.getComponentAt(0) as AbstractDataPanel<T>
}
/**
* Returns horizontal layout of components.
*
* @param layout layout
* @return horizontal layout of components
*/
private fun createHorizontalLayout(layout: GroupLayout): GroupLayout.Group {
val data = layout.createSequentialGroup()
.addComponent(listScrollPane, HORIZONTAL_SCROLL_PANE_SIZE, HORIZONTAL_SCROLL_PANE_SIZE, HORIZONTAL_SCROLL_PANE_SIZE)
.addGap(HORIZONTAL_GAP_SIZE)
.addComponent(tabbedPane, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt())
return if (statsTableDataModel == null) {
data
} else {
layout.createParallelGroup()
.addGroup(data)
.addComponent(statsTableScrollPane, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE.toInt())
}
}
/**
* Returns vertical layout of components.
*
* @param layout layout
* @return vertical layout of components
*/
private fun createVerticalLayout(layout: GroupLayout): GroupLayout.Group {
val data = layout.createParallelGroup()
.addComponent(listScrollPane, VERTICAL_DATA_COMPONENT_SIZE, VERTICAL_DATA_COMPONENT_SIZE, Short.MAX_VALUE.toInt())
.addComponent(tabbedPane, VERTICAL_DATA_COMPONENT_SIZE, VERTICAL_DATA_COMPONENT_SIZE, Short.MAX_VALUE.toInt())
return if (statsTableDataModel == null) {
data
} else {
layout.createSequentialGroup()
.addGroup(data)
.addGap(VERTICAL_GAP_SIZE)
.addComponent(statsTableScrollPane, VERTICAL_STATS_SCROLL_PANE_SIZE, VERTICAL_STATS_SCROLL_PANE_SIZE, VERTICAL_STATS_SCROLL_PANE_SIZE)
}
}
companion object {
/**
* Horizontal scroll pane size
*/
private const val HORIZONTAL_SCROLL_PANE_SIZE = 200
/**
* Horizontal gap size
*/
private const val HORIZONTAL_GAP_SIZE = 5
/**
* Vertical data component size
*/
private const val VERTICAL_DATA_COMPONENT_SIZE = 200
/**
* Vertical size for scroll pane for table with stats
*/
private const val VERTICAL_STATS_SCROLL_PANE_SIZE = 45
/**
* Vertical gap size
*/
private const val VERTICAL_GAP_SIZE = 2
/**
* Update property
*/
private const val UPDATE_PROPERTY = "update"
}
}
| mit | 4a6ad5b6dabb419d22ed22d1be86bdbf | 27.027559 | 154 | 0.617924 | 4.869357 | false | false | false | false |
facebookincubator/ktfmt | core/src/main/java/com/facebook/ktfmt/format/FormattingOptions.kt | 1 | 1749 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* 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.facebook.ktfmt.format
data class FormattingOptions(
val style: Style = Style.FACEBOOK,
/** ktfmt breaks lines longer than maxWidth. */
val maxWidth: Int = DEFAULT_MAX_WIDTH,
/**
* blockIndent is the size of the indent used when a new block is opened, in spaces.
*
* For example,
* ```
* fun f() {
* //
* }
* ```
*/
val blockIndent: Int = 2,
/**
* continuationIndent is the size of the indent used when a line is broken because it's too
* long, in spaces.
*
* For example,
* ```
* val foo = bar(
* 1)
* ```
*/
val continuationIndent: Int = 4,
/** Whether ktfmt should remove imports that are not used. */
val removeUnusedImports: Boolean = true,
/**
* Print the Ops generated by KotlinInputAstVisitor to help reason about formatting (i.e.,
* newline) decisions
*/
val debuggingPrintOpsAfterFormatting: Boolean = false
) {
companion object {
const val DEFAULT_MAX_WIDTH: Int = 100
}
enum class Style {
FACEBOOK,
DROPBOX,
GOOGLE
}
}
| apache-2.0 | e8cef9e992efbf465fdb78a8edf93e8b | 24.720588 | 95 | 0.638079 | 4.076923 | false | false | false | false |
RFonzi/RxAware | rxaware-lib/src/main/java/io/github/rfonzi/rxaware/RxAwareActivity.kt | 1 | 2619 | package io.github.rfonzi.rxaware
import android.content.Intent
import android.support.v4.app.FragmentTransaction
import android.support.v4.app.NavUtils
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.jakewharton.rxrelay2.BehaviorRelay
import io.github.rfonzi.rxaware.bus.UIBus
import io.github.rfonzi.rxaware.bus.events.*
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
/**
* Created by ryan on 9/21/17.
*/
abstract class RxAwareActivity : AppCompatActivity(), RxAwareControls {
private val disposables = CompositeDisposable()
private val posts: BehaviorRelay<Any> = BehaviorRelay.create()
override fun onStart() {
super.onStart()
UIBus.toObservable()
.subscribe {
when (it.id) {
EventID.TOAST -> toast((it as ToastEvent).message)
EventID.NAVIGATE_UP -> navigateUp()
EventID.FRAGMENT_TRANSACTION -> fragmentTransaction((it as FragmentTransactionEvent).event)
EventID.START_ACTIVITY -> startActivity((it as StartActivityEvent).activity)
EventID.POST_TO_CURRENT_ACTIVITY -> posts.accept((it as PostToCurrentActivityEvent).post)
}
}.lifecycleAware()
}
fun Disposable.lifecycleAware() = disposables.add(this)
override fun toast(message: String) = Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
override fun navigateUp() =
if (supportFragmentManager.backStackEntryCount > 0)
supportFragmentManager.popBackStack()
else
NavUtils.navigateUpFromSameTask(this)
override fun fragmentTransaction(operations: FragmentTransaction.() -> Unit) {
val fragmentTransaction = supportFragmentManager.beginTransaction()
fragmentTransaction.operations()
fragmentTransaction.commit()
}
override fun startActivity(target: Class<out AppCompatActivity>) = startActivity(Intent(this, target))
override fun startActivityAndStore(target: Class<out AppCompatActivity>, data: Any) = UIBus.startActivityAndStore(target, data)
override fun store(data: Any) = UIBus.store(data)
override fun receive(): Any = UIBus.receive()
inline fun <reified T : Any> onPost(): Observable<T> = getPostsAsObservable().ofType(T::class.java)
fun getPostsAsObservable(): Observable<Any> = posts
override fun onStop() {
super.onStop()
disposables.clear()
}
} | mit | 7dbb4c6f7314a1a04d207c7e3aa97e0d | 36.971014 | 131 | 0.686522 | 4.823204 | false | false | false | false |
mingdroid/tumbviewer | app/src/main/java/com/nutrition/express/ui/video/VideoPlayerActivity.kt | 1 | 2655 | package com.nutrition.express.ui.video
import android.annotation.SuppressLint
import android.content.pm.ActivityInfo
import android.media.AudioManager
import android.net.Uri
import android.os.Bundle
import com.google.android.exoplayer2.C
import com.google.android.exoplayer2.SimpleExoPlayer
import com.google.android.exoplayer2.util.Util
import com.nutrition.express.application.BaseActivity
import com.nutrition.express.common.MyExoPlayer
import com.nutrition.express.databinding.ActivityVideoPlayerBinding
class VideoPlayerActivity : BaseActivity() {
private lateinit var player: SimpleExoPlayer
private lateinit var binding: ActivityVideoPlayerBinding
@SuppressLint("SourceLockedOrientationActivity")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val uri = intent.getParcelableExtra<Uri>("uri")
val playPosition = intent.getLongExtra("position", C.TIME_UNSET)
val playWindow = intent.getIntExtra("windowIndex", 0)
val rotation = intent.getBooleanExtra("rotation", false)
if (rotation) {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
}
if (uri == null) {
finish()
return
}
player = MyExoPlayer.preparePlayer(uri, null)
binding = ActivityVideoPlayerBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.playerView.requestFocus()
binding.playerView.player = player
if (playPosition == C.TIME_UNSET) {
player.seekToDefaultPosition(playWindow)
} else {
player.seekTo(playWindow, playPosition)
}
volumeControlStream = AudioManager.STREAM_MUSIC
}
override fun onStart() {
super.onStart()
if (Util.SDK_INT > 23) {
binding.playerView.onResume()
}
}
override fun onResume() {
super.onResume()
if (Util.SDK_INT <= 23) {
binding.playerView.onResume()
}
player.playWhenReady = true
}
override fun onPause() {
super.onPause()
if (Util.SDK_INT <= 23) {
binding.playerView.onPause()
}
player.playWhenReady = false
}
override fun onStop() {
super.onStop()
if (Util.SDK_INT > 23) {
binding.playerView.onPause()
}
player.stop()
}
override fun onDestroy() {
super.onDestroy()
//remove all callbacks, avoiding memory leak
binding.playerView.player = null
binding.playerView.overlayFrameLayout?.removeAllViews()
}
} | apache-2.0 | af84596e5b9cd6fadfb7d413442b6df3 | 29.528736 | 83 | 0.65838 | 4.77518 | false | false | false | false |
defio/Room-experimets-in-kotlin | app/src/main/java/com/nicoladefiorenze/room/database/entity/Email.kt | 1 | 788 | package com.nicoladefiorenze.room.database.entity
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.ForeignKey
import android.arch.persistence.room.PrimaryKey
import java.security.InvalidParameterException
/**
* Project: Room<br></br>
* created on: 2017-05-20
* @author Nicola De Fiorenze
*/
@Entity(tableName = "email",
foreignKeys = arrayOf(ForeignKey(
entity = User::class,
parentColumns = arrayOf("id"),
childColumns = arrayOf("user_id"),
onDelete = ForeignKey.CASCADE)))
class Email {
@PrimaryKey
var email: String = ""
var isPrimary: Boolean = false
@ColumnInfo(name = "user_id")
var userId: Int = 0
}
| apache-2.0 | e8e0d7f024765ebaa69098e88cd3f2f7 | 26.172414 | 50 | 0.673858 | 4.125654 | false | false | false | false |
gmillz/SlimFileManager | manager/src/main/java/com/getbase/floatingactionbutton/FloatingActionsMenu.kt | 1 | 24276 | package com.getbase.floatingactionbutton
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.content.res.TypedArray
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.graphics.drawable.LayerDrawable
import android.os.Parcel
import android.os.Parcelable
import android.support.annotation.ColorRes
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.ContextThemeWrapper
import android.view.TouchDelegate
import android.view.View
import android.view.ViewGroup
import android.view.animation.DecelerateInterpolator
import android.view.animation.Interpolator
import android.view.animation.OvershootInterpolator
import android.widget.TextView
import com.slim.slimfilemanager.R
class FloatingActionsMenu : ViewGroup {
private var mAddButtonPlusColor: Int = 0
private var mAddButtonColorNormal: Int = 0
private var mAddButtonColorPressed: Int = 0
private var mAddButtonSize: Int = 0
private var mAddButtonStrokeVisible: Boolean = false
private var mExpandDirection: Int = 0
private var mButtonSpacing: Int = 0
private var mLabelsMargin: Int = 0
private var mLabelsVerticalOffset: Int = 0
var isExpanded: Boolean = false
private set
private val mExpandAnimation = AnimatorSet().setDuration(ANIMATION_DURATION.toLong())
private val mCollapseAnimation = AnimatorSet().setDuration(ANIMATION_DURATION.toLong())
private var mAddButton: AddFloatingActionButton? = null
private var mRotatingDrawable: RotatingDrawable? = null
private var mMaxButtonWidth: Int = 0
private var mMaxButtonHeight: Int = 0
private var mLabelsStyle: Int = 0
private var mLabelsPosition: Int = 0
private var mButtonsCount: Int = 0
private var mTouchDelegateGroup: TouchDelegateGroup? = null
private var mListener: OnFloatingActionsMenuUpdateListener? = null
@JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : super(context,
attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(context, attrs,
defStyle) {
init(context, attrs)
}
private fun init(context: Context, attributeSet: AttributeSet?) {
mButtonSpacing =
(resources.getDimension(R.dimen.fab_actions_spacing) - resources.getDimension(
R.dimen.fab_shadow_radius) - resources.getDimension(
R.dimen.fab_shadow_offset)).toInt()
mLabelsMargin = resources.getDimensionPixelSize(R.dimen.fab_labels_margin)
mLabelsVerticalOffset = resources.getDimensionPixelSize(R.dimen.fab_shadow_offset)
mTouchDelegateGroup = TouchDelegateGroup(this)
touchDelegate = mTouchDelegateGroup
val attr =
context.obtainStyledAttributes(attributeSet, R.styleable.FloatingActionsMenu, 0, 0)
mAddButtonPlusColor =
attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonPlusIconColor,
getColor(android.R.color.white))
mAddButtonColorNormal =
attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonColorNormal,
getColor(android.R.color.holo_blue_dark))
mAddButtonColorPressed =
attr.getColor(R.styleable.FloatingActionsMenu_fab_addButtonColorPressed,
getColor(android.R.color.holo_blue_light))
mAddButtonSize = attr.getInt(R.styleable.FloatingActionsMenu_fab_addButtonSize,
FloatingActionButton.SIZE_NORMAL)
mAddButtonStrokeVisible =
attr.getBoolean(R.styleable.FloatingActionsMenu_fab_addButtonStrokeVisible, true)
mExpandDirection =
attr.getInt(R.styleable.FloatingActionsMenu_fab_expandDirection, EXPAND_UP)
mLabelsStyle = attr.getResourceId(R.styleable.FloatingActionsMenu_fab_labelStyle, 0)
mLabelsPosition =
attr.getInt(R.styleable.FloatingActionsMenu_fab_labelsPosition, LABELS_ON_LEFT_SIDE)
attr.recycle()
if (mLabelsStyle != 0 && expandsHorizontally()) {
throw IllegalStateException(
"Action labels in horizontal expand orientation is not supported.")
}
createAddButton(context)
}
fun setOnFloatingActionsMenuUpdateListener(listener: OnFloatingActionsMenuUpdateListener) {
mListener = listener
}
private fun expandsHorizontally(): Boolean {
return mExpandDirection == EXPAND_LEFT || mExpandDirection == EXPAND_RIGHT
}
private fun createAddButton(context: Context) {
mAddButton = object : AddFloatingActionButton(context) {
override var iconDrawable: Drawable?
get() {
val rotatingDrawable = super.iconDrawable?.let { RotatingDrawable(it) }
mRotatingDrawable = rotatingDrawable
val interpolator = OvershootInterpolator()
val collapseAnimator = ObjectAnimator.ofFloat(rotatingDrawable, "rotation",
EXPANDED_PLUS_ROTATION, COLLAPSED_PLUS_ROTATION)
val expandAnimator = ObjectAnimator.ofFloat(rotatingDrawable, "rotation",
COLLAPSED_PLUS_ROTATION, EXPANDED_PLUS_ROTATION)
collapseAnimator.interpolator = interpolator
expandAnimator.interpolator = interpolator
mExpandAnimation.play(expandAnimator)
mCollapseAnimation.play(collapseAnimator)
return rotatingDrawable
}
set(value: Drawable?) {
super.iconDrawable = value
}
internal override fun updateBackground() {
mPlusColor = mAddButtonPlusColor
mColorNormal = mAddButtonColorNormal
mColorPressed = mAddButtonColorPressed
mStrokeVisible = mAddButtonStrokeVisible
super.updateBackground()
}
}
mAddButton!!.id = R.id.fab_expand_menu_button
mAddButton!!.size = mAddButtonSize
mAddButton!!.setOnClickListener { toggle() }
addView(mAddButton, super.generateDefaultLayoutParams())
mButtonsCount++
}
fun setColorNormal(color: Int) {
mAddButtonColorNormal = color
mAddButton!!.updateBackground()
}
fun setColorPressed(color: Int) {
mAddButtonColorPressed = color
mAddButton!!.updateBackground()
}
fun addButton(button: FloatingActionButton) {
addView(button, mButtonsCount - 1)
mButtonsCount++
if (mLabelsStyle != 0) {
createLabels()
}
}
fun removeButton(button: FloatingActionButton) {
removeView(button.labelView)
removeView(button)
button.setTag(R.id.fab_label, null)
mButtonsCount--
}
private fun getColor(@ColorRes id: Int): Int {
return ContextCompat.getColor(context, id)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
measureChildren(widthMeasureSpec, heightMeasureSpec)
var width = 0
var height = 0
mMaxButtonWidth = 0
mMaxButtonHeight = 0
var maxLabelWidth = 0
for (i in 0 until mButtonsCount) {
val child = getChildAt(i)
if (child.visibility == View.GONE) {
continue
}
when (mExpandDirection) {
EXPAND_UP, EXPAND_DOWN -> {
mMaxButtonWidth = Math.max(mMaxButtonWidth, child.measuredWidth)
height += child.measuredHeight
}
EXPAND_LEFT, EXPAND_RIGHT -> {
width += child.measuredWidth
mMaxButtonHeight = Math.max(mMaxButtonHeight, child.measuredHeight)
}
}
if (!expandsHorizontally()) {
val label = child.getTag(R.id.fab_label) as TextView?
if (label != null) {
maxLabelWidth = Math.max(maxLabelWidth, label.measuredWidth)
}
}
}
if (!expandsHorizontally()) {
width = mMaxButtonWidth + if (maxLabelWidth > 0) maxLabelWidth + mLabelsMargin else 0
} else {
height = mMaxButtonHeight
}
when (mExpandDirection) {
EXPAND_UP, EXPAND_DOWN -> {
height += mButtonSpacing * (mButtonsCount - 1)
height = adjustForOvershoot(height)
}
EXPAND_LEFT, EXPAND_RIGHT -> {
width += mButtonSpacing * (mButtonsCount - 1)
width = adjustForOvershoot(width)
}
}
setMeasuredDimension(width, height)
}
private fun adjustForOvershoot(dimension: Int): Int {
return dimension * 12 / 10
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
when (mExpandDirection) {
EXPAND_UP, EXPAND_DOWN -> {
val expandUp = mExpandDirection == EXPAND_UP
if (changed) {
mTouchDelegateGroup!!.clearTouchDelegates()
}
val addButtonY = if (expandUp) b - t - mAddButton!!.measuredHeight else 0
// Ensure mAddButton is centered on the line where the buttons should be
val buttonsHorizontalCenter = if (mLabelsPosition == LABELS_ON_LEFT_SIDE)
r - l - mMaxButtonWidth / 2
else
mMaxButtonWidth / 2
val addButtonLeft = buttonsHorizontalCenter - mAddButton!!.measuredWidth / 2
mAddButton!!.layout(addButtonLeft, addButtonY,
addButtonLeft + mAddButton!!.measuredWidth,
addButtonY + mAddButton!!.measuredHeight)
val labelsOffset = mMaxButtonWidth / 2 + mLabelsMargin
val labelsXNearButton = if (mLabelsPosition == LABELS_ON_LEFT_SIDE)
buttonsHorizontalCenter - labelsOffset
else
buttonsHorizontalCenter + labelsOffset
var nextY = if (expandUp)
addButtonY - mButtonSpacing
else
addButtonY + mAddButton!!.measuredHeight + mButtonSpacing
for (i in mButtonsCount - 1 downTo 0) {
val child = getChildAt(i)
if (child === mAddButton || child.visibility == View.GONE) continue
val childX = buttonsHorizontalCenter - child.measuredWidth / 2
val childY = if (expandUp) nextY - child.measuredHeight else nextY
child.layout(childX, childY, childX + child.measuredWidth,
childY + child.measuredHeight)
val collapsedTranslation = (addButtonY - childY).toFloat()
val expandedTranslation = 0f
child.translationY =
if (isExpanded) expandedTranslation else collapsedTranslation
child.alpha = if (isExpanded) 1f else 0f
val params = child.layoutParams as LayoutParams
params.mCollapseDir.setFloatValues(expandedTranslation, collapsedTranslation)
params.mExpandDir.setFloatValues(collapsedTranslation, expandedTranslation)
params.setAnimationsTarget(child)
val label = child.getTag(R.id.fab_label) as View
if (label != null) {
val labelXAwayFromButton = if (mLabelsPosition == LABELS_ON_LEFT_SIDE)
labelsXNearButton - label.measuredWidth
else
labelsXNearButton + label.measuredWidth
val labelLeft = if (mLabelsPosition == LABELS_ON_LEFT_SIDE)
labelXAwayFromButton
else
labelsXNearButton
val labelRight = if (mLabelsPosition == LABELS_ON_LEFT_SIDE)
labelsXNearButton
else
labelXAwayFromButton
val labelTop =
childY - mLabelsVerticalOffset + (child.measuredHeight - label.measuredHeight) / 2
label.layout(labelLeft, labelTop, labelRight,
labelTop + label.measuredHeight)
val touchArea = Rect(
Math.min(childX, labelLeft),
childY - mButtonSpacing / 2,
Math.max(childX + child.measuredWidth, labelRight),
childY + child.measuredHeight + mButtonSpacing / 2)
mTouchDelegateGroup!!.addTouchDelegate(TouchDelegate(touchArea, child))
label.translationY =
if (isExpanded) expandedTranslation else collapsedTranslation
label.alpha = if (isExpanded) 1f else 0f
val labelParams = label.layoutParams as LayoutParams
labelParams.mCollapseDir.setFloatValues(expandedTranslation,
collapsedTranslation)
labelParams.mExpandDir.setFloatValues(collapsedTranslation,
expandedTranslation)
labelParams.setAnimationsTarget(label)
}
nextY = if (expandUp)
childY - mButtonSpacing
else
childY + child.measuredHeight + mButtonSpacing
}
}
EXPAND_LEFT, EXPAND_RIGHT -> {
val expandLeft = mExpandDirection == EXPAND_LEFT
val addButtonX = if (expandLeft) r - l - mAddButton!!.measuredWidth else 0
// Ensure mAddButton is centered on the line where the buttons should be
val addButtonTop =
b - t - mMaxButtonHeight + (mMaxButtonHeight - mAddButton!!.measuredHeight) / 2
mAddButton!!.layout(addButtonX, addButtonTop,
addButtonX + mAddButton!!.measuredWidth,
addButtonTop + mAddButton!!.measuredHeight)
var nextX = if (expandLeft)
addButtonX - mButtonSpacing
else
addButtonX + mAddButton!!.measuredWidth + mButtonSpacing
for (i in mButtonsCount - 1 downTo 0) {
val child = getChildAt(i)
if (child === mAddButton || child.visibility == View.GONE) continue
val childX = if (expandLeft) nextX - child.measuredWidth else nextX
val childY =
addButtonTop + (mAddButton!!.measuredHeight - child.measuredHeight) / 2
child.layout(childX, childY, childX + child.measuredWidth,
childY + child.measuredHeight)
val collapsedTranslation = (addButtonX - childX).toFloat()
val expandedTranslation = 0f
child.translationX =
if (isExpanded) expandedTranslation else collapsedTranslation
child.alpha = if (isExpanded) 1f else 0f
val params = child.layoutParams as LayoutParams
params.mCollapseDir.setFloatValues(expandedTranslation, collapsedTranslation)
params.mExpandDir.setFloatValues(collapsedTranslation, expandedTranslation)
params.setAnimationsTarget(child)
nextX = if (expandLeft)
childX - mButtonSpacing
else
childX + child.measuredWidth + mButtonSpacing
}
}
}
}
override fun generateDefaultLayoutParams(): ViewGroup.LayoutParams {
return LayoutParams(super.generateDefaultLayoutParams())
}
override fun generateLayoutParams(attrs: AttributeSet): ViewGroup.LayoutParams {
return LayoutParams(super.generateLayoutParams(attrs))
}
override fun generateLayoutParams(p: ViewGroup.LayoutParams): ViewGroup.LayoutParams {
return LayoutParams(super.generateLayoutParams(p))
}
override fun checkLayoutParams(p: ViewGroup.LayoutParams): Boolean {
return super.checkLayoutParams(p)
}
override fun onFinishInflate() {
super.onFinishInflate()
bringChildToFront(mAddButton)
mButtonsCount = childCount
if (mLabelsStyle != 0) {
createLabels()
}
}
private fun createLabels() {
val context = ContextThemeWrapper(context, mLabelsStyle)
for (i in 0 until mButtonsCount) {
val button = getChildAt(i) as FloatingActionButton
val title = button.title
if (button === mAddButton || title == null ||
button.getTag(R.id.fab_label) != null)
continue
val label = TextView(context)
label.setTextAppearance(getContext(), mLabelsStyle)
label.text = button.title
addView(label)
button.setTag(R.id.fab_label, label)
}
}
fun collapse() {
collapse(false)
}
fun collapseImmediately() {
collapse(true)
}
private fun collapse(immediately: Boolean) {
if (isExpanded) {
isExpanded = false
mTouchDelegateGroup!!.setEnabled(false)
mCollapseAnimation.duration = (if (immediately) 0 else ANIMATION_DURATION).toLong()
mCollapseAnimation.start()
mExpandAnimation.cancel()
if (mListener != null) {
mListener!!.onMenuCollapsed()
}
}
}
fun toggle() {
if (isExpanded) {
collapse()
} else {
expand()
}
}
fun expand() {
if (!isExpanded) {
isExpanded = true
mTouchDelegateGroup!!.setEnabled(true)
mCollapseAnimation.cancel()
mExpandAnimation.start()
if (mListener != null) {
mListener!!.onMenuExpanded()
}
}
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
mAddButton!!.isEnabled = enabled
}
public override fun onSaveInstanceState(): Parcelable? {
val superState = super.onSaveInstanceState()
val savedState = SavedState(superState)
savedState.mExpanded = isExpanded
return savedState
}
public override fun onRestoreInstanceState(state: Parcelable) {
if (state is SavedState) {
val savedState = state
isExpanded = savedState.mExpanded
mTouchDelegateGroup!!.setEnabled(isExpanded)
if (mRotatingDrawable != null) {
mRotatingDrawable!!.rotation =
if (isExpanded) EXPANDED_PLUS_ROTATION else COLLAPSED_PLUS_ROTATION
}
super.onRestoreInstanceState(savedState.superState)
} else {
super.onRestoreInstanceState(state)
}
}
interface OnFloatingActionsMenuUpdateListener {
fun onMenuExpanded()
fun onMenuCollapsed()
}
private class RotatingDrawable(drawable: Drawable) : LayerDrawable(arrayOf(drawable)) {
var rotation: Float = 0.toFloat()
set(rotation) {
field = rotation
invalidateSelf()
}
override fun draw(canvas: Canvas) {
canvas.save()
canvas.rotate(rotation, bounds.centerX().toFloat(), bounds.centerY().toFloat())
super.draw(canvas)
canvas.restore()
}
}
class SavedState : View.BaseSavedState {
var mExpanded: Boolean = false
constructor(parcel: Parcelable) : super(parcel) {}
private constructor(`in`: Parcel) : super(`in`) {
mExpanded = `in`.readInt() == 1
}
override fun writeToParcel(out: Parcel, flags: Int) {
super.writeToParcel(out, flags)
out.writeInt(if (mExpanded) 1 else 0)
}
companion object {
@JvmField val CREATOR: Parcelable.Creator<SavedState> = object : Parcelable.Creator<SavedState> {
override fun createFromParcel(`in`: Parcel): SavedState {
return SavedState(`in`)
}
override fun newArray(size: Int): Array<SavedState> {
return emptyArray()
}
}
}
}
private inner class LayoutParams(source: ViewGroup.LayoutParams) :
ViewGroup.LayoutParams(source) {
val mExpandDir = ObjectAnimator()
val mExpandAlpha = ObjectAnimator()
val mCollapseDir = ObjectAnimator()
val mCollapseAlpha = ObjectAnimator()
var animationsSetToPlay: Boolean = false
init {
mExpandDir.interpolator = sExpandInterpolator
mExpandAlpha.interpolator = sAlphaExpandInterpolator
mCollapseDir.interpolator = sCollapseInterpolator
mCollapseAlpha.interpolator = sCollapseInterpolator
mCollapseAlpha.setProperty(View.ALPHA)
mCollapseAlpha.setFloatValues(1f, 0f)
mExpandAlpha.setProperty(View.ALPHA)
mExpandAlpha.setFloatValues(0f, 1f)
when (mExpandDirection) {
EXPAND_UP, EXPAND_DOWN -> {
mCollapseDir.setProperty(View.TRANSLATION_Y)
mExpandDir.setProperty(View.TRANSLATION_Y)
}
EXPAND_LEFT, EXPAND_RIGHT -> {
mCollapseDir.setProperty(View.TRANSLATION_X)
mExpandDir.setProperty(View.TRANSLATION_X)
}
}
}
fun setAnimationsTarget(view: View?) {
mCollapseAlpha.target = view
mCollapseDir.target = view
mExpandAlpha.target = view
mExpandDir.target = view
// Now that the animations have targets, set them to be played
if (!animationsSetToPlay) {
addLayerTypeListener(mExpandDir, view)
addLayerTypeListener(mCollapseDir, view)
mCollapseAnimation.play(mCollapseAlpha)
mCollapseAnimation.play(mCollapseDir)
mExpandAnimation.play(mExpandAlpha)
mExpandAnimation.play(mExpandDir)
animationsSetToPlay = true
}
}
private fun addLayerTypeListener(animator: Animator, view: View?) {
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
view!!.setLayerType(View.LAYER_TYPE_NONE, null)
}
override fun onAnimationStart(animation: Animator) {
view!!.setLayerType(View.LAYER_TYPE_HARDWARE, null)
}
})
}
}
companion object {
val EXPAND_UP = 0
val EXPAND_DOWN = 1
val EXPAND_LEFT = 2
val EXPAND_RIGHT = 3
val LABELS_ON_LEFT_SIDE = 0
private val ANIMATION_DURATION = 300
private val COLLAPSED_PLUS_ROTATION = 0f
private val EXPANDED_PLUS_ROTATION = 90f + 45f
private val sExpandInterpolator = OvershootInterpolator()
private val sCollapseInterpolator = DecelerateInterpolator(3f)
private val sAlphaExpandInterpolator = DecelerateInterpolator()
}
} | gpl-3.0 | 9952797f01d3731665893f32bff5e229 | 36.522411 | 114 | 0.587411 | 5.386288 | false | false | false | false |
loziuu/vehicle-management | ivms/src/main/kotlin/pl/loziuu/ivms/inference/application/InferenceService.kt | 1 | 1413 | package pl.loziuu.ivms.inference.application
import pl.loziuu.ivms.ddd.ApplicationService
import pl.loziuu.ivms.inference.fuzzy.FuzzyLogicService
import pl.loziuu.ivms.maintenance.application.MaintenanceQueryService
import pl.loziuu.ivms.maintenance.journal.query.JournalDto
import java.time.LocalDate
@ApplicationService
class InferenceService(val maintenanceService: MaintenanceQueryService) {
fun getFleetStatus(withoutInsurance: Double, withoutCheckout: Double) : Double {
return FuzzyLogicService.getFleetStatus(withoutInsurance, withoutCheckout)
}
fun getFutureFleetStatusForDate(fleetId: Long, date: LocalDate): Double {
val journals = maintenanceService.getJournalsForFleet(fleetId)
val withoutInsurance = getPercentageForNotInsured(journals, date)
val withoutCheckout = getPercentageForNotCheckouted(journals, date)
return FuzzyLogicService.getFleetStatus(withoutInsurance, withoutCheckout)
}
private fun getPercentageForNotCheckouted(journals: List<JournalDto>, date: LocalDate = LocalDate.now()) =
(journals.count { !it.willHaveActualCheckoutAt(date) }.toDouble() / journals.size.toDouble()) * 100.0
private fun getPercentageForNotInsured(journals: List<JournalDto>, date: LocalDate = LocalDate.now()) =
(journals.count { !it.willHaveActualInsuranceAt(date) }.toDouble() / journals.size.toDouble()) * 100.0
} | gpl-3.0 | f2d01663a9a37b49c2fd79fe4c5e9cb8 | 49.5 | 114 | 0.778485 | 3.914127 | false | false | false | false |
strykeforce/thirdcoast | src/main/kotlin/org/strykeforce/trapper/Activity.kt | 1 | 1035 | package org.strykeforce.trapper
import com.squareup.moshi.JsonClass
import com.squareup.moshi.Moshi
import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okio.Buffer
import okio.BufferedSource
import java.time.LocalDateTime
private val activityJsonAdapter = ActivityJsonAdapter(moshi)
@JsonClass(generateAdapter = true)
data class Activity(
val name: String = "Activity ${LocalDateTime.now()}",
) : Postable {
var id: Int? = null
var url: String? = null
var meta: MutableMap<String, Any> = mutableMapOf()
override fun endpoint(baseUrl: String) = "$baseUrl/activities/".toHttpUrl()
override fun asRequestBody(): RequestBody {
val buffer = Buffer()
activityJsonAdapter.toJson(buffer, this)
return buffer.readUtf8().toRequestBody(MEDIA_TYPE_JSON)
}
@Suppress("UNCHECKED_CAST")
override fun <T : Postable> fromJson(source: BufferedSource): T =
activityJsonAdapter.fromJson(source)!! as T
}
| mit | 3b270bb6eec39b3c5c1746308be4fb90 | 29.441176 | 79 | 0.73913 | 4.3125 | false | false | false | false |
jskierbi/bundle-helper | bundle-helper/src/test/java/com/jskierbi/bundle_helper/BundleExtrasExtensionsTest.kt | 1 | 4068 | package com.jskierbi.bundle_helper
import android.app.Activity
import android.app.Fragment
import android.content.Intent
import android.location.Location
import android.os.Build
import org.junit.Assert.*
import org.junit.Ignore
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.android.controller.ActivityController
import org.robolectric.annotation.Config
/**
* Created by jakub on 18.09.17.
*/
@RunWith(RobolectricTestRunner::class)
@Config(
constants = BuildConfig::class,
sdk = intArrayOf(
Build.VERSION_CODES.JELLY_BEAN,
Build.VERSION_CODES.N
))
class BundleExtrasExtensionsTest {
lateinit var activityCtrl: ActivityController<TestActivity>
@Test fun ` start activity with extras`() {
// Assemble
val str = "asdf"
val bool = true
val int = 10233
val double = 573.33
val parcelable = Location("").apply { // Location implements parcelable
latitude = 10.0
longitude = 3.0
}
val intent = Intent(RuntimeEnvironment.application, TestActivity::class.java).withExtras(
TestActivity.EXTRA_STRING to str,
TestActivity.EXTRA_BOOLEAN to bool,
TestActivity.EXTRA_INT to int,
TestActivity.EXTRA_DOUBLE to double,
TestActivity.EXTRA_PARCELABLE to parcelable
)
// Act
val activity = Robolectric.buildActivity(TestActivity::class.java, intent).create().visible().get()
// Assert
assertEquals(str, activity.stringExtra)
assertEquals(bool, activity.boolExtra)
assertEquals(int, activity.intExtra)
assertEquals(double, activity.doubleExtra, 0.01)
assertEquals(parcelable.latitude, activity.locationExtra.latitude, 0.01)
assertEquals(parcelable.longitude, activity.locationExtra.longitude, 0.01)
}
@Test fun ` start activity with optional extras - non-null`() {
// Assemble
val str = "asdf"
val parcelable = Location("").apply { // Location implements parcelable
latitude = 10.0
longitude = 3.0
}
val intent = Intent(RuntimeEnvironment.application, TestActivity::class.java).withExtras(
TestActivity.EXTRA_OPTIONAL_STRING to str,
TestActivity.EXTRA_OPTIONAL_PARCELABLE to parcelable
)
// Act
val activity = Robolectric.buildActivity(TestActivity::class.java, intent).create().visible().get()
// Assert
assertEquals(str, activity.stringExtraOptional)
assertNotNull(activity.locationExtraOptional)
assertEquals(parcelable.latitude, activity.locationExtraOptional?.latitude!! , 0.01)
assertEquals(parcelable.longitude, activity.locationExtraOptional?.longitude!! , 0.01)
}
@Test fun ` start activity with optional extras - null`() {
// Assemble
val intent = Intent(RuntimeEnvironment.application, TestActivity::class.java).withExtras(
TestActivity.EXTRA_OPTIONAL_STRING to null,
TestActivity.EXTRA_OPTIONAL_PARCELABLE to null
)
// Act
val activity = Robolectric.buildActivity(TestActivity::class.java, intent).create().visible().get()
// Assert
assertNull(activity.stringExtraOptional)
assertNull(activity.locationExtraOptional)
}
class TestActivity : Activity() {
companion object {
val EXTRA_STRING = "EXTRA_STRING"
val EXTRA_BOOLEAN = "EXTRA_BOOLEAN"
val EXTRA_INT = "EXTRA_INT"
val EXTRA_DOUBLE = "EXTRA_DOUBLE"
val EXTRA_PARCELABLE = "EXTRA_PARCELABLE"
val EXTRA_OPTIONAL_STRING = "EXTRA_OPTIONAL_STRING"
val EXTRA_OPTIONAL_PARCELABLE = "EXTRA_OPTIONAL_PARCELABLE"
}
val stringExtra by lazyExtra<String>(EXTRA_STRING)
val boolExtra by lazyExtra<Boolean>(EXTRA_BOOLEAN)
val intExtra by lazyExtra<Int>(EXTRA_INT)
val doubleExtra by lazyExtra<Double>(EXTRA_DOUBLE)
val locationExtra by lazyExtra<Location>(EXTRA_PARCELABLE)
val stringExtraOptional by lazyExtra<String?>(EXTRA_OPTIONAL_STRING)
val locationExtraOptional by lazyExtra<Location?>(EXTRA_OPTIONAL_PARCELABLE)
}
} | apache-2.0 | 39bbb443118b5b9a3cf8348fff73e098 | 32.908333 | 103 | 0.730826 | 4.341515 | false | true | false | false |
debop/debop4k | debop4k-core/src/test/kotlin/debop4k/core/collections/permutations/DropWhileTest.kt | 1 | 1775 | /*
* Copyright (c) 2016. KESTI co, 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 debop4k.core.collections.permutations
import debop4k.core.collections.permutations.samples.primes
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
/**
* DropWhileTest
* @author [email protected]
*/
class DropWhileTest : AbstractPermutationTest() {
@Test
fun testEmptySeq() {
val empty = emptyPermutation<Any>()
val filtered = empty.dropWhile { true }
assertThat(filtered).isEmpty()
}
@Test
fun testSingleElement() {
val single = permutationOf(1)
val filtered = single.dropWhile { it > 0 }
assertThat(filtered).isEmpty()
val positives = single.dropWhile { it < 0 }
assertThat(positives).isEqualTo(permutationOf(1))
}
@Test
fun testFixedSeq() {
val fixed = permutationOf(2, 4, 6, 8, 10)
val overFive = fixed.dropWhile { it < 5 }
assertThat(overFive).isEqualTo(permutationOf(6, 8, 10))
val positives = fixed.dropWhile { it < 0 }
assertThat(positives).isEqualTo(fixed)
}
@Test
fun testInifiteSeq() {
val primes = primes()
val filtered = primes.dropWhile { it < 10 }
assertThat(filtered.take(5)).isEqualTo(permutationOf(11, 13, 17, 19, 23))
}
} | apache-2.0 | f25e471fff0c5fcbd1bdc048e4ec6f61 | 28.114754 | 77 | 0.703662 | 3.841991 | false | true | false | false |
lightem90/Sismic | app/src/main/java/com/polito/sismic/Presenters/ReportActivity/Fragments/RilieviReportFragment.kt | 1 | 6051 | package com.polito.sismic.Presenters.ReportActivity.Fragments
import android.graphics.Color
import android.os.Bundle
import android.support.annotation.Nullable
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Adapter
import android.widget.AdapterView
import com.github.mikephil.charting.components.Legend
import com.github.mikephil.charting.components.LegendEntry
import com.github.mikephil.charting.components.XAxis
import com.github.mikephil.charting.components.YAxis
import com.polito.sismic.Interactors.Helpers.UiMapper
import com.polito.sismic.Interactors.SismicPlantBuildingInteractor
import com.polito.sismic.Presenters.Adapters.PlantPointsAdapter
import com.polito.sismic.Presenters.Helpers.TakeoverValueFormatter
import com.polito.sismic.R
import com.stepstone.stepper.StepperLayout
import com.stepstone.stepper.VerificationError
import kotlinx.android.synthetic.main.rilievi_report_layout.*
/**
* Created by Matteo on 10/08/2017.
*/
class RilieviReportFragment : BaseReportFragment(){
val mSismicPlantBuildingInteractor : SismicPlantBuildingInteractor by lazy {
SismicPlantBuildingInteractor(getReport().reportState.buildingState.takeoverState, context)
}
override fun onCreateView(inflater: LayoutInflater?, @Nullable container: ViewGroup?, @Nullable savedInstanceState: Bundle?): View? {
return inflateFragment(R.layout.rilievi_report_layout, inflater, container)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
piani_numero_parameter.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onItemSelected(parent: AdapterView<*>, mView: View?, pos: Int, id: Long) {
if (pos > 0)
altezza_piani_sup_parameter.visibility = View.VISIBLE
else
altezza_piani_sup_parameter.visibility = View.GONE
}
override fun onNothingSelected(parent: AdapterView<out Adapter>?) { }
}
altezza_piano_tr_parameter.attachDataConfirmedCallback {
if (altezza_piani_sup_parameter.visibility == View.VISIBLE)
altezza_piani_sup_parameter.requestFocus()
}
plant_point_list.layoutManager = LinearLayoutManager(activity)
val adapter = PlantPointsAdapter(activity, mSismicPlantBuildingInteractor){ plant_point_list?.adapter?.notifyDataSetChanged() }
plant_point_list.adapter = adapter
with(plant_graph)
{
val formatter = TakeoverValueFormatter()
xAxis.valueFormatter = formatter.xValueFormatter
getAxis(YAxis.AxisDependency.LEFT).valueFormatter = formatter.yValueFormatter
xAxis.position = XAxis.XAxisPosition.BOTTOM
legend.form = Legend.LegendForm.DEFAULT
legend.setCustom(listOf(LegendEntry(context.getString(R.string.rilievo_esterno), Legend.LegendForm.DEFAULT, 8f, 1f, null, Color.BLACK),
LegendEntry(context.getString(R.string.centro_di_massa), Legend.LegendForm.DEFAULT, 8f, 1f, null, Color.RED)))
description.isEnabled = false
getAxis(YAxis.AxisDependency.RIGHT).isEnabled = false
getAxis(YAxis.AxisDependency.LEFT).axisMinimum = 0f
}
calculate.setOnClickListener { updateGraph() }
}
override fun onReload() {
super.onReload()
updateGraph()
}
private fun updateGraph() = with(plant_graph)
{
plant_point_list?.adapter?.notifyDataSetChanged()
mSismicPlantBuildingInteractor.convertListForGraph()?.let {
data = it
invalidate()
updateLabels()
}
}
private fun updateLabels()
{
area_label.setValue(String.format(context.getString(R.string.area_label), "%.2f".format(mSismicPlantBuildingInteractor.area)))
perimeter_label.setValue(String.format(context.getString(R.string.perimeter_label), "%.2f".format(mSismicPlantBuildingInteractor.perimeter)))
barycenter_label.setValue(String.format(context.getString(R.string.barycenter_label),
"%.2f".format(mSismicPlantBuildingInteractor.mCenter.x),
"%.2f".format(mSismicPlantBuildingInteractor.mCenter.y)))
}
override fun verifyStep(): VerificationError? {
if (altezza_piano_tr_parameter.isEmpty()) return VerificationError(String.format(resources.getString(R.string.verification_empty_field), altezza_piano_tr_parameter.getTitle()))
if (altezza_piani_sup_parameter.visibility == View.VISIBLE && altezza_piani_sup_parameter.isEmpty()) return VerificationError(String.format(resources.getString(R.string.verification_empty_field), altezza_piani_sup_parameter.getTitle()))
if (mSismicPlantBuildingInteractor.mCenter == mSismicPlantBuildingInteractor.mOrigin) return VerificationError(resources.getString(R.string.verification_barycenter))
if (!mSismicPlantBuildingInteractor.isClosed()) return VerificationError(resources.getString(R.string.verification_takeover_invalid))
if (mSismicPlantBuildingInteractor.pointList.isEmpty()) return VerificationError(resources.getString(R.string.verification_takeover_points_not_present))
if (mSismicPlantBuildingInteractor.mFigure == null) return VerificationError(resources.getString(R.string.verification_takeover_figure_not_valid))
return null
}
override fun onNeedReload(): Boolean {
return true
}
//callback to activity updates domain instance for activity and all existing and future fragments
override fun onNextClicked(callback: StepperLayout.OnNextClickedCallback?) {
//Fixes the pillar count with the one that really exists in the graph
getReport().reportState.buildingState.takeoverState = UiMapper.createTakeoverStateForDomain(this)
super.onNextClicked(callback)
}
} | mit | f93b4e6638b8cf0de8cd4b50383b895b | 47.806452 | 244 | 0.733102 | 4.436217 | false | false | false | false |
jeffgbutler/mybatis-qbe | src/test/kotlin/examples/kotlin/mybatis3/canonical/YesNoTypeHandler.kt | 1 | 1406 | /*
* Copyright 2016-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package examples.kotlin.mybatis3.canonical
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.TypeHandler
import java.sql.CallableStatement
import java.sql.PreparedStatement
import java.sql.ResultSet
class YesNoTypeHandler : TypeHandler<Boolean> {
override fun setParameter(ps: PreparedStatement, i: Int, parameter: Boolean, jdbcType: JdbcType) =
ps.setString(i, if (parameter) "Yes" else "No")
override fun getResult(rs: ResultSet, columnName: String) =
"Yes" == rs.getString(columnName)
override fun getResult(rs: ResultSet, columnIndex: Int) =
"Yes" == rs.getString(columnIndex)
override fun getResult(cs: CallableStatement, columnIndex: Int) =
"Yes" == cs.getString(columnIndex)
}
| apache-2.0 | 728439d19de9ba12d21c5d04f92ecf1c | 37 | 102 | 0.722617 | 4.111111 | false | false | false | false |
FHannes/intellij-community | platform/platform-impl/src/com/intellij/internal/statistic/StatisticsUtil.kt | 6 | 3369 | /*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.internal.statistic
import com.intellij.internal.statistic.beans.UsageDescriptor
/**
* Constructs a proper UsageDescriptor for a boolean value,
* by adding "enabled" or "disabled" suffix to the given key, depending on the value.
*/
fun getBooleanUsage(key: String, value: Boolean): UsageDescriptor {
return UsageDescriptor(key + if (value) ".enabled" else ".disabled", 1)
}
fun getEnumUsage(key: String, value: Enum<*>?): UsageDescriptor {
return UsageDescriptor(key + "." + value?.name?.toLowerCase(), 1)
}
/**
* Constructs a proper UsageDescriptor for a counting value.
* If one needs to know a number of some items in the project, there is no direct way to report usages per-project.
* Therefore this workaround: create several keys representing interesting ranges, and report that key which correspond to the range
* which the given value belongs to.
*
* For example, to report a number of commits in Git repository, you can call this method like that:
* ```
* val usageDescriptor = getCountingUsage("git.commit.count", listOf(0, 1, 100, 10000, 100000), realCommitCount)
* ```
* and if there are e.g. 50000 commits in the repository, one usage of the following key will be reported: `git.commit.count.10K+`.
*
* NB:
* (1) the list of steps must be sorted ascendingly; If it is not, the result is undefined.
* (2) the value should lay somewhere inside steps ranges. If it is below the first step, the following usage will be reported:
* `git.commit.count.<1`.
*
* @key The key prefix which will be appended with "." and range code.
* @steps Limits of the ranges. Each value represents the start of the next range. The list must be sorted ascendingly.
* @value Value to be checked among the given ranges.
*/
fun getCountingUsage(key: String, value: Int, steps: List<Int>) : UsageDescriptor {
if (steps.isEmpty()) return UsageDescriptor("$key.$value", 1)
if (value < steps[0]) return UsageDescriptor("$key.<${steps[0]}", 1)
val index = steps.binarySearch(value)
val stepIndex : Int
if (index == steps.size) {
stepIndex = steps.last()
}
else if (index >= 0) {
stepIndex = index
}
else {
stepIndex = -index - 2
}
val step = steps[stepIndex]
val addPlus = stepIndex == steps.size - 1 || steps[stepIndex + 1] != step + 1
val maybePlus = if (addPlus) "+" else ""
return UsageDescriptor("$key.${humanize(step)}$maybePlus", 1)
}
private val kilo = 1000
private val mega = kilo * kilo
private fun humanize(number: Int): String {
if (number == 0) return "0"
val m = number / mega
val k = (number % mega) / kilo
val r = (number % kilo)
val ms = if (m > 0) "${m}M" else ""
val ks = if (k > 0) "${k}K" else ""
val rs = if (r > 0) "${r}" else ""
return ms + ks + rs
}
| apache-2.0 | 761524f22d3dc2b34dc44587445181ce | 38.174419 | 132 | 0.69724 | 3.772676 | false | false | false | false |
JVMDeveloperID/kotlin-android-example | app/src/main/kotlin/com/gojek/sample/kotlin/internal/data/local/realm/ContactRealm.kt | 1 | 771 | package com.gojek.sample.kotlin.internal.data.local.realm
import com.gojek.sample.kotlin.internal.data.local.RealmObjects
import com.gojek.sample.kotlin.internal.data.local.model.Contact
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
@RealmObjects
class ContactRealm : RealmObject() {
@PrimaryKey
var id: Int? = 0
var firstName: String? = ""
var lastName: String? = ""
var email: String? = ""
var phoneNumber: String? = ""
var profilePic: String? = ""
internal fun fill(contact: Contact?) {
id = contact?.id
firstName = contact?.firstName
lastName = contact?.lastName
email = contact?.email
phoneNumber = contact?.phoneNumber
profilePic = contact?.profilePic
}
} | apache-2.0 | 692eef26cc04a317a15e3ac764745b7c | 26.571429 | 64 | 0.680934 | 4.190217 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/opentasks/OpenTaskContentObserver.kt | 1 | 2133 | package org.tasks.opentasks
import android.content.ContentResolver
import android.content.Context
import android.content.SyncStatusObserver
import android.database.ContentObserver
import android.net.Uri
import android.os.Handler
import android.os.HandlerThread
import dagger.hilt.android.qualifiers.ApplicationContext
import org.dmfs.tasks.contract.TaskContract.*
import org.tasks.R
import org.tasks.sync.SyncAdapters
import timber.log.Timber
import javax.inject.Inject
class OpenTaskContentObserver @Inject constructor(
@ApplicationContext context: Context,
private val syncAdapters: SyncAdapters,
) : ContentObserver(getHandler()), SyncStatusObserver {
val authority = context.getString(R.string.opentasks_authority)
override fun onChange(selfChange: Boolean) = onChange(selfChange, null)
override fun onChange(selfChange: Boolean, uri: Uri?) {
if (selfChange || uri == null) {
Timber.d("Ignoring onChange(selfChange = $selfChange, uri = $uri)")
return
} else {
Timber.v("onChange($selfChange, $uri)")
}
syncAdapters.syncOpenTasks()
}
override fun onStatusChanged(which: Int) {
syncAdapters.setOpenTaskSyncActive(
ContentResolver.getCurrentSyncs().any { it.authority == authority }
)
}
companion object {
fun getHandler() = HandlerThread("OT-handler)").let {
it.start()
Handler(it.looper)
}
fun registerObserver(context: Context, observer: OpenTaskContentObserver) {
getUris(observer.authority).forEach {
context.contentResolver.registerContentObserver(it, false, observer)
}
ContentResolver.addStatusChangeListener(
ContentResolver.SYNC_OBSERVER_TYPE_ACTIVE,
observer
)
}
private fun getUris(authority: String): List<Uri> =
listOf(TaskLists.getContentUri(authority),
Tasks.getContentUri(authority),
Properties.getContentUri(authority))
}
}
| gpl-3.0 | 7cd4b92f6ee7be910df964b3fbd40886 | 32.328125 | 84 | 0.662447 | 4.825792 | false | false | false | false |
renard314/textfairy | app/src/main/java/com/renard/ocr/documents/creation/ocr/OCRImageView.kt | 1 | 10224 | /*
* Copyright (C) 2012,2013 Renard Wellnitz.
*
* 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.renard.ocr.documents.creation.ocr
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.core.graphics.times
import androidx.core.graphics.toRectF
import com.renard.ocr.R
import com.renard.ocr.documents.creation.crop.ImageViewTouchBase
import java.util.*
/**
* is used to show preview images and progress during ocr process
*
* @author renard
*/
class OCRImageView : ImageViewTouchBase {
private val mNumberStrokePaint = Paint()
private val mNumberPaint = Paint()
private val mWordPaint = Paint()
private val mBackgroundPaint = Paint()
private val mScanLinePaint = Paint()
private val mImageRectPaint = Paint()
private val mTextRectPaint = Paint()
private val mTouchedImageRectPaint = Paint()
private val mTouchedTextRectPaint = Paint()
private var mImageRects: MutableList<RectF> = mutableListOf()
private var mTextRects: MutableList<RectF> = mutableListOf()
private val mTouchedImageRects = ArrayList<RectF>()
private var mTouchedTextRects = ArrayList<RectF>()
private var mProgress = 0
private val mWordBoundingBox = RectF()
private val mOCRBoundingBox = RectF()
private val mViewDrawingRect = RectF()
constructor(context: Context) : super(context) {
init(context)
}
fun clearAllProgressInfo() {
mTouchedImageRects.clear()
mTouchedTextRects.clear()
mImageRects.clear()
mTextRects.clear()
mProgress = -1
mWordBoundingBox.setEmpty()
mOCRBoundingBox.setEmpty()
invalidate()
}
fun getSelectedImageIndexes(): IntArray {
val result = IntArray(mTouchedImageRects.size)
for (i in mTouchedImageRects.indices) {
val j = mImageRects.indexOf(mTouchedImageRects[i])
result[i] = j
}
return result
}
fun getSelectedTextIndexes(): IntArray {
val result = IntArray(mTouchedTextRects.size)
for (i in mTouchedTextRects.indices) {
val j = mTextRects.indexOf(mTouchedTextRects[i])
result[i] = j
}
return result
}
fun setImageRects(boxes: List<Rect>, pageWidth: Int, pageHeight: Int) {
val xScale = 1.0f * mBitmapDisplayed.width / pageWidth
mImageRects.apply {
clear()
addAll(boxes.map { it.toRectF().times(xScale) })
}
this.invalidate()
}
fun setTextRects(boxes: List<Rect>, pageWidth: Int, pageHeight: Int) {
val xScale = 1.0f * mBitmapDisplayed.width / pageWidth
mTextRects.apply {
clear()
addAll(boxes.map { it.toRectF().times(xScale) })
}
this.invalidate()
}
fun setProgress(newProgress: Int, wordBoundingBox: Rect, pageBoundingBox: Rect, pageWidth: Int, pageHeight: Int) {
if (mBitmapDisplayed.bitmap == null) {
return
}
// scale the word bounding rectangle to the preview image space
val xScale = 1.0f * mBitmapDisplayed.width / pageWidth
val wordBounds = wordBoundingBox.toRectF().times(xScale)
val ocrBounds = pageBoundingBox.toRectF().times(xScale)
mProgress = newProgress
mWordBoundingBox.set(wordBounds)
mOCRBoundingBox.set(ocrBounds)
this.invalidate()
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context)
mTouchedTextRects = ArrayList()
}
override fun onZoomFinished() {}
private fun init(c: Context) {
val progressColor = c.resources.getColor(R.color.progress_color)
mBackgroundPaint.setARGB(125, 50, 50, 50)
mScanLinePaint.color = progressColor
mScanLinePaint.strokeWidth = 3f
mScanLinePaint.isAntiAlias = true
mScanLinePaint.style = Paint.Style.STROKE
mWordPaint.setARGB(125, Color.red(progressColor), Color.green(progressColor), Color.blue(progressColor))
mImageRectPaint.color = progressColor
mImageRectPaint.strokeWidth = 3f
mImageRectPaint.isAntiAlias = true
mImageRectPaint.style = Paint.Style.STROKE
mTouchedImageRectPaint.setARGB(125, Color.red(progressColor), Color.green(progressColor), Color.blue(progressColor))
mTouchedImageRectPaint.strokeWidth = 3f
mTouchedImageRectPaint.isAntiAlias = true
mTouchedImageRectPaint.style = Paint.Style.FILL
mTextRectPaint.color = -0xffd501
mTextRectPaint.strokeWidth = 3f
mTextRectPaint.isAntiAlias = true
mTextRectPaint.style = Paint.Style.STROKE
mTouchedTextRectPaint.setARGB(125, 0x00, 0x2A, 0xFF)
mTouchedTextRectPaint.strokeWidth = 3f
mTouchedTextRectPaint.isAntiAlias = true
mTouchedTextRectPaint.style = Paint.Style.FILL
mNumberPaint.setARGB(0xff, 0x33, 0xb5, 0xe5)
mNumberPaint.textAlign = Paint.Align.CENTER
mNumberPaint.textSize = TEXT_SIZE * resources.displayMetrics.density
val tf = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD)
mNumberPaint.typeface = tf
mNumberPaint.isAntiAlias = true
mNumberPaint.maskFilter = BlurMaskFilter(3.toFloat(), BlurMaskFilter.Blur.SOLID)
mNumberStrokePaint.setARGB(255, 0, 0, 0)
mNumberStrokePaint.textAlign = Paint.Align.CENTER
mNumberStrokePaint.textSize = TEXT_SIZE * resources.displayMetrics.density
mNumberStrokePaint.typeface = tf
mNumberStrokePaint.style = Paint.Style.STROKE
mNumberStrokePaint.strokeWidth = 2f
mNumberStrokePaint.isAntiAlias = true
// mNumberPaint.setMaskFilter(new EmbossMaskFilter(new float[] { 1, 1,
// 1},0.8f, 10, 4f));
mProgress = -1
}
private fun updateTouchedBoxesByPoint(x: Float, y: Float, boxes: List<RectF>?, touchedBoxes: MutableList<RectF>) {
if (boxes != null) {
for (r in boxes) {
if (r.contains(x, y)) {
if (touchedBoxes.contains(r)) {
touchedBoxes.remove(r)
} else {
touchedBoxes.add(r)
}
}
}
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
when (event.action) {
MotionEvent.ACTION_DOWN -> {
val pts = floatArrayOf(event.x, event.y)
val inverse = Matrix()
imageViewMatrix.invert(inverse)
inverse.mapPoints(pts)
updateTouchedBoxesByPoint(pts[0], pts[1], mImageRects, mTouchedImageRects)
updateTouchedBoxesByPoint(pts[0], pts[1], mTextRects, mTouchedTextRects)
this.invalidate()
}
}
return super.onTouchEvent(event)
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
if (drawable == null) {
return
}
if (mProgress >= 0) {
drawBoxAroundCurrentWord(canvas)
/* draw progress rectangle */mViewDrawingRect[mOCRBoundingBox.left, mOCRBoundingBox.top, mOCRBoundingBox.right] = mOCRBoundingBox.bottom
imageViewMatrix.mapRect(mViewDrawingRect)
canvas.drawRect(mViewDrawingRect, mScanLinePaint)
val centerx = mViewDrawingRect.centerX()
val centery = mViewDrawingRect.centerY()
val pos = (mViewDrawingRect.height() * (mProgress / 100f)).toInt()
mViewDrawingRect.top += pos.toFloat()
canvas.drawRect(mViewDrawingRect, mBackgroundPaint)
canvas.drawLine(mViewDrawingRect.left, mViewDrawingRect.top, mViewDrawingRect.right, mViewDrawingRect.top, mScanLinePaint)
canvas.drawText("$mProgress%", centerx, centery, mNumberPaint)
canvas.drawText("$mProgress%", centerx, centery, mNumberStrokePaint)
}
/* draw boxes around text/images */drawRects(canvas, mImageRects, mImageRectPaint)
drawRects(canvas, mTextRects, mTextRectPaint)
/* draw special boxes around text/images selected by the user */drawRects(canvas, mTouchedImageRects, mTouchedImageRectPaint)
drawRectsWithIndex(canvas, mTouchedTextRects, mTouchedTextRectPaint)
}
private fun drawBoxAroundCurrentWord(canvas: Canvas) {
if (!mWordBoundingBox.isEmpty) {
imageViewMatrix.mapRect(mWordBoundingBox)
canvas.drawRect(mWordBoundingBox, mWordPaint)
}
}
private fun drawRectsWithIndex(canvas: Canvas, rects: ArrayList<RectF>?, paint: Paint) {
if (rects != null) {
val mappedRect = RectF()
for (i in rects.indices) {
val r = rects[i]
mappedRect.set(r)
imageViewMatrix.mapRect(mappedRect)
canvas.drawRect(mappedRect, paint)
canvas.drawText((i + 1).toString(), mappedRect.centerX(), mappedRect.centerY(), mNumberPaint)
canvas.drawText((i + 1).toString(), mappedRect.centerX(), mappedRect.centerY(), mNumberStrokePaint)
}
}
}
private fun drawRects(canvas: Canvas, rects: List<RectF>?, paint: Paint) {
if (rects != null) {
val mappedRect = RectF()
for (r in rects) {
mappedRect.set(r)
imageViewMatrix.mapRect(mappedRect)
canvas.drawRect(mappedRect, paint)
}
}
}
companion object {
private const val TEXT_SIZE = 60f
private val LOG_TAG = OCRImageView::class.java.simpleName
}
} | apache-2.0 | b68a7c765e9f6c492e25887b871efb39 | 38.478764 | 148 | 0.647105 | 4.284996 | false | false | false | false |
jereksel/LibreSubstratum | sublib/colorreader/src/main/java/com/jereksel/libresubstratumlib/colorreader/ColorReader.kt | 1 | 1161 | package com.jereksel.libresubstratumlib.colorreader
import java.io.File
import java.util.regex.Pattern
object ColorReader {
private val COLOR_PATTERN = Pattern.compile(":color/(.*):.*?d=(\\S*)")
fun getColorsValues(aapt: File, apk: File): List<Color> {
val cmd = listOf(aapt.absolutePath, "d", "resources", apk.absolutePath)
val proc = ProcessBuilder(cmd).start()
val statusCode = proc.waitFor()
val output = proc.inputStream.bufferedReader().use { it.readText() }
val error = proc.errorStream.bufferedReader().use { it.readText() }
if (statusCode != 0) {
throw RuntimeException(error)
}
return output.lineSequence()
.mapNotNull {
val matcher = COLOR_PATTERN.matcher(it)
if (matcher.find()) {
Color(matcher.group(1), matcher.group(2))
} else {
null
}
}
.toList()
}
fun getColorValue(aapt:File, apk: File, color: String) = getColorsValues(aapt, apk).first { it.name == color }.value
} | mit | 49546b1c7eee377e55d22ea483957a96 | 30.405405 | 120 | 0.555556 | 4.414449 | false | false | false | false |
nemerosa/ontrack | ontrack-repository-impl/src/main/java/net/nemerosa/ontrack/repository/AccountJdbcRepository.kt | 1 | 7284 | package net.nemerosa.ontrack.repository
import net.nemerosa.ontrack.model.Ack
import net.nemerosa.ontrack.model.exceptions.AccountNameAlreadyDefinedException
import net.nemerosa.ontrack.model.exceptions.AccountNotFoundException
import net.nemerosa.ontrack.model.security.*
import net.nemerosa.ontrack.model.security.Account.Companion.of
import net.nemerosa.ontrack.model.structure.ID
import net.nemerosa.ontrack.model.structure.ID.Companion.of
import net.nemerosa.ontrack.repository.support.AbstractJdbcRepository
import org.apache.commons.lang3.StringUtils
import org.springframework.dao.DuplicateKeyException
import org.springframework.stereotype.Repository
import java.sql.ResultSet
import javax.sql.DataSource
@Repository
class AccountJdbcRepository(
dataSource: DataSource,
private val authenticationSourceRepository: AuthenticationSourceRepository
) : AbstractJdbcRepository(dataSource), AccountRepository {
override fun findBuiltinAccount(username: String): BuiltinAccount? {
return getFirstItem(
"SELECT * FROM ACCOUNTS WHERE PROVIDER = :provider AND NAME = :name",
params("name", username)
.addValue("provider", BuiltinAuthenticationSourceProvider.ID)
) { rs: ResultSet, _: Int ->
toAccount(rs)?.let { account ->
BuiltinAccount(
account,
rs.getString("password")
)
}
}
}
private fun toAccount(rs: ResultSet): Account? {
val authenticationSource = rs.getAuthenticationSource(authenticationSourceRepository)
return authenticationSource?.let {
of(
rs.getString("name"),
rs.getString("fullName"),
rs.getString("email"),
getEnum(SecurityRole::class.java, rs, "role"),
authenticationSource,
disabled = rs.getBoolean("disabled"),
locked = rs.getBoolean("locked"),
).withId(id(rs))
}
}
override fun findAll(): Collection<Account> {
return jdbcTemplate!!.query(
"SELECT * FROM ACCOUNTS ORDER BY NAME"
) { rs: ResultSet, _ ->
toAccount(rs)
}
}
override fun newAccount(account: Account): Account {
return try {
val id = dbCreate(
"INSERT INTO ACCOUNTS (NAME, FULLNAME, EMAIL, PROVIDER, SOURCE, PASSWORD, ROLE, DISABLED, LOCKED) " +
"VALUES (:name, :fullName, :email, :provider, :source, :password, :role, :disabled, :locked)",
account.authenticationSource.asParams()
.addValue("name", account.name)
.addValue("fullName", account.fullName)
.addValue("email", account.email)
.addValue("password", "")
.addValue("role", account.role.name)
.addValue("disabled", account.disabled)
.addValue("locked", account.locked)
)
account.withId(of(id))
} catch (ex: DuplicateKeyException) {
throw AccountNameAlreadyDefinedException(account.name)
}
}
override fun saveAccount(account: Account) {
try {
namedParameterJdbcTemplate!!.update(
"UPDATE ACCOUNTS SET NAME = :name, FULLNAME = :fullName, EMAIL = :email, DISABLED = :disabled, LOCKED = :locked " +
"WHERE ID = :id",
params("id", account.id())
.addValue("name", account.name)
.addValue("fullName", account.fullName)
.addValue("email", account.email)
.addValue("disabled", account.disabled)
.addValue("locked", account.locked)
)
} catch (ex: DuplicateKeyException) {
throw AccountNameAlreadyDefinedException(account.name)
}
}
override fun deleteAccount(accountId: ID): Ack {
return Ack.one(
namedParameterJdbcTemplate!!.update(
"DELETE FROM ACCOUNTS WHERE ID = :id",
params("id", accountId.value)
)
)
}
override fun setPassword(accountId: Int, encodedPassword: String) {
namedParameterJdbcTemplate!!.update(
"UPDATE ACCOUNTS SET PASSWORD = :password WHERE ID = :id",
params("id", accountId)
.addValue("password", encodedPassword)
)
}
override fun getAccount(accountId: ID): Account {
return namedParameterJdbcTemplate!!.queryForObject(
"SELECT * FROM ACCOUNTS WHERE ID = :id",
params("id", accountId.value)
) { rs: ResultSet, _ ->
toAccount(rs)
} ?: throw AccountNotFoundException(accountId.value)
}
override fun deleteAccountBySource(source: AuthenticationSource) {
namedParameterJdbcTemplate!!.update(
"DELETE FROM ACCOUNTS WHERE PROVIDER = :provider AND SOURCE = :source",
source.asParams()
)
}
override fun doesAccountIdExist(id: ID): Boolean {
return getFirstItem(
"SELECT ID FROM ACCOUNTS WHERE ID = :id",
params("id", id.value),
Int::class.java
) != null
}
override fun findByNameToken(token: String): List<Account> {
return namedParameterJdbcTemplate!!.query(
"SELECT * FROM ACCOUNTS WHERE LOWER(NAME) LIKE :filter ORDER BY NAME",
params("filter", String.format("%%%s%%", StringUtils.lowerCase(token)))
) { rs: ResultSet, _ ->
toAccount(rs)
}
}
override fun getAccountsForGroup(accountGroup: AccountGroup): List<Account> {
return namedParameterJdbcTemplate!!.query(
"SELECT A.* FROM ACCOUNTS A " +
"INNER JOIN ACCOUNT_GROUP_LINK L ON L.ACCOUNT = A.ID " +
"WHERE L.ACCOUNTGROUP = :accountGroupId " +
"ORDER BY A.NAME ASC",
params("accountGroupId", accountGroup.id())
) { rs: ResultSet, _ ->
toAccount(rs)
}
}
override fun findAccountByName(username: String): Account? {
return getFirstItem(
"SELECT * FROM ACCOUNTS WHERE NAME = :name",
params("name", username)
) { rs: ResultSet, _ ->
toAccount(rs)
}
}
override fun setAccountDisabled(id: ID, disabled: Boolean) {
namedParameterJdbcTemplate!!.update(
"UPDATE ACCOUNTS SET DISABLED = :disabled WHERE ID = :id",
params("id", id.get())
.addValue("disabled", disabled)
)
}
override fun setAccountLocked(id: ID, locked: Boolean) {
namedParameterJdbcTemplate!!.update(
"UPDATE ACCOUNTS SET LOCKED = :locked WHERE ID = :id",
params("id", id.get())
.addValue("locked", locked)
)
}
} | mit | 65e92ac5f045f7a37e6f6b35e41935fe | 38.592391 | 135 | 0.562328 | 5.140438 | false | false | false | false |
xiaojinzi123/Component | ComponentImpl/src/main/java/com/xiaojinzi/component/impl/RouterFragment.kt | 1 | 2968 | package com.xiaojinzi.component.impl
import android.content.Intent
import androidx.fragment.app.Fragment
import com.xiaojinzi.component.bean.ActivityResult
import com.xiaojinzi.component.support.Consumer1
import java.util.*
/**
* 为了完成跳转拿 [ActivityResult] 的功能, 需要预埋一个 [Fragment]
* 此 [Fragment] 是不可见的, 它的主要作用:
* 1. 用作跳转的
* 2. 用作接受 [Fragment.onActivityResult] 的回调的值
*
*
* 当发出多个路由的之后, 有可能多个 [RouterRequest] 对象中的 [RouterRequest.requestCode]
* 是一致的, 那么就会造成 [ActivityResult] 回调的时候出现不对应的问题.
* 这个问题在 [com.xiaojinzi.component.impl.NavigatorImpl.Help.isExist] 方法中
* 得以保证
*
*
* time : 2018/11/03
*
* @author : xiaojinzi
*/
class RouterFragment : Fragment() {
private val singleEmitterMap: MutableMap<RouterRequest, Consumer1<ActivityResult>> = HashMap()
override fun onDestroy() {
super.onDestroy()
singleEmitterMap.clear()
}
/**
* 此方法我觉得官方不应该废弃的. 因为新的方式其实在易用性上并不好.
* 不过官方废弃了那我也只能支持官方的方式:[Call.navigateForTargetIntent]
* 或者 [Call.forwardForTargetIntent] 都可以在回调中拿到目标界面的 Intent.
* 这时候, 路由框架是不会发起跳转的.
*
* @param requestCode 业务请求码
* @param resultCode 返回码
* @param data 返回的数据
*/
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// 根据 requestCode 获取发射器
var findConsumer: Consumer1<ActivityResult>? = null
var findRequest: RouterRequest? = null
// 找出 requestCode 一样的那个
val keySet: Set<RouterRequest> = singleEmitterMap.keys
for (request in keySet) {
if (request.requestCode != null && request.requestCode == requestCode) {
findRequest = request
break
}
}
if (findRequest != null) {
findConsumer = singleEmitterMap[findRequest]
}
if (findConsumer != null) {
try {
findConsumer.accept(ActivityResult(requestCode, resultCode, data))
} catch (ignore: Exception) {
// ignore
}
}
if (findRequest != null) {
singleEmitterMap.remove(findRequest)
}
}
fun addActivityResultConsumer(request: RouterRequest,
consumer: Consumer1<ActivityResult>) {
// 检测是否重复的在这个方法调用之前被检查掉了
singleEmitterMap[request] = consumer
}
fun removeActivityResultConsumer(request: RouterRequest) {
singleEmitterMap.remove(request)
}
} | apache-2.0 | 35ae986db988a6a64e3a04130570fb49 | 28.964286 | 98 | 0.63752 | 3.744048 | false | false | false | false |
jaredsburrows/cs-interview-questions | kotlin/src/main/kotlin/api/LinkedList.kt | 1 | 719 | package api
data class LinkedList<T>(val value: T? = null) {
var head: Node<T>? = null
var next: Node<T>? = head?.next
constructor() : this(null)
fun addToFront(value: T) {
val node = Node(value)
node.next = head
head = node
}
fun add(value: T) {
addToEnd(value)
}
fun addToEnd(value: T) {
var temp = head
while (temp?.next != null) {
temp = temp.next
}
temp?.next = Node(value)
}
fun removeFront() {
head = head?.next
}
fun removeLast() {
var temp = head
while (temp?.next?.next != null) {
temp = temp.next
}
temp?.next = null
}
}
| apache-2.0 | fbea5f79173bc266bcd12f2f2e2204c3 | 17.921053 | 48 | 0.482615 | 3.668367 | false | false | false | false |
255BITS/hypr | app/src/main/java/hypr/hypergan/com/hypr/Network/ModelApi.kt | 1 | 1988 | package hypr.hypergan.com.hypr.Network
import android.content.Context
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import hypr.hypergan.com.hypr.Generator.Generator
import retrofit2.Retrofit
import retrofit2.converter.scalars.ScalarsConverterFactory
import java.io.File
import java.lang.reflect.Type
class ModelApi {
private val BASE_URL = "https://gist.githubusercontent.com"
val retrofit: Retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(ScalarsConverterFactory.create())
.build()
val service: ModelService? = retrofit.create(ModelService::class.java)
val generatorFileName = "generatorJson.json"
fun listOfModels(context: Context): List<Generator>? {
val type: Type = Types.newParameterizedType(List::class.java, Generator::class.java)
val adapter: JsonAdapter<List<Generator>> = Moshi.Builder().build().adapter(type)
val cachedFile = File(context.cacheDir, generatorFileName)
return if (cachedFile.exists()) {
getCachedGenerator(adapter, cachedFile)
} else {
getGeneratorFromNetwork(adapter, cachedFile)
}
}
private fun getGeneratorFromNetwork(adapter: JsonAdapter<List<Generator>>, cachedFile: File): List<Generator>? {
val jsonString: String? = service?.listOfModels()?.execute()?.body().toString()
val json = adapter.fromJson(jsonString)
cacheGenerators(jsonString!!, cachedFile)
return json
}
private fun getCachedGenerator(adapter: JsonAdapter<List<Generator>>, cachedFile: File): List<Generator>? {
val cachedFileRead = cachedFile.readText()
return adapter.fromJson(cachedFileRead)
}
private fun cacheGenerators(generatorJson: String, cachedFile: File) {
cachedFile.bufferedWriter().use { out ->
generatorJson.forEach { text -> out.write(text.toString()) }
}
}
} | mit | 0bd9da71e2c2fbdfddf1d7c0812f4e19 | 38.78 | 116 | 0.703219 | 4.497738 | false | false | false | false |
android/health-samples | health-connect/HealthConnectSample/app/src/main/java/com/example/healthconnectsample/presentation/screen/exercisesessiondetail/ExerciseSessionDetailViewModel.kt | 1 | 5074 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.healthconnectsample.presentation.screen.exercisesessiondetail
import android.os.RemoteException
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.health.connect.client.permission.HealthPermission
import androidx.health.connect.client.records.DistanceRecord
import androidx.health.connect.client.records.HeartRateRecord
import androidx.health.connect.client.records.SpeedRecord
import androidx.health.connect.client.records.StepsRecord
import androidx.health.connect.client.records.TotalCaloriesBurnedRecord
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.example.healthconnectsample.data.ExerciseSessionData
import com.example.healthconnectsample.data.HealthConnectManager
import kotlinx.coroutines.launch
import java.io.IOException
import java.util.UUID
class ExerciseSessionDetailViewModel(
private val uid: String,
private val healthConnectManager: HealthConnectManager
) : ViewModel() {
val permissions = setOf(
HealthPermission.createReadPermission(StepsRecord::class),
HealthPermission.createReadPermission(DistanceRecord::class),
HealthPermission.createReadPermission(SpeedRecord::class),
HealthPermission.createReadPermission(TotalCaloriesBurnedRecord::class),
HealthPermission.createReadPermission(HeartRateRecord::class)
)
var permissionsGranted = mutableStateOf(false)
private set
var sessionMetrics: MutableState<ExerciseSessionData> = mutableStateOf(ExerciseSessionData(uid))
private set
var uiState: UiState by mutableStateOf(UiState.Uninitialized)
private set
val permissionsLauncher = healthConnectManager.requestPermissionsActivityContract()
fun initialLoad() {
readAssociatedSessionData()
}
private fun readAssociatedSessionData() {
viewModelScope.launch {
tryWithPermissionsCheck {
sessionMetrics.value = healthConnectManager.readAssociatedSessionData(uid)
}
}
}
/**
* Provides permission check and error handling for Health Connect suspend function calls.
*
* Permissions are checked prior to execution of [block], and if all permissions aren't granted
* the [block] won't be executed, and [permissionsGranted] will be set to false, which will
* result in the UI showing the permissions button.
*
* Where an error is caught, of the type Health Connect is known to throw, [uiState] is set to
* [UiState.Error], which results in the snackbar being used to show the error message.
*/
private suspend fun tryWithPermissionsCheck(block: suspend () -> Unit) {
permissionsGranted.value = healthConnectManager.hasAllPermissions(permissions)
uiState = try {
if (permissionsGranted.value) {
block()
}
UiState.Done
} catch (remoteException: RemoteException) {
UiState.Error(remoteException)
} catch (securityException: SecurityException) {
UiState.Error(securityException)
} catch (ioException: IOException) {
UiState.Error(ioException)
} catch (illegalStateException: IllegalStateException) {
UiState.Error(illegalStateException)
}
}
sealed class UiState {
object Uninitialized : UiState()
object Done : UiState()
// A random UUID is used in each Error object to allow errors to be uniquely identified,
// and recomposition won't result in multiple snackbars.
data class Error(val exception: Throwable, val uuid: UUID = UUID.randomUUID()) : UiState()
}
}
class ExerciseSessionDetailViewModelFactory(
private val uid: String,
private val healthConnectManager: HealthConnectManager
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(ExerciseSessionDetailViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return ExerciseSessionDetailViewModel(
uid = uid,
healthConnectManager = healthConnectManager
) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| apache-2.0 | 5bb794df86c6d49eda9bd74bdae8e5f4 | 39.592 | 100 | 0.729996 | 5.188139 | false | false | false | false |
ffc-nectec/FFC | ffc/src/main/kotlin/ffc/app/search/RecentSearchProvider.kt | 1 | 1237 | package ffc.app.search
import android.app.SearchManager
import android.app.SearchManager.SUGGEST_URI_PATH_QUERY
import android.content.Context
import android.content.SearchRecentSuggestionsProvider
import android.net.Uri
class RecentSearchProvider : SearchRecentSuggestionsProvider() {
init {
setupSuggestions(AUTHORITY, MODE)
}
companion object {
const val AUTHORITY = "ffc.app.search.RecentSearchProvider"
const val MODE: Int = SearchRecentSuggestionsProvider.DATABASE_MODE_QUERIES
val URI = Uri.parse("content://" + AUTHORITY + '/' + SUGGEST_URI_PATH_QUERY)
fun query(context: Context, query: String? = "", limit: Int = 8): List<String> {
val suggestion = mutableListOf<String>()
context.contentResolver.query(URI, null, null, arrayOf(query), null)?.let { cursor ->
val loop = if (cursor.count > limit) limit else cursor.count - 1
for (i in 0..loop) {
cursor.moveToPosition(i)
suggestion.add(cursor.getString(cursor.getColumnIndex(SearchManager.SUGGEST_COLUMN_TEXT_1)))
}
cursor.close()
}
return suggestion
}
}
}
| apache-2.0 | 95ead01def7bc095a2a36750cadf3b1c | 36.484848 | 112 | 0.63945 | 4.598513 | false | false | false | false |
martypitt/boxtape | cli/src/main/java/io/boxtape/cli/core/MavenDependencyCollector.kt | 1 | 1468 | package io.boxtape.core
import org.apache.maven.cli.MavenCli
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.PrintStream
import java.util.regex.Pattern
@Component
public class MavenDependencyCollector @Autowired constructor(val mvn: MavenCli) {
val ALPHA_CHARACTER = Pattern.compile("[a-zA-Z]");
val GROUP_ID = 0
val ARTIFACT_ID = 1
val VERSION = 3
fun collect(project: Project):List<Dependency> {
val outputStream = ByteArrayOutputStream()
val printStream = PrintStream(outputStream)
val outputFile = File.createTempFile("dependencies",".txt")
System.setProperty("maven.multiModuleProjectDirectory" , project.projectHome().canonicalPath)
mvn.doMain(arrayOf("dependency:tree","-Dscope=compile", "-DoutputFile=${outputFile.getCanonicalPath()}"), project.projectHome().canonicalPath, printStream, printStream)
val output = outputFile.readLines()
.map { trimTreeSyntax(it) }
.map {
val parts = it.splitBy(":")
Dependency(parts[GROUP_ID], parts[ARTIFACT_ID], parts[VERSION])
}
return output
}
private fun trimTreeSyntax(line: String): String {
val matcher = ALPHA_CHARACTER.matcher(line)
return if (matcher.find()) line.substring(matcher.start()) else ""
}
}
| apache-2.0 | ca078bbce857c329a5756e40aa22b2de | 35.7 | 176 | 0.692779 | 4.489297 | false | false | false | false |
AndroidX/androidx | compose/foundation/foundation/benchmark/src/androidTest/java/androidx/compose/foundation/benchmark/text/AnnotatedTextInColumnTestCase.kt | 3 | 2389 | /*
* 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.foundation.benchmark.text
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.testutils.LayeredComposeTestCase
import androidx.compose.testutils.ToggleableTestCase
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.TextUnit
/**
* The benchmark test case for [Text], where the input is a plain annotated string.
*/
class AnnotatedTextInColumnTestCase(
private val texts: List<AnnotatedString>,
private val width: Dp,
private val fontSize: TextUnit
) : LayeredComposeTestCase(), ToggleableTestCase {
private val color = mutableStateOf(Color.Black)
@Composable
override fun MeasuredContent() {
for (text in texts) {
Text(text = text, color = color.value, fontSize = fontSize)
}
}
@Composable
override fun ContentWrappers(content: @Composable () -> Unit) {
Column(
modifier = Modifier.wrapContentSize(Alignment.Center).width(width)
.verticalScroll(rememberScrollState())
) {
content()
}
}
override fun toggleState() {
if (color.value == Color.Black) {
color.value = Color.Red
} else {
color.value = Color.Black
}
}
} | apache-2.0 | d3c26366395476d930901df568d0e41b | 32.661972 | 83 | 0.729175 | 4.55916 | false | true | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/definitions/implementations/Cast.kt | 1 | 3009 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.definitions.implementations
import onnx.Onnx
import org.nd4j.autodiff.samediff.SDVariable
import org.nd4j.autodiff.samediff.SameDiff
import org.nd4j.autodiff.samediff.internal.SameDiffOp
import org.nd4j.samediff.frameworkimport.ImportGraph
import org.nd4j.samediff.frameworkimport.hooks.PreImportHook
import org.nd4j.samediff.frameworkimport.hooks.annotations.PreHookRule
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRDataType
import org.nd4j.samediff.frameworkimport.registry.OpMappingRegistry
import org.nd4j.shade.protobuf.GeneratedMessageV3
import org.nd4j.shade.protobuf.ProtocolMessageEnum
import java.lang.IllegalArgumentException
/**
* A port of cast.py from onnx tensorflow for samediff:
* https://github.com/onnx/onnx-tensorflow/blob/master/onnx_tf/handlers/backend/cast.py
*
* @author Adam Gibson
*/
@PreHookRule(nodeNames = [],opNames = ["Cast"],frameworkName = "onnx")
class Cast : PreImportHook {
override fun doImport(
sd: SameDiff,
attributes: Map<String, Any>,
outputNames: List<String>,
op: SameDiffOp,
mappingRegistry: OpMappingRegistry<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum, GeneratedMessageV3, GeneratedMessageV3>,
importGraph: ImportGraph<GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, GeneratedMessageV3, ProtocolMessageEnum>,
dynamicVariables: Map<String, GeneratedMessageV3>
): Map<String, List<SDVariable>> {
var inputVariable = sd.getVariable(op.inputsToOp[0])
if(!attributes.containsKey("to")) {
throw IllegalArgumentException("")
}
val dTypeIndex = attributes["to"] as Long
val dtype = Onnx.TensorProto.DataType.values()[dTypeIndex.toInt()]
val inputDataType = OnnxIRDataType(dtype)
val newDataType = inputDataType.nd4jDataType()
val outputVar = sd.castTo(outputNames[0],inputVariable,newDataType)
return mapOf(outputVar.name() to listOf(outputVar))
}
} | apache-2.0 | b71b71d785357a4e74b7d085b73f0b5b | 44.606061 | 184 | 0.709206 | 4.298571 | false | false | false | false |
codeka/wwmmo | server/src/main/kotlin/au/com/codeka/warworlds/server/store/SequenceStore.kt | 1 | 2223 | package au.com.codeka.warworlds.server.store
import au.com.codeka.warworlds.server.store.base.BaseStore
const val DATA_STORE_INCREMENT_AMOUNT = 100L
/**
* A store for storing a sequence of unique IDs. To keep this performant, we only query/update the
* actual data store in batches. Each time we increment the counter in the data store by
* [.DATA_STORE_INCREMENT_AMOUNT], and then return values from that "pool" each time
* [.nextIdentifier] is called.
*/
class SequenceStore internal constructor(fileName: String) : BaseStore(fileName) {
private val lock = Any()
/** The next identifier that we should return. */
private var identifier: Long = 0
/**
* The maximum identifier we can return without having to go back to the store to fetch another
* batch.
*/
private var maxIdentifier: Long = 0
/** Returns the next identifier in the sequence. */
fun nextIdentifier(): Long {
synchronized(lock) {
if (identifier == maxIdentifier) {
try {
newReader().stmt("SELECT id FROM identifiers").query().use { res ->
if (!res.next()) {
throw RuntimeException("Expected at least one row in identifiers table.")
}
identifier = res.getLong(0)
maxIdentifier = identifier + DATA_STORE_INCREMENT_AMOUNT
}
} catch (e: Exception) {
// We can't continue if this fails, it'll cause irreversible corruption.
throw RuntimeException(e)
}
try {
newWriter()
.stmt("UPDATE identifiers SET id = ?")
.param(0, maxIdentifier)
.execute()
} catch (e: StoreException) {
// We can't continue if this fails, it'll cause irreversible corruption.
throw RuntimeException(e)
}
}
identifier++
return identifier
}
}
override fun onOpen(diskVersion: Int): Int {
var version = diskVersion
if (version == 0) {
newWriter()
.stmt("CREATE TABLE identifiers (id INTEGER PRIMARY KEY)")
.execute()
newWriter()
.stmt("INSERT INTO identifiers (id) VALUES (100)")
.execute()
version++
}
return version
}
} | mit | c39732f17edaadbd60be429bf60149d4 | 31.231884 | 98 | 0.617634 | 4.481855 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/move/common/RsMoveTraitMethodsProcessor.kt | 3 | 5109 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.move.common
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.NlsContexts.DialogMessage
import com.intellij.psi.PsiElement
import com.intellij.util.containers.MultiMap
import org.rust.ide.refactoring.move.common.RsMoveUtil.isInsideMovedElements
import org.rust.ide.utils.import.RsImportHelper
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
/**
* To resolve some references it is needed to have trait in scope. E.g.:
* - `expr.trait_method()`
* - `Trait::trait_method(expr)`
* - `Trait::AssocConst`
* This class finds such references inside [sourceMod] and adds necessary trait imports.
* There are two types of references:
* - Outside references from moved item to method of trait which is in scope of [sourceMod]
* - Inside references from item in [sourceMod] to method of moved trait
*/
class RsMoveTraitMethodsProcessor(
private val psiFactory: RsPsiFactory,
private val sourceMod: RsMod,
private val targetMod: RsMod,
private val pathHelper: RsMovePathHelper
) {
fun preprocessOutsideReferences(
@Suppress("UnstableApiUsage") conflicts: MultiMap<PsiElement, @DialogMessage String>,
elementsToMove: List<ElementToMove>
) {
val references = getReferencesToTraitAssocItems(elementsToMove)
preprocessReferencesToTraitAssocItems(
references,
conflicts,
{ trait -> RsImportHelper.findPath(targetMod, trait) },
{ trait -> !trait.isInsideMovedElements(elementsToMove) }
)
}
fun preprocessInsideReferences(
@Suppress("UnstableApiUsage") conflicts: MultiMap<PsiElement, @DialogMessage String>,
elementsToMove: List<ElementToMove>
) {
val traitsToMove = elementsToMove
.filterIsInstance<ItemToMove>()
.map { it.item }
.filterIsInstance<RsTraitItem>()
.toSet()
if (traitsToMove.isEmpty()) return
val references = sourceMod.descendantsOfType<RsReferenceElement>()
.filter { it.isMethodOrPath() && !it.isInsideMovedElements(elementsToMove) }
preprocessReferencesToTraitAssocItems(
references,
conflicts,
{ trait -> pathHelper.findPathAfterMove(sourceMod, trait)?.text },
{ trait -> trait in traitsToMove }
)
}
private fun preprocessReferencesToTraitAssocItems(
references: List<RsReferenceElement>,
@Suppress("UnstableApiUsage") conflicts: MultiMap<PsiElement, @DialogMessage String>,
findTraitUsePath: (RsTraitItem) -> String?,
shouldProcessTrait: (RsTraitItem) -> Boolean
) {
for (reference in references) {
val assocItem = reference.reference?.resolve() as? RsAbstractable ?: continue
if (assocItem !is RsFunction && assocItem !is RsConstant) continue
val trait = assocItem.getTrait() ?: continue
if (!shouldProcessTrait(trait)) continue
val traitUsePath = findTraitUsePath(trait)
if (traitUsePath == null) {
addVisibilityConflict(conflicts, reference, assocItem.superItem ?: trait)
} else {
reference.putCopyableUserData(RS_METHOD_CALL_TRAIT_USE_PATH, Pair(trait, traitUsePath))
}
}
}
fun addTraitImportsForOutsideReferences(elementsToMove: List<ElementToMove>) =
addTraitImportsForReferences(getReferencesToTraitAssocItems(elementsToMove))
fun addTraitImportsForInsideReferences() {
val references = sourceMod.descendantsOfType<RsReferenceElement>().filter { it.isMethodOrPath() }
addTraitImportsForReferences(references)
}
private fun addTraitImportsForReferences(references: Collection<RsReferenceElement>) {
for (reference in references) {
val (trait, traitUsePath) = reference.getCopyableUserData(RS_METHOD_CALL_TRAIT_USE_PATH) ?: continue
// can't check `reference.reference.resolve() != null`, because it is always not null
if (listOf(trait).filterInScope(reference).isNotEmpty()) continue
addImport(psiFactory, reference, traitUsePath)
}
}
companion object {
private val RS_METHOD_CALL_TRAIT_USE_PATH: Key<Pair<RsTraitItem, String>> = Key.create("RS_METHOD_CALL_TRAIT_USE_PATH")
}
}
private fun getReferencesToTraitAssocItems(elementsToMove: List<ElementToMove>): List<RsReferenceElement> =
movedElementsShallowDescendantsOfType<RsReferenceElement>(elementsToMove, processInlineModules = false)
.filter(RsReferenceElement::isMethodOrPath)
private fun RsReferenceElement.isMethodOrPath(): Boolean = this is RsMethodCall || this is RsPath
private fun RsAbstractable.getTrait(): RsTraitItem? {
return when (val owner = owner) {
is RsAbstractableOwner.Trait -> owner.trait
is RsAbstractableOwner.Impl -> owner.impl.traitRef?.resolveToTrait()
else -> null
}
}
| mit | b34d58e3c387e982d148c3d47427f7bf | 40.877049 | 127 | 0.694461 | 4.695772 | false | false | false | false |
oldcwj/iPing | commons/src/main/kotlin/com/simplemobiletools/commons/models/FileDirItem.kt | 1 | 2017 | package com.simplemobiletools.commons.models
import com.simplemobiletools.commons.helpers.SORT_BY_DATE_MODIFIED
import com.simplemobiletools.commons.helpers.SORT_BY_NAME
import com.simplemobiletools.commons.helpers.SORT_BY_SIZE
import com.simplemobiletools.commons.helpers.SORT_DESCENDING
import java.io.File
data class FileDirItem(val path: String, val name: String, val isDirectory: Boolean, val children: Int, val size: Long) :
Comparable<FileDirItem> {
companion object {
var sorting: Int = 0
}
override fun compareTo(other: FileDirItem): Int {
return if (isDirectory && !other.isDirectory) {
-1
} else if (!isDirectory && other.isDirectory) {
1
} else {
var result: Int
when {
sorting and SORT_BY_NAME != 0 -> result = name.toLowerCase().compareTo(other.name.toLowerCase())
sorting and SORT_BY_SIZE != 0 -> result = when {
size == other.size -> 0
size > other.size -> 1
else -> -1
}
sorting and SORT_BY_DATE_MODIFIED != 0 -> {
val file = File(path)
val otherFile = File(other.path)
result = when {
file.lastModified() == otherFile.lastModified() -> 0
file.lastModified() > otherFile.lastModified() -> 1
else -> -1
}
}
else -> {
val extension = if (isDirectory) name else path.substringAfterLast('.', "")
val otherExtension = if (other.isDirectory) other.name else other.path.substringAfterLast('.', "")
result = extension.toLowerCase().compareTo(otherExtension.toLowerCase())
}
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
result
}
}
}
| gpl-3.0 | 83e551bfccd26496de45bd04e3002af0 | 38.54902 | 121 | 0.529499 | 5.055138 | false | false | false | false |
androidx/androidx | viewpager2/integration-tests/testapp/src/main/java/androidx/viewpager2/integration/testapp/BrowseActivity.kt | 3 | 3796 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.viewpager2.integration.testapp
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ListView
import android.widget.SimpleAdapter
/**
* This activity lists all the activities in this application.
*/
@Suppress("DEPRECATION")
class BrowseActivity : android.app.ListActivity() {
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
listAdapter = SimpleAdapter(
this, getData(),
android.R.layout.simple_list_item_1, arrayOf("title"),
intArrayOf(android.R.id.text1)
)
}
private fun getData(): List<Map<String, Any>> {
val myData = mutableListOf<Map<String, Any>>()
myData.add(
mapOf(
"title" to "ViewPager2 with Views",
"intent" to activityToIntent(CardViewActivity::class.java.name)
)
)
myData.add(
mapOf(
"title" to "ViewPager2 with Fragments",
"intent" to activityToIntent(CardFragmentActivity::class.java.name)
)
)
myData.add(
mapOf(
"title" to "ViewPager2 with a Mutable Collection (Views)",
"intent" to activityToIntent(MutableCollectionViewActivity::class.java.name)
)
)
myData.add(
mapOf(
"title" to "ViewPager2 with a Mutable Collection (Fragments)",
"intent" to activityToIntent(MutableCollectionFragmentActivity::class.java.name)
)
)
myData.add(
mapOf(
"title" to "ViewPager2 with a TabLayout (Views)",
"intent" to activityToIntent(CardViewTabLayoutActivity::class.java.name)
)
)
myData.add(
mapOf(
"title" to "ViewPager2 with Fake Dragging",
"intent" to activityToIntent(FakeDragActivity::class.java.name)
)
)
myData.add(
mapOf(
"title" to "ViewPager2 with PageTransformers",
"intent" to activityToIntent(PageTransformerActivity::class.java.name)
)
)
myData.add(
mapOf(
"title" to "ViewPager2 with a Preview of Next/Prev Page",
"intent" to activityToIntent(PreviewPagesActivity::class.java.name)
)
)
myData.add(
mapOf(
"title" to "ViewPager2 with Nested RecyclerViews",
"intent" to activityToIntent(ParallelNestedScrollingActivity::class.java.name)
)
)
return myData
}
private fun activityToIntent(activity: String): Intent =
Intent(Intent.ACTION_VIEW).setClassName(this.packageName, activity)
override fun onListItemClick(listView: ListView, view: View, position: Int, id: Long) {
val map = listView.getItemAtPosition(position) as Map<*, *>
val intent = Intent(map["intent"] as Intent)
intent.addCategory(Intent.CATEGORY_SAMPLE_CODE)
startActivity(intent)
}
}
| apache-2.0 | 9d5e74fded24d49c085de7e5e890522e | 32.892857 | 96 | 0.608799 | 4.780856 | false | false | false | false |
androidx/androidx | navigation/navigation-dynamic-features-fragment/src/main/java/androidx/navigation/dynamicfeatures/fragment/DynamicFragmentNavigatorDestinationBuilder.kt | 3 | 4999 | /*
* 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.navigation.dynamicfeatures.fragment
import androidx.annotation.IdRes
import androidx.fragment.app.Fragment
import androidx.navigation.NavDestinationBuilder
import androidx.navigation.NavDestinationDsl
import androidx.navigation.dynamicfeatures.DynamicNavGraphBuilder
import androidx.navigation.fragment.FragmentNavigator
import androidx.navigation.fragment.fragment
import androidx.navigation.get
/**
* Construct a new [DynamicFragmentNavigator.Destination]
* @param id Destination id.
*/
@Suppress("Deprecation")
@Deprecated(
"Use routes to create your DynamicFragmentDestination instead",
ReplaceWith("fragment(route = id.toString())")
)
public inline fun <reified F : Fragment> DynamicNavGraphBuilder.fragment(
@IdRes id: Int
): Unit = fragment<F>(id) {}
/**
* Construct a new [DynamicFragmentNavigator.Destination]
* @param id Destination id.
*/
@Suppress("Deprecation")
@Deprecated(
"Use routes to create your DynamicFragmentDestination instead",
ReplaceWith("fragment(route = id.toString()) { builder.invoke() }")
)
public inline fun <reified F : Fragment> DynamicNavGraphBuilder.fragment(
@IdRes id: Int,
builder: DynamicFragmentNavigatorDestinationBuilder.() -> Unit
): Unit = fragment(id, F::class.java.name, builder)
/**
* Construct a new [DynamicFragmentNavigator.Destination]
* @param id Destination id.
* @param fragmentClassName Fully qualified class name of destination Fragment.
*/
@Suppress("Deprecation")
@Deprecated(
"Use routes to create your DynamicFragmentDestination instead",
ReplaceWith("fragment(route = id.toString(), fragmentClassName) { builder.invoke() }")
)
public inline fun DynamicNavGraphBuilder.fragment(
@IdRes id: Int,
fragmentClassName: String,
builder: DynamicFragmentNavigatorDestinationBuilder.() -> Unit
): Unit = destination(
DynamicFragmentNavigatorDestinationBuilder(
provider[DynamicFragmentNavigator::class],
id,
fragmentClassName
).apply(builder)
)
/**
* Construct a new [DynamicFragmentNavigator.Destination]
* @param route Destination route.
*/
public inline fun <reified F : Fragment> DynamicNavGraphBuilder.fragment(
route: String
): Unit = fragment<F>(route) {}
/**
* Construct a new [DynamicFragmentNavigator.Destination]
* @param route Destination route.
*/
public inline fun <reified F : Fragment> DynamicNavGraphBuilder.fragment(
route: String,
builder: DynamicFragmentNavigatorDestinationBuilder.() -> Unit
): Unit = fragment(route, F::class.java.name, builder)
/**
* Construct a new [DynamicFragmentNavigator.Destination]
* @param route Destination route.
* @param fragmentClassName Fully qualified class name of destination Fragment.
*/
public inline fun DynamicNavGraphBuilder.fragment(
route: String,
fragmentClassName: String,
builder: DynamicFragmentNavigatorDestinationBuilder.() -> Unit
): Unit = destination(
DynamicFragmentNavigatorDestinationBuilder(
provider[DynamicFragmentNavigator::class],
route,
fragmentClassName
).apply(builder)
)
/**
* DSL for constructing a new [DynamicFragmentNavigator.Destination]
*/
@NavDestinationDsl
public class DynamicFragmentNavigatorDestinationBuilder :
NavDestinationBuilder<FragmentNavigator.Destination> {
private var fragmentClassName: String
@Suppress("Deprecation")
@Deprecated(
"Use routes to create your DynamicFragmentDestinationBuilder instead",
ReplaceWith(
"DynamicFragmentNavigatorDestinationBuilder(navigator, route = id.toString(), " +
"fragmentClassName)"
)
)
public constructor(
navigator: DynamicFragmentNavigator,
@IdRes id: Int,
fragmentClassName: String
) : super(navigator, id) {
this.fragmentClassName = fragmentClassName
}
public constructor(
navigator: DynamicFragmentNavigator,
route: String,
fragmentClassName: String
) : super(navigator, route) {
this.fragmentClassName = fragmentClassName
}
public var moduleName: String? = null
override fun build(): DynamicFragmentNavigator.Destination =
(super.build() as DynamicFragmentNavigator.Destination).also { destination ->
destination.setClassName(fragmentClassName)
destination.moduleName = moduleName
}
}
| apache-2.0 | 45113e4f0b03bffc6efbaceb7653897d | 32.10596 | 93 | 0.735947 | 4.815992 | false | false | false | false |
qikh/mini-block-chain | src/main/kotlin/mbc/core/BlockChainManager.kt | 1 | 5481 | package mbc.core
import io.reactivex.Flowable
import io.reactivex.schedulers.Schedulers
import mbc.miner.BlockMiner
import mbc.miner.MineResult
import mbc.network.Peer
import mbc.network.client.PeerClient
import org.slf4j.LoggerFactory
import java.net.URI
class BlockChainManager(val blockChain: BlockChain) {
private val logger = LoggerFactory.getLogger(javaClass)
/**
* 等待加入区块的交易数据。
*/
val pendingTransactions = mutableListOf<Transaction>()
/**
* 当前连接的Peer。
*/
var peers = mutableListOf<Peer>()
/**
* 等待发现的Node。
*/
var discoveryNodes = mutableListOf<Node>()
/**
* 是否正在挖矿中。
*/
var mining: Boolean = false
/**
* 正在挖矿中的区块。
*/
var miningBlock: Block? = null
/**
* 是否正在同步区块中。
*/
var synching: Boolean = false
/**
* 将Transaction加入到Pending List。
*/
fun addPendingTransaction(trx: Transaction) {
if (trx.isValid) {
pendingTransactions.add(trx)
} else {
logger.debug("Invalid transaction $trx was ignored.")
}
}
/**
* 批量将Transaction加入到Pending List。
*/
fun addPendingTransactions(transactions: List<Transaction>) {
logger.debug("Appending ${transactions.size} transactions to pending transactions.")
transactions.map { addPendingTransaction(it) }
}
/**
* 增加Peer连接。
*/
fun addPeer(peer: Peer): Int {
logger.debug("Peer connected: $peer")
if (peers.none { it.node.nodeId == peer.node.nodeId }) {
peers.add(peer)
} else {
logger.debug("Peer $peer.node.nodeId already exists in connected peer list")
return -1
}
// 监听Peer的连接关闭事件
peer.channel.closeFuture().addListener { notifyPeerClosed(peer) }
return 0
}
private fun notifyPeerClosed(peer: Peer) {
logger.debug("Peer closed: $peer.")
peers.remove(peer)
}
/**
* 开始异步Mining。
*/
fun startMining() {
mining = true
mineBlock()
}
/**
* 停止异步Mining。
*/
fun stopMining() {
mining = false
}
fun mineBlock() {
logger.debug("Mine block.")
miningBlock = blockChain.generateNewBlock(pendingTransactions)
Flowable.fromCallable({ BlockMiner.mine(miningBlock!!) })
.subscribeOn(Schedulers.computation())
.observeOn(Schedulers.single())
.subscribe({
if (it.success) {
processMinedBlock(it)
}
if (mining) { // continue mining.
mineBlock()
}
})
}
/**
* 开始同步区块。
*/
fun startSync(peer: Peer) {
synching = true
requestPeerBlocks(peer)
}
/**
* 向Peer请求区块数据。
*/
fun requestPeerBlocks(peer: Peer) {
peer.sendGetBlocks(blockChain.getBestBlock().height + 1, 10)
}
/**
* 处理Peer同步的区块。
*/
fun processPeerBlocks(peer: Peer, blocks: List<Block>) {
/**
* 同步区块中。。。
*/
if (synching) {
/**
* 收到区块的数量大于0则保存区块,否则说明同步完成,停止区块同步。
*/
if (blocks.size > 0) {
blocks.forEach { blockChain.importBlock(it) }
// 继续请求区块数据,直至同步完毕。
requestPeerBlocks(peer)
} else {
stopSync()
startMining()
}
}
}
fun stopSync() {
synching = false
}
/**
* Mining完成后把挖到的区块加入到区块链。
*/
private fun processMinedBlock(result: MineResult) {
val block = result.block
logger.debug("Mined block: $block")
if (blockChain.importBlock(block) == BlockChain.ImportResult.BEST_BLOCK) {
val bestBlock = blockChain.getBestBlock()
peers.forEach { it.sendNewBlock(bestBlock) }
}
}
/**
* 开始搜索可连接的Peer。
*
* TODO: 运行时更新Peer地址列表并刷新连接。
*/
fun startPeerDiscovery() {
val bootnodes = blockChain.config.getBootnodes()
if (bootnodes.size > 0) {
bootnodes.forEach {
val uri = URI(it)
if (uri.scheme == "mnode") {
// Run PeerClient for nodes in bootnodes list. It will make async connection.
PeerClient(this).connectAsync(Node(uri.userInfo, uri.host, uri.port))
}
}
} else {
startMining()
}
}
/**
* 停止对Peer的搜索。
*/
fun stopPeerDiscovery() {
}
/**
* 提交交易数据,会进入Pending Transactions并发布给已连接的客户端。
*/
fun submitTransaction(trx: Transaction) {
if (trx.isValid) {
addPendingTransaction(trx)
peers.map { it.sendTransaction(trx) }
}
}
/**
* 判断Peer是否已经在连接列表内
*/
fun peerConnected(peer: Peer): Boolean {
return peers.any { it.node.nodeId == peer.node.nodeId }
}
/**
* 处理同步过来的区块数据,检索区块是否已经存在,只保存新增区块。
*/
fun processPeerNewBlock(block: Block, peer: Peer) {
val importResult = blockChain.importBlock(block)
if (importResult == BlockChain.ImportResult.BEST_BLOCK) {
if (miningBlock != null && block.height >= miningBlock!!.height) {
BlockMiner.skip()
}
broadcastBlock(block, peer)
}
}
private fun broadcastBlock(block: Block, skipPeer: Peer) {
peers.filterNot { it == skipPeer }.forEach { it.sendNewBlock(block) }
}
}
| apache-2.0 | 01fa7a12d8cb65a7302ae7ffa594da22 | 19.110204 | 88 | 0.611934 | 3.372348 | false | false | false | false |
jean79/yested | src/main/kotlin/net/yested/bootstrap/layout.kt | 2 | 1944 | package net.yested.bootstrap
import net.yested.Div
import net.yested.HTMLComponent
import net.yested.with
import net.yested.div
import org.w3c.dom.HTMLElement
import net.yested.el
import net.yested.Component
import net.yested.createElement
import net.yested.appendComponent
class Row(): Component {
override val element = createElement("div")
init {
element.setAttribute("class", "row")
}
fun col(vararg modifiers: ColumnModifier, init: HTMLComponent.() -> Unit) {
element.appendComponent(
Div() with {
clazz = modifiers.map {it.toString()}.joinToString(" ")
init()
})
}
}
enum class ContainerLayout(val code:String) {
DEFAULT("container"),
FLUID("container-fluid")
}
class Page(val element: HTMLElement, val layout: ContainerLayout = ContainerLayout.DEFAULT) {
fun topMenu(navbar: Navbar) {
element.appendComponent(navbar)
}
fun content(init: HTMLComponent.() -> Unit): Unit {
element.appendChild(
div {
"class"..layout.code
init()
}.element)
}
fun footer(init: HTMLComponent.() -> Unit): Unit {
element.appendChild(
div {
div(clazz = "container") {
tag("hr") {}
init()
}
}.element
)
}
}
class PageHeader : HTMLComponent("div") {
init {
clazz = "page-header"
}
}
fun HTMLComponent.pageHeader(init: HTMLComponent.() -> Unit) {
+(PageHeader() with { init() })
}
fun HTMLComponent.row(init:Row.()->Unit) {
+(Row() with { init() })
}
fun page(placeholderElementId:String, layout: ContainerLayout = ContainerLayout.DEFAULT, init:Page.() -> Unit):Unit {
Page(el(placeholderElementId) as HTMLElement, layout) with {
this.init()
}
}
| mit | 8763417b8c0389530b8fa97a0f5a24eb | 23 | 118 | 0.574074 | 4.272527 | false | false | false | false |
noemus/kotlin-eclipse | kotlin-eclipse-core/src/org/jetbrains/kotlin/core/references/KotlinReference.kt | 1 | 6199 | /*******************************************************************************
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*******************************************************************************/
package org.jetbrains.kotlin.core.references
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.psi.KtSimpleNameExpression
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.psi.KtReferenceExpression
import org.jetbrains.kotlin.descriptors.PackageViewDescriptor
import org.jetbrains.kotlin.core.resolve.EclipseDescriptorUtils
import org.jetbrains.kotlin.descriptors.SourceElement
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.resolve.calls.callUtil.getCall
import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.calls.model.VariableAsFunctionResolvedCall
import org.jetbrains.kotlin.psi.Call
import org.jetbrains.kotlin.psi.KtConstructorDelegationReferenceExpression
import org.eclipse.jdt.core.IJavaProject
import org.jetbrains.kotlin.psi.KtElement
import java.util.ArrayList
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.synthetic.SyntheticJavaPropertyDescriptor
import com.intellij.util.SmartList
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.lexer.KtTokens
inline private fun <reified T> ArrayList<KotlinReference>.register(e: KtElement, action: (T) -> KotlinReference) {
if (e is T) this.add(action(e))
}
inline private fun <reified T> ArrayList<KotlinReference>.registerMulti(e: KtElement, action: (T) -> List<KotlinReference>) {
if (e is T) this.addAll(action(e))
}
public fun createReferences(element: KtReferenceExpression): List<KotlinReference> {
return arrayListOf<KotlinReference>().apply {
register<KtSimpleNameExpression>(element, ::KotlinSimpleNameReference)
register<KtCallExpression>(element, ::KotlinInvokeFunctionReference)
register<KtConstructorDelegationReferenceExpression>(element, ::KotlinConstructorDelegationReference)
registerMulti<KtNameReferenceExpression>(element) {
if (it.getReferencedNameElementType() != KtTokens.IDENTIFIER) return@registerMulti emptyList()
when (it.readWriteAccess()) {
ReferenceAccess.READ -> listOf(KotlinSyntheticPropertyAccessorReference.Getter(it))
ReferenceAccess.WRITE -> listOf(KotlinSyntheticPropertyAccessorReference.Setter(it))
ReferenceAccess.READ_WRITE -> listOf(
KotlinSyntheticPropertyAccessorReference.Getter(it),
KotlinSyntheticPropertyAccessorReference.Setter(it))
}
}
}
}
public interface KotlinReference {
val expression: KtReferenceExpression
fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor>
}
open class KotlinSimpleNameReference(override val expression: KtSimpleNameExpression) : KotlinReference {
override fun getTargetDescriptors(context: BindingContext) = expression.getReferenceTargets(context)
}
public class KotlinInvokeFunctionReference(override val expression: KtCallExpression) : KotlinReference {
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
val call = expression.getCall(context)
val resolvedCall = call.getResolvedCall(context)
return when {
resolvedCall is VariableAsFunctionResolvedCall -> listOf(resolvedCall.functionCall.getCandidateDescriptor())
call != null && resolvedCall != null && call.getCallType() == Call.CallType.INVOKE -> listOf(resolvedCall.getCandidateDescriptor())
else -> emptyList()
}
}
}
sealed class KotlinSyntheticPropertyAccessorReference(override val expression: KtNameReferenceExpression, private val getter: Boolean)
: KotlinSimpleNameReference(expression) {
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
val descriptors = super.getTargetDescriptors(context)
if (descriptors.none { it is SyntheticJavaPropertyDescriptor }) return emptyList()
val result = SmartList<FunctionDescriptor>()
for (descriptor in descriptors) {
if (descriptor is SyntheticJavaPropertyDescriptor) {
if (getter) {
result.add(descriptor.getMethod)
} else {
result.addIfNotNull(descriptor.setMethod)
}
}
}
return result
}
class Getter(expression: KtNameReferenceExpression) : KotlinSyntheticPropertyAccessorReference(expression, true)
class Setter(expression: KtNameReferenceExpression) : KotlinSyntheticPropertyAccessorReference(expression, false)
}
public class KotlinConstructorDelegationReference(override val expression: KtConstructorDelegationReferenceExpression) : KotlinReference {
override fun getTargetDescriptors(context: BindingContext) = expression.getReferenceTargets(context)
}
fun KtReferenceExpression.getReferenceTargets(context: BindingContext): Collection<DeclarationDescriptor> {
val targetDescriptor = context[BindingContext.REFERENCE_TARGET, this]
return if (targetDescriptor != null) {
listOf(targetDescriptor)
} else {
context[BindingContext.AMBIGUOUS_REFERENCE_TARGET, this].orEmpty()
}
} | apache-2.0 | 3debdbfdc91b066f6cf1a85285b05097 | 47.062016 | 143 | 0.733021 | 5.524955 | false | false | false | false |
wealthfront/magellan | magellan-legacy/src/test/java/com/wealthfront/magellan/HistoryRewriterExtensionsKtTest.kt | 1 | 3783 | package com.wealthfront.magellan
import com.google.common.truth.Truth.assertThat
import com.wealthfront.magellan.core.Journey
import com.wealthfront.magellan.internal.test.DummyScreen
import com.wealthfront.magellan.internal.test.databinding.MagellanDummyLayoutBinding
import com.wealthfront.magellan.navigation.NavigationEvent
import com.wealthfront.magellan.transitions.DefaultTransition
import com.wealthfront.magellan.transitions.ShowTransition
import org.junit.Before
import org.junit.Test
import org.mockito.Mock
import org.mockito.MockitoAnnotations.initMocks
import rewriteHistoryWithNavigationEvents
import java.util.ArrayDeque
public class HistoryRewriterExtensionsKtTest {
private lateinit var root: LegacyJourney<*>
private lateinit var journey1: Journey<*>
private lateinit var screen: Screen<*>
@Mock private lateinit var view: BaseScreenView<DummyScreen>
@Before
public fun setUp() {
initMocks(this)
root = RootJourney()
journey1 = DummyJourney1()
screen = DummyScreen(view)
}
@Test
public fun historyRewriter() {
val backStack = ArrayDeque<NavigationEvent>()
backStack.push(NavigationEvent(root, DefaultTransition()))
backStack.push(NavigationEvent(journey1, ShowTransition()))
backStack.push(NavigationEvent(screen, DefaultTransition()))
val historyRewriter = HistoryRewriter { stack ->
stack.pop()
}
assertThat(backStack.size).isEqualTo(3)
historyRewriter.rewriteHistoryWithNavigationEvents(backStack)
assertThat(backStack.size).isEqualTo(2)
val journeyInBackStack = backStack.poll()!!
val rootInBackStack = backStack.poll()!!
assertThat(journeyInBackStack.navigable).isEqualTo(journey1)
assertThat(journeyInBackStack.magellanTransition).isInstanceOf(DefaultTransition::class.java)
assertThat(rootInBackStack.navigable).isEqualTo(root)
assertThat(rootInBackStack.magellanTransition).isInstanceOf(DefaultTransition::class.java)
}
@Test
public fun historyRewriter_compatibility() {
val backStack = ArrayDeque<NavigationEvent>()
backStack.push(NavigationEvent(root, DefaultTransition()))
backStack.push(NavigationEvent(journey1, ShowTransition()))
val historyRewriter = HistoryRewriter { stack ->
stack.push(screen)
}
assertThat(backStack.size).isEqualTo(2)
historyRewriter.rewriteHistoryWithNavigationEvents(backStack)
assertThat(backStack.size).isEqualTo(3)
val screenInBackStack = backStack.poll()!!
val journeyInBackStack = backStack.poll()!!
val rootInBackStack = backStack.poll()!!
assertThat(screenInBackStack.navigable).isEqualTo(screen)
assertThat(screenInBackStack.magellanTransition).isInstanceOf(DefaultTransition::class.java)
assertThat(journeyInBackStack.navigable).isEqualTo(journey1)
assertThat(journeyInBackStack.magellanTransition).isInstanceOf(DefaultTransition::class.java)
assertThat(rootInBackStack.navigable).isEqualTo(root)
assertThat(rootInBackStack.magellanTransition).isInstanceOf(DefaultTransition::class.java)
}
@Test(expected = NoSuchElementException::class)
public fun historyRewriter_exceptionWhenNoItemOnBackStack() {
val backStack = ArrayDeque<NavigationEvent>()
backStack.push(NavigationEvent(root, DefaultTransition()))
val historyRewriter = HistoryRewriter { stack ->
stack.pop()
stack.pop()
}
historyRewriter.rewriteHistoryWithNavigationEvents(backStack)
}
private inner class RootJourney : LegacyJourney<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
)
private inner class DummyJourney1 : Journey<MagellanDummyLayoutBinding>(
MagellanDummyLayoutBinding::inflate,
MagellanDummyLayoutBinding::container
)
}
| apache-2.0 | 944e02b43a05bfb9f5b326b9e41ea19b | 34.027778 | 97 | 0.785091 | 4.758491 | false | true | false | false |
andstatus/andstatus | app/src/main/kotlin/oauth/signpost/commonshttp/HttpRequestAdapter.kt | 1 | 1712 | package oauth.signpost.commonshttp
import cz.msebera.android.httpclient.HttpEntity
import cz.msebera.android.httpclient.HttpEntityEnclosingRequest
import cz.msebera.android.httpclient.client.methods.HttpUriRequest
import oauth.signpost.http.HttpRequest
import java.io.InputStream
import java.util.*
class HttpRequestAdapter(private val request: HttpUriRequest) : HttpRequest {
private val entity: HttpEntity? = if (request is HttpEntityEnclosingRequest) {
(request as HttpEntityEnclosingRequest).entity
} else null
override fun getMethod(): String? {
return request.requestLine.method
}
override fun getRequestUrl(): String {
return request.uri.toString()
}
override fun setRequestUrl(url: String?) {
throw RuntimeException(UnsupportedOperationException())
}
override fun getHeader(name: String?): String? {
val header = request.getFirstHeader(name) ?: return null
return header.value
}
override fun setHeader(name: String?, value: String?) {
request.setHeader(name, value)
}
override fun getAllHeaders(): MutableMap<String, String?> {
val origHeaders = request.allHeaders
val headers = HashMap<String, String?>()
for (h in origHeaders) {
headers[h.name] = h.value
}
return headers
}
override fun getContentType(): String? {
if (entity == null) {
return null
}
val header = entity.contentType ?: return null
return header.value
}
override fun getMessagePayload(): InputStream? {
return entity?.content
}
override fun unwrap(): Any {
return request
}
}
| apache-2.0 | 52d7135f7edf403b6e2caee6b415cdf0 | 27.065574 | 82 | 0.668808 | 4.639566 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/manga/MangaActivity.kt | 1 | 9632 | package me.proxer.app.manga
import android.app.Activity
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.Menu
import android.view.MenuItem
import android.view.View.SYSTEM_UI_FLAG_FULLSCREEN
import android.view.View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
import android.view.View.SYSTEM_UI_FLAG_IMMERSIVE
import android.view.View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
import android.view.View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
import android.view.View.SYSTEM_UI_FLAG_LAYOUT_STABLE
import android.view.View.SYSTEM_UI_FLAG_LOW_PROFILE
import android.view.View.SYSTEM_UI_FLAG_VISIBLE
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ShareCompat
import androidx.core.view.updateLayoutParams
import androidx.fragment.app.commitNow
import com.google.android.material.appbar.AppBarLayout
import com.google.android.material.appbar.AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS
import com.google.android.material.appbar.AppBarLayout.LayoutParams.SCROLL_FLAG_NO_SCROLL
import com.google.android.material.appbar.AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL
import com.jakewharton.rxbinding3.view.clicks
import com.jakewharton.rxbinding3.view.systemUiVisibilityChanges
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import kotterknife.bindView
import me.proxer.app.R
import me.proxer.app.base.BaseActivity
import me.proxer.app.media.MediaActivity
import me.proxer.app.util.extension.getSafeStringExtra
import me.proxer.app.util.extension.startActivity
import me.proxer.app.util.extension.toEpisodeAppString
import me.proxer.library.enums.Category
import me.proxer.library.enums.Language
import me.proxer.library.util.ProxerUrls
import me.proxer.library.util.ProxerUtils
import java.lang.ref.WeakReference
/**
* @author Ruben Gees
*/
class MangaActivity : BaseActivity() {
companion object {
private const val ID_EXTRA = "id"
private const val EPISODE_EXTRA = "episode"
private const val LANGUAGE_EXTRA = "language"
private const val CHAPTER_TITLE_EXTRA = "chapter_title"
private const val NAME_EXTRA = "name"
private const val EPISODE_AMOUNT_EXTRA = "episode_amount"
fun navigateTo(
context: Activity,
id: String,
episode: Int,
language: Language,
chapterTitle: String?,
name: String? = null,
episodeAmount: Int? = null
) {
context.startActivity<MangaActivity>(
ID_EXTRA to id,
EPISODE_EXTRA to episode,
LANGUAGE_EXTRA to language,
CHAPTER_TITLE_EXTRA to chapterTitle,
NAME_EXTRA to name,
EPISODE_AMOUNT_EXTRA to episodeAmount
)
}
}
val id: String
get() = when (intent.hasExtra(ID_EXTRA)) {
true -> intent.getSafeStringExtra(ID_EXTRA)
false -> intent.data?.pathSegments?.getOrNull(1) ?: "-1"
}
var episode: Int
get() = when (intent.hasExtra(EPISODE_EXTRA)) {
true -> intent.getIntExtra(EPISODE_EXTRA, 1)
false -> intent.data?.pathSegments?.getOrNull(2)?.toIntOrNull() ?: 1
}
set(value) {
intent.putExtra(EPISODE_EXTRA, value)
updateTitle()
}
val language: Language
get() = when (intent.hasExtra(LANGUAGE_EXTRA)) {
true -> intent.getSerializableExtra(LANGUAGE_EXTRA) as Language
false -> intent.data?.pathSegments?.getOrNull(3)?.let { ProxerUtils.toApiEnum<Language>(it) }
?: Language.ENGLISH
}
var chapterTitle: String?
get() = intent.getStringExtra(CHAPTER_TITLE_EXTRA)
set(value) {
intent.putExtra(CHAPTER_TITLE_EXTRA, value)
updateTitle()
}
var name: String?
get() = intent.getStringExtra(NAME_EXTRA)
set(value) {
intent.putExtra(NAME_EXTRA, value)
updateTitle()
}
var episodeAmount: Int?
get() = when (intent.hasExtra(EPISODE_AMOUNT_EXTRA)) {
true -> intent.getIntExtra(EPISODE_AMOUNT_EXTRA, 1)
else -> null
}
set(value) {
when (value) {
null -> intent.removeExtra(EPISODE_AMOUNT_EXTRA)
else -> intent.putExtra(EPISODE_AMOUNT_EXTRA, value)
}
}
private val toolbar: Toolbar by bindView(R.id.toolbar)
private val fullscreenHandler = FullscreenHandler(WeakReference(this))
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_manga)
setSupportActionBar(toolbar)
setupToolbar()
updateTitle()
window.decorView.systemUiVisibilityChanges()
.skip(1)
.autoDisposable(this.scope())
.subscribe { handleUIChange() }
toggleFullscreen(false)
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, MangaFragment.newInstance())
}
}
}
override fun onDestroy() {
fullscreenHandler.removeCallbacksAndMessages(null)
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
IconicsMenuInflaterUtil.inflate(menuInflater, this, R.menu.activity_share, menu, true)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_share -> name?.let {
val link = ProxerUrls.mangaWeb(id, episode, language)
val text = chapterTitle.let { title ->
when {
title.isNullOrBlank() -> getString(R.string.share_manga, episode, it, link)
else -> getString(R.string.share_manga_title, title, it, link)
}
}
ShareCompat.IntentBuilder
.from(this)
.setText(text)
.setType("text/plain")
.setChooserTitle(getString(R.string.share_title))
.startChooser()
}
}
return super.onOptionsItemSelected(item)
}
override fun onMultiWindowModeChanged(isInMultiWindowMode: Boolean, newConfig: Configuration?) {
super.onMultiWindowModeChanged(isInMultiWindowMode, newConfig)
handleUIChange()
}
fun toggleFullscreen(fullscreen: Boolean, delay: Long = 0) {
val fullscreenMessage = Message().apply {
what = 0
obj = fullscreen
}
fullscreenHandler.removeMessages(0)
if (delay <= 0L) {
fullscreenHandler.handleMessage(fullscreenMessage)
} else {
fullscreenHandler.sendMessageDelayed(fullscreenMessage, delay)
}
}
private fun setupToolbar() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
toolbar.clicks()
.autoDisposable(this.scope())
.subscribe {
name?.let {
MediaActivity.navigateTo(this, id, name, Category.MANGA)
}
}
}
private fun updateTitle() {
title = name
supportActionBar?.subtitle = chapterTitle ?: Category.MANGA.toEpisodeAppString(this, episode)
}
private fun handleUIChange() {
val isInMultiWindowMode = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && this.isInMultiWindowMode
val isInFullscreenMode = window.decorView.systemUiVisibility and SYSTEM_UI_FLAG_FULLSCREEN != 0
toolbar.updateLayoutParams<AppBarLayout.LayoutParams> {
scrollFlags = when {
isInMultiWindowMode -> SCROLL_FLAG_SCROLL or SCROLL_FLAG_ENTER_ALWAYS
isInFullscreenMode -> SCROLL_FLAG_SCROLL
else -> SCROLL_FLAG_NO_SCROLL
}
}
if (isInFullscreenMode) {
if (isInMultiWindowMode) {
toggleFullscreen(false)
} else {
toggleFullscreen(true)
}
} else {
toggleFullscreen(false)
if (!isInMultiWindowMode) {
toggleFullscreen(true, 2_000)
}
}
}
private class FullscreenHandler(private val activity: WeakReference<MangaActivity>) : Handler() {
override fun handleMessage(message: Message) {
this.activity.get()?.apply {
val isInMultiWindowMode = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && this.isInMultiWindowMode
if (message.obj as Boolean && !isInMultiWindowMode) {
window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_LOW_PROFILE or
SYSTEM_UI_FLAG_LAYOUT_STABLE or
SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
SYSTEM_UI_FLAG_HIDE_NAVIGATION or
SYSTEM_UI_FLAG_FULLSCREEN or
SYSTEM_UI_FLAG_IMMERSIVE
} else {
window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_VISIBLE or
SYSTEM_UI_FLAG_LAYOUT_STABLE or
SYSTEM_UI_FLAG_IMMERSIVE
}
}
}
}
}
| gpl-3.0 | e5526ffe93f9e6b9cb3e91e965878d19 | 33.647482 | 116 | 0.621782 | 4.756543 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.