repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/regressions/kt5395.kt | 5 | 177 | class D {
companion object {
protected val F: String = "OK"
}
inner class E {
fun foo() = F
}
}
fun box(): String {
return D().E().foo()
}
| apache-2.0 |
aconsuegra/algorithms-playground | src/main/kotlin/me/consuegra/algorithms/KPalindromeNumber.kt | 1 | 436 | package me.consuegra.algorithms
/**
* Determine whether an integer is a palindrome. Do this without extra space.
*/
class KPalindromeNumber {
fun isPalindrome(x: Int) : Boolean {
if (x < 0) {
return false
}
var input = x
var reverse = 0
while (input > 0) {
reverse = reverse * 10 + input % 10
input /= 10
}
return reverse == x
}
}
| mit |
InventiDevelopment/AndroidSkeleton | app/src/main/java/cz/inventi/inventiskeleton/presentation/common/BaseMviController.kt | 1 | 1118 | package cz.inventi.inventiskeleton.presentation.common
import android.app.Activity
import android.os.Bundle
import android.view.View
import com.bluelinelabs.conductor.ControllerChangeHandler
import com.bluelinelabs.conductor.ControllerChangeType
import com.hannesdorfmann.mosby3.MviController
import com.hannesdorfmann.mosby3.mvi.MviPresenter
/**
* Created by tomas.valenta on 6/15/2017.
*/
abstract class BaseMviController <V : BaseView, P : MviPresenter<V, *>> : MviController<V, P>, BaseView, RefWatcherDelegate, ViewBindingDelegate {
protected constructor() {}
protected constructor(args: Bundle) : super(args) {}
override var hasExited: Boolean = false
override fun getParentActivity(): Activity? = activity
override fun onDestroy() {
super<RefWatcherDelegate>.onDestroy()
}
override fun onChangeEnded(changeHandler: ControllerChangeHandler, changeType: ControllerChangeType) {
super<RefWatcherDelegate>.onChangeEnded(changeHandler, changeType)
}
override fun onDestroyView(view: View) {
super<ViewBindingDelegate>.onDestroyView(view)
}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/junit/testData/codeInsight/junit5malformed/NoSourcesProvided.kt | 12 | 219 | package test
import org.junit.jupiter.params.ParameterizedTest
object PrivateRule {
@<warning descr="No sources are provided, the suite would be empty">ParameterizedTest</warning>
fun testWithParamsNoSource() {}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/shortenRefs/java/staticClassNoImports.kt | 13 | 69 | fun bar(s: String) {
<selection>val t: A.B = A.B(s)</selection>
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/rename/renameKotlinFile/before/Foo.kt | 26 | 50 | package testing.rename
var foo: String = "xyzzy"
| apache-2.0 |
psenchanka/comant | comant-site/src/main/kotlin/com/psenchanka/comant/dao/impl/ClassDaoImpl.kt | 1 | 457 | package com.psenchanka.comant.dao.impl
import com.psenchanka.comant.dao.ClassDao
import com.psenchanka.comant.model.Class
import org.hibernate.SessionFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Repository
@Repository("classDao")
open class ClassDaoImpl @Autowired constructor(sessionFactory: SessionFactory)
: ClassDao, AbstractDaoImpl<Class, Int>(sessionFactory, Class::class.java) | mit |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/multiModuleQuickFix/fixNativeThrowsErrors/addCancellationException3/native/test.kt | 12 | 262 | // "Add 'CancellationException::class'" "false"
// ERROR: @Throws must have non-empty class list
// ACTION: Make internal
// ACTION: Make private
// ACTION: Remove annotation
// No compilation error => no quickfix.
<caret>@Throws()
suspend fun emptyThrows() {}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/functionWithLambdaExpressionBody/getterHasType.kt | 13 | 61 | // PROBLEM: none
val test: () -> String get() = <caret>{ "" } | apache-2.0 |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/lang/documentation/ide/impl/links.kt | 1 | 2821 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.lang.documentation.ide.impl
import com.intellij.codeInsight.documentation.DocumentationManager
import com.intellij.ide.BrowserUtil
import com.intellij.lang.documentation.CompositeDocumentationProvider
import com.intellij.lang.documentation.DocumentationTarget
import com.intellij.lang.documentation.ExternalDocumentationHandler
import com.intellij.lang.documentation.impl.resolveLink
import com.intellij.lang.documentation.psi.PsiElementDocumentationTarget
import com.intellij.model.Pointer
import com.intellij.openapi.application.readAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.roots.OrderEntry
import com.intellij.psi.PsiManager
import com.intellij.util.SlowOperations
import com.intellij.util.ui.EDT
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
internal suspend fun handleLink(
project: Project,
targetPointer: Pointer<out DocumentationTarget>,
url: String,
): Any? {
if (url.startsWith("open")) {
return libraryEntry(project, targetPointer)
}
return resolveLink(targetPointer, url)
}
private suspend fun libraryEntry(project: Project, targetPointer: Pointer<out DocumentationTarget>): OrderEntry? {
return withContext(Dispatchers.Default) {
readAction {
val target = targetPointer.dereference() ?: return@readAction null
if (target is PsiElementDocumentationTarget) { // currently, only PSI targets are supported
DocumentationManager.libraryEntry(project, target.targetElement)
}
else {
null
}
}
}
}
internal fun openUrl(project: Project, targetPointer: Pointer<out DocumentationTarget>, url: String): Boolean {
EDT.assertIsEdt()
if (handleExternal(project, targetPointer, url)) {
return true
}
return BrowserUtil.browseAbsolute(url)
}
private fun handleExternal(project: Project, targetPointer: Pointer<out DocumentationTarget>, url: String): Boolean {
return SlowOperations.allowSlowOperations("old API fallback").use {
doHandleExternal(project, targetPointer, url)
}
}
private fun doHandleExternal(project: Project, targetPointer: Pointer<out DocumentationTarget>, url: String): Boolean {
val target = targetPointer.dereference() as? PsiElementDocumentationTarget ?: return false
val element = target.targetElement
val provider = DocumentationManager.getProviderFromElement(element) as? CompositeDocumentationProvider ?: return false
for (p in provider.allProviders) {
if (p !is ExternalDocumentationHandler) {
continue
}
if (p.handleExternalLink(PsiManager.getInstance(project), url, element)) {
return true
}
}
return false
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/equalsBetweenInconvertibleTypes/stringEqNullableInt.kt | 13 | 85 | // FIX: none
fun test(x: String, y: Int?): Boolean? {
return x.<caret>equals(y)
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/increaseVisibility/privateTopLevelVarInFile.after.Dependency.kt | 13 | 41 | package test
internal var prop: Int = 10 | apache-2.0 |
MyPureCloud/platform-client-sdk-common | resources/sdk/purecloudkotlin/extensions/extensions/notifications/WebSocketListener.kt | 1 | 504 | package com.mypurecloud.sdk.v2.extensions.notifications
import com.neovisionaries.ws.client.WebSocketException
import com.neovisionaries.ws.client.WebSocketState
interface WebSocketListener {
fun onStateChanged(state: WebSocketState?)
fun onConnected()
fun onDisconnected(closedByServer: Boolean)
fun onError(exception: WebSocketException?)
fun onConnectError(exception: WebSocketException?)
fun onCallbackError(exception: Throwable?)
fun onUnhandledEvent(event: String?)
}
| mit |
vanniktech/lint-rules | lint-rules-rxjava2-lint/src/main/java/com/vanniktech/lintrules/rxjava2/RxJava2SchedulersFactoryCallDetector.kt | 1 | 2704 | @file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final.
package com.vanniktech.lintrules.rxjava2
import com.android.tools.lint.detector.api.Category.Companion.CORRECTNESS
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Detector.UastScanner
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Scope.JAVA_FILE
import com.android.tools.lint.detector.api.Severity.WARNING
import com.intellij.psi.PsiMethod
import org.jetbrains.uast.UAnnotated
import org.jetbrains.uast.UCallExpression
import org.jetbrains.uast.getContainingUMethod
import java.util.EnumSet
val ISSUE_RAW_SCHEDULER_CALL = Issue.create(
"RxJava2SchedulersFactoryCall",
"Instead of calling the Schedulers factory methods directly inject the Schedulers.",
"Injecting the Schedulers instead of accessing them via the factory methods has the benefit that unit testing is way easier. Instead of overriding them via the Plugin mechanism we can just pass a custom Scheduler.",
CORRECTNESS, PRIORITY, WARNING,
Implementation(RxJava2SchedulersFactoryCallDetector::class.java, EnumSet.of(JAVA_FILE)),
)
private val schedulersMethods = listOf("io", "computation", "newThread", "single", "from")
private val androidSchedulersMethods = listOf("mainThread")
class RxJava2SchedulersFactoryCallDetector : Detector(), UastScanner {
override fun getApplicableMethodNames() = schedulersMethods + androidSchedulersMethods
override fun visitMethodCall(context: JavaContext, node: UCallExpression, method: PsiMethod) {
val evaluator = context.evaluator
val isInSchedulers = evaluator.isMemberInClass(method, "io.reactivex.schedulers.Schedulers")
val isInAndroidSchedulers = evaluator.isMemberInClass(method, "io.reactivex.android.schedulers.AndroidSchedulers")
val isSchedulersMatch = schedulersMethods.contains(node.methodName) && isInSchedulers
val isAndroidSchedulersMatch = androidSchedulersMethods.contains(node.methodName) && isInAndroidSchedulers
val containingMethod = node.getContainingUMethod()
val shouldIgnore = containingMethod != null && context.evaluator.getAllAnnotations(containingMethod as UAnnotated, false)
.any { annotation -> listOf("dagger.Provides", "io.reactivex.annotations.SchedulerSupport").any { it == annotation.qualifiedName } }
if ((isSchedulersMatch || isAndroidSchedulersMatch) && !shouldIgnore) {
context.report(ISSUE_RAW_SCHEDULER_CALL, node, context.getNameLocation(node), "Inject this Scheduler instead of calling it directly")
}
}
}
| apache-2.0 |
kickstarter/android-oss | app/src/main/java/com/kickstarter/services/firebase/ResetDeviceIdWorker.kt | 1 | 1760 | package com.kickstarter.services.firebase
import android.content.Context
import android.content.Intent
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.kickstarter.KSApplication
import com.kickstarter.libs.Build
import com.kickstarter.libs.FirebaseHelper
import com.kickstarter.libs.qualifiers.ApplicationContext
import com.kickstarter.services.ApiClientType
import timber.log.Timber
import java.io.IOException
import javax.inject.Inject
class ResetDeviceIdWorker(@ApplicationContext applicationContext: Context, params: WorkerParameters) : Worker(applicationContext, params) {
@Inject
lateinit var build: Build
@Inject
lateinit var apiClient: ApiClientType
override fun doWork(): Result {
(applicationContext as KSApplication).component().inject(this)
return try {
FirebaseHelper.delete()
logSuccess()
applicationContext.sendBroadcast(Intent(BROADCAST))
Result.success()
} catch (e: IOException) {
logError(e)
Result.failure()
}
}
private fun logSuccess() {
val successMessage = "Successfully reset Firebase device ID"
if (this.build.isDebug) {
Timber.d(successMessage)
}
FirebaseCrashlytics.getInstance().log(successMessage)
}
private fun logError(ioException: IOException) {
if (this.build.isDebug) {
Timber.e(ioException.localizedMessage)
}
FirebaseCrashlytics.getInstance().recordException(ioException)
}
companion object {
const val BROADCAST = "reset_device_id_success"
const val TAG = "ResetDeviceIdWorker"
}
}
| apache-2.0 |
leafclick/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/actions/CommonCheckinFilesAction.kt | 1 | 3369 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.actions
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil.pluralize
import com.intellij.openapi.vcs.AbstractVcs
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.FileStatus
import com.intellij.openapi.vcs.VcsBundle.message
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.changes.ChangeListManagerImpl
import com.intellij.openapi.vcs.changes.LocalChangeList
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.containers.ContainerUtil.intersects
import com.intellij.vcsUtil.VcsUtil.getVcsFor
import kotlin.streams.asSequence
private fun VcsContext.getRoots(): Sequence<FilePath> = selectedFilePathsStream.asSequence()
private fun VcsContext.getCommonVcs(): AbstractVcs? {
val project = project ?: return null
return getRoots().mapNotNull { getVcsFor(project, it) }.distinct().singleOrNull()
}
open class CommonCheckinFilesAction : AbstractCommonCheckinAction() {
override fun getActionName(dataContext: VcsContext): String {
val actionName = dataContext.getCommonVcs()?.checkinEnvironment?.checkinOperationName
return appendSubject(dataContext, actionName ?: message("vcs.command.name.checkin"))
}
private fun appendSubject(dataContext: VcsContext, checkinActionName: String): String {
val roots = dataContext.getRoots().take(2).toList()
if (roots.isEmpty()) return checkinActionName
val messageKey = if (roots[0].isDirectory) "action.name.checkin.directory" else "action.name.checkin.file"
return message(pluralize(messageKey, roots.size), checkinActionName)
}
override fun getInitiallySelectedChangeList(context: VcsContext, project: Project): LocalChangeList {
val manager = ChangeListManager.getInstance(project)
val defaultChangeList = manager.defaultChangeList
var result: LocalChangeList? = null
for (root in getRoots(context)) {
if (root.virtualFile == null) continue
val changes = manager.getChangesIn(root)
if (intersects(changes, defaultChangeList.changes)) return defaultChangeList
result = changes.firstOrNull()?.let { manager.getChangeList(it) }
}
return result ?: defaultChangeList
}
override fun approximatelyHasRoots(dataContext: VcsContext): Boolean =
dataContext.getRoots().any { isApplicableRoot(it, dataContext) }
protected open fun isApplicableRoot(path: FilePath, dataContext: VcsContext): Boolean {
val manager = ChangeListManagerImpl.getInstanceImpl(dataContext.project!!)
val status = manager.getStatus(path)
@Suppress("DEPRECATION")
return (path.isDirectory || status != FileStatus.NOT_CHANGED) && status != FileStatus.IGNORED &&
path.virtualFile?.let { isApplicableRoot(it, status, dataContext) } != false
}
@Deprecated("Use `isApplicableRoot(FilePath, VcsContext)` instead", ReplaceWith("isApplicableRoot()"))
protected open fun isApplicableRoot(file: VirtualFile, status: FileStatus, dataContext: VcsContext): Boolean = true
override fun getRoots(dataContext: VcsContext): Array<FilePath> = dataContext.selectedFilePaths
override fun isForceUpdateCommitStateFromContext(): Boolean = true
}
| apache-2.0 |
siosio/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/diagnostic/dto/JsonFileProviderIndexStatistics.kt | 1 | 1621 | // 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.util.indexing.diagnostic.dto
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.intellij.util.indexing.diagnostic.dump.paths.PortableFilePath
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonFileProviderIndexStatistics(
val providerName: String = "",
val totalNumberOfIndexedFiles: Int = 0,
val totalNumberOfFilesFullyIndexedByExtensions: Int = 0,
val totalIndexingTime: JsonDuration = JsonDuration(0),
val contentLoadingTime: JsonDuration = JsonDuration(0),
val numberOfTooLargeForIndexingFiles: Int = 0,
val slowIndexedFiles: List<JsonSlowIndexedFile> = emptyList(),
// Available only if [com.intellij.util.indexing.diagnostic.IndexDiagnosticDumper.shouldDumpPathsOfIndexedFiles] is enabled.
val indexedFiles: List<JsonIndexedFile>? = null
) {
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonSlowIndexedFile(
val fileName: String = "",
val processingTime: JsonDuration = JsonDuration(0),
val indexingTime: JsonDuration = JsonDuration(0),
val contentLoadingTime: JsonDuration = JsonDuration(0)
)
@JsonIgnoreProperties(ignoreUnknown = true)
data class JsonIndexedFile(
val path: PortableFilePath = PortableFilePath.AbsolutePath(""),
@JsonProperty("wfibe")
val wasFullyIndexedByExtensions: Boolean = false
)
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/iterationOverMap/EntriesCallIsMissing.kt | 4 | 259 | // WITH_RUNTIME
fun main(args: Array<String>) {
val map = hashMapOf(1 to 1)
val entries = map.entries
for (<caret>entry in entries) {
val key = entry.key
val value = entry.value
println(key)
println(value)
}
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertToStringTemplate/simple.kt | 4 | 53 | fun foo(p: Int) {
val v = <caret>"(" + p + ")"
}
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/removeArgument/matchedArguments.kt | 4 | 326 | // "Remove argument" "false"
// ACTION: Add 'i =' to argument
// ACTION: Convert to also
// ACTION: Convert to apply
// ACTION: Convert to run
// ACTION: Convert to with
// ACTION: Put arguments on separate lines
class Bar() {
fun foo(s: String, i: Int) {
}
}
fun main() {
val b = Bar()
b.foo("a", 1<caret>)
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/KotlinIntentionActionFactoryWithDelegate.kt | 1 | 3576 | // 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.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.util.Ref
import com.intellij.psi.SmartPsiElementPointer
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
abstract class KotlinSingleIntentionActionFactoryWithDelegate<E : KtElement, D : Any>(
private val actionPriority: IntentionActionPriority = IntentionActionPriority.NORMAL
) : KotlinIntentionActionFactoryWithDelegate<E, D>() {
protected abstract fun createFix(originalElement: E, data: D): IntentionAction?
final override fun createFixes(
originalElementPointer: SmartPsiElementPointer<E>,
diagnostic: Diagnostic,
quickFixDataFactory: () -> D?
): List<QuickFixWithDelegateFactory> = QuickFixWithDelegateFactory(actionPriority) factory@{
val originalElement = originalElementPointer.element ?: return@factory null
val data = quickFixDataFactory() ?: return@factory null
createFix(originalElement, data)
}.let(::listOf)
}
abstract class KotlinIntentionActionFactoryWithDelegate<E : KtElement, D : Any> : KotlinIntentionActionsFactory() {
abstract fun getElementOfInterest(diagnostic: Diagnostic): E?
protected abstract fun createFixes(
originalElementPointer: SmartPsiElementPointer<E>,
diagnostic: Diagnostic,
quickFixDataFactory: () -> D?
): List<QuickFixWithDelegateFactory>
abstract fun extractFixData(element: E, diagnostic: Diagnostic): D?
final override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction> {
val diagnosticMessage = DefaultErrorMessages.render(diagnostic)
val diagnosticElementPointer = diagnostic.psiElement.createSmartPointer()
val originalElement = getElementOfInterest(diagnostic) ?: return emptyList()
val originalElementPointer = originalElement.createSmartPointer()
val file = originalElement.containingFile
val project = file.project
// Cache data so that it can be shared between quick fixes bound to the same element & diagnostic
// Cache null values
val cachedData: Ref<D> = Ref.create(extractFixData(originalElement, diagnostic))
return try {
createFixes(originalElementPointer, diagnostic) factory@{
val element = originalElementPointer.element ?: return@factory null
val diagnosticElement = diagnosticElementPointer.element ?: return@factory null
if (!diagnosticElement.isValid || !element.isValid) return@factory null
val currentDiagnostic = element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
.diagnostics
.forElement(diagnosticElement)
.firstOrNull { DefaultErrorMessages.render(it) == diagnosticMessage } ?: return@factory null
cachedData.get() ?: extractFixData(element, currentDiagnostic)
}.filter { it.isAvailable(project, null, file) }
} finally {
cachedData.set(null) // Do not keep cache after all actions are initialized
}
}
}
| apache-2.0 |
feelfreelinux/WykopMobilny | app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/input/entry/add/AddEntryPresenter.kt | 1 | 1684 | package io.github.feelfreelinux.wykopmobilny.ui.modules.input.entry.add
import io.github.feelfreelinux.wykopmobilny.api.WykopImageFile
import io.github.feelfreelinux.wykopmobilny.api.entries.EntriesApi
import io.github.feelfreelinux.wykopmobilny.base.Schedulers
import io.github.feelfreelinux.wykopmobilny.ui.modules.input.InputPresenter
import io.github.feelfreelinux.wykopmobilny.utils.intoComposite
class AddEntryPresenter(
private val schedulers: Schedulers,
private val entriesApi: EntriesApi
) : InputPresenter<AddEntryActivityView>() {
override fun sendWithPhoto(photo: WykopImageFile, containsAdultContent: Boolean) {
view?.showProgressBar = true
entriesApi.addEntry(view?.textBody!!, photo, containsAdultContent)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe(
{ view?.openEntryActivity(it.id) },
{
view?.showProgressBar = false
view?.showErrorDialog(it)
})
.intoComposite(compositeObservable)
}
override fun sendWithPhotoUrl(photo: String?, containsAdultContent: Boolean) {
view?.showProgressBar = true
entriesApi.addEntry(view?.textBody!!, photo, containsAdultContent)
.subscribeOn(schedulers.backgroundThread())
.observeOn(schedulers.mainThread())
.subscribe(
{ view?.openEntryActivity(it.id) },
{
view?.showProgressBar = false
view?.showErrorDialog(it)
})
.intoComposite(compositeObservable)
}
} | mit |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/collections/ConvertCallChainIntoSequenceInspection.kt | 1 | 10917 | // 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.collections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.editor.event.DocumentEvent
import com.intellij.openapi.editor.event.DocumentListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.LabeledComponent
import com.intellij.psi.PsiWhiteSpace
import com.intellij.ui.EditorTextField
import org.jetbrains.annotations.NonNls
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import java.awt.BorderLayout
import javax.swing.JPanel
class ConvertCallChainIntoSequenceInspection : AbstractKotlinInspection() {
private val defaultCallChainLength = 5
private var callChainLength = defaultCallChainLength
var callChainLengthText = defaultCallChainLength.toString()
set(value) {
field = value
callChainLength = value.toIntOrNull() ?: defaultCallChainLength
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
qualifiedExpressionVisitor(fun(expression) {
val (qualified, firstCall, callChainLength) = expression.findCallChain() ?: return
val rangeInElement = firstCall.calleeExpression?.textRange?.shiftRight(-qualified.startOffset) ?: return
val highlightType = if (callChainLength >= this.callChainLength)
ProblemHighlightType.GENERIC_ERROR_OR_WARNING
else
ProblemHighlightType.INFORMATION
holder.registerProblemWithoutOfflineInformation(
qualified,
KotlinBundle.message("call.chain.on.collection.could.be.converted.into.sequence.to.improve.performance"),
isOnTheFly,
highlightType,
rangeInElement,
ConvertCallChainIntoSequenceFix()
)
})
override fun createOptionsPanel(): JPanel = OptionsPanel(this)
private class OptionsPanel(owner: ConvertCallChainIntoSequenceInspection) : JPanel() {
init {
layout = BorderLayout()
val regexField = EditorTextField(owner.callChainLengthText).apply { setOneLineMode(true) }
regexField.document.addDocumentListener(object : DocumentListener {
override fun documentChanged(e: DocumentEvent) {
owner.callChainLengthText = regexField.text
}
})
val labeledComponent = LabeledComponent.create(regexField, KotlinBundle.message("call.chain.length.to.transform"), BorderLayout.WEST)
add(labeledComponent, BorderLayout.NORTH)
}
}
}
private class ConvertCallChainIntoSequenceFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("convert.call.chain.into.sequence.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val expression = descriptor.psiElement as? KtQualifiedExpression ?: return
val context = expression.analyze(BodyResolveMode.PARTIAL)
val calls = expression.collectCallExpression(context).reversed()
val firstCall = calls.firstOrNull() ?: return
val lastCall = calls.lastOrNull() ?: return
val first = firstCall.getQualifiedExpressionForSelector() ?: firstCall
val last = lastCall.getQualifiedExpressionForSelector() ?: return
val endWithTermination = lastCall.isTermination(context)
val psiFactory = KtPsiFactory(expression)
val dot = buildString {
if (first is KtQualifiedExpression
&& first.receiverExpression.siblings().filterIsInstance<PsiWhiteSpace>().any { it.textContains('\n') }
) append("\n")
if (first is KtSafeQualifiedExpression) append("?")
append(".")
}
val firstCommentSaver = CommentSaver(first)
val firstReplaced = first.replaced(
psiFactory.buildExpression {
if (first is KtQualifiedExpression) {
appendExpression(first.receiverExpression)
appendFixedText(dot)
}
appendExpression(psiFactory.createExpression("asSequence()"))
appendFixedText(dot)
appendExpression(firstCall)
}
)
firstCommentSaver.restore(firstReplaced)
if (!endWithTermination) {
val lastCommentSaver = CommentSaver(last)
val lastReplaced = last.replace(
psiFactory.buildExpression {
appendExpression(last)
appendFixedText(dot)
appendExpression(psiFactory.createExpression("toList()"))
}
)
lastCommentSaver.restore(lastReplaced)
}
}
}
private data class CallChain(
val qualified: KtQualifiedExpression,
val firstCall: KtCallExpression,
val callChainLength: Int
)
private fun KtQualifiedExpression.findCallChain(): CallChain? {
if (parent is KtQualifiedExpression) return null
val context = analyze(BodyResolveMode.PARTIAL)
val calls = collectCallExpression(context)
if (calls.isEmpty()) return null
val lastCall = calls.last()
val receiverType = lastCall.receiverType(context)
if (receiverType?.isIterable(DefaultBuiltIns.Instance) != true) return null
val firstCall = calls.first()
val qualified = firstCall.getQualifiedExpressionForSelector() ?: firstCall.getQualifiedExpressionForReceiver() ?: return null
return CallChain(qualified, lastCall, calls.size)
}
private fun KtQualifiedExpression.collectCallExpression(context: BindingContext): List<KtCallExpression> {
val calls = mutableListOf<KtCallExpression>()
fun collect(qualified: KtQualifiedExpression) {
val call = qualified.callExpression ?: return
calls.add(call)
val receiver = qualified.receiverExpression
if (receiver is KtCallExpression && receiver.implicitReceiver(context) != null) {
calls.add(receiver)
return
}
if (receiver is KtQualifiedExpression) collect(receiver)
}
collect(this)
if (calls.size < 2) return emptyList()
val transformationCalls = calls
.asSequence()
.dropWhile { !it.isTransformationOrTermination(context) }
.takeWhile { it.isTransformationOrTermination(context) && !it.hasReturn() }
.toList()
.dropLastWhile { it.isLazyTermination(context) }
if (transformationCalls.size < 2) return emptyList()
return transformationCalls
}
private fun KtCallExpression.hasReturn(): Boolean = valueArguments.any { arg ->
arg.anyDescendantOfType<KtReturnExpression> { it.labelQualifier == null }
}
private fun KtCallExpression.isTransformationOrTermination(context: BindingContext): Boolean {
val fqName = transformationAndTerminations[calleeExpression?.text] ?: return false
return isCalling(fqName, context)
}
private fun KtCallExpression.isTermination(context: BindingContext): Boolean {
val fqName = terminations[calleeExpression?.text] ?: return false
return isCalling(fqName, context)
}
private fun KtCallExpression.isLazyTermination(context: BindingContext): Boolean {
val fqName = lazyTerminations[calleeExpression?.text] ?: return false
return isCalling(fqName, context)
}
internal val collectionTransformationFunctionNames = listOf(
"chunked",
"distinct",
"distinctBy",
"drop",
"dropWhile",
"filter",
"filterIndexed",
"filterIsInstance",
"filterNot",
"filterNotNull",
"flatten",
"map",
"mapIndexed",
"mapIndexedNotNull",
"mapNotNull",
"minus",
"minusElement",
"onEach",
"onEachIndexed",
"plus",
"plusElement",
"requireNoNulls",
"sorted",
"sortedBy",
"sortedByDescending",
"sortedDescending",
"sortedWith",
"take",
"takeWhile",
"windowed",
"withIndex",
"zipWithNext"
)
@NonNls
private val transformations = collectionTransformationFunctionNames.associateWith { FqName("kotlin.collections.$it") }
internal val collectionTerminationFunctionNames = listOf(
"all",
"any",
"asIterable",
"asSequence",
"associate",
"associateBy",
"associateByTo",
"associateTo",
"average",
"contains",
"count",
"elementAt",
"elementAtOrElse",
"elementAtOrNull",
"filterIndexedTo",
"filterIsInstanceTo",
"filterNotNullTo",
"filterNotTo",
"filterTo",
"find",
"findLast",
"first",
"firstNotNullOf",
"firstNotNullOfOrNull",
"firstOrNull",
"fold",
"foldIndexed",
"groupBy",
"groupByTo",
"groupingBy",
"indexOf",
"indexOfFirst",
"indexOfLast",
"joinTo",
"joinToString",
"last",
"lastIndexOf",
"lastOrNull",
"mapIndexedNotNullTo",
"mapIndexedTo",
"mapNotNullTo",
"mapTo",
"maxOrNull",
"maxByOrNull",
"maxWithOrNull",
"maxOf",
"maxOfOrNull",
"maxOfWith",
"maxOfWithOrNull",
"minOrNull",
"minByOrNull",
"minWithOrNull",
"minOf",
"minOfOrNull",
"minOfWith",
"minOfWithOrNull",
"none",
"partition",
"reduce",
"reduceIndexed",
"reduceIndexedOrNull",
"reduceOrNull",
"runningFold",
"runningFoldIndexed",
"runningReduce",
"runningReduceIndexed",
"scan",
"scanIndexed",
"single",
"singleOrNull",
"sum",
"sumBy",
"sumByDouble",
"sumOf",
"toCollection",
"toHashSet",
"toList",
"toMutableList",
"toMutableSet",
"toSet",
"toSortedSet",
"unzip"
)
@NonNls
private val terminations = collectionTerminationFunctionNames.associateWith {
val pkg = if (it in listOf("contains", "indexOf", "lastIndexOf")) "kotlin.collections.List" else "kotlin.collections"
FqName("$pkg.$it")
}
private val lazyTerminations = terminations.filter { (key, _) -> key == "groupingBy" }
private val transformationAndTerminations = transformations + terminations
| apache-2.0 |
siosio/intellij-community | plugins/kotlin/jps/jps-plugin/tests/testData/incremental/withJava/other/accessingFunctionsViaRenamedFileClass/a.kt | 10 | 27 | package test
fun a() = "a" | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceGuardClauseWithFunctionCall/require/not.kt | 4 | 140 | // FIX: Replace with 'require()' call
// WITH_RUNTIME
fun test(foo: Boolean) {
<caret>if (!foo) throw IllegalArgumentException("test")
} | apache-2.0 |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/mount/MountNfs.kt | 2 | 1372 | package com.github.kerubistan.kerub.planner.steps.storage.mount
import com.fasterxml.jackson.annotation.JsonTypeName
import com.github.kerubistan.kerub.model.Host
import com.github.kerubistan.kerub.model.config.HostConfiguration
import com.github.kerubistan.kerub.model.services.HostService
import com.github.kerubistan.kerub.model.services.NfsMount
import com.github.kerubistan.kerub.planner.reservations.Reservation
import com.github.kerubistan.kerub.planner.reservations.UseHostReservation
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStep
import com.github.kerubistan.kerub.planner.steps.InvertibleStep
import com.github.kerubistan.kerub.planner.steps.ProducedBy
@JsonTypeName("mount-nfs")
@ProducedBy(MountNfsFactory::class)
data class MountNfs(override val host: Host, val remoteHost: Host, val directory: String, val remoteDirectory: String) :
AbstractNfsMount(), InvertibleStep {
override fun isInverseOf(other: AbstractOperationalStep) =
other is UnmountNfs && other.mountDir == directory
override fun updateHostConfiguration(config: HostConfiguration): List<HostService> = config.services + NfsMount(
remoteHostId = remoteHost.id,
localDirectory = directory,
remoteDirectory = remoteDirectory
)
override fun reservations(): List<Reservation<*>> = super.reservations() + listOf(
UseHostReservation(remoteHost)
)
} | apache-2.0 |
pengwei1024/sampleShare | HenCoderSample/class3/src/main/java/com/apkfuns/class3/MainActivity.kt | 1 | 301 | package com.apkfuns.class3
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
| apache-2.0 |
JetBrains/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/KonanReflectionTypes.kt | 1 | 3112 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.backend.konan
import org.jetbrains.kotlin.builtins.StandardNames.KOTLIN_REFLECT_FQ_NAME
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import kotlin.reflect.KProperty
class KonanReflectionTypes(module: ModuleDescriptor, internalPackage: FqName) {
private val kotlinReflectScope: MemberScope by lazy(LazyThreadSafetyMode.PUBLICATION) {
module.getPackage(KOTLIN_REFLECT_FQ_NAME).memberScope
}
private val internalScope: MemberScope by lazy(LazyThreadSafetyMode.PUBLICATION) {
module.getPackage(internalPackage).memberScope
}
private fun find(memberScope: MemberScope, className: String): ClassDescriptor {
val name = Name.identifier(className)
return memberScope.getContributedClassifier(name, NoLookupLocation.FROM_REFLECTION) as ClassDescriptor
}
private class ClassLookup(val memberScope: MemberScope) {
operator fun getValue(types: KonanReflectionTypes, property: KProperty<*>): ClassDescriptor {
return types.find(memberScope, property.name.capitalize())
}
}
fun getKFunction(n: Int): ClassDescriptor = find(kotlinReflectScope, "KFunction$n")
fun getKSuspendFunction(n: Int): ClassDescriptor = find(kotlinReflectScope, "KSuspendFunction$n")
val kProperty0: ClassDescriptor by ClassLookup(kotlinReflectScope)
val kMutableProperty0: ClassDescriptor by ClassLookup(kotlinReflectScope)
val kMutableProperty1: ClassDescriptor by ClassLookup(kotlinReflectScope)
val kMutableProperty2: ClassDescriptor by ClassLookup(kotlinReflectScope)
val kTypeProjection: ClassDescriptor by ClassLookup(kotlinReflectScope)
val kType: ClassDescriptor by ClassLookup(kotlinReflectScope)
val kVariance: ClassDescriptor by ClassLookup(kotlinReflectScope)
val kFunctionImpl: ClassDescriptor by ClassLookup(internalScope)
val kSuspendFunctionImpl: ClassDescriptor by ClassLookup(internalScope)
val kProperty0Impl: ClassDescriptor by ClassLookup(internalScope)
val kProperty1Impl: ClassDescriptor by ClassLookup(internalScope)
val kProperty2Impl: ClassDescriptor by ClassLookup(internalScope)
val kMutableProperty0Impl: ClassDescriptor by ClassLookup(internalScope)
val kMutableProperty1Impl: ClassDescriptor by ClassLookup(internalScope)
val kMutableProperty2Impl: ClassDescriptor by ClassLookup(internalScope)
val kLocalDelegatedPropertyImpl: ClassDescriptor by ClassLookup(internalScope)
val kLocalDelegatedMutablePropertyImpl: ClassDescriptor by ClassLookup(internalScope)
val typeOf = kotlinReflectScope.getContributedFunctions(Name.identifier("typeOf"), NoLookupLocation.FROM_REFLECTION).single()
}
| apache-2.0 |
JetBrains/kotlin-native | runtime/src/main/kotlin/kotlin/native/internal/test/TestLogger.kt | 2 | 3006 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package kotlin.native.internal.test
internal interface TestLogger: TestListener {
fun logTestList(runner: TestRunner, suites: Collection<TestSuite>)
fun log(message: String)
}
internal open class BaseTestLogger: BaseTestListener(), TestLogger {
override fun log(message: String) = println(message)
override fun logTestList(runner: TestRunner, suites: Collection<TestSuite>) {
suites.forEach { suite ->
println("${suite.name}.")
suite.testCases.values.forEach {
println(" ${it.name}")
}
}
}
}
internal open class TestLoggerWithStatistics: BaseTestLogger() {
protected val statistics = MutableTestStatistics()
override fun startTesting(runner: TestRunner) = statistics.reset()
override fun startIteration(runner: TestRunner, iteration: Int, suites: Collection<TestSuite>) = statistics.reset()
override fun finishSuite(suite: TestSuite, timeMillis: Long) = statistics.registerSuite()
override fun ignoreSuite(suite: TestSuite) = statistics.registerIgnore(suite.size)
override fun pass(testCase: TestCase, timeMillis: Long) = statistics.registerPass()
override fun fail(testCase: TestCase, e: Throwable, timeMillis: Long) = statistics.registerFail(testCase)
override fun ignore(testCase: TestCase) = statistics.registerIgnore()
}
internal class SilentTestLogger: BaseTestLogger() {
override fun logTestList(runner: TestRunner, suites: Collection<TestSuite>) {}
override fun log(message: String) {}
override fun fail(testCase: TestCase, e: Throwable, timeMillis: Long) = e.printStackTrace()
}
internal class SimpleTestLogger: BaseTestLogger() {
override fun startTesting(runner: TestRunner) = println("Starting testing")
override fun finishTesting(runner: TestRunner, timeMillis: Long) = println("Testing finished")
override fun startIteration(runner: TestRunner, iteration: Int, suites: Collection<TestSuite>) =
println("Starting iteration: $iteration")
override fun finishIteration(runner: TestRunner, iteration: Int, timeMillis: Long) =
println("Iteration finished: $iteration")
override fun startSuite(suite: TestSuite) = println("Starting test suite: $suite")
override fun finishSuite(suite: TestSuite, timeMillis: Long) = println("Test suite finished: $suite")
override fun ignoreSuite(suite: TestSuite) = println("Test suite ignored: $suite")
override fun start(testCase: TestCase) = println("Starting test case: $testCase")
override fun pass(testCase: TestCase, timeMillis: Long) = println("Passed: $testCase")
override fun fail(testCase: TestCase, e: Throwable, timeMillis: Long) {
println("Failed: $testCase. Exception:")
e.printStackTrace()
}
override fun ignore(testCase: TestCase) = println("Ignore: $testCase")
}
| apache-2.0 |
jwren/intellij-community | plugins/kotlin/fir/testData/intentions/useExpressionBody/convertToExpressionBody/funWithNoBlock.kt | 8 | 49 | // IS_APPLICABLE: false
fun foo() = <caret>"abc" | apache-2.0 |
JetBrains/kotlin-native | build-tools/src/main/kotlin/org/jetbrains/kotlin/CopySamples.kt | 1 | 2880 | package org.jetbrains.kotlin
import groovy.lang.Closure
import org.gradle.api.Task
import org.gradle.api.tasks.Copy
import org.gradle.api.tasks.InputDirectory
import java.io.File
/**
* A task that copies samples and replaces direct repository URLs with ones provided by the cache-redirector service.
* This task also adds kotlin compiler repository from the project's gradle.properties file.
*/
open class CopySamples : Copy() {
@InputDirectory
var samplesDir: File = project.file("samples")
private fun configureReplacements() {
from(samplesDir) {
it.exclude("**/*.gradle.kts")
it.exclude("**/*.gradle")
it.exclude("**/gradle.properties")
}
from(samplesDir) {
it.include("**/*.gradle")
it.include("**/*.gradle.kts")
it.filter { line ->
replacements.forEach { (repo, replacement) ->
if (line.contains(repo)) {
return@filter line.replace(repo, replacement)
}
}
return@filter line
}
}
from(samplesDir) {
it.include("**/gradle.properties")
val kotlinVersion = project.property("kotlinVersion") as? String
?: throw IllegalArgumentException("Property kotlinVersion should be specified in the root project")
val kotlinCompilerRepo = project.property("kotlinCompilerRepo") as? String
?: throw IllegalArgumentException("Property kotlinCompilerRepo should be specified in the root project")
it.filter { line ->
when {
line.startsWith("kotlin_version") -> "kotlin_version=$kotlinVersion"
line.startsWith("#kotlinCompilerRepo") || line.startsWith("kotlinCompilerRepo") ->
"kotlinCompilerRepo=$kotlinCompilerRepo"
else -> line
}
}
}
}
override fun configure(closure: Closure<Any>): Task {
super.configure(closure)
configureReplacements()
return this
}
private val replacements = listOf(
"https://dl.bintray.com/kotlin/kotlin-dev" to "https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/kotlin-dev",
"https://dl.bintray.com/kotlin/kotlin-eap" to "https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/kotlin-eap",
"https://dl.bintray.com/kotlin/ktor" to "https://cache-redirector.jetbrains.com/dl.bintray.com/kotlin/ktor",
"https://plugins.gradle.org/m2" to "https://cache-redirector.jetbrains.com/plugins.gradle.org/m2",
"mavenCentral()" to "maven { setUrl(\"https://cache-redirector.jetbrains.com/maven-central\") }",
"jcenter()" to "maven { setUrl(\"https://cache-redirector.jetbrains.com/jcenter\") }",
)
}
| apache-2.0 |
BijoySingh/Quick-Note-Android | scarlet/src/main/java/com/bijoysingh/quicknote/firebase/data/FirebaseNote.kt | 1 | 1353 | package com.bijoysingh.quicknote.firebase.data
import com.google.firebase.database.Exclude
import com.maubis.scarlet.base.core.note.INoteContainer
import com.maubis.scarlet.base.core.note.NoteState
import java.util.*
// TODO: Remove this on Firebase deprecation
class FirebaseNote(
val uuid: String,
val description: String,
val timestamp: Long,
val updateTimestamp: Long,
val color: Int,
val state: String,
val tags: String,
val locked: Boolean,
val pinned: Boolean,
val folder: String) : INoteContainer {
@Exclude
override fun uuid(): String = uuid
@Exclude
override fun description(): String = description
@Exclude
override fun timestamp(): Long = timestamp
@Exclude
override fun updateTimestamp(): Long = updateTimestamp
@Exclude
override fun color(): Int = color
@Exclude
override fun state(): String = state
@Exclude
override fun tags(): String = tags
@Exclude
override fun meta(): Map<String, Any> = emptyMap()
@Exclude
override fun locked(): Boolean = locked
@Exclude
override fun pinned(): Boolean = pinned
@Exclude
override fun folder(): String = folder
constructor() : this(
"invalid",
"",
Calendar.getInstance().timeInMillis,
Calendar.getInstance().timeInMillis,
-0xff8695,
NoteState.DEFAULT.name,
"",
false,
false,
"")
} | gpl-3.0 |
jwren/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/completion/weighers/VariableOrFunctionWeigher.kt | 8 | 1572 | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.idea.completion.weighers
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementWeigher
import com.intellij.openapi.util.Key
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionLikeSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtVariableLikeSymbol
import org.jetbrains.kotlin.psi.UserDataProperty
object VariableOrFunctionWeigher {
private enum class Weight {
VARIABLE,
FUNCTION
}
const val WEIGHER_ID = "kotlin.variableOrFunction"
private var LookupElement.variableOrFunction by UserDataProperty(Key<Weight>("KOTLIN_VARIABLE_OR_FUNCTION_WEIGHT"))
fun KtAnalysisSession.addWeight(lookupElement: LookupElement, symbol: KtSymbol) {
when (symbol) {
is KtVariableLikeSymbol -> {
lookupElement.variableOrFunction = Weight.VARIABLE
}
is KtFunctionLikeSymbol -> {
lookupElement.variableOrFunction = Weight.FUNCTION
}
else -> {
}
}
}
object Weigher : LookupElementWeigher(WEIGHER_ID) {
override fun weigh(element: LookupElement): Comparable<*>? = element.variableOrFunction
}
} | apache-2.0 |
JetBrains/intellij-community | python/src/com/jetbrains/python/sdk/PySdkPopupFactory.kt | 1 | 5296 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.intellij.ide.DataManager
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.ListPopup
import com.intellij.openapi.util.Condition
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.registry.Registry
import com.intellij.util.text.trimMiddle
import com.intellij.util.ui.SwingHelper
import com.jetbrains.python.PyBundle
import com.jetbrains.python.configuration.PyConfigurableInterpreterList
import com.jetbrains.python.inspections.PyInterpreterInspection
import com.jetbrains.python.psi.LanguageLevel
import com.jetbrains.python.run.PythonInterpreterTargetEnvironmentFactory
import com.jetbrains.python.run.codeCouldProbablyBeRunWithConfig
class PySdkPopupFactory(val project: Project, val module: Module) {
companion object {
private fun nameInPopup(sdk: Sdk): String {
val (_, primary, secondary) = name(sdk)
return if (secondary == null) primary else "$primary [$secondary]"
}
@NlsSafe
fun shortenNameInPopup(sdk: Sdk, maxLength: Int) = nameInPopup(sdk).trimMiddle(maxLength)
fun descriptionInPopup(sdk: Sdk) = "${nameInPopup(sdk)} [${path(sdk)}]".trimMiddle(150)
fun createAndShow(project: Project, module: Module) {
DataManager.getInstance()
.dataContextFromFocusAsync
.onSuccess {
val popup = PySdkPopupFactory(project, module).createPopup(it)
val component = SwingHelper.getComponentFromRecentMouseEvent()
if (component != null) {
popup.showUnderneathOf(component)
}
else {
popup.showInBestPositionFor(it)
}
}
}
}
fun createPopup(context: DataContext): ListPopup {
val group = DefaultActionGroup()
val interpreterList = PyConfigurableInterpreterList.getInstance(project)
val moduleSdksByTypes = groupModuleSdksByTypes(interpreterList.getAllPythonSdks(project, module), module) {
!it.sdkSeemsValid ||
PythonSdkType.hasInvalidRemoteCredentials(it) ||
PythonSdkType.isIncompleteRemote(it) ||
!LanguageLevel.SUPPORTED_LEVELS.contains(PythonSdkType.getLanguageLevelForSdk(it))
}
val currentSdk = module.pythonSdk
val model = interpreterList.model
val targetModuleSitsOn = PythonInterpreterTargetEnvironmentFactory.getTargetModuleResidesOn(module)
PyRenderedSdkType.values().forEachIndexed { index, type ->
if (type in moduleSdksByTypes) {
if (index != 0) group.addSeparator()
group.addAll(moduleSdksByTypes
.getValue(type)
.filter {
targetModuleSitsOn == null ||
targetModuleSitsOn.codeCouldProbablyBeRunWithConfig(it.targetAdditionalData?.targetEnvironmentConfiguration)
}
.mapNotNull { model.findSdk(it) }
.map { SwitchToSdkAction(it, currentSdk) })
}
}
if (moduleSdksByTypes.isNotEmpty()) group.addSeparator()
if (Registry.get("python.use.targets.api").asBoolean()) {
val addNewInterpreterPopupGroup = DefaultActionGroup(PyBundle.message("python.sdk.action.add.new.interpreter.text"), true)
addNewInterpreterPopupGroup.addAll(collectAddInterpreterActions(project, module) { switchToSdk(module, it, currentSdk) })
group.add(addNewInterpreterPopupGroup)
group.addSeparator()
}
group.add(InterpreterSettingsAction())
if (!Registry.get("python.use.targets.api").asBoolean()) {
group.add(AddInterpreterAction(project, module, currentSdk))
}
return JBPopupFactory.getInstance().createActionGroupPopup(
PyBundle.message("configurable.PyActiveSdkModuleConfigurable.python.interpreter.display.name"),
group,
context,
JBPopupFactory.ActionSelectionAid.SPEEDSEARCH,
false,
null,
-1,
Condition { it is SwitchToSdkAction && it.sdk == currentSdk },
null
).apply { setHandleAutoSelectionBeforeShow(true) }
}
private inner class SwitchToSdkAction(val sdk: Sdk, val currentSdk: Sdk?) : DumbAwareAction() {
init {
val presentation = templatePresentation
presentation.setText(shortenNameInPopup(sdk, 100), false)
presentation.description = PyBundle.message("python.sdk.switch.to", descriptionInPopup(sdk))
presentation.icon = icon(sdk)
}
override fun actionPerformed(e: AnActionEvent) = switchToSdk(module, sdk, currentSdk)
}
private inner class InterpreterSettingsAction : DumbAwareAction(PyBundle.messagePointer("python.sdk.popup.interpreter.settings")) {
override fun actionPerformed(e: AnActionEvent) {
PyInterpreterInspection.InterpreterSettingsQuickFix.showPythonInterpreterSettings(project, module)
}
}
} | apache-2.0 |
aquatir/remember_java_api | code-sample-angular-kotlin/code-sample-jwt-token-example/kotlin-backend/src/main/kotlin/codesample/kotlin/jwtexample/controller/ImportantDataController.kt | 1 | 829 | package codesample.kotlin.jwtexample.controller
import codesample.kotlin.jwtexample.dto.StringReqResp
import org.springframework.security.access.prepost.PreAuthorize
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class ImportantDataController {
@GetMapping("/data")
fun getData() = StringReqResp("data success!")
@GetMapping("/userData")
@PreAuthorize("hasRole('USER')")
fun getUserDate() = StringReqResp("userData success!")
@GetMapping("/adminData")
@PreAuthorize("hasRole('ADMIN')")
fun getAdminDate() = StringReqResp("adminData success!")
@GetMapping("/userOrAdminData")
@PreAuthorize("hasAnyRole('USER', 'ADMIN')")
fun getUserOrAdminData() = StringReqResp("userOrAdminData success!")
} | mit |
androidx/androidx | work/work-testing/src/main/java/androidx/work/testing/TestScheduler.kt | 3 | 9547 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
package androidx.work.testing
import android.content.Context
import androidx.annotation.GuardedBy
import androidx.annotation.RestrictTo
import androidx.work.Worker
import androidx.work.impl.ExecutionListener
import androidx.work.impl.Scheduler
import androidx.work.impl.WorkDatabase
import androidx.work.impl.model.WorkGenerationalId
import androidx.work.impl.WorkManagerImpl
import androidx.work.impl.StartStopTokens
import androidx.work.impl.model.generationalId
import androidx.work.impl.model.WorkSpec
import androidx.work.impl.model.WorkSpecDao
import java.util.UUID
/**
* A test scheduler that schedules unconstrained, non-timed workers. It intentionally does
* not acquire any WakeLocks, instead trying to brute-force them as time allows before the process
* gets killed.
*
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class TestScheduler(private val context: Context) : Scheduler, ExecutionListener {
@GuardedBy("lock")
private val pendingWorkStates = mutableMapOf<String, InternalWorkState>()
@GuardedBy("lock")
private val terminatedWorkIds = mutableSetOf<String>()
private val lock = Any()
private val mStartStopTokens = StartStopTokens()
override fun hasLimitedSchedulingSlots() = true
override fun schedule(vararg workSpecs: WorkSpec) {
if (workSpecs.isEmpty()) {
return
}
val toSchedule = mutableMapOf<WorkSpec, InternalWorkState>()
synchronized(lock) {
workSpecs.forEach {
val state = pendingWorkStates.getOrPut(it.generationalId().workSpecId) {
InternalWorkState(it)
}
toSchedule[it] = state
}
}
toSchedule.forEach { (originalSpec, state) ->
// this spec is attempted to run for the first time
// so we have to rewind the time, because we have to override flex.
val spec = if (originalSpec.isPeriodic && state.periodDelayMet) {
WorkManagerImpl.getInstance(context).rewindLastEnqueueTime(originalSpec.id)
} else originalSpec
// don't even try to run a worker that WorkerWrapper won't execute anyway.
// similar to logic in WorkerWrapper
if ((spec.isPeriodic || spec.isBackedOff) &&
(spec.calculateNextRunTime() > System.currentTimeMillis())) {
return@forEach
}
scheduleInternal(spec.generationalId(), state)
}
}
override fun cancel(workSpecId: String) {
// We don't need to keep track of cancelled workSpecs. This is because subsequent calls
// to enqueue() will no-op because insertWorkSpec in WorkDatabase has a conflict
// policy of @Ignore. So TestScheduler will _never_ be asked to schedule those
// WorkSpecs.
val tokens = mStartStopTokens.remove(workSpecId)
tokens.forEach { WorkManagerImpl.getInstance(context).stopWork(it) }
synchronized(lock) {
val internalWorkState = pendingWorkStates[workSpecId]
if (internalWorkState != null && !internalWorkState.isPeriodic) {
// Don't remove PeriodicWorkRequests from the list of pending work states.
// This is because we keep track of mPeriodDelayMet for PeriodicWorkRequests.
// `mPeriodDelayMet` is set to `false` when `onExecuted()` is called as a result of a
// successful run or a cancellation. That way subsequent calls to schedule() no-op
// until a developer explicitly calls setPeriodDelayMet().
pendingWorkStates.remove(workSpecId)
}
}
}
/**
* Tells the [TestScheduler] to pretend that all constraints on the [Worker] with
* the given `workSpecId` are met.
*
* @param workSpecId The [Worker]'s id
* @throws IllegalArgumentException if `workSpecId` is not enqueued
*/
fun setAllConstraintsMet(workSpecId: UUID) {
val id = workSpecId.toString()
val state: InternalWorkState
synchronized(lock) {
if (id in terminatedWorkIds) return
val oldState = pendingWorkStates[id]
?: throw IllegalArgumentException("Work with id $workSpecId is not enqueued!")
state = oldState.copy(constraintsMet = true)
pendingWorkStates[id] = state
}
scheduleInternal(WorkGenerationalId(id, state.generation), state)
}
/**
* Tells the [TestScheduler] to pretend that the initial delay on the [Worker] with
* the given `workSpecId` are met.
*
* @param workSpecId The [Worker]'s id
* @throws IllegalArgumentException if `workSpecId` is not enqueued
*/
fun setInitialDelayMet(workSpecId: UUID) {
val id = workSpecId.toString()
val state: InternalWorkState
synchronized(lock) {
if (id in terminatedWorkIds) return
val oldState = pendingWorkStates[id]
?: throw IllegalArgumentException("Work with id $workSpecId is not enqueued!")
state = oldState.copy(initialDelayMet = true)
pendingWorkStates[id] = state
}
WorkManagerImpl.getInstance(context).rewindLastEnqueueTime(id)
scheduleInternal(WorkGenerationalId(id, state.generation), state)
}
/**
* Tells the [TestScheduler] to pretend that the periodic delay on the [Worker] with
* the given `workSpecId` are met.
*
* @param workSpecId The [Worker]'s id
* @throws IllegalArgumentException if `workSpecId` is not enqueued
*/
fun setPeriodDelayMet(workSpecId: UUID) {
val id = workSpecId.toString()
val state: InternalWorkState
synchronized(lock) {
val oldState = pendingWorkStates[id]
?: throw IllegalArgumentException("Work with id $workSpecId is not enqueued!")
state = oldState.copy(periodDelayMet = true)
pendingWorkStates[id] = state
}
WorkManagerImpl.getInstance(context).rewindLastEnqueueTime(id)
scheduleInternal(WorkGenerationalId(id, state.generation), state)
}
override fun onExecuted(id: WorkGenerationalId, needsReschedule: Boolean) {
synchronized(lock) {
val workSpecId = id.workSpecId
val internalWorkState = pendingWorkStates[workSpecId] ?: return
if (internalWorkState.isPeriodic) {
pendingWorkStates[workSpecId] = internalWorkState.copy(
periodDelayMet = !internalWorkState.isPeriodic,
constraintsMet = !internalWorkState.hasConstraints,
)
} else {
pendingWorkStates.remove(workSpecId)
terminatedWorkIds.add(workSpecId)
}
mStartStopTokens.remove(workSpecId)
}
}
private fun scheduleInternal(generationalId: WorkGenerationalId, state: InternalWorkState) {
if (state.isRunnable) {
val wm = WorkManagerImpl.getInstance(context)
wm.startWork(mStartStopTokens.tokenFor(generationalId))
}
}
}
internal data class InternalWorkState(
val generation: Int,
val constraintsMet: Boolean,
val initialDelayMet: Boolean,
val periodDelayMet: Boolean,
val hasConstraints: Boolean,
val isPeriodic: Boolean,
)
internal val InternalWorkState.isRunnable: Boolean
get() = constraintsMet && initialDelayMet && periodDelayMet
internal fun InternalWorkState(spec: WorkSpec): InternalWorkState =
InternalWorkState(
generation = spec.generation,
constraintsMet = !spec.hasConstraints(),
initialDelayMet = spec.initialDelay == 0L,
periodDelayMet = true,
hasConstraints = spec.hasConstraints(),
isPeriodic = spec.isPeriodic
)
private fun WorkManagerImpl.rewindLastEnqueueTime(id: String): WorkSpec {
// We need to pass check that mWorkSpec.calculateNextRunTime() < now
// so we reset "rewind" enqueue time to pass the check
// we don't reuse available internalWorkState.mWorkSpec, because it
// is not update with period_count and last_enqueue_time
// More proper solution would be to abstract away time instead of just using
// System.currentTimeMillis() in WM
val workDatabase: WorkDatabase = workDatabase
val dao: WorkSpecDao = workDatabase.workSpecDao()
val workSpec: WorkSpec = dao.getWorkSpec(id)
?: throw IllegalStateException("WorkSpec is already deleted from WM's db")
val now = System.currentTimeMillis()
val timeOffset = workSpec.calculateNextRunTime() - now
if (timeOffset > 0) {
dao.setLastEnqueuedTime(id, workSpec.lastEnqueueTime - timeOffset)
}
return dao.getWorkSpec(id)
?: throw IllegalStateException("WorkSpec is already deleted from WM's db")
} | apache-2.0 |
androidx/androidx | core/uwb/uwb/src/androidTest/java/androidx/core/uwb/impl/UwbClientSessionScopeImplTest.kt | 3 | 10166 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.uwb.impl
import androidx.core.uwb.RangingResult
import androidx.core.uwb.RangingResult.RangingResultPeerDisconnected
import androidx.core.uwb.RangingResult.RangingResultPosition
import androidx.core.uwb.common.TestCommons.Companion.COMPLEX_CHANNEL
import androidx.core.uwb.common.TestCommons.Companion.LOCAL_ADDRESS
import androidx.core.uwb.common.TestCommons.Companion.RANGING_CAPABILITIES
import androidx.core.uwb.common.TestCommons.Companion.RANGING_PARAMETERS
import androidx.core.uwb.common.TestCommons.Companion.UWB_DEVICE
import androidx.core.uwb.mock.TestUwbClient
import com.google.common.truth.Truth.assertThat
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.cancellable
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
class UwbClientSessionScopeImplTest {
private val uwbClient = TestUwbClient(
COMPLEX_CHANNEL, LOCAL_ADDRESS, RANGING_CAPABILITIES,
isAvailable = true,
isController = false
)
private val uwbClientSession = UwbClientSessionScopeImpl(
uwbClient,
androidx.core.uwb.RangingCapabilities(
RANGING_CAPABILITIES.supportsDistance(),
RANGING_CAPABILITIES.supportsAzimuthalAngle(),
RANGING_CAPABILITIES.supportsElevationAngle()
),
androidx.core.uwb.UwbAddress(LOCAL_ADDRESS.address)
)
@Test
public fun testInitSession_singleConsumer() {
val sessionFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS)
var rangingResult: RangingResult? = null
val job = sessionFlow
.cancellable()
.onEach { rangingResult = it }
.launchIn(CoroutineScope(Dispatchers.Main.immediate))
runBlocking {
// wait for the coroutines for UWB to get launched.
delay(500)
}
// a non-null RangingResult should return from the TestUwbClient.
if (rangingResult != null) {
assertThat(rangingResult is RangingResultPosition).isTrue()
} else {
job.cancel()
Assert.fail()
}
// cancel and wait for the job to terminate.
job.cancel()
runBlocking {
job.join()
}
// StopRanging should have been called after the coroutine scope completed.
assertThat(uwbClient.stopRangingCalled).isTrue()
}
@Test
public fun testInitSession_multipleSharedConsumers() {
var passed1 = false
var passed2 = false
val sharedFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS)
.shareIn(CoroutineScope(Dispatchers.Main.immediate), SharingStarted.WhileSubscribed(),
replay = 1)
val job = CoroutineScope(Dispatchers.Main.immediate).launch {
sharedFlow
.onEach {
if (it is RangingResultPosition) {
passed1 = true
}
}
.collect()
}
val job2 = CoroutineScope(Dispatchers.Main.immediate).launch {
sharedFlow
.onEach {
if (it is RangingResultPosition) {
passed2 = true
}
}
.collect()
}
runBlocking {
// wait for coroutines for flow to start.
delay(500)
}
// a non-null RangingResult should return from the TestUwbClient.
assertThat(passed1).isTrue()
assertThat(passed2).isTrue()
// cancel and wait for the first job to terminate.
job.cancel()
runBlocking {
job.join()
}
// StopRanging should not have been called because not all consumers have finished.
assertThat(uwbClient.stopRangingCalled).isFalse()
// cancel and wait for the second job to terminate.
job2.cancel()
runBlocking {
job2.join()
}
// StopRanging should have been called because all consumers have finished.
assertThat(uwbClient.stopRangingCalled).isTrue()
}
@Test
public fun testInitSession_singleConsumer_disconnectPeerDevice() {
val sessionFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS)
var peerDisconnected = false
val job = CoroutineScope(Dispatchers.Main.immediate).launch {
sessionFlow
.cancellable()
.onEach {
if (it is RangingResultPeerDisconnected) {
peerDisconnected = true
}
}
.collect()
}
runBlocking {
// wait for coroutines for flow to start.
delay(500)
uwbClient.disconnectPeer(com.google.android.gms.nearby.uwb.UwbDevice.createForAddress(
UWB_DEVICE.address.address))
// wait for rangingResults to get filled.
delay(500)
}
// a peer disconnected event should have occurred.
assertThat(peerDisconnected).isTrue()
// cancel and wait for the job to terminate.
job.cancel()
runBlocking {
job.join()
}
// StopRanging should have been called after the coroutine scope completed.
assertThat(uwbClient.stopRangingCalled).isTrue()
}
@Test
public fun testInitSession_multipleSharedConsumers_disconnectPeerDevice() {
val sharedFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS)
.shareIn(CoroutineScope(Dispatchers.Main.immediate), SharingStarted.WhileSubscribed())
var peerDisconnected = false
var peerDisconnected2 = false
val job = CoroutineScope(Dispatchers.Main.immediate).launch {
sharedFlow
.onEach {
if (it is RangingResultPeerDisconnected) {
peerDisconnected = true
}
}
.collect()
}
val job2 = CoroutineScope(Dispatchers.Main.immediate).launch {
sharedFlow
.onEach {
if (it is RangingResultPeerDisconnected) {
peerDisconnected2 = true
}
}
.collect()
}
runBlocking {
// wait for coroutines for flow to start.
delay(500)
uwbClient.disconnectPeer(com.google.android.gms.nearby.uwb.UwbDevice.createForAddress(
UWB_DEVICE.address.address))
// wait for rangingResults to get filled.
delay(500)
}
// a peer disconnected event should have occurred.
assertThat(peerDisconnected).isTrue()
assertThat(peerDisconnected2).isTrue()
// cancel and wait for the job to terminate.
job.cancel()
runBlocking {
job.join()
}
// StopRanging should not have been called because not all consumers have finished.
assertThat(uwbClient.stopRangingCalled).isFalse()
// cancel and wait for the job to terminate.
job2.cancel()
runBlocking {
job2.join()
}
// StopRanging should have been called because all consumers have finished.
assertThat(uwbClient.stopRangingCalled).isTrue()
}
@Test
public fun testInitSession_multipleSessions_throwsUwbApiException() {
val sessionFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS)
val sessionFlow2 = uwbClientSession.prepareSession(RANGING_PARAMETERS)
val job = CoroutineScope(Dispatchers.Main.immediate).launch {
sessionFlow.collect()
}
runBlocking {
// wait for coroutines for flow to start.
delay(500)
}
val job2 = CoroutineScope(Dispatchers.Main.immediate).launch {
try {
sessionFlow2.collect()
Assert.fail()
} catch (e: IllegalStateException) {
// verified the exception was thrown.
}
}
job.cancel()
job2.cancel()
}
@Test
public fun testInitSession_reusingSession_throwsUwbApiException() {
val sessionFlow = uwbClientSession.prepareSession(RANGING_PARAMETERS)
val job = CoroutineScope(Dispatchers.Main.immediate).launch {
sessionFlow.collect()
}
runBlocking {
// wait for coroutines for flow to start.
delay(500)
}
// cancel and wait for the job to terminate.
job.cancel()
runBlocking {
job.join()
}
// StopRanging should not have been called because not all consumers have finished.
assertThat(uwbClient.stopRangingCalled).isTrue()
val job2 = CoroutineScope(Dispatchers.Main.immediate).launch {
try {
// Reuse the same session after it was closed.
sessionFlow.collect()
Assert.fail()
} catch (e: IllegalStateException) {
// verified the exception was thrown.
}
}
job2.cancel()
}
} | apache-2.0 |
androidx/androidx | compose/ui/ui-unit/src/androidAndroidTest/kotlin/androidx/compose/ui/unit/DpDeviceTest.kt | 3 | 1649 | /*
* 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.compose.ui.unit
import android.app.Activity
import android.util.TypedValue
import androidx.test.filters.SmallTest
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import androidx.test.ext.junit.runners.AndroidJUnit4
@SmallTest
@RunWith(AndroidJUnit4::class)
class DpDeviceTest {
@Suppress("DEPRECATION")
@get:Rule
val activityTestRule = androidx.test.rule.ActivityTestRule<TestActivity>(
TestActivity::class.java
)
private lateinit var activity: Activity
@Before
fun setup() {
activity = activityTestRule.activity
}
@Test
fun dimensionCalculation() {
val dm = activity.resources.displayMetrics
val dp10InPx = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 10f, dm)
with(Density(activity)) {
assertEquals(dp10InPx, 10.dp.toPx(), 0.01f)
}
}
companion object {
class TestActivity : Activity()
}
} | apache-2.0 |
androidx/androidx | room/room-compiler/src/test/test-data/kotlinCodeGen/pojoRowAdapter_internalVisibility.kt | 3 | 3373 | import android.database.Cursor
import androidx.room.EntityInsertionAdapter
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.query
import androidx.sqlite.db.SupportSQLiteStatement
import java.lang.Class
import javax.`annotation`.processing.Generated
import kotlin.Int
import kotlin.Long
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmStatic
@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"])
public class MyDao_Impl(
__db: RoomDatabase,
) : MyDao {
private val __db: RoomDatabase
private val __insertionAdapterOfMyEntity: EntityInsertionAdapter<MyEntity>
init {
this.__db = __db
this.__insertionAdapterOfMyEntity = object : EntityInsertionAdapter<MyEntity>(__db) {
public override fun createQuery(): String =
"INSERT OR ABORT INTO `MyEntity` (`pk`,`internalVal`,`internalVar`,`internalSetterVar`) VALUES (?,?,?,?)"
public override fun bind(statement: SupportSQLiteStatement, entity: MyEntity): Unit {
statement.bindLong(1, entity.pk.toLong())
statement.bindLong(2, entity.internalVal)
statement.bindLong(3, entity.internalVar)
statement.bindLong(4, entity.internalSetterVar)
}
}
}
public override fun addEntity(item: MyEntity): Unit {
__db.assertNotSuspendingTransaction()
__db.beginTransaction()
try {
__insertionAdapterOfMyEntity.insert(item)
__db.setTransactionSuccessful()
} finally {
__db.endTransaction()
}
}
public override fun getEntity(): MyEntity {
val _sql: String = "SELECT * FROM MyEntity"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfPk: Int = getColumnIndexOrThrow(_cursor, "pk")
val _cursorIndexOfInternalVal: Int = getColumnIndexOrThrow(_cursor, "internalVal")
val _cursorIndexOfInternalVar: Int = getColumnIndexOrThrow(_cursor, "internalVar")
val _cursorIndexOfInternalSetterVar: Int = getColumnIndexOrThrow(_cursor, "internalSetterVar")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpPk: Int
_tmpPk = _cursor.getInt(_cursorIndexOfPk)
val _tmpInternalVal: Long
_tmpInternalVal = _cursor.getLong(_cursorIndexOfInternalVal)
_result = MyEntity(_tmpPk,_tmpInternalVal)
_result.internalVar = _cursor.getLong(_cursorIndexOfInternalVar)
_result.internalSetterVar = _cursor.getLong(_cursorIndexOfInternalSetterVar)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public companion object {
@JvmStatic
public fun getRequiredConverters(): List<Class<*>> = emptyList()
}
} | apache-2.0 |
androidx/androidx | resourceinspection/resourceinspection-processor/src/main/kotlin/androidx/resourceinspection/processor/LayoutInspectionStep.kt | 3 | 20929 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.resourceinspection.processor
import com.google.auto.common.AnnotationMirrors.getAnnotationValue
import com.google.auto.common.BasicAnnotationProcessor
import com.google.auto.common.GeneratedAnnotationSpecs.generatedAnnotationSpec
import com.google.auto.common.MoreElements.asExecutable
import com.google.auto.common.MoreElements.asType
import com.google.auto.common.MoreElements.getPackage
import com.google.auto.common.Visibility
import com.google.auto.common.Visibility.effectiveVisibilityOfElement
import com.google.common.collect.ImmutableSetMultimap
import com.squareup.javapoet.AnnotationSpec
import javax.annotation.processing.ProcessingEnvironment
import javax.annotation.processing.Processor
import javax.lang.model.element.AnnotationMirror
import javax.lang.model.element.AnnotationValue
import javax.lang.model.element.Element
import javax.lang.model.element.ExecutableElement
import javax.lang.model.element.TypeElement
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
import javax.tools.Diagnostic
/** Processing step for generating layout inspection companions from `Attribute` annotations. */
internal class LayoutInspectionStep(
private val processingEnv: ProcessingEnvironment,
processorClass: Class<out Processor>
) : BasicAnnotationProcessor.Step {
private val generatedAnnotation: AnnotationSpec? = generatedAnnotationSpec(
processingEnv.elementUtils,
processingEnv.sourceVersion,
processorClass
).orElse(null)
override fun annotations(): Set<String> {
return setOf(ATTRIBUTE, APP_COMPAT_SHADOWED_ATTRIBUTES)
}
override fun process(
elementsByAnnotation: ImmutableSetMultimap<String, Element>
): Set<Element> {
if (!isViewInspectorApiPresent()) {
printError(
"View inspector (android.view.inspector) API is not present. " +
"Please ensure compile SDK is 29 or greater."
)
return emptySet()
}
val views = mergeViews(
elementsByAnnotation[ATTRIBUTE]
.groupBy({ asType(it.enclosingElement) }, { asExecutable(it) }),
elementsByAnnotation[APP_COMPAT_SHADOWED_ATTRIBUTES]
.mapTo(mutableSetOf()) { asType(it) }
)
val filer = processingEnv.filer
views.forEach { generateInspectionCompanion(it, generatedAnnotation).writeTo(filer) }
// We don't defer elements for later rounds in this processor
return emptySet()
}
/** Checks if the view inspector API is present in the compile class path */
private fun isViewInspectorApiPresent(): Boolean {
return VIEW_INSPECTOR_CLASSES.all { className ->
processingEnv.elementUtils.getTypeElement(className) != null
}
}
/** Merge shadowed and regular attributes into [View] models. */
private fun mergeViews(
viewsWithGetters: Map<TypeElement, List<ExecutableElement>>,
viewsWithShadowedAttributes: Set<TypeElement>
): List<View> {
return (viewsWithGetters.keys + viewsWithShadowedAttributes).mapNotNull { viewType ->
val getterAttributes = viewsWithGetters[viewType].orEmpty().map(::parseGetter)
if (viewType in viewsWithShadowedAttributes) {
inferShadowedAttributes(viewType)?.let { shadowedAttributes ->
createView(viewType, getterAttributes + shadowedAttributes)
}
} else {
createView(viewType, getterAttributes)
}
}
}
/** Parse the annotated getters of a view class into a [View]. */
private fun createView(type: TypeElement, attributes: Collection<Attribute?>): View? {
val duplicateAttributes = attributes
.filterNotNull()
.groupBy { it.qualifiedName }
.values
.filter { it.size > 1 }
if (duplicateAttributes.any()) {
duplicateAttributes.forEach { duplicates ->
duplicates.forEach { attribute ->
val qualifiedName = attribute.qualifiedName
val otherGetters = duplicates
.filter { it.invocation != attribute.invocation }
.joinToString { it.invocation }
printError(
"Duplicate attribute $qualifiedName is also present on $otherGetters",
(attribute as? GetterAttribute)?.getter,
(attribute as? GetterAttribute)?.annotation
)
}
}
return null
}
if (attributes.isEmpty() || attributes.any { it == null }) {
return null
}
return View(type, attributes = attributes.filterNotNull().sortedBy { it.qualifiedName })
}
/** Get an [Attribute] from a method known to have an `Attribute` annotation. */
private fun parseGetter(getter: ExecutableElement): Attribute? {
val annotation = getter.getAnnotationMirror(ATTRIBUTE)!!
val annotationValue = getAnnotationValue(annotation, "value")
val value = annotationValue.value as String
var hasError = false
if (getter.parameters.isNotEmpty() || getter.returnType.kind == TypeKind.VOID) {
printError("@Attribute must annotate a getter", getter, annotation)
hasError = true
}
if (effectiveVisibilityOfElement(getter) != Visibility.PUBLIC) {
printError("@Attribute getter must be public", getter, annotation)
hasError = true
}
if (!getter.enclosingElement.asType().isAssignableTo(VIEW)) {
printError("@Attribute must be on a subclass of android.view.View", getter, annotation)
hasError = true
}
val intMapping = parseIntMapping(annotation)
if (!validateIntMapping(getter, intMapping)) {
hasError = true
}
val match = ATTRIBUTE_VALUE.matchEntire(value)
if (match == null) {
if (!value.contains(':')) {
printError("@Attribute must include namespace", getter, annotation, annotationValue)
} else {
printError("Invalid attribute name", getter, annotation, annotationValue)
}
return null // Returning here since there's no more checks we can do
}
if (hasError) {
return null
}
val (namespace, name) = match.destructured
val type = inferAttributeType(getter, intMapping)
if (!isAttributeInRFile(namespace, name)) {
printError("Attribute $namespace:$name not found", getter, annotation)
return null
}
return GetterAttribute(getter, annotation, namespace, name, type, intMapping)
}
/** Parse `Attribute.intMapping`. */
private fun parseIntMapping(annotation: AnnotationMirror): List<IntMap> {
return (getAnnotationValue(annotation, "intMapping").value as List<*>).map { entry ->
val intMapAnnotation = (entry as AnnotationValue).value as AnnotationMirror
IntMap(
name = getAnnotationValue(intMapAnnotation, "name").value as String,
value = getAnnotationValue(intMapAnnotation, "value").value as Int,
mask = getAnnotationValue(intMapAnnotation, "mask").value as Int,
annotation = intMapAnnotation
)
}.sortedBy { it.value }
}
/** Check that int mapping is valid and consistent */
private fun validateIntMapping(element: Element, intMapping: List<IntMap>): Boolean {
if (intMapping.isEmpty()) {
return true // Return early for the common case of no int mapping
}
var result = true
val isEnum = intMapping.all { it.mask == 0 }
// Check for duplicate names for both flags and enums
val duplicateNames = intMapping.groupBy { it.name }.values.filter { it.size > 1 }
duplicateNames.flatten().forEach { intMap ->
printError(
"Duplicate int ${if (isEnum) "enum" else "flag"} entry name: \"${intMap.name}\"",
element,
intMap.annotation,
intMap.annotation?.let { getAnnotationValue(it, "name") }
)
}
if (duplicateNames.isNotEmpty()) {
result = false
}
if (isEnum) {
// Check for duplicate enum values
val duplicateValues = intMapping.groupBy { it.value }.values.filter { it.size > 1 }
duplicateValues.forEach { group ->
group.forEach { intMap ->
val others = (group - intMap).joinToString { "\"${it.name}\"" }
printError(
"Int enum value ${intMap.value} is duplicated on entries $others",
element,
intMap.annotation,
intMap.annotation?.let { getAnnotationValue(it, "value") }
)
}
}
if (duplicateValues.isNotEmpty()) {
result = false
}
} else {
// Check for invalid flags, with masks that obscure part of the value. Note that a mask
// of 0 is a special case which implies that the mask is equal to the value as in enums.
intMapping.forEach { intMap ->
if (intMap.mask and intMap.value != intMap.value && intMap.mask != 0) {
printError(
"Int flag mask 0x${intMap.mask.toString(16)} does not reveal value " +
"0x${intMap.value.toString(16)}",
element,
intMap.annotation
)
result = false
}
}
// Check for duplicate flags
val duplicatePairs = intMapping
.groupBy { Pair(if (it.mask != 0) it.mask else it.value, it.value) }
.values
.filter { it.size > 1 }
duplicatePairs.forEach { group ->
group.forEach { intMap ->
val others = (group - intMap).joinToString { "\"${it.name}\"" }
val mask = if (intMap.mask != 0) intMap.mask else intMap.value
printError(
"Int flag mask 0x${mask.toString(16)} and value " +
"0x${intMap.value.toString(16)} is duplicated on entries $others",
element,
intMap.annotation
)
}
}
if (duplicatePairs.isNotEmpty()) {
result = false
}
}
return result
}
/** Map the getter's annotations and return type to the internal attribute type. */
private fun inferAttributeType(
getter: ExecutableElement,
intMapping: List<IntMap>
): AttributeType {
return when (getter.returnType.kind) {
TypeKind.BOOLEAN -> AttributeType.BOOLEAN
TypeKind.BYTE -> AttributeType.BYTE
TypeKind.CHAR -> AttributeType.CHAR
TypeKind.DOUBLE -> AttributeType.DOUBLE
TypeKind.FLOAT -> AttributeType.FLOAT
TypeKind.SHORT -> AttributeType.SHORT
TypeKind.INT -> when {
getter.isAnnotationPresent(COLOR_INT) -> AttributeType.COLOR
getter.isAnnotationPresent(GRAVITY_INT) -> AttributeType.GRAVITY
getter.hasResourceIdAnnotation() -> AttributeType.RESOURCE_ID
intMapping.any { it.mask != 0 } -> AttributeType.INT_FLAG
intMapping.isNotEmpty() -> AttributeType.INT_ENUM
else -> AttributeType.INT
}
TypeKind.LONG ->
if (getter.isAnnotationPresent(COLOR_LONG)) {
AttributeType.COLOR
} else {
AttributeType.LONG
}
TypeKind.DECLARED, TypeKind.ARRAY ->
if (getter.returnType.isAssignableTo(COLOR)) {
AttributeType.COLOR
} else {
AttributeType.OBJECT
}
else -> throw IllegalArgumentException("Unexpected attribute type")
}
}
/** Determines shadowed attributes based on interfaces present on the view. */
private fun inferShadowedAttributes(viewType: TypeElement): List<ShadowedAttribute>? {
if (!viewType.asType().isAssignableTo(VIEW)) {
printError(
"@AppCompatShadowedAttributes must be on a subclass of android.view.View",
viewType,
viewType.getAnnotationMirror(APP_COMPAT_SHADOWED_ATTRIBUTES)
)
return null
}
if (!getPackage(viewType).qualifiedName.startsWith("androidx.appcompat.")) {
printError(
"@AppCompatShadowedAttributes is only supported in the androidx.appcompat package",
viewType,
viewType.getAnnotationMirror(APP_COMPAT_SHADOWED_ATTRIBUTES)
)
return null
}
val attributes = viewType.interfaces.flatMap {
APP_COMPAT_INTERFACE_MAP[it.toString()].orEmpty()
}
if (attributes.isEmpty()) {
printError(
"@AppCompatShadowedAttributes is present on this view, but it does not implement " +
"any interfaces that indicate it has shadowed attributes.",
viewType,
viewType.getAnnotationMirror(APP_COMPAT_SHADOWED_ATTRIBUTES)
)
return null
}
return attributes
}
/** Check if an R.java file exists for [namespace] and that it contains attribute [name] */
private fun isAttributeInRFile(namespace: String, name: String): Boolean {
return processingEnv.elementUtils.getTypeElement("$namespace.R")
?.enclosedElements?.find { it.simpleName.contentEquals("attr") }
?.enclosedElements?.find { it.simpleName.contentEquals(name) } != null
}
private fun Element.hasResourceIdAnnotation(): Boolean {
return this.annotationMirrors.any {
asType(it.annotationType.asElement()).qualifiedName matches RESOURCE_ID_ANNOTATION
}
}
private fun TypeMirror.isAssignableTo(typeName: String): Boolean {
val assignableType = requireNotNull(processingEnv.elementUtils.getTypeElement(typeName)) {
"Expected $typeName to exist"
}
return processingEnv.typeUtils.isAssignable(this, assignableType.asType())
}
/** Convenience wrapper for [javax.annotation.processing.Messager.printMessage]. */
private fun printError(
message: String,
element: Element? = null,
annotation: AnnotationMirror? = null,
value: AnnotationValue? = null
) {
processingEnv.messager.printMessage(
Diagnostic.Kind.ERROR,
message,
element,
annotation,
value
)
}
/** Find an annotation mirror by its qualified name */
private fun Element.getAnnotationMirror(qualifiedName: String): AnnotationMirror? {
return this.annotationMirrors.firstOrNull { annotation ->
asType(annotation.annotationType.asElement())
.qualifiedName.contentEquals(qualifiedName)
}
}
/** True if the supplied annotation name is present on the element */
private fun Element.isAnnotationPresent(qualifiedName: String): Boolean {
return getAnnotationMirror(qualifiedName) != null
}
private companion object {
/** Regex for validating and parsing attribute name and namespace. */
val ATTRIBUTE_VALUE = """(\w+(?:\.\w+)*):(\w+)""".toRegex()
/** Regex for matching resource ID annotations. */
val RESOURCE_ID_ANNOTATION = """androidx?\.annotation\.[A-Z]\w+Res""".toRegex()
/** Fully qualified name of the `Attribute` annotation */
const val ATTRIBUTE = "androidx.resourceinspection.annotation.Attribute"
/** Fully qualified name of the `AppCompatShadowedAttributes` annotation */
const val APP_COMPAT_SHADOWED_ATTRIBUTES =
"androidx.resourceinspection.annotation.AppCompatShadowedAttributes"
/** Fully qualified name of the platform's `Color` class */
const val COLOR = "android.graphics.Color"
/** Fully qualified name of `ColorInt` */
const val COLOR_INT = "androidx.annotation.ColorInt"
/** Fully qualified name of `ColorLong` */
const val COLOR_LONG = "androidx.annotation.ColorLong"
/** Fully qualified name of `GravityInt` */
const val GRAVITY_INT = "androidx.annotation.GravityInt"
/** Fully qualified name of the platform's View class */
const val VIEW = "android.view.View"
/** Fully qualified names of the view inspector classes introduced in API 29 */
val VIEW_INSPECTOR_CLASSES = listOf(
"android.view.inspector.InspectionCompanion",
"android.view.inspector.PropertyReader",
"android.view.inspector.PropertyMapper"
)
/**
* Map of compat interface names in `androidx.core` to the AppCompat attributes they
* shadow. These virtual attributes are added to the inspection companion for views within
* AppCompat with the `@AppCompatShadowedAttributes` annotation.
*
* As you can tell, this is brittle. The good news is these are established platform APIs
* from API <= 29 (the minimum for app inspection) and are unlikely to change in the
* future. If you update this list, please update the documentation comment in
* [androidx.resourceinspection.annotation.AppCompatShadowedAttributes] as well.
*/
val APP_COMPAT_INTERFACE_MAP: Map<String, List<ShadowedAttribute>> = mapOf(
"androidx.core.view.TintableBackgroundView" to listOf(
ShadowedAttribute("backgroundTint", "getBackgroundTintList()"),
ShadowedAttribute("backgroundTintMode", "getBackgroundTintMode()")
),
"androidx.core.widget.AutoSizeableTextView" to listOf(
ShadowedAttribute(
"autoSizeTextType",
"getAutoSizeTextType()",
AttributeType.INT_ENUM,
listOf(
IntMap("none", 0 /* TextView.AUTO_SIZE_TEXT_TYPE_NONE */),
IntMap("uniform", 1 /* TextView.AUTO_SIZE_TEXT_TYPE_UNIFORM */),
)
),
ShadowedAttribute(
"autoSizeStepGranularity", "getAutoSizeStepGranularity()", AttributeType.INT
),
ShadowedAttribute(
"autoSizeMinTextSize", "getAutoSizeMinTextSize()", AttributeType.INT
),
ShadowedAttribute(
"autoSizeMaxTextSize", "getAutoSizeMaxTextSize()", AttributeType.INT
)
),
"androidx.core.widget.TintableCheckedTextView" to listOf(
ShadowedAttribute("checkMarkTint", "getCheckMarkTintList()"),
ShadowedAttribute("checkMarkTintMode", "getCheckMarkTintMode()")
),
"androidx.core.widget.TintableCompoundButton" to listOf(
ShadowedAttribute("buttonTint", "getButtonTintList()"),
ShadowedAttribute("buttonTintMode", "getButtonTintMode()")
),
"androidx.core.widget.TintableCompoundDrawablesView" to listOf(
ShadowedAttribute("drawableTint", "getCompoundDrawableTintList()"),
ShadowedAttribute("drawableTintMode", "getCompoundDrawableTintMode()")
),
"androidx.core.widget.TintableImageSourceView" to listOf(
ShadowedAttribute("tint", "getImageTintList()"),
ShadowedAttribute("tintMode", "getImageTintMode()"),
)
)
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/changeSignature/RemoveParameterKeepOtherCommentsAfter.kt | 13 | 152 | data class <caret>VertexAttribute(
/**
* The number of components this attribute has.
**/
val numComponents: Int
) {} | apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/increaseVisibility/privateSetterToInternal.kt | 7 | 316 | // "Make '<set-attribute>' internal" "true"
// ACTION: Converts the assignment statement to an expression
// ACTION: Make '<set-attribute>' internal
// ACTION: Make '<set-attribute>' public
class Demo {
var attribute = "a"
private set
}
fun main() {
val c = Demo()
<caret>c.attribute = "test"
} | apache-2.0 |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/quickfix/suspiciousCollectionReassignment/replaceWithFilter/plusEq.kt | 4 | 383 | // "Replace with filter" "false"
// TOOL: org.jetbrains.kotlin.idea.inspections.SuspiciousCollectionReassignmentInspection
// ACTION: Change type to mutable
// ACTION: Join with initializer
// ACTION: Replace overloaded operator with function call
// ACTION: Replace with ordinary assignment
// WITH_RUNTIME
fun test() {
var list = listOf(1, 2, 3)
list +=<caret> listOf (4)
} | apache-2.0 |
alt236/Bluetooth-LE-Library---Android | sample_app/src/main/java/uk/co/alt236/btlescan/ui/details/recyclerview/holder/IBeaconHolder.kt | 1 | 854 | package uk.co.alt236.btlescan.ui.details.recyclerview.holder
import android.view.View
import android.widget.TextView
import uk.co.alt236.btlescan.R
import uk.co.alt236.btlescan.ui.common.recyclerview.BaseViewHolder
import uk.co.alt236.btlescan.ui.details.recyclerview.model.IBeaconItem
class IBeaconHolder(itemView: View) : BaseViewHolder<IBeaconItem>(itemView) {
val companyId: TextView = itemView.findViewById<View>(R.id.companyId) as TextView
val advert: TextView = itemView.findViewById<View>(R.id.advertisement) as TextView
val uuid: TextView = itemView.findViewById<View>(R.id.uuid) as TextView
val major: TextView = itemView.findViewById<View>(R.id.major) as TextView
val minor: TextView = itemView.findViewById<View>(R.id.minor) as TextView
val txPower: TextView = itemView.findViewById<View>(R.id.txpower) as TextView
} | apache-2.0 |
siosio/intellij-community | platform/lang-api/src/com/intellij/execution/target/TargetEnvironmentConfiguration.kt | 3 | 2653 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.target
import com.intellij.execution.ExecutionBundle
import com.intellij.execution.configurations.RuntimeConfigurationException
import com.intellij.execution.configurations.RuntimeConfigurationWarning
import com.intellij.execution.target.ContributedConfigurationBase.Companion.getTypeImpl
import com.intellij.openapi.components.BaseState
import com.intellij.openapi.project.Project
import java.util.*
/**
* Base class for configuration instances contributed by the ["com.intellij.executionTargetType"][TargetEnvironmentType.EXTENSION_NAME] extension point.
*
* To be useful, target configuration should normally include at least one language runtime configuration, either introspected
* or explicitly edited by the user.
*
* All available target configurations can be retrieved via [com.intellij.execution.target.TargetEnvironmentsManager]
*/
abstract class TargetEnvironmentConfiguration(typeId: String) : ContributedConfigurationBase(typeId, TargetEnvironmentType.EXTENSION_NAME) {
/**
* Allows implementing links to the configuration. F.e. the link for the project default target.
*
* Note. Some initializations with generated UUID are excessive because they will be overridden during the deserialization.
*/
var uuid: String = UUID.randomUUID().toString()
internal set
val runtimes = ContributedConfigurationsList(LanguageRuntimeType.EXTENSION_NAME)
fun addLanguageRuntime(runtime: LanguageRuntimeConfiguration) = runtimes.addConfig(runtime)
fun removeLanguageRuntime(runtime: LanguageRuntimeConfiguration) = runtimes.removeConfig(runtime)
fun createEnvironmentRequest(project: Project): TargetEnvironmentRequest = getTargetType().createEnvironmentRequest(project, this)
abstract var projectRootOnTarget: String
/**
* Validates this configuration. By default delegates validation to each of the attached language runtimes.
* Subclasses may override.
*/
@Throws(RuntimeConfigurationException::class)
open fun validateConfiguration() {
with(runtimes.resolvedConfigs()) {
if (isEmpty()) {
throw RuntimeConfigurationWarning(
ExecutionBundle.message("TargetEnvironmentConfiguration.error.language.runtime.not.configured"))
}
forEach {
it.validateConfiguration()
}
}
}
abstract class TargetBaseState : BaseState() {
var uuid by string()
}
}
fun <C : TargetEnvironmentConfiguration, T : TargetEnvironmentType<C>> C.getTargetType(): T = this.getTypeImpl() | apache-2.0 |
siosio/intellij-community | platform/util/ui/src/com/intellij/ui/svg/SvgTranscoder.kt | 1 | 12972 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:Suppress("UndesirableClassUsage")
package com.intellij.ui.svg
import com.intellij.openapi.diagnostic.Logger
import com.intellij.util.ImageLoader
import org.apache.batik.anim.dom.SVGOMDocument
import org.apache.batik.bridge.*
import org.apache.batik.bridge.svg12.SVG12BridgeContext
import org.apache.batik.ext.awt.RenderingHintsKeyExt
import org.apache.batik.gvt.CanvasGraphicsNode
import org.apache.batik.gvt.CompositeGraphicsNode
import org.apache.batik.gvt.GraphicsNode
import org.apache.batik.transcoder.TranscoderException
import org.apache.batik.util.ParsedURL
import org.apache.batik.util.SVGConstants
import org.apache.batik.util.SVGFeatureStrings
import org.jetbrains.annotations.ApiStatus
import org.w3c.dom.Document
import org.w3c.dom.Element
import org.w3c.dom.svg.SVGAElement
import org.w3c.dom.svg.SVGDocument
import java.awt.*
import java.awt.geom.AffineTransform
import java.awt.image.BufferedImage
import java.lang.ref.WeakReference
import kotlin.math.max
import kotlin.math.min
private fun logger() = Logger.getInstance(SvgTranscoder::class.java)
private val identityTransform = AffineTransform()
private val supportedFeatures = HashSet<String>()
@ApiStatus.Internal
class SvgTranscoder private constructor(private var width: Float, private var height: Float) : UserAgent {
companion object {
// An SVG tag custom attribute, optional for @2x SVG icons.
// When provided and is set to "true" the document size should be treated as double-scaled of the base size.
// See https://youtrack.jetbrains.com/issue/IDEA-267073
const val DATA_SCALED_ATTR = "data-scaled"
init {
SVGFeatureStrings.addSupportedFeatureStrings(supportedFeatures)
}
@JvmStatic
val iconMaxSize: Float by lazy {
var maxSize = Integer.MAX_VALUE.toFloat()
if (!GraphicsEnvironment.isHeadless()) {
val device = GraphicsEnvironment.getLocalGraphicsEnvironment().defaultScreenDevice
val bounds = device.defaultConfiguration.bounds
val tx = device.defaultConfiguration.defaultTransform
maxSize = max(bounds.width * tx.scaleX, bounds.height * tx.scaleY).toInt().toFloat()
}
maxSize
}
@JvmStatic
fun getDocumentSize(scale: Float, document: Document): ImageLoader.Dimension2DDouble {
val transcoder = SvgTranscoder(16f, 16f)
val bridgeContext = if ((document as SVGOMDocument).isSVG12) {
SVG12BridgeContext(transcoder)
}
else {
BridgeContext(transcoder)
}
GVTBuilder().build(bridgeContext, document)
val size = bridgeContext.documentSize
return ImageLoader.Dimension2DDouble(size.width * scale, size.height * scale)
}
@Throws(TranscoderException::class)
@JvmStatic
@JvmOverloads
fun createImage(scale: Float,
document: Document,
outDimensions: ImageLoader.Dimension2DDouble? /*OUT*/,
overriddenWidth: Float = -1f,
overriddenHeight: Float = -1f): BufferedImage {
val transcoder = SvgTranscoder(if (overriddenWidth == -1f) 16f else overriddenWidth,
if (overriddenHeight == -1f) 16f else overriddenHeight)
val iconMaxSize = iconMaxSize
val bridgeContext = if ((document as SVGOMDocument).isSVG12) {
SVG12BridgeContext(transcoder)
}
else {
BridgeContext(transcoder)
}
try {
// build the GVT tree - it will set bridgeContext.documentSize
val gvtRoot = GVTBuilder().build(bridgeContext, document)!!
// get the 'width' and 'height' attributes of the SVG document
val docWidth = bridgeContext.documentSize.width.toFloat()
val docHeight = bridgeContext.documentSize.height.toFloat()
var normalizingScale = 1f
if ((document.url?.contains("@2x") == true) and
document.rootElement?.attributes?.getNamedItem(DATA_SCALED_ATTR)?.nodeValue?.toLowerCase().equals("true"))
{
normalizingScale = 2f
}
val imageScale = scale / normalizingScale
transcoder.setImageSize(docWidth * imageScale, docHeight * imageScale, overriddenWidth, overriddenHeight, iconMaxSize)
val transform = computeTransform(document, gvtRoot, bridgeContext, docWidth, docHeight, transcoder.width, transcoder.height)
transcoder.currentTransform = transform
val image = render((transcoder.width + 0.5f).toInt(), (transcoder.height + 0.5f).toInt(), transform, gvtRoot)
// Take into account the image size rounding and correct the original user size in order to compensate the inaccuracy.
val effectiveUserWidth = image.width / scale;
val effectiveUserHeight = image.height / scale;
// outDimensions should contain the base size
outDimensions?.setSize(effectiveUserWidth.toDouble() / normalizingScale, effectiveUserHeight.toDouble() / normalizingScale)
return image
}
catch (e: TranscoderException) {
throw e
}
catch (e: Exception) {
throw TranscoderException(e)
}
finally {
bridgeContext.dispose()
}
}
}
private var currentTransform: AffineTransform? = null
private fun setImageSize(docWidth: Float, docHeight: Float, overriddenWidth: Float, overriddenHeight: Float, iconMaxSize: Float) {
if (overriddenWidth > 0 && overriddenHeight > 0) {
width = overriddenWidth
height = overriddenHeight
}
else if (overriddenHeight > 0) {
width = docWidth * overriddenHeight / docHeight
height = overriddenHeight
}
else if (overriddenWidth > 0) {
width = overriddenWidth
height = docHeight * overriddenWidth / docWidth
}
else {
width = docWidth
height = docHeight
}
// limit image size according to the maximum size hints
if (iconMaxSize > 0 && height > iconMaxSize) {
width = docWidth * iconMaxSize / docHeight
height = iconMaxSize
}
if (iconMaxSize > 0 && width > iconMaxSize) {
width = iconMaxSize
height = docHeight * iconMaxSize / docWidth
}
}
override fun getMedia() = "screen"
override fun getBrokenLinkDocument(e: Element, url: String, message: String): SVGDocument {
logger().warn("$url $message")
val fallbackIcon = "<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"16\" height=\"16\" viewBox=\"0 0 16 16\">\n" +
" <rect x=\"1\" y=\"1\" width=\"14\" height=\"14\" fill=\"none\" stroke=\"red\" stroke-width=\"2\"/>\n" +
" <line x1=\"1\" y1=\"1\" x2=\"15\" y2=\"15\" stroke=\"red\" stroke-width=\"2\"/>\n" +
" <line x1=\"1\" y1=\"15\" x2=\"15\" y2=\"1\" stroke=\"red\" stroke-width=\"2\"/>\n" +
"</svg>\n"
return createSvgDocument(null, fallbackIcon.byteInputStream()) as SVGDocument
}
override fun getTransform() = currentTransform!!
override fun setTransform(value: AffineTransform) = throw IllegalStateException()
override fun getViewportSize() = Dimension(width.toInt(), height.toInt())
override fun displayError(e: Exception) {
logger().debug(e)
}
override fun displayMessage(message: String) {
logger().debug(message)
}
override fun getScriptSecurity(scriptType: String?, scriptUrl: ParsedURL?, documentUrl: ParsedURL?) = NoLoadScriptSecurity(scriptType)
override fun getExternalResourceSecurity(resourceUrl: ParsedURL, documentUrl: ParsedURL?): ExternalResourceSecurity {
return ExternalResourceSecurity { checkLoadExternalResource(resourceUrl, documentUrl) }
}
override fun showAlert(message: String?) {}
override fun showPrompt(message: String?) = null
override fun showPrompt(message: String?, defaultValue: String?) = null
override fun showConfirm(message: String?) = false
override fun getPixelUnitToMillimeter(): Float = 0.26458333333333333333333333333333f // 96dpi
override fun getPixelToMM() = pixelUnitToMillimeter
override fun getDefaultFontFamily() = "Arial, Helvetica, sans-serif"
// 9pt (72pt = 1in)
override fun getMediumFontSize(): Float = 9f * 25.4f / (72f * pixelUnitToMillimeter)
override fun getLighterFontWeight(f: Float) = getStandardLighterFontWeight(f)
override fun getBolderFontWeight(f: Float) = getStandardBolderFontWeight(f)
override fun getLanguages() = "en"
override fun getAlternateStyleSheet() = null
override fun getUserStyleSheetURI() = null
override fun getXMLParserClassName() = null
override fun isXMLParserValidating() = false
override fun getEventDispatcher() = null
override fun openLink(elt: SVGAElement?) {}
override fun setSVGCursor(cursor: Cursor?) {}
override fun setTextSelection(start: Mark?, end: Mark?) {}
override fun deselectAll() {}
override fun getClientAreaLocationOnScreen() = Point()
override fun hasFeature(s: String?) = supportedFeatures.contains(s)
override fun supportExtension(s: String?) = false
override fun registerExtension(ext: BridgeExtension) {
}
override fun handleElement(elt: Element?, data: Any?) {}
override fun checkLoadScript(scriptType: String?, scriptURL: ParsedURL, docURL: ParsedURL?) {
throw SecurityException("NO_EXTERNAL_RESOURCE_ALLOWED")
}
override fun checkLoadExternalResource(resourceUrl: ParsedURL, documentUrl: ParsedURL?) {
// make sure that the archives comes from the same host as the document itself
if (documentUrl == null) {
throw SecurityException("NO_EXTERNAL_RESOURCE_ALLOWED")
}
val docHost = documentUrl.host
val externalResourceHost: String = resourceUrl.host
if (docHost != externalResourceHost && (docHost == null || docHost != externalResourceHost) && "data" != resourceUrl.protocol) {
throw SecurityException("NO_EXTERNAL_RESOURCE_ALLOWED")
}
}
override fun loadDocument(url: String?) {
}
override fun getFontFamilyResolver(): FontFamilyResolver = DefaultFontFamilyResolver.SINGLETON
}
private fun computeTransform(document: SVGOMDocument,
gvtRoot: GraphicsNode,
context: BridgeContext,
docWidth: Float,
docHeight: Float,
width: Float,
height: Float): AffineTransform {
// compute the preserveAspectRatio matrix
val preserveAspectRatioMatrix: AffineTransform
val root = document.rootElement
val viewBox = root.getAttributeNS(null, SVGConstants.SVG_VIEW_BOX_ATTRIBUTE)
if (viewBox != null && viewBox.isNotEmpty()) {
val aspectRatio = root.getAttributeNS(null, SVGConstants.SVG_PRESERVE_ASPECT_RATIO_ATTRIBUTE)
preserveAspectRatioMatrix = ViewBox.getPreserveAspectRatioTransform(root, viewBox, aspectRatio, width, height, context)
}
else {
// no viewBox has been specified, create a scale transform
val scale = min(width / docWidth, height / docHeight)
preserveAspectRatioMatrix = AffineTransform.getScaleInstance(scale.toDouble(), scale.toDouble())
}
val cgn = (gvtRoot as? CompositeGraphicsNode)?.children?.firstOrNull() as? CanvasGraphicsNode
if (cgn == null) {
return preserveAspectRatioMatrix
}
else {
cgn.viewingTransform = preserveAspectRatioMatrix
return AffineTransform()
}
}
private fun render(offScreenWidth: Int, offScreenHeight: Int, usr2dev: AffineTransform, gvtRoot: GraphicsNode): BufferedImage {
val image = BufferedImage(offScreenWidth, offScreenHeight, BufferedImage.TYPE_INT_ARGB)
val g = image.createGraphics()
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR)
g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE)
g.setRenderingHint(RenderingHintsKeyExt.KEY_BUFFERED_IMAGE, WeakReference(image))
g.transform = identityTransform
g.setClip(0, 0, offScreenWidth, offScreenHeight)
g.composite = AlphaComposite.Clear
g.fillRect(0, 0, offScreenWidth, offScreenHeight)
g.composite = AlphaComposite.SrcOver
g.transform(usr2dev)
gvtRoot.paint(g)
g.dispose()
return image
}
private fun getStandardLighterFontWeight(f: Float): Float {
// Round f to nearest 100...
return when (((f + 50) / 100).toInt() * 100) {
100, 200 -> 100f
300 -> 200f
400 -> 300f
500, 600, 700, 800, 900 -> 400f
else -> throw IllegalArgumentException("Bad Font Weight: $f")
}
}
private fun getStandardBolderFontWeight(f: Float): Float {
// Round f to nearest 100...
return when (((f + 50) / 100).toInt() * 100) {
100, 200, 300, 400, 500 -> 600f
600 -> 700f
700 -> 800f
800 -> 900f
900 -> 900f
else -> throw IllegalArgumentException("Bad Font Weight: $f")
}
} | apache-2.0 |
josecefe/Rueda | src/es/um/josecefe/rueda/resolutor/ResolutorV7.kt | 1 | 10745 | /*
* Copyright (c) 2016-2017. Jose Ceferino Ortega Carretero
*
* 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 es.um.josecefe.rueda.resolutor
import es.um.josecefe.rueda.modelo.AsignacionDia
import es.um.josecefe.rueda.modelo.Dia
import es.um.josecefe.rueda.modelo.Horario
import java.util.*
/**
* ResolutorV7
*
*
* Se trata de un resolutor que aplica la tecnica de Ramificación y poda (B&B).
*
* @author josecefe
*/
class ResolutorV7 : ResolutorAcotado() {
override var estrategia = Estrategia.EQUILIBRADO
private val estGlobal = EstadisticasV7()
override fun resolver(horarios: Set<Horario>): Map<Dia, AsignacionDia> {
return resolver(horarios, Integer.MAX_VALUE - 1)
}
override fun resolver(horarios: Set<Horario>, cotaInfCorte: Int): Map<Dia, AsignacionDia> {
if (horarios.isEmpty()) {
return emptyMap()
}
if (ESTADISTICAS) {
estGlobal.inicia()
}
var ultMilisEst: Long = 0 // La ultima vez que se hizo estadística
continuar = true
val contex = ContextoResolucionHeuristico(horarios)
contex.estrategia = estrategia
solucionFinal = emptyMap()
val tamanosNivel = contex.ordenExploracionDias.map { i -> contex.solucionesCandidatas[contex.dias[i]]!!.size }.toIntArray()
val totalPosiblesSoluciones = tamanosNivel.map { i -> i.toDouble() }.fold(1.0) { a, b -> a * b }
val nPosiblesSoluciones = DoubleArray(tamanosNivel.size)
if (ESTADISTICAS) {
if (DEBUG) {
println("Nº de posibles soluciones: " + tamanosNivel.joinToString(separator = " * ") { it.toDouble().toString() } + " = "
+ totalPosiblesSoluciones)
}
var acum = 1.0
for (i in tamanosNivel.indices.reversed()) {
nPosiblesSoluciones[i] = acum
acum *= tamanosNivel[i]
}
estGlobal.totalPosiblesSoluciones = totalPosiblesSoluciones
estGlobal.actualizaProgreso()
if (DEBUG) {
System.out.format("Tiempo inicializar =%s\n", estGlobal.tiempoString)
}
}
// Preparamos el algoritmo
val raiz = Nodo(contex)
var actual = raiz
var mejor = actual
var cotaInferiorCorte = if (cotaInfCorte < Integer.MAX_VALUE) cotaInfCorte + 1 else cotaInfCorte
var lnv: MutableCollection<Nodo>
var opPull: () -> Nodo
contex.pesoCotaInferiorNum = PESO_COTA_INFERIOR_NUM_DEF_INI //Primero buscamos en profundidad
contex.pesoCotaInferiorDen = PESO_COTA_INFERIOR_DEN_DEF_INI //Primero buscamos en profundidad
if (CON_CAMBIO_DE_ESTRATEGIA) {
val pilaNodosVivos = ArrayDeque<Nodo>() // Inicialmente es una cola LIFO (pila)
lnv = pilaNodosVivos
opPull = { pilaNodosVivos.removeLast() } //Para controlar si es pila o cola, inicialmente pila
} else {
val colaNodosVivos = PriorityQueue<Nodo>()
lnv = colaNodosVivos
opPull = { colaNodosVivos.poll() }
}
lnv.add(actual)
// Bucle principal
do {
actual = opPull()
if (ESTADISTICAS && estGlobal.incExpandidos() % CADA_EXPANDIDOS == 0L && System.currentTimeMillis() - ultMilisEst > CADA_MILIS_EST) {
ultMilisEst = System.currentTimeMillis()
estGlobal.fitness = cotaInferiorCorte
estGlobal.actualizaProgreso()
if (DEBUG) {
System.out.format("> LNV=%,d, ", lnv.size)
println(estGlobal)
println("-- Trabajando con $actual")
}
}
if (actual.cotaInferior < cotaInferiorCorte) { //Estrategia de poda: si la cotaInferior >= C no seguimos
if (ESTADISTICAS) {
estGlobal.addGenerados(tamanosNivel[actual.nivel + 1].toDouble())
}
if (actual.nivel + 2 == contex.dias.size) { // Los hijos son terminales
if (ESTADISTICAS) {
estGlobal.addTerminales(tamanosNivel[actual.nivel + 1].toDouble())
}
val mejorHijo = actual.generaHijos().min()
if (mejorHijo!=null && mejorHijo < mejor) {
if (mejor === raiz) {
// Cambiamos los pesos
contex.pesoCotaInferiorNum = PESO_COTA_INFERIOR_NUM_DEF_FIN //Después buscamos más equilibrado
contex.pesoCotaInferiorDen = PESO_COTA_INFERIOR_DEN_DEF_FIN //Después buscamos más equilibrado
lnv.forEach{ it.calculaCosteEstimado() }// Hay que forzar el calculo de nuevo de los costes de los nodos
val colaNodosVivos: PriorityQueue<Nodo> = PriorityQueue(lnv.size)
colaNodosVivos.addAll(lnv)
if (DEBUG) {
println("---- ACTUALIZANDO LA LNV POR CAMBIO DE PESOS")
}
opPull = { colaNodosVivos.poll() }
lnv = colaNodosVivos
}
mejor = mejorHijo
if (DEBUG) {
System.out.format("$$$$ A partir del padre=%s\n -> mejoramos con el hijo=%s\n", actual, mejor)
}
if (mejor.costeEstimado < cotaInferiorCorte) {
if (DEBUG) {
System.out.format("** Nuevo C: Anterior=%,d, Nuevo=%,d\n", cotaInferiorCorte, mejor.costeEstimado)
}
cotaInferiorCorte = mejor.costeEstimado
val fC = cotaInferiorCorte
// Limpiamos la lista de nodos vivos de los que no cumplan...
val antes = lnv.size
if (ESTADISTICAS) {
estGlobal.addDescartados(lnv.filter { n -> n.cotaInferior >= fC }.map { n -> nPosiblesSoluciones[n.nivel] }.sum())
estGlobal.fitness = cotaInferiorCorte
estGlobal.actualizaProgreso()
}
val removeIf = lnv.removeAll { n -> n.cotaInferior >= fC }
if (ESTADISTICAS && DEBUG && removeIf) {
System.out.format("** Hemos eliminado %,d nodos de la LNV\n", antes - lnv.size)
}
}
}
} else { // Es un nodo intermedio
val corte = cotaInferiorCorte
val lNF = actual.generaHijos().filter { n -> n.cotaInferior < corte }.toMutableList()
val menorCotaSuperior = lNF.map{ it.cotaSuperior }.min()
if (menorCotaSuperior!=null && menorCotaSuperior < cotaInferiorCorte) { // Mejora de C
if (DEBUG) {
System.out.format("** Nuevo C: Anterior=%,d, Nuevo=%,d\n", cotaInferiorCorte, menorCotaSuperior)
}
cotaInferiorCorte = menorCotaSuperior //Actualizamos C
val fC = cotaInferiorCorte
lNF.removeAll { n -> n.cotaInferior >= fC } //Recalculamos lNF
// Limpiamos la LNV
val antes = lnv.size
if (ESTADISTICAS) {
estGlobal.addDescartados(lnv.filter { n -> n.cotaInferior >= fC }.map { n -> nPosiblesSoluciones[n.nivel] }.sum())
estGlobal.fitness = cotaInferiorCorte
estGlobal.actualizaProgreso()
}
val removeIf = lnv.removeAll { n -> n.cotaInferior >= fC }
if (ESTADISTICAS && DEBUG && removeIf) {
System.out.format("## Hemos eliminado %,d nodos de la LNV\n", antes - lnv.size)
}
}
if (ESTADISTICAS) {
estGlobal.addDescartados((tamanosNivel[actual.nivel + 1] - lNF.size) * nPosiblesSoluciones[actual.nivel + 1])
}
lnv.addAll(lNF)
}
} else if (ESTADISTICAS) {
estGlobal.addDescartados(nPosiblesSoluciones[actual.nivel])
}
} while (!lnv.isEmpty() && continuar)
//Estadisticas finales
if (ESTADISTICAS) {
estGlobal.fitness = cotaInferiorCorte
estGlobal.actualizaProgreso()
if (DEBUG) {
println("====================")
println("Estadísticas finales")
println("====================")
println(estGlobal)
println("Solución final=$mejor")
println("-----------------------------------------------")
}
}
// Construimos la solución final
solucionFinal = if (mejor.costeEstimado < cotaInfCorte) {
mejor.solucion
} else {
emptyMap()
}
return solucionFinal
}
override var solucionFinal: Map<Dia, AsignacionDia> = emptyMap()
private set
override val estadisticas: Estadisticas
get() = estGlobal
companion object {
private const val DEBUG = false
//private const val PARALELO = false
private const val ESTADISTICAS = true
private const val CADA_EXPANDIDOS = 1000
private const val CADA_MILIS_EST = 1000
private const val CON_CAMBIO_DE_ESTRATEGIA = false
private const val PESO_COTA_INFERIOR_NUM_DEF_INI = 1
private const val PESO_COTA_INFERIOR_DEN_DEF_INI = 8
private const val PESO_COTA_INFERIOR_NUM_DEF_FIN = 1
private const val PESO_COTA_INFERIOR_DEN_DEF_FIN = 2
}
}
| gpl-3.0 |
K0zka/kerub | src/main/kotlin/com/github/kerubistan/kerub/model/AuditEventType.kt | 2 | 98 | package com.github.kerubistan.kerub.model
enum class AuditEventType {
Insert,
Update,
Delete
} | apache-2.0 |
PaleoCrafter/VanillaImmersion | src/main/kotlin/de/mineformers/vanillaimmersion/client/renderer/AnvilRenderer.kt | 1 | 5355 | package de.mineformers.vanillaimmersion.client.renderer
import de.mineformers.vanillaimmersion.block.Anvil
import de.mineformers.vanillaimmersion.client.gui.AnvilTextGui
import de.mineformers.vanillaimmersion.tileentity.AnvilLogic
import de.mineformers.vanillaimmersion.tileentity.AnvilLogic.Companion.Slot
import net.minecraft.client.Minecraft
import net.minecraft.client.renderer.GlStateManager.color
import net.minecraft.client.renderer.GlStateManager.disableRescaleNormal
import net.minecraft.client.renderer.GlStateManager.enableRescaleNormal
import net.minecraft.client.renderer.GlStateManager.popMatrix
import net.minecraft.client.renderer.GlStateManager.pushMatrix
import net.minecraft.client.renderer.GlStateManager.rotate
import net.minecraft.client.renderer.GlStateManager.scale
import net.minecraft.client.renderer.GlStateManager.translate
import net.minecraft.client.renderer.OpenGlHelper
import net.minecraft.client.renderer.RenderHelper
import net.minecraft.client.renderer.block.model.ItemCameraTransforms.TransformType.FIXED
import net.minecraft.client.renderer.texture.TextureMap
import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer
import net.minecraft.client.resources.I18n
import net.minecraft.item.ItemBlock
import org.apache.commons.lang3.StringUtils
/**
* Renders the items on top of an anvil.
*/
open class AnvilRenderer : TileEntitySpecialRenderer<AnvilLogic>() {
// TODO: Maybe switch to FastTESR?
override fun render(te: AnvilLogic, x: Double, y: Double, z: Double,
partialTicks: Float, destroyStage: Int, partialAlpha: Float) {
if (te.blockState.block !is Anvil)
return
pushMatrix()
color(1f, 1f, 1f, 1f)
// Use the brightness of the block above the anvil for lighting
val light = te.world.getCombinedLight(te.pos.add(0, 1, 0), 0)
val bX = light % 65536
val bY = light / 65536
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, bX.toFloat(), bY.toFloat())
// Translate to the anvil's center and rotate according to its orientation
translate(x + 0.5, y + 1.0, z + 0.5)
rotate(180f - te.facing.horizontalAngle, 0f, 1f, 0f)
enableRescaleNormal()
RenderHelper.enableStandardItemLighting()
Minecraft.getMinecraft().textureManager.bindTexture(TextureMap.LOCATION_BLOCKS_TEXTURE)
// Render both inputs
// TODO: Achieve this with baked models
renderItem(te, Slot.INPUT_OBJECT, .0, .33)
renderItem(te, Slot.INPUT_MATERIAL, .0, -.03)
// Render the hammer, if present
val hammer = te[Slot.HAMMER]
if (!hammer.isEmpty) {
pushMatrix()
// Magic numbers, but this appears to be the perfect offset
translate(.0, .05, -.32)
rotate(-90f, 0f, 1f, 0f)
rotate(85f, 1f, 0f, 0f)
rotate(6f, 0f, 0f, 1f)
scale(0.5f, 0.5f, 0.5f)
Minecraft.getMinecraft().renderItem.renderItem(hammer, FIXED)
popMatrix()
}
RenderHelper.disableStandardItemLighting()
disableRescaleNormal()
// Render the text on the front of the anvil
translate(0f, -0.05f, 0f)
rotate(90f, 0f, 1f, 0f)
translate(0f, 0f, 0.32f)
scale(0.00625f, -0.00625f, 0.00625f)
val font = Minecraft.getMinecraft().fontRenderer
val activeScreen = Minecraft.getMinecraft().currentScreen
if (StringUtils.isNotEmpty(te.itemName)) {
val label = I18n.format("vimmersion.anvil.itemName")
font.drawString(label, -font.getStringWidth(label) / 2, 25 - font.FONT_HEIGHT - 2, 0xFFFFFF)
if (activeScreen is AnvilTextGui && activeScreen.anvil == te) {
activeScreen.nameField.x = -font.getStringWidth(te.itemName) / 2
activeScreen.nameField.y = 25
activeScreen.nameField.drawTextBox()
} else {
font.drawString(te.itemName, -font.getStringWidth(te.itemName) / 2, 25, 0xFFFFFF)
}
} else if (activeScreen is AnvilTextGui && activeScreen.anvil == te) {
val label = I18n.format("vimmersion.anvil.itemName")
font.drawString(label, -font.getStringWidth(label) / 2, 25 - font.FONT_HEIGHT - 2, 0xFFFFFF)
activeScreen.nameField.x = -font.getStringWidth(activeScreen.nameField.text) / 2
activeScreen.nameField.y = 25
activeScreen.nameField.drawTextBox()
}
popMatrix()
}
/**
* Renders an item on top of the anvil.
*/
private fun renderItem(te: AnvilLogic, slot: Slot, x: Double, z: Double) {
pushMatrix()
// Magic numbers, but this appears to be the perfect offset
translate(x, 0.015, z)
rotate(-90f, 0f, 1f, 0f)
val stack = te[slot]
// Most blocks use a block model which requires special treatment
if (stack.item is ItemBlock) {
translate(0.0, 0.135, 0.0)
scale(2f, 2f, 2f)
} else {
// Rotate items to lie down flat on the anvil
rotate(90f, 1f, 0f, 0f)
rotate(180f, 0f, 1f, 0f)
}
scale(0.3, 0.3, 0.3)
Minecraft.getMinecraft().renderItem.renderItem(stack, FIXED)
popMatrix()
}
} | mit |
zhiayang/pew | core/src/main/kotlin/Utilities/DelayComponent.kt | 1 | 617 | // Copyright (c) 2014 Orion Industries, [email protected]
// Licensed under the Apache License version 2.0
package Utilities
public data class DelayComponent(public val delay: Float)
{
private var running: Float = this.delay
public var elapsed: Boolean = false
private set
get()
{
if (this.$elapsed)
{
this.$elapsed = false
return true
}
else
return false
}
public fun tick(delta: Float)
{
this.running += delta
if (this.running >= this.delay)
{
this.running = 0.0f
this.elapsed = true
}
}
public fun reset()
{
this.running = 0f
this.elapsed = false
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/simplifyBooleanWithConstants/positiveZeroNegativeZero1.kt | 12 | 62 | // IS_APPLICABLE: false
fun foo() {
-0.0 <caret>== +0.0
} | apache-2.0 |
smmribeiro/intellij-community | platform/vcs-impl/src/com/intellij/vcs/commit/NullCommitWorkflowHandler.kt | 13 | 1045 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.vcs.commit
import com.intellij.openapi.Disposable
import com.intellij.openapi.vcs.changes.CommitExecutor
object NullCommitWorkflowHandler : CommitWorkflowHandler {
override val amendCommitHandler: AmendCommitHandler = NullAmendCommitHandler
override fun getExecutor(executorId: String): CommitExecutor? = null
override fun isExecutorEnabled(executor: CommitExecutor): Boolean = false
override fun execute(executor: CommitExecutor) = Unit
}
@Suppress("UNUSED_PARAMETER")
object NullAmendCommitHandler : AmendCommitHandler {
override var isAmendCommitMode: Boolean
get() = false
set(value) = Unit
override var isAmendCommitModeTogglingEnabled: Boolean
get() = false
set(value) = Unit
override fun isAmendCommitModeSupported(): Boolean = false
override fun addAmendCommitModeListener(listener: AmendCommitModeListener, parent: Disposable) = Unit
} | apache-2.0 |
zielu/GitToolBox | src/main/kotlin/zielu/gittoolbox/completion/gitmoji/GitmojiResBundle.kt | 1 | 510 | package zielu.gittoolbox.completion.gitmoji
import com.intellij.DynamicBundle
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
internal object GitmojiResBundle : DynamicBundle(BUNDLE_NAME) {
fun message(@PropertyKey(resourceBundle = BUNDLE_NAME) key: String, vararg params: Any?): String {
return getMessage(key, *params)
}
fun keySet(): Set<String> {
return resourceBundle.keySet()
}
}
@NonNls
private const val BUNDLE_NAME = "zielu.gittoolbox.gitmoji"
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/multiModuleQuickFix/other/addActualToTopLevelMember/jvm/jvm.kt | 4 | 55 | // "Add 'actual' modifier" "true"
fun <caret>foo() {}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/wordSelection/ValueParametersInLambda2/1.kt | 12 | 98 | fun foo(f: (Int) -> Int) {}
fun test() {
foo { it -> <caret><selection>it</selection> + 1 }
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/simplifiableCall/filterIsNotInstance.kt | 9 | 102 | // WITH_STDLIB
// PROBLEM: none
fun test(list: List<Any>) {
list.<caret>filter { it !is String }
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/test/testData/coroutines/twoDumps.kt | 11 | 377 | package twoDumps
// ATTACH_LIBRARY: maven(org.jetbrains.kotlinx:kotlinx-coroutines-debug:1.3.8)-javaagent
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
suspend fun foo() {
//Breakpoint!
println("")
}
suspend fun bar() {
//Breakpoint!
println("")
}
fun main() = runBlocking<Unit> {
foo()
runBlocking {
bar()
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/refactoring/introduceVariable/InsideOfInitializerAnnotation.kt | 13 | 66 | class C {
@deprecated(<selection>""</selection>)
init {}
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/project-model/src/org/jetbrains/kotlin/idea/projectModel/KotlinCompilation.kt | 3 | 1999 | // 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.projectModel
interface KotlinCompilation : KotlinComponent {
@Deprecated("Use allSourceSets or declaredSourceSets instead", ReplaceWith("declaredSourceSets"))
val sourceSets: Collection<KotlinSourceSet>
get() = declaredSourceSets
/**
* All source sets participated in this compilation, including those available
* via dependsOn.
*/
val allSourceSets: Collection<KotlinSourceSet>
/**
* Only directly declared source sets of this compilation, i.e. those which are included
* into compilations directly.
*
* Usually, those are automatically created source sets for automatically created
* compilations (like jvmMain for JVM compilations) or manually included source sets
* (like 'jvm().compilations["main"].source(mySourceSet)' )
*/
val declaredSourceSets: Collection<KotlinSourceSet>
val output: KotlinCompilationOutput
@Suppress("DEPRECATION_ERROR")
@Deprecated(
"Raw compiler arguments are not available anymore",
ReplaceWith("cachedArgsInfo#currentCompilerArguments or cachedArgsInfo#defaultCompilerArguments"),
level = DeprecationLevel.ERROR
)
val arguments: KotlinCompilationArguments
@Deprecated(
"Raw dependency classpath is not available anymore",
ReplaceWith("cachedArgsInfo#dependencyClasspath"),
level = DeprecationLevel.ERROR
)
val dependencyClasspath: Array<String>
val cachedArgsInfo: CachedArgsInfo<*>
val disambiguationClassifier: String?
val platform: KotlinPlatform
val kotlinTaskProperties: KotlinTaskProperties
val nativeExtensions: KotlinNativeCompilationExtensions?
companion object {
const val MAIN_COMPILATION_NAME = "main"
const val TEST_COMPILATION_NAME = "test"
}
}
| apache-2.0 |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/UnknownSdkStartupChecker.kt | 5 | 2509 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.projectRoots.impl
import com.intellij.ProjectTopics
import com.intellij.openapi.extensions.ExtensionPointListener
import com.intellij.openapi.extensions.PluginDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.roots.ex.ProjectRootManagerEx
import com.intellij.openapi.roots.ui.configuration.UnknownSdkResolver
import com.intellij.openapi.startup.StartupActivity
internal class UnknownSdkStartupChecker : StartupActivity.DumbAware {
override fun runActivity(project: Project) {
checkUnknownSdks(project)
UnknownSdkResolver.EP_NAME.addExtensionPointListener(object: ExtensionPointListener<UnknownSdkResolver> {
override fun extensionAdded(extension: UnknownSdkResolver, pluginDescriptor: PluginDescriptor) {
checkUnknownSdks(project)
}
override fun extensionRemoved(extension: UnknownSdkResolver, pluginDescriptor: PluginDescriptor) {
checkUnknownSdks(project)
}
}, project)
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object: ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
checkUnknownSdks(event.project)
}
})
ProjectRootManagerEx.getInstanceEx(project).addProjectJdkListener {
checkUnknownSdks(project)
}
project.messageBus.connect().subscribe(ProjectJdkTable.JDK_TABLE_TOPIC, object : ProjectJdkTable.Listener {
override fun jdkAdded(jdk: Sdk) {
checkUnknownSdks(project)
}
override fun jdkRemoved(jdk: Sdk) {
checkUnknownSdks(project)
}
override fun jdkNameChanged(jdk: Sdk, previousName: String) {
checkUnknownSdks(project)
}
})
}
private fun checkUnknownSdks(project: Project) {
if (project.isDisposed || project.isDefault) return
//TODO: workaround for tests, right not it can happen that project.earlyDisposable is null with @NotNull annotation
if (project is ProjectEx && kotlin.runCatching { project.earlyDisposable }.isFailure) return
UnknownSdkTracker.getInstance(project).updateUnknownSdks()
}
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/branched/safeAccessToIfThen/let.kt | 9 | 86 | // WITH_STDLIB
fun foo(value: Int?): Int? {
return value<caret>?.let { it + 1 }
} | apache-2.0 |
smmribeiro/intellij-community | platform/platform-impl/src/com/intellij/codeInsight/daemon/impl/HintRenderer.kt | 1 | 12349 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.codeInsight.daemon.impl
import com.intellij.codeInsight.hints.HintWidthAdjustment
import com.intellij.ide.ui.AntialiasingType
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.editor.DefaultLanguageHighlighterColors
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorCustomElementRenderer
import com.intellij.openapi.editor.Inlay
import com.intellij.openapi.editor.colors.EditorColorsManager
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.editor.ex.EditorSettingsExternalizable
import com.intellij.openapi.editor.ex.util.EditorUtil
import com.intellij.openapi.editor.impl.EditorImpl
import com.intellij.openapi.editor.impl.FocusModeModel
import com.intellij.openapi.editor.impl.FontInfo
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.util.Key
import com.intellij.ui.paint.EffectPainter
import com.intellij.util.ui.GraphicsUtil
import com.intellij.util.ui.StartupUiUtil
import org.intellij.lang.annotations.JdkConstants
import java.awt.*
import java.awt.font.FontRenderContext
import javax.swing.UIManager
import kotlin.math.ceil
import kotlin.math.max
import kotlin.math.roundToInt
open class HintRenderer(var text: String?) : EditorCustomElementRenderer {
var widthAdjustment: HintWidthAdjustment? = null
override fun calcWidthInPixels(inlay: Inlay<*>): Int {
return calcWidthInPixels(inlay.editor, text, widthAdjustment, useEditorFont())
}
protected open fun getTextAttributes(editor: Editor): TextAttributes? {
return editor.colorsScheme.getAttributes(DefaultLanguageHighlighterColors.INLINE_PARAMETER_HINT)
}
override fun paint(inlay: Inlay<*>, g: Graphics, r: Rectangle, textAttributes: TextAttributes) {
val editor = inlay.editor
if (editor !is EditorImpl) return
val focusModeRange = editor.focusModeRange
val attributes = if (focusModeRange != null && (inlay.offset <= focusModeRange.startOffset || focusModeRange.endOffset <= inlay.offset)) {
editor.getUserData(FocusModeModel.FOCUS_MODE_ATTRIBUTES) ?: getTextAttributes(editor)
}
else {
getTextAttributes(editor)
}
paintHint(g, editor, r, text, attributes, attributes ?: textAttributes, widthAdjustment, useEditorFont())
}
/**
* @deprecated
* @see calcHintTextWidth
*/
protected fun doCalcWidth(text: String?, fontMetrics: FontMetrics): Int {
return calcHintTextWidth(text, fontMetrics)
}
protected open fun useEditorFont() = useEditorFontFromSettings()
companion object {
@JvmStatic
fun calcWidthInPixels(editor: Editor, text: String?, widthAdjustment: HintWidthAdjustment?): Int {
return calcWidthInPixels(editor, text, widthAdjustment, useEditorFontFromSettings())
}
@JvmStatic
fun calcWidthInPixels(editor: Editor, text: String?, widthAdjustment: HintWidthAdjustment?, useEditorFont: Boolean): Int {
val fontMetrics = getFontMetrics(editor, useEditorFont).metrics
return calcHintTextWidth(text, fontMetrics) + calcWidthAdjustment(text, editor, fontMetrics, widthAdjustment)
}
@JvmStatic
fun paintHint(g: Graphics,
editor: EditorImpl,
r: Rectangle,
text: String?,
attributes: TextAttributes?,
textAttributes: TextAttributes,
widthAdjustment: HintWidthAdjustment?) {
paintHint(g, editor, r, text, attributes, textAttributes, widthAdjustment, useEditorFontFromSettings())
}
@JvmStatic
fun paintHint(g: Graphics,
editor: EditorImpl,
r: Rectangle,
text: String?,
attributes: TextAttributes?,
textAttributes: TextAttributes,
widthAdjustment: HintWidthAdjustment?,
useEditorFont: Boolean) {
val ascent = editor.ascent
val descent = editor.descent
val g2d = g as Graphics2D
if (text != null && attributes != null) {
val fontMetrics = getFontMetrics(editor, useEditorFont)
val gap = if (r.height < fontMetrics.lineHeight + 2) 1 else 2
val backgroundColor = attributes.backgroundColor
if (backgroundColor != null) {
val alpha = if (isInsufficientContrast(attributes, textAttributes)) 1.0f else BACKGROUND_ALPHA
val config = GraphicsUtil.setupAAPainting(g)
GraphicsUtil.paintWithAlpha(g, alpha)
g.setColor(backgroundColor)
g.fillRoundRect(r.x + 2, r.y + gap, r.width - 4, r.height - gap * 2, 8, 8)
config.restore()
}
val foregroundColor = attributes.foregroundColor
if (foregroundColor != null) {
val savedHint = g2d.getRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING)
val savedClip = g.getClip()
g.setColor(foregroundColor)
g.setFont(getFont(editor, useEditorFont))
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, AntialiasingType.getKeyForCurrentScope(false))
g.clipRect(r.x + 3, r.y + 2, r.width - 6, r.height - 4)
val metrics = fontMetrics.metrics
val startX = r.x + 7
val startY = r.y + max(ascent, (r.height + metrics.ascent - metrics.descent) / 2) - 1
val adjustment = calcWidthAdjustment(text, editor, g.fontMetrics, widthAdjustment)
if (adjustment == 0) {
g.drawString(text, startX, startY)
}
else {
val adjustmentPosition = widthAdjustment!!.adjustmentPosition
val firstPart = text.substring(0, adjustmentPosition)
val secondPart = text.substring(adjustmentPosition)
g.drawString(firstPart, startX, startY)
g.drawString(secondPart, startX + g.getFontMetrics().stringWidth(firstPart) + adjustment, startY)
}
g.setClip(savedClip)
g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, savedHint)
}
}
val effectColor = textAttributes.effectColor
val effectType = textAttributes.effectType
if (effectColor != null) {
g.setColor(effectColor)
val xStart = r.x
val xEnd = r.x + r.width
val y = r.y + ascent
val font = editor.getColorsScheme().getFont(EditorFontType.PLAIN)
@Suppress("NON_EXHAUSTIVE_WHEN")
when (effectType) {
EffectType.LINE_UNDERSCORE -> EffectPainter.LINE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font)
EffectType.BOLD_LINE_UNDERSCORE -> EffectPainter.BOLD_LINE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font)
EffectType.STRIKEOUT -> EffectPainter.STRIKE_THROUGH.paint(g2d, xStart, y, xEnd - xStart, editor.charHeight, font)
EffectType.WAVE_UNDERSCORE -> EffectPainter.WAVE_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font)
EffectType.BOLD_DOTTED_LINE -> EffectPainter.BOLD_DOTTED_UNDERSCORE.paint(g2d, xStart, y, xEnd - xStart, descent, font)
}
}
}
private fun isInsufficientContrast(
attributes: TextAttributes,
surroundingAttributes: TextAttributes
): Boolean {
val backgroundUnderHint = surroundingAttributes.backgroundColor
if (backgroundUnderHint != null && attributes.foregroundColor != null) {
val backgroundBlended = srcOverBlend(attributes.backgroundColor, backgroundUnderHint, BACKGROUND_ALPHA)
val backgroundBlendedGrayed = backgroundBlended.toGray()
val textGrayed = attributes.foregroundColor.toGray()
val delta = Math.abs(backgroundBlendedGrayed - textGrayed)
return delta < 10
}
return false
}
private fun Color.toGray(): Double {
return (0.30 * red) + (0.59 * green) + (0.11 * blue)
}
private fun srcOverBlend(foreground: Color, background: Color, foregroundAlpha: Float): Color {
val r = foreground.red * foregroundAlpha + background.red * (1.0f - foregroundAlpha)
val g = foreground.green * foregroundAlpha + background.green * (1.0f - foregroundAlpha)
val b = foreground.blue * foregroundAlpha + background.blue * (1.0f - foregroundAlpha)
return Color(r.roundToInt(), g.roundToInt(), b.roundToInt())
}
private fun calcWidthAdjustment(text: String?, editor: Editor, fontMetrics: FontMetrics, widthAdjustment: HintWidthAdjustment?): Int {
if (widthAdjustment == null || editor !is EditorImpl) return 0
val editorTextWidth = editor.getFontMetrics(Font.PLAIN).stringWidth(widthAdjustment.editorTextToMatch)
return max(0, editorTextWidth
+ calcHintTextWidth(widthAdjustment.hintTextToMatch, fontMetrics)
- calcHintTextWidth(text, fontMetrics))
}
class MyFontMetrics internal constructor(editor: Editor, size: Int, @JdkConstants.FontStyle fontType: Int, useEditorFont: Boolean) {
val metrics: FontMetrics
val lineHeight: Int
val font: Font
get() = metrics.font
init {
val font = if (useEditorFont) {
val editorFont = EditorUtil.getEditorFont()
editorFont.deriveFont(fontType, size.toFloat())
} else {
val familyName = UIManager.getFont("Label.font").family
StartupUiUtil.getFontWithFallback(familyName, fontType, size)
}
val context = getCurrentContext(editor)
metrics = FontInfo.getFontMetrics(font, context)
// We assume this will be a better approximation to a real line height for a given font
lineHeight = ceil(font.createGlyphVector(context, "Ap").visualBounds.height).toInt()
}
fun isActual(editor: Editor, size: Int, fontType: Int, familyName: String): Boolean {
val font = metrics.font
if (familyName != font.family || size != font.size || fontType != font.style) return false
val currentContext = getCurrentContext(editor)
return currentContext.equals(metrics.fontRenderContext)
}
private fun getCurrentContext(editor: Editor): FontRenderContext {
val editorContext = FontInfo.getFontRenderContext(editor.contentComponent)
return FontRenderContext(editorContext.transform,
AntialiasingType.getKeyForCurrentScope(false),
UISettings.editorFractionalMetricsHint)
}
}
@JvmStatic
protected fun getFontMetrics(editor: Editor, useEditorFont: Boolean): MyFontMetrics {
val size = max(1, editor.colorsScheme.editorFontSize - 1)
var metrics = editor.getUserData(HINT_FONT_METRICS)
val attributes = editor.colorsScheme.getAttributes(DefaultLanguageHighlighterColors.INLINE_PARAMETER_HINT)
val fontType = attributes.fontType
val familyName = if (useEditorFont) {
EditorColorsManager.getInstance().globalScheme.editorFontName
}
else {
StartupUiUtil.getLabelFont().family
}
if (metrics != null && !metrics.isActual(editor, size, fontType, familyName)) {
metrics = null
}
if (metrics == null) {
metrics = MyFontMetrics(editor, size, fontType, useEditorFont)
editor.putUserData(HINT_FONT_METRICS, metrics)
}
return metrics
}
@JvmStatic
fun useEditorFontFromSettings() = EditorSettingsExternalizable.getInstance().isUseEditorFontInInlays
private fun getFont(editor: Editor, useEditorFont: Boolean): Font {
return getFontMetrics(editor, useEditorFont).font
}
@JvmStatic
protected fun calcHintTextWidth(text: String?, fontMetrics: FontMetrics): Int {
return if (text == null) 0 else fontMetrics.stringWidth(text) + 14
}
private val HINT_FONT_METRICS = Key.create<MyFontMetrics>("ParameterHintFontMetrics")
private const val BACKGROUND_ALPHA = 0.55f
}
// workaround for KT-12063 "IllegalAccessError when accessing @JvmStatic protected member of a companion object from a subclass"
@JvmSynthetic
@JvmName("getFontMetrics$")
protected fun getFontMetrics(editor: Editor, useEditorFont: Boolean): MyFontMetrics = Companion.getFontMetrics(editor, useEditorFont)
}
| apache-2.0 |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/model/detail/PermissionData.kt | 1 | 612 | package sk.styk.martin.apkanalyzer.model.detail
import android.annotation.SuppressLint
import android.content.pm.PermissionInfo
import android.os.Parcelable
import kotlinx.android.parcel.Parcelize
import sk.styk.martin.apkanalyzer.manager.appanalysis.AppPermissionManager
@SuppressLint("ParcelCreator")
@Parcelize
data class PermissionData(val name: String,
val simpleName: String = AppPermissionManager.createSimpleName(name),
val groupName: String? = null,
val protectionLevel: Int = PermissionInfo.PROTECTION_NORMAL) : Parcelable | gpl-3.0 |
MartinStyk/AndroidApkAnalyzer | app/src/main/java/sk/styk/martin/apkanalyzer/manager/analytics/FragmentScreenTracker.kt | 1 | 1323 | package sk.styk.martin.apkanalyzer.manager.analytics
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.scopes.ActivityScoped
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import sk.styk.martin.apkanalyzer.manager.navigationdrawer.ForegroundFragmentWatcher
import sk.styk.martin.apkanalyzer.util.FragmentTag
import sk.styk.martin.apkanalyzer.util.coroutines.DispatcherProvider
import javax.inject.Inject
@ActivityScoped
class FragmentScreenTracker @Inject constructor(private val foregroundFragmentWatcher: ForegroundFragmentWatcher,
private val analyticsTracker: AnalyticsTracker,
dispatcherProvider: DispatcherProvider) : ViewModel() {
private var lastTrackedTag: FragmentTag? = null
init {
viewModelScope.launch(dispatcherProvider.default()) {
foregroundFragmentWatcher.foregroundFragment
.filter {
it != lastTrackedTag
}.onEach {
lastTrackedTag = it
}.collect {
analyticsTracker.trackScreenView(it.tag)
}
}
}
} | gpl-3.0 |
WYKCode/WYK-Android | app/src/main/java/college/wyk/app/ui/feed/FeedFragment.kt | 1 | 3976 | package college.wyk.app.ui.feed
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentStatePagerAdapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import college.wyk.app.R
import college.wyk.app.commons.inflate
import college.wyk.app.commons.landingActivity
import college.wyk.app.ui.feed.directus.DirectusFeedFragment
import college.wyk.app.ui.feed.sns.SnsFeedFragment
import com.astuetz.PagerSlidingTabStrip
import com.github.florent37.materialviewpager.header.HeaderDesign
import kotlinx.android.synthetic.main.fragment_feed.*
class FeedFragment : Fragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_feed, container, false)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState) // Do not use saved instance state; view pager may crash
// set up toolbar
val toolbar = view_pager.toolbar
toolbar.title = "What's New"
landingActivity.updateToolbar(toolbar)
// set up view pager
view_pager.viewPager.adapter = FeedAdapter(childFragmentManager) // use child fragment manager
view_pager.setMaterialViewPagerListener { page ->
when (page) {
indices["School"] -> HeaderDesign.fromColorResAndUrl(R.color.school, "http://wyk.tigerhix.me/cover/feed.jpg")
indices["CampusTV"] -> HeaderDesign.fromColorResAndUrl(R.color.campus_tv, "http://wyk.tigerhix.me/cover/campus_tv.jpg")
indices["SA"] -> HeaderDesign.fromColorResAndUrl(R.color.sa, "http://wyk.tigerhix.me/cover/sa.png")
indices["MA"] -> HeaderDesign.fromColorResAndUrl(R.color.ma, "http://wyk.tigerhix.me/cover/ma.jpg")
else -> null
}
}
view_pager.pagerTitleStrip.setViewPager(view_pager.viewPager)
view_pager.viewPager.currentItem = indices["School"]!!
}
}
class FeedAdapter(supportFragmentManager: FragmentManager) : FragmentStatePagerAdapter(supportFragmentManager), PagerSlidingTabStrip.CustomTabProvider {
override fun getItem(position: Int) = when (position) {
indices["School"] -> DirectusFeedFragment()
indices["CampusTV"] -> SnsFeedFragment.newInstance("CampusTV")
indices["SA"] -> SnsFeedFragment.newInstance("SA")
indices["MA"] -> SnsFeedFragment.newInstance("MA")
else -> SnsFeedFragment.newInstance(position.toString())
}
override fun getCount() = 4
override fun getPageTitle(position: Int) = when (position) {
indices["School"] -> "School"
indices["CampusTV"] -> "Campus TV"
indices["SA"] -> "SA"
indices["MA"] -> "MA"
else -> ""
}
override fun getCustomTabView(parent: ViewGroup, position: Int): View {
val view = parent.inflate(R.layout.tab, false)
val imageView = view.findViewById(R.id.tab_icon) as ImageView
imageView.setImageResource(when (position) {
indices["School"] -> R.drawable.ic_school_white_48dp
indices["CampusTV"] -> R.drawable.ic_videocam_white_48dp
indices["SA"] -> R.drawable.ic_group_white_48dp
indices["MA"] -> R.drawable.ic_music_note_white_48dp
else -> R.drawable.ic_school_white_48dp
})
return view
}
override fun tabUnselected(tab: View) {
val imageView = tab.findViewById(R.id.tab_icon) as ImageView
imageView.alpha = .6f
}
override fun tabSelected(tab: View) {
val imageView = tab.findViewById(R.id.tab_icon) as ImageView
imageView.alpha = 1.0f
}
}
val indices = mapOf(
"MA" to 3,
"SA" to 2,
"School" to 1,
"CampusTV" to 0
) | mit |
hitting1024/IndexedListViewForAndroid | library/src/main/kotlin/jp/hitting/android/indexedlist/IndexedListView.kt | 1 | 6498 | package jp.hitting.android.indexedlist
import android.content.Context
import android.graphics.Color
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.util.AttributeSet
import android.util.Pair
import android.util.SparseBooleanArray
import android.view.Gravity
import android.view.View
import android.widget.*
import android.widget.AdapterView.*
class IndexedListView(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) {
companion object {
private var indexTextColor: Int = Color.WHITE
private var indexTextSize: Float = 12f
}
private var indexList: List<Pair<String, Int>>? = null
private val listView: ListView
private val indexLayout: LinearLayout
init {
val typedAry = context.obtainStyledAttributes(attrs, R.styleable.IndexedListView)
indexTextColor = typedAry.getColor(R.styleable.IndexedListView_index_color, Color.WHITE)
indexTextSize = typedAry.getDimension(R.styleable.IndexedListView_index_size, 12f)
typedAry.recycle()
this.listView = ListView(this.context)
this.addView(this.listView, LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT))
this.indexLayout = LinearLayout(this.context)
this.indexLayout.setPadding(10, 5, 10, 5)
this.indexLayout.orientation = LinearLayout.VERTICAL
this.indexLayout.setHorizontalGravity(ALIGN_PARENT_RIGHT)
val params = LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT)
params.addRule(ALIGN_PARENT_RIGHT)
this.indexLayout.setOnTouchListener { view, motionEvent ->
this.moveSection(motionEvent.getX(), motionEvent.getY())
return@setOnTouchListener true
}
this.addView(this.indexLayout, params)
}
/**
* @param indexList the pair of (index key, jump position) list.
*/
fun setIndex(indexList: List<Pair<String, Int>>) {
this.indexList = indexList
this.indexLayout.removeAllViews()
for (index in this.indexList!!) {
val textView = TextView(this.context)
textView.text = index.first
textView.gravity = Gravity.CENTER
textView.textSize = indexTextSize
textView.setTypeface(Typeface.DEFAULT, Typeface.BOLD)
textView.setTextColor(indexTextColor)
textView.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f)
this.indexLayout.addView(textView)
}
}
fun setIndexVisibility(visibility: Int) {
this.indexLayout.visibility = visibility
}
private fun moveSection(x: Float, y: Float) {
val size = this.indexList!!.size
var position = (y / (this.listView.height / size)).toInt()
if (position < 0) {
position = 0
} else if (position >= size) {
position = size - 1
}
val sectionPosition = this.indexList!![position].second
this.listView.setSelection(sectionPosition)
}
//
// ListView
//
// method
val maxScrollAmount: Int
get() = this.listView.maxScrollAmount
fun addHeaderView(v: View, data: Any, isSelectable: Boolean) {
this.listView.addHeaderView(v, data, isSelectable)
}
fun addHeaderView(v: View) {
this.listView.addHeaderView(v)
}
val headerViewsCount: Int
get() = this.listView.headerViewsCount
fun removeHeaderView(v: View): Boolean {
return this.listView.removeHeaderView(v)
}
fun addFooterView(v: View, data: Any, isSelectable: Boolean) {
this.listView.addFooterView(v, data, isSelectable)
}
fun addFooterView(v: View) {
this.listView.addFooterView(v)
}
val footerViewsCount: Int
get() = this.listView.footerViewsCount
fun removeFooterView(v: View): Boolean {
return this.listView.removeFooterView(v)
}
var adapter: ListAdapter
get() = this.listView.adapter
set(adapter) {
this.listView.adapter = adapter
}
fun setSelection(position: Int) {
this.listView.setSelection(position)
}
fun setSelectionFromTop(position: Int, y: Int) {
this.listView.setSelectionFromTop(position, y)
}
fun setSelectionAfterHeaderView() {
this.listView.setSelectionAfterHeaderView()
}
var itemsCanFocus: Boolean
get() = this.listView.itemsCanFocus
set(itemsCanFocus) {
this.listView.itemsCanFocus = itemsCanFocus
}
fun setCacheColorHint(color: Int) {
this.listView.cacheColorHint = color
}
var divider: Drawable
get() = this.listView.divider
set(divider) {
this.listView.divider = divider
}
var dividerHeight: Int
get() = this.listView.dividerHeight
set(height) {
this.listView.dividerHeight = height
}
fun setHeaderDividersEnabled(headerDividersEnabled: Boolean) {
this.listView.setHeaderDividersEnabled(headerDividersEnabled)
}
fun setFooterDividersEnabled(footerDividersEnabled: Boolean) {
this.listView.setFooterDividersEnabled(footerDividersEnabled)
}
var choiceMode: Int
get() = this.listView.choiceMode
set(choiceMode) {
this.listView.choiceMode = choiceMode
}
fun performItemClick(view: View, position: Int, id: Long): Boolean {
return this.listView.performItemClick(view, position, id)
}
fun setItemChecked(position: Int, value: Boolean) {
this.listView.setItemChecked(position, value)
}
fun isItemChecked(position: Int): Boolean {
return this.listView.isItemChecked(position)
}
val checkedItemPosition: Int
get() = this.listView.checkedItemPosition
val checkedItemPositions: SparseBooleanArray
get() = this.listView.checkedItemPositions
fun clearChoices() {
this.listView.clearChoices()
}
// listener
fun setOnItemClickListener(listener: OnItemClickListener) {
this.listView.onItemClickListener = listener
}
fun setOnItemLongClickListener(listener: OnItemLongClickListener) {
this.listView.onItemLongClickListener = listener
}
fun setOnItemSelectedListener(listener: OnItemSelectedListener) {
this.listView.onItemSelectedListener = listener
}
} | mit |
fkorotkov/k8s-kotlin-dsl | DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/execNewPod.kt | 1 | 402 | // GENERATED
package com.fkorotkov.openshift
import io.fabric8.openshift.api.model.ExecNewPodHook as model_ExecNewPodHook
import io.fabric8.openshift.api.model.LifecycleHook as model_LifecycleHook
fun model_LifecycleHook.`execNewPod`(block: model_ExecNewPodHook.() -> Unit = {}) {
if(this.`execNewPod` == null) {
this.`execNewPod` = model_ExecNewPodHook()
}
this.`execNewPod`.block()
}
| mit |
MyCollab/mycollab | mycollab-web/src/main/java/com/mycollab/module/project/view/IFavoritePresenter.kt | 3 | 894 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.view
import com.mycollab.vaadin.mvp.IPresenter
/**
* @author MyCollab Ltd
* @since 5.2.10
*/
interface IFavoritePresenter : IPresenter<IFavoriteView>
| agpl-3.0 |
aosp-mirror/platform_frameworks_support | core/ktx/src/androidTest/java/androidx/core/graphics/RectTest.kt | 1 | 6777 | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.core.graphics
import android.graphics.Matrix
import android.graphics.Point
import android.graphics.PointF
import android.graphics.Rect
import android.graphics.RectF
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
class RectTest {
@Test fun destructuringInt() {
val (l, t, r, b) = Rect(4, 8, 16, 24)
assertEquals(4, l)
assertEquals(8, t)
assertEquals(16, r)
assertEquals(24, b)
}
@Test fun destructuringFloat() {
val (l, t, r, b) = RectF(4.0f, 8.0f, 16.0f, 24.0f)
assertEquals(4.0f, l)
assertEquals(8.0f, t)
assertEquals(16.0f, r)
assertEquals(24.0f, b)
}
@Test fun unionInt() {
val (l, t, r, b) = Rect(0, 0, 4, 4) + Rect(-1, -1, 6, 6)
assertEquals(-1, l)
assertEquals(-1, t)
assertEquals(6, r)
assertEquals(6, b)
}
@Test fun unionAsAndInt() {
val (l, t, r, b) = Rect(0, 0, 4, 4) and Rect(-1, -1, 6, 6)
assertEquals(-1, l)
assertEquals(-1, t)
assertEquals(6, r)
assertEquals(6, b)
}
@Test fun unionFloat() {
val (l, t, r, b) = RectF(0.0f, 0.0f, 4.0f, 4.0f) + RectF(-1.0f, -1.0f, 6.0f, 6.0f)
assertEquals(-1.0f, l)
assertEquals(-1.0f, t)
assertEquals(6.0f, r)
assertEquals(6.0f, b)
}
@Test fun unionAsAndFloat() {
val (l, t, r, b) = RectF(0.0f, 0.0f, 4.0f, 4.0f) and RectF(-1.0f, -1.0f, 6.0f, 6.0f)
assertEquals(-1.0f, l)
assertEquals(-1.0f, t)
assertEquals(6.0f, r)
assertEquals(6.0f, b)
}
@Test fun differenceInt() {
val r = Rect(0, 0, 4, 4) - Rect(-1, 2, 6, 6)
assertEquals(Rect(0, 0, 4, 2), r.bounds)
}
@Test fun differenceFloat() {
val r = RectF(0.0f, 0.0f, 4.0f, 4.0f) - RectF(-1.0f, 2.0f, 6.0f, 6.0f)
assertEquals(Rect(0, 0, 4, 2), r.bounds)
}
@Test fun intersectionAsOrInt() {
val (l, t, r, b) = Rect(0, 0, 4, 4) or Rect(2, 2, 6, 6)
assertEquals(2, l)
assertEquals(2, t)
assertEquals(4, r)
assertEquals(4, b)
}
@Test fun intersectionAsOrFloat() {
val (l, t, r, b) = RectF(0.0f, 0.0f, 4.0f, 4.0f) or RectF(2.0f, 2.0f, 6.0f, 6.0f)
assertEquals(2.0f, l)
assertEquals(2.0f, t)
assertEquals(4.0f, r)
assertEquals(4.0f, b)
}
@Test fun xorInt() {
val r = Rect(0, 0, 4, 4) xor Rect(2, 2, 6, 6)
assertEquals(Rect(0, 0, 4, 4) and Rect(2, 2, 6, 6), r.bounds)
assertFalse(r.contains(3, 3))
}
@Test fun xorFloat() {
val r = RectF(0.0f, 0.0f, 4.0f, 4.0f) xor RectF(2.0f, 2.0f, 6.0f, 6.0f)
assertEquals(Rect(0, 0, 4, 4) and Rect(2, 2, 6, 6), r.bounds)
assertFalse(r.contains(3, 3))
}
@Test fun offsetInt() {
val (l, t, r, b) = Rect(0, 0, 2, 2) + 2
assertEquals(l, 2)
assertEquals(t, 2)
assertEquals(r, 4)
assertEquals(b, 4)
}
@Test fun offsetPoint() {
val (l, t, r, b) = Rect(0, 0, 2, 2) + Point(1, 2)
assertEquals(l, 1)
assertEquals(t, 2)
assertEquals(r, 3)
assertEquals(b, 4)
}
@Test fun offsetFloat() {
val (l, t, r, b) = RectF(0.0f, 0.0f, 2.0f, 2.0f) + 2.0f
assertEquals(l, 2.0f)
assertEquals(t, 2.0f)
assertEquals(r, 4.0f)
assertEquals(b, 4.0f)
}
@Test fun offsetPointF() {
val (l, t, r, b) = RectF(0.0f, 0.0f, 2.0f, 2.0f) + PointF(1.0f, 2.0f)
assertEquals(l, 1.0f)
assertEquals(t, 2.0f)
assertEquals(r, 3.0f)
assertEquals(b, 4.0f)
}
@Test fun negativeOffsetInt() {
val (l, t, r, b) = Rect(0, 0, 2, 2) - 2
assertEquals(l, -2)
assertEquals(t, -2)
assertEquals(r, 0)
assertEquals(b, 0)
}
@Test fun negativeOffsetPoint() {
val (l, t, r, b) = Rect(0, 0, 2, 2) - Point(1, 2)
assertEquals(l, -1)
assertEquals(t, -2)
assertEquals(r, 1)
assertEquals(b, 0)
}
@Test fun negativeOffsetFloat() {
val (l, t, r, b) = RectF(0.0f, 0.0f, 2.0f, 2.0f) - 2.0f
assertEquals(l, -2.0f)
assertEquals(t, -2.0f)
assertEquals(r, 0.0f)
assertEquals(b, 0.0f)
}
@Test fun negativeOffsetPointF() {
val (l, t, r, b) = RectF(0.0f, 0.0f, 2.0f, 2.0f) - PointF(1.0f, 2.0f)
assertEquals(l, -1.0f)
assertEquals(t, -2.0f)
assertEquals(r, 1.0f)
assertEquals(b, 0.0f)
}
@Test fun pointInside() {
assertTrue(Point(1, 1) in Rect(0, 0, 2, 2))
assertTrue(PointF(1.0f, 1.0f) in RectF(0.0f, 0.0f, 2.0f, 2.0f))
}
@Test fun toRect() {
assertEquals(
Rect(0, 1, 2, 3),
RectF(0f, 1f, 2f, 3f).toRect())
assertEquals(
Rect(0, 1, 2, 3),
RectF(0.1f, 1.1f, 1.9f, 2.9f).toRect())
}
@Test fun toRectF() {
val rectF = Rect(0, 1, 2, 3).toRectF()
assertEquals(0f, rectF.left, 0f)
assertEquals(1f, rectF.top, 0f)
assertEquals(2f, rectF.right, 0f)
assertEquals(3f, rectF.bottom, 0f)
}
@Test fun toRegionInt() {
assertEquals(Rect(1, 1, 5, 5), Rect(1, 1, 5, 5).toRegion().bounds)
}
@Test fun toRegionFloat() {
assertEquals(Rect(1, 1, 5, 5), RectF(1.1f, 1.1f, 4.8f, 4.8f).toRegion().bounds)
}
@Test fun transformRectToRect() {
val m = Matrix()
m.setScale(2.0f, 2.0f)
val r = RectF(2.0f, 2.0f, 5.0f, 7.0f).transform(m)
assertEquals(4f, r.left, 0f)
assertEquals(4f, r.top, 0f)
assertEquals(10f, r.right, 0f)
assertEquals(14f, r.bottom, 0f)
}
@Test fun transformRectNotPreserved() {
val m = Matrix()
m.setRotate(45.0f)
val (l, t, r, b) = RectF(-1.0f, -1.0f, 1.0f, 1.0f).transform(m)
assertEquals(-1.414f, l, 1e-3f)
assertEquals(-1.414f, t, 1e-3f)
assertEquals( 1.414f, r, 1e-3f)
assertEquals( 1.414f, b, 1e-3f)
}
}
| apache-2.0 |
marktony/ZhiHuDaily | app/src/main/java/com/marktony/zhihudaily/data/GuokrHandpickNewsAvatar.kt | 1 | 1573 | /*
* Copyright 2016 lizhaotailang
*
* 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.marktony.zhihudaily.data
import android.annotation.SuppressLint
import android.arch.persistence.room.ColumnInfo
import android.os.Parcelable
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import kotlinx.android.parcel.Parcelize
/**
* Created by lizhaotailang on 2017/6/17.
*
* Immutable model class for guokr handpick new avatar. See the json string for more details.
* Entity class for [com.google.gson.Gson] and [android.arch.persistence.room.Room].
*/
@Parcelize
@SuppressLint("ParcelCreator")
data class GuokrHandpickNewsAvatar(
@ColumnInfo(name = "avatar_large")
@Expose
@SerializedName("large")
val large: String,
@ColumnInfo(name = "avatar_small")
@Expose
@SerializedName("small")
val small: String,
@ColumnInfo(name = "avatar_normal")
@Expose
@SerializedName("normal")
val normal: String
) : Parcelable
| apache-2.0 |
kerubistan/kerub | src/test/kotlin/com/github/kerubistan/kerub/model/dynamic/gvinum/MirroredGvinumConfigurationTest.kt | 2 | 426 | package com.github.kerubistan.kerub.model.dynamic.gvinum
import com.github.kerubistan.kerub.model.AbstractDataRepresentationTest
internal class MirroredGvinumConfigurationTest : AbstractDataRepresentationTest<MirroredGvinumConfiguration>() {
override val testInstances = listOf(
MirroredGvinumConfiguration(disks = listOf("test-disk-1", "test-disk-2"))
)
override val clazz = MirroredGvinumConfiguration::class.java
} | apache-2.0 |
kerubistan/kerub | src/test/kotlin/com/github/kerubistan/kerub/model/collection/HostDataCollectionTest.kt | 2 | 1406 | package com.github.kerubistan.kerub.model.collection
import com.github.kerubistan.kerub.hostUp
import com.github.kerubistan.kerub.model.config.HostConfiguration
import com.github.kerubistan.kerub.testHost
import com.github.kerubistan.kerub.testOtherHost
import org.junit.Test
import org.junit.jupiter.api.assertThrows
import kotlin.test.assertEquals
import kotlin.test.assertNotEquals
class HostDataCollectionTest {
@Test
fun updateDynamic() {
val original = HostDataCollection(
stat = testHost,
dynamic = hostUp(testHost)
)
val updated = original.updateDynamic { it.copy(systemCpu = 1) }
assertNotEquals(updated, original.dynamic)
}
@Test
fun updateWithDynamic() {
val original = HostDataCollection(
stat = testHost,
dynamic = hostUp(testHost)
)
val updated = original.updateWithDynamic { it.copy(systemCpu = 1) }
assertEquals(original.stat, updated.stat)
assertNotEquals(original.dynamic, updated.dynamic)
}
@Test
fun validation() {
assertThrows<IllegalStateException>("host id of dyn and stat must be the same") {
HostDataCollection(
stat = testHost,
dynamic = hostUp(testOtherHost)
)
}
assertThrows<IllegalStateException>("host id of config and stat must be the same") {
HostDataCollection(
stat = testHost,
dynamic = hostUp(testHost),
config = HostConfiguration(
id = testOtherHost.id
)
)
}
}
} | apache-2.0 |
mike-plummer/KotlinCalendar | src/main/kotlin/com/objectpartners/plummer/kotlin/calendar/input/handler/CalendarEntryInputHandler.kt | 1 | 1562 | package com.objectpartners.plummer.kotlin.calendar.input.handler
import com.objectpartners.plummer.kotlin.calendar.entry.CalendarEntry
import com.objectpartners.plummer.kotlin.calendar.parseHMS
import java.io.BufferedReader
import java.time.Duration
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
abstract class CalendarEntryInputHandler<out T: CalendarEntry>(): InputHandler<CalendarEntry> {
abstract val type: String
private final val pattern: String = "yyyy-MM-dd HH:mm:ss";
private final val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern(pattern)
override fun handle(source: BufferedReader): T {
println("-- $type entry --")
// Read a dttm from the source, if none found then use current dttm
print("\tStart time ($pattern): ")
val startString = source.readLine()
// Kotlin has no ternary operator so we use a succinct if-else instead
val start = if (startString.isBlank()) LocalDateTime.now() else LocalDateTime.from(formatter.parse(startString))
// Parse hours, minutes, and seconds from the source
print("\tDuration (HH:mm:ss): ")
val duration = Duration.ZERO.parseHMS(source.readLine())
// Build object and populate
val entry: T = buildInstance()
return entry.apply { this.start = start
this.duration = duration }
}
/**
* Construct a new instance of the type of [CalendarEntry] this handler manages ([T]).
*/
abstract fun buildInstance() : T
} | mit |
seventhroot/elysium | bukkit/rpk-chat-lib-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/event/chatchannel/RPKChatChannelMessageEvent.kt | 1 | 1123 | /*
* 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.chat.bukkit.event.chatchannel
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannel
import com.rpkit.players.bukkit.event.minecraftprofile.RPKMinecraftProfileEvent
import com.rpkit.players.bukkit.event.profile.RPKThinProfileEvent
import com.rpkit.players.bukkit.profile.RPKThinProfile
interface RPKChatChannelMessageEvent: RPKChatChannelEvent, RPKMinecraftProfileEvent, RPKThinProfileEvent {
override val profile: RPKThinProfile
override var chatChannel: RPKChatChannel
val message: String
} | apache-2.0 |
hazuki0x0/YuzuBrowser | legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/utils/extensions/ViewExtensions.kt | 1 | 6951 | /*
* Copyright (C) 2017-2020 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.utils.extensions
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.ContentValues
import android.content.Context
import android.os.Build
import android.provider.MediaStore
import androidx.core.app.NotificationCompat
import androidx.documentfile.provider.DocumentFile
import jp.hazuki.yuzubrowser.core.MIME_TYPE_MHTML
import jp.hazuki.yuzubrowser.core.utility.extensions.getWritableFileOrNull
import jp.hazuki.yuzubrowser.core.utility.log.ErrorReport
import jp.hazuki.yuzubrowser.core.utility.utils.getMimeType
import jp.hazuki.yuzubrowser.core.utility.utils.ui
import jp.hazuki.yuzubrowser.download.NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY
import jp.hazuki.yuzubrowser.download.core.data.DownloadFile
import jp.hazuki.yuzubrowser.download.core.data.DownloadFileInfo
import jp.hazuki.yuzubrowser.download.core.data.MetaData
import jp.hazuki.yuzubrowser.download.createFileOpenIntent
import jp.hazuki.yuzubrowser.download.repository.DownloadsDao
import jp.hazuki.yuzubrowser.legacy.R
import jp.hazuki.yuzubrowser.ui.widget.toast
import jp.hazuki.yuzubrowser.webview.CustomWebView
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import java.io.File
import java.io.IOException
fun CustomWebView.saveArchive(downloadsDao: DownloadsDao, root: DocumentFile, file: DownloadFile) {
ui {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
val outFile = root.uri.getWritableFileOrNull()
if (outFile != null && outFile.exists()) {
val downloadedFile = File(outFile, file.name!!)
saveWebArchiveMethod(downloadedFile.toString())
onDownload(webView.context, downloadsDao, root, file, DocumentFile.fromFile(downloadedFile), true, downloadedFile.length())
return@ui
}
}
val context = webView.context
val tmpFile = File(context.cacheDir, "page.tmp")
saveWebArchiveMethod(tmpFile.absolutePath)
delay(1000)
var success = tmpFile.exists()
if (success) {
val size = withContext(Dispatchers.IO) {
var size = 0L
do {
delay(500)
val oldSize = size
size = tmpFile.length()
} while (size == 0L || oldSize != size)
return@withContext size
}
val name = file.name!!
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && root.uri.scheme == "file") {
context.copyArchive(downloadsDao, tmpFile, name, file)
return@ui
}
val saveTo = root.createFile(MIME_TYPE_MHTML, name)
if (saveTo == null) {
context.toast(R.string.failed)
return@ui
}
withContext(Dispatchers.IO) {
tmpFile.inputStream().use { input ->
context.contentResolver.openOutputStream(saveTo.uri, "w")!!.use { out ->
input.copyTo(out)
}
}
tmpFile.delete()
}
success = saveTo.exists()
onDownload(context, downloadsDao, root, file, saveTo, success, size)
}
}
}
private suspend fun Context.copyArchive(downloadsDao: DownloadsDao, tmpFile: File, name: String, file: DownloadFile) {
val values = ContentValues().apply {
put(MediaStore.Downloads.DISPLAY_NAME, name)
put(MediaStore.Downloads.MIME_TYPE, getMimeType(name))
put(MediaStore.Downloads.IS_DOWNLOAD, 1)
put(MediaStore.Downloads.IS_PENDING, 1)
}
val collection = MediaStore.Downloads.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY)
val uri = contentResolver.insert(collection, values)
if (uri == null) {
tmpFile.delete()
return
}
val result = withContext(Dispatchers.IO) {
try {
contentResolver.openOutputStream(uri)?.use { os ->
tmpFile.inputStream().use {
it.copyTo(os)
values.apply {
clear()
put(MediaStore.Downloads.IS_PENDING, 0)
}
val dFile = DocumentFile.fromSingleUri(this@copyArchive, uri)!!
val size = dFile.length()
val info = DownloadFileInfo(uri, file, MetaData(name, MIME_TYPE_MHTML, size, false))
info.state = DownloadFileInfo.STATE_DOWNLOADED
downloadsDao.insert(info)
contentResolver.update(uri, values, null, null)
return@withContext true
}
}
} catch (e: IOException) {
ErrorReport.printAndWriteLog(e)
} finally {
tmpFile.delete()
}
return@withContext false
}
if (!result) {
contentResolver.delete(uri, null, null)
}
}
private suspend fun onDownload(
context: Context,
dao: DownloadsDao,
root: DocumentFile,
file: DownloadFile,
downloadedFile: DocumentFile,
success: Boolean,
size: Long
) {
val name = file.name!!
val info = DownloadFileInfo(root.uri, file, MetaData(name, MIME_TYPE_MHTML, size, false)).also {
it.state = if (success) {
DownloadFileInfo.STATE_DOWNLOADED
} else {
DownloadFileInfo.STATE_UNKNOWN_ERROR
}
it.id = dao.insertAsync(it)
}
if (success) {
context.toast(context.getString(R.string.saved_file) + name)
val notify = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_DOWNLOAD_NOTIFY)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(name)
.setContentText(context.getText(R.string.download_success))
.setSmallIcon(android.R.drawable.stat_sys_download_done)
.setContentIntent(PendingIntent.getActivity(context.applicationContext, 0, info.createFileOpenIntent(context, downloadedFile), 0))
.build()
val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
manager.notify(info.id.toInt(), notify)
}
}
| apache-2.0 |
geeniuss01/PWM | app/src/main/java/me/samen/pwm/setup/SetupActivity.kt | 1 | 1727 | package me.samen.pwm.setup
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.View
import kotlinx.android.synthetic.main.activity_setup.*
import me.samen.pwm.common.PWMApp
import me.samen.pwm.R
import me.samen.pwm.common.Data
class SetupActivity : AppCompatActivity() {
var appData: Data? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_setup)
val toolBar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolBar)
appData = (application as PWMApp).appData
editTextPin.setOnEditorActionListener { textView, i,
keyEvent ->
checkPinAndFinish(textView.text.toString())
}
editTextPin.post { Runnable { editTextPin.requestFocus() } }
if (appData?.getPin() == null) {
textViewInstruction.visibility = View.VISIBLE
textViewInstruction.text=resources.getString(R.string.setup_choose_pin)
}
}
fun checkPinAndFinish(pin: String): Boolean {
textViewInstruction.text=""
if (appData?.getPin() == null && editTextPin.text.toString().length == 4) {
appData?.savePin(editTextPin.text.toString())
finish()
} else if (pin.equals(appData?.getPin())) {
appData?.authenticated = true
finish()
} else {
textViewInstruction.visibility = View.VISIBLE
textViewInstruction.text=resources.getString(R.string.setup_wrong_pin)
}
return true
}
}
| apache-2.0 |
JetBrains/teamcity-azure-plugin | plugin-azure-agent/src/main/kotlin/jetbrains/buildServer/clouds/azure/WindowsCustomDataReader.kt | 1 | 1602 | /*
* Copyright 2000-2021 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 jetbrains.buildServer.clouds.azure
import com.intellij.openapi.diagnostic.Logger
import jetbrains.buildServer.agent.BuildAgentConfigurationEx
class WindowsCustomDataReader(agentConfiguration: BuildAgentConfigurationEx,
fileUtils: FileUtils)
: AzureCustomDataReader(agentConfiguration, fileUtils) {
override val customDataFileName: String
get() = WINDOWS_CUSTOM_DATA_FILE
override fun parseCustomData(customData: String) {
// Process custom data
try {
processCustomData(customData)
} catch (e: Exception) {
LOG.warnAndDebugDetails(String.format(UNABLE_TO_READ_CUSTOM_DATA_FILE, customDataFileName), e)
}
}
companion object {
private val LOG = Logger.getInstance(WindowsCustomDataReader::class.java.name)
private val SYSTEM_DRIVE = System.getenv("SystemDrive")
private val WINDOWS_CUSTOM_DATA_FILE = "$SYSTEM_DRIVE\\AzureData\\CustomData.bin"
}
}
| apache-2.0 |
KrenVpravo/CheckReaction | app/src/main/java/com/two_two/checkreaction/ui/gamescore/science/ScienceScoreActivity.kt | 1 | 1306 | package com.two_two.checkreaction.ui.gamescore.science
import android.app.Activity
import android.app.ProgressDialog
import android.os.Bundle
import com.google.firebase.database.FirebaseDatabase
import com.two_two.checkreaction.BuildConfig
import com.two_two.checkreaction.R
import com.two_two.checkreaction.models.firebase.FirebaseScienceResult
import com.two_two.checkreaction.ui.gamescore.OnLoadListener
import kotlinx.android.synthetic.main.activity_science_score.*
class ScienceScoreActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_science_score)
init()
}
private fun init() {
val dialog = ProgressDialog.show(this, getString(R.string.loading_title),
getString(R.string.loading_message))
val currentResult = intent.getSerializableExtra(FirebaseScienceResult.TAG) as FirebaseScienceResult?
val firebase = FirebaseDatabase.getInstance().reference
.child(BuildConfig.SCIENCE_GAMESCORES)
val adapter = ScienceScoreListAdapter(this, firebase.orderByChild(FirebaseScienceResult.TIMESTAMP),
currentResult, OnLoadListener { dialog.dismiss() })
ac_scores_list.adapter = adapter
}
}
| mit |
juanavelez/crabzilla | crabzilla-pg-client/src/main/java/io/github/crabzilla/pgc/PgcUowRepo.kt | 1 | 10235 | package io.github.crabzilla.pgc
import io.github.crabzilla.framework.*
import io.github.crabzilla.framework.UnitOfWork.JsonMetadata.EVENTS_JSON_CONTENT
import io.github.crabzilla.framework.UnitOfWork.JsonMetadata.EVENT_NAME
import io.github.crabzilla.internal.RangeOfEvents
import io.github.crabzilla.internal.UnitOfWorkEvents
import io.github.crabzilla.internal.UnitOfWorkRepository
import io.vertx.core.Promise
import io.vertx.core.json.JsonArray
import io.vertx.core.json.JsonObject
import io.vertx.pgclient.PgPool
import io.vertx.sqlclient.Tuple
import org.slf4j.LoggerFactory
import java.util.*
internal class PgcUowRepo<E: Entity>(private val pgPool: PgPool, private val jsonFunctions: EntityJsonAware<E>)
: UnitOfWorkRepository {
companion object {
internal val log = LoggerFactory.getLogger(PgcUowRepo::class.java)
private const val UOW_ID = "uow_id"
private const val UOW_EVENTS = "uow_events"
private const val CMD_ID = "cmd_id"
private const val CMD_DATA = "cmd_data"
private const val CMD_NAME = "cmd_name"
private const val AR_ID = "ar_id"
private const val AR_NAME = "ar_name"
private const val VERSION = "version"
private const val SQL_SELECT_FIELDS =
"select uow_id, uow_events, cmd_id, cmd_data, cmd_name, ar_id, ar_name, version"
const val SQL_SELECT_UOW_BY_CMD_ID = "$SQL_SELECT_FIELDS from units_of_work where cmd_id = $1"
const val SQL_SELECT_UOW_BY_UOW_ID = "$SQL_SELECT_FIELDS from units_of_work where uow_id = $1"
const val SQL_SELECT_UOW_BY_ENTITY_ID = "$SQL_SELECT_FIELDS from units_of_work where ar_id = $1 order by version"
const val SQL_SELECT_AFTER_VERSION = "select uow_events, version from units_of_work " +
"where ar_id = $1 and ar_name = $2 and version > $3 order by version"
}
override fun getUowByCmdId(cmdId: UUID): Promise<Pair<UnitOfWork, Long>> {
val promise = Promise.promise<Pair<UnitOfWork, Long>>()
val params = Tuple.of(cmdId)
pgPool.preparedQuery(SQL_SELECT_UOW_BY_CMD_ID, params) { ar ->
if (ar.failed()) {
promise.fail(ar.cause())
return@preparedQuery
}
val rows = ar.result()
if (rows.size() == 0) {
promise.complete(null)
return@preparedQuery
}
val row = rows.first()
val commandName = row.getString(CMD_NAME)
val commandAsJson = row.get(JsonObject::class.java, 3)
val command = try { jsonFunctions.cmdFromJson(commandName, commandAsJson) }
catch (e: Exception) { null }
if (command == null) {
promise.fail("error when getting command $commandName from json ")
return@preparedQuery
}
val jsonArray = row.get(JsonArray::class.java, 1)
val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index ->
val jsonObject = jsonArray.getJsonObject(index)
val eventName = jsonObject.getString(EVENT_NAME)
val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT)
val domainEvent = jsonFunctions.eventFromJson(eventName, eventJson)
domainEvent
}
val events: List<Pair<String, DomainEvent>> = List(jsonArray.size(), jsonToEventPair)
val uowId = row.getLong(UOW_ID)
val uow = UnitOfWork(row.getString(AR_NAME), row.getInteger(AR_ID),
row.getUUID(CMD_ID), row.getString(CMD_NAME), command, row.getInteger(VERSION)!!, events)
promise.complete(Pair(uow, uowId))
}
return promise
}
override fun getUowByUowId(uowId: Long): Promise<UnitOfWork> {
val promise = Promise.promise<UnitOfWork>()
val params = Tuple.of(uowId)
pgPool.preparedQuery(SQL_SELECT_UOW_BY_UOW_ID, params) { ar ->
if (ar.failed()) {
promise.fail(ar.cause())
return@preparedQuery
}
val rows = ar.result()
if (rows.size() == 0) {
promise.complete(null)
return@preparedQuery
}
val row = rows.first()
val commandName = row.getString(CMD_NAME)
val commandAsJson = row.get(JsonObject::class.java, 3)
val command = try { jsonFunctions.cmdFromJson(commandName, commandAsJson) } catch (e: Exception) { null }
if (command == null) {
promise.fail("error when getting command $commandName from json ")
return@preparedQuery
}
val jsonArray = row.get(JsonArray::class.java, 1)
val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index ->
val jsonObject = jsonArray.getJsonObject(index)
val eventName = jsonObject.getString(EVENT_NAME)
val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT)
val domainEvent = jsonFunctions.eventFromJson(eventName, eventJson)
domainEvent
}
val events: List<Pair<String, DomainEvent>> = List(jsonArray.size(), jsonToEventPair)
val uow = UnitOfWork(row.getString(AR_NAME), row.getInteger(AR_ID),
row.getUUID(CMD_ID), row.getString(CMD_NAME), command, row.getInteger(VERSION)!!, events)
promise.complete(uow)
}
return promise
}
override fun getAllUowByEntityId(id: Int): Promise<List<UnitOfWork>> {
val promise = Promise.promise<List<UnitOfWork>>()
val params = Tuple.of(id)
pgPool.preparedQuery(SQL_SELECT_UOW_BY_ENTITY_ID, params) { ar ->
if (ar.failed()) {
promise.fail(ar.cause())
return@preparedQuery
}
val result = ArrayList<UnitOfWork>()
val rows = ar.result()
for (row in rows) {
val commandName = row.getString(CMD_NAME)
val commandAsJson = row.get(JsonObject::class.java, 3)
val command =
try { jsonFunctions.cmdFromJson(commandName, commandAsJson) } catch (e: Exception) { null }
if (command == null) {
promise.fail("error when getting command $commandName from json ")
return@preparedQuery
}
val jsonArray = row.get(JsonArray::class.java, 1)
val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index ->
val jsonObject = jsonArray.getJsonObject(index)
val eventName = jsonObject.getString(EVENT_NAME)
val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT)
val domainEvent = jsonFunctions.eventFromJson(eventName, eventJson)
domainEvent
}
val events: List<Pair<String, DomainEvent>> = List(jsonArray.size(), jsonToEventPair)
val uow = UnitOfWork(row.getString(AR_NAME), row.getInteger(AR_ID),
row.getUUID(CMD_ID), row.getString(CMD_NAME), command, row.getInteger(VERSION)!!, events)
result.add(uow)
}
promise.complete(result)
}
return promise
}
override fun selectAfterVersion(id: Int, version: Version, aggregateRootName: String): Promise<RangeOfEvents> {
val promise = Promise.promise<RangeOfEvents>()
log.trace("will load id [{}] after version [{}]", id, version)
pgPool.getConnection { ar0 ->
if (ar0.failed()) {
promise.fail(ar0.cause())
return@getConnection
}
val conn = ar0.result()
conn.prepare(SQL_SELECT_AFTER_VERSION) { ar1 ->
if (ar1.failed()) {
promise.fail(ar1.cause())
} else {
val pq = ar1.result()
// Fetch 100 rows at a time
val tuple = Tuple.of( id, aggregateRootName, version)
val stream = pq.createStream(100, tuple)
val list = ArrayList<RangeOfEvents>()
// Use the stream
stream.handler { row ->
val eventsArray = row.get(JsonArray::class.java, 0)
val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index ->
val jsonObject = eventsArray.getJsonObject(index)
val eventName = jsonObject.getString(EVENT_NAME)
val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT)
jsonFunctions.eventFromJson(eventName, eventJson)
}
val events: List<Pair<String, DomainEvent>> = List(eventsArray.size(), jsonToEventPair)
val snapshotData = RangeOfEvents(version, row.getInteger(1)!!, events)
list.add(snapshotData)
}
stream.endHandler {
log.trace("found {} units of work for id {} and version > {}", list.size, id, version)
val finalVersion = if (list.size == 0) 0 else list[list.size - 1].untilVersion
val flatMappedToEvents = list.flatMap { sd -> sd.events }
promise.complete(RangeOfEvents(version, finalVersion, flatMappedToEvents))
}
stream.exceptionHandler { err ->
log.error(err.message)
promise.fail(err)
}
}
}
}
return promise
}
override fun selectAfterUowId(uowId: Long, maxRows: Int): Promise<List<UnitOfWorkEvents>> {
val promise = Promise.promise<List<UnitOfWorkEvents>>()
log.trace("will load after uowId [{}]", uowId)
val selectAfterUowIdSql = "select uow_id, ar_id, uow_events " +
" from units_of_work " +
" where uow_id > $1 " +
" order by uow_id " +
" limit " + maxRows
val list = ArrayList<UnitOfWorkEvents>()
pgPool.preparedQuery(selectAfterUowIdSql, Tuple.of(uowId)) { ar ->
if (ar.failed()) {
promise.fail(ar.cause().message)
return@preparedQuery
}
val rows = ar.result()
if (rows.size() == 0) {
promise.complete(list)
return@preparedQuery
}
for (row in rows) {
val uowSeq = row.getLong("uow_id")
val targetId = row.getInteger("ar_id")
val eventsArray = row.get(JsonArray::class.java, 2)
val jsonToEventPair: (Int) -> Pair<String, DomainEvent> = { index ->
val jsonObject = eventsArray.getJsonObject(index)
val eventName = jsonObject.getString(EVENT_NAME)
val eventJson = jsonObject.getJsonObject(EVENTS_JSON_CONTENT)
jsonFunctions.eventFromJson(eventName, eventJson)
}
val events: List<Pair<String, DomainEvent>> = List(eventsArray.size(), jsonToEventPair)
val projectionData = UnitOfWorkEvents(uowSeq.toLong(), targetId, events)
list.add(projectionData)
}
promise.complete(list)
}
return promise
}
}
| apache-2.0 |
Szewek/Minecraft-Flux | src/main/java/szewek/mcflux/items/ItemMFTool.kt | 1 | 3588 | package szewek.mcflux.items
import net.minecraft.entity.EntityLivingBase
import net.minecraft.entity.player.EntityPlayer
import net.minecraft.item.ItemStack
import net.minecraft.util.EnumActionResult
import net.minecraft.util.EnumFacing
import net.minecraft.util.EnumHand
import net.minecraft.util.math.BlockPos
import net.minecraft.util.text.TextComponentTranslation
import net.minecraft.util.text.TextFormatting
import net.minecraft.world.World
import szewek.fl.FLU
import szewek.mcflux.U
import szewek.mcflux.fluxable.FluxableCapabilities
import szewek.mcflux.fluxcompat.FluxCompat
import szewek.mcflux.tileentities.TileEntityEnergyMachine
class ItemMFTool : ItemMCFlux() {
private val textBlock = TextComponentTranslation("mcflux.blockcompat.start")
private val textEntity = TextComponentTranslation("mcflux.entitycompat.start")
private val textIsCompat = TextComponentTranslation("mcflux.iscompat")
private val textNoCompat = TextComponentTranslation("mcflux.nocompat")
private val textEnergyUnknown = TextComponentTranslation("mcflux.energystatunknown")
private val textWorldChunk = TextComponentTranslation("mcflux.worldchunk")
init {
setMaxStackSize(1)
textIsCompat.style.setColor(TextFormatting.GREEN).bold = true
textNoCompat.style.setColor(TextFormatting.RED).bold = true
}
override fun onItemUse(p: EntityPlayer, w: World, pos: BlockPos, h: EnumHand, f: EnumFacing, x: Float, y: Float, z: Float): EnumActionResult {
if (!w.isRemote) {
val te = w.getTileEntity(pos)
if (te != null) {
if (te is TileEntityEnergyMachine) {
val teem = te as TileEntityEnergyMachine?
if (teem!!.moduleId < 2)
p.sendMessage(TextComponentTranslation("mcflux.transfer", te.getTransferSide(f)))
return EnumActionResult.SUCCESS
}
val ie = FLU.getEnergySafely(te, f)
val tcb = textBlock.createCopy()
tcb.appendSibling(if (ie != null) textIsCompat else textNoCompat).appendSibling(TextComponentTranslation("mcflux.blockcompat.end", f))
p.sendMessage(tcb)
if (ie != null)
p.sendMessage(TextComponentTranslation("mcflux.energystat", U.formatMF(ie)))
if (ie is FluxCompat.Convert)
p.sendMessage(TextComponentTranslation("mcflux.fluxcompat.type", (ie as FluxCompat.Convert).energyType.name))
} else {
val wce = w.getCapability(FluxableCapabilities.CAP_WCE, null)
if (wce != null) {
val bat = wce.getEnergyChunk(p.posX.toInt(), (p.posY + 0.5).toInt(), p.posZ.toInt())
val tcb = textWorldChunk.createCopy()
tcb.appendSibling(TextComponentTranslation("mcflux.energystat", U.formatMF(bat)))
p.sendMessage(tcb)
} else {
return EnumActionResult.PASS
}
}
return EnumActionResult.SUCCESS
} else if (p.isSneaking) {
return EnumActionResult.SUCCESS
}
return EnumActionResult.PASS
}
override fun itemInteractionForEntity(stk: ItemStack, p: EntityPlayer, elb: EntityLivingBase, h: EnumHand): Boolean {
if (!elb.world.isRemote) {
val ie = FLU.getEnergySafely(elb, EnumFacing.UP) // FIXME: SET TO null
val tcb = textEntity.createCopy()
tcb.appendSibling(if (ie != null) textIsCompat else textNoCompat)
tcb.appendSibling(TextComponentTranslation("mcflux.entitycompat.end"))
p.sendMessage(tcb)
if (ie != null) {
val nc = ie.energyCapacity
p.sendMessage(if (nc == 1L) textEnergyUnknown else TextComponentTranslation("mcflux.energystat", U.formatMF(ie)))
}
if (ie is FluxCompat.Convert)
p.sendMessage(TextComponentTranslation("mcflux.fluxcompat.type", (ie as FluxCompat.Convert).energyType.name))
return true
}
return false
}
}
| mit |
ykode/android-kotlin-rxsample | src/main/kotlin/MainActivity.kt | 1 | 2745 | package com.ykode.research.RxKotlinSample
import android.app.Activity
import android.app.Fragment
import android.os.Bundle
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import android.view.View
import android.widget.EditText
import android.widget.Button
import android.graphics.Color
import rx.Observable
import rx.Subscription
import rx.subscriptions.CompositeSubscription
import com.jakewharton.rxbinding.widget.*
import kotlinx.android.synthetic.fragment_main.*
import kotlin.text.Regex
var View.enabled: Boolean
get() = this.isEnabled()
set(value) = this.setEnabled(value)
val Fragment.ctx:Context?
get() = this.activity
class MainActivity : Activity() {
override fun onCreate(savedInstanceState:Bundle?) {
super<Activity>.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (null == savedInstanceState) {
fragmentManager.beginTransaction()
.add(R.id.container, MainFragment())
.commit()
}
}
}
abstract class ReactiveFragment : Fragment() {
private var _compoSub = CompositeSubscription()
private val compoSub: CompositeSubscription
get() {
if (_compoSub.isUnsubscribed()) {
_compoSub = CompositeSubscription()
}
return _compoSub
}
protected final fun manageSub(s: Subscription) = compoSub.add(s)
override fun onDestroyView() {
compoSub.unsubscribe()
super<Fragment>.onDestroyView()
}
}
internal class MainFragment : ReactiveFragment() {
override fun onCreateView(inflater: LayoutInflater?,
container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater?.inflate(R.layout.fragment_main, container, false)
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
val emailPattern = Regex("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+
"[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})${'$'}")
val userNameValid = edtUserName.textChanges().map { t -> t.length > 4 }
val emailValid = edtEmail.textChanges().map { t -> emailPattern in t }
manageSub(emailValid.distinctUntilChanged()
.map{ b -> if (b) Color.WHITE else Color.RED }
.subscribe{ color -> edtEmail.setTextColor(color) })
manageSub(userNameValid.distinctUntilChanged()
.map{ b -> if (b) Color.WHITE else Color.RED }
.subscribe{ color -> edtUserName.setTextColor(color) })
val registerEnabled = Observable.combineLatest(userNameValid, emailValid, {a, b -> a && b})
manageSub(registerEnabled.distinctUntilChanged()
.subscribe{ enabled -> buttonRegister.enabled = enabled })
}
}
| bsd-2-clause |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/api/ConnectionName.kt | 1 | 994 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.api
/** Used to describe a [Connection], specifying whether it's a Read or Write connection. */
sealed class ConnectionName<T : Connection> {
internal abstract val name: Name
data class Reader<T : Connection>(override val name: Name) : ConnectionName<T>()
data class Writer<T : Connection>(override val name: Name) : ConnectionName<T>()
}
| apache-2.0 |
google/private-compute-libraries | java/com/google/android/libraries/pcc/chronicle/remote/handler/Extensions.kt | 1 | 1674 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.remote.handler
import com.google.android.libraries.pcc.chronicle.api.remote.IResponseCallback
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteResponse
import com.google.android.libraries.pcc.chronicle.api.remote.RemoteResponseMetadata
import com.google.android.libraries.pcc.chronicle.api.remote.serialization.Serializer
import com.google.android.libraries.pcc.chronicle.api.storage.WrappedEntity
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.onEach
/**
* Handles a [Flow] of pages of [WrappedEntities][WrappedEntity] by calling
* [IResponseCallback.onData] for each page, using the supplied [serializer] to transform each
* [WrappedEntity] for transmission.
*/
fun <T : Any> Flow<List<WrappedEntity<T>>>.sendEachPage(
callback: IResponseCallback,
serializer: Serializer<T>
): Flow<List<WrappedEntity<T>>> = onEach {
callback.onData(
RemoteResponse(
metadata = RemoteResponseMetadata.newBuilder().build(),
entities = it.map(serializer::serialize)
)
)
}
| apache-2.0 |
mniami/android.kotlin.benchmark | app/src/main/java/guideme/volunteers/ui/fragments/volunteer/details/project/ProjectDetailsPresenter.kt | 2 | 292 | package guideme.volunteers.ui.fragments.volunteer.details.project
import guideme.volunteers.domain.Project
import guideme.volunteers.ui.fragments.base.BasicPresenter
class ProjectDetailsPresenter(val fragment: IProjectDetailsFragment) : BasicPresenter() {
var project: Project? = null
} | apache-2.0 |
AK-47-D/cms | src/main/kotlin/com/ak47/cms/cms/entity/TechArticle.kt | 1 | 629 | package com.ak47.cms.cms.entity
import java.util.*
import javax.persistence.*
@Entity
@Table(indexes = arrayOf(
Index(name = "idx_url", unique = true, columnList = "url")))
open class TechArticle {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long = -1
var url = "URL"
var title = "Kotlin 使用 Spring WebFlux 实现响应式编程"
@Lob
var simpleContent = "文章摘要"
@Lob
var showContent = "文章内容"
// TechArticleTag 表中的 tagId
var tagId = -1
var category = "编程语言"
var gmtCreate = Date()
var gmtModified = Date()
} | apache-2.0 |
fgsguedes/notes | architecture/src/main/java/io/guedes/notes/arch/ARSN.kt | 1 | 117 | package io.guedes.notes.arch
interface BaseAction
interface BaseResult
interface BaseState
interface BaseNavigation
| gpl-3.0 |
shymmq/librus-client-kotlin | app/src/main/kotlin/com/wabadaba/dziennik/vo/EventCategory.kt | 1 | 422 | package com.wabadaba.dziennik.vo
import com.fasterxml.jackson.databind.annotation.JsonDeserialize
import io.requery.Entity
import io.requery.Key
import io.requery.ManyToOne
@Entity
@LibrusEntity("HomeWorks/Categories")
@JsonDeserialize(`as` = EventCategoryEntity::class)
interface EventCategory : Identifiable {
@get:Key
override val id: String
val name: String?
@get:ManyToOne
val color: Color
} | gpl-3.0 |
Tomlezen/FragmentBuilder | annotations/src/main/java/com/tlz/fragmentbuilder/annotation/Serializer.kt | 1 | 353 | package com.tlz.fragmentbuilder.annotation
import kotlin.reflect.KClass
/**
*
* Created by Tomlezen.
* Date: 2017/7/14.
* Time: 10:06.
*/
@MustBeDocumented
@Repeatable
@Retention(AnnotationRetention.SOURCE)
@Target(AnnotationTarget.FIELD)
annotation class Serializer(
val to: KClass<*>,
val serializer: KClass<out ArgsSerializer<*, *>>
) | apache-2.0 |
michaeimm/kmn_bot-tool | app/src/main/java/tw/shounenwind/kmnbottool/gson/GsonHelper.kt | 1 | 754 | package tw.shounenwind.kmnbottool.gson
import android.os.Parcel
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.stream.JsonReader
import java.io.Reader
val gsonInstances: Gson by lazy {
Gson()
}
inline fun <reified T> Gson.fromJson(json: String): T {
return fromJson(json, T::class.java)
}
inline fun <reified T> Gson.fromJson(json: Reader): T {
return fromJson(json, T::class.java)
}
inline fun <reified T> Gson.fromJson(json: JsonElement): T {
return fromJson(json, T::class.java)
}
inline fun <reified T> Gson.fromJson(reader: JsonReader): T {
return fromJson(reader, T::class.java)
}
inline fun <reified T> Parcel.readValue(): T {
return readValue(T::class.java.classLoader) as T
} | apache-2.0 |
willowtreeapps/assertk | assertk/src/commonTest/kotlin/test/assertk/AssertLambdaTest.kt | 1 | 653 | package test.assertk
import assertk.assertThat
import test.assertk.assertions.valueOrFail
import kotlin.test.Test
import kotlin.test.assertEquals
class AssertLambdaTest {
@Test fun successful_assert_lambda_returns_success() {
assertEquals(Result.success(2), assertThat { 1 + 1 }.valueOrFail)
}
@Test fun successful_assert_lambda_returning_null_returns_success() {
assertEquals(Result.success(null), assertThat { null }.valueOrFail)
}
@Test fun failing_assert_lambda_returns_failure() {
val e = Exception("error")
assertEquals(Result.failure<String>(e), assertThat { throw e }.valueOrFail)
}
} | mit |
RP-Kit/RPKit | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/placeholder/RPKPlayersPlaceholderExpansion.kt | 1 | 1868 | /*
* Copyright 2022 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.players.bukkit.placeholder
import com.rpkit.core.service.Services
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.minecraft.RPKMinecraftProfileService
import me.clip.placeholderapi.expansion.PlaceholderExpansion
import org.bukkit.entity.Player
class RPKPlayersPlaceholderExpansion(private val plugin: RPKPlayersBukkit) : PlaceholderExpansion() {
override fun persist() = true
override fun canRegister() = true
override fun getIdentifier() = "rpkplayers"
override fun getAuthor() = plugin.description.authors.joinToString()
override fun getVersion() = plugin.description.version
override fun onPlaceholderRequest(player: Player, params: String): String? {
val minecraftProfileService = Services[RPKMinecraftProfileService::class.java] ?: return null
val minecraftProfile = player.let { minecraftProfileService.getPreloadedMinecraftProfile(it) }
val profile = minecraftProfile?.profile as? RPKProfile
return when (params.lowercase()) {
"minecraftusername" -> minecraftProfile?.name
"profile" -> profile?.name?.plus(profile.discriminator)
else -> null
}
}
} | apache-2.0 |
RP-Kit/RPKit | bukkit/rpk-crafting-skill-bukkit/src/main/kotlin/com/rpkit/craftingskill/bukkit/RPKCraftingSkillBukkit.kt | 1 | 4702 | /*
* Copyright 2022 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.craftingskill.bukkit
import com.rpkit.core.bukkit.listener.registerListeners
import com.rpkit.core.database.Database
import com.rpkit.core.database.DatabaseConnectionProperties
import com.rpkit.core.database.DatabaseMigrationProperties
import com.rpkit.core.database.UnsupportedDatabaseDialectException
import com.rpkit.core.plugin.RPKPlugin
import com.rpkit.core.service.Services
import com.rpkit.craftingskill.bukkit.command.craftingskill.CraftingSkillCommand
import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingSkillService
import com.rpkit.craftingskill.bukkit.craftingskill.RPKCraftingSkillServiceImpl
import com.rpkit.craftingskill.bukkit.database.table.RPKCraftingExperienceTable
import com.rpkit.craftingskill.bukkit.listener.*
import com.rpkit.craftingskill.bukkit.messages.CraftingSkillMessages
import org.bstats.bukkit.Metrics
import org.bukkit.configuration.file.YamlConfiguration
import org.bukkit.plugin.java.JavaPlugin
import java.io.File
class RPKCraftingSkillBukkit : JavaPlugin(), RPKPlugin {
lateinit var database: Database
lateinit var messages: CraftingSkillMessages
override fun onEnable() {
System.setProperty("com.rpkit.craftingskill.bukkit.shadow.impl.org.jooq.no-logo", "true")
System.setProperty("com.rpkit.craftingskill.bukkit.shadow.impl.org.jooq.no-tips", "true")
Metrics(this, 5350)
saveDefaultConfig()
messages = CraftingSkillMessages(this)
val databaseConfigFile = File(dataFolder, "database.yml")
if (!databaseConfigFile.exists()) {
saveResource("database.yml", false)
}
val databaseConfig = YamlConfiguration.loadConfiguration(databaseConfigFile)
val databaseUrl = databaseConfig.getString("database.url")
if (databaseUrl == null) {
logger.severe("Database URL not set!")
isEnabled = false
return
}
val databaseUsername = databaseConfig.getString("database.username")
val databasePassword = databaseConfig.getString("database.password")
val databaseSqlDialect = databaseConfig.getString("database.dialect")
val databaseMaximumPoolSize = databaseConfig.getInt("database.maximum-pool-size", 3)
val databaseMinimumIdle = databaseConfig.getInt("database.minimum-idle", 3)
if (databaseSqlDialect == null) {
logger.severe("Database SQL dialect not set!")
isEnabled = false
return
}
database = Database(
DatabaseConnectionProperties(
databaseUrl,
databaseUsername,
databasePassword,
databaseSqlDialect,
databaseMaximumPoolSize,
databaseMinimumIdle
),
DatabaseMigrationProperties(
when (databaseSqlDialect) {
"MYSQL" -> "com/rpkit/craftingskill/migrations/mysql"
"SQLITE" -> "com/rpkit/craftingskill/migrations/sqlite"
else -> throw UnsupportedDatabaseDialectException("Unsupported database dialect $databaseSqlDialect")
},
"flyway_schema_history_crafting_skill"
),
classLoader
)
database.addTable(RPKCraftingExperienceTable(database, this))
Services[RPKCraftingSkillService::class.java] = RPKCraftingSkillServiceImpl(this)
registerListeners()
registerCommands()
}
private fun registerListeners() {
registerListeners(
RPKCharacterDeleteListener(this),
BlockBreakListener(this),
CraftItemListener(this),
PrepareItemCraftListener(this),
InventoryClickListener(this),
AsyncPlayerPreLoginListener(this),
PlayerQuitListener(this)
)
}
private fun registerCommands() {
getCommand("craftingskill")?.setExecutor(CraftingSkillCommand(this))
}
} | apache-2.0 |
tburch/jsonblob | src/main/kotlin/jsonblob/Application.kt | 1 | 160 | package jsonblob
import io.micronaut.runtime.Micronaut.build
fun main(args: Array<String>) {
build()
.args(*args)
.packages("jsonblob")
.start()
}
| apache-2.0 |
wakim/esl-pod-client | app/src/main/java/br/com/wakim/eslpodclient/android/receiver/ConnectivityBroadcastReceiver.kt | 2 | 942 | package br.com.wakim.eslpodclient.android.receiver
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import br.com.wakim.eslpodclient.Application
import br.com.wakim.eslpodclient.dagger.AppComponent
import javax.inject.Inject
class ConnectivityBroadcastReceiver: BroadcastReceiver() {
companion object {
fun isNetworkConnected(connectivityManager: ConnectivityManager): Boolean = connectivityManager.activeNetworkInfo?.isConnected ?: false
}
@Inject
lateinit var app: Application
override fun onReceive(context: Context, intent: Intent?) {
(context.applicationContext.getSystemService(AppComponent::class.java.simpleName) as AppComponent).inject(this)
app.connected = isNetworkConnected()
}
fun isNetworkConnected(): Boolean {
return isNetworkConnected(app.connectivityManager)
}
} | apache-2.0 |
cketti/k-9 | app/k9mail/src/main/java/com/fsck/k9/widget/list/MessageListWidgetProvider.kt | 1 | 322 | package com.fsck.k9.widget.list
import app.k9mail.ui.widget.list.MessageListWidgetConfig
class MessageListWidgetProvider : app.k9mail.ui.widget.list.MessageListWidgetProvider()
internal class K9MessageListWidgetConfig : MessageListWidgetConfig {
override val providerClass = MessageListWidgetProvider::class.java
}
| apache-2.0 |
itachi1706/CheesecakeUtilities | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/listApplications/objects/RestoreAppsItemsHeader.kt | 1 | 1737 | package com.itachi1706.cheesecakeutilities.modules.listApplications.objects
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import com.itachi1706.cheesecakeutilities.R
/**
* Created by Kenneth on 3/12/2016.
* for com.itachi1706.cheesecakeutilities.modules.AppRestore.Objects in CheesecakeUtilities
*/
data class RestoreAppsItemsHeader(var appName: String? = null, var count: Int = 0, var icon: Drawable? = null, private var child: List<RestoreAppsItemsFooter>? = null) : RestoreAppsItemsBase() {
constructor(appName: String, context: Context) : this(appName = appName, icon = ContextCompat.getDrawable(context, R.mipmap.ic_launcher), child = ArrayList<RestoreAppsItemsFooter>()) {
this.count = this.child!!.size
}
constructor(appName: String, appIcon: Drawable) : this(appName = appName, icon = appIcon, child = ArrayList<RestoreAppsItemsFooter>()) {
this.count = this.child!!.size
}
constructor(appName: String, child: List<RestoreAppsItemsFooter>, context: Context) : this(appName = appName, child = child, icon = ContextCompat.getDrawable(context, R.mipmap.ic_launcher)) {
this.count = this.child!!.size
}
constructor(appName: String, child: List<RestoreAppsItemsFooter>, appIcon: Drawable) : this(appName = appName, child = child, icon = appIcon) {
this.count = this.child!!.size
}
fun getChild(): List<RestoreAppsItemsFooter>? {
return child
}
fun setChild(child: List<RestoreAppsItemsFooter>) {
this.child = child
this.count = this.child!!.size
}
fun hasChild(): Boolean {
return this.child != null && this.child!!.isNotEmpty()
}
}
| mit |
googlearchive/background-tasks-samples | WorkManager/app/src/main/java/com/example/background/FilterActivity.kt | 1 | 5532 | /*
*
* * Copyright (C) 2018 The Android Open Source Project
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.example.background
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import android.widget.Button
import android.widget.Checkable
import android.widget.ImageView
import android.widget.ProgressBar
import androidx.activity.viewModels
import androidx.annotation.IdRes
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import com.bumptech.glide.Glide
/**
* The [android.app.Activity] where the user picks filters to be applied on an
* image.
*/
class FilterActivity : AppCompatActivity() {
private val mViewModel: FilterViewModel by viewModels()
private var mImageUri: Uri? = null
private var mOutputImageUri: Uri? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_processing)
// Don't enable upload to Imgur, unless the developer specifies their own clientId.
val enableUpload = !TextUtils.isEmpty(Constants.IMGUR_CLIENT_ID)
findViewById<View>(R.id.upload).isEnabled = enableUpload
val intent = intent
val imageUriExtra = intent.getStringExtra(Constants.KEY_IMAGE_URI)
if (!TextUtils.isEmpty(imageUriExtra)) {
mImageUri = Uri.parse(imageUriExtra)
val imageView = findViewById<ImageView>(R.id.imageView)
Glide.with(this).load(mImageUri).into(imageView)
}
findViewById<View>(R.id.go).setOnClickListener {
val applyWaterColor = isChecked(R.id.filter_watercolor)
val applyGrayScale = isChecked(R.id.filter_grayscale)
val applyBlur = isChecked(R.id.filter_blur)
val save = isChecked(R.id.save)
val upload = isChecked(R.id.upload)
val imageOperations = ImageOperations.Builder(applicationContext, mImageUri!!)
.setApplyWaterColor(applyWaterColor)
.setApplyGrayScale(applyGrayScale)
.setApplyBlur(applyBlur)
.setApplySave(save)
.setApplyUpload(upload)
.build()
mViewModel.apply(imageOperations)
}
findViewById<View>(R.id.output).setOnClickListener {
if (mOutputImageUri != null) {
val actionView = Intent(Intent.ACTION_VIEW, mOutputImageUri)
if (actionView.resolveActivity(packageManager) != null) {
startActivity(actionView)
}
}
}
findViewById<View>(R.id.cancel).setOnClickListener { mViewModel.cancel() }
// Check to see if we have output.
mViewModel.outputStatus.observe(this, Observer { listOfInfos ->
if (listOfInfos == null || listOfInfos.isEmpty()) {
return@Observer
}
// We only care about the one output status.
// Every continuation has only one worker tagged TAG_OUTPUT
val info = listOfInfos[0]
val finished = info.state.isFinished
val progressBar = findViewById<ProgressBar>(R.id.progressBar)
val go = findViewById<Button>(R.id.go)
val cancel = findViewById<Button>(R.id.cancel)
val output = findViewById<Button>(R.id.output)
if (!finished) {
progressBar.visibility = View.VISIBLE
cancel.visibility = View.VISIBLE
go.visibility = View.GONE
output.visibility = View.GONE
} else {
progressBar.visibility = View.GONE
cancel.visibility = View.GONE
go.visibility = View.VISIBLE
val outputData = info.outputData
val outputImageUri = outputData.getString(Constants.KEY_IMAGE_URI)
if (!TextUtils.isEmpty(outputImageUri)) {
mOutputImageUri = Uri.parse(outputImageUri)
output.visibility = View.VISIBLE
}
}
})
}
private fun isChecked(@IdRes resourceId: Int): Boolean {
val view = findViewById<View>(resourceId)
return view is Checkable && (view as Checkable).isChecked
}
companion object {
/**
* Creates a new intent which can be used to start [FilterActivity].
*
* @param context the application [Context].
* @param imageUri the input image [Uri].
* @return the instance of [Intent].
*/
internal fun newIntent(context: Context, imageUri: Uri): Intent {
val intent = Intent(context, FilterActivity::class.java)
intent.putExtra(Constants.KEY_IMAGE_URI, imageUri.toString())
return intent
}
}
}
| apache-2.0 |
alexmonthy/lttng-scope | lttng-scope/src/main/kotlin/org/lttng/scope/common/jfx/Logo.kt | 2 | 2601 | /*
* Copyright (C) 2017-2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.lttng.scope.common.jfx
import javafx.animation.Animation
import javafx.animation.Interpolator
import javafx.animation.RotateTransition
import javafx.application.Application
import javafx.application.Application.launch
import javafx.scene.Group
import javafx.scene.Scene
import javafx.scene.layout.Pane
import javafx.scene.paint.Color
import javafx.scene.shape.Circle
import javafx.scene.shape.Rectangle
import javafx.stage.Stage
import javafx.util.Duration
fun main(args: Array<String>) {
launch(Logo::class.java, *args)
}
class Logo : Application() {
companion object {
private const val BACKGROUND_STYLE = "-fx-background-color: rgba(255, 255, 255, 255);"
private val LTTNG_PURPLE: Color = Color.web("#996ABC")
private val LTTNG_LIGHT_BLUE: Color = Color.web("#C3DEF4")
}
override fun start(stage: Stage?) {
stage ?: return
val clipRect1 = Rectangle(-130.0, -130.0, 115.0, 115.0)
val clipRect2 = Rectangle(15.0, -130.0, 115.0, 115.0)
val clipRect3 = Rectangle(-130.0, 15.0, 115.0, 115.0)
val clipRect4 = Rectangle(15.0, 15.0, 115.0, 115.0)
val clip = Group(clipRect1, clipRect2, clipRect3, clipRect4)
val spinnanCircle = Circle(100.0)
spinnanCircle.setFill(null);
spinnanCircle.setStrokeWidth(30.0);
spinnanCircle.setStroke(LTTNG_PURPLE);
spinnanCircle.setClip(clip);
val magCircle = Circle(60.0);
magCircle.setFill(null);
magCircle.setStrokeWidth(25.0);
magCircle.setStroke(LTTNG_LIGHT_BLUE);
val magHandle = Rectangle(-12.5, 60.0, 25.0, 110.0);
magHandle.setFill(LTTNG_LIGHT_BLUE);
val mag = Group(magCircle, magHandle);
val root = Group(spinnanCircle, mag);
root.setRotate(30.0)
root.relocate(0.0, 0.0)
val pane = Pane(root);
pane.setStyle(BACKGROUND_STYLE);
val spinnan = RotateTransition(Duration.seconds(4.0), spinnanCircle);
spinnan.setByAngle(360.0);
spinnan.setCycleCount(Animation.INDEFINITE);
spinnan.setInterpolator(Interpolator.LINEAR);
val scene = Scene(pane);
stage.setScene(scene);
stage.show();
spinnan.play();
}
}
| epl-1.0 |
lijunzz/LongChuanGang | app/src/main/kotlin/net/junzz/app/lcg/ListAdapter.kt | 1 | 1088 | package net.junzz.app.lcg
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import net.junzz.app.ui.widget.RoundAvatar
class ListAdapter(val data: List<ListItemDO>) : RecyclerView.Adapter<ListAdapter.ListHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
= ListHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item, parent, false))
override fun getItemCount() = data.size
override fun onBindViewHolder(holder: ListHolder, position: Int) {
holder.avatarView.setImageAvatar(data[position].avatar)
holder.titleView.text = data[position].title
}
class ListHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val categoryView = itemView.findViewById<TextView>(R.id.tv_list_item_category)
val avatarView = itemView.findViewById<RoundAvatar>(R.id.ra_list_item_avatar)
val titleView = itemView.findViewById<TextView>(R.id.tv_list_item_title)
}
} | gpl-3.0 |
ujpv/intellij-rust | src/test/kotlin/org/rust/lang/utils/RustEscapesUtilsTest.kt | 1 | 2773 | package org.rust.lang.utils
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class UnescapeRustTest(private val input: String,
private val expected: String,
private val unicode: Boolean,
private val eol: Boolean,
private val extendedByte: Boolean) {
@Test
fun test() = assertEquals(expected, input.unescapeRust(unicode, eol, extendedByte))
companion object {
@Parameterized.Parameters(name = "{index}: \"{0}\" → \"{1}\" U:{2} E:{3}")
@JvmStatic fun data(): Collection<Array<Any>> = listOf(
arrayOf("aaa", "aaa", true, true, false),
arrayOf("aaa", "aaa", false, false, false),
arrayOf("a\\na", "a\na", true, true, false),
arrayOf("a\\ra", "a\ra", true, true, false),
arrayOf("a\\ta", "a\ta", true, true, false),
arrayOf("a\\0a", "a\u0000a", true, true, false),
arrayOf("a\\'a", "a'a", true, true, false),
arrayOf("a\\\"a", "a\"a", true, true, false),
arrayOf("a\\\\a", "a\\a", true, true, false),
arrayOf("a\\x20a", "a a", true, true, false),
arrayOf("a\\x0aa", "a\na", true, true, false),
arrayOf("a\\x0Aa", "a\na", true, true, false),
arrayOf("foo\\\n bar", "foobar", true, true, false),
arrayOf("foo\\\r\n bar", "foobar", true, true, false),
arrayOf("foo\\\r\n bar", "foo\\\r\n bar", true, false, false),
arrayOf("foo\\r\\nbar", "foo\r\nbar", true, true, false),
arrayOf("\\u{0119}dw\\u{0105}rd", "\u0119dw\u0105rd", true, true, false),
arrayOf("\\u{0119}dw\\u{0105}rd", "\\u{0119}dw\\u{0105}rd", false, true, false),
arrayOf("\\u{0}", "\u0000", true, true, false),
arrayOf("\\u{00}", "\u0000", true, true, false),
arrayOf("\\u{000}", "\u0000", true, true, false),
arrayOf("\\u{0000}", "\u0000", true, true, false),
arrayOf("\\u{00000}", "\u0000", true, true, false),
arrayOf("\\u{000000}", "\u0000", true, true, false),
arrayOf("\\u{0000000}", "\\u{0000000}", true, true, false),
arrayOf("\\u{00000000}", "\\u{00000000}", true, true, false),
arrayOf("\\u{}", "\\u{}", true, true, false),
arrayOf("\\u{", "\\u{", true, true, false),
arrayOf("\\u", "\\u", true, true, false),
arrayOf("\\u{zzzz}", "\\u{zzzz}", true, true, false),
arrayOf("\\xff", "\\xff", true, true, false),
arrayOf("\\xff", "\u00ff", true, true, true)
)
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.