repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
dahlstrom-g/intellij-community | plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/hint/GroovyInlayParameterHintsProvider.kt | 8 | 4176 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.codeInsight.hint
import com.intellij.codeInsight.hints.HintInfo.MethodInfo
import com.intellij.codeInsight.hints.InlayInfo
import com.intellij.codeInsight.hints.InlayParameterHintsProvider
import com.intellij.lang.Language
import com.intellij.lang.java.JavaLanguage
import com.intellij.openapi.util.text.StringUtil
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMirrorElement
import org.jetbrains.plugins.groovy.GroovyBundle
import org.jetbrains.plugins.groovy.editor.shouldHideInlayHints
import org.jetbrains.plugins.groovy.lang.psi.api.GrFunctionalExpression
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyMethodResult
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrUnaryExpression
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral
import org.jetbrains.plugins.groovy.lang.resolve.api.ExpressionArgument
import org.jetbrains.plugins.groovy.lang.resolve.api.PsiCallParameter
class GroovyInlayParameterHintsProvider : InlayParameterHintsProvider {
override fun getParameterHints(element: PsiElement): List<InlayInfo> {
if (element !is GrCall) return emptyList()
if (shouldHideInlayHints(element)) return emptyList()
return element.doGetParameterHints() ?: emptyList()
}
override fun getHintInfo(element: PsiElement): MethodInfo? {
val call = element as? GrCall
val resolved = call?.resolveMethod()
val method = (resolved as? PsiMirrorElement)?.prototype as? PsiMethod ?: resolved
return method?.getMethodInfo()
}
private fun PsiMethod.getMethodInfo(): MethodInfo? {
val clazzName = containingClass?.qualifiedName ?: return null
val fullMethodName = StringUtil.getQualifiedName(clazzName, name)
val paramNames: List<String> = parameterList.parameters.map { it.name }
return MethodInfo(fullMethodName, paramNames, if (language == blackListDependencyLanguage) language else null)
}
override fun getDefaultBlackList(): Set<String> = blackList
override fun getBlackListDependencyLanguage(): Language = JavaLanguage.INSTANCE
override fun getDescription(): String = GroovyBundle.message("shows.parameter.names.at.function.call.sites")
private companion object {
private val blackList = setOf(
"org.codehaus.groovy.runtime.DefaultGroovyMethods.*"
)
private fun GrCall.doGetParameterHints(): List<InlayInfo>? {
val argumentList = argumentList ?: return null
val result = advancedResolve() as? GroovyMethodResult ?: return null
val mapping = result.candidate?.argumentMapping ?: return null
val map: Map<PsiCallParameter, List<GrExpression>> = argumentList.expressionArguments
.asSequence()
.map(::ExpressionArgument)
.mapNotNull { arg ->
val parameter = mapping.targetParameter(arg)
parameter?.let { Pair(it, arg.expression) }
}
.groupBy({ it.first }, { it.second })
val varargParameter = mapping.varargParameter
val inlays = ArrayList<InlayInfo>(map.size)
for ((parameter, expressions) in map) {
val name = parameter.parameterName ?: continue
if (expressions.none(::shouldShowHint)) continue
val inlayText = if (parameter === varargParameter) "...$name" else name
inlays += InlayInfo(inlayText, expressions.first().textRange.startOffset)
}
return inlays
}
/**
* Show:
* - regular literal arguments
* - varargs which contain literals
* - prefix unary expressions with numeric literal arguments
*/
private fun shouldShowHint(arg: PsiElement): Boolean = when (arg) {
is GrFunctionalExpression -> true
is GrLiteral -> true
is GrUnaryExpression -> (arg.operand as? GrLiteral)?.value is Number
else -> false
}
}
}
| apache-2.0 | 988708551f4cfaebd7000c3ca0f16403 | 42.5 | 140 | 0.749282 | 4.660714 | false | false | false | false |
androidx/androidx | compose/animation/animation/integration-tests/animation-demos/src/main/java/androidx/compose/animation/demos/lookahead/SharedElementExplorationDemo.kt | 3 | 3344 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.animation.demos.lookahead
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.movableContentWithReceiverOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun SharedElementExplorationDemo() {
val A = remember {
movableContentWithReceiverOf<SceneScope, Modifier> { modifier ->
Box(
modifier = Modifier
.sharedElement().then(modifier)
.background(color = Color(0xfff3722c), RoundedCornerShape(10))
)
}
}
val B = remember {
movableContentWithReceiverOf<SceneScope, Modifier> { modifier ->
Box(
modifier = Modifier
.sharedElement().then(modifier)
.background(color = Color(0xff90be6d), RoundedCornerShape(10))
)
}
}
val C = remember {
movableContentWithReceiverOf<SceneScope, @Composable () -> Unit> { content ->
Box(Modifier.sharedElement().background(Color(0xfff9c74f)).padding(20.dp)) {
content()
}
}
}
var isHorizontal by remember { mutableStateOf(true) }
SceneHost(Modifier.fillMaxSize().clickable { isHorizontal = !isHorizontal }) {
Box(contentAlignment = Alignment.Center) {
if (isHorizontal) {
C {
Row(Modifier.background(Color.Gray).padding(10.dp)) {
A(Modifier.size(40.dp))
B(Modifier.size(40.dp))
Box(Modifier.size(40.dp).background(Color(0xff4d908e)))
}
}
} else {
C {
Column(Modifier.background(Color.DarkGray).padding(10.dp)) {
A(Modifier.size(width = 120.dp, height = 60.dp))
B(Modifier.size(width = 120.dp, height = 60.dp))
}
}
}
}
}
} | apache-2.0 | 5ed8055fb8192e1124caa558dda8a15e | 36.166667 | 88 | 0.644139 | 4.618785 | false | false | false | false |
GunoH/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ContentFolderBridge.kt | 2 | 5914 | package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.roots.ContentFolder
import com.intellij.openapi.roots.ExcludeFolder
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.pointers.VirtualFilePointer
import com.intellij.workspaceModel.storage.bridgeEntities.addJavaSourceRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.SourceRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaResourceRoot
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaSourceRoot
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.java.JavaModuleSourceRootTypes
import org.jetbrains.jps.model.module.JpsModuleSourceRoot
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.module.UnknownSourceRootType
import org.jetbrains.jps.model.serialization.JpsModelSerializerExtension
import com.intellij.workspaceModel.storage.bridgeEntities.modifyEntity
internal abstract class ContentFolderBridge(private val entry: ContentEntryBridge, private val contentFolderUrl: VirtualFileUrl) : ContentFolder {
override fun getContentEntry(): ContentEntryBridge = entry
override fun getUrl(): String = contentFolderUrl.url
override fun isSynthetic(): Boolean = false
override fun equals(other: Any?): Boolean = contentFolderUrl == (other as? ContentFolderBridge)?.contentFolderUrl
override fun hashCode(): Int = contentFolderUrl.hashCode()
}
internal class SourceFolderBridge(private val entry: ContentEntryBridge, val sourceRootEntity: SourceRootEntity)
: ContentFolderBridge(entry, sourceRootEntity.url), SourceFolder {
override fun getFile(): VirtualFile? {
val virtualFilePointer = sourceRootEntity.url as VirtualFilePointer
return virtualFilePointer.file
}
private var packagePrefixVar: String? = null
private val sourceRootType: JpsModuleSourceRootType<out JpsElement> = getSourceRootType(sourceRootEntity)
override fun getRootType() = sourceRootType
override fun isTestSource() = sourceRootType.isForTests
override fun getPackagePrefix() = packagePrefixVar ?:
sourceRootEntity.asJavaSourceRoot()?.packagePrefix ?:
sourceRootEntity.asJavaResourceRoot()?.relativeOutputPath?.replace('/', '.') ?: ""
override fun getJpsElement(): JpsModuleSourceRoot {
return entry.model.getOrCreateJpsRootProperties(sourceRootEntity.url) {
SourceRootPropertiesHelper.loadRootProperties(sourceRootEntity, rootType, url)
}
}
override fun <P : JpsElement> changeType(newType: JpsModuleSourceRootType<P>, properties: P) {
(ModuleRootManager.getInstance(contentEntry.rootModel.module) as ModuleRootComponentBridge).dropRootModelCache()
}
override fun hashCode() = entry.url.hashCode()
override fun equals(other: Any?): Boolean {
if (other !is SourceFolderBridge) return false
if (sourceRootEntity.url != other.sourceRootEntity.url) return false
if (sourceRootEntity.rootType != other.sourceRootEntity.rootType) return false
val javaSourceRoot = sourceRootEntity.asJavaSourceRoot()
val otherJavaSourceRoot = other.sourceRootEntity.asJavaSourceRoot()
if (javaSourceRoot?.generated != otherJavaSourceRoot?.generated) return false
if (javaSourceRoot?.packagePrefix != otherJavaSourceRoot?.packagePrefix) return false
val javaResourceRoot = sourceRootEntity.asJavaResourceRoot()
val otherJavaResourceRoot = other.sourceRootEntity.asJavaResourceRoot()
if (javaResourceRoot?.generated != otherJavaResourceRoot?.generated) return false
if (javaResourceRoot?.relativeOutputPath != otherJavaResourceRoot?.relativeOutputPath) return false
val customRoot = sourceRootEntity.customSourceRootProperties
val otherCustomRoot = other.sourceRootEntity.customSourceRootProperties
if (customRoot?.propertiesXmlTag != otherCustomRoot?.propertiesXmlTag) return false
return true
}
override fun setPackagePrefix(packagePrefix: String) {
if (getPackagePrefix() == packagePrefix) return
val updater = entry.updater ?: error("Model is read-only")
val javaSourceRoot = sourceRootEntity.asJavaSourceRoot()
if (javaSourceRoot == null) {
val javaResourceRoot = sourceRootEntity.asJavaResourceRoot()
// Original setPackagePrefix silently does nothing on any non-java-source-roots
if (javaResourceRoot != null) return
updater { diff ->
diff.addJavaSourceRootEntity(sourceRootEntity, false, packagePrefix)
}
}
else {
updater { diff ->
diff.modifyEntity(javaSourceRoot) {
this.packagePrefix = packagePrefix
}
}
}
//we need to also update package prefix in Jps root properties, otherwise this change will be lost if some code changes some other
// property (e.g. 'forGeneratedProperties') in Jps root later
jpsElement.getProperties(JavaModuleSourceRootTypes.SOURCES)?.packagePrefix = packagePrefix
packagePrefixVar = packagePrefix
}
private fun getSourceRootType(entity: SourceRootEntity): JpsModuleSourceRootType<out JpsElement> {
return SourceRootTypeRegistry.getInstance().findTypeById(entity.rootType) ?: UnknownSourceRootType.getInstance(entity.rootType)
}
companion object {
val LOG by lazy { logger<ContentFolderBridge>() }
}
}
internal class ExcludeFolderBridge(val entry: ContentEntryBridge, val excludeFolderUrl: VirtualFileUrl)
: ContentFolderBridge(entry, excludeFolderUrl), ExcludeFolder {
override fun getFile(): VirtualFile? {
val virtualFilePointer = excludeFolderUrl as VirtualFilePointer
return virtualFilePointer.file
}
}
| apache-2.0 | 960b0070baad1526cb9c67be40e6cb07 | 45.936508 | 146 | 0.785255 | 5.285076 | false | false | false | false |
GunoH/intellij-community | platform/lang-api/src/com/intellij/refactoring/suggested/SuggestedRefactoringUI.kt | 8 | 4385 | // 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.refactoring.suggested
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.psi.PsiCodeFragment
import com.intellij.refactoring.suggested.SuggestedRefactoringExecution.NewParameterValue
import com.intellij.refactoring.suggested.SuggestedRefactoringSupport.Signature
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
/**
* A service providing information required for building user-interface of Change Signature refactoring.
*/
abstract class SuggestedRefactoringUI {
/**
* Creates an instance of helper [SignaturePresentationBuilder] class which is used to build [SignatureChangePresentationModel].
* @param signature signature (either old or new) to build presentation for
* @param otherSignature other signature (either new or old)
* @param isOldSignature true if [signature] represents the old signature, or false otherwise
*/
abstract fun createSignaturePresentationBuilder(
signature: Signature,
otherSignature: Signature,
isOldSignature: Boolean
): SignaturePresentationBuilder
open fun buildSignatureChangePresentation(oldSignature: Signature, newSignature: Signature): SignatureChangePresentationModel {
val oldSignaturePresentation = createSignaturePresentationBuilder(oldSignature, newSignature, isOldSignature = true)
.apply { buildPresentation() }
.result
val newSignaturePresentation = createSignaturePresentationBuilder(newSignature, oldSignature, isOldSignature = false)
.apply { buildPresentation() }
.result
val model = SignatureChangePresentationModel(oldSignaturePresentation, newSignaturePresentation)
return model.improvePresentation()
}
data class NewParameterData constructor(
@Nls val presentableName: String,
val valueFragment: PsiCodeFragment,
val offerToUseAnyVariable: Boolean,
@Nls(capitalization = Nls.Capitalization.Sentence) val placeholderText: String? = null,
val additionalData: NewParameterAdditionalData? = null,
val suggestRename: Boolean = false
) {
@Deprecated("For compatibility", level = DeprecationLevel.HIDDEN)
@JvmOverloads
constructor(
presentableName: @Nls String,
valueFragment: PsiCodeFragment,
offerToUseAnyVariable: Boolean,
placeholderText: @Nls(capitalization = Nls.Capitalization.Sentence) String? = null,
additionalData: NewParameterAdditionalData? = null,
) : this(presentableName, valueFragment, offerToUseAnyVariable, placeholderText, additionalData, false)
}
/**
* Language-specific information to be stored in [NewParameterData].
*
* Don't put any PSI-related objects here.
*/
interface NewParameterAdditionalData {
override fun equals(other: Any?): Boolean
}
/**
* Extracts data about new parameters to offer the user to specify its values for updating calls.
*/
abstract fun extractNewParameterData(data: SuggestedChangeSignatureData): List<NewParameterData>
/**
* Validates value for [data] typed in [component].
* This method should be very fast since it is called on any change for any parameter even if the updated parameter is not [data].
*/
open fun validateValue(data: NewParameterData, component: JComponent?): ValidationInfo? = null
/**
* Extracts value for a new parameter from code fragment after its editing by the user.
* @return entered expression or *null* if no expression in the code fragment
*/
abstract fun extractValue(fragment: PsiCodeFragment): NewParameterValue.Expression?
/**
* Use this implementation of [SuggestedRefactoringUI], if only Rename refactoring is supported for the language.
*/
object RenameOnly : SuggestedRefactoringUI() {
override fun createSignaturePresentationBuilder(
signature: Signature,
otherSignature: Signature,
isOldSignature: Boolean
): SignaturePresentationBuilder {
throw UnsupportedOperationException()
}
override fun extractNewParameterData(data: SuggestedChangeSignatureData): List<NewParameterData> {
throw UnsupportedOperationException()
}
override fun extractValue(fragment: PsiCodeFragment): NewParameterValue.Expression? {
throw UnsupportedOperationException()
}
}
} | apache-2.0 | 766e177b09df69b81b6c29e6bb044251 | 39.990654 | 140 | 0.766477 | 5.276775 | false | false | false | false |
siosio/intellij-community | plugins/devkit/devkit-core/src/formConversion/ConvertFormNotificationProvider.kt | 1 | 1864 | // 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 org.jetbrains.idea.devkit.formConversion
import com.intellij.openapi.fileEditor.FileEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Key
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiManager
import com.intellij.psi.search.ProjectScope
import com.intellij.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.intellij.ui.LightColors
import com.intellij.uiDesigner.editor.UIFormEditor
import org.jetbrains.idea.devkit.DevKitBundle
import org.jetbrains.idea.devkit.util.PsiUtil
class ConvertFormNotificationProvider : EditorNotifications.Provider<EditorNotificationPanel>() {
companion object {
private val KEY = Key.create<EditorNotificationPanel>("convert.form.notification.panel")
}
override fun getKey(): Key<EditorNotificationPanel> = KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (fileEditor !is UIFormEditor) return null
if (!PsiUtil.isIdeaProject(project)) return null
val formPsiFile = PsiManager.getInstance(project).findFile(file) ?: return null
val classToBind = fileEditor.editor.rootContainer.classToBind ?: return null
val psiClass = JavaPsiFacade.getInstance(project).findClass(classToBind, ProjectScope.getProjectScope(project)) ?: return null
return EditorNotificationPanel(LightColors.RED).apply {
setText(DevKitBundle.message("convert.form.editor.notification.label"))
createActionLabel(DevKitBundle.message("convert.form.editor.notification.link.convert")) {
convertFormToUiDsl(psiClass, formPsiFile)
}
}
}
}
| apache-2.0 | f6c0312efea62fa3517c6ca15b851f6e | 44.463415 | 140 | 0.800966 | 4.579853 | false | false | false | false |
vovagrechka/fucking-everything | alraune/alraune/src/main/java/alraune/entities.kt | 1 | 327 | package alraune
import vgrechka.*
import java.sql.Timestamp
object AlUserParams_DBMeta {
val table = "user_params"
val kind = "kind"
val email = "email"
val entityID = "entityID"
val state = "state"
val profileUpdatedAt = "profileUpdatedAt"
val createdAt = "createdAt"
}
| apache-2.0 | 6c16881013342bbc81aa77bda9fc5ce4 | 7.175 | 45 | 0.623853 | 3.939759 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/SpecifyTypeExplicitlyInDestructuringAssignmentIntention.kt | 4 | 2248 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.psi.KtCodeFragment
import org.jetbrains.kotlin.psi.KtDestructuringDeclaration
import org.jetbrains.kotlin.psi.KtParameterList
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getParentOfType
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.types.isError
class SpecifyTypeExplicitlyInDestructuringAssignmentIntention : SelfTargetingRangeIntention<KtDestructuringDeclaration>(
KtDestructuringDeclaration::class.java, KotlinBundle.lazyMessage("specify.all.types.explicitly.in.destructuring.declaration")
), LowPriorityAction {
override fun applicabilityRange(element: KtDestructuringDeclaration): TextRange? {
if (element.containingFile is KtCodeFragment) return null
val entries = element.noTypeReferenceEntries()
if (entries.isEmpty()) return null
if (entries.any { SpecifyTypeExplicitlyIntention.getTypeForDeclaration(it).isError }) return null
return TextRange(element.startOffset, element.initializer?.let { it.startOffset - 1 } ?: element.endOffset)
}
override fun applyTo(element: KtDestructuringDeclaration, editor: Editor?) {
val entries = element.noTypeReferenceEntries()
if (editor != null && element.getParentOfType<KtParameterList>(false) == null)
SpecifyTypeExplicitlyIntention.addTypeAnnotationWithTemplate(editor, entries.iterator())
else
entries.forEach {
it.setType(SpecifyTypeExplicitlyIntention.getTypeForDeclaration(it))
}
}
}
private fun KtDestructuringDeclaration.noTypeReferenceEntries() = entries.filter { it.typeReference == null }
| apache-2.0 | 9a53373e69053474f34d86b27edeb140 | 53.829268 | 158 | 0.790036 | 4.973451 | false | false | false | false |
smmribeiro/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/service/GHPRCommentServiceImpl.kt | 2 | 2754 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data.service
import com.intellij.collaboration.async.CompletableFutureUtil.submitIOTask
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import org.jetbrains.plugins.github.api.GHGQLRequests
import org.jetbrains.plugins.github.api.GHRepositoryCoordinates
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.data.GithubIssueCommentWithHtml
import org.jetbrains.plugins.github.pullrequest.data.GHPRIdentifier
import org.jetbrains.plugins.github.pullrequest.data.service.GHServiceUtil.logError
import java.util.concurrent.CompletableFuture
class GHPRCommentServiceImpl(private val progressManager: ProgressManager,
private val requestExecutor: GithubApiRequestExecutor,
private val repository: GHRepositoryCoordinates) : GHPRCommentService {
override fun addComment(progressIndicator: ProgressIndicator,
pullRequestId: GHPRIdentifier,
body: String): CompletableFuture<GithubIssueCommentWithHtml> {
return progressManager.submitIOTask(progressIndicator) {
val comment = requestExecutor.execute(
GithubApiRequests.Repos.Issues.Comments.create(repository, pullRequestId.number, body))
comment
}.logError(LOG, "Error occurred while adding PR comment")
}
override fun getCommentMarkdownBody(progressIndicator: ProgressIndicator, commentId: String): CompletableFuture<String> =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(GHGQLRequests.Comment.getCommentBody(repository.serverPath, commentId))
}.logError(LOG, "Error occurred while loading comment source")
override fun updateComment(progressIndicator: ProgressIndicator, commentId: String, text: String) =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(GHGQLRequests.Comment.updateComment(repository.serverPath, commentId, text))
}.logError(LOG, "Error occurred while updating comment")
override fun deleteComment(progressIndicator: ProgressIndicator, commentId: String) =
progressManager.submitIOTask(progressIndicator) {
requestExecutor.execute(GHGQLRequests.Comment.deleteComment(repository.serverPath, commentId))
}.logError(LOG, "Error occurred while deleting comment")
companion object {
private val LOG = logger<GHPRCommentService>()
}
} | apache-2.0 | cf03ca7b21be6bc10698e60346d7c27e | 55.22449 | 140 | 0.790487 | 5.389432 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/common/src/org/jetbrains/kotlin/idea/util/TypeUtils.kt | 2 | 13048 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("TypeUtils")
package org.jetbrains.kotlin.idea.util
import com.intellij.psi.*
import org.jetbrains.kotlin.builtins.getReturnTypeFromFunctionType
import org.jetbrains.kotlin.builtins.isBuiltinFunctionalType
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMapper
import org.jetbrains.kotlin.builtins.replaceReturnType
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.FilteredAnnotations
import org.jetbrains.kotlin.descriptors.impl.ClassDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.MutablePackageFragmentDescriptor
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.imports.canBeReferencedViaImport
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.MUTABLE_ANNOTATIONS
import org.jetbrains.kotlin.load.java.NULLABILITY_ANNOTATIONS
import org.jetbrains.kotlin.load.java.READ_ONLY_ANNOTATIONS
import org.jetbrains.kotlin.load.java.components.TypeUsage
import org.jetbrains.kotlin.load.java.lazy.JavaResolverComponents
import org.jetbrains.kotlin.load.java.lazy.LazyJavaResolverContext
import org.jetbrains.kotlin.load.java.lazy.TypeParameterResolver
import org.jetbrains.kotlin.load.java.lazy.child
import org.jetbrains.kotlin.load.java.lazy.descriptors.LazyJavaTypeParameterDescriptor
import org.jetbrains.kotlin.load.java.lazy.types.JavaTypeAttributes
import org.jetbrains.kotlin.load.java.lazy.types.JavaTypeResolver
import org.jetbrains.kotlin.load.java.structure.JavaTypeParameter
import org.jetbrains.kotlin.load.java.structure.impl.JavaTypeImpl
import org.jetbrains.kotlin.load.java.structure.impl.JavaTypeParameterImpl
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
import org.jetbrains.kotlin.resolve.scopes.utils.findClassifier
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.typeUtil.*
import org.jetbrains.kotlin.utils.SmartSet
fun KotlinType.approximateFlexibleTypes(
preferNotNull: Boolean = false,
preferStarForRaw: Boolean = false
): KotlinType {
if (isDynamic()) return this
return unwrapEnhancement().approximateNonDynamicFlexibleTypes(preferNotNull, preferStarForRaw)
}
fun KotlinType.withoutRedundantAnnotations(): KotlinType {
var argumentsWasChanged = false
val newArguments = arguments.map(fun(typeProjection: TypeProjection): TypeProjection {
if (typeProjection.isStarProjection) return typeProjection
val newType = typeProjection.type.withoutRedundantAnnotations()
if (typeProjection.type === newType) return typeProjection
argumentsWasChanged = true
return typeProjection.replaceType(newType)
})
val newAnnotations = FilteredAnnotations(
annotations,
isDefinitelyNewInference = true,
fqNameFilter = { !it.isRedundantJvmAnnotation },
)
val annotationsWasChanged = newAnnotations.count() != annotations.count()
if (!argumentsWasChanged && !annotationsWasChanged) return this
return replace(
newArguments = newArguments.takeIf { argumentsWasChanged } ?: arguments,
newAnnotations = newAnnotations.takeIf { annotationsWasChanged } ?: annotations,
)
}
val FqName.isRedundantJvmAnnotation: Boolean get() = this in NULLABILITY_ANNOTATIONS ||
this in MUTABLE_ANNOTATIONS ||
this in READ_ONLY_ANNOTATIONS
private fun KotlinType.approximateNonDynamicFlexibleTypes(
preferNotNull: Boolean = false,
preferStarForRaw: Boolean = false
): SimpleType {
if (this is ErrorType) return this
if (isFlexible()) {
val flexible = asFlexibleType()
val lowerBound = flexible.lowerBound
val upperBound = flexible.upperBound
val lowerClass = lowerBound.constructor.declarationDescriptor as? ClassDescriptor?
val isCollection = lowerClass != null && JavaToKotlinClassMapper.isMutable(lowerClass)
// (Mutable)Collection<T>! -> MutableCollection<T>?
// Foo<(Mutable)Collection<T>!>! -> Foo<Collection<T>>?
// Foo! -> Foo?
// Foo<Bar!>! -> Foo<Bar>?
var approximation =
if (isCollection)
// (Mutable)Collection<T>!
if (lowerBound.isMarkedNullable != upperBound.isMarkedNullable)
lowerBound.makeNullableAsSpecified(!preferNotNull)
else
lowerBound
else
if (this is RawType && preferStarForRaw) upperBound.makeNullableAsSpecified(!preferNotNull)
else
if (preferNotNull) lowerBound else upperBound
approximation = approximation.approximateNonDynamicFlexibleTypes()
approximation = if (nullability() == TypeNullability.NOT_NULL) approximation.makeNullableAsSpecified(false) else approximation
if (approximation.isMarkedNullable && !lowerBound
.isMarkedNullable && TypeUtils.isTypeParameter(approximation) && TypeUtils.hasNullableSuperType(approximation)
) {
approximation = approximation.makeNullableAsSpecified(false)
}
return approximation
}
(unwrap() as? AbbreviatedType)?.let {
return AbbreviatedType(it.expandedType, it.abbreviation.approximateNonDynamicFlexibleTypes(preferNotNull))
}
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
annotations,
constructor,
arguments.map { it.substitute { type -> type.approximateFlexibleTypes(preferNotNull = true) } },
isMarkedNullable,
ErrorUtils.createErrorScope("This type is not supposed to be used in member resolution", true)
)
}
fun KotlinType.isResolvableInScope(scope: LexicalScope?, checkTypeParameters: Boolean, allowIntersections: Boolean = false): Boolean {
if (constructor is IntersectionTypeConstructor) {
if (!allowIntersections) return false
return constructor.supertypes.all { it.isResolvableInScope(scope, checkTypeParameters, allowIntersections) }
}
if (canBeReferencedViaImport()) return true
val descriptor = constructor.declarationDescriptor
if (descriptor == null || descriptor.name.isSpecial) return false
if (!checkTypeParameters && descriptor is TypeParameterDescriptor) return true
return scope != null && scope.findClassifier(descriptor.name, NoLookupLocation.FROM_IDE) == descriptor
}
fun KotlinType.approximateWithResolvableType(scope: LexicalScope?, checkTypeParameters: Boolean): KotlinType {
if (isError || isResolvableInScope(scope, checkTypeParameters)) return this
return supertypes().firstOrNull { it.isResolvableInScope(scope, checkTypeParameters) }
?: builtIns.anyType
}
fun KotlinType.anonymousObjectSuperTypeOrNull(): KotlinType? {
val classDescriptor = constructor.declarationDescriptor
if (classDescriptor != null && DescriptorUtils.isAnonymousObject(classDescriptor)) {
return immediateSupertypes().firstOrNull() ?: classDescriptor.builtIns.anyType
}
return null
}
fun KotlinType.getResolvableApproximations(
scope: LexicalScope?,
checkTypeParameters: Boolean,
allowIntersections: Boolean = false
): Sequence<KotlinType> {
return (listOf(this) + TypeUtils.getAllSupertypes(this))
.asSequence()
.mapNotNull {
it.asTypeProjection()
.fixTypeProjection(scope, checkTypeParameters, allowIntersections, isOutVariance = true)
?.type
}
}
private fun TypeProjection.fixTypeProjection(
scope: LexicalScope?,
checkTypeParameters: Boolean,
allowIntersections: Boolean,
isOutVariance: Boolean
): TypeProjection? {
if (!type.isResolvableInScope(scope, checkTypeParameters, allowIntersections)) return null
if (type.arguments.isEmpty()) return this
val resolvableArgs = type.arguments.filterTo(SmartSet.create()) { typeProjection ->
typeProjection.type.isResolvableInScope(scope, checkTypeParameters, allowIntersections)
}
if (resolvableArgs.containsAll(type.arguments)) {
fun fixArguments(type: KotlinType): KotlinType? = type.replace(
(type.arguments zip type.constructor.parameters).map { (arg, param) ->
if (arg.isStarProjection) arg
else arg.fixTypeProjection(
scope,
checkTypeParameters,
allowIntersections,
isOutVariance = isOutVariance && param.variance == Variance.OUT_VARIANCE
) ?: when {
!isOutVariance -> return null
param.variance == Variance.OUT_VARIANCE -> arg.type.approximateWithResolvableType(
scope,
checkTypeParameters
).asTypeProjection()
else -> type.replaceArgumentsWithStarProjections().arguments.first()
}
})
return if (type.isBuiltinFunctionalType) {
val returnType = type.getReturnTypeFromFunctionType()
type.replaceReturnType(fixArguments(returnType) ?: return null).asTypeProjection()
} else fixArguments(type)?.asTypeProjection()
}
if (!isOutVariance) return null
val newArguments = (type.arguments zip type.constructor.parameters).map { (arg, param) ->
when {
arg in resolvableArgs -> arg
arg.projectionKind == Variance.OUT_VARIANCE ||
param.variance == Variance.OUT_VARIANCE -> TypeProjectionImpl(
arg.projectionKind,
arg.type.approximateWithResolvableType(scope, checkTypeParameters)
)
else -> return if (isOutVariance) type.replaceArgumentsWithStarProjections().asTypeProjection() else null
}
}
return type.replace(newArguments).asTypeProjection()
}
fun KotlinType.isAbstract(): Boolean {
val modality = (constructor.declarationDescriptor as? ClassDescriptor)?.modality
return modality == Modality.ABSTRACT || modality == Modality.SEALED
}
/**
* NOTE: this is a very shaky implementation of [PsiType] to [KotlinType] conversion,
* produced types are fakes and are usable only for code generation. Please be careful using this method.
*/
@OptIn(FrontendInternals::class)
fun PsiType.resolveToKotlinType(resolutionFacade: ResolutionFacade): KotlinType {
if (this == PsiType.NULL) {
return resolutionFacade.moduleDescriptor.builtIns.nullableAnyType
}
val typeParameters = collectTypeParameters()
val components = resolutionFacade.getFrontendService(JavaResolverComponents::class.java)
val rootContext = LazyJavaResolverContext(components, TypeParameterResolver.EMPTY) { null }
val dummyPackageDescriptor = MutablePackageFragmentDescriptor(resolutionFacade.moduleDescriptor, FqName("dummy"))
val dummyClassDescriptor = ClassDescriptorImpl(
dummyPackageDescriptor,
Name.identifier("Dummy"),
Modality.FINAL,
ClassKind.CLASS,
emptyList(),
SourceElement.NO_SOURCE,
false,
LockBasedStorageManager.NO_LOCKS
)
val typeParameterResolver = object : TypeParameterResolver {
override fun resolveTypeParameter(javaTypeParameter: JavaTypeParameter): TypeParameterDescriptor? {
val psiTypeParameter = (javaTypeParameter as JavaTypeParameterImpl).psi
val index = typeParameters.indexOf(psiTypeParameter)
if (index < 0) return null
return LazyJavaTypeParameterDescriptor(rootContext.child(this), javaTypeParameter, index, dummyClassDescriptor)
}
}
val typeResolver = JavaTypeResolver(rootContext, typeParameterResolver)
val attributes = JavaTypeAttributes(TypeUsage.COMMON)
return typeResolver.transformJavaType(JavaTypeImpl.create(this), attributes).approximateFlexibleTypes(preferNotNull = true)
}
private fun PsiType.collectTypeParameters(): List<PsiTypeParameter> {
val results = ArrayList<PsiTypeParameter>()
accept(
object : PsiTypeVisitor<Unit>() {
override fun visitArrayType(arrayType: PsiArrayType) {
arrayType.componentType.accept(this)
}
override fun visitClassType(classType: PsiClassType) {
(classType.resolve() as? PsiTypeParameter)?.let { results += it }
classType.parameters.forEach { it.accept(this) }
}
override fun visitWildcardType(wildcardType: PsiWildcardType) {
wildcardType.bound?.accept(this)
}
}
)
return results
}
| apache-2.0 | cde2a860ac98420c063261d9a3d45cd5 | 42.638796 | 158 | 0.721337 | 5.102855 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/structuralsearch/visitor/KotlinMatchingVisitor.kt | 1 | 68287 | // 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.structuralsearch.visitor
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.elementType
import com.intellij.structuralsearch.StructuralSearchUtil
import com.intellij.structuralsearch.impl.matcher.CompiledPattern
import com.intellij.structuralsearch.impl.matcher.GlobalMatchingVisitor
import com.intellij.structuralsearch.impl.matcher.handlers.LiteralWithSubstitutionHandler
import com.intellij.structuralsearch.impl.matcher.handlers.SubstitutionHandler
import com.intellij.util.containers.reverse
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.ConstructorDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.AnonymousFunctionDescriptor
import org.jetbrains.kotlin.descriptors.impl.PropertyDescriptorImpl
import org.jetbrains.kotlin.fir.builder.toUnaryName
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.resolveToCall
import org.jetbrains.kotlin.idea.core.resolveType
import org.jetbrains.kotlin.idea.intentions.callExpression
import org.jetbrains.kotlin.idea.intentions.calleeName
import org.jetbrains.kotlin.idea.intentions.getCallableDescriptor
import org.jetbrains.kotlin.idea.refactoring.fqName.fqName
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.references.resolveToDescriptors
import org.jetbrains.kotlin.idea.search.declarationsSearch.HierarchySearchRequest
import org.jetbrains.kotlin.idea.search.declarationsSearch.searchInheritors
import org.jetbrains.kotlin.idea.search.usagesSearch.descriptor
import org.jetbrains.kotlin.idea.structuralsearch.*
import org.jetbrains.kotlin.idea.util.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.kdoc.lexer.KDocTokens
import org.jetbrains.kotlin.kdoc.psi.api.KDoc
import org.jetbrains.kotlin.kdoc.psi.impl.KDocImpl
import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink
import org.jetbrains.kotlin.kdoc.psi.impl.KDocSection
import org.jetbrains.kotlin.kdoc.psi.impl.KDocTag
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.getChildrenOfType
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.psi2ir.deparenthesize
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassDescriptor
import org.jetbrains.kotlin.resolve.source.getPsi
import org.jetbrains.kotlin.types.typeUtil.supertypes
import org.jetbrains.kotlin.util.OperatorNameConventions
class KotlinMatchingVisitor(private val myMatchingVisitor: GlobalMatchingVisitor) : SSRKtVisitor() {
/** Gets the next element in the query tree and removes unnecessary parentheses. */
private inline fun <reified T> getTreeElementDepar(): T? = when (val element = myMatchingVisitor.element) {
is KtParenthesizedExpression -> {
val deparenthesized = element.deparenthesize()
if (deparenthesized is T) deparenthesized else {
myMatchingVisitor.result = false
null
}
}
else -> getTreeElement<T>()
}
/** Gets the next element in the tree */
private inline fun <reified T> getTreeElement(): T? = when (val element = myMatchingVisitor.element) {
is T -> element
else -> {
myMatchingVisitor.result = false
null
}
}
private inline fun <reified T:KtElement> factory(context: PsiElement, f: KtPsiFactory.() -> T): T {
val psiFactory = KtPsiFactory(context, true)
val result = psiFactory.f()
(result.containingFile as KtFile).analysisContext = context
return result
}
private fun GlobalMatchingVisitor.matchSequentially(elements: List<PsiElement?>, elements2: List<PsiElement?>) =
matchSequentially(elements.toTypedArray(), elements2.toTypedArray())
private fun GlobalMatchingVisitor.matchInAnyOrder(elements: List<PsiElement?>, elements2: List<PsiElement?>) =
matchInAnyOrder(elements.toTypedArray(), elements2.toTypedArray())
private fun GlobalMatchingVisitor.matchNormalized(
element: KtExpression?,
element2: KtExpression?,
returnExpr: Boolean = false
): Boolean {
val (e1, e2) =
if (element is KtBlockExpression && element2 is KtBlockExpression) element to element2
else normalizeExpressions(element, element2, returnExpr)
val impossible = e1?.let {
val handler = getHandler(it)
e2 !is KtBlockExpression && handler is SubstitutionHandler && handler.minOccurs > 1
} ?: false
return !impossible && match(e1, e2)
}
private fun getHandler(element: PsiElement) = myMatchingVisitor.matchContext.pattern.getHandler(element)
private fun matchTextOrVariable(el1: PsiElement?, el2: PsiElement?): Boolean {
if (el1 == null) return true
if (el2 == null) return el1 == el2
return when (val handler = getHandler(el1)) {
is SubstitutionHandler -> handler.validate(el2, myMatchingVisitor.matchContext)
else -> myMatchingVisitor.matchText(el1, el2)
}
}
override fun visitLeafPsiElement(leafPsiElement: LeafPsiElement) {
val other = getTreeElementDepar<LeafPsiElement>() ?: return
// Match element type
if (!myMatchingVisitor.setResult(leafPsiElement.elementType == other.elementType)) return
when (leafPsiElement.elementType) {
KDocTokens.TEXT -> {
myMatchingVisitor.result = when (val handler = leafPsiElement.getUserData(CompiledPattern.HANDLER_KEY)) {
is LiteralWithSubstitutionHandler -> handler.match(leafPsiElement, other, myMatchingVisitor.matchContext)
else -> matchTextOrVariable(leafPsiElement, other)
}
}
KDocTokens.TAG_NAME, KtTokens.IDENTIFIER -> myMatchingVisitor.result = matchTextOrVariable(leafPsiElement, other)
}
}
override fun visitArrayAccessExpression(expression: KtArrayAccessExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
myMatchingVisitor.result = when (other) {
is KtArrayAccessExpression -> myMatchingVisitor.match(expression.arrayExpression, other.arrayExpression)
&& myMatchingVisitor.matchSons(expression.indicesNode, other.indicesNode)
is KtDotQualifiedExpression -> myMatchingVisitor.match(expression.arrayExpression, other.receiverExpression)
&& other.calleeName == "${OperatorNameConventions.GET}"
&& myMatchingVisitor.matchSequentially(
expression.indexExpressions, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!!
)
else -> false
}
}
/** Matches binary expressions including translated operators. */
override fun visitBinaryExpression(expression: KtBinaryExpression) {
fun KtBinaryExpression.match(other: KtBinaryExpression) = operationToken == other.operationToken
&& myMatchingVisitor.match(left, other.left)
&& myMatchingVisitor.match(right, other.right)
fun KtQualifiedExpression.match(name: Name?, receiver: KtExpression?, callEntry: KtExpression?): Boolean {
val callExpr = callExpression
return callExpr is KtCallExpression && calleeName == "$name"
&& myMatchingVisitor.match(receiver, receiverExpression)
&& myMatchingVisitor.match(callEntry, callExpr.valueArguments.first().getArgumentExpression())
}
fun KtBinaryExpression.matchEq(other: KtBinaryExpression): Boolean {
val otherLeft = other.left?.deparenthesize()
val otherRight = other.right?.deparenthesize()
return otherLeft is KtSafeQualifiedExpression
&& otherLeft.match(OperatorNameConventions.EQUALS, left, right)
&& other.operationToken == KtTokens.ELVIS
&& otherRight is KtBinaryExpression
&& myMatchingVisitor.match(right, otherRight.left)
&& otherRight.operationToken == KtTokens.EQEQEQ
&& myMatchingVisitor.match(factory(other) {createExpression("null")}, otherRight.right)
}
val other = getTreeElementDepar<KtExpression>() ?: return
when (other) {
is KtBinaryExpression -> {
if (expression.operationToken == KtTokens.IDENTIFIER ) {
myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.right)
&& myMatchingVisitor.match(expression.right, other.right)
&& myMatchingVisitor.match(expression.operationReference, other.operationReference)
return
}
if (myMatchingVisitor.setResult(expression.match(other))) return
when (expression.operationToken) { // semantical matching
KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ -> { // a.compareTo(b) OP 0
val left = other.left?.deparenthesize()
myMatchingVisitor.result = left is KtDotQualifiedExpression
&& left.match(OperatorNameConventions.COMPARE_TO, expression.left, expression.right)
&& expression.operationToken == other.operationToken
&& myMatchingVisitor.match(other.right, factory(other) {createExpression("0")})
}
in augmentedAssignmentsMap.keys -> { // x OP= y with x = x OP y
if (other.operationToken == KtTokens.EQ) {
val right = other.right?.deparenthesize()
val left = other.left?.deparenthesize()
myMatchingVisitor.result = right is KtBinaryExpression
&& augmentedAssignmentsMap[expression.operationToken] == right.operationToken
&& myMatchingVisitor.match(expression.left, left)
&& myMatchingVisitor.match(expression.left, right.left)
&& myMatchingVisitor.match(expression.right, right.right)
}
}
KtTokens.EQ -> { // x = x OP y with x OP= y
val right = expression.right?.deparenthesize()
if (right is KtBinaryExpression && right.operationToken == augmentedAssignmentsMap[other.operationToken]) {
myMatchingVisitor.result = myMatchingVisitor.match(expression.left, other.left)
&& myMatchingVisitor.match(right.left, other.left)
&& myMatchingVisitor.match(right.right, other.right)
}
}
KtTokens.EQEQ -> { // a?.equals(b) ?: (b === null)
myMatchingVisitor.result = expression.matchEq(other)
}
}
}
is KtDotQualifiedExpression -> { // translated matching
val token = expression.operationToken
val left = expression.left
val right = expression.right
when {
token == KtTokens.IN_KEYWORD -> { // b.contains(a)
val parent = other.parent
val isNotNegated = if (parent is KtPrefixExpression) parent.operationToken != KtTokens.EXCL else true
myMatchingVisitor.result = isNotNegated && other.match(OperatorNameConventions.CONTAINS, right, left)
}
token == KtTokens.NOT_IN -> myMatchingVisitor.result = false // already matches with prefix expression
token == KtTokens.EQ && left is KtArrayAccessExpression -> { // a[x] = expression
val matchedArgs = left.indexExpressions.apply { add(right) }
myMatchingVisitor.result = myMatchingVisitor.match(left.arrayExpression, other.receiverExpression)
&& other.calleeName == "${OperatorNameConventions.SET}"
&& myMatchingVisitor.matchSequentially(
matchedArgs, other.callExpression?.valueArguments?.map(KtValueArgument::getArgumentExpression)!!
)
}
else -> { // a.plus(b) all arithmetic operators
val selector = other.selectorExpression
if (expression.operationToken == KtTokens.EQ && right is KtBinaryExpression) {
// Matching x = x + y with x.plusAssign(y)
val opName = augmentedAssignmentsMap.reverse()[right.operationToken]?.binaryExprOpName()
myMatchingVisitor.result = selector is KtCallExpression
&& myMatchingVisitor.match(left, other.receiverExpression)
&& other.match(opName, right.left, right.right)
} else {
myMatchingVisitor.result = selector is KtCallExpression && other.match(
expression.operationToken.binaryExprOpName(), left, right
)
}
}
}
}
is KtPrefixExpression -> { // translated matching
val baseExpr = other.baseExpression?.deparenthesize()
when (expression.operationToken) {
KtTokens.NOT_IN -> { // !b.contains(a)
myMatchingVisitor.result = other.operationToken == KtTokens.EXCL
&& baseExpr is KtDotQualifiedExpression
&& baseExpr.match(OperatorNameConventions.CONTAINS, expression.right, expression.left)
}
KtTokens.EXCLEQ -> { // !(a?.equals(b) ?: (b === null))
myMatchingVisitor.result = other.operationToken == KtTokens.EXCL
&& baseExpr is KtBinaryExpression
&& expression.matchEq(baseExpr)
}
}
}
else -> myMatchingVisitor.result = false
}
}
override fun visitBlockExpression(expression: KtBlockExpression) {
val other = getTreeElementDepar<KtBlockExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.statements, other.statements)
}
override fun visitUnaryExpression(expression: KtUnaryExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
myMatchingVisitor.result = when (other) {
is KtDotQualifiedExpression -> {
myMatchingVisitor.match(expression.baseExpression, other.receiverExpression)
&& expression.operationToken.toUnaryName().toString() == other.calleeName
}
is KtUnaryExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression)
&& myMatchingVisitor.match(expression.operationReference, other.operationReference)
else -> false
}
}
override fun visitParenthesizedExpression(expression: KtParenthesizedExpression) {
fun KtExpression.countParenthesize(initial: Int = 0): Int {
val parentheses = children.firstOrNull { it is KtParenthesizedExpression } as KtExpression?
return parentheses?.countParenthesize(initial + 1) ?: initial
}
val other = getTreeElement<KtParenthesizedExpression>() ?: return
if (!myMatchingVisitor.setResult(expression.countParenthesize() == other.countParenthesize())) return
myMatchingVisitor.result = myMatchingVisitor.match(expression.deparenthesize(), other.deparenthesize())
}
override fun visitConstantExpression(expression: KtConstantExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
myMatchingVisitor.result = matchTextOrVariable(expression, other)
}
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
val other = getTreeElementDepar<PsiElement>() ?: return
val exprHandler = getHandler(expression)
if (other is KtReferenceExpression && exprHandler is SubstitutionHandler) {
val ref = other.mainReference
val bindingContext = ref.element.safeAnalyzeNonSourceRootCode(BodyResolveMode.PARTIAL)
val referenced = ref.resolveToDescriptors(bindingContext).firstOrNull()?.let {
if (it is ConstructorDescriptor) it.constructedClass else it
}
if (referenced is ClassifierDescriptor) {
val fqName = referenced.fqNameOrNull()
val predicate = exprHandler.findRegExpPredicate()
if (predicate != null && fqName != null &&
predicate.doMatch(fqName.asString(), myMatchingVisitor.matchContext, other)
) {
myMatchingVisitor.result = true
exprHandler.addResult(other, myMatchingVisitor.matchContext)
return
}
}
}
// Match Int::class with X.Int::class
val skipReceiver = other.parent is KtDoubleColonExpression
&& other is KtDotQualifiedExpression
&& myMatchingVisitor.match(expression, other.selectorExpression)
myMatchingVisitor.result = skipReceiver || matchTextOrVariable(
expression.getReferencedNameElement(),
if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other
)
val handler = getHandler(expression.getReferencedNameElement())
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(
if (other is KtSimpleNameExpression) other.getReferencedNameElement() else other,
myMatchingVisitor.matchContext
)
}
}
override fun visitContinueExpression(expression: KtContinueExpression) {
val other = getTreeElementDepar<KtContinueExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
}
override fun visitBreakExpression(expression: KtBreakExpression) {
val other = getTreeElementDepar<KtBreakExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
}
override fun visitThisExpression(expression: KtThisExpression) {
val other = getTreeElementDepar<KtThisExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
}
override fun visitSuperExpression(expression: KtSuperExpression) {
val other = getTreeElementDepar<KtSuperExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
&& myMatchingVisitor.match(expression.superTypeQualifier, other.superTypeQualifier)
}
override fun visitReturnExpression(expression: KtReturnExpression) {
val other = getTreeElementDepar<KtReturnExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.getTargetLabel(), other.getTargetLabel())
&& myMatchingVisitor.match(expression.returnedExpression, other.returnedExpression)
}
override fun visitFunctionType(type: KtFunctionType) {
val other = getTreeElementDepar<KtFunctionType>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(type.receiverTypeReference, other.receiverTypeReference)
&& myMatchingVisitor.match(type.parameterList, other.parameterList)
&& myMatchingVisitor.match(type.returnTypeReference, other.returnTypeReference)
}
override fun visitUserType(type: KtUserType) {
val other = myMatchingVisitor.element
myMatchingVisitor.result = when (other) {
is KtUserType -> {
type.qualifier?.let { typeQualifier -> // if query has fq type
myMatchingVisitor.match(typeQualifier, other.qualifier) // recursively match qualifiers
&& myMatchingVisitor.match(type.referenceExpression, other.referenceExpression)
&& myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList)
} ?: let { // no fq type
myMatchingVisitor.match(type.referenceExpression, other.referenceExpression)
&& myMatchingVisitor.match(type.typeArgumentList, other.typeArgumentList)
}
}
is KtTypeElement -> matchTextOrVariable(type.referenceExpression, other)
else -> false
}
}
override fun visitNullableType(nullableType: KtNullableType) {
val other = getTreeElementDepar<KtNullableType>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(nullableType.innerType, other.innerType)
}
override fun visitDynamicType(type: KtDynamicType) {
myMatchingVisitor.result = myMatchingVisitor.element is KtDynamicType
}
private fun matchTypeReferenceWithDeclaration(typeReference: KtTypeReference?, other: KtDeclaration): Boolean {
val type = other.resolveKotlinType()
if (type != null) {
val fqType = DescriptorRenderer.FQ_NAMES_IN_TYPES.renderType(type)
val analzyableFile = factory(other) {createAnalyzableFile("${other.hashCode()}.kt", "val x: $fqType = TODO()", other)}
return myMatchingVisitor.match(typeReference, (analzyableFile.lastChild as KtProperty).typeReference)
}
return false
}
override fun visitTypeReference(typeReference: KtTypeReference) {
val other = getTreeElementDepar<KtTypeReference>() ?: return
val parent = other.parent
val isReceiverTypeReference = when (parent) {
is KtProperty -> parent.receiverTypeReference == other
is KtNamedFunction -> parent.receiverTypeReference == other
else -> false
}
val type = when {
!isReceiverTypeReference && parent is KtProperty -> parent.resolveKotlinType()
isReceiverTypeReference && parent is KtDeclaration && parent.descriptor is FunctionDescriptor ->
(parent.descriptor as FunctionDescriptor).extensionReceiverParameter?.value?.type
isReceiverTypeReference && parent is KtDeclaration && parent.descriptor is PropertyDescriptorImpl ->
(parent.descriptor as PropertyDescriptorImpl).extensionReceiverParameter?.value?.type
else -> null
}
val fqMatch = when {
type != null -> {
val handler = getHandler(typeReference)
type.renderNames().any {
if (handler is SubstitutionHandler)
if (handler.findRegExpPredicate()?.doMatch(it, myMatchingVisitor.matchContext, other) == true) {
handler.addResult(other, myMatchingVisitor.matchContext)
true
} else false
else myMatchingVisitor.matchText(typeReference.text, it)
}
}
else -> false
}
myMatchingVisitor.result = fqMatch || myMatchingVisitor.matchSons(typeReference, other)
}
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
val other = getTreeElementDepar<KtQualifiedExpression>() ?: return
myMatchingVisitor.result = expression.operationSign == other.operationSign
&& myMatchingVisitor.match(expression.receiverExpression, other.receiverExpression)
&& myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression)
}
override fun visitDotQualifiedExpression(expression: KtDotQualifiedExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
val handler = getHandler(expression.receiverExpression)
if (other is KtDotQualifiedExpression) {
// Regular matching
myMatchingVisitor.result = myMatchingVisitor.matchOptionally(expression.receiverExpression, other.receiverExpression)
&& other.selectorExpression is KtCallExpression == expression.selectorExpression is KtCallExpression
&& myMatchingVisitor.match(expression.selectorExpression, other.selectorExpression)
} else {
val selector = expression.selectorExpression
// Match '_?.'_()
myMatchingVisitor.result = selector is KtCallExpression == other is KtCallExpression
&& (handler is SubstitutionHandler && handler.minOccurs == 0 || other.parent is KtDoubleColonExpression)
&& other.parent !is KtDotQualifiedExpression
&& other.parent !is KtReferenceExpression
&& myMatchingVisitor.match(selector, other)
// Match fq.call() with call()
if (!myMatchingVisitor.result && other is KtCallExpression && other.parent !is KtDotQualifiedExpression && selector is KtCallExpression) {
val expressionCall = expression.text.substringBefore('(')
val otherCall = other.getCallableDescriptor()?.fqNameSafe
myMatchingVisitor.result = otherCall != null
&& myMatchingVisitor.matchText(expressionCall, otherCall.toString().substringBefore(".<"))
&& myMatchingVisitor.match(selector.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(resolveParameters(other),
selector.valueArgumentList, other.valueArgumentList,
selector.lambdaArguments, other.lambdaArguments)
}
}
}
override fun visitLambdaExpression(lambdaExpression: KtLambdaExpression) {
val other = getTreeElementDepar<KtLambdaExpression>() ?: return
val lambdaVP = lambdaExpression.valueParameters
val otherVP = other.valueParameters
myMatchingVisitor.result =
(!lambdaExpression.functionLiteral.hasParameterSpecification()
|| myMatchingVisitor.matchSequentially(lambdaVP, otherVP)
|| lambdaVP.map { p -> getHandler(p).let { if (it is SubstitutionHandler) it.minOccurs else 1 } }.sum() == 1
&& !other.functionLiteral.hasParameterSpecification()
&& (other.functionLiteral.descriptor as AnonymousFunctionDescriptor).valueParameters.size == 1)
&& myMatchingVisitor.match(lambdaExpression.bodyExpression, other.bodyExpression)
}
override fun visitTypeProjection(typeProjection: KtTypeProjection) {
val other = getTreeElementDepar<KtTypeProjection>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(typeProjection.typeReference, other.typeReference)
&& myMatchingVisitor.match(typeProjection.modifierList, other.modifierList)
&& typeProjection.projectionKind == other.projectionKind
}
override fun visitTypeArgumentList(typeArgumentList: KtTypeArgumentList) {
val other = getTreeElementDepar<KtTypeArgumentList>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(typeArgumentList.arguments, other.arguments)
}
override fun visitArgument(argument: KtValueArgument) {
val other = getTreeElementDepar<KtValueArgument>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(argument.getArgumentExpression(), other.getArgumentExpression())
&& (!argument.isNamed() || !other.isNamed() || matchTextOrVariable(
argument.getArgumentName(), other.getArgumentName()
))
}
private fun MutableList<KtValueArgument>.addDefaultArguments(parameters: List<KtParameter?>) {
if (parameters.isEmpty()) return
val params = parameters.toTypedArray()
var i = 0
while (i < size) {
val arg = get(i)
if (arg.isNamed()) {
params[parameters.indexOfFirst { it?.nameAsName == arg.getArgumentName()?.asName }] = null
i++
} else {
val curParam = params[i] ?: throw IllegalStateException(
KotlinBundle.message("error.param.can.t.be.null.at.index.0.in.1", i, params.map { it?.text })
)
params[i] = null
if (curParam.isVarArg) {
val varArgType = arg.getArgumentExpression()?.resolveType()
var curArg: KtValueArgument? = arg
while (varArgType != null && varArgType == curArg?.getArgumentExpression()?.resolveType() || curArg?.isSpread == true) {
i++
curArg = getOrNull(i)
}
} else i++
}
}
params.filterNotNull().forEach { add(factory(myMatchingVisitor.element) {createArgument(it.defaultValue, it.nameAsName, reformat = false) }) }
}
private fun matchValueArguments(
parameters: List<KtParameter>,
valueArgList: KtValueArgumentList?,
otherValueArgList: KtValueArgumentList?,
lambdaArgList: List<KtLambdaArgument>,
otherLambdaArgList: List<KtLambdaArgument>
): Boolean {
if (valueArgList != null) {
val handler = getHandler(valueArgList)
val normalizedOtherArgs = otherValueArgList?.arguments?.toMutableList() ?: mutableListOf()
normalizedOtherArgs.addAll(otherLambdaArgList)
normalizedOtherArgs.addDefaultArguments(parameters)
if (normalizedOtherArgs.isEmpty() && handler is SubstitutionHandler && handler.minOccurs == 0) {
return myMatchingVisitor.matchSequentially(lambdaArgList, otherLambdaArgList)
}
val normalizedArgs = valueArgList.arguments.toMutableList()
normalizedArgs.addAll(lambdaArgList)
return matchValueArguments(normalizedArgs, normalizedOtherArgs)
}
return matchValueArguments(lambdaArgList, otherLambdaArgList)
}
private fun matchValueArguments(queryArgs: List<KtValueArgument>, codeArgs: List<KtValueArgument>): Boolean {
var queryIndex = 0
var codeIndex = 0
while (queryIndex < queryArgs.size) {
val queryArg = queryArgs[queryIndex]
val codeArg = codeArgs.getOrElse(codeIndex) { return@matchValueArguments false }
if (getHandler(queryArg) is SubstitutionHandler) {
return myMatchingVisitor.matchSequentially(
queryArgs.subList(queryIndex, queryArgs.lastIndex + 1),
codeArgs.subList(codeIndex, codeArgs.lastIndex + 1)
)
}
// varargs declared in call matching with one-to-one argument passing
if (queryArg.isSpread && !codeArg.isSpread) {
val spreadArgExpr = queryArg.getArgumentExpression()
if (spreadArgExpr is KtCallExpression) {
spreadArgExpr.valueArguments.forEach { spreadedArg ->
if (!myMatchingVisitor.match(spreadedArg, codeArgs[codeIndex++])) return@matchValueArguments false
}
queryIndex++
continue
} // can't match array that is not created in the call itself
myMatchingVisitor.result = false
return myMatchingVisitor.result
}
if (!queryArg.isSpread && codeArg.isSpread) {
val spreadArgExpr = codeArg.getArgumentExpression()
if (spreadArgExpr is KtCallExpression) {
spreadArgExpr.valueArguments.forEach { spreadedArg ->
if (!myMatchingVisitor.match(queryArgs[queryIndex++], spreadedArg)) return@matchValueArguments false
}
codeIndex++
continue
}
return false// can't match array that is not created in the call itself
}
// normal argument matching
if (!myMatchingVisitor.match(queryArg, codeArg)) {
return if (queryArg.isNamed() || codeArg.isNamed()) { // start comparing for out of order arguments
myMatchingVisitor.matchInAnyOrder(
queryArgs.subList(queryIndex, queryArgs.lastIndex + 1),
codeArgs.subList(codeIndex, codeArgs.lastIndex + 1)
)
} else false
}
queryIndex++
codeIndex++
}
if (codeIndex != codeArgs.size) return false
return true
}
private fun resolveParameters(other: KtElement): List<KtParameter> {
return other.resolveToCall()?.candidateDescriptor?.original?.valueParameters?.mapNotNull {
it.source.getPsi() as? KtParameter
} ?: emptyList()
}
override fun visitCallExpression(expression: KtCallExpression) {
val other = getTreeElementDepar<KtExpression>() ?: return
val parameters = resolveParameters(other)
myMatchingVisitor.result = when (other) {
is KtCallExpression -> {
myMatchingVisitor.match(expression.calleeExpression, other.calleeExpression)
&& myMatchingVisitor.match(expression.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(
parameters, expression.valueArgumentList, other.valueArgumentList,
expression.lambdaArguments, other.lambdaArguments
)
}
is KtDotQualifiedExpression -> other.callExpression is KtCallExpression
&& myMatchingVisitor.match(expression.calleeExpression, other.receiverExpression)
&& other.calleeName == "${OperatorNameConventions.INVOKE}"
&& matchValueArguments(
parameters,
expression.valueArgumentList, other.callExpression?.valueArgumentList,
expression.lambdaArguments, other.callExpression?.lambdaArguments ?: emptyList()
)
else -> false
}
}
override fun visitCallableReferenceExpression(expression: KtCallableReferenceExpression) {
val other = getTreeElementDepar<KtCallableReferenceExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.callableReference, other.callableReference)
&& myMatchingVisitor.matchOptionally(expression.receiverExpression, other.receiverExpression)
}
override fun visitTypeParameter(parameter: KtTypeParameter) {
val other = getTreeElementDepar<KtTypeParameter>() ?: return
myMatchingVisitor.result = matchTextOrVariable(parameter.firstChild, other.firstChild) // match generic identifier
&& myMatchingVisitor.match(parameter.extendsBound, other.extendsBound)
&& parameter.variance == other.variance
parameter.nameIdentifier?.let { nameIdentifier ->
val handler = getHandler(nameIdentifier)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
}
override fun visitParameter(parameter: KtParameter) {
val other = getTreeElementDepar<KtParameter>() ?: return
val decl = other.parent.parent
val typeMatched = when {
decl is KtFunctionType || decl is KtCatchClause || (parameter.isVarArg && other.isVarArg) -> {
myMatchingVisitor.match(parameter.typeReference, other.typeReference)
}
else -> matchTypeReferenceWithDeclaration(parameter.typeReference, other)
}
val otherNameIdentifier = if (getHandler(parameter) is SubstitutionHandler
&& parameter.nameIdentifier != null
&& other.nameIdentifier == null
) other else other.nameIdentifier
myMatchingVisitor.result = typeMatched
&& myMatchingVisitor.match(parameter.defaultValue, other.defaultValue)
&& (parameter.isVarArg == other.isVarArg || getHandler(parameter) is SubstitutionHandler)
&& myMatchingVisitor.match(parameter.valOrVarKeyword, other.valOrVarKeyword)
&& (parameter.nameIdentifier == null || matchTextOrVariable(parameter.nameIdentifier, otherNameIdentifier))
&& myMatchingVisitor.match(parameter.modifierList, other.modifierList)
&& myMatchingVisitor.match(parameter.destructuringDeclaration, other.destructuringDeclaration)
parameter.nameIdentifier?.let { nameIdentifier ->
val handler = getHandler(nameIdentifier)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
}
override fun visitTypeParameterList(list: KtTypeParameterList) {
val other = getTreeElementDepar<KtTypeParameterList>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters)
}
override fun visitParameterList(list: KtParameterList) {
val other = getTreeElementDepar<KtParameterList>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(list.parameters, other.parameters)
}
override fun visitConstructorDelegationCall(call: KtConstructorDelegationCall) {
val other = getTreeElementDepar<KtConstructorDelegationCall>() ?: return
val parameters = resolveParameters(other)
myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression)
&& myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(
parameters,
call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments
)
}
override fun visitSecondaryConstructor(constructor: KtSecondaryConstructor) {
val other = getTreeElementDepar<KtSecondaryConstructor>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList)
&& myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList)
&& myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList)
&& myMatchingVisitor.match(constructor.getDelegationCallOrNull(), other.getDelegationCallOrNull())
&& myMatchingVisitor.match(constructor.bodyExpression, other.bodyExpression)
}
override fun visitPrimaryConstructor(constructor: KtPrimaryConstructor) {
val other = getTreeElementDepar<KtPrimaryConstructor>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(constructor.modifierList, other.modifierList)
&& myMatchingVisitor.match(constructor.typeParameterList, other.typeParameterList)
&& myMatchingVisitor.match(constructor.valueParameterList, other.valueParameterList)
}
override fun visitAnonymousInitializer(initializer: KtAnonymousInitializer) {
val other = getTreeElementDepar<KtAnonymousInitializer>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(initializer.body, other.body)
}
override fun visitClassBody(classBody: KtClassBody) {
val other = getTreeElementDepar<KtClassBody>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(classBody, other)
}
override fun visitSuperTypeCallEntry(call: KtSuperTypeCallEntry) {
val other = getTreeElementDepar<KtSuperTypeCallEntry>() ?: return
val parameters = resolveParameters(other)
myMatchingVisitor.result = myMatchingVisitor.match(call.calleeExpression, other.calleeExpression)
&& myMatchingVisitor.match(call.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(
parameters,
call.valueArgumentList, other.valueArgumentList, call.lambdaArguments, other.lambdaArguments
)
}
override fun visitSuperTypeEntry(specifier: KtSuperTypeEntry) {
val other = getTreeElementDepar<KtSuperTypeEntry>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(specifier.typeReference, other.typeReference)
}
private fun matchTypeAgainstElement(
type: String,
element: PsiElement,
other: PsiElement
): Boolean {
return when (val predicate = (getHandler(element) as? SubstitutionHandler)?.findRegExpPredicate()) {
null -> element.text == type
// Ignore type parameters if absent from the pattern
|| !element.text.contains('<') && element.text == type.removeTypeParameters()
else -> predicate.doMatch(type, myMatchingVisitor.matchContext, other)
}
}
override fun visitSuperTypeList(list: KtSuperTypeList) {
val other = getTreeElementDepar<KtSuperTypeList>() ?: return
val withinHierarchyEntries = list.entries.filter {
val type = it.typeReference; type is KtTypeReference && getHandler(type).withinHierarchyTextFilterSet
}
(other.parent as? KtClassOrObject)?.let { klass ->
val supertypes = (klass.descriptor as ClassDescriptor).toSimpleType().supertypes()
withinHierarchyEntries.forEach { entry ->
val typeReference = entry.typeReference
if (!matchTextOrVariable(typeReference, klass.nameIdentifier) && typeReference != null && supertypes.none {
it.renderNames().any { type -> matchTypeAgainstElement(type, typeReference, other) }
}) {
myMatchingVisitor.result = false
return@visitSuperTypeList
}
}
}
myMatchingVisitor.result =
myMatchingVisitor.matchInAnyOrder(list.entries.filter { it !in withinHierarchyEntries }, other.entries)
}
override fun visitClass(klass: KtClass) {
val other = getTreeElementDepar<KtClass>() ?: return
val otherDescriptor = other.descriptor ?: return
val identifier = klass.nameIdentifier
val otherIdentifier = other.nameIdentifier
var matchNameIdentifiers = matchTextOrVariable(identifier, otherIdentifier)
|| identifier != null && otherIdentifier != null && matchTypeAgainstElement(
(otherDescriptor as LazyClassDescriptor).defaultType.fqName.toString(), identifier, otherIdentifier
)
// Possible match if "within hierarchy" is set
if (!matchNameIdentifiers && identifier != null && otherIdentifier != null) {
val identifierHandler = getHandler(identifier)
val checkHierarchyDown = identifierHandler.withinHierarchyTextFilterSet
if (checkHierarchyDown) {
// Check hierarchy down (down of pattern element = supertypes of code element)
matchNameIdentifiers = (otherDescriptor as ClassDescriptor).toSimpleType().supertypes().any { type ->
type.renderNames().any { renderedType ->
matchTypeAgainstElement(renderedType, identifier, otherIdentifier)
}
}
} else if (identifier.getUserData(KotlinCompilingVisitor.WITHIN_HIERARCHY) == true) {
// Check hierarchy up (up of pattern element = inheritors of code element)
matchNameIdentifiers = HierarchySearchRequest(
other,
GlobalSearchScope.allScope(other.project),
true
).searchInheritors().any { psiClass ->
arrayOf(psiClass.name, psiClass.qualifiedName).filterNotNull().any { renderedType ->
matchTypeAgainstElement(renderedType, identifier, otherIdentifier)
}
}
}
}
myMatchingVisitor.result = myMatchingVisitor.match(klass.getClassOrInterfaceKeyword(), other.getClassOrInterfaceKeyword())
&& myMatchingVisitor.match(klass.modifierList, other.modifierList)
&& matchNameIdentifiers
&& myMatchingVisitor.match(klass.typeParameterList, other.typeParameterList)
&& myMatchingVisitor.match(klass.primaryConstructor, other.primaryConstructor)
&& myMatchingVisitor.matchInAnyOrder(klass.secondaryConstructors, other.secondaryConstructors)
&& myMatchingVisitor.match(klass.getSuperTypeList(), other.getSuperTypeList())
&& myMatchingVisitor.match(klass.body, other.body)
&& myMatchingVisitor.match(klass.docComment, other.docComment)
val handler = getHandler(klass.nameIdentifier!!)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
override fun visitObjectLiteralExpression(expression: KtObjectLiteralExpression) {
val other = getTreeElementDepar<KtObjectLiteralExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.objectDeclaration, other.objectDeclaration)
}
override fun visitObjectDeclaration(declaration: KtObjectDeclaration) {
val other = getTreeElementDepar<KtObjectDeclaration>() ?: return
val otherIdentifier =
other.nameIdentifier ?: if (other.isCompanion()) (other.parent.parent as KtClass).nameIdentifier else null
myMatchingVisitor.result = myMatchingVisitor.match(declaration.modifierList, other.modifierList)
&& matchTextOrVariable(declaration.nameIdentifier, otherIdentifier)
&& myMatchingVisitor.match(declaration.getSuperTypeList(), other.getSuperTypeList())
&& myMatchingVisitor.match(declaration.body, other.body)
declaration.nameIdentifier?.let { declNameIdentifier ->
val handler = getHandler(declNameIdentifier)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(otherIdentifier, myMatchingVisitor.matchContext)
}
}
}
private fun normalizeExpressionRet(expression: KtExpression?): KtExpression? = when {
expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement?.let {
if (it is KtReturnExpression) it.returnedExpression else it
}
else -> expression
}
private fun normalizeExpression(expression: KtExpression?): KtExpression? = when {
expression is KtBlockExpression && expression.statements.size == 1 -> expression.firstStatement
else -> expression
}
private fun normalizeExpressions(
patternExpr: KtExpression?,
codeExpr: KtExpression?,
returnExpr: Boolean
): Pair<KtExpression?, KtExpression?> {
val normalizedExpr = if (returnExpr) normalizeExpressionRet(patternExpr) else normalizeExpression(patternExpr)
val normalizedCodeExpr = if (returnExpr) normalizeExpressionRet(codeExpr) else normalizeExpression(codeExpr)
return when {
normalizedExpr is KtBlockExpression || normalizedCodeExpr is KtBlockExpression -> patternExpr to codeExpr
else -> normalizedExpr to normalizedCodeExpr
}
}
override fun visitNamedFunction(function: KtNamedFunction) {
val other = getTreeElementDepar<KtNamedFunction>() ?: return
val (patternBody, codeBody) = normalizeExpressions(function.bodyBlockExpression, other.bodyBlockExpression, true)
val bodyHandler = patternBody?.let(::getHandler)
val bodyMatch = when {
patternBody is KtNameReferenceExpression && codeBody == null -> bodyHandler is SubstitutionHandler
&& bodyHandler.minOccurs <= 1 && bodyHandler.maxOccurs >= 1
&& myMatchingVisitor.match(patternBody, other.bodyExpression)
patternBody is KtNameReferenceExpression -> myMatchingVisitor.match(
function.bodyBlockExpression,
other.bodyBlockExpression
)
patternBody == null && codeBody == null -> myMatchingVisitor.match(function.bodyExpression, other.bodyExpression)
patternBody == null -> function.bodyExpression == null || codeBody !is KtBlockExpression && myMatchingVisitor.match(function.bodyExpression, codeBody)
codeBody == null -> patternBody !is KtBlockExpression && myMatchingVisitor.match(patternBody, other.bodyExpression)
else -> myMatchingVisitor.match(function.bodyBlockExpression, other.bodyBlockExpression)
}
myMatchingVisitor.result = myMatchingVisitor.match(function.modifierList, other.modifierList)
&& matchTextOrVariable(function.nameIdentifier, other.nameIdentifier)
&& myMatchingVisitor.match(function.typeParameterList, other.typeParameterList)
&& matchTypeReferenceWithDeclaration(function.typeReference, other)
&& myMatchingVisitor.match(function.valueParameterList, other.valueParameterList)
&& myMatchingVisitor.match(function.receiverTypeReference, other.receiverTypeReference)
&& bodyMatch
function.nameIdentifier?.let { nameIdentifier ->
val handler = getHandler(nameIdentifier)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
}
override fun visitModifierList(list: KtModifierList) {
val other = getTreeElementDepar<KtModifierList>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSonsInAnyOrder(list, other)
}
override fun visitIfExpression(expression: KtIfExpression) {
val other = getTreeElementDepar<KtIfExpression>() ?: return
val elseBranch = normalizeExpression(expression.`else`)
myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
&& myMatchingVisitor.matchNormalized(expression.then, other.then)
&& (elseBranch == null || myMatchingVisitor.matchNormalized(expression.`else`, other.`else`))
}
override fun visitForExpression(expression: KtForExpression) {
val other = getTreeElementDepar<KtForExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.loopParameter, other.loopParameter)
&& myMatchingVisitor.match(expression.loopRange, other.loopRange)
&& myMatchingVisitor.matchNormalized(expression.body, other.body)
}
override fun visitWhileExpression(expression: KtWhileExpression) {
val other = getTreeElementDepar<KtWhileExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
&& myMatchingVisitor.matchNormalized(expression.body, other.body)
}
override fun visitDoWhileExpression(expression: KtDoWhileExpression) {
val other = getTreeElementDepar<KtDoWhileExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.condition, other.condition)
&& myMatchingVisitor.matchNormalized(expression.body, other.body)
}
override fun visitWhenConditionInRange(condition: KtWhenConditionInRange) {
val other = getTreeElementDepar<KtWhenConditionInRange>() ?: return
myMatchingVisitor.result = condition.isNegated == other.isNegated
&& myMatchingVisitor.match(condition.rangeExpression, other.rangeExpression)
}
override fun visitWhenConditionIsPattern(condition: KtWhenConditionIsPattern) {
val other = getTreeElementDepar<KtWhenConditionIsPattern>() ?: return
myMatchingVisitor.result = condition.isNegated == other.isNegated
&& myMatchingVisitor.match(condition.typeReference, other.typeReference)
}
override fun visitWhenConditionWithExpression(condition: KtWhenConditionWithExpression) {
val other = getTreeElementDepar<PsiElement>() ?: return
val handler = getHandler(condition)
if (handler is SubstitutionHandler) {
myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext)
} else {
myMatchingVisitor.result = other is KtWhenConditionWithExpression
&& myMatchingVisitor.match(condition.expression, other.expression)
}
}
override fun visitWhenEntry(ktWhenEntry: KtWhenEntry) {
val other = getTreeElementDepar<KtWhenEntry>() ?: return
// $x$ -> $y$ should match else branches
val bypassElseTest = ktWhenEntry.firstChild is KtWhenConditionWithExpression
&& ktWhenEntry.firstChild.children.size == 1
&& ktWhenEntry.firstChild.firstChild is KtNameReferenceExpression
myMatchingVisitor.result =
(bypassElseTest && other.isElse || myMatchingVisitor.matchInAnyOrder(ktWhenEntry.conditions, other.conditions))
&& myMatchingVisitor.match(ktWhenEntry.expression, other.expression)
&& (bypassElseTest || ktWhenEntry.isElse == other.isElse)
}
override fun visitWhenExpression(expression: KtWhenExpression) {
val other = getTreeElementDepar<KtWhenExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.subjectExpression, other.subjectExpression)
&& myMatchingVisitor.matchInAnyOrder(expression.entries, other.entries)
}
override fun visitFinallySection(finallySection: KtFinallySection) {
val other = getTreeElementDepar<KtFinallySection>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(finallySection.finalExpression, other.finalExpression)
}
override fun visitCatchSection(catchClause: KtCatchClause) {
val other = getTreeElementDepar<KtCatchClause>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(catchClause.parameterList, other.parameterList)
&& myMatchingVisitor.match(catchClause.catchBody, other.catchBody)
}
override fun visitTryExpression(expression: KtTryExpression) {
val other = getTreeElementDepar<KtTryExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.tryBlock, other.tryBlock)
&& myMatchingVisitor.matchInAnyOrder(expression.catchClauses, other.catchClauses)
&& myMatchingVisitor.match(expression.finallyBlock, other.finallyBlock)
}
override fun visitTypeAlias(typeAlias: KtTypeAlias) {
val other = getTreeElementDepar<KtTypeAlias>() ?: return
myMatchingVisitor.result = matchTextOrVariable(typeAlias.nameIdentifier, other.nameIdentifier)
&& myMatchingVisitor.match(typeAlias.getTypeReference(), other.getTypeReference())
&& myMatchingVisitor.matchInAnyOrder(typeAlias.annotationEntries, other.annotationEntries)
val handler = getHandler(typeAlias.nameIdentifier!!)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
override fun visitConstructorCalleeExpression(constructorCalleeExpression: KtConstructorCalleeExpression) {
val other = getTreeElementDepar<KtConstructorCalleeExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(
constructorCalleeExpression.constructorReferenceExpression, other.constructorReferenceExpression
)
}
override fun visitAnnotationEntry(annotationEntry: KtAnnotationEntry) {
val other = getTreeElementDepar<KtAnnotationEntry>() ?: return
val parameters = resolveParameters(other)
myMatchingVisitor.result = myMatchingVisitor.match(annotationEntry.calleeExpression, other.calleeExpression)
&& myMatchingVisitor.match(annotationEntry.typeArgumentList, other.typeArgumentList)
&& matchValueArguments(
parameters,
annotationEntry.valueArgumentList, other.valueArgumentList, annotationEntry.lambdaArguments, other.lambdaArguments
)
&& matchTextOrVariable(annotationEntry.useSiteTarget, other.useSiteTarget)
}
override fun visitAnnotatedExpression(expression: KtAnnotatedExpression) {
myMatchingVisitor.result = when (val other = myMatchingVisitor.element) {
is KtAnnotatedExpression -> myMatchingVisitor.match(expression.baseExpression, other.baseExpression)
&& myMatchingVisitor.matchInAnyOrder(expression.annotationEntries, other.annotationEntries)
else -> myMatchingVisitor.match(expression.baseExpression, other) && expression.annotationEntries.all {
val handler = getHandler(it); handler is SubstitutionHandler && handler.minOccurs == 0
}
}
}
override fun visitProperty(property: KtProperty) {
val other = getTreeElementDepar<KtProperty>() ?: return
myMatchingVisitor.result = matchTypeReferenceWithDeclaration(property.typeReference, other)
&& myMatchingVisitor.match(property.modifierList, other.modifierList)
&& matchTextOrVariable(property.nameIdentifier, other.nameIdentifier)
&& myMatchingVisitor.match(property.docComment, other.docComment)
&& myMatchingVisitor.matchOptionally(
property.delegateExpressionOrInitializer,
other.delegateExpressionOrInitializer
)
&& myMatchingVisitor.match(property.getter, other.getter)
&& myMatchingVisitor.match(property.setter, other.setter)
&& myMatchingVisitor.match(property.receiverTypeReference, other.receiverTypeReference)
val handler = getHandler(property.nameIdentifier!!)
if (myMatchingVisitor.result && handler is SubstitutionHandler) {
handler.handle(other.nameIdentifier, myMatchingVisitor.matchContext)
}
}
override fun visitPropertyAccessor(accessor: KtPropertyAccessor) {
val other = getTreeElementDepar<KtPropertyAccessor>() ?: return
val accessorBody = if (accessor.hasBlockBody()) accessor.bodyBlockExpression else accessor.bodyExpression
val otherBody = if (other.hasBlockBody()) other.bodyBlockExpression else other.bodyExpression
myMatchingVisitor.result = myMatchingVisitor.match(accessor.modifierList, other.modifierList)
&& myMatchingVisitor.matchNormalized(accessorBody, otherBody, true)
}
override fun visitStringTemplateExpression(expression: KtStringTemplateExpression) {
val other = getTreeElementDepar<KtStringTemplateExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(expression.entries, other.entries)
}
override fun visitSimpleNameStringTemplateEntry(entry: KtSimpleNameStringTemplateEntry) {
val other = getTreeElement<KtStringTemplateEntry>() ?: return
val handler = getHandler(entry)
if (handler is SubstitutionHandler) {
myMatchingVisitor.result = handler.handle(other, myMatchingVisitor.matchContext)
return
}
myMatchingVisitor.result = when (other) {
is KtSimpleNameStringTemplateEntry, is KtBlockStringTemplateEntry ->
myMatchingVisitor.match(entry.expression, other.expression)
else -> false
}
}
override fun visitLiteralStringTemplateEntry(entry: KtLiteralStringTemplateEntry) {
val other = myMatchingVisitor.element
myMatchingVisitor.result = when (val handler = entry.getUserData(CompiledPattern.HANDLER_KEY)) {
is LiteralWithSubstitutionHandler -> handler.match(entry, other, myMatchingVisitor.matchContext)
else -> matchTextOrVariable(entry, other)
}
}
override fun visitBlockStringTemplateEntry(entry: KtBlockStringTemplateEntry) {
val other = getTreeElementDepar<KtBlockStringTemplateEntry>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(entry.expression, other.expression)
}
override fun visitEscapeStringTemplateEntry(entry: KtEscapeStringTemplateEntry) {
val other = getTreeElementDepar<KtEscapeStringTemplateEntry>() ?: return
myMatchingVisitor.result = matchTextOrVariable(entry, other)
}
override fun visitBinaryWithTypeRHSExpression(expression: KtBinaryExpressionWithTypeRHS) {
val other = getTreeElementDepar<KtBinaryExpressionWithTypeRHS>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.operationReference, other.operationReference)
&& myMatchingVisitor.match(expression.left, other.left)
&& myMatchingVisitor.match(expression.right, other.right)
}
override fun visitIsExpression(expression: KtIsExpression) {
val other = getTreeElementDepar<KtIsExpression>() ?: return
myMatchingVisitor.result = expression.isNegated == other.isNegated
&& myMatchingVisitor.match(expression.leftHandSide, other.leftHandSide)
&& myMatchingVisitor.match(expression.typeReference, other.typeReference)
}
override fun visitDestructuringDeclaration(destructuringDeclaration: KtDestructuringDeclaration) {
val other = getTreeElementDepar<KtDestructuringDeclaration>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchSequentially(destructuringDeclaration.entries, other.entries)
&& myMatchingVisitor.match(destructuringDeclaration.initializer, other.initializer)
&& myMatchingVisitor.match(destructuringDeclaration.docComment, other.docComment)
}
override fun visitDestructuringDeclarationEntry(multiDeclarationEntry: KtDestructuringDeclarationEntry) {
val other = getTreeElementDepar<KtDestructuringDeclarationEntry>() ?: return
myMatchingVisitor.result = matchTypeReferenceWithDeclaration(multiDeclarationEntry.typeReference, other)
&& myMatchingVisitor.match(multiDeclarationEntry.modifierList, other.modifierList)
&& multiDeclarationEntry.isVar == other.isVar
&& matchTextOrVariable(multiDeclarationEntry.nameIdentifier, other.nameIdentifier)
}
override fun visitThrowExpression(expression: KtThrowExpression) {
val other = getTreeElementDepar<KtThrowExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.referenceExpression(), other.referenceExpression())
}
override fun visitClassLiteralExpression(expression: KtClassLiteralExpression) {
val other = getTreeElementDepar<KtClassLiteralExpression>() ?: return
myMatchingVisitor.result = myMatchingVisitor.match(expression.firstChild, other.firstChild)
|| other.resolveType()?.let { resolved ->
myMatchingVisitor.matchText(expression.text, resolved.arguments.first().type.fqName.toString())
} ?: false
}
override fun visitComment(comment: PsiComment) {
val other = getTreeElementDepar<PsiComment>() ?: return
when (val handler = comment.getUserData(CompiledPattern.HANDLER_KEY)) {
is LiteralWithSubstitutionHandler -> {
if (other is KDocImpl) {
myMatchingVisitor.result = handler.match(comment, other, myMatchingVisitor.matchContext)
} else {
val offset = 2 + other.text.substring(2).indexOfFirst { it > ' ' }
myMatchingVisitor.result = handler.match(other, getCommentText(other), offset, myMatchingVisitor.matchContext)
}
}
is SubstitutionHandler -> {
handler.findRegExpPredicate()?.let {
it.setNodeTextGenerator { comment -> getCommentText(comment as PsiComment) }
}
myMatchingVisitor.result = handler.handle(
other,
2,
other.textLength - if (other.tokenType == KtTokens.EOL_COMMENT) 0 else 2,
myMatchingVisitor.matchContext
)
}
else -> myMatchingVisitor.result = myMatchingVisitor.matchText(
StructuralSearchUtil.normalize(getCommentText(comment)),
StructuralSearchUtil.normalize(getCommentText(other))
)
}
}
override fun visitKDoc(kDoc: KDoc) {
val other = getTreeElementDepar<KDoc>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(
kDoc.getChildrenOfType<KDocSection>(),
other.getChildrenOfType<KDocSection>()
)
}
override fun visitKDocSection(section: KDocSection) {
val other = getTreeElementDepar<KDocSection>() ?: return
val important: (PsiElement) -> Boolean = {
it.elementType != KDocTokens.LEADING_ASTERISK
&& !(it.elementType == KDocTokens.TEXT && it.text.trim().isEmpty())
}
myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(
section.allChildren.filter(important).toList(),
other.allChildren.filter(important).toList()
)
}
override fun visitKDocTag(tag: KDocTag) {
val other = getTreeElementDepar<KDocTag>() ?: return
myMatchingVisitor.result = myMatchingVisitor.matchInAnyOrder(tag.getChildrenOfType(), other.getChildrenOfType())
}
override fun visitKDocLink(link: KDocLink) {
val other = getTreeElementDepar<KDocLink>() ?: return
myMatchingVisitor.result = matchTextOrVariable(link, other)
}
companion object {
private val augmentedAssignmentsMap = mapOf(
KtTokens.PLUSEQ to KtTokens.PLUS,
KtTokens.MINUSEQ to KtTokens.MINUS,
KtTokens.MULTEQ to KtTokens.MUL,
KtTokens.DIVEQ to KtTokens.DIV,
KtTokens.PERCEQ to KtTokens.PERC
)
}
}
| apache-2.0 | 42c2bd772dbd685fdd3457b8368d01d3 | 53.239079 | 162 | 0.665339 | 5.738886 | false | false | false | false |
mr-max/anko | preview/idea-plugin/src/org/jetbrains/kotlin/android/dslpreview/RobowrapperDependencies.kt | 5 | 1757 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.dslpreview
import com.intellij.openapi.application.PathManager
import java.io.File
object RobowrapperDependencies {
val DEPENDENCIES_DIRECTORY: File = File(PathManager.getSystemPath(), "dsl-plugin/deps")
val ANDROID_ALL_DEPENDENCY = Dependency("org.robolectric", "android-all", "5.0.0_r2-robolectric-1")
val DEPENDENCIES: List<Dependency> = listOf(
ANDROID_ALL_DEPENDENCY,
Dependency("org.robolectric", "shadows-core", "3.0-rc3", postfix = "-21"),
Dependency("org.robolectric", "shadows-support-v4", "3.0-rc3", postfix = "-21"),
Dependency("org.json", "json", "20080701"),
Dependency("org.ccil.cowan.tagsoup", "tagsoup", "1.2")
)
}
private class Dependency(
group: String,
artifact: String,
version: String,
extension: String = "jar",
postfix: String? = ""
) {
val downloadUrl = "http://central.maven.org/maven2/${group.replace('.', '/')}/" +
"$artifact/$version/$artifact-$version.$extension"
val file = File(RobowrapperDependencies.DEPENDENCIES_DIRECTORY, "$artifact-$version$postfix.$extension")
} | apache-2.0 | c873d216716441ecaa0dd47d65597608 | 35.625 | 108 | 0.688105 | 3.870044 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/mvn/Artifact.kt | 1 | 773 | package com.cognifide.gradle.aem.common.mvn
class Artifact(val notation: String) {
val id get() = notation.substringBeforeLast(":")
val extension get() = notation.substringAfterLast(":")
override fun toString() = "Artifact(id='$id', extension='$extension')"
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Artifact
if (notation != other.notation) return false
return true
}
override fun hashCode() = notation.hashCode()
companion object {
const val POM = "pom"
const val ZIP = "zip"
const val JAR = "jar"
const val RUN = "run"
}
}
fun String.toArtifact() = Artifact(this)
| apache-2.0 | ce2337a429fc9ab668db9bab88ec680d | 22.424242 | 74 | 0.617076 | 4.392045 | false | false | false | false |
Cognifide/gradle-aem-plugin | src/main/kotlin/com/cognifide/gradle/aem/common/instance/provision/Condition.kt | 1 | 3204 | package com.cognifide.gradle.aem.common.instance.provision
import com.cognifide.gradle.common.utils.Formats
import com.cognifide.gradle.common.utils.Patterns
import java.util.concurrent.ThreadLocalRandom
import java.util.concurrent.TimeUnit
@Suppress("FunctionOnlyReturningConstant")
class Condition(val step: InstanceStep) {
val instance = step.instance
// Partial conditions
fun always(): Boolean = true
fun never(): Boolean = false
fun greedy(): Boolean = step.greedy
fun rerunOnFail(): Boolean = step.ended && step.failed && step.definition.rerunOnFail.get()
fun sinceEndedMoreThan(millis: Long) = step.ended && !Formats.durationFit(step.endedAt.time, instance.zoneId, millis)
fun onEnv(env: String) = Patterns.wildcard(instance.env, env)
fun onImage() = step.definition.provisioner.aem.commonOptions.envImage
fun onInstance(name: String) = Patterns.wildcard(instance.name, name)
fun onAuthor() = instance.author
fun onPublish() = instance.publish
fun onLocal() = instance.local
fun onRemote() = !onLocal()
fun onRunMode(vararg modes: String) = onRunMode(modes.asIterable())
fun onRunMode(modes: Iterable<String>, except: Iterable<String> = listOf()) = instance.runningModes.run {
containsAll(modes.toList()) && none { except.contains(it) }
}
// Complete conditions
/**
* Perform step only once, but try again if it fails.
*/
fun once() = greedy() || failSafeOnce()
/**
* Perform step only once, but try again if it fails.
*/
fun failSafeOnce(): Boolean = ultimateOnce() || rerunOnFail()
/**
* Perform step only once regardless if it fails or not.
*/
fun ultimateOnce() = !step.ended || step.changed
/**
* Repeat performing step after specified number of milliseconds since last time.
*/
fun repeatAfter(millis: Long): Boolean = failSafeOnce() || sinceEndedMoreThan(millis)
/**
* Repeat performing step after specified number of seconds since last time.
*/
fun repeatAfterSeconds(count: Long) = repeatAfter(TimeUnit.SECONDS.toMillis(count))
/**
* Repeat performing step after specified number of minutes since last time.
*/
fun repeatAfterMinutes(count: Long) = repeatAfter(TimeUnit.MINUTES.toMillis(count))
/**
* Repeat performing step after specified number of hours since last time.
*/
fun repeatAfterHours(count: Long) = repeatAfter(TimeUnit.HOURS.toMillis(count))
/**
* Repeat performing step after specified number of days since last time.
*/
fun repeatAfterDays(count: Long) = repeatAfter(TimeUnit.DAYS.toMillis(count))
/**
* Repeat performing step basing on counter based predicate.
*/
fun repeatEvery(counterPredicate: (Long) -> Boolean) = counterPredicate(step.counter)
/**
* Repeat performing step every n-times.
*/
fun repeatEvery(times: Long) = repeatEvery { counter -> counter % times == 0L }
/**
* Repeat performing step with a probability specified as percentage [0, 1.0).
*/
fun repeatProbably(probability: Double) = ThreadLocalRandom.current().nextDouble() <= probability
}
| apache-2.0 | 7f757d85271793002eb6ff087e07b725 | 30.722772 | 121 | 0.68789 | 4.277704 | false | false | false | false |
NlRVANA/Unity | app/src/main/java/com/zwq65/unity/data/network/ApiHelper.kt | 1 | 2206 | /*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zwq65.unity.data.network
import com.zwq65.unity.data.network.retrofit.response.GankApiResponse
import com.zwq65.unity.data.network.retrofit.response.enity.Article
import com.zwq65.unity.data.network.retrofit.response.enity.Image
import com.zwq65.unity.data.network.retrofit.response.enity.Video
import io.reactivex.Observable
/**
* ================================================
* 网络访问接口
* <p>
* Created by NIRVANA on 2017/01/27.
* Contact with <[email protected]>
* ================================================
*/
interface ApiHelper {
/**
* 获取随机数目的image'list
*
*/
fun getRandomImages(): Observable<GankApiResponse<List<Image>>>
/**
* 获取page页的image'list
*
* @param page 页数
*/
fun get20Images(page: Int): Observable<GankApiResponse<List<Image>>>
/**
* 同时获取相同数量的image和video实例
*
* @param page 页数
*/
fun getVideosAndImages(page: Int): Observable<List<Video>>
/**
* 获取page页的android'list
*
* @param page 页数
*/
fun getAndroidArticles(page: Int): Observable<List<Article>>
/**
* 获取page页的ios'list
*
* @param page 页数
*/
fun getIosArticles(page: Int): Observable<List<Article>>
/**
* 获取page页的前端'list
*
* @param page 页数
*/
fun getQianduanArticles(page: Int): Observable<List<Article>>
}
| apache-2.0 | 2a38eb85c3834ba112b1e07a67c905ea | 26.631579 | 78 | 0.608095 | 3.839122 | false | false | false | false |
simonnorberg/dmach | app/src/main/java/net/simno/dmach/machine/MachineScreen.kt | 1 | 9412 | package net.simno.dmach.machine
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBarsPadding
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawingPadding
import androidx.compose.foundation.layout.systemBarsPadding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DeleteForever
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Tune
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.stringResource
import androidx.navigation.NavController
import net.simno.dmach.Destination
import net.simno.dmach.R
import net.simno.dmach.core.DarkMediumText
import net.simno.dmach.core.DarkSmallText
import net.simno.dmach.core.IconButton
import net.simno.dmach.core.TextButton
import net.simno.dmach.data.Channel
import net.simno.dmach.theme.AppTheme
@Composable
fun MachineScreen(
navController: NavController,
viewModel: MachineViewModel
) {
val state by viewModel.viewState.collectAsState()
Machine(
state = state,
onAction = viewModel::onAction,
onClickPatch = { navController.navigate(Destination.Patch.name) }
)
}
@Composable
private fun Machine(
state: ViewState,
onAction: (Action) -> Unit,
onClickPatch: () -> Unit
) {
val buttonLarge = AppTheme.dimens.ButtonLarge
val buttonSmall = AppTheme.dimens.ButtonSmall
val paddingLarge = AppTheme.dimens.PaddingLarge
val paddingMedium = AppTheme.dimens.PaddingMedium
val paddingSmall = AppTheme.dimens.PaddingSmall
Column(
modifier = Modifier
.fillMaxSize()
.systemBarsPadding()
.navigationBarsPadding()
.safeDrawingPadding()
.padding(paddingSmall)
) {
Row(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(.16f)
.padding(start = paddingSmall, top = paddingSmall, end = paddingSmall),
horizontalArrangement = Arrangement.spacedBy(paddingMedium)
) {
IconButton(
icon = Icons.Filled.PlayArrow,
iconPadding = AppTheme.dimens.PaddingSmall,
description = R.string.description_play,
selected = state.isPlaying,
modifier = Modifier
.width(buttonLarge)
.wrapContentWidth(),
onClick = { onAction(PlayPauseAction) }
)
IconButton(
icon = Icons.Filled.Tune,
description = R.string.description_config,
selected = state.showConfig,
modifier = Modifier
.width(buttonLarge)
.wrapContentWidth(),
onClick = { onAction(ConfigAction) }
)
IconButton(
icon = Icons.Filled.DeleteForever,
description = R.string.description_reset,
selected = false,
modifier = Modifier
.width(buttonLarge)
.wrapContentWidth(),
onClick = { onAction(ChangeSequenceAction.Empty) }
)
IconButton(
icon = Icons.Filled.Refresh,
description = R.string.description_random,
selected = false,
modifier = Modifier
.width(buttonLarge)
.wrapContentWidth(),
onClick = { onAction(ChangeSequenceAction.Randomize()) }
)
Row(
modifier = Modifier
.weight(1f)
.fillMaxSize()
.clip(MaterialTheme.shapes.medium)
.clickable(onClick = onClickPatch)
.padding(paddingSmall),
horizontalArrangement = Arrangement.spacedBy(paddingLarge)
) {
Column(
modifier = Modifier
.weight(1f)
.align(Alignment.CenterVertically)
.padding(horizontal = paddingSmall),
verticalArrangement = Arrangement.Center
) {
DarkSmallText(stringResource(R.string.patch_name).uppercase())
DarkMediumText(state.title)
}
Column(
modifier = Modifier.align(Alignment.CenterVertically),
verticalArrangement = Arrangement.Center
) {
DarkSmallText(stringResource(R.string.patch_swing).uppercase())
DarkMediumText(state.swing.toString())
}
Column(
modifier = Modifier.align(Alignment.CenterVertically),
verticalArrangement = Arrangement.Center
) {
DarkSmallText(stringResource(R.string.patch_bpm).uppercase())
DarkMediumText(state.tempo.toString())
}
}
}
Row {
Column(
modifier = Modifier
.fillMaxHeight()
.width(buttonSmall)
.padding(start = paddingSmall, top = paddingSmall, bottom = paddingSmall),
verticalArrangement = Arrangement.spacedBy(paddingSmall)
) {
ChannelName.values().forEachIndexed { index, channelName ->
TextButton(
text = channelName.name,
selected = state.selectedChannel == index,
modifier = Modifier
.weight(1f)
.fillMaxSize(),
onClick = { onAction(SelectChannelAction(index, state.selectedChannel == index)) }
)
}
}
if (state.selectedChannel == Channel.NONE_ID) {
StepSequencer(
sequenceId = state.sequenceId,
sequence = state.sequence,
modifier = Modifier.padding(paddingSmall),
onSequence = { sequence -> onAction(ChangeSequenceAction.Edit(state.sequenceId, sequence)) }
)
} else {
Column(
modifier = Modifier
.fillMaxHeight()
.width(buttonSmall)
.padding(start = paddingSmall, top = paddingSmall, bottom = paddingSmall),
verticalArrangement = Arrangement.spacedBy(paddingSmall)
) {
(1..6).forEachIndexed { index, name ->
TextButton(
text = name.toString(),
selected = state.selectedSetting == index,
modifier = Modifier
.weight(1f)
.fillMaxSize(),
enabled = state.settingsSize > index,
radioButton = true,
onClick = { onAction(SelectSettingAction(index)) }
)
}
}
ChaosPad(
settingId = state.settingId,
position = state.position,
horizontalText = state.hText,
verticalText = state.vText,
modifier = Modifier
.weight(1f)
.padding(paddingSmall),
onPosition = { onAction(ChangePositionAction(it)) }
)
PanFader(
panId = state.panId,
pan = state.pan,
modifier = Modifier
.padding(top = paddingSmall, end = paddingSmall, bottom = paddingSmall),
onPan = { onAction(ChangePanAction(it)) }
)
}
}
}
if (state.showConfig) {
ConfigDialog(
configId = state.configId,
tempo = state.tempo,
swing = state.swing,
ignoreAudioFocus = state.ignoreAudioFocus,
onTempo = { onAction(ChangeTempoAction(it)) },
onSwing = { onAction(ChangeSwingAction(it)) },
onAudioFocus = { onAction(AudioFocusAction(it)) },
onDismissRequest = { onAction(DismissAction) }
)
}
}
private enum class ChannelName { BD, SD, CP, TT, CB, HH }
| gpl-3.0 | dc5b319306ec84a2527f6a2884a510be | 39.568966 | 112 | 0.551424 | 5.552802 | false | false | false | false |
ThiagoGarciaAlves/intellij-community | platform/script-debugger/backend/src/debugger/BreakpointManagerBase.kt | 2 | 5131 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.concurrency.ConcurrentCollectionFactory
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.EventDispatcher
import com.intellij.util.SmartList
import com.intellij.util.Url
import com.intellij.util.containers.ContainerUtil
import gnu.trove.TObjectHashingStrategy
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.all
import org.jetbrains.concurrency.nullPromise
import org.jetbrains.concurrency.rejectedPromise
import java.util.concurrent.ConcurrentMap
abstract class BreakpointManagerBase<T : BreakpointBase<*>> : BreakpointManager {
override val breakpoints = ContainerUtil.newConcurrentSet<T>()
protected val breakpointDuplicationByTarget: ConcurrentMap<T, T> = ConcurrentCollectionFactory.createMap<T, T>(object : TObjectHashingStrategy<T> {
override fun computeHashCode(b: T): Int {
var result = b.line
result *= 31 + b.column
if (b.condition != null) {
result *= 31 + b.condition!!.hashCode()
}
result *= 31 + b.target.hashCode()
return result
}
override fun equals(b1: T, b2: T) =
b1.target.javaClass == b2.target.javaClass &&
b1.target == b2.target &&
b1.line == b2.line &&
b1.column == b2.column &&
StringUtil.equals(b1.condition, b2.condition)
})
protected val dispatcher: EventDispatcher<BreakpointListener> = EventDispatcher.create(BreakpointListener::class.java)
protected abstract fun createBreakpoint(target: BreakpointTarget, line: Int, column: Int, condition: String?, ignoreCount: Int, enabled: Boolean): T
protected abstract fun doSetBreakpoint(target: BreakpointTarget, url: Url?, breakpoint: T): Promise<out Breakpoint>
override fun setBreakpoint(target: BreakpointTarget,
line: Int,
column: Int,
url: Url?,
condition: String?,
ignoreCount: Int): BreakpointManager.SetBreakpointResult {
val breakpoint = createBreakpoint(target, line, column, condition, ignoreCount, true)
val existingBreakpoint = breakpointDuplicationByTarget.putIfAbsent(breakpoint, breakpoint)
if (existingBreakpoint != null) {
return BreakpointManager.BreakpointExist(existingBreakpoint)
}
breakpoints.add(breakpoint)
val promise = doSetBreakpoint(target, url, breakpoint)
.rejected { dispatcher.multicaster.errorOccurred(breakpoint, it.message ?: it.toString()) }
return BreakpointManager.BreakpointCreated(breakpoint, promise)
}
override final fun remove(breakpoint: Breakpoint): Promise<*> {
@Suppress("UNCHECKED_CAST")
val b = breakpoint as T
val existed = breakpoints.remove(b)
if (existed) {
breakpointDuplicationByTarget.remove(b)
}
return if (!existed || !b.isVmRegistered()) nullPromise() else doClearBreakpoint(b)
}
override final fun removeAll(): Promise<*> {
val list = breakpoints.toList()
breakpoints.clear()
breakpointDuplicationByTarget.clear()
val promises = SmartList<Promise<*>>()
for (b in list) {
if (b.isVmRegistered()) {
promises.add(doClearBreakpoint(b))
}
}
return all(promises)
}
protected abstract fun doClearBreakpoint(breakpoint: T): Promise<*>
override final fun addBreakpointListener(listener: BreakpointListener) {
dispatcher.addListener(listener)
}
protected fun notifyBreakpointResolvedListener(breakpoint: T) {
if (breakpoint.isResolved) {
dispatcher.multicaster.resolved(breakpoint)
}
}
@Suppress("UNCHECKED_CAST")
override fun flush(breakpoint: Breakpoint) = (breakpoint as T).flush(this)
override fun enableBreakpoints(enabled: Boolean): Promise<*> = rejectedPromise<Any?>("Unsupported")
}
// used in goland
@Suppress("unused")
class DummyBreakpointManager : BreakpointManager {
override val breakpoints: Iterable<Breakpoint>
get() = emptyList()
override fun setBreakpoint(target: BreakpointTarget, line: Int, column: Int, url: Url?, condition: String?, ignoreCount: Int): BreakpointManager.SetBreakpointResult {
throw UnsupportedOperationException()
}
override fun remove(breakpoint: Breakpoint) = nullPromise()
override fun addBreakpointListener(listener: BreakpointListener) {
}
override fun removeAll() = nullPromise()
override fun flush(breakpoint: Breakpoint) = nullPromise()
override fun enableBreakpoints(enabled: Boolean) = nullPromise()
} | apache-2.0 | 1ca8439ac1526d0f54b40235a78be834 | 36.188406 | 168 | 0.719938 | 4.540708 | false | false | false | false |
breadwallet/breadwallet-android | app/src/main/java/com/breadwallet/ui/addwallets/AddTokenListAdapter.kt | 1 | 5623 | /**
* BreadWallet
*
* Created by Ahsan Butt <[email protected]> on 10/11/19.
* Copyright (c) 2019 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.ui.addwallets
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.GradientDrawable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.breadwallet.R
import com.breadwallet.tools.util.TokenUtil
import com.squareup.picasso.Picasso
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import java.io.File
import java.util.Locale
class AddTokenListAdapter(
private val tokensFlow: Flow<List<Token>>,
private val sendChannel: SendChannel<AddWallets.E>
) : RecyclerView.Adapter<AddTokenListAdapter.TokenItemViewHolder>() {
private var tokens: List<Token> = emptyList()
private val scope = CoroutineScope(Dispatchers.Main)
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
tokensFlow
.onEach { tokens ->
this.tokens = tokens
notifyDataSetChanged()
}
.launchIn(scope)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
scope.coroutineContext.cancelChildren()
}
override fun onBindViewHolder(holder: TokenItemViewHolder, position: Int) {
val token = tokens[position]
val currencyCode = token.currencyCode.toLowerCase(Locale.ROOT)
val tokenIconPath = TokenUtil.getTokenIconPath(currencyCode, true)
val iconDrawable = holder.iconParent.background as GradientDrawable
when {
tokenIconPath == null -> {
// If no icon is present, then use the capital first letter of the token currency code instead.
holder.iconLetter.visibility = View.VISIBLE
iconDrawable.setColor(Color.parseColor(token.startColor))
holder.iconLetter.text = currencyCode.substring(0, 1).toUpperCase(Locale.ROOT)
holder.logo.visibility = View.GONE
}
else -> {
val iconFile = File(tokenIconPath)
Picasso.get().load(iconFile).into(holder.logo)
holder.iconLetter.visibility = View.GONE
holder.logo.visibility = View.VISIBLE
iconDrawable.setColor(Color.TRANSPARENT)
}
}
holder.name.text = token.name
holder.symbol.text = token.currencyCode.toUpperCase(Locale.ROOT)
holder.addRemoveButton.apply {
text = context.getString(
when {
token.enabled -> R.string.TokenList_remove
else -> R.string.TokenList_add
}
)
isEnabled = !token.enabled || token.removable
setOnClickListener {
if (token.enabled) {
sendChannel.offer(AddWallets.E.OnRemoveWalletClicked(token))
} else {
sendChannel.offer(AddWallets.E.OnAddWalletClicked(token))
}
}
}
}
override fun getItemCount(): Int {
return tokens.size
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): TokenItemViewHolder {
val inflater = LayoutInflater.from(parent.context)
val convertView = inflater.inflate(R.layout.token_list_item, parent, false)
val holder = TokenItemViewHolder(convertView)
holder.setIsRecyclable(false)
return holder
}
inner class TokenItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val logo: ImageView = view.findViewById(R.id.token_icon)
val symbol: TextView = view.findViewById(R.id.token_symbol)
val name: TextView = view.findViewById(R.id.token_name)
val addRemoveButton: Button = view.findViewById(R.id.add_remove_button)
val iconParent: View = view.findViewById(R.id.icon_parent)
val iconLetter: TextView = view.findViewById(R.id.icon_letter)
}
}
| mit | 58d943922da0bfc6120555f97b31232d | 37.513699 | 111 | 0.687889 | 4.773345 | false | false | false | false |
koma-im/koma | src/test/kotlin/link/continuum/desktop/database/models/ConfigurationKVKtTest.kt | 1 | 565 | package link.continuum.desktop.database.models
import link.continuum.database.models.deserialize
import link.continuum.database.models.serialize
import kotlin.test.Test
import kotlin.test.assertEquals
internal class ConfigurationKVKtTest
class Test {
@Test
fun testSerialization() {
val x = "hello"
val b = serialize(x)!!
val y = deserialize<String>(b)
assertEquals(x, y)
val x1 = listOf("hello")
val b1 = serialize(x1)!!
val y1 = deserialize<List<String>>(b1)
assertEquals(x1, y1)
}
}
| gpl-3.0 | 91943123769b684de6f500b137874b7b | 24.681818 | 49 | 0.667257 | 3.843537 | false | true | false | false |
AlmasB/Zephyria | src/main/kotlin/com/almasb/zeph/data/Quests.kt | 1 | 1466 | package com.almasb.zeph.data
import com.almasb.zeph.combat.XP
import com.almasb.zeph.data.Data.Maps
import com.almasb.zeph.data.Data.UsableItems
import com.almasb.zeph.data.Data.Monsters
import com.almasb.zeph.data.Data.NPCs
import com.almasb.zeph.quest.quest
/**
* Quests [7500-7999].
*
* @author Almas Baimagambetov ([email protected])
*/
class Quests {
val SARAH_HEALING_HERBS = quest {
desc {
id = 7500
name = "A cure..."
}
rewardMoney = 50
rewardXP = XP(1, 1, 5)
collect {
UsableItems.HEALING_HERBS x 5
}
}
val TUTORIAL_KILLS = quest {
desc {
id = 7501
name = "A new beginning"
}
rewardMoney = 70
rewardXP = XP(2, 2, 2)
kill {
Monsters.SKELETON_WARRIOR x 3
}
}
val TUTORIAL_GOTO = quest {
desc {
id = 7502
name = "Finding your way"
description = "This tutorial tells you how to move around."
}
rewardMoney = 10
rewardXP = XP(3, 2, 1)
go {
Maps.TUTORIAL_MAP at p(5, 5)
}
}
val TUTORIAL_TALKTO = quest {
desc {
id = 7503
name = "Networking is good"
description = "This tutorial tells you how to talk to NPCs."
}
rewardMoney = 20
rewardXP = XP(1, 2, 4)
talk(NPCs.SARAH)
}
} | gpl-2.0 | 1809a8c060bb401b3664a4ecc666c876 | 19.375 | 72 | 0.521146 | 3.610837 | false | false | false | false |
AlmasB/Zephyria | src/main/kotlin/com/almasb/zeph/ui/CharInfoView.kt | 1 | 4161 | package com.almasb.zeph.ui
import com.almasb.fxgl.dsl.FXGL
import com.almasb.zeph.character.CharacterEntity
import com.almasb.zeph.combat.Attribute
import com.almasb.zeph.combat.Stat
import javafx.beans.binding.Bindings
import javafx.beans.property.SimpleStringProperty
import javafx.geometry.Orientation
import javafx.scene.Cursor
import javafx.scene.ImageCursor
import javafx.scene.control.Separator
import javafx.scene.layout.*
import javafx.scene.paint.Color
import javafx.scene.text.Font
import javafx.scene.text.Text
/**
*
* @author Almas Baimagambetov ([email protected])
*/
class CharInfoView(player: CharacterEntity) : Region() {
init {
background = Background(BackgroundFill(Color.BLACK, null, null))
val font = Font.font("Lucida Console", 14.0)
val cursorQuestion: Cursor = ImageCursor(FXGL.image("ui/cursors/question.png"), 52.0, 10.0)
val attrBox = VBox(5.0)
attrBox.translateY = 10.0
for (attr in Attribute.values()) {
val text = Text()
text.font = font
text.fill = Color.WHITE
text.cursor = cursorQuestion
text.textProperty().bind(player.characterComponent.baseProperty(attr).asString("$attr: %-3d"))
val bText = Text()
bText.font = font
bText.fill = Color.YELLOW
bText.visibleProperty().bind(player.characterComponent.bonusProperty(attr).greaterThan(0))
bText.textProperty().bind(player.characterComponent.bonusProperty(attr).asString("+%d ")
.concat(player.characterComponent.totalProperty(attr).asString("(%d)")))
val btn = Text("+")
btn.cursor = Cursor.HAND
btn.stroke = Color.YELLOWGREEN.brighter()
btn.strokeWidth = 3.0
btn.font = font
btn.visibleProperty().bind(player.playerComponent!!.attributePoints.greaterThan(0)
.and(player.characterComponent.baseProperty(attr).lessThan(100)))
btn.setOnMouseClicked {
player.playerComponent!!.increaseAttribute(attr)
}
val box = Pane()
box.setPrefSize(160.0, 15.0)
box.children.addAll(text, bText, btn)
bText.translateX = 70.0
btn.translateX = 155.0
box.setOnTooltipHover {
it.setText(attr.description)
}
attrBox.children.add(box)
}
val info = Text()
info.font = font
info.fill = Color.WHITE
info.visibleProperty().bind(player.playerComponent!!.attributePoints.greaterThan(0))
info.textProperty().bind(SimpleStringProperty("Attribute Points: ").concat(player.playerComponent!!.attributePoints)
.concat("\nSkill Points: ").concat(player.playerComponent!!.skillPoints))
attrBox.children.addAll(Separator(), info)
val statBox = VBox(5.0)
for (stat in Stat.values()) {
val text = Text()
text.font = font
text.fill = Color.WHITE
text.cursor = cursorQuestion
val statName = stat.toString().replace("_", " ")
text.textProperty().bind(player.characterComponent.baseProperty(stat).asString("$statName: %d"))
val bText = Text()
bText.font = font
bText.fill = Color.YELLOW
val textBinding = Bindings.`when`(player.characterComponent.bonusProperty(stat).isNotEqualTo(0))
.then(player.characterComponent.bonusProperty(stat).asString("+%d ")
.concat(player.characterComponent.baseProperty(stat).add(player.characterComponent.bonusProperty(stat)).asString("(%d)"))
.concat(stat.measureUnit))
.otherwise(stat.measureUnit)
bText.textProperty().bind(textBinding)
val box = HBox(5.0, text, bText)
box.setOnTooltipHover {
it.setText(stat.description)
}
statBox.children.add(box)
}
children.add(HBox(10.0, attrBox, Separator(Orientation.VERTICAL), statBox))
}
} | gpl-2.0 | e7e41e4e51f61ba86c6ee4213bdf1be3 | 36.836364 | 149 | 0.619082 | 4.343424 | false | false | false | false |
osfans/trime | app/src/main/java/com/osfans/trime/ui/main/PrefMainActivity.kt | 1 | 6501 | package com.osfans.trime.ui.main
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.ViewGroup
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.forEach
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.blankj.utilcode.util.ToastUtils
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.osfans.trime.R
import com.osfans.trime.core.Rime
import com.osfans.trime.data.AppPrefs
import com.osfans.trime.databinding.ActivityPrefBinding
import com.osfans.trime.ui.setup.SetupActivity
import com.osfans.trime.util.applyTranslucentSystemBars
import com.osfans.trime.util.briefResultLogDialog
import com.osfans.trime.util.withLoadingDialog
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
class PrefMainActivity : AppCompatActivity() {
private val viewModel: MainViewModel by viewModels()
private val prefs get() = AppPrefs.defaultInstance()
private lateinit var navHostFragment: NavHostFragment
private fun onNavigateUpListener(): Boolean {
val navController = navHostFragment.navController
return when (navController.currentDestination?.id) {
R.id.prefFragment -> {
// "minimize" the app, don't exit activity
moveTaskToBack(false)
true
}
else -> onSupportNavigateUp()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
val uiMode = when (prefs.other.uiMode) {
"auto" -> AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM
"light" -> AppCompatDelegate.MODE_NIGHT_NO
"dark" -> AppCompatDelegate.MODE_NIGHT_YES
else -> AppCompatDelegate.MODE_NIGHT_UNSPECIFIED
}
AppCompatDelegate.setDefaultNightMode(uiMode)
super.onCreate(savedInstanceState)
applyTranslucentSystemBars()
val binding = ActivityPrefBinding.inflate(layoutInflater)
ViewCompat.setOnApplyWindowInsetsListener(binding.root) { _, windowInsets ->
val statusBars = windowInsets.getInsets(WindowInsetsCompat.Type.statusBars())
val navBars = windowInsets.getInsets(WindowInsetsCompat.Type.navigationBars())
binding.toolbar.appBar.updateLayoutParams<ViewGroup.MarginLayoutParams> {
leftMargin = navBars.left
rightMargin = navBars.right
}
binding.toolbar.toolbar.updateLayoutParams<ViewGroup.MarginLayoutParams> {
topMargin = statusBars.top
}
binding.navHostFragment.updateLayoutParams<ViewGroup.MarginLayoutParams> {
leftMargin = navBars.left
rightMargin = navBars.right
}
windowInsets
}
setContentView(binding.root)
setSupportActionBar(binding.toolbar.toolbar)
val appBarConfiguration = AppBarConfiguration(
topLevelDestinationIds = setOf(),
fallbackOnNavigateUpListener = ::onNavigateUpListener
)
navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
binding.toolbar.toolbar.setupWithNavController(navHostFragment.navController, appBarConfiguration)
viewModel.toolbarTitle.observe(this) {
binding.toolbar.toolbar.title = it
}
viewModel.topOptionsMenu.observe(this) {
binding.toolbar.toolbar.menu.forEach { m ->
m.isVisible = it
}
}
supportActionBar?.setDisplayHomeAsUpEnabled(true)
if (SetupActivity.shouldSetup()) {
startActivity(Intent(this, SetupActivity::class.java))
}
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.preference_main_menu, menu)
menu?.forEach {
it.isVisible = viewModel.topOptionsMenu.value ?: true
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.preference__menu_deploy -> {
lifecycleScope.withLoadingDialog(
context = this, titleId = R.string.deploy_progress
) {
withContext(Dispatchers.IO) {
Runtime.getRuntime().exec(arrayOf("logcat", "-c"))
}
withContext(Dispatchers.Default) {
Rime.destroy()
Rime.get(true)
}
briefResultLogDialog("rime.trime", "W", 1)
}
true
}
R.id.preference__menu_about -> {
navHostFragment.navController.navigate(R.id.action_prefFragment_to_aboutFragment)
true
}
else -> super.onOptionsItemSelected(item)
}
}
override fun onResume() {
super.onResume()
requestExternalStoragePermission()
}
private fun requestExternalStoragePermission() {
XXPermissions.with(this)
.permission(Permission.Group.STORAGE)
.request(object : OnPermissionCallback {
override fun onGranted(permissions: MutableList<String>?, all: Boolean) {
if (all) {
ToastUtils.showShort(R.string.external_storage_permission_granted)
}
}
override fun onDenied(permissions: MutableList<String>?, never: Boolean) {
if (never) {
ToastUtils.showShort(R.string.external_storage_permission_denied)
XXPermissions.startPermissionActivity(
this@PrefMainActivity, permissions
)
} else {
ToastUtils.showShort(R.string.external_storage_permission_denied)
}
}
})
}
}
| gpl-3.0 | b345e4b60a11ae879fdf97b33ae41ec8 | 38.4 | 106 | 0.638517 | 5.377171 | false | false | false | false |
BlueBoxWare/LibGDXPlugin | src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/atlas2/LibGDXAtlas2FileType.kt | 1 | 1202 | package com.gmail.blueboxware.libgdxplugin.filetypes.atlas2
import com.intellij.openapi.fileTypes.LanguageFileType
import icons.Icons
import javax.swing.Icon
/*
* Copyright 2022 Blue Box Ware
*
* 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.
*/
class LibGDXAtlas2FileType private constructor() : LanguageFileType(LibGDXAtlas2Language.INSTANCE) {
companion object {
val INSTANCE = LibGDXAtlas2FileType()
}
override fun getIcon(): Icon = Icons.ATLAS_FILETYPE
override fun getName(): String = "libGDX Atlas"
override fun getDefaultExtension() = "atlas"
@Suppress("DialogTitleCapitalization")
override fun getDescription() = "libGDX texture atlas file"
}
| apache-2.0 | 47961ee86fd41a5a8d2f699cc89410b5 | 30.631579 | 100 | 0.749584 | 4.468401 | false | false | false | false |
RocketChat/Rocket.Chat.Android | app/src/main/java/chat/rocket/android/dagger/module/ActivityBuilder.kt | 2 | 5492 | package chat.rocket.android.dagger.module
import chat.rocket.android.authentication.di.AuthenticationModule
import chat.rocket.android.authentication.login.di.LoginFragmentProvider
import chat.rocket.android.authentication.loginoptions.di.LoginOptionsFragmentProvider
import chat.rocket.android.authentication.onboarding.di.OnBoardingFragmentProvider
import chat.rocket.android.authentication.registerusername.di.RegisterUsernameFragmentProvider
import chat.rocket.android.authentication.resetpassword.di.ResetPasswordFragmentProvider
import chat.rocket.android.authentication.server.di.ServerFragmentProvider
import chat.rocket.android.authentication.signup.di.SignupFragmentProvider
import chat.rocket.android.authentication.twofactor.di.TwoFAFragmentProvider
import chat.rocket.android.authentication.ui.AuthenticationActivity
import chat.rocket.android.chatdetails.di.ChatDetailsFragmentProvider
import chat.rocket.android.chatinformation.di.MessageInfoFragmentProvider
import chat.rocket.android.chatinformation.ui.MessageInfoActivity
import chat.rocket.android.chatroom.di.ChatRoomFragmentProvider
import chat.rocket.android.chatroom.di.ChatRoomModule
import chat.rocket.android.chatroom.ui.ChatRoomActivity
import chat.rocket.android.chatrooms.di.ChatRoomsFragmentProvider
import chat.rocket.android.createchannel.di.CreateChannelProvider
import chat.rocket.android.dagger.scope.PerActivity
import chat.rocket.android.directory.di.DirectoryFragmentProvider
import chat.rocket.android.draw.main.di.DrawModule
import chat.rocket.android.draw.main.ui.DrawingActivity
import chat.rocket.android.favoritemessages.di.FavoriteMessagesFragmentProvider
import chat.rocket.android.files.di.FilesFragmentProvider
import chat.rocket.android.inviteusers.di.InviteUsersFragmentProvider
import chat.rocket.android.main.di.MainModule
import chat.rocket.android.main.ui.MainActivity
import chat.rocket.android.members.di.MembersFragmentProvider
import chat.rocket.android.mentions.di.MentionsFragmentProvider
import chat.rocket.android.pinnedmessages.di.PinnedMessagesFragmentProvider
import chat.rocket.android.profile.di.ProfileFragmentProvider
import chat.rocket.android.server.di.ChangeServerModule
import chat.rocket.android.server.ui.ChangeServerActivity
import chat.rocket.android.servers.di.ServersBottomSheetFragmentProvider
import chat.rocket.android.settings.di.SettingsFragmentProvider
import chat.rocket.android.settings.password.di.PasswordFragmentProvider
import chat.rocket.android.settings.password.ui.PasswordActivity
import chat.rocket.android.sortingandgrouping.di.SortingAndGroupingBottomSheetFragmentProvider
import chat.rocket.android.userdetails.di.UserDetailsFragmentProvider
import chat.rocket.android.videoconference.di.VideoConferenceModule
import chat.rocket.android.videoconference.ui.VideoConferenceActivity
import chat.rocket.android.webview.adminpanel.di.AdminPanelWebViewFragmentProvider
import dagger.Module
import dagger.android.ContributesAndroidInjector
@Module
abstract class ActivityBuilder {
@PerActivity
@ContributesAndroidInjector(
modules = [AuthenticationModule::class,
OnBoardingFragmentProvider::class,
ServerFragmentProvider::class,
LoginOptionsFragmentProvider::class,
LoginFragmentProvider::class,
RegisterUsernameFragmentProvider::class,
ResetPasswordFragmentProvider::class,
SignupFragmentProvider::class,
TwoFAFragmentProvider::class
]
)
abstract fun bindAuthenticationActivity(): AuthenticationActivity
@PerActivity
@ContributesAndroidInjector(
modules = [MainModule::class,
ChatRoomsFragmentProvider::class,
ServersBottomSheetFragmentProvider::class,
SortingAndGroupingBottomSheetFragmentProvider::class,
CreateChannelProvider::class,
ProfileFragmentProvider::class,
SettingsFragmentProvider::class,
AdminPanelWebViewFragmentProvider::class,
DirectoryFragmentProvider::class
]
)
abstract fun bindMainActivity(): MainActivity
@PerActivity
@ContributesAndroidInjector(
modules = [ChatRoomModule::class,
ChatRoomFragmentProvider::class,
UserDetailsFragmentProvider::class,
ChatDetailsFragmentProvider::class,
MembersFragmentProvider::class,
InviteUsersFragmentProvider::class,
MentionsFragmentProvider::class,
PinnedMessagesFragmentProvider::class,
FavoriteMessagesFragmentProvider::class,
FilesFragmentProvider::class
]
)
abstract fun bindChatRoomActivity(): ChatRoomActivity
@PerActivity
@ContributesAndroidInjector(modules = [PasswordFragmentProvider::class])
abstract fun bindPasswordActivity(): PasswordActivity
@PerActivity
@ContributesAndroidInjector(modules = [ChangeServerModule::class])
abstract fun bindChangeServerActivity(): ChangeServerActivity
@PerActivity
@ContributesAndroidInjector(modules = [MessageInfoFragmentProvider::class])
abstract fun bindMessageInfoActiviy(): MessageInfoActivity
@PerActivity
@ContributesAndroidInjector(modules = [DrawModule::class])
abstract fun bindDrawingActivity(): DrawingActivity
@PerActivity
@ContributesAndroidInjector(modules = [VideoConferenceModule::class])
abstract fun bindVideoConferenceActivity(): VideoConferenceActivity
}
| mit | a0268126454a9a5fde436ced1efeac46 | 46.344828 | 94 | 0.806264 | 5.190926 | false | false | false | false |
yrsegal/CommandControl | src/main/java/wiresegal/cmdctrl/common/commands/control/CommandMath.kt | 1 | 1956 | package wiresegal.cmdctrl.common.commands.control
import com.udojava.evalex.Expression.ExpressionException
import net.minecraft.command.CommandBase
import net.minecraft.command.CommandException
import net.minecraft.command.CommandResultStats
import net.minecraft.command.ICommandSender
import net.minecraft.server.MinecraftServer
import wiresegal.cmdctrl.common.CommandControl
import wiresegal.cmdctrl.common.core.CTRLException
import wiresegal.cmdctrl.common.core.CTRLUsageException
import wiresegal.cmdctrl.common.core.notifyCTRLListener
import java.math.BigDecimal
/**
* @author WireSegal
* Created at 5:20 PM on 12/14/16.
*/
object CommandMath : CommandBase() {
@Throws(CommandException::class)
override fun execute(server: MinecraftServer, sender: ICommandSender, args: Array<out String>) {
if (args.isEmpty()) throw CTRLUsageException(getCommandUsage(sender))
val expression = args.joinToString(" ")
val x = evaluate(args)
notifyCTRLListener(sender, this, "commandcontrol.math.expr", expression)
val formattedX: Number = if (x.toLong().toDouble() == x.toDouble()) x.toLong() else x.toDouble()
notifyCTRLListener(sender, this, "commandcontrol.math.answer", formattedX)
sender.setCommandStat(CommandResultStats.Type.QUERY_RESULT, x.toInt())
}
fun evaluate(args: Array<out String>): BigDecimal {
val expression = args.joinToString(" ")
val exprObj = ExpressionCommand(expression)
return try {
exprObj.eval()
} catch (e: ExpressionException) {
throw CommandException(e.message)
} catch (e: NumberFormatException) {
throw CTRLException("commandcontrol.math.invalidnumber")
}
}
override fun getRequiredPermissionLevel() = 0
override fun getCommandName() = "math"
override fun getCommandUsage(sender: ICommandSender?) = CommandControl.translate("commandcontrol.math.usage")
}
| mit | bb4bc38343fd214cb98e5e93147e0bfb | 39.75 | 113 | 0.73364 | 4.445455 | false | false | false | false |
OpenConference/OpenConference-android | app/src/main/java/com/openconference/util/FragmentExtensions.kt | 1 | 620 | package com.openconference.util
import android.app.Activity
import android.support.annotation.IntegerRes
import android.support.v4.app.Fragment
import android.util.DisplayMetrics
import com.openconference.OpenConfApp
fun Fragment.applicationComponent() = OpenConfApp.getApplicationComponent(activity)
fun Fragment.layoutInflater() = activity.layoutInflater
fun Fragment.getInt(@IntegerRes intRes: Int) = resources.getInteger(intRes)
fun Fragment.dpToPx(dp: Int): Float {
val metrics = resources.displayMetrics;
val px: Float = dp * (metrics.densityDpi.toFloat() / DisplayMetrics.DENSITY_DEFAULT);
return px;
} | apache-2.0 | ea9674355af61c516b5d6354aeb8bda2 | 31.684211 | 87 | 0.81129 | 4.189189 | false | false | false | false |
takuji31/Koreference | koreference/src/main/java/jp/takuji31/koreference/KoreferenceFunctions.kt | 1 | 4098 | package jp.takuji31.koreference
import jp.takuji31.koreference.converter.RawValueConverter
import jp.takuji31.koreference.type.*
import java.util.*
/**
* Created by takuji on 2015/08/09.
*/
fun stringPreference(default: String = "", key: String? = null): KoreferencePropertyProvider<String, String> {
return object : KoreferencePropertyProvider<String, String>(key, default){
override fun createDelegate(key: String, defaultValue: String): KoreferenceProperty<String, String> {
return object : KoreferenceProperty<String, String>(default = default, preferenceKey = key), StringPreference, RawValueConverter<String> {}
}
}
}
fun nullableStringPreference(default: String? = null, key: String? = null): KoreferencePropertyProvider<String?, String?> {
return object : KoreferencePropertyProvider<String?, String?>(key, default){
override fun createDelegate(key: String, defaultValue: String?): KoreferenceProperty<String?, String?> {
return object : KoreferenceProperty<String?, String?>(default = default, preferenceKey = key), NullableStringPreference, RawValueConverter<String?> {}
}
}
}
fun intPreference(default: Int = -1, key: String? = null): KoreferencePropertyProvider<Int, Int> {
return object : KoreferencePropertyProvider<Int, Int>(key, default){
override fun createDelegate(key: String, defaultValue: Int): KoreferenceProperty<Int, Int> {
return object : KoreferenceProperty<Int, Int>(default = default, preferenceKey = key), IntPreference, RawValueConverter<Int> {}
}
}
}
fun longPreference(default: Long = -1L, key: String? = null): KoreferencePropertyProvider<Long, Long> {
return object : KoreferencePropertyProvider<Long, Long>(key, default){
override fun createDelegate(key: String, defaultValue: Long): KoreferenceProperty<Long, Long> {
return object : KoreferenceProperty<Long, Long>(default = default, preferenceKey = key), LongPreference, RawValueConverter<Long> {}
}
}
}
fun floatPreference(default: Float = -1.0f, key: String? = null): KoreferencePropertyProvider<Float, Float> {
return object : KoreferencePropertyProvider<Float, Float>(key, default){
override fun createDelegate(key: String, defaultValue: Float): KoreferenceProperty<Float, Float> {
return object : KoreferenceProperty<Float, Float>(default = default, preferenceKey = key), FloatPreference, RawValueConverter<Float> {}
}
}
}
fun booleanPreference(default: Boolean = false, key: String? = null): KoreferencePropertyProvider<Boolean, Boolean> {
return object : KoreferencePropertyProvider<Boolean, Boolean>(key, default){
override fun createDelegate(key: String, defaultValue: Boolean): KoreferenceProperty<Boolean, Boolean> {
return object : KoreferenceProperty<Boolean, Boolean>(default = default, preferenceKey = key), BooleanPreference, RawValueConverter<Boolean> {}
}
}
}
fun stringSetPreference(default: Set<String> = HashSet<String>(), key: String? = null): KoreferencePropertyProvider<Set<String>, Set<String>> {
return object : KoreferencePropertyProvider<Set<String>, Set<String>>(key, default){
override fun createDelegate(key: String, defaultValue: Set<String>): KoreferenceProperty<Set<String>, Set<String>> {
return object : KoreferenceProperty<Set<String>, Set<String>>(default = default, preferenceKey = key), StringSetPreference, RawValueConverter<Set<String>> {}
}
}
}
fun nullableStringSetPreference(default: Set<String>? = null, key: String? = null): KoreferencePropertyProvider<Set<String>?, Set<String>?> {
return object : KoreferencePropertyProvider<Set<String>?, Set<String>?>(key, default){
override fun createDelegate(key: String, defaultValue: Set<String>?): KoreferenceProperty<Set<String>?, Set<String>?> {
return object : KoreferenceProperty<Set<String>?, Set<String>?>(default = default, preferenceKey = key), NullableStringSetPreference, RawValueConverter<Set<String>?> {}
}
}
}
| apache-2.0 | 6102aa5d06c65201ceccef5b8a6d32c1 | 55.916667 | 180 | 0.719375 | 4.181633 | false | false | false | false |
ethauvin/kobalt | modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/internal/build/BuildSources.kt | 2 | 2024 | package com.beust.kobalt.internal.build
import com.beust.kobalt.homeDir
import java.io.File
import java.nio.file.*
import java.nio.file.attribute.BasicFileAttributes
/**
* The abstraction to represent a directory that contains source files. @param{root} is typically
* the root of the project and build files are searched under root/kobalt/src/ *kt.
*/
interface IBuildSources {
fun findSourceFiles() : List<File>
val root: File
fun exists(): Boolean
}
class SingleFileBuildSources(val file: File) : IBuildSources {
override fun exists() = file.exists()
override fun findSourceFiles() = listOf(file)
override val root: File = file.parentFile.parentFile.parentFile
override fun toString() : String = file.path
}
class BuildSources(val file: File = File("")) : IBuildSources {
override val root = file
override fun findSourceFiles() : List<File> {
return findBuildFiles(listOf(file))
}
override fun exists() = findSourceFiles().isNotEmpty()
override fun toString() = "{BuildSources " + findSourceFiles().joinToString(", ") + "}"
fun findBuildFiles(roots: List<File>) : List<File> {
val result = arrayListOf<File>()
roots.forEach { file ->
Files.walkFileTree(Paths.get(file.path), object : SimpleFileVisitor<Path>() {
override fun preVisitDirectory(dir: Path?, attrs: BasicFileAttributes?): FileVisitResult {
if (dir != null) {
val path = dir.toFile()
if (path.name == "src" && path.parentFile.name == "kobalt") {
val sources = path.listFiles().filter { it.name.endsWith(".kt") }
result.addAll(sources)
}
}
return FileVisitResult.CONTINUE
}
})
}
return result
}
}
fun main(args: Array<String>) {
val sources = BuildSources(File(homeDir("kotlin/kobalt"))).findSourceFiles()
println("sources: " + sources)
} | apache-2.0 | 2b001c054f4d4e45c66077c98ac12035 | 32.196721 | 102 | 0.625 | 4.448352 | false | false | false | false |
LApptelier/SmartRecyclerView | smartrecyclerview/src/main/java/com/lapptelier/smartrecyclerview/SmartRecyclerView.kt | 1 | 15162 | package com.lapptelier.smartrecyclerview
/**
* com.msd.msdetmoi.common.util.new_smart_recycler_view.SmartBindingRecyclerView
* <p/>
* Generic implementation of a {@see RecyclerView} intagrated in {@SwipeRefreshLayout} layout.
* Feature placeholder for empty list and loading progress bar both during reloading and loading more items.
* <p/>
*
* @author L'Apptelier SARL
* @date 02/09/2020
*/
import android.animation.LayoutTransition
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewStub
import android.widget.LinearLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
open class SmartRecyclerView : LinearLayout {
// count of item to display before firing the loadmore action
private var itemLeftMoreToLoad = 10
// actual recycler view
var recyclerView: RecyclerView? = null
// swipe layout
var swipeLayout: SwipeRefreshLayout? = null
// placeholder on the loading of the list
var mLoadingViewStub: ViewStub? = null
var mEmptyViewStub: ViewStub? = null
/**
* Return the inflated view layout placed when the list is loading elements
*
* @return the 'loading' view
*/
var loadingView: View? = null
/**
* Return the inflated view layout placed when the list is empty
*
* @return the 'empty' view
*/
var emptyView: View? = null
// main layout of the view
private var mOuterLayout: LinearLayout? = null
// flag used when either the loadmore, swipe layout loading or full loading screen is displayed
private var isLoading: Boolean = false
// recycler view listener
private lateinit var mInternalOnScrollListener: RecyclerView.OnScrollListener
// List of all external scroll listerners
private var mExternalOnScrollListeners: MutableList<RecyclerView.OnScrollListener> = ArrayList()
// On More Listener
private var mOnMoreListener: OnMoreListener? = null
// Flag for disabling the loading view while the list is empty
private var emptyLoadingViewEnabled = true
// Generic adapter
private var mAdapter: GenericAdapter? = null
var loadingLayout: Int = 0
set(layout) {
field = layout
mLoadingViewStub!!.layoutResource = layout
loadingView = mLoadingViewStub!!.inflate()
emptyLoadingViewEnabled = true
}
var emptyLayout: Int = 0
set(layout) {
field = layout
mEmptyViewStub!!.layoutResource = layout
emptyView = mEmptyViewStub!!.inflate()
}
/**
* Enable or disable the animation on new list entry
*
* @param animate true to enable layout animation, false to disable
*/
fun setAnimateLayoutChange(animate: Boolean) {
mOuterLayout?.layoutTransition = if (animate) LayoutTransition() else null
}
/**
* Simple Constructor
*
* @param context the current context
*/
constructor(context: Context) : super(context)
/**
* Constructor with attributeSet
*
* @param context the current context
* @param attrs attribute set to customize the RecyclerView
*/
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
setup()
}
/**
* Constructor with attributeSet and style
*
* @param context the current context
* @param attrs attribute set to customize the RecyclerView
* @param defStyle style of the RecyclerView
*/
constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super(
context,
attrs,
defStyle
) {
setup()
}
/**
* Initialize the view
*/
private fun setup() {
//bypass for Layout display in UIBuilder
if (isInEditMode) {
return
}
mExternalOnScrollListeners = ArrayList()
val inflater = LayoutInflater.from(context)
val view = inflater.inflate(R.layout.layout_smart_recycler_view, this)
recyclerView = view.findViewById(R.id.smart_list_recycler)
mEmptyViewStub = view.findViewById(R.id.smart_list_empty_stub)
mLoadingViewStub = view.findViewById(R.id.smart_list_loading_stub)
swipeLayout = view.findViewById(R.id.smart_list_swipe_layout)
if (recyclerView != null) {
mInternalOnScrollListener = object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
if (recyclerView.layoutManager is LinearLayoutManager) {
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
if (layoutManager.findLastVisibleItemPosition() >= layoutManager.itemCount - itemLeftMoreToLoad
&& !isLoading && mAdapter != null && mAdapter!!.hasMore
) {
isLoading = true
if (mOnMoreListener != null) {
mOnMoreListener!!.onMoreAsked(
[email protected]!!.adapter!!.itemCount,
itemLeftMoreToLoad,
layoutManager.findLastVisibleItemPosition()
)
}
}
}
for (listener in mExternalOnScrollListeners)
listener.onScrolled(recyclerView, dx, dy)
}
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
for (listener in mExternalOnScrollListeners)
listener.onScrollStateChanged(recyclerView, newState)
}
}
recyclerView!!.addOnScrollListener(mInternalOnScrollListener)
}
//by default, empty screen is hidden and loading screen is displayed
if (emptyView != null)
emptyView!!.visibility = View.GONE
if (loadingView != null)
loadingView!!.visibility = if (emptyLoadingViewEnabled) View.VISIBLE else View.GONE
}
/**
* Set inner RecyclerView' LayoutManager
*
* @param layoutManager inner RecyclerView' LayoutManager
*/
fun setLayoutManager(layoutManager: RecyclerView.LayoutManager) {
if (recyclerView != null)
recyclerView!!.layoutManager = layoutManager
}
/**
* Set inner RecyclerView' adapter
*
* @param adapter inner RecyclerView' adapter
*/
fun setAdapter(adapter: GenericAdapter) {
setAdapter(adapter, true)
}
/**
* Set inner RecyclerView' adapter
*
* @param adapter inner RecyclerView' adapter
* @param dismissLoadingViewAutomatically true to handle loading view automatically at every adapter changes
*/
fun setAdapter(adapter: GenericAdapter, dismissLoadingViewAutomatically: Boolean) {
mAdapter = adapter
if (recyclerView != null) {
recyclerView!!.adapter = mAdapter
if (dismissLoadingViewAutomatically) {
this.dismissLoadingView()
mAdapter?.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onItemRangeChanged(positionStart: Int, itemCount: Int) {
super.onItemRangeChanged(positionStart, itemCount)
dismissLoadingView()
}
override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
super.onItemRangeInserted(positionStart, itemCount)
dismissLoadingView()
}
override fun onChanged() {
super.onChanged()
dismissLoadingView()
}
override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
super.onItemRangeRemoved(positionStart, itemCount)
dismissLoadingView()
}
override fun onItemRangeMoved(
fromPosition: Int,
toPosition: Int,
itemCount: Int
) {
super.onItemRangeMoved(fromPosition, toPosition, itemCount)
dismissLoadingView()
}
override fun onItemRangeChanged(
positionStart: Int,
itemCount: Int,
payload: Any?
) {
super.onItemRangeChanged(positionStart, itemCount, payload)
dismissLoadingView()
}
})
}
}
}
/**
* Update the view to display loading if needed
*/
fun dismissLoadingView() {
//flag indicating that the data loading is complete
isLoading = false
// hiding the loading view first
loadingView?.visibility = View.GONE
//hidding swipe to refresh too
swipeLayout?.isRefreshing = false
if (mAdapter == null || mAdapter!!.isEmpty) {
emptyView?.visibility = View.VISIBLE
} else {
emptyView?.visibility = View.GONE
}
}
/**
* Set the RecyclerView' SwipeRefreshListener
*
* @param listener the RecyclerView' SwipeRefreshListener
*/
fun setRefreshListener(listener: SwipeRefreshLayout.OnRefreshListener) {
if (swipeLayout != null) {
swipeLayout!!.isEnabled = true
swipeLayout!!.setOnRefreshListener(listener)
}
}
/**
* set the OnMore Listener
*
* @param onMoreListener the LoadMore Listener
* @param max count of items left before firing the LoadMore
*/
fun setOnMoreListener(onMoreListener: OnMoreListener, max: Int) {
mOnMoreListener = onMoreListener
itemLeftMoreToLoad = max
}
/**
* Set the recyclerView' OnTouchListener
*
* @param listener OnTouchListener
*/
@SuppressLint("ClickableViewAccessibility")
override fun setOnTouchListener(listener: View.OnTouchListener) {
recyclerView?.setOnTouchListener(listener)
}
/**
* Display the pull-to-refresh of the SwipeLayout
*
* @param display true to display the pull-to-refresh, false otherwise
*/
fun enableSwipeToRefresh(display: Boolean) {
swipeLayout?.let {
it.isEnabled = display
}
}
/**
* Tell the recyclerView if the empty view should be displayed when there is no items.
*
* @param enableEmpty true to display the empty view, false otherwise
*/
fun enableEmptyLoadingView(enableEmpty: Boolean) {
emptyLoadingViewEnabled = enableEmpty
loadingView?.visibility = View.GONE
}
/**
* Display the loading placeholder ontop of the list
*/
fun displayLoadingView() {
//updating internal loading flag
isLoading = true
if (mAdapter != null && mAdapter!!.itemCount > 0) {
if (swipeLayout != null && !swipeLayout!!.isRefreshing) {
// on affiche le PTR
val typedValue = TypedValue()
context.theme.resolveAttribute(
androidx.appcompat.R.attr.actionBarSize,
typedValue,
true
)
swipeLayout?.setProgressViewOffset(
false,
0,
resources.getDimensionPixelSize(typedValue.resourceId)
)
swipeLayout?.isRefreshing = true
}
} else {
this.emptyView?.visibility = View.GONE
this.loadingView?.visibility = View.VISIBLE
}
}
/**
* Add a custom cell divider to the recycler view
*
* @param dividerItemDecoration custom cell divider
*/
fun addItemDecoration(dividerItemDecoration: RecyclerView.ItemDecoration) {
if (recyclerView != null)
recyclerView!!.addItemDecoration(dividerItemDecoration)
}
/**
* Change view background color
*
* @param color view background color
*/
override fun setBackgroundColor(color: Int) {
if (recyclerView != null)
recyclerView!!.setBackgroundColor(color)
}
/**
* Scroll the recycler view to its top
*/
fun scrollToTop() {
if (!recyclerView!!.isAnimating && !recyclerView!!.isComputingLayout)
recyclerView!!.scrollToPosition(0)
}
/**
* Smooth scroll the recycler view to its top
*/
fun smoothScrollToTop() {
if (!recyclerView!!.isAnimating && !recyclerView!!.isComputingLayout)
recyclerView!!.smoothScrollToPosition(0)
}
/**
* @return the scroll listeners of the recyclerView
*/
fun getExternalOnScrollListeners(): List<RecyclerView.OnScrollListener> {
return mExternalOnScrollListeners
}
/**
* Add a scroll listener to the recyclerView
*
* @param externalOnScrollListener
*/
fun addExternalOnScrollListener(externalOnScrollListener: RecyclerView.OnScrollListener) {
this.mExternalOnScrollListeners.add(externalOnScrollListener)
}
/**
* Clear all scroll listeners of the recycler view
*/
fun clearExternalOnScrollListeners() {
mExternalOnScrollListeners.clear()
}
/**
* Scroll to the bottom of the list
*/
fun scrollToBottom() {
if (recyclerView != null && mAdapter != null && mAdapter!!.itemCount > 0)
recyclerView!!.scrollToPosition(mAdapter!!.itemCount - 1)
}
/**
* Scroll smoothly to the bottom of the list
*/
fun smoothScrollToBottom() {
if (recyclerView != null && mAdapter != null && mAdapter!!.itemCount > 0)
recyclerView!!.smoothScrollToPosition(mAdapter!!.itemCount - 1)
}
/**
* Scroll without animation to an item position in the RecyclerView
*
* @param position position to scroll to
*/
fun scrollTo(position: Int) {
if (recyclerView != null)
this.recyclerView!!.scrollToPosition(position)
}
/**
* Scroll smoothly to an item position in the RecyclerView
*
* @param position position to scroll to
*/
fun smoothScrollTo(position: Int) {
if (recyclerView != null)
this.recyclerView!!.smoothScrollToPosition(position)
}
}
| apache-2.0 | 02bb227370d4b06a448e5aa2b73c12fd | 30.653445 | 119 | 0.60058 | 5.59277 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/components/CinnamonSelectMenuExecutor.kt | 1 | 7002 | package net.perfectdreams.loritta.cinnamon.discord.interactions.components
import dev.kord.common.entity.Snowflake
import dev.kord.core.entity.User
import kotlinx.datetime.Clock
import mu.KotlinLogging
import net.perfectdreams.discordinteraktions.common.components.ComponentContext
import net.perfectdreams.discordinteraktions.common.components.SelectMenuExecutor
import net.perfectdreams.i18nhelper.core.I18nContext
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.i18n.I18nKeysData
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CommandException
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CommandExecutorWrapper
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.EphemeralCommandException
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.SilentCommandException
import net.perfectdreams.loritta.cinnamon.discord.utils.metrics.InteractionsMetrics
import net.perfectdreams.loritta.common.components.ComponentType
abstract class CinnamonSelectMenuExecutor(val loritta: LorittaBot) : SelectMenuExecutor {
companion object {
private val logger = KotlinLogging.logger {}
}
private val executorClazzName = this::class.simpleName ?: "UnknownExecutor"
abstract suspend fun onSelect(user: User, context: net.perfectdreams.loritta.cinnamon.discord.interactions.components.ComponentContext, values: List<String>)
override suspend fun onSelect(user: User, context: ComponentContext, values: List<String>) {
val rootDeclarationClazzName = context.componentExecutorDeclaration::class.simpleName ?: "UnknownDeclaration"
logger.info { "(${context.sender.id.value}) $this" }
val timer = InteractionsMetrics.EXECUTED_SELECT_MENU_LATENCY_COUNT
.labels(rootDeclarationClazzName, executorClazzName)
.startTimer()
// These variables are used in the catch { ... } block, to make our lives easier
var i18nContext: I18nContext? = null
var cinnamonContext: net.perfectdreams.loritta.cinnamon.discord.interactions.components.ComponentContext? = null
val guildId = (context as? net.perfectdreams.discordinteraktions.common.components.GuildComponentContext)?.guildId
var stacktrace: String? = null
try {
val serverConfig = if (guildId != null) {
// TODO: Fix this workaround, while this does work, it isn't that good
loritta.pudding.serverConfigs.getServerConfigRoot(guildId.value)?.data ?: CommandExecutorWrapper.NonGuildServerConfigRoot
} else {
// TODO: Should this class *really* be named "ServerConfig"? After all, it isn't always used for guilds
CommandExecutorWrapper.NonGuildServerConfigRoot
}
val locale = loritta.localeManager.getLocaleById(serverConfig.localeId)
i18nContext = loritta.languageManager.getI18nContextByLegacyLocaleId(serverConfig.localeId)
// val channel = loritta.interactions.rest.channel.getChannel(context.request.channelId)
cinnamonContext = if (guildId != null) {
// TODO: Add Guild ID here
GuildComponentContext(
loritta,
i18nContext,
locale,
context.sender,
context,
context.guildId,
context.member
)
} else {
ComponentContext(
loritta,
i18nContext,
locale,
context.sender,
context
)
}
// Don't let users that are banned from using Loritta
if (CommandExecutorWrapper.handleIfBanned(loritta, cinnamonContext))
return
onSelect(
user,
cinnamonContext,
values
)
} catch (e: Throwable) {
if (e is SilentCommandException)
return // SilentCommandExceptions should be ignored
if (e is CommandException) {
context.sendPublicMessage(e.builder)
return
}
if (e is EphemeralCommandException) {
context.sendEphemeralMessage(e.builder)
return
}
logger.warn(e) { "Something went wrong while executing this executor!" } // TODO: Better logs
// If the i18nContext is not present, we will default to the default language provided
i18nContext = i18nContext ?: loritta.languageManager.getI18nContextByLegacyLocaleId(loritta.languageManager.defaultLanguageId)
// Tell the user that something went *really* wrong
// While we do have access to the Cinnamon Context, it may be null at this stage, so we will use the Discord InteraKTions context
val content = "${Emotes.LoriHm} **|** " + i18nContext.get(
I18nKeysData.Commands.ErrorWhileExecutingCommand(
loriRage = Emotes.LoriRage,
loriSob = Emotes.LoriSob,
// To avoid leaking important things (example: Interaction Webhook URL when a request to Discord timeouts), let's not send errors to everyone
stacktrace = if (context.sender.id == Snowflake(123170274651668480)) {// TODO: Stop hardcoding this
if (!e.message.isNullOrEmpty())
" `${e.message}`" // TODO: Sanitize
else
" `${e::class.simpleName}`"
} else ""
)
)
// If the context was already deferred, but it isn't ephemeral, then we will send a non-ephemeral message
val isEphemeral = if (context.isDeferred)
context.wasInitiallyDeferredEphemerally
else true
if (isEphemeral)
context.sendEphemeralMessage {
this.content = content
}
else
context.sendMessage {
this.content = content
}
stacktrace = e.stackTraceToString()
}
val commandLatency = timer.observeDuration()
logger.info { "(${context.sender.id.value}) $this - OK! Took ${commandLatency * 1000}ms" }
loritta.pudding.executedInteractionsLog.insertComponentLog(
context.sender.id.value.toLong(),
guildId?.value?.toLong(),
context.channelId.value.toLong(),
Clock.System.now(),
ComponentType.BUTTON,
rootDeclarationClazzName,
executorClazzName,
stacktrace == null,
commandLatency,
stacktrace
)
}
} | agpl-3.0 | b08e870aea79534929e7aeccab5f24b5 | 44.180645 | 161 | 0.630534 | 5.365517 | false | true | false | false |
ethankhall/gradle-plugins | base-plugins/src/main/kotlin/io/ehdev/gradle/DevelopmentPlugin.kt | 1 | 2055 | package io.ehdev.gradle
import io.ehdev.gradle.internal.AddTestSourceSets
import io.ehdev.gradle.internal.LocalTestListener
import org.gradle.api.JavaVersion
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.plugins.JavaPluginConvention
import org.gradle.api.tasks.testing.Test
import org.gradle.api.tasks.testing.TestDescriptor
import org.gradle.api.tasks.testing.TestResult
import org.gradle.testing.jacoco.plugins.JacocoTaskExtension
import org.gradle.testing.jacoco.tasks.JacocoReport
import java.io.File
open class DevelopmentPlugin : Plugin<Project> {
override fun apply(project: Project) {
project.plugins.apply("java")
project.plugins.apply("idea")
project.plugins.apply("jacoco")
val javaPluginConvention = project.convention.plugins["java"] as JavaPluginConvention
javaPluginConvention.sourceCompatibility = JavaVersion.VERSION_1_8
AddTestSourceSets.addSourceSet(project, "integTest")
project.tasks.withType(Test::class.java) { task ->
task.addTestListener(object : LocalTestListener() {
override fun afterSuite(suite: TestDescriptor, result: TestResult) {
if (suite.parent == null) {
project.logger.lifecycle("Results: {} ({} tests, {} successes, {} failures, {} skipped)",
result.resultType, result.testCount, result.successfulTestCount,
result.failedTestCount, result.skippedTestCount)
}
}
})
val jacoco = task.extensions.getByType(JacocoTaskExtension::class.java)
jacoco.apply {
isAppend = true
destinationFile = File(project.buildDir, "/jacoco/${task.name}-jacocoTest.exec")
classDumpDir = File(project.buildDir, "/jacoco/${task.name}-classpathdumps")
}
}
project.tasks.getByName("check").dependsOn(project.tasks.withType(JacocoReport::class.java))
}
}
| bsd-3-clause | 0dfefcf513cc38c246866b13b1685534 | 40.938776 | 113 | 0.666667 | 4.556541 | false | true | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/armorsetbuilder/armorselect/ArmorSelectAllFragment.kt | 1 | 2909 | package com.ghstudios.android.features.armorsetbuilder.armorselect
import android.app.Activity
import androidx.lifecycle.Observer
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.text.Editable
import android.text.TextWatcher
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.features.armor.detail.ArmorSetDetailPagerActivity
import com.ghstudios.android.mhgendatabase.databinding.FragmentGenericExpandableListBinding
/**
* Creates a fragment used to display the list of all armor
* available to insert to an ArmorSetBuilder
*/
class ArmorSelectAllFragment : Fragment() {
private lateinit var binding: FragmentGenericExpandableListBinding
/**
* ViewModel (anchored to parent)
*/
private val viewModel by lazy {
ViewModelProvider(activity!!).get(ArmorSelectViewModel::class.java)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = FragmentGenericExpandableListBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapterItems = mutableListOf<ArmorGroup>()
val adapter = ArmorExpandableListAdapter(adapterItems)
binding.expandableListView.setAdapter(adapter)
enableFilter {
viewModel.setFilter(it)
}
viewModel.filteredArmor.observe(viewLifecycleOwner, Observer {
if (it == null) return@Observer
adapterItems.clear()
adapterItems.addAll(it)
adapter.notifyDataSetChanged()
adapter.onArmorSelected = {
val intent = activity!!.intent
intent.putExtra(ArmorSetDetailPagerActivity.EXTRA_ARMOR_ID, it.id)
activity?.setResult(Activity.RESULT_OK, intent)
activity?.finish()
}
})
}
private var previousListener: TextWatcher? = null
fun enableFilter(onUpdate: (String) -> Unit) {
val textField = binding.inputSearch
textField.visibility = View.VISIBLE
if (previousListener != null) {
textField.removeTextChangedListener(previousListener)
}
previousListener = object : TextWatcher {
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
val value = (s?.toString() ?: "").trim()
onUpdate(value)
}
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
}
textField.addTextChangedListener(previousListener)
}
}
| mit | 310ca103b6511daeb0b5d69941306583 | 33.223529 | 116 | 0.686146 | 5.130511 | false | false | false | false |
christophpickl/kpotpourri | common4k/src/main/kotlin/com/github/christophpickl/kpotpourri/common/os/Notifier.kt | 1 | 1014 | package com.github.christophpickl.kpotpourri.common.os
import com.github.christophpickl.kpotpourri.common.process.ExecuteContext
import com.github.christophpickl.kpotpourri.common.process.ProcessExecuterImpl
import mu.KotlinLogging.logger
class Notifier {
private val log = logger {}
private val os = OsSniffer.os
private var warningPrinted = false
fun display(notification: Notification) {
if (os == Os.Mac) {
ProcessExecuterImpl.execute(
command = "osascript",
args = listOf("-e", "display notification \"${notification.message}\" with title \"${notification.title}\""),
context = ExecuteContext(
suppressOutput = true
)
)
} else if (!warningPrinted) {
warningPrinted = true
log.warn { "Your operating system is not supported for notifications :(" }
}
}
}
data class Notification(
val title: String,
val message: String
)
| apache-2.0 | 3da9a564e7eb167112d2061af1690311 | 29.727273 | 125 | 0.631164 | 4.738318 | false | false | false | false |
edsilfer/presence-control | app/src/main/java/br/com/edsilfer/android/presence_control/core/services/PropertiesAPI.kt | 1 | 1875 | package br.com.edsilfer.android.presence_control.core.services
import br.com.edsilfer.android.presence_control.core.App
import java.util.*
/**
* Created by ferna on 6/5/2017.
*/
object PropertiesAPI {
private val ARG_PROPERTY_FILE = "settings.properties"
private var properties: Properties = Properties()
init {
Thread().run {
properties.load(App.getContext().assets.open(ARG_PROPERTY_FILE))
}
}
/**
* PROPERTIES
*/
val PROPERTY_MINIMUM_RADIUS = "MINIMUM_RADIUS"
val PROPERTY_MAXIMUM_RADIUS = "MAXIMUM_RADIUS"
val PROPERTY_DEFAULT_LOITERING_TIME_IN_MILLISECONDS = "DEFAULT_LOITERING_DELAY_IN_MILLISECONDS"
val PROPERTY_MINIMUM_TIME_BETWEEN_ACTIVITIES_IN_MILLISENCONDS = "MINIMUM_TIME_BETWEEN_ACTIVITIES_IN_MILLISECONDS"
fun readStringProperty(property: String, defaultValue: String): String {
return properties.getProperty(property, defaultValue)
}
fun readIntProperty(property: String, defaultValue: Int): Int {
try {
return properties.getProperty(property).toInt()
} catch (e: Exception) {
return defaultValue
}
}
fun readLongProperty(property: String, defaultValue: Long): Long {
try {
return properties.getProperty(property).toLong()
} catch (e: Exception) {
return defaultValue
}
}
fun readDoubleProperty(property: String, defaultValue: Double): Double {
try {
return properties.getProperty(property).toDouble()
} catch (e: Exception) {
return defaultValue
}
}
fun readBooleanProperty(property: String, defaultValue: Boolean): Boolean {
try {
return properties.getProperty(property).toBoolean()
} catch (e: Exception) {
return defaultValue
}
}
} | apache-2.0 | db5b3bbf0b3d5c4cea0ed9718a3167ff | 29.258065 | 117 | 0.643733 | 4.507212 | false | false | false | false |
charbgr/CliffHanger | cliffhanger/feature-movie-detail/src/main/kotlin/com/github/charbgr/cliffhanger/features/detail/arch/UiBinder.kt | 1 | 2466 | package com.github.charbgr.cliffhanger.features.detail.arch
import com.github.charbgr.cliffhanger.api_tmdb.TmdbHelper
import com.github.charbgr.cliffhanger.domain.FullMovie
import com.github.charbgr.cliffhanger.features.detail.MovieDetailActivity
import com.github.charbgr.cliffhanger.features.detail.R
import com.github.charbgr.cliffhanger.shared.extensions.visibleOrGone
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
internal open class UiBinder(
private val movieDetailActivity: MovieDetailActivity
) : View {
private val movieLoadIntent: PublishSubject<Int> = PublishSubject.create()
fun onCreateView() {
loadMovie()
}
fun render(render: Pair<PartialChange, ViewModel>) {
val viewModel = render.second
movieDetailActivity.progressBar.visibleOrGone(viewModel.showLoader)
if (viewModel.showError) {
// NavigateToError(movieDetailActivity)
// .closeCurrentActivity()
// .execute()
}
if (viewModel.showMovie) {
bindMovie(viewModel.movie!!)
}
}
private fun bindMovie(movie: FullMovie) {
movieDetailActivity.title.text = movie.title
bindImages(movie)
bindDirector(movie)
bindSecondaryInfo(movie)
bindTagline(movie)
movieDetailActivity.overview.text = movie.overview
}
private fun bindImages(movie: FullMovie) {
movieDetailActivity.poster.bindPoster(TmdbHelper.bestPoster(movie.posterPath))
movieDetailActivity.backdrop.bindBackdrop(TmdbHelper.bestBackdrop(movie.backdropPath))
}
private fun bindDirector(movie: FullMovie) {
val director = movie.director
movieDetailActivity.directedBy.visibleOrGone(director != null)
movieDetailActivity.director.visibleOrGone(director != null)
movieDetailActivity.director.text = director?.name
}
private fun bindSecondaryInfo(movie: FullMovie) {
movieDetailActivity.duration.text = movieDetailActivity.getString(R.string.movie_duration_mins,
movie.duration)
movieDetailActivity.chronology.text = movie.chronology
}
private fun bindTagline(movie: FullMovie) {
movieDetailActivity.tagline.visibleOrGone(!movie.tagline.isNullOrBlank())
movieDetailActivity.tagline.text = movie.tagline
}
private fun loadMovie() {
val movieId = movieDetailActivity.intent.getIntExtra(MovieDetailActivity.MOVIE_ID_EXTRA, -1)
movieLoadIntent.onNext(movieId)
}
override fun fetchMovieIntent(): Observable<Int> = movieLoadIntent.hide()
}
| mit | 22b7827ab2f0c98c9503bed0d5dd6ba7 | 31.447368 | 99 | 0.767234 | 4.259067 | false | false | false | false |
7hens/KDroid | sample/src/main/java/cn/thens/kdroid/sample/common/app/FragmentSelector.kt | 1 | 2324 | package cn.thens.kdroid.sample.common.app
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
@Suppress("MemberVisibilityCanBePrivate", "unused")
abstract class FragmentSelector(
private val fragmentManager: FragmentManager,
private val containerId: Int) {
private var selectedIndex: Int = 0
abstract fun getFragmentClass(index: Int): Class<out Fragment>
open fun shouldCache(index: Int): Boolean = true
fun select(index: Int) {
fragmentManager.beginTransaction()
.show(index)
.hide(currentIndex())
.commitNowAllowingStateLoss()
selectedIndex = index
}
fun getFragment(index: Int): Fragment? {
val fragmentTag = getFragmentTag(index)
return fragmentManager.findFragmentByTag(fragmentTag)
}
fun currentIndex(): Int {
return selectedIndex
}
private fun getFragmentTag(index: Int): String {
val fragClassName = getFragmentClass(index).canonicalName
return "FragmentSelector.$fragClassName.$index"
}
private fun FragmentTransaction.show(index: Int): FragmentTransaction {
val fragmentTag = getFragmentTag(index)
var fragment = fragmentManager.findFragmentByTag(fragmentTag)
if (fragment == null) {
fragment = getFragmentClass(index).newInstance()
add(containerId, fragment, fragmentTag)
} else {
show(fragment)
}
fragment!!.userVisibleHint = true
return this
}
private fun FragmentTransaction.hide(index: Int): FragmentTransaction {
val fragment = getFragment(index)
if (fragment != null) {
if (shouldCache(index)) hide(fragment) else remove(fragment)
fragment.userVisibleHint = false
}
return this
}
companion object {
fun create(fragmentManager: FragmentManager, containerId: Int, fragClasses: List<Class<out Fragment>>): FragmentSelector {
return object : FragmentSelector(fragmentManager, containerId) {
override fun getFragmentClass(index: Int): Class<out Fragment> {
return fragClasses[index]
}
}
}
}
} | apache-2.0 | 1d2c0e7288155e886168a4a028dee125 | 31.746479 | 130 | 0.650602 | 5.318078 | false | false | false | false |
toastkidjp/Jitte | article/src/main/java/jp/toastkid/article_viewer/article/detail/LinkBehaviorService.kt | 2 | 1706 | /*
* Copyright (c) 2019 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.article_viewer.article.detail
import androidx.core.net.toUri
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.ContentViewModel
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
/**
* @author toastkidjp
*/
class LinkBehaviorService(
private val contentViewModel: ContentViewModel,
private val browserViewModel: BrowserViewModel,
private val exists: (String) -> Boolean,
private val internalLinkScheme: InternalLinkScheme = InternalLinkScheme(),
private val mainDispatcher: CoroutineDispatcher = Dispatchers.Main,
private val ioDispatcher: CoroutineDispatcher = Dispatchers.IO
) {
operator fun invoke(url: String?) {
if (url.isNullOrBlank()) {
return
}
if (!internalLinkScheme.isInternalLink(url)) {
browserViewModel.open(url.toUri())
return
}
val title = internalLinkScheme.extract(url)
CoroutineScope(mainDispatcher).launch {
val exists = withContext(ioDispatcher) { exists(title) }
if (exists) {
contentViewModel.newArticle(title)
} else {
contentViewModel.snackShort("\"$title\" does not exist.")
}
}
}
} | epl-1.0 | 6bddc43ec7d9c21f127b7f966b98d663 | 32.470588 | 88 | 0.702227 | 4.888252 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsBaseType.kt | 2 | 627 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import org.rust.lang.core.psi.RsBaseType
val RsBaseType.isCself: Boolean get() {
val path = path
return path != null && !path.hasColonColon && path.hasCself
}
val RsBaseType.isUnit: Boolean get() = (stub?.isUnit) ?: (lparen != null && rparen != null)
val RsBaseType.isNever: Boolean get() = (stub?.isNever) ?: (excl != null)
val RsBaseType.isUnderscore: Boolean get() = (stub?.isUnderscore) ?: (underscore != null)
val RsBaseType.name: String? get() = path?.referenceName
| mit | 99d005bc090827d96d012651ad27da20 | 32 | 91 | 0.695375 | 3.335106 | false | false | false | false |
emufog/emufog | src/main/kotlin/emufog/reader/brite/BriteFormatReader.kt | 1 | 6111 | /*
* MIT License
*
* Copyright (c) 2018 emufog contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package emufog.reader.brite
import emufog.graph.Graph
import emufog.reader.GraphReader
import java.nio.file.Path
/**
* The reader reads in a graph object from the BRITE file format specified in the documentation
* (https://www.cs.bu.edu/brite/user_manual/node29.html).
*/
object BriteFormatReader : GraphReader {
/**
* Reads in a new graph object from a brite format file. This call only supports one file.
*
* @param files the list of input files must only contain one file path
* @param baseAddress base address of the IPv4 space to start with
* @throws BriteFormatException if format does not match the BRITE standard
* @throws IllegalArgumentException if the list is empty or not exactly of size one
*/
override fun readGraph(files: List<Path>, baseAddress: String): Graph {
require(files.isNotEmpty()) { "No files given to read in." }
require(files.size == 1) { "The BRITE reader only supports one input file." }
return BriteFormatReaderImpl(files[0], baseAddress).readGraph()
}
}
internal class BriteFormatReaderImpl internal constructor(path: Path, baseAddress: String) {
private companion object {
/**
* number of columns defined for a line containing a node
*/
const val NODE_COLUMNS = 7
/**
* number of columns defined for a line containing an edge
*/
const val EDGE_COLUMNS = 9
val regex = "\t".toRegex()
}
private val reader = path.toFile().bufferedReader()
private val graph = Graph(baseAddress)
/**
* Reads in the BRITE topology from the associated file and returns the created [Graph] object.
* @throws BriteFormatException if the format does not match the BRITE format standard
*/
internal fun readGraph(): Graph {
val lambda: (String) -> Unit = {
if (it.startsWith("Nodes:")) {
parseNodes()
}
// read in the edges of the graph
if (it.startsWith("Edges:")) {
parseEdges()
}
}
iterateLines(lambda)
return graph
}
/**
* Reads in all the nodes from the BRITE file and adds them to the given graph.
*/
private fun parseNodes() = iterateLines({ parseNode(it) }, { !this.isNullOrBlank() })
/**
* Reads in all the edges from the BRITE file and adds them to the given graph. The required nodes have to present
* in the given graph.
*/
private fun parseEdges() = iterateLines({ parseEdge(it) }, { !this.isNullOrBlank() })
private fun parseNode(line: String) {
val values = line.split(regex)
if (values.size < NODE_COLUMNS) {
throw BriteFormatException("The node line '$line' does not contain $NODE_COLUMNS columns.")
}
val id = values[0].asInt { "Failed to parse the id: ${values[0]}" }
val asId = values[5].asInt { "Failed to parse the autonomous system: ${values[5]}" }
// create a new edge node
graph.createEdgeNode(id, graph.getOrCreateAutonomousSystem(asId))
}
private fun parseEdge(line: String) {
val values = line.split(regex)
if (values.size < EDGE_COLUMNS) {
throw BriteFormatException("The edge node '$line' does not contain $EDGE_COLUMNS columns.")
}
val id = values[0].asInt { "Failed to parse the id: ${values[0]}" }
val from = values[1].asInt { "Failed to parse the link's source id: ${values[1]}" }
val to = values[2].asInt { "Failed to parse the link's destinations id: ${values[2]}" }
val delay = values[4].asFloat { "Failed to parse the link's latency: ${values[4]}" }
val bandwidth = values[5].asFloat { "Failed to parse the link's bandwidth: ${values[5]}" }
// get the source and destination nodes from the existing graph
val fromNode = graph.getEdgeNode(from)
checkNotNull(fromNode) { "The link starting node: $from is not part of the graph." }
val toNode = graph.getEdgeNode(to)
checkNotNull(toNode) { "The link ending node: $from is not part of the graph." }
// create the new edge
graph.createEdge(id, fromNode, toNode, delay, bandwidth)
}
private fun nextLine(): String? = reader.readLine()
private fun iterateLines(block: (String) -> Unit, condition: String?.() -> Boolean = { true }) {
var line = nextLine()
while (line != null && line.condition()) {
block(line)
line = nextLine()
}
}
}
private inline fun <T> String.toType(f: String.() -> T, exceptionMsg: () -> String): T {
try {
return f()
} catch (e: NumberFormatException) {
throw BriteFormatException(exceptionMsg(), e)
}
}
private inline fun String.asInt(msg: () -> String) = toType(String::toInt, msg)
private inline fun String.asFloat(msg: () -> String) = toType(String::toFloat, msg)
| mit | 0ad52110751552ef3e573397eed40beb | 37.19375 | 118 | 0.650139 | 4.276417 | false | false | false | false |
mayuki/AgqrPlayer4Tv | AgqrPlayer4Tv/app/src/main/java/org/misuzilla/agqrplayer4tv/component/activity/MainActivity.kt | 1 | 4961 | package org.misuzilla.agqrplayer4tv.component.activity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.util.Log
import android.view.KeyEvent
import android.view.WindowManager
import org.misuzilla.agqrplayer4tv.R
import org.misuzilla.agqrplayer4tv.component.fragment.PlaybackDefaultVideoViewFragment
import org.misuzilla.agqrplayer4tv.component.fragment.PlaybackExoPlayerFragment
import org.misuzilla.agqrplayer4tv.component.fragment.PlaybackPlayerFragmentBase
import org.misuzilla.agqrplayer4tv.component.fragment.PlaybackWebViewFragment
import org.misuzilla.agqrplayer4tv.component.broadcastreceiver.BootupBroadcastReceiver
import org.misuzilla.agqrplayer4tv.component.service.UpdateRecommendationService
import org.misuzilla.agqrplayer4tv.model.preference.ApplicationPreference
import org.misuzilla.agqrplayer4tv.model.preference.PlayerType
import org.misuzilla.agqrplayer4tv.model.preference.StreamingType
import android.content.Intent
class MainActivity : FragmentActivity() {
private var currentFragment: PlaybackPlayerFragmentBase? = null
private var lastPlayerType: PlayerType = PlayerType.EXO_PLAYER
override fun onAttachedToWindow() {
Log.d("MainActivity", "onAttachedToWindow")
super.onAttachedToWindow()
updateWindowFlags()
}
override fun onCreate(savedInstanceState: Bundle?) {
Log.d("MainActivity", "onCreate")
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// スケジュールして、同時にサービスを起動する
ApplicationPreference.recommendationCurrentProgram.set("")
BootupBroadcastReceiver.scheduleRecommendationUpdate(applicationContext)
startService(Intent(this, UpdateRecommendationService::class.java))
updateWindowFlags()
setupPlayerFlagment()
}
override fun onResume() {
Log.d("MainActivity", "onResume")
super.onResume()
updateWindowFlags()
if (lastPlayerType != ApplicationPreference.playerType.get()) {
setupPlayerFlagment()
}
}
override fun onPause() {
Log.d("MainActivity", "onPause")
super.onPause()
clearWindowFlags()
// 正常シャットダウンフラグを立てる
ApplicationPreference.isLastShutdownCorrectly.set(true)
}
private fun updateWindowFlags() {
// 起動したらスクリーンをオンにするように
window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
window.addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD)
window.addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON)
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
}
private fun clearWindowFlags() {
// 起動したらスクリーンをオンにするようにしたやつを落とす
// そうじゃないとActivityが生きている間、無限につきっぱなしになる
window.clearFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED)
window.clearFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD)
window.clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON)
window.clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) // DayDream(スクリーンセーバー)を抑制する
}
override fun onDestroy() {
Log.d("MainActivity", "onDestroy")
super.onDestroy()
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
when (keyCode) {
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
currentFragment?.let {
if (it.isPlaying.get()) {
it.stop()
} else {
it.play()
}
}
return true
}
}
return super.onKeyDown(keyCode, event)
}
fun setupPlayerFlagment() {
// RTMPは突然の死を迎えることがある…
// if (!ApplicationPreference.isLastShutdownCorrectly.get() && ApplicationPreference.streamingType.get() == StreamingType.RTMP) {
// ApplicationPreference.streamingType.set(StreamingType.HLS)
// }
val fragment = when (ApplicationPreference.playerType.get()) {
PlayerType.EXO_PLAYER -> PlaybackExoPlayerFragment()
PlayerType.ANDROID_DEFAULT -> PlaybackDefaultVideoViewFragment()
PlayerType.WEB_VIEW -> PlaybackWebViewFragment()
}
this.supportFragmentManager
.beginTransaction()
.replace(R.id.main_frame, fragment)
.commit()
// 正常シャットダウンフラグを折っておく
ApplicationPreference.isLastShutdownCorrectly.set(false)
lastPlayerType = ApplicationPreference.playerType.get()
}
}
| mit | 9d3fa213d3f23ed85d590bafa284dcab | 34.204545 | 136 | 0.695287 | 4.400568 | false | false | false | false |
beyama/winter | winter-compiler/src/test/resources/NoArgumentInjectConstructor_WinterFactory.kt | 1 | 785 | package test
import io.jentz.winter.Component
import io.jentz.winter.Graph
import io.jentz.winter.TypeKey
import io.jentz.winter.inject.ApplicationScope
import io.jentz.winter.inject.Factory
import javax.annotation.Generated
import kotlin.Boolean
@Generated(
value = ["io.jentz.winter.compiler.WinterProcessor"],
date = "2019-02-10T14:52Z"
)
class NoArgumentInjectConstructor_WinterFactory : Factory<NoArgumentInjectConstructor> {
override fun invoke(graph: Graph): NoArgumentInjectConstructor = NoArgumentInjectConstructor()
override fun register(builder: Component.Builder, override: Boolean):
TypeKey<NoArgumentInjectConstructor> {
builder.checkComponentQualifier(ApplicationScope::class)
return builder.singleton(override = override, factory = this)
}
}
| apache-2.0 | 904398bb51a09f12572ce533c472c816 | 33.130435 | 96 | 0.802548 | 4.088542 | false | false | false | false |
http4k/http4k | http4k-contract/src/main/kotlin/org/http4k/contract/openapi/v3/values4kExt.kt | 1 | 1348 | package org.http4k.contract.openapi.v3
import dev.forkhandles.values.Value
import org.http4k.core.Uri
import java.time.Instant
import java.time.LocalDate
import java.util.UUID
import kotlin.reflect.full.declaredMembers
/**
* Set format values for OpenApi descriptions for fields of this type
*/
object Values4kFieldMetadataRetrievalStrategy : FieldMetadataRetrievalStrategy {
override fun invoke(target: Any, fieldName: String): FieldMetadata {
val value = target::class.declaredMembers.find { it.name == fieldName }?.call(target)
return when {
value.isAValue<Int>() -> FieldMetadata("format" to "int32")
value.isAValue<Long>() -> FieldMetadata("format" to "int64")
value.isAValue<Double>() -> FieldMetadata("format" to "double")
value.isAValue<Float>() -> FieldMetadata("format" to "float")
value.isAValue<Instant>() -> FieldMetadata("format" to "date-time")
value.isAValue<LocalDate>() -> FieldMetadata("format" to "date")
value.isAValue<UUID>() -> FieldMetadata("format" to "uuid")
value.isAValue<Uri>() -> FieldMetadata("format" to "uri")
else -> FieldMetadata()
}
}
}
private inline fun <reified T> Any?.isAValue(): Boolean {
return (this as? Value<*>)?.value?.javaClass == T::class.java
}
| apache-2.0 | 6631c5c4feafdc5fabab394c1a578db3 | 36.444444 | 93 | 0.664688 | 4 | false | false | false | false |
mbuhot/eskotlin | src/main/kotlin/mbuhot/eskotlin/query/term/Wildcard.kt | 1 | 978 | /*
* Copyright (c) 2016. Michael Buhot [email protected]
*/
package mbuhot.eskotlin.query.term
import mbuhot.eskotlin.query.QueryData
import mbuhot.eskotlin.query.initQuery
import org.elasticsearch.index.query.WildcardQueryBuilder
class WildcardBlock {
class WildcardData(
val name: String,
var wildcard: String? = null) : QueryData()
infix fun String.to(wildcard: String) = WildcardData(name = this, wildcard = wildcard)
@Deprecated(message = "Use invoke operator instead.", replaceWith = ReplaceWith("invoke(init)"))
infix fun String.to(init: WildcardData.() -> Unit) = this.invoke(init)
operator fun String.invoke(init: WildcardData.() -> Unit) = WildcardData(name = this).apply(init)
}
fun wildcard(init: WildcardBlock.() -> WildcardBlock.WildcardData): WildcardQueryBuilder {
val params = WildcardBlock().init()
return WildcardQueryBuilder(params.name, params.wildcard).apply {
initQuery(params)
}
}
| mit | 583a0ffb2122fb9a11660b5125cae678 | 32.724138 | 101 | 0.713701 | 4.008197 | false | false | false | false |
http4k/http4k | http4k-core/src/main/kotlin/org/http4k/routing/static.kt | 1 | 3115 | package org.http4k.routing
import org.http4k.core.Body
import org.http4k.core.ContentType
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.MimeTypes
import org.http4k.core.NoOp
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Status
import org.http4k.core.then
import org.http4k.routing.ResourceLoader.Companion.Classpath
/**
* Serve static content using the passed ResourceLoader. Note that for security, by default ONLY mime-types registered in
* mime.types (resource file) will be served. All other types are registered as application/octet-stream and are not served.
*/
fun static(resourceLoader: ResourceLoader = Classpath(), vararg extraFileExtensionToContentTypes: Pair<String, ContentType>): RoutingHttpHandler = StaticRoutingHttpHandler("", resourceLoader, extraFileExtensionToContentTypes.asList().toMap())
internal data class StaticRoutingHttpHandler(
private val pathSegments: String,
private val resourceLoader: ResourceLoader,
private val extraFileExtensionToContentTypes: Map<String, ContentType>,
private val filter: Filter = Filter.NoOp
) : RoutingHttpHandler {
override fun withFilter(new: Filter): RoutingHttpHandler = copy(filter = new.then(filter))
override fun withBasePath(new: String): RoutingHttpHandler = copy(pathSegments = new + pathSegments)
private val handlerNoFilter = ResourceLoadingHandler(pathSegments, resourceLoader, extraFileExtensionToContentTypes)
private val handlerWithFilter = filter.then(handlerNoFilter)
override fun match(request: Request): RouterMatch = handlerNoFilter(request).let {
if (it.status != Status.NOT_FOUND) RouterMatch.MatchingHandler(filter.then { _: Request -> it }, description) else null
} ?: RouterMatch.Unmatched(description)
override fun invoke(request: Request): Response = handlerWithFilter(request)
}
internal class ResourceLoadingHandler(
private val pathSegments: String,
private val resourceLoader: ResourceLoader,
extraFileExtensionToContentTypes: Map<String, ContentType>
) : HttpHandler {
private val extMap = MimeTypes(extraFileExtensionToContentTypes)
override fun invoke(p1: Request): Response = if (p1.uri.path.startsWith(pathSegments)) {
val path = convertPath(p1.uri.path)
resourceLoader.load(path)?.let { url ->
val lookupType = extMap.forFile(path)
if (p1.method == Method.GET && lookupType != ContentType.OCTET_STREAM) {
Response(Status.OK)
.header("Content-Type", lookupType.value)
.body(Body(url.openStream()))
} else Response(Status.NOT_FOUND)
} ?: Response(Status.NOT_FOUND)
} else Response(Status.NOT_FOUND)
private fun convertPath(path: String): String {
val newPath = if (pathSegments == "/" || pathSegments == "") path else path.replaceFirst(pathSegments, "")
val resolved = if (newPath == "/" || newPath.isBlank()) "/index.html" else newPath
return resolved.trimStart('/')
}
}
| apache-2.0 | 740b75f124956213d915243e503dbe3b | 45.492537 | 242 | 0.735795 | 4.296552 | false | false | false | false |
dexbleeker/hamersapp | hamersapp/src/main/java/nl/ecci/hamers/ui/fragments/UserListFragment.kt | 1 | 5267 | package nl.ecci.hamers.ui.fragments
import android.content.Context
import android.os.AsyncTask
import android.os.Bundle
import android.view.*
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.google.gson.GsonBuilder
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.fragment_hamers_list.*
import nl.ecci.hamers.R
import nl.ecci.hamers.data.GetCallback
import nl.ecci.hamers.data.Loader
import nl.ecci.hamers.models.User
import nl.ecci.hamers.ui.activities.MainActivity
import nl.ecci.hamers.ui.adapters.UserFragmentAdapter
import nl.ecci.hamers.ui.adapters.UserListAdapter
import nl.ecci.hamers.utils.DividerItemDecoration
import org.jetbrains.anko.padding
import java.util.*
class UserListFragment : HamersListFragment(), SwipeRefreshLayout.OnRefreshListener {
private val dataSet = ArrayList<User>()
private var exUser: Boolean = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setHasOptionsMenu(true)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_hamers_list, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
hamers_list.addItemDecoration(DividerItemDecoration(requireContext()))
hamers_list.padding = 0
hamers_list.adapter = UserListAdapter(dataSet, activity as Context)
hamers_fab.visibility = View.GONE
exUser = arguments!!.getBoolean(UserFragmentAdapter.exUser, false)
populateList().execute()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.user_menu, menu)
}
override fun onRefresh() {
setRefreshing(true)
Loader.getData(requireContext(), Loader.USERURL, -1, object : GetCallback {
override fun onSuccess(response: String) {
populateList().execute(response)
}
}, null)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
R.id.sort_username -> {
sortByUsername()
return true
}
R.id.sort_quotes -> {
sortByQuoteCount()
return true
}
R.id.sort_reviews -> {
sortByReviewCount()
return true
}
R.id.sort_batch -> {
sortByBatch()
return true
}
else -> return false
}
}
private fun sort() {
when (prefs?.getString("userSort", "")) {
"name" -> sortByUsername()
"quotecount" -> sortByQuoteCount()
"reviewcount" -> sortByReviewCount()
}
notifyAdapter()
}
private fun sortByUsername() {
val nameComperator = Comparator<User> { user1, user2 -> user1.name.compareTo(user2.name, ignoreCase = true) }
Collections.sort(dataSet, nameComperator)
notifyAdapter()
}
private fun sortByQuoteCount() {
val quoteComperator = Comparator<User> { user1, user2 -> user2.quoteCount - user1.quoteCount }
Collections.sort(dataSet, quoteComperator)
notifyAdapter()
}
private fun sortByReviewCount() {
val reviewComperator = Comparator<User> { user1, user2 -> user2.reviewCount - user1.reviewCount }
Collections.sort(dataSet, reviewComperator)
notifyAdapter()
}
private fun sortByBatch() {
val batchComperator = Comparator<User> { user1, user2 -> user1.batch - user2.batch }
Collections.sort(dataSet, batchComperator)
notifyAdapter()
}
private inner class populateList : AsyncTask<String, Void, ArrayList<User>>() {
override fun doInBackground(vararg params: String): ArrayList<User> {
val result = ArrayList<User>()
val tempList: ArrayList<User>?
val type = object : TypeToken<ArrayList<User>>() {
}.type
val gsonBuilder = GsonBuilder()
gsonBuilder.setDateFormat(MainActivity.dbDF.toPattern())
val gson = gsonBuilder.create()
tempList = if (params.isNotEmpty()) {
gson.fromJson<ArrayList<User>>(params[0], type)
} else {
gson.fromJson<ArrayList<User>>(prefs?.getString(Loader.USERURL, null), type)
}
if (tempList != null) {
for (user in tempList) {
if (exUser && user.member !== User.Member.LID) {
result.add(user)
} else if (!exUser && user.member === User.Member.LID) {
result.add(user)
}
}
}
return result
}
override fun onPostExecute(result: ArrayList<User>?) {
if (result != null) {
dataSet.clear()
dataSet.addAll(result)
notifyAdapter()
}
sort()
setRefreshing(false)
}
}
}
| gpl-3.0 | 40b1321450ac7dc7688c649080d74def | 32.980645 | 117 | 0.607746 | 4.749324 | false | false | false | false |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/utils/FieldAwareValidator.kt | 1 | 1240 | package lt.vilnius.tvarkau.utils
import io.reactivex.Single
import io.reactivex.Single.defer
import io.reactivex.Single.just
class FieldAwareValidator<T> private constructor(
private val obj: T,
private val exception: ValidationException? = null
) {
fun validate(predicate: (T) -> Boolean, viewId: Int, message: CharSequence): FieldAwareValidator<T> {
return validate(predicate, viewId, message.toString())
}
fun validate(predicate: (T) -> Boolean, viewId: Int, message: String): FieldAwareValidator<T> {
if (exception == null && !predicate(obj)) {
return FieldAwareValidator(obj, ValidationException(viewId, message))
}
return this
}
/**
* Will throw [ValidationException] if form data is not valid
*/
fun get(): T {
return if (exception == null) {
obj
} else {
throw exception
}
}
fun toSingle(): Single<T> {
return defer { just(get()) }
}
companion object {
fun <T> of(obj: T): FieldAwareValidator<T> {
return FieldAwareValidator(obj)
}
}
class ValidationException(val viewId: Int, message: String) : IllegalStateException(message)
}
| mit | bfa77ce31c1d515cca2e38a362722c41 | 25.956522 | 105 | 0.625 | 4.261168 | false | false | false | false |
nidi3/code-assert | code-assert/src/test/kotlin/guru/nidi/codeassert/Linker.kt | 1 | 2385 | /*
* Copyright © 2015 Stefan Niederhauser ([email protected])
*
* 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 guru.nidi.codeassert
import java.util.List
import java.util.*
object Linker {
private val urlRegex = Regex("(https?://|www\\.)[^\\s\\p{Z}…|”“»<>]+")
private val hashRegex = Regex("#([^\\s\\p{Z}-:;,+!?()…@#*\"'/|\\[\\]{}`<>\$%^&=”“»~’\u2013\u2014.]+)")
private val userRegex = Regex("@([^\\s\\p{Z}-:;,+!?()…@#*\"'/|\\[\\]{}`<>\$%^&=”“»~’\u2013\u2014]+)")
fun twitter(content: String) = user(hash(url(newlines(content)), "https://twitter.com/hashtag/"), "https://twitter.com/")
fun facebook(content: String) = hash(url(newlines(content)), "https://facebook.com/hashtag/")
fun instagram(content: String) = user(hash(url(newlines(content)), "https://instagram.com/explore/tags/"), "https://instagram.com/")
private fun newlines(s: String) = s.replace("\n", "<br>");
fun url(s: String) =
urlRegex.replace(s) { res ->
val value = res.value
val trim = value.trimEnd('.', ')', ',', '!', '?')
val rest = value.substring(trim.length)
"""<a href="$trim" target="_blank">$trim</a>$rest"""
}
fun hash(s: String, base: String) = try {
hashRegex.replace(s, """<a href="$base$1" target="_blank" rel="nofollow">#$1</a>""")
} catch (e: Exception) {
""
}
fun user(s: String, base: String) =
userRegex.replace(s) { res ->
val value = res.groups[1]!!.value
if (".." in value) res.value
else {
val trim = value.trimEnd('.')
val rest = value.substring(trim.length)
"""<a href="$base$trim" target="_blank" rel="nofollow">@$trim</a>$rest"""
}
}
} | apache-2.0 | 2071d6ef10e5c680d489a2576db68560 | 39 | 136 | 0.560831 | 3.640432 | false | false | false | false |
tfcbandgeek/SmartReminders-android | app/src/main/java/jgappsandgames/smartreminderslite/sort/StatusActivity.kt | 1 | 2705 | package jgappsandgames.smartreminderslite.sort
// Android OS
import android.app.Activity
import android.os.Bundle
// Views
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
// App
import jgappsandgames.smartreminderslite.R
import jgappsandgames.smartreminderslite.adapter.TaskAdapter
import jgappsandgames.smartreminderslite.utility.*
// KotlinX
import kotlinx.android.synthetic.main.activity_status.*
// Save
import jgappsandgames.smartreminderssave.MasterManager
import jgappsandgames.smartreminderssave.status.StatusManager
import jgappsandgames.smartreminderssave.tasks.Task
/**
* StatusActivity
* Created by joshua on 12/14/2017.
*/
class StatusActivity: AppCompatActivity(), TaskAdapter.OnTaskChangedListener {
// LifeCycle Methods ---------------------------------------------------------------------------
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_status)
// Handle Data
loadClass(this)
}
override fun onResume() {
super.onResume()
// Create Status Manager
StatusManager.create()
val i = ArrayList<Task>()
i.addAll(StatusManager.getInProgress())
i.addAll(StatusManager.getIncomplete())
// Set Adapters
status_overdue_list.adapter = TaskAdapter(this, this, TaskAdapter.swapTasks(StatusManager.getOverdue()), "")
status_incomplete_list.adapter = TaskAdapter(this, this, TaskAdapter.swapTasks(i), "")
status_done_list.adapter = TaskAdapter(this, this, TaskAdapter.swapTasks(StatusManager.getCompleted()), "")
// Set Text
status_overdue_text.text = getString(R.string.overdue_tasks, StatusManager.getOverdue().size)
status_incomplete_text.text = getString(R.string.incomplete_tasks, i.size)
status_done_text.text = getString(R.string.completed_tasks, StatusManager.getCompleted().size)
}
// Menu Methods --------------------------------------------------------------------------------
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_auxilary, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = onOptionsItemSelected(this, item, object: Save { override fun save() = [email protected]() })
// Task Change Listeners -----------------------------------------------------------------------
override fun onTaskChanged() = onResume()
// Parent Methods ------------------------------------------------------------------------------
fun save() = MasterManager.save()
} | apache-2.0 | b81bd911519b39ba8aab874d29f9f8d3 | 36.068493 | 166 | 0.645102 | 5.084586 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/data/LanternDataRegistration.kt | 1 | 2234 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.data
import org.lanternpowered.api.util.optional.emptyOptional
import org.lanternpowered.api.util.optional.asOptional
import org.lanternpowered.api.util.uncheckedCast
import org.lanternpowered.server.catalog.DefaultCatalogType
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.plugin.PluginContainer
import org.lanternpowered.api.util.type.TypeToken
import org.spongepowered.api.data.DataHolder
import org.spongepowered.api.data.DataProvider
import org.spongepowered.api.data.DataRegistration
import org.spongepowered.api.data.Key
import org.spongepowered.api.data.UnregisteredKeyException
import org.spongepowered.api.data.persistence.DataStore
import org.spongepowered.api.data.value.Value
import java.util.Optional
class LanternDataRegistration(
key: NamespacedKey,
private val pluginContainer: PluginContainer,
private val keys: Set<Key<*>>,
private val dataStores: List<DataStore>,
private val providers: Map<Key<*>, DataProvider<*,*>>
) : DefaultCatalogType(key), DataRegistration {
override fun <V : Value<E>, E : Any> getProviderFor(key: Key<V>): Optional<DataProvider<V, E>> {
val provider = this.providers[key]
if (provider != null) {
return provider.uncheckedCast<DataProvider<V, E>>().asOptional()
}
if (key !in this.keys) throw UnregisteredKeyException()
return emptyOptional()
}
override fun getDataStore(token: TypeToken<out DataHolder>) =
this.dataStores.first { store -> store.supportedTokens.any { token.isSubtypeOf(it) } }.asOptional()
override fun getKeys() = this.keys
override fun getPluginContainer() = this.pluginContainer
override fun toStringHelper() = super.toStringHelper()
.add("keys", this.keys.map { it.key }.joinToString(separator = ",", prefix = "[", postfix = "]"))
}
| mit | b5ef9629c6390dbf2ffda3cff4e47cee | 40.37037 | 111 | 0.733662 | 4.287908 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/world/chunk/LocalPosition.kt | 1 | 1561 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.world.chunk
import org.spongepowered.math.vector.Vector3i
/**
* Represents a local position of a block in a chunk.
*/
@Suppress("NON_PUBLIC_PRIMARY_CONSTRUCTOR_OF_INLINE_CLASS")
inline class LocalPosition @PublishedApi internal constructor(
internal val packedShort: Short
) {
/**
* Constructs a new [LocalPosition] from the given packed value.
*/
constructor(packed: Int) : this(packed.toShort())
/**
* Constructs a new [LocalPosition] from the given x, y and z values.
*/
constructor(x: Int, y: Int, z: Int) : this(LocalPositionHelper.pack(x, y, z))
/**
* The packed as an int.
*/
internal inline val packed: Int
get() = this.packedShort.toInt()
/**
* The x coordinate.
*/
val x: Int
get() = LocalPositionHelper.unpackX(this.packedShort)
/**
* The y coordinate.
*/
val y: Int
get() = LocalPositionHelper.unpackY(this.packedShort)
/**
* The z coordinate.
*/
val z: Int
get() = LocalPositionHelper.unpackZ(this.packedShort)
fun toVector(): Vector3i = Vector3i(this.x, this.y, this.z)
override fun toString(): String = "($x, $y, $z)"
}
| mit | 7a437bfe3edde9c5a6dba3d72070e800 | 25.016667 | 81 | 0.638693 | 3.690307 | false | false | false | false |
mustafaberkaymutlu/uv-index | autocomplete/src/main/java/net/epictimes/uvindex/autocomplete/PlacesRecyclerViewAdapter.kt | 1 | 1289 | package net.epictimes.uvindex.autocomplete
import android.location.Address
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
class PlacesRecyclerViewAdapter : RecyclerView.Adapter<PlaceViewHolder>() {
private val addresses = mutableListOf<Address>()
var rowClickListener: ((address: Address) -> Unit)? = null
fun setAddresses(newAddresses: List<Address>) {
with(addresses) {
clear()
addAll(newAddresses)
}
notifyDataSetChanged()
}
fun clearAddresses() {
val previousSize = addresses.size
addresses.clear()
notifyItemRangeRemoved(0, previousSize)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlaceViewHolder {
val view = LayoutInflater.from(parent.context).inflate(PlaceViewHolder.LAYOUT_ID, parent, false)
val placeViewHolder = PlaceViewHolder(view)
placeViewHolder.clickListener = { pos ->
rowClickListener?.invoke(addresses[pos])
}
return placeViewHolder
}
override fun onBindViewHolder(holder: PlaceViewHolder, position: Int) {
holder.bind(addresses[position])
}
override fun getItemCount(): Int = addresses.size
} | apache-2.0 | 4d41bacd65836b14cfac299ce56192ec | 28.318182 | 104 | 0.692009 | 4.882576 | false | false | false | false |
pokk/mvp-magazine | app/src/main/kotlin/taiwan/no1/app/mvp/models/tv/TvListResModel.kt | 1 | 1186 | package taiwan.no1.app.mvp.models.tv
import android.os.Parcel
import android.os.Parcelable
/**
*
* @author Jieyi
* @since 2/5/17
*/
data class TvListResModel(val page: Int = 0,
val total_results: Int = 0,
val total_pages: Int = 0,
val results: List<TvBriefModel>? = null): Parcelable {
//region Parcelable
companion object {
@JvmField val CREATOR: Parcelable.Creator<TvListResModel> = object: Parcelable.Creator<TvListResModel> {
override fun createFromParcel(source: Parcel): TvListResModel = TvListResModel(source)
override fun newArray(size: Int): Array<TvListResModel?> = arrayOfNulls(size)
}
}
constructor(source: Parcel): this(source.readInt(),
source.readInt(),
source.readInt(),
source.createTypedArrayList(TvBriefModel.CREATOR))
override fun describeContents() = 0
override fun writeToParcel(dest: Parcel?, flags: Int) {
dest?.writeInt(page)
dest?.writeInt(total_results)
dest?.writeInt(total_pages)
dest?.writeTypedList(results)
}
//endregion
}
| apache-2.0 | 709168614b006ca0dbd464938e9d8529 | 30.210526 | 112 | 0.618887 | 4.250896 | false | false | false | false |
PaulWoitaschek/Voice | folderPicker/src/main/kotlin/voice/folderPicker/selectType/SelectFolderType.kt | 1 | 6032 | package voice.folderPicker.selectType
import android.net.Uri
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Close
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.MediumTopAppBar
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.material3.TopAppBarScrollBehavior
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.documentfile.provider.DocumentFile
import com.squareup.anvil.annotations.ContributesTo
import voice.common.AppScope
import voice.common.compose.rememberScoped
import voice.common.rootComponentAs
import voice.folderPicker.R
@ContributesTo(AppScope::class)
interface SelectFolderTypeComponent {
val selectFolderTypeViewModel: SelectFolderTypeViewModel
}
@Composable
fun SelectFolderType(uri: Uri) {
val viewModel = rememberScoped {
rootComponentAs<SelectFolderTypeComponent>().selectFolderTypeViewModel
}
val documentFile = DocumentFile.fromTreeUri(LocalContext.current, uri) ?: return
viewModel.args = SelectFolderTypeViewModel.Args(uri, documentFile)
val viewState = viewModel.viewState()
SelectFolderType(
viewState = viewState,
onFolderModeSelected = { viewModel.setFolderMode(it) },
onAddClick = { viewModel.add() },
onBackClick = { viewModel.onCloseClick() },
)
}
@Composable
private fun SelectFolderType(
viewState: SelectFolderTypeViewState,
onFolderModeSelected: (FolderMode) -> Unit,
onAddClick: () -> Unit,
onBackClick: () -> Unit,
) {
val scrollBehavior = TopAppBarDefaults.exitUntilCollapsedScrollBehavior()
Scaffold(
modifier = Modifier.nestedScroll(scrollBehavior.nestedScrollConnection),
floatingActionButton = {
AddingFab(addButtonVisible = viewState.addButtonVisible, onAddClick = onAddClick)
},
topBar = {
AppBar(scrollBehavior, onBackClick)
},
) { contentPadding ->
Content(
contentPadding = contentPadding,
onFolderModeSelected = onFolderModeSelected,
viewState = viewState,
)
}
}
@Composable
private fun Content(
contentPadding: PaddingValues,
viewState: SelectFolderTypeViewState,
onFolderModeSelected: (FolderMode) -> Unit,
) {
LazyVerticalGrid(
columns = GridCells.Adaptive(150.dp),
contentPadding = contentPadding,
modifier = Modifier.fillMaxSize(),
) {
item(
key = "header",
span = { GridItemSpan(maxLineSpan) },
) {
FolderModeSelectionCard(
onFolderModeSelected = onFolderModeSelected,
selectedFolderMode = viewState.selectedFolderMode,
)
}
item(
key = "folderStructureExplanation",
span = { GridItemSpan(maxLineSpan) },
) {
Column(modifier = Modifier.padding(horizontal = 16.dp)) {
Text(
modifier = Modifier.padding(top = 24.dp),
text = stringResource(id = R.string.folder_type_book_example_header),
style = MaterialTheme.typography.headlineSmall,
)
}
}
if (viewState.loading) {
item(
key = "loading",
span = { GridItemSpan(maxLineSpan) },
) {
Box(Modifier.padding(top = 24.dp)) {
CircularProgressIndicator(
Modifier
.size(48.dp)
.align(Alignment.Center),
)
}
}
} else {
if (viewState.noBooksDetected) {
item(
key = "noBooksDetected",
span = { GridItemSpan(maxLineSpan) },
) {
Text(text = stringResource(id = R.string.folder_type_no_books))
}
} else {
item(span = { GridItemSpan(maxLineSpan) }) {
Spacer(modifier = Modifier.size(16.dp))
}
items(viewState.books) { book ->
FolderModeBook(
modifier = Modifier.padding(top = 8.dp, bottom = 8.dp, end = 8.dp, start = 8.dp),
book = book,
)
}
item { Spacer(modifier = Modifier.size(24.dp)) }
}
}
}
}
@Composable
private fun AppBar(
scrollBehavior: TopAppBarScrollBehavior,
onBackClick: () -> Unit,
) {
MediumTopAppBar(
scrollBehavior = scrollBehavior,
navigationIcon = {
IconButton(onClick = onBackClick) {
Icon(
imageVector = Icons.Outlined.Close,
contentDescription = stringResource(id = R.string.close),
)
}
},
title = {
Text(text = stringResource(id = R.string.folder_type_title))
},
)
}
@Preview
@Composable
private fun SelectFolderTypePreview() {
SelectFolderType(
onBackClick = {},
onFolderModeSelected = {},
viewState = SelectFolderTypeViewState(
books = listOf(
SelectFolderTypeViewState.Book("Cats", 42),
SelectFolderTypeViewState.Book("Dogs", 12),
),
selectedFolderMode = FolderMode.SingleBook,
noBooksDetected = false,
loading = false,
addButtonVisible = true,
),
onAddClick = {},
)
}
| gpl-3.0 | 4f8d609784c248cca7b0594d8c2bff01 | 29.933333 | 93 | 0.706068 | 4.428781 | false | false | false | false |
andreyfomenkov/green-cat | plugin/src/ru/fomenkov/runner/update/PluginUpdater.kt | 1 | 2593 | package ru.fomenkov.runner.update
import ru.fomenkov.plugin.util.exec
import ru.fomenkov.runner.GREENCAT_JAR
import ru.fomenkov.runner.logger.Log
import ru.fomenkov.runner.params.RunnerParams
import ru.fomenkov.runner.ssh.ssh
import java.io.File
class PluginUpdater(
updateTimestampFile: String,
artifactVersionInfoUrl: String,
) : Updater(updateTimestampFile, artifactVersionInfoUrl) {
override fun checkForUpdate(params: RunnerParams, forceCheck: Boolean) {
val remoteJarPath = "${params.greencatRoot}/$GREENCAT_JAR"
val exists = ssh { cmd("ls $remoteJarPath && echo OK") }.find { line -> line.trim() == "OK" } != null
ssh { cmd("mkdir -p ${params.greencatRoot}") }
fun downloadUpdate(version: String, artifactUrl: String) {
Log.d("Downloading plugin... ", newLine = false)
val tmpDir = exec("echo \$TMPDIR").firstOrNull() ?: ""
check(tmpDir.isNotBlank()) { "Unable to get /tmp directory" }
exec("curl -s $artifactUrl > $tmpDir/$GREENCAT_JAR")
val tmpJarPath = "$tmpDir/$GREENCAT_JAR"
if (!File(tmpJarPath).exists()) {
error("Error downloading $GREENCAT_JAR to /tmp directory")
}
ssh { cmd("rm $remoteJarPath") }
val isDeleted = ssh { cmd("ls $remoteJarPath && echo OK") }.find { line -> line.trim() == "OK" } == null
if (!isDeleted) {
error("Failed to delete old JAR version on the remote host")
}
exec("scp $tmpJarPath ${params.sshHost}:$remoteJarPath")
val isUpdated = ssh { cmd("ls $remoteJarPath && echo OK") }.find { line -> line.trim() == "OK" } != null
when {
isUpdated -> Log.d("Done. GreenCat updated to v$version")
else -> error("Error uploading $GREENCAT_JAR to the remote host")
}
}
if (exists) {
if (forceCheck || isNeedToCheckVersion()) {
Log.d("[Plugin] Checking for update... ", newLine = false)
val curVersion = ssh { cmd("java -jar $remoteJarPath -v") }.firstOrNull()?.trim() ?: ""
val (updVersion, artifactUrl) = getVersionInfo()
if (curVersion == updVersion) {
Log.d("Everything is up to date")
} else {
downloadUpdate(updVersion, artifactUrl)
}
}
} else {
val (updVersion, artifactUrl) = getVersionInfo()
downloadUpdate(updVersion, artifactUrl)
}
}
} | apache-2.0 | 28a904dcc81ca26417d2772cf8bfc6f0 | 39.53125 | 116 | 0.572696 | 4.16881 | false | false | false | false |
micabyte/lib_base | src/main/java/com/micabytes/map/HexUtil.kt | 2 | 1591 | package com.micabytes.map
import java.lang.Math.abs
import java.lang.Math.round
import com.google.android.gms.common.util.Hex
fun cubeToOddR(cube: Triple<Int, Int, Int>): Pair<Int, Int> {
val col = cube.first + (cube.third - (abs(cube.third) % 2)) / 2
val row = cube.third
return Pair(col, row)
}
fun oddRToCube(hex: Pair<Int, Int>): Triple<Int, Int, Int> {
val x = hex.first - (hex.second - (abs(hex.second) % 2)) / 2
val z = hex.second
val y = -x - z
return Triple(x, y, z)
}
fun cube_round(cube: Triple<Double, Double, Double>): Triple<Int, Int, Int> {
var rx = round(cube.first)
var ry = round(cube.second)
var rz = round(cube.third)
val x_diff = abs(rx - cube.first)
val y_diff = abs(ry - cube.second)
val z_diff = abs(rz - cube.third)
if (x_diff > y_diff && x_diff > z_diff)
rx = -ry - rz
else if (y_diff > z_diff)
ry = -rx - rz
else
rz = -rx - ry
return Triple(rx.toInt(), ry.toInt(), rz.toInt())
}
fun lerp(a: Double, b: Double, t: Double): Double {
return (a * (1 - t) + b * t)
}
/*
fun hex_lerp(a: Triple<Int, Int, Int>, b: Triple<Int, Int, Int>, t: Double): Triple<Double, Double, Double> {
return Triple(
lerp(a.first.toDouble(), b.first.toDouble(), t),
lerp(a.second.toDouble(), b.second.toDouble(), t),
lerp(a.third.toDouble(), b.third.toDouble(), t)
)
}
*/
fun hex_lerp(a: Triple<Double, Double, Double>, b: Triple<Double, Double, Double>, t: Double): Triple<Double, Double, Double> {
return Triple(
lerp(a.first, b.first, t),
lerp(a.second, b.second, t),
lerp(a.third, b.third, t)
)
}
| apache-2.0 | aa80665acb9950cd807bb905c4bb3a6b | 25.966102 | 127 | 0.619107 | 2.710392 | false | false | false | false |
hanks-zyh/KotlinExample | src/LearnExtensions.kt | 1 | 530 | /**
* Created by hanks on 15-11-25.
*/
// Extension Function
fun MutableList<Int>.swap(index1: Int, index2: Int) {
val tmp = this[index1]
this[index1] = this[index2]
this[index2] = tmp
}
fun main(args: Array<String>) {
val list = listOf("a", "b", "c")
print(list.string())
println("------------")
print("${list.size},${list.lastIndex}")
}
fun Any?.string(): String {
if (this == null ) return "null"
return "hanks:${toString()}"
}
val <T> List<T>.lastIndex: Int
get() = size - 1
| apache-2.0 | 561cc31d094884ca08f849f1c178202c | 16.666667 | 53 | 0.564151 | 3.028571 | false | false | false | false |
schaal/ocreader | app/src/main/java/email/schaal/ocreader/ui/loginflow/LoginFlowFragment.kt | 1 | 3124 | /*
* Copyright © 2020. Daniel Schaal <[email protected]>
*
* This file is part of ocreader.
*
* ocreader 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.
*
* ocreader 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 Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
package email.schaal.ocreader.ui.loginflow
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import email.schaal.ocreader.R
import email.schaal.ocreader.databinding.LoginFlowFragmentBinding
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
class LoginFlowFragment : Fragment() {
private lateinit var binding: LoginFlowFragmentBinding
private var url: String? = null
companion object {
private const val ARG_URL = "URL"
@JvmStatic
fun newInstance(url: String? = null) =
LoginFlowFragment().apply {
url?.let {
arguments = Bundle().apply {
putString(ARG_URL, it)
}
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
arguments?.let {
url = it.getString(ARG_URL)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View {
binding = LoginFlowFragmentBinding.inflate(inflater, container, false)
binding.inputUrl.setText(url, TextView.BufferType.EDITABLE)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.buttonLogin.setOnClickListener {
// Check if inputUrl starts with a scheme (http or https)
val urlString = binding.inputUrl.text?.let {
if(!it.startsWith("http"))
"https://${it}"
else
it
}?.toString()
val url = urlString
?.toHttpUrlOrNull()
?.newBuilder()
?.addPathSegments("index.php/login/flow")
if(url != null) {
parentFragmentManager.beginTransaction()
.replace(R.id.container, LoginFlowWebViewFragment.newInstance(url.toString()))
.commit()
} else {
binding.inputUrl.error = getString(R.string.error_incorrect_url)
}
}
}
}
| gpl-3.0 | 937126e3b4f657984776cb0f43438e37 | 33.7 | 102 | 0.617355 | 4.91811 | false | false | false | false |
tasks/tasks | app/src/main/java/com/todoroo/astrid/adapter/AstridTaskAdapter.kt | 1 | 3953 | package com.todoroo.astrid.adapter
import com.todoroo.andlib.utility.DateUtilities
import com.todoroo.astrid.api.Filter
import com.todoroo.astrid.dao.TaskDao
import com.todoroo.astrid.data.Task
import com.todoroo.astrid.subtasks.SubtasksFilterUpdater
import org.tasks.LocalBroadcastManager
import org.tasks.Strings.isNullOrEmpty
import org.tasks.data.CaldavDao
import org.tasks.data.GoogleTaskDao
import org.tasks.data.TaskContainer
import org.tasks.data.TaskListMetadata
import timber.log.Timber
import java.util.*
import kotlin.math.abs
@Deprecated("legacy astrid manual sorting")
class AstridTaskAdapter internal constructor(
private val list: TaskListMetadata,
private val filter: Filter,
private val updater: SubtasksFilterUpdater,
googleTaskDao: GoogleTaskDao,
caldavDao: CaldavDao,
private val taskDao: TaskDao,
private val localBroadcastManager: LocalBroadcastManager)
: TaskAdapter(false, googleTaskDao, caldavDao, taskDao, localBroadcastManager) {
private val chainedCompletions = Collections.synchronizedMap(HashMap<String, ArrayList<String>>())
override fun getIndent(task: TaskContainer) = updater.getIndentForTask(task.uuid)
override fun canMove(source: TaskContainer, from: Int, target: TaskContainer, to: Int) = !updater.isDescendantOf(target.uuid, source.uuid)
override fun maxIndent(previousPosition: Int, task: TaskContainer): Int {
val previous = getTask(previousPosition)
return updater.getIndentForTask(previous.uuid) + 1
}
override fun supportsAstridSorting() = true
override suspend fun moved(from: Int, to: Int, indent: Int) {
val source = getTask(from)
val targetTaskId = source.uuid
try {
if (to >= count) {
updater.moveTo(list, filter, targetTaskId, "-1") // $NON-NLS-1$
} else {
val destinationTaskId = getItemUuid(to)
updater.moveTo(list, filter, targetTaskId, destinationTaskId)
}
val currentIndent = updater.getIndentForTask(targetTaskId)
val delta = indent - currentIndent
for (i in 0 until abs(delta)) {
updater.indent(list, filter, targetTaskId, delta)
}
localBroadcastManager.broadcastRefresh()
} catch (e: Exception) {
Timber.e(e)
}
}
override suspend fun onTaskCreated(uuid: String) = updater.onCreateTask(list, filter, uuid)
override suspend fun onTaskDeleted(task: Task) = updater.onDeleteTask(list, filter, task.uuid)
override suspend fun onCompletedTask(task: TaskContainer, newState: Boolean) {
val itemId = task.uuid
val completionDate = if (newState) DateUtilities.now() else 0
if (!newState) {
val chained = chainedCompletions[itemId]
if (chained != null) {
for (taskId in chained) {
taskDao.setCompletionDate(taskId, completionDate)
}
}
return
}
val chained = ArrayList<String>()
updater.applyToDescendants(itemId) { node: SubtasksFilterUpdater.Node ->
val uuid = node.uuid
taskDao.setCompletionDate(uuid, completionDate)
chained.add(node.uuid)
}
if (chained.size > 0) {
// move recurring items to item parent
val tasks = taskDao.getRecurringTasks(chained)
var madeChanges = false
for (t in tasks) {
if (!isNullOrEmpty(t.recurrence)) {
updater.moveToParentOf(t.uuid, itemId)
madeChanges = true
}
}
if (madeChanges) {
updater.writeSerialization(list, updater.serializeTree())
}
chainedCompletions[itemId] = chained
}
}
override fun supportsHiddenTasks() = false
} | gpl-3.0 | d48b65dc54f392c22910d6131f4b4104 | 37.38835 | 142 | 0.646092 | 4.694774 | false | false | false | false |
sys1yagi/mastodon4j | mastodon4j/src/test/java/com/sys1yagi/mastodon4j/api/method/StatusesTest.kt | 1 | 5514 | package com.sys1yagi.mastodon4j.api.method
import com.sys1yagi.mastodon4j.api.exception.Mastodon4jRequestException
import com.sys1yagi.mastodon4j.testtool.MockClient
import org.amshove.kluent.shouldEqualTo
import org.amshove.kluent.shouldNotBe
import org.junit.Test
import org.junit.Assert.*
class StatusesTest {
@Test
fun getStatus() {
val client = MockClient.mock("status.json")
val statuses = Statuses(client)
val status = statuses.getStatus(1L).execute()
status.id shouldEqualTo 11111L
}
@Test(expected = Mastodon4jRequestException::class)
fun getStatusWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.getStatus(1L).execute()
}
@Test
fun getContext() {
val client = MockClient.mock("context.json")
val statuses = Statuses(client)
val context = statuses.getContext(1L).execute()
context.ancestors.size shouldEqualTo 2
context.descendants.size shouldEqualTo 1
}
@Test(expected = Mastodon4jRequestException::class)
fun getContextWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.getContext(1L).execute()
}
@Test
fun getCard() {
val client = MockClient.mock("card.json")
val statuses = Statuses(client)
val card = statuses.getCard(1L).execute()
card.url shouldEqualTo "The url associated with the card"
card.title shouldEqualTo "The title of the card"
card.description shouldEqualTo "The card description"
card.image shouldNotBe null
}
@Test(expected = Mastodon4jRequestException::class)
fun getCardWithExcetpion() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.getCard(1L).execute()
}
@Test
fun getRebloggedBy() {
val client = MockClient.mock("reblogged_by.json")
val statuses = Statuses(client)
val pageable = statuses.getRebloggedBy(1L).execute()
val account = pageable.part.first()
account.acct shouldEqualTo "[email protected]"
account.displayName shouldEqualTo "test"
account.userName shouldEqualTo "test"
}
@Test(expected = Mastodon4jRequestException::class)
fun getRebloggedByWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.getRebloggedBy(1L).execute()
}
@Test
fun getFavouritedBy() {
val client = MockClient.mock("reblogged_by.json")
val statuses = Statuses(client)
val pageable = statuses.getFavouritedBy(1L).execute()
val account = pageable.part.first()
account.acct shouldEqualTo "[email protected]"
account.displayName shouldEqualTo "test"
account.userName shouldEqualTo "test"
}
@Test(expected = Mastodon4jRequestException::class)
fun getFavouritedByWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.getFavouritedBy(1L).execute()
}
@Test
fun postStatus() {
val client = MockClient.mock("status.json")
val statuses = Statuses(client)
val status = statuses.postStatus("a", null, null, false, null).execute()
status.id shouldEqualTo 11111L
}
@Test(expected = Mastodon4jRequestException::class)
fun postStatusWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.postStatus("a", null, null, false, null).execute()
}
@Test
fun postReblog() {
val client = MockClient.mock("status.json")
val statuses = Statuses(client)
val status = statuses.postReblog(1L).execute()
status.id shouldEqualTo 11111L
}
@Test(expected = Mastodon4jRequestException::class)
fun postReblogWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.postReblog(1L).execute()
}
@Test
fun postUnreblog() {
val client = MockClient.mock("status.json")
val statuses = Statuses(client)
val status = statuses.postUnreblog(1L).execute()
status.id shouldEqualTo 11111L
}
@Test(expected = Mastodon4jRequestException::class)
fun postUnreblogWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.postUnreblog(1L).execute()
}
@Test
fun postFavourite() {
val client = MockClient.mock("status.json")
val statuses = Statuses(client)
val status = statuses.postFavourite(1L).execute()
status.id shouldEqualTo 11111L
}
@Test(expected = Mastodon4jRequestException::class)
fun postFavouriteWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.postFavourite(1L).execute()
}
@Test
fun postUnfavourite() {
val client = MockClient.mock("status.json")
val statuses = Statuses(client)
val status = statuses.postUnfavourite(1L).execute()
status.id shouldEqualTo 11111L
}
@Test(expected = Mastodon4jRequestException::class)
fun postUnfavouriteWithException() {
val client = MockClient.ioException()
val statuses = Statuses(client)
statuses.postUnfavourite(1L).execute()
}
}
| mit | 79961417a19d2223dd4625d027ee11ab | 31.245614 | 80 | 0.660138 | 4.379666 | false | true | false | false |
soniccat/android-taskmanager | app_demo/src/main/java/com/main/Networks.kt | 1 | 4246 | package com.main
import com.example.alexeyglushkov.authorization.Api.Foursquare2Api
import com.example.alexeyglushkov.authorization.Auth.Account
import com.example.alexeyglushkov.authorization.Auth.AccountStore
import com.example.alexeyglushkov.authorization.Auth.Authorizer
import com.example.alexeyglushkov.authorization.Auth.SimpleAccount
import com.example.alexeyglushkov.authorization.OAuth.OAuth20Authorizer
import com.example.alexeyglushkov.authorization.OAuth.OAuthAuthorizerBuilder
import com.example.alexeyglushkov.authorization.OAuth.OAuthWebClient
import com.example.alexeyglushkov.authtaskmanager.ServiceTaskProvider
import com.example.alexeyglushkov.authtaskmanager.ServiceTaskRunner
import com.example.alexeyglushkov.quizletservice.auth.QuizletApi2
import com.example.alexeyglushkov.taskmanager.TaskManager
import org.junit.Assert
/**
* Created by alexeyglushkov on 25.11.15.
*/
// TODO: avoid method duplication for every network, move to classes
object Networks {
//TODO: it could be different for each network
const val CALLBACK_URL = "http://gaolife.blogspot.ru"
val authWebClient: OAuthWebClient
get() = MainApplication.instance.authWebClient
val taskManager: TaskManager
get() = MainApplication.instance.taskManager
val accountStore: AccountStore
get() = MainApplication.instance.accountStore
fun getAccount(serviceType: Int): Account {
Assert.assertNotNull("accountStore must exists", accountStore)
val accounts = accountStore.getAccounts(serviceType)
return if (accounts.size > 0) {
accounts[0]
} else {
createAccount(Network.Quizlet)
}
}
fun restoreAuthorizer(acc: Account) {
if (acc.serviceType == Network.Foursquare.ordinal) {
acc.authorizer = foursquareAuthorizer
} else if (acc.serviceType == Network.Quizlet.ordinal) {
acc.authorizer = quizletAuthorizer
}
}
fun createAccount(network: Network): Account {
return when (network) {
Network.Foursquare -> createFoursquareAccount()
Network.Quizlet -> createQuizletAccount()
Network.None -> throw IllegalArgumentException("Invalid network")
}
}
fun createFoursquareAccount(): Account {
val authorizer = foursquareAuthorizer
val account: Account = SimpleAccount(Network.Foursquare.ordinal)
account.authorizer = authorizer
account.setAuthCredentialStore(accountStore)
return account
}
val foursquareAuthorizer: Authorizer
get() {
val apiKey = "FEGFXJUFANVVDHVSNUAMUKTTXCP1AJQD53E33XKJ44YP1S4I"
val apiSecret = "AYWKUL5SWPNC0CTQ202QXRUG2NLZYXMRA34ZSDW4AUYBG2RC"
val authorizer = OAuthAuthorizerBuilder()
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback(CALLBACK_URL)
.build(Foursquare2Api()) as OAuth20Authorizer
authorizer.setServiceCommandProvider(ServiceTaskProvider())
authorizer.setServiceCommandRunner(ServiceTaskRunner(taskManager, "authorizerId"))
authorizer.webClient = authWebClient
return authorizer
}
fun createQuizletAccount(): Account {
val authorizer = quizletAuthorizer
val account: Account = SimpleAccount(Network.Quizlet.ordinal)
account.authorizer = authorizer
account.setAuthCredentialStore(accountStore)
return account
}
val quizletAuthorizer: Authorizer
get() {
val apiKey = "9zpZ2myVfS"
val apiSecret = "bPHS9xz2sCXWwq5ddcWswG"
val authorizer = OAuthAuthorizerBuilder()
.apiKey(apiKey)
.apiSecret(apiSecret)
.callback(CALLBACK_URL)
.build(QuizletApi2()) as OAuth20Authorizer
authorizer.setServiceCommandProvider(ServiceTaskProvider())
authorizer.setServiceCommandRunner(ServiceTaskRunner(taskManager, "authorizerId"))
authorizer.webClient = authWebClient
return authorizer
}
enum class Network {
None, Foursquare, Quizlet;
}
} | mit | 552556070411b100329cc6c70fabf9d9 | 37.963303 | 94 | 0.691945 | 4.580367 | false | false | false | false |
BjoernPetersen/JMusicBot | src/main/kotlin/net/bjoernpetersen/musicbot/internal/player/ActorPlayer.kt | 1 | 16799 | package net.bjoernpetersen.musicbot.internal.player
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.channels.actor
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import mu.KotlinLogging
import net.bjoernpetersen.musicbot.api.player.DefaultSuggester
import net.bjoernpetersen.musicbot.api.player.ErrorState
import net.bjoernpetersen.musicbot.api.player.PauseState
import net.bjoernpetersen.musicbot.api.player.PlayState
import net.bjoernpetersen.musicbot.api.player.PlayerState
import net.bjoernpetersen.musicbot.api.player.ProgressTracker
import net.bjoernpetersen.musicbot.api.player.QueueEntry
import net.bjoernpetersen.musicbot.api.player.Song
import net.bjoernpetersen.musicbot.api.player.SongEntry
import net.bjoernpetersen.musicbot.api.player.StopState
import net.bjoernpetersen.musicbot.api.player.SuggestedSongEntry
import net.bjoernpetersen.musicbot.spi.loader.ResourceCache
import net.bjoernpetersen.musicbot.spi.player.Player
import net.bjoernpetersen.musicbot.spi.player.PlayerStateListener
import net.bjoernpetersen.musicbot.spi.player.QueueChangeListener
import net.bjoernpetersen.musicbot.spi.player.SongPlayedNotifier
import net.bjoernpetersen.musicbot.spi.player.SongQueue
import net.bjoernpetersen.musicbot.spi.plugin.AbstractPlayback
import net.bjoernpetersen.musicbot.spi.plugin.BrokenSuggesterException
import net.bjoernpetersen.musicbot.spi.plugin.Playback
import net.bjoernpetersen.musicbot.spi.plugin.PlaybackFeedbackChannel
import net.bjoernpetersen.musicbot.spi.plugin.PlaybackState
import net.bjoernpetersen.musicbot.spi.plugin.PluginLookup
import net.bjoernpetersen.musicbot.spi.plugin.Suggester
import java.time.Duration
import javax.inject.Inject
import kotlin.coroutines.CoroutineContext
private sealed class PlayerMessage
private sealed class FeedbackPlayerMessage<T>(val response: CompletableDeferred<T>) :
PlayerMessage()
private class Start(response: CompletableDeferred<Unit>) : FeedbackPlayerMessage<Unit>(response)
private data class StateChange(
val oldState: PlayerState,
val feedback: PlaybackState
) : PlayerMessage()
private data class AddListener(val listener: PlayerStateListener) : PlayerMessage()
private data class RemoveListener(val listener: PlayerStateListener) : PlayerMessage()
private class Play(response: CompletableDeferred<Unit>) : FeedbackPlayerMessage<Unit>(response)
private class Pause(response: CompletableDeferred<Unit>) : FeedbackPlayerMessage<Unit>(response)
private class Stop(response: CompletableDeferred<Unit>) : FeedbackPlayerMessage<Unit>(response)
private class Next(
val oldState: PlayerState,
response: CompletableDeferred<Unit>
) : FeedbackPlayerMessage<Unit>(response)
private class Await(response: CompletableDeferred<Unit>) : FeedbackPlayerMessage<Unit>(response)
/**
* A playback implementation that doesn't actually do anything. The only way it ever ends is if
* [close] is called.
*/
private class CompletablePlayback : AbstractPlayback() {
override suspend fun play() = Unit
override suspend fun pause() = Unit
}
/**
* A player implementation that performs no synchronization at all, so it is not thread safe.
*
* This player should be used by a "synchronizing" player like [ActorPlayer].
*/
private class SyncPlayer @Inject private constructor(
private val queue: SongQueue,
defaultSuggester: DefaultSuggester,
private val resourceCache: ResourceCache,
private val pluginLookup: PluginLookup,
private val songPlayedNotifier: SongPlayedNotifier,
override val playbackFeedbackChannel: ActorPlaybackFeedbackChannel
) : Player {
private val logger = KotlinLogging.logger {}
private val stateListeners: MutableSet<PlayerStateListener> = HashSet()
/**
* The current state of this player. This might be play, pause, stop or error.
*/
override var state: PlayerState = StopState
private set(value) {
val old = field
field = value
logger.debug { "Now playing ${value.entry}" }
for (listener in stateListeners) {
listener(old, value)
}
}
private var playback: Playback = CompletablePlayback()
private val suggester: Suggester? = defaultSuggester.suggester
suspend fun applyStateFeedback(feedback: PlaybackState) {
val oldState = state
when (feedback) {
PlaybackState.PLAY -> if (oldState is PauseState) {
logger.debug { "Changed to PLAY by Playback request" }
state = oldState.play()
}
PlaybackState.PAUSE -> if (oldState is PlayState) {
logger.debug { "Changed to PAUSE by Playback request" }
state = oldState.pause()
}
PlaybackState.BROKEN -> if (state !is ErrorState) {
logger.error { "Playback broke: ${playback::class.qualifiedName}" }
state = ErrorState
}
}
}
suspend fun awaitCurrentPlayback() {
logger.debug { "Awaiting playback $playback" }
playback.waitForFinish()
}
override fun start() {
// This player isn't active in any way.
}
override fun addListener(listener: PlayerStateListener) {
stateListeners.add(listener)
}
override fun removeListener(listener: PlayerStateListener) {
stateListeners.remove(listener)
}
override suspend fun play() {
logger.debug("Playing...")
when (val oldState = state) {
is PlayState -> logger.debug { "Already playing." }
!is PauseState -> {
logger.debug { "Calling next because of play call in state ${oldState.name}" }
next()
}
else -> {
playback.play()
state = oldState.play()
}
}
}
override suspend fun pause() {
logger.debug("Pausing...")
when (val oldState = state) {
is PauseState -> logger.debug { "Already paused." }
!is PlayState -> logger.info { "Tried to pause player in state $oldState" }
else -> {
playback.pause()
state = oldState.pause()
}
}
}
@Suppress("ReturnCount")
override suspend fun next() {
logger.debug("Next...")
@Suppress("TooGenericExceptionCaught")
try {
logger.debug { "Closing playback $playback" }
playback.close()
} catch (e: Exception) {
logger.warn(e) { "Error closing playback" }
}
val nextQueueEntry = queue.pop()
if (nextQueueEntry == null && suggester == null) {
if (state !is StopState) logger.info("Queue is empty. Stopping.")
playback = CompletablePlayback()
state = StopState
return
}
val nextEntry: SongEntry = nextQueueEntry ?: try {
SuggestedSongEntry(suggester!!.suggestNext())
} catch (e: BrokenSuggesterException) {
logger.warn("Default suggester could not suggest anything. Stopping.")
playback = CompletablePlayback()
state = ErrorState
return
}
val nextSong = nextEntry.song
songPlayedNotifier.notifyPlayed(nextEntry)
logger.debug { "Next song is: $nextSong" }
@Suppress("TooGenericExceptionCaught")
try {
val resource = resourceCache.get(nextSong)
val provider = pluginLookup
.lookup(nextSong.provider)
?: throw IllegalArgumentException("No such provider: ${nextSong.provider}")
playback = provider.supplyPlayback(nextSong, resource)
} catch (e: Throwable) {
logger.warn(e) { "Error creating playback" }
playback = CompletablePlayback()
state = ErrorState
return
}
playback.setFeedbackChannel(playbackFeedbackChannel)
state = PauseState(nextEntry)
play()
}
@Suppress("TooGenericExceptionCaught")
override suspend fun close() {
try {
playback.close()
} catch (e: Exception) {
logger.error(e) { "Could not close playback" }
}
playback = CompletablePlayback()
state = ErrorState
}
}
@Suppress("EXPERIMENTAL_API_USAGE")
internal class ActorPlayer @Inject private constructor(
private val syncPlayer: SyncPlayer,
private val queue: SongQueue,
defaultSuggester: DefaultSuggester,
private val resourceCache: ResourceCache,
progressTracker: ProgressTracker
) : Player, CoroutineScope {
private val logger = KotlinLogging.logger {}
private val job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Default + job
override val playbackFeedbackChannel: PlaybackFeedbackChannel
get() = syncPlayer.playbackFeedbackChannel
private val suggester: Suggester? = defaultSuggester.suggester
override val state: PlayerState
get() = syncPlayer.state
private val actor = actor<PlayerMessage> {
for (msg in channel) {
@Suppress("TooGenericExceptionCaught")
try {
when (msg) {
is Start -> {
syncPlayer.play()
msg.response.complete(Unit)
}
is AddListener -> syncPlayer.addListener(msg.listener)
is RemoveListener -> syncPlayer.removeListener(msg.listener)
is Play -> {
syncPlayer.play()
msg.response.complete(Unit)
}
is Pause -> {
syncPlayer.pause()
msg.response.complete(Unit)
}
is Next -> {
if (syncPlayer.state !== msg.oldState) {
logger.debug { "Skipping next call due to state change" }
} else {
syncPlayer.next()
}
msg.response.complete(Unit)
}
is Stop -> {
syncPlayer.close()
msg.response.complete(Unit)
}
is StateChange -> {
if (syncPlayer.state !== msg.oldState) {
logger.debug { "Ignoring playback state due to state change" }
} else {
syncPlayer.applyStateFeedback(msg.feedback)
}
}
is Await -> {
launch {
syncPlayer.awaitCurrentPlayback()
msg.response.complete(Unit)
}
}
}
} catch (e: Throwable) {
if (msg is FeedbackPlayerMessage<*>) {
msg.response.completeExceptionally(e)
}
// TODO remove
logger.warn(e) { "May be cancellation in ActorPlayer actor loop" }
if (e is CancellationException) {
throw e
}
logger.error(e) { "Error in ActorPlayer actor loop" }
}
}
}
init {
syncPlayer.playbackFeedbackChannel.onStateChange = { feedback ->
logger.trace { "Playback state update: $feedback" }
try {
launch { actor.send(StateChange(state, feedback)) }
} catch (e: CancellationException) {
logger.warn(e) { "Could not send playback feedback to actor" }
}
}
addListener { old, new ->
launch {
if (!old.hasSong() && new.hasSong()) {
progressTracker.startSong()
}
if (new.hasSong() && new.entry?.song != old.entry?.song) {
progressTracker.reset()
progressTracker.startSong()
}
when (new) {
is PauseState -> progressTracker.startPause()
is PlayState -> progressTracker.stopPause()
ErrorState, StopState -> progressTracker.reset()
}
}
}
queue.addListener(object : QueueChangeListener {
override fun onAdd(entry: QueueEntry) {
launch { resourceCache.get(entry.song) }
if (state is StopState) launch { next() }
}
override fun onRemove(entry: QueueEntry) = Unit
override fun onMove(entry: QueueEntry, fromIndex: Int, toIndex: Int) = Unit
})
if (suggester != null) {
addListener { _, _ -> preloadSuggestion(suggester) }
}
}
override fun start() {
launch {
val response = CompletableDeferred<Unit>()
actor.send(Start(response))
response.await()
autoPlay()
}
}
private fun preloadSuggestion(suggester: Suggester) {
launch {
if (queue.isEmpty) {
val suggestions: List<Song> = try {
suggester.getNextSuggestions(1)
} catch (e: BrokenSuggesterException) {
logger.warn(e) { "Default suggester could not suggest anything to preload" }
return@launch
}
resourceCache.get(suggestions[0])
}
}
}
override fun addListener(listener: PlayerStateListener) {
launch {
actor.send(AddListener(listener))
}
}
override fun removeListener(listener: PlayerStateListener) {
launch {
actor.send(RemoveListener(listener))
}
}
override suspend fun play() {
withContext(coroutineContext) {
val result = CompletableDeferred<Unit>()
actor.send(Play(result))
result.await()
}
}
override suspend fun pause() {
withContext(coroutineContext) {
val result = CompletableDeferred<Unit>()
actor.send(Pause(result))
result.await()
}
}
override suspend fun next() {
val oldState = state
withContext(coroutineContext) {
val result = CompletableDeferred<Unit>()
actor.send(Next(oldState, result))
result.await()
}
}
private suspend fun autoPlay() {
withContext(coroutineContext) {
while (!actor.isClosedForSend) {
val previousState = state
logger.debug("Waiting for song to finish")
val await = CompletableDeferred<Unit>()
actor.send(Await(await))
await.await()
logger.trace("Waiting done")
if (actor.isClosedForSend) continue
// Prevent auto next calls if next was manually called or an error occurred
when {
state !== previousState ->
logger.debug("Skipping auto call to next() due to state change")
state is ErrorState ->
logger.debug("Skipping auto call to next() because player is in $state")
else -> {
logger.debug("Auto call to next()")
next()
}
}
}
}
}
override suspend fun close() {
withContext(coroutineContext) {
job.complete()
val result = CompletableDeferred<Unit>()
actor.send(Stop(result))
actor.close()
result.await()
}
job.cancel()
}
}
private class ActorPlaybackFeedbackChannel @Inject private constructor(
private val progressTracker: ProgressTracker
) : PlaybackFeedbackChannel {
var onStateChange: ((PlaybackState) -> Unit)? = null
set(value) {
if (field != null) throw IllegalStateException("Already initialized")
else field = value
}
override fun updateState(state: PlaybackState) {
onStateChange?.let { it(state) }
}
override fun updateProgress(progress: Duration) {
runBlocking {
progressTracker.updateProgress(progress)
}
}
}
| mit | aac3922cc6190c00e1f8d334f1a6b850 | 34.144351 | 96 | 0.590809 | 5.196103 | false | false | false | false |
SeunAdelekan/Kanary | examples/Kanary-Mini-Twitter-Clone/src/curious/cwitter/app.kt | 1 | 1917 | package curious.cwitter
import com.iyanuadelekan.kanary.app.KanaryApp
import com.iyanuadelekan.kanary.core.KanaryRouter
import com.iyanuadelekan.kanary.handlers.AppHandler
import com.iyanuadelekan.kanary.server.Server
import javax.servlet.http.HttpServletRequest
val requestLogger: (HttpServletRequest?) -> Unit = {
if(it != null && it.method != null && it.pathInfo != null) {
println("Started ${it.scheme} ${it.method} request to: '${it.pathInfo}'")
}
}
fun main(args: Array<String>) {
val app = KanaryApp()
val server = Server()
val cweetRouter = KanaryRouter()
val authController = AuthController()
val timelineController = TimelineController()
cweetRouter on "auth/" use authController
cweetRouter.post("signin/", authController::userSignIn)
cweetRouter.post("signup/", authController::userSignUp)
cweetRouter.post("signout/", authController::userSignOut)
// Preflight *mdfkr, this will be refactored later
cweetRouter.options("signin/", authController::opt)
cweetRouter.options("signout/", authController::opt)
cweetRouter.options("signup/", authController::opt)
cweetRouter on "cweet/" use timelineController
cweetRouter.post("new/", timelineController::createCweet)
cweetRouter.post("profile/", timelineController::fetchUserFeed)
cweetRouter.get("timeline/", timelineController::fetchFeed)
// Preflight *mdfkr
cweetRouter.options("new/", timelineController::opt)
cweetRouter.options("profile/", timelineController::opt)
// So, the options routes are basically there to respond to Preflight requests
// which happens when you're making a cross domain XMLHTTPRequest
app.mount(cweetRouter)
app.use(requestLogger)
server.handler = AppHandler(app)
//server.listen(Integer.valueOf(System.getenv("PORT"))) // for Heroku deployment
server.listen(8080) // for local development
} | apache-2.0 | 09a9163bb8fbb7222afc8b6fff831086 | 33.872727 | 84 | 0.730308 | 4.002088 | false | false | false | false |
wxdao/Barcode-Pusher | app/src/main/java/wxdao/barcodepusher/MainActivity.kt | 1 | 20777 | package wxdao.barcodepusher
import android.Manifest
import android.app.ProgressDialog
import android.content.*
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Environment
import android.os.Handler
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AlertDialog
import android.support.v7.app.AppCompatActivity
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.text.method.ScrollingMovementMethod
import android.util.DisplayMetrics
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.*
import com.google.gson.Gson
import com.google.zxing.*
import com.google.zxing.common.HybridBinarizer
import com.google.zxing.integration.android.IntentIntegrator
import okhttp3.*
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileOutputStream
import java.util.*
class MainActivity : AppCompatActivity() {
var remoteEdit: EditText? = null
var sharedPref: SharedPreferences? = null
var listView: ListView? = null
var gson: Gson? = null
var clipboard: ClipboardManager? = null
val FILE_CHOOSE_REQUEST_CODE = 0xf001
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val metrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(metrics);
clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
gson = Gson()
sharedPref = getPreferences(Context.MODE_PRIVATE)
listView = findViewById(R.id.listView) as ListView
remoteEdit = findViewById(R.id.remoteEdit) as EditText
remoteEdit?.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable) {
val editor = sharedPref!!.edit()
editor.putString("remote", s.toString())
editor.commit()
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
(findViewById(R.id.button) as Button).setOnClickListener {
view ->
val integrator = IntentIntegrator(this)
integrator.captureActivity = PortraitCaptureActivity::class.java
integrator.initiateScan()
}
(findViewById(R.id.fromFile) as Button).setOnClickListener {
view ->
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
intent.addCategory(Intent.CATEGORY_OPENABLE)
intent.type = "image/*"
startActivityForResult(intent, FILE_CHOOSE_REQUEST_CODE)
}
(findViewById(R.id.manual) as Button).setOnClickListener {
view ->
val input = EditText(this)
input.inputType = (InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE)
val dialogBuilder = AlertDialog.Builder(this).setTitle("Manual Input")
dialogBuilder.setCancelable(false)
dialogBuilder.setView(input)
dialogBuilder.setPositiveButton("OK", { dialogInterface: DialogInterface, i: Int ->
pushData(remoteEdit!!.text.toString(), input.text.toString(), (findViewById(R.id.checkBox) as CheckBox).isChecked)
dialogInterface.dismiss()
})
dialogBuilder.setNegativeButton("Cancel", { dialogInterface: DialogInterface, i: Int ->
dialogInterface.dismiss()
})
dialogBuilder.create().show()
}
(findViewById(R.id.textView3) as TextView).setOnClickListener {
view ->
AlertDialog.Builder(this).setPositiveButton("Yes", { dialogInterface: DialogInterface, i: Int ->
val editor = sharedPref!!.edit()
editor.putString("history", "")
editor.commit()
updateHistory()
}).setNegativeButton("No", null).setMessage("Clear history?").setTitle("Confirm").show()
}
listView?.setOnItemClickListener { adapterView: AdapterView<*>, view1: View, i: Int, l: Long ->
clipboard?.primaryClip = ClipData.newPlainText("Captured content", (view1.findViewById(R.id.item_contentTextView) as TextView).text.toString())
Toast.makeText(this, "Copied to Clipboard", Toast.LENGTH_SHORT).show()
}
listView?.setOnItemLongClickListener { adapterView, view, i, l ->
AlertDialog.Builder(this).setTitle("Actions").setItems(arrayOf("Push / Re-push", "Delete", "Share")) { dialog, which ->
when (which) {
0 -> {
pushData(remoteEdit!!.text.toString(), (view.findViewById(R.id.item_contentTextView) as TextView).text.toString(), true)
}
1 -> {
deleteData((view.findViewById(R.id.item_uuidTextView) as TextView).text.toString(), remoteEdit!!.text.toString(), (findViewById(R.id.checkBox) as CheckBox).isChecked)
}
2 -> {
val shareView = layoutInflater.inflate(R.layout.share_layout, null)
val imageView = shareView.findViewById(R.id.shareImageView) as ImageView
val textView = shareView.findViewById(R.id.shareContentDisplayTextView) as TextView
val spinnerView = shareView.findViewById(R.id.shareCodeTypeSpinner) as Spinner
textView.movementMethod = ScrollingMovementMethod.getInstance()
val content = (view.findViewById(R.id.item_contentTextView) as TextView).text.toString()
textView.text = content
imageView.contentDescription = content
imageView.isLongClickable = true
imageView.setOnLongClickListener { view ->
try {
verifyStoragePermissions()
val bitmap = (imageView.drawable as BitmapDrawable).bitmap
val root = File(Environment.getExternalStorageDirectory(), "barcode_share")
root.mkdirs()
val file = File(root, (System.currentTimeMillis()).toString() + ".png")
val stream = FileOutputStream(file)
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
stream.flush()
stream.close()
Toast.makeText(this@MainActivity, "Image saved to " + file.absolutePath, Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Toast.makeText(this@MainActivity, "ERROR", Toast.LENGTH_SHORT).show()
Log.e("", "", e)
}
true
}
imageView.setOnClickListener { view ->
val intent = Intent(this@MainActivity, LargeImageActivity::class.java)
val bitmap = (imageView.drawable as BitmapDrawable).bitmap
val stream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)
stream.flush()
intent.putExtra("image", stream.toByteArray())
stream.close()
startActivity(intent)
}
val codeTypes = listOf("QR Code", "Aztec", "Data Matrix", "PDF 417", "Code 128")
val adapter = ArrayAdapter<String>(this@MainActivity, android.R.layout.simple_spinner_item, codeTypes)
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
spinnerView.adapter = adapter
spinnerView.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
spinnerView.setSelection(0, true)
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
try {
val writer = MultiFormatWriter()
var width = Math.min(metrics.heightPixels, metrics.widthPixels) * 7 / 8
var height = Math.min(metrics.heightPixels, metrics.widthPixels) * 7 / 8
val result = writer.encode(content,
when (position) {
0 -> {
BarcodeFormat.QR_CODE
}
1 -> {
BarcodeFormat.AZTEC
}
2 -> {
BarcodeFormat.DATA_MATRIX
}
3 -> {
BarcodeFormat.PDF_417
}
4 -> {
height = width * 2 / 6
BarcodeFormat.CODE_128
}
else -> {
BarcodeFormat.QR_CODE
}
}, width, height)
val w = result.width
val h = result.height
val pixels = IntArray(w * h)
for (y in 0..(h - 1)) {
val offset = y * w
for (x in 0..(w - 1)) {
pixels[offset + x] = if (result.get(x, y)) Color.BLACK else Color.WHITE
}
}
val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
bitmap.setPixels(pixels, 0, w, 0, 0, w, h)
val dstBitmap =
if ((position == 2 || position == 3) && w != h) {
Bitmap.createScaledBitmap(bitmap, width, (width.toFloat() * (h.toFloat() / w.toFloat())).toInt(), false)
} else {
Bitmap.createScaledBitmap(bitmap, width, height, false)
}
imageView.setImageBitmap(dstBitmap)
} catch (e: Exception) {
Toast.makeText(this@MainActivity, "ERROR", Toast.LENGTH_SHORT).show()
Log.e("", "", e)
}
}
}
AlertDialog.Builder(this@MainActivity).setView(shareView).setTitle("Share").show()
spinnerView.setSelection(0, true)
}
}
}.show()
true
}
}
override fun onResume() {
super.onResume()
remoteEdit!!.setText(sharedPref!!.getString("remote", ""))
remoteEdit!!.setSelection(remoteEdit!!.text.length)
updateHistory()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
val intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data)
intentResult?.let {
it.contents?.let {
pushData(remoteEdit!!.text.toString(), it, (findViewById(R.id.checkBox) as CheckBox).isChecked)
}
}
when (requestCode) {
FILE_CHOOSE_REQUEST_CODE -> {
if (resultCode == RESULT_OK) {
val uri = data!!.data
val bmp = BitmapFactory.decodeStream(contentResolver.openInputStream(uri))
val decoder = MultiFormatReader()
val pixels = IntArray(bmp.width * bmp.height)
bmp.getPixels(pixels, 0, bmp.width, 0, 0, bmp.width, bmp.height);
try {
val result = decoder.decodeWithState(BinaryBitmap(HybridBinarizer(RGBLuminanceSource(bmp.width, bmp.height, pixels))))
val text = result.text
pushData(remoteEdit!!.text.toString(), text, (findViewById(R.id.checkBox) as CheckBox).isChecked)
} catch (e: Exception) {
AlertDialog.Builder(this).setMessage("Content not found").show()
}
}
}
}
super.onActivityResult(requestCode, resultCode, data)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menu.add(0, 0, 0, "Additional Info")
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == 0 && item.groupId == 0) {
val input = EditText(this)
input.inputType = (InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE)
input.setText(sharedPref!!.getString("additional", ""))
input.setSelection(input.text.length)
val dialogBuilder = AlertDialog.Builder(this).setTitle("Additional Information")
dialogBuilder.setCancelable(false)
dialogBuilder.setView(input)
dialogBuilder.setPositiveButton("OK", { dialogInterface: DialogInterface, i: Int ->
val editor = sharedPref!!.edit()
editor.putString("additional", input.text.toString())
editor.commit()
dialogInterface.dismiss()
})
dialogBuilder.setNegativeButton("Cancel", { dialogInterface: DialogInterface, i: Int ->
dialogInterface.dismiss()
})
dialogBuilder.create().show()
}
return super.onOptionsItemSelected(item)
}
@Synchronized
fun pushData(remote: String, content: String, toPush: Boolean) {
val handler = Handler()
val dialog = ProgressDialog(this)
dialog.setTitle("Network")
dialog.setMessage("Pushing")
dialog.setCancelable(true)
val uuid = UUID.randomUUID().toString()
val timestamp = (System.currentTimeMillis() / 1000L).toLong()
if (toPush) {
Thread({
handler.post {
dialog.show()
}
try {
val client = OkHttpClient()
val body = FormBody.Builder()
.add("content", content)
.add("additional", sharedPref!!.getString("additional", ""))
.add("timestamp", timestamp.toString())
.add("uuid", uuid)
.build()
val request = Request.Builder().url(remote).post(body).build()
val response = client.newCall(request).execute()
response.body().close()
handler.post {
pushItem(content, remote + " : " + response.code().toString(), uuid, timestamp)
}
} catch (e: Exception) {
Log.e("", "", e)
handler.post {
pushItem(content, remote + " : ERROR", uuid, timestamp)
}
}
handler.post {
dialog.dismiss()
}
}).start()
} else {
pushItem(content, "Not pushed", uuid, timestamp)
}
}
@Synchronized
fun deleteData(uuid: String, remote: String, toPush: Boolean) {
val handler = Handler()
val deleteLocal = fun() {
val history = gson!!.fromJson(sharedPref!!.getString("history", null), HistoryObject::class.java) ?: HistoryObject()
history.item.removeAll { ho: HistoryItem ->
if (ho.uuid == uuid) {
true
} else {
false
}
}
val editor = sharedPref!!.edit()
editor.putString("history", gson!!.toJson(history))
editor.commit()
updateHistory()
}
val dialog = ProgressDialog(this)
dialog.setTitle("Network")
dialog.setMessage("Pushing")
dialog.setCancelable(true)
if (toPush) {
Thread({
handler.post {
dialog.show()
}
try {
val client = OkHttpClient()
val request = Request.Builder().url(remote).delete(RequestBody.create(MediaType.parse("text/plain"), uuid)).build()
val response = client.newCall(request).execute()
if (response.code() == 200) {
handler.post {
deleteLocal()
}
} else {
handler.post {
AlertDialog.Builder(this).setTitle("Network").setMessage("Rejected by remote").show()
}
}
response.body().close()
} catch (e: Exception) {
Log.e("", "", e)
handler.post {
AlertDialog.Builder(this).setTitle("Network").setMessage("Failed to push").show()
}
}
handler.post {
dialog.dismiss()
}
}).start()
} else {
deleteLocal()
}
}
@Synchronized
fun pushItem(content: String, remoteInfo: String, uuid: String, timestamp: Long) {
val history = gson!!.fromJson(sharedPref!!.getString("history", null), HistoryObject::class.java) ?: HistoryObject()
history.item.add(HistoryItem(remoteInfo, content, uuid, timestamp))
val editor = sharedPref!!.edit()
editor.putString("history", gson!!.toJson(history))
editor.commit()
updateHistory()
}
@Synchronized
fun updateHistory() {
val list = LinkedList<HashMap<String, String>>()
val history = gson!!.fromJson(sharedPref!!.getString("history", null), HistoryObject::class.java)
for (i in (history ?: HistoryObject()).item) {
val map = HashMap<String, String>()
map.put("remote", i.remote)
map.put("content", i.content)
map.put("date", Date(i.timestamp * 1000L).toString())
map.put("uuid", i.uuid)
list.addFirst(map)
}
val adapter = SimpleAdapter(this, list, R.layout.history_list_item, arrayOf("remote", "content", "date", "uuid"), arrayOf(R.id.item_remoteTextView, R.id.item_contentTextView, R.id.item_dateTextView, R.id.item_uuidTextView).toIntArray())
listView?.adapter = adapter
}
fun verifyStoragePermissions() {
val permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
if (permission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE), 1)
}
}
}
| gpl-3.0 | d27564fdbfcf0a3784aad4a856ae011b | 45.689888 | 244 | 0.507917 | 5.595745 | false | false | false | false |
DemonWav/IntelliJBukkitSupport | src/main/kotlin/toml/TomlSchema.kt | 1 | 3344 | /*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.toml
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiFileFactory
import com.intellij.psi.util.PsiTreeUtil
import org.intellij.lang.annotations.Language
import org.toml.lang.psi.TomlArrayTable
import org.toml.lang.psi.TomlElement
import org.toml.lang.psi.TomlFileType
import org.toml.lang.psi.TomlKeyValue
import org.toml.lang.psi.TomlKeyValueOwner
import org.toml.lang.psi.TomlTable
// Modified version of the intellij-rust file
// https://github.com/intellij-rust/intellij-rust/blob/42d0981d45e8830aa5efe82c45688bab8223201c/toml/src/main/kotlin/org/rust/toml/completion/RsTomlKeysCompletionProvider.kt
class TomlSchema private constructor(
val topLevelEntries: Set<TomlSchemaEntry>,
private val tables: List<TomlTableSchema>
) {
fun topLevelKeys(isArray: Boolean): Set<String> =
tables.filter { it.isArray == isArray }.mapTo(mutableSetOf()) { it.name }
fun keysForTable(tableName: String): Set<String> =
tableSchema(tableName)?.entries?.mapTo(mutableSetOf()) { it.key }.orEmpty()
fun tableEntry(tableName: String, key: String): TomlSchemaEntry? =
tableSchema(tableName)?.entries?.find { it.key == key }
fun tableSchema(tableName: String): TomlTableSchema? =
tables.find { it.name == tableName }
companion object {
fun parse(project: Project, @Language("TOML") example: String): TomlSchema {
val toml = PsiFileFactory.getInstance(project)
.createFileFromText("dummy.toml", TomlFileType, example)
val rootKeys = toml.children
.filterIsInstance<TomlKeyValue>()
.mapTo(mutableSetOf()) { it.schemaEntry }
val tables = toml.children
.filterIsInstance<TomlKeyValueOwner>()
.mapNotNull { it.schema }
return TomlSchema(rootKeys, tables)
}
}
}
private val TomlKeyValueOwner.schema: TomlTableSchema?
get() {
val (name, isArray) = when (this) {
is TomlTable -> header.key?.segments?.firstOrNull()?.text to false
is TomlArrayTable -> header.key?.segments?.firstOrNull()?.text to true
else -> return null
}
if (name == null) return null
val keys = entries.mapTo(mutableSetOf()) { it.schemaEntry }
val description = getComments()
return TomlTableSchema(name, isArray, keys, description)
}
private val TomlKeyValue.schemaEntry: TomlSchemaEntry
get() = TomlSchemaEntry(this.key.text, getComments(), value?.tomlType)
private fun TomlElement.getComments(): List<String> {
val comments = mutableListOf<String>()
var sibling = PsiTreeUtil.skipWhitespacesBackward(this)
while (sibling is PsiComment) {
comments += sibling.text.removePrefix("#").trim()
sibling = PsiTreeUtil.skipWhitespacesBackward(sibling)
}
return comments.reversed()
}
data class TomlSchemaEntry(
val key: String,
val description: List<String>,
val type: TomlValueType?
)
class TomlTableSchema(
val name: String,
val isArray: Boolean,
val entries: Set<TomlSchemaEntry>,
val description: List<String>
)
| mit | e4d6c98523bf405253caba7273b80ccc | 32.777778 | 173 | 0.691089 | 4.113161 | false | false | false | false |
agrosner/KBinding | kbinding/src/main/java/com/andrewgrosner/kbinding/BindingHolder.kt | 1 | 12740 | package com.andrewgrosner.kbinding
import android.app.Activity
import android.app.Fragment
import android.view.View
import com.andrewgrosner.kbinding.bindings.Binding
import com.andrewgrosner.kbinding.bindings.InputExpressionBindingConverter
import com.andrewgrosner.kbinding.bindings.NullableInputExpressionBindingConverter
import com.andrewgrosner.kbinding.bindings.ObservableBindingConverter
import com.andrewgrosner.kbinding.bindings.OneWayBinding
import com.andrewgrosner.kbinding.bindings.OneWayToSource
import com.andrewgrosner.kbinding.bindings.PropertyExpressionBindingConverter
import com.andrewgrosner.kbinding.bindings.TwoWayBinding
import com.andrewgrosner.kbinding.bindings.ViewBinder
import com.andrewgrosner.kbinding.bindings.ViewRegister
import com.andrewgrosner.kbinding.bindings.onSelf
import kotlin.reflect.KProperty
/**
* Internal interface class that's used to consolidate the functionality between a [BindingRegister]
* and [BindingHolder].
*/
interface BindingRegister<V> {
/**
* Starts an [Observable] expression that executes when the attached observable changes.
*/
fun <Input> bind(function: (V) -> ObservableField<Input>) = ObservableBindingConverter(function, this)
/**
* Starts a [KProperty] expression that executes when the [BaseObservable] notifies its value changes.
*/
fun <Input> bind(kProperty: KProperty<*>? = null, expression: (V) -> Input) = InputExpressionBindingConverter(expression, kProperty, this)
/**
* Starts a [KProperty] expression that executes when the [BaseObservable] notifies its value changes.
* Uses reflection in the getter of the [KProperty] to retrieve the value of the property.
* Ensure you add kotlin-reflect to classpath to prevent a runtime crash.
*/
fun <Input> bind(kProperty: KProperty<Input>) = InputExpressionBindingConverter({ kProperty.getter.call(it) }, kProperty, this)
/**
* Starts a [KProperty] expression that executes even when the possibility
* of the parent [BaseObservable] in this [BindingRegister] is null. Useful for loading state
* or when expected data is not present yet in the view.
*/
fun <Input> bindNullable(kProperty: KProperty<*>? = null, expression: (V?) -> Input) = NullableInputExpressionBindingConverter(expression, kProperty, this)
/**
* Starts an [Observable] that unwraps the [ObservableField.value] from the function when the value
* changes.
*/
fun <Input> bindSelf(function: (V) -> ObservableField<Input>) = bind(function).onSelf()
/**
* Starts a [KProperty] expression that passes the result of the expression to the final view expression.
*/
fun <Input> bindSelf(kProperty: KProperty<*>, expression: (V) -> Input) = bind(kProperty, expression).onSelf()
/**
* Starts a [KProperty] expression that passes the result of the expression to the final view expression.
* Uses reflection to get the value of the property instead of declaring redundant call.
* Ensure you add kotlin-reflect to classpath to prevent a runtime crash.
*/
fun <Input> bindSelf(kProperty: KProperty<Input>) = bind(kProperty).onSelf()
/**
* Starts a OneWayToSource [View] expression that will evaluate from the [View] onto the next expression.
*/
fun <Output, VW : View> bind(v: VW, viewRegister: ViewRegister<VW, Output>) = ViewBinder(v, viewRegister, this)
/**
* The data registered on the holder. Use this to pass down variables and content that you expect
* to change.
*/
var viewModel: V?
/**
* Non-null safe access expression. Will throw a [KotlinNullPointerException] if null. This is
* assuming the viewmodel exists.
*/
val viewModelSafe: V
get() = viewModel!!
/**
* Returns true if the [viewModel] is bound.
*/
var isBound: Boolean
/**
* Internal helper method to register OneWay binding.
*/
fun registerBinding(oneWayBinding: OneWayBinding<V, *, *, *, *>)
/**
* Internal helper method to unregister OneWay binding.
*/
fun unregisterBinding(oneWayBinding: OneWayBinding<V, *, *, *, *>)
/**
* Internal helper method to register TwoWay binding.
*/
fun registerBinding(twoWayBinding: TwoWayBinding<V, *, *, *, *>)
/**
* Internal helper method to unregister TwoWay binding.
*/
fun unregisterBinding(twoWayBinding: TwoWayBinding<V, *, *, *, *>)
/**
* Internal helper method to register OneWayToSource binding.
*/
fun registerBinding(oneWayToSource: OneWayToSource<V, *, *, *>)
/**
* Internal helper method to unregister OneWayToSource binding.
*/
fun unregisterBinding(oneWayToSource: OneWayToSource<V, *, *, *>)
/**
* Called when a [viewModel] is set. Evaluates all binding expressions as well as binds their changes
* to this [BindingHolder].
*/
fun bindAll()
/**
* Call this to unregister all bindings from this [BindingHolder]. Preferrably in the [Activity.onDestroy]
* or [Fragment.onDestroyView]
*/
fun unbindAll()
/**
* Forces a reevaluation of all bindings
*/
fun notifyChanges()
}
/**
* Represents a set of [Binding]. Provides convenience operations and handles changes from the parent
* [viewModel] if it is an [Observable].
*/
class BindingHolder<V>(viewModel: V? = null) : BindingRegister<V> {
private val observableBindings = mutableListOf<OneWayBinding<V, *, *, *, *>>()
private val genericOneWayBindings = mutableListOf<OneWayBinding<V, *, *, *, *>>()
private val propertyBindings = mutableMapOf<KProperty<*>, MutableList<OneWayBinding<V, *, *, *, *>>>()
private val twoWayBindings = mutableListOf<TwoWayBinding<V, *, *, *, *>>()
private val twoWayPropertyBindings = mutableMapOf<KProperty<*>, TwoWayBinding<V, *, *, *, *>>()
private val sourceBindings = mutableMapOf<View, MutableList<OneWayToSource<V, *, *, *>>>()
val onViewModelChanged = { _: Observable, property: KProperty<*>? -> onFieldChanged(property) }
override var isBound = false
override var viewModel: V? = viewModel
set(value) {
if (field != value) {
// existing field remove property changes
if (field is Observable) {
(field as Observable).removeOnPropertyChangedCallback(onViewModelChanged)
}
field = value
if (isBound) bindAll()
}
}
override fun registerBinding(oneWayBinding: OneWayBinding<V, *, *, *, *>) {
if (oneWayBinding.converter is ObservableBindingConverter) {
observableBindings += oneWayBinding
} else if (oneWayBinding.converter is PropertyExpressionBindingConverter) {
val kProperty = oneWayBinding.converter.property
if (kProperty != null) {
var mutableList = propertyBindings[kProperty]
if (mutableList == null) {
mutableList = mutableListOf()
propertyBindings[kProperty] = mutableList
}
mutableList.add(oneWayBinding)
} else {
// generic observableBindings have no property association
genericOneWayBindings += oneWayBinding
}
}
}
override fun unregisterBinding(oneWayBinding: OneWayBinding<V, *, *, *, *>) {
if (oneWayBinding.converter is ObservableBindingConverter) {
observableBindings -= oneWayBinding
} else if (oneWayBinding.converter is PropertyExpressionBindingConverter) {
val kProperty = oneWayBinding.converter.property
if (kProperty != null) {
propertyBindings[kProperty]?.remove(oneWayBinding)
} else {
genericOneWayBindings -= oneWayBinding
}
}
}
override fun registerBinding(twoWayBinding: TwoWayBinding<V, *, *, *, *>) {
val converter = twoWayBinding.oneWayBinding.converter
if (converter is ObservableBindingConverter) {
if (twoWayBindings.contains(twoWayBinding)) {
throw IllegalStateException("Cannot register more than one two way binding on an Observable field. This could result in a view update cycle.")
}
twoWayBindings += twoWayBinding
} else if (converter is PropertyExpressionBindingConverter) {
val key = converter.property
if (twoWayPropertyBindings.containsKey(key)) {
throw IllegalStateException("Cannot register more than one two way binding to property updates. This could result in a view update cycle.")
}
if (key != null) {
twoWayPropertyBindings[key] = twoWayBinding
} else {
throw IllegalStateException("Cannot register generic two way binding. Specify a property.")
}
}
}
override fun unregisterBinding(twoWayBinding: TwoWayBinding<V, *, *, *, *>) {
val converter = twoWayBinding.oneWayBinding.converter
if (converter is ObservableBindingConverter) {
twoWayBindings -= twoWayBinding
} else if (converter is PropertyExpressionBindingConverter) {
val key = converter.property
if (key != null) {
twoWayPropertyBindings -= key
}
}
}
override fun registerBinding(oneWayToSource: OneWayToSource<V, *, *, *>) {
val view = oneWayToSource.view
var mutableList = sourceBindings[view]
if (mutableList == null) {
mutableList = mutableListOf()
sourceBindings[view] = mutableList
}
mutableList.add(oneWayToSource)
}
override fun unregisterBinding(oneWayToSource: OneWayToSource<V, *, *, *>) {
val view = oneWayToSource.view
sourceBindings[view]?.remove(oneWayToSource)
}
private fun onFieldChanged(property: KProperty<*>?) {
if (property != null) {
propertyBindings[property]?.let { it.forEach { it.notifyValueChange() } }
twoWayPropertyBindings[property]?.notifyValueChange()
} else {
// rebind everything if the parent ViewModel changes.
propertyBindings.forEach { (_, bindings) -> bindings.forEach { it.notifyValueChange() } }
twoWayPropertyBindings.forEach { (_, binding) -> binding.notifyValueChange() }
genericOneWayBindings.forEach { it.notifyValueChange() }
}
}
override fun notifyChanges() {
if (!isBound) {
throw IllegalStateException("Cannot notify changes on an unbound binding holder.")
}
observableBindings.forEach { it.notifyValueChange() }
sourceBindings.values.forEach { bindings -> bindings.forEach { it.notifyValueChange() } }
propertyBindings.values.forEach { bindings -> bindings.forEach { it.notifyValueChange() } }
twoWayBindings.forEach { it.notifyValueChange() }
twoWayPropertyBindings.values.forEach { it.notifyValueChange() }
genericOneWayBindings.forEach { it.notifyValueChange() }
}
override fun bindAll() {
// new field is observable, register now for changes
val viewModel = this.viewModel
if (viewModel is Observable) {
viewModel.addOnPropertyChangedCallback(onViewModelChanged)
}
observableBindings.forEach { it.bind() }
sourceBindings.values.forEach { bindings -> bindings.forEach { it.bind() } }
propertyBindings.values.forEach { bindings -> bindings.forEach { it.bind() } }
twoWayBindings.forEach { it.bind() }
twoWayPropertyBindings.values.forEach { it.bind() }
genericOneWayBindings.forEach { it.bind() }
isBound = true
}
override fun unbindAll() {
val viewModel = viewModel
if (viewModel is Observable) {
viewModel.removeOnPropertyChangedCallback(onViewModelChanged)
}
observableBindings.forEach { it.unbindInternal() }
observableBindings.clear()
sourceBindings.values.forEach { bindings -> bindings.forEach { it.unbindInternal() } }
sourceBindings.clear()
propertyBindings.values.forEach { bindings -> bindings.forEach { it.unbindInternal() } }
propertyBindings.clear()
genericOneWayBindings.forEach { it.unbindInternal() }
genericOneWayBindings.clear()
twoWayBindings.forEach { it.unbindInternal() }
twoWayBindings.clear()
twoWayPropertyBindings.values.forEach { it.unbindInternal() }
twoWayPropertyBindings.clear()
isBound = false
}
} | mit | ad3b497878505dc3673060210e77f678 | 39.31962 | 159 | 0.659262 | 4.780488 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/model/notification/NotificationChannelSpec.kt | 1 | 3797 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.model.notification
import android.app.NotificationManager
import android.support.annotation.StringRes
import de.vanita5.twittnuker.R
enum class NotificationChannelSpec(
val id: String,
@StringRes val nameRes: Int,
@StringRes val descriptionRes: Int = 0,
val importance: Int,
val showBadge: Boolean = false,
val grouped: Boolean = false) {
/**
* For notifications send by app itself.
* Such as "what's new"
*/
appNotices("app_notices", R.string.notification_channel_name_app_notices,
importance = NotificationManager.IMPORTANCE_LOW, showBadge = true),
/**
* For notifications indicate that some lengthy operations are performing in the background.
* Such as sending attachment process.
*/
backgroundProgresses("background_progresses", R.string.notification_channel_name_background_progresses,
importance = NotificationManager.IMPORTANCE_MIN),
/**
* For ongoing notifications indicating service statuses.
* Such as notification showing streaming service running
*/
serviceStatuses("service_statuses", R.string.notification_channel_name_service_statuses,
importance = NotificationManager.IMPORTANCE_MIN),
/**
* For updates related to micro-blogging features.
* Such as new statuses posted by friends.
*/
contentUpdates("content_updates", R.string.notification_channel_name_content_updates,
descriptionRes = R.string.notification_channel_descriptions_content_updates,
importance = NotificationManager.IMPORTANCE_DEFAULT, showBadge = true, grouped = true),
/**
* For updates related to micro-blogging features.
* Such as new statuses posted by friends user subscribed to.
*/
contentSubscriptions("content_subscriptions", R.string.notification_channel_name_content_subscriptions,
descriptionRes = R.string.notification_channel_descriptions_content_subscriptions,
importance = NotificationManager.IMPORTANCE_HIGH, showBadge = true, grouped = true),
/**
* For interactions related to micro-blogging features.
* Such as replies and likes.
*/
contentInteractions("content_interactions", R.string.notification_channel_name_content_interactions,
descriptionRes = R.string.notification_channel_description_content_interactions,
importance = NotificationManager.IMPORTANCE_HIGH, showBadge = true, grouped = true),
/**
* For messages related to micro-blogging features.
* Such as direct messages.
*/
contentMessages("content_messages", R.string.notification_channel_name_content_messages,
descriptionRes = R.string.notification_channel_description_content_messages,
importance = NotificationManager.IMPORTANCE_HIGH, showBadge = true, grouped = true)
} | gpl-3.0 | 17cad3c1e5815e34060a8a0f69e508a3 | 43.162791 | 107 | 0.716618 | 4.653186 | false | false | false | false |
stripe/stripe-android | stripe-core/src/main/java/com/stripe/android/core/browser/BrowserCapabilitiesSupplier.kt | 1 | 1588 | package com.stripe.android.core.browser
import android.content.ComponentName
import android.content.Context
import androidx.annotation.RestrictTo
import androidx.browser.customtabs.CustomTabsClient
import androidx.browser.customtabs.CustomTabsServiceConnection
/**
* Supply the device's [BrowserCapabilities].
*
* See https://developer.chrome.com/docs/android/custom-tabs/integration-guide/ for more details
* on Custom Tabs.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
class BrowserCapabilitiesSupplier(
private val context: Context
) {
fun get(): BrowserCapabilities {
return when {
isCustomTabsSupported() -> BrowserCapabilities.CustomTabs
else -> BrowserCapabilities.Unknown
}
}
private fun isCustomTabsSupported(): Boolean {
return runCatching {
CustomTabsClient.bindCustomTabsService(
context,
CHROME_PACKAGE,
NoopCustomTabsServiceConnection()
)
}.getOrDefault(false)
}
private class NoopCustomTabsServiceConnection : CustomTabsServiceConnection() {
override fun onCustomTabsServiceConnected(
componentName: ComponentName,
customTabsClient: CustomTabsClient
) = Unit
override fun onServiceDisconnected(name: ComponentName) = Unit
}
private companion object {
/**
* Stable = com.android.chrome
* Beta = com.chrome.beta
* Dev = com.chrome.dev
*/
private const val CHROME_PACKAGE = "com.android.chrome"
}
}
| mit | 6dbc8bd34a530a34b1c11406427c9387 | 28.962264 | 96 | 0.673174 | 5.122581 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/refactoring/inlineValue/RsInlineValueProcessor.kt | 2 | 3956 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.refactoring.inlineValue
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiReference
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.search.searches.ReferencesSearch
import com.intellij.refactoring.BaseRefactoringProcessor
import com.intellij.usageView.UsageInfo
import com.intellij.usageView.UsageViewDescriptor
import org.rust.ide.refactoring.RsInlineUsageViewDescriptor
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.isShorthand
import org.rust.lang.core.resolve.ref.RsReference
import org.rust.stdext.capitalized
class RsInlineValueProcessor(
private val project: Project,
private val context: InlineValueContext,
private val mode: InlineValueMode
) : BaseRefactoringProcessor(project) {
override fun findUsages(): Array<UsageInfo> {
if (mode is InlineValueMode.InlineThisOnly && context.reference != null) {
return arrayOf(UsageInfo(context.reference))
}
val projectScope = GlobalSearchScope.projectScope(project)
val usages = mutableListOf<PsiReference>()
usages.addAll(ReferencesSearch.search(context.element, projectScope).findAll())
return usages.map(::UsageInfo).toTypedArray()
}
override fun performRefactoring(usages: Array<out UsageInfo>) {
val factory = RsPsiFactory(project)
usages.asIterable().forEach loop@{
val reference = it.reference as? RsReference ?: return@loop
when (val element = reference.element) {
is RsStructLiteralField -> {
if (element.isShorthand) {
element.addAfter(factory.createColon(), element.referenceNameElement)
}
if (element.expr == null) {
element.addAfter(context.expr, element.colon)
}
}
is RsPath -> when (val parent = element.parent) {
is RsPathExpr -> parent.replaceWithAddingParentheses(context.expr, factory)
else -> Unit // Can't replace RsPath to RsExpr
}
else -> element.replaceWithAddingParentheses(context.expr, factory)
}
}
if (mode is InlineValueMode.InlineAllAndRemoveOriginal) {
context.delete()
}
}
override fun getCommandName(): String = "Inline ${context.type} ${context.name}"
override fun createUsageViewDescriptor(usages: Array<out UsageInfo>): UsageViewDescriptor {
return RsInlineUsageViewDescriptor(context.element, "${context.type.capitalized()} to inline")
}
}
/** Replaces [this] either with `expr` or `(expr)`, depending on context */
fun RsElement.replaceWithAddingParentheses(expr: RsElement, factory: RsPsiFactory): PsiElement {
val parent = parent
val needsParentheses = when {
expr is RsBinaryExpr && (parent is RsBinaryExpr || parent.requiresSingleExpr) -> true
expr.isBlockLikeExpr && parent.requiresSingleExpr -> true
expr is RsStructLiteral && (parent is RsMatchExpr || parent is RsForExpr || parent is RsCondition || parent is RsLetExpr) -> true
else -> false
}
val newExpr = if (needsParentheses) {
factory.createExpression("(${expr.text})")
} else {
expr
}
return replace(newExpr)
}
private val PsiElement.isBlockLikeExpr: Boolean
get() =
this is RsRangeExpr || this is RsLambdaExpr ||
this is RsMatchExpr || this is RsBlockExpr ||
this is RsLoopExpr || this is RsWhileExpr
private val PsiElement.requiresSingleExpr: Boolean
get() = this is RsDotExpr || this is RsTryExpr || this is RsUnaryExpr || this is RsCastExpr || this is RsCallExpr
| mit | 370318208f6257563239af399aabdcbf | 40.208333 | 137 | 0.677705 | 4.800971 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewmodels/MainActivityViewModel.kt | 1 | 6615 | package com.habitrpg.android.habitica.ui.viewmodels
import android.content.SharedPreferences
import androidx.core.content.edit
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.api.HostConfig
import com.habitrpg.android.habitica.api.MaintenanceApiService
import com.habitrpg.android.habitica.components.UserComponent
import com.habitrpg.android.habitica.data.ContentRepository
import com.habitrpg.android.habitica.data.InventoryRepository
import com.habitrpg.android.habitica.data.TaskRepository
import com.habitrpg.android.habitica.helpers.AmplitudeManager
import com.habitrpg.android.habitica.helpers.RxErrorHandler
import com.habitrpg.android.habitica.helpers.TaskAlarmManager
import com.habitrpg.android.habitica.helpers.notifications.PushNotificationManager
import com.habitrpg.android.habitica.models.TutorialStep
import com.habitrpg.android.habitica.models.inventory.Egg
import com.habitrpg.android.habitica.models.responses.MaintenanceResponse
import com.habitrpg.android.habitica.proxy.AnalyticsManager
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.schedulers.Schedulers
import io.realm.kotlin.isValid
import java.util.Date
import javax.inject.Inject
class MainActivityViewModel : BaseViewModel() {
@Inject
internal lateinit var hostConfig: HostConfig
@Inject
internal lateinit var pushNotificationManager: PushNotificationManager
@Inject
internal lateinit var sharedPreferences: SharedPreferences
@Inject
internal lateinit var contentRepository: ContentRepository
@Inject
internal lateinit var taskRepository: TaskRepository
@Inject
internal lateinit var inventoryRepository: InventoryRepository
@Inject
internal lateinit var taskAlarmManager: TaskAlarmManager
@Inject
internal lateinit var analyticsManager: AnalyticsManager
@Inject
internal lateinit var maintenanceService: MaintenanceApiService
override fun inject(component: UserComponent) {
component.inject(this)
}
val isAuthenticated: Boolean
get() = hostConfig.apiKey.isNotBlank() && hostConfig.userID.isNotBlank()
val launchScreen: String?
get() = sharedPreferences.getString("launch_screen", "")
var preferenceLanguage: String?
get() = sharedPreferences.getString("language", "en")
set(value) {
sharedPreferences.edit {
putString("language", value)
}
}
override fun onCleared() {
taskRepository.close()
inventoryRepository.close()
contentRepository.close()
super.onCleared()
}
fun onCreate() {
try {
taskAlarmManager.scheduleAllSavedAlarms(sharedPreferences.getBoolean("preventDailyReminder", false))
} catch (e: Exception) {
analyticsManager.logException(e)
}
}
fun onResume() {
// Track when the app was last opened, so that we can use this to send out special reminders after a week of inactivity
sharedPreferences.edit {
putLong("lastAppLaunch", Date().time)
putBoolean("preventDailyReminder", false)
}
}
fun retrieveUser(forced: Boolean = false) {
if (hostConfig.hasAuthentication()) {
disposable.add(
contentRepository.retrieveWorldState()
.flatMap { userRepository.retrieveUser(true, forced) }
.doOnNext { user1 ->
analyticsManager.setUserProperty("has_party", if (user1.party?.id?.isNotEmpty() == true) "true" else "false")
analyticsManager.setUserProperty("is_subscribed", if (user1.isSubscribed) "true" else "false")
analyticsManager.setUserProperty("checkin_count", user1.loginIncentives.toString())
analyticsManager.setUserProperty("level", user1.stats?.lvl?.toString() ?: "")
pushNotificationManager.setUser(user1)
pushNotificationManager.addPushDeviceUsingStoredToken()
}
.flatMap { userRepository.retrieveTeamPlans() }
.flatMap { contentRepository.retrieveContent() }
.subscribe({ }, RxErrorHandler.handleEmptyError())
)
}
}
fun logTutorialStatus(step: TutorialStep, complete: Boolean) {
val additionalData = HashMap<String, Any>()
additionalData["eventLabel"] = step.identifier + "-android"
additionalData["eventValue"] = step.identifier ?: ""
additionalData["complete"] = complete
AmplitudeManager.sendEvent(
"tutorial",
AmplitudeManager.EVENT_CATEGORY_BEHAVIOUR,
AmplitudeManager.EVENT_HITTYPE_EVENT,
additionalData
)
}
fun ifNeedsMaintenance(onResult: ((MaintenanceResponse) -> Unit)) {
disposable.add(
this.maintenanceService.maintenanceStatus
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ maintenanceResponse ->
if (maintenanceResponse == null) {
return@subscribe
}
onResult(maintenanceResponse)
},
RxErrorHandler.handleEmptyError()
)
)
}
fun getToolbarTitle(id: Int, label: CharSequence?, eggType: String?, onSuccess: ((CharSequence?) -> Unit)) {
if (id == R.id.petDetailRecyclerFragment || id == R.id.mountDetailRecyclerFragment) {
disposable.add(
inventoryRepository.getItem("egg", eggType ?: "").firstElement().subscribe(
{
if (!it.isValid()) return@subscribe
onSuccess(
if (id == R.id.petDetailRecyclerFragment) {
(it as? Egg)?.text
} else {
(it as? Egg)?.mountText
}
)
},
RxErrorHandler.handleEmptyError()
)
)
} else {
onSuccess(
if (id == R.id.promoInfoFragment) {
""
} else if (label.isNullOrEmpty() && user.value?.isValid == true) {
user.value?.profile?.name
} else label ?: ""
)
}
}
}
| gpl-3.0 | 65ae58616bc16b3fc392266a9bd3afe7 | 39.833333 | 133 | 0.621013 | 5.485075 | false | false | false | false |
OpenConference/DroidconBerlin2017 | app/src/main/java/de/droidcon/berlin2018/analytics/FirebaseAnalytics.kt | 1 | 2703 | package de.droidcon.berlin2018.analytics
import android.content.Context
import android.os.Bundle
import com.bluelinelabs.conductor.Controller
import com.google.firebase.analytics.FirebaseAnalytics
/**
*
*
* @author Hannes Dorfmann
*/
class FirebaseAnalytics(context: Context) : Analytics {
private val firebase = FirebaseAnalytics.getInstance(context);
override fun trackLoadSessionDetails(id: String) {
val bundle = Bundle()
bundle.putString("SessionId", id)
firebase.logEvent("LoadSessionDetails", bundle)
}
override fun trackLoadSpeakerDetails(id: String) {
val bundle = Bundle()
bundle.putString("SpeakerId", id)
firebase.logEvent("LoadSpeakerDetails", bundle)
}
override fun trackScreen(controller: Controller) {
firebase.setCurrentScreen(controller.activity!!, controller::class.java.simpleName, null)
}
override fun trackSearch(query: String) {
val bundle = Bundle()
bundle.putString(FirebaseAnalytics.Param.SEARCH_TERM, query)
firebase.logEvent(FirebaseAnalytics.Event.SEARCH, bundle)
}
override fun trackSessionMarkedAsFavorite(sessionId: String) {
val bundle = Bundle()
bundle.putString("SessionId", sessionId)
firebase.logEvent("MarkSessionAsFavorite", bundle)
}
override fun trackSessionRemovedFromFavorite(sessionId: String) {
val bundle = Bundle()
bundle.putString("SessionId", sessionId)
firebase.logEvent("RemoveSessionFromFavorite", bundle)
}
override fun trackInstallUpdateDismissed() {
val bundle = Bundle()
firebase.logEvent("InstallUpdateDismissed", bundle)
}
override fun trackInstallUpdateClicked() {
val bundle = Bundle()
firebase.logEvent("InstallUpdate", bundle)
}
override fun trackTwitterRefresh() {
val bundle = Bundle()
firebase.logEvent("TwitterPullToRefresh", bundle)
}
override fun trackSessionNotificationOpened(sessionId: String) {
val bundle = Bundle()
bundle.putString("SessionId", sessionId)
firebase.logEvent("SessionNotificationOpened", bundle)
}
override fun trackSessionNotificationGenerated(sessionId: String) {
val bundle = Bundle()
bundle.putString("SessionId", sessionId)
firebase.logEvent("SessionNotificationGenerated", bundle)
}
override fun trackShowSourceCode() {
val bundle = Bundle()
firebase.logEvent("ShowSourceCodeClicked", bundle)
}
override fun trackShowLicenses() {
val bundle = Bundle()
firebase.logEvent("ShowLicenseClicked", bundle)
}
override fun trackFastScrollStarted(controllerName: String) {
val bundle = Bundle()
bundle.putString("ControllerName", controllerName)
firebase.logEvent("FastScrollStarted", bundle)
}
}
| apache-2.0 | 8fde30f155a00fec1f526ded822b9bf0 | 27.755319 | 93 | 0.739919 | 4.589134 | false | false | false | false |
oleksiyp/mockk | agent/jvm/src/main/kotlin/io/mockk/proxy/jvm/JvmMockKAgentFactory.kt | 1 | 6048 | package io.mockk.proxy.jvm
import io.mockk.proxy.*
import io.mockk.proxy.common.transformation.ClassTransformationSpecMap
import io.mockk.proxy.jvm.dispatcher.BootJarLoader
import io.mockk.proxy.jvm.dispatcher.JvmMockKWeakMap
import io.mockk.proxy.jvm.transformation.InliningClassTransformer
import io.mockk.proxy.jvm.transformation.JvmInlineInstrumentation
import io.mockk.proxy.jvm.transformation.SubclassInstrumentation
import net.bytebuddy.ByteBuddy
import net.bytebuddy.NamingStrategy
import net.bytebuddy.agent.ByteBuddyAgent
import net.bytebuddy.description.type.TypeDescription
import net.bytebuddy.dynamic.scaffold.TypeValidation
import java.lang.instrument.Instrumentation
import java.util.*
import java.util.concurrent.atomic.AtomicLong
class JvmMockKAgentFactory : MockKAgentFactory {
private lateinit var log: MockKAgentLogger
private lateinit var jvmInstantiator: ObjenesisInstantiator
private lateinit var jvmProxyMaker: MockKProxyMaker
private lateinit var jvmStaticProxyMaker: MockKStaticProxyMaker
private lateinit var jvmConstructorProxyMaker: MockKConstructorProxyMaker
override fun init(logFactory: MockKAgentLogFactory) {
log = logFactory.logger(JvmMockKAgentFactory::class.java)
val loader = BootJarLoader(
logFactory.logger(BootJarLoader::class.java)
)
val jvmInstrumentation = initInstrumentation(loader)
class Initializer {
fun preload() {
listOf(
"java.lang.WeakPairMap\$Pair\$Weak",
"java.lang.WeakPairMap\$Pair\$Lookup",
"java.lang.WeakPairMap",
"java.lang.WeakPairMap\$WeakRefPeer",
"java.lang.WeakPairMap\$Pair",
"java.lang.WeakPairMap\$Pair\$Weak\$1"
).forEach {
try {
Class.forName(it, false, null)
} catch (ignored: ClassNotFoundException) {
// skip
}
}
}
fun init() {
preload()
val byteBuddy = ByteBuddy()
.with(TypeValidation.DISABLED)
.with(MockKSubclassNamingStrategy())
jvmInstantiator = ObjenesisInstantiator(
logFactory.logger(ObjenesisInstantiator::class.java),
byteBuddy
)
val handlers = handlerMap(jvmInstrumentation != null)
val staticHandlers = handlerMap(jvmInstrumentation != null)
val constructorHandlers = handlerMap(jvmInstrumentation != null)
val specMap = ClassTransformationSpecMap()
val inliner = jvmInstrumentation?.let {
it.addTransformer(
InliningClassTransformer(
logFactory.logger(InliningClassTransformer::class.java),
specMap,
handlers,
staticHandlers,
constructorHandlers,
byteBuddy
),
true
)
JvmInlineInstrumentation(
logFactory.logger(JvmInlineInstrumentation::class.java),
specMap,
jvmInstrumentation
)
}
val subclasser = SubclassInstrumentation(
logFactory.logger(SubclassInstrumentation::class.java),
handlers,
byteBuddy
)
jvmProxyMaker = ProxyMaker(
logFactory.logger(ProxyMaker::class.java),
inliner,
subclasser,
jvmInstantiator,
handlers
)
jvmStaticProxyMaker = StaticProxyMaker(
logFactory.logger(StaticProxyMaker::class.java),
inliner,
staticHandlers
)
jvmConstructorProxyMaker = ConstructorProxyMaker(
logFactory.logger(ConstructorProxyMaker::class.java),
inliner,
constructorHandlers
)
}
private fun handlerMap(hasInstrumentation: Boolean) =
if (hasInstrumentation)
JvmMockKWeakMap<Any, MockKInvocationHandler>()
else
Collections.synchronizedMap(mutableMapOf<Any, MockKInvocationHandler>())
}
Initializer().init()
}
private fun initInstrumentation(loader: BootJarLoader): Instrumentation? {
val instrumentation = ByteBuddyAgent.install()
if (instrumentation == null) {
log.debug(
"Can't install ByteBuddy agent.\n" +
"Try running VM with MockK Java Agent\n" +
"i.e. with -javaagent:mockk-agent.jar option."
)
return null
}
log.trace("Byte buddy agent installed")
if (!loader.loadBootJar(instrumentation)) {
log.trace("Can't inject boot jar.")
return null
}
return instrumentation
}
override val instantiator get() = jvmInstantiator
override val proxyMaker get() = jvmProxyMaker
override val staticProxyMaker get() = jvmStaticProxyMaker
override val constructorProxyMaker get() = jvmConstructorProxyMaker
}
internal class MockKSubclassNamingStrategy : NamingStrategy.AbstractBase() {
val counter = AtomicLong()
override fun name(superClass: TypeDescription): String {
var baseName = superClass.name
if (baseName.startsWith("java.")) {
baseName = "io.mockk.renamed.$baseName"
}
return "$baseName\$Subclass${counter.getAndIncrement()}"
}
} | apache-2.0 | acb4396b8c2948203cec94b1a6ec604c | 34.374269 | 92 | 0.571263 | 5.615599 | false | false | false | false |
Adonai/Man-Man | app/src/main/java/com/adonai/manman/adapters/ChaptersArrayAdapter.kt | 1 | 1275 | package com.adonai.manman.adapters
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.TextView
import com.adonai.manman.R
import com.adonai.manman.Utils
import com.adonai.manman.ManChaptersFragment
/**
* This class represents an array adapter for showing man chapters
* There are only about ten constant chapters, so it was convenient to place it to the string-array
*
* The array is retrieved via [Utils.parseStringArray]
* and stored in [ManChaptersFragment.mCachedChapters]
*
* @author Kanedias
*/
class ChaptersArrayAdapter(context: Context, resource: Int, textViewResourceId: Int, objects: List<Map.Entry<String, String>>) : ArrayAdapter<Map.Entry<String, String>>(context, resource, textViewResourceId, objects) {
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val root = super.getView(position, convertView, parent)
val current = getItem(position)
val index = root.findViewById<View>(R.id.chapter_index_label) as TextView
val name = root.findViewById<View>(R.id.chapter_name_label) as TextView
index.text = current!!.key
name.text = current.value
return root
}
} | gpl-3.0 | 95153cc719d7d80926b79413f7461a29 | 35.457143 | 218 | 0.747451 | 4.153094 | false | false | false | false |
bastman/kotlin-spring-jpa-examples | src/main/kotlin/com/example/demo/api/realestate/handler/properties/crud/create/CreatePropertyHandler.kt | 1 | 1883 | package com.example.demo.api.realestate.handler.properties.crud.create
import com.example.demo.api.common.validation.validateRequest
import com.example.demo.api.realestate.domain.jpa.entities.Property
import com.example.demo.api.realestate.domain.jpa.entities.PropertyAddress
import com.example.demo.api.realestate.domain.jpa.services.JpaPropertyService
import com.example.demo.api.realestate.handler.common.response.PropertyResponse
import org.springframework.stereotype.Component
import org.springframework.validation.Validator
import java.time.Instant
import java.util.*
@Component
class CreatePropertyHandler(
private val validator: Validator,
private val jpaPropertyService: JpaPropertyService
) {
fun handle(request: CreatePropertyRequest): PropertyResponse =
execute(validator.validateRequest(request, "request"))
private fun execute(request: CreatePropertyRequest): PropertyResponse {
val newPropertyId = UUID.randomUUID()
val property = Property(
id = newPropertyId,
created = Instant.now(),
modified = Instant.now(),
clusterId = null,
type = request.type,
name = request.name,
address = PropertyAddress(
country = request.address.country.trim(),
city = request.address.city.trim(),
zip = request.address.zip.trim(),
street = request.address.street.trim(),
number = request.address.number.trim(),
district = request.address.district.trim(),
neighborhood = request.address.neighborhood.trim()
)
)
return PropertyResponse.of(
property = jpaPropertyService.insert(property)
)
}
}
| mit | 44b842c7950f53254d25f4d5441be020 | 39.934783 | 79 | 0.643123 | 4.916449 | false | false | false | false |
sybila/ode-generator | src/main/java/com/github/sybila/ode/generator/smt/remote/bridge/RemoteZ3.kt | 1 | 3706 | package com.github.sybila.ode.generator.smt.remote.bridge
import com.github.sybila.ode.model.OdeModel
import com.github.sybila.ode.safeString
import java.io.Closeable
import java.util.*
class RemoteZ3(
params: List<OdeModel.Parameter>,
private val verbose: Boolean = false,
logic: String = "QF_LRA",
z3Executable: String = "z3"
) : Closeable {
val parameters = listOf(
"model=false",
"pp.single_line=true",
"pp.fixed_indent=true",
"pp.flat_assoc=true",
"pp.decimal=true",
"pp.min_alias_size=${Integer.MAX_VALUE}" //this should prevent usage of let
)
val process = kotlin.run {
val command = (listOf(z3Executable, "-in") + parameters)
Runtime.getRuntime().exec(command.toTypedArray())
}!!
val results = process.inputStream.bufferedReader().lineSequence().iterator()
val commands = process.outputStream.bufferedWriter()
val bounds: String = params.flatMap {
listOf("(< ${it.name} ${it.range.second.safeString()})", "(> ${it.name} ${it.range.first.safeString()})")
}.joinToString(separator = " ", prefix = "(and ", postfix = ")")
val activeAssertions = HashSet<String>()
init {
//setup solver
"(set-logic $logic)".execute()
//add parameter bounds and declarations
params.forEach {
"(declare-const ${it.name} Real)".execute()
}
"(assert $bounds)".execute()
"(apply ctx-solver-simplify)".execute()
if ("(goals" != readResult()) throw IllegalStateException("Unexpected z3 output when minimizing")
if ("(goal" != readResult()) throw IllegalStateException("Unexpected z3 output when minimizing")
var line = readResult()
while (!line.trim().startsWith(":precision")) {
activeAssertions.add(line.filter { it != '?' })
line = readResult()
}
if (")" != readResult()) throw IllegalStateException("Unexpected z3 output when minimizing")
}
fun checkSat(formula: String): Boolean {
"(push)".execute()
"(assert $formula)".execute()
"(check-sat-using (using-params qflra :logic QF_LRA))".execute()
val result = readResult()
"(pop)".execute()
return result == "sat"
}
fun minimize(formula: String): String {
"(push)".execute()
"(assert $formula)".execute()
"(apply (repeat ctx-solver-simplify))".execute()
if ("(goals" != readResult()) throw IllegalStateException("Unexpected z3 output when minimizing")
if ("(goal" != readResult()) throw IllegalStateException("Unexpected z3 output when minimizing")
val assertions = ArrayList<String>()
var line = readResult()
while (!line.startsWith(":precision")) {
if (line !in activeAssertions) assertions.add(line)
line = readResult()
}
if (")" != readResult()) throw IllegalStateException("Unexpected z3 output when minimizing")
"(pop)".execute()
return when {
assertions.isEmpty() -> "true"
assertions.size == 1 -> assertions.first()
else -> assertions.joinToString(prefix = "(and ", postfix = ")", separator = " ")
}
}
private fun String.execute() {
if (verbose) println(this)
commands.write(this+"\n")
commands.flush()
}
private fun readResult(): String {
val r = results.next().filter { it != '?' }.trim()
if (verbose) println(r)
return r
}
override fun close() {
if (process.isAlive) {
process.destroyForcibly()
}
}
} | gpl-3.0 | fb855f135cdea7debbb48c3e35495207 | 33.009174 | 113 | 0.586346 | 4.370283 | false | false | false | false |
mike-neck/kuickcheck | core/src/test/kotlin/org/mikeneck/kuickcheck/generator/internal/FunctionInvocationHandlerTest.kt | 1 | 5985 | /*
* Copyright 2016 Shinya Mochida
*
* Licensed under the Apache License,Version2.0(the"License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,software
* Distributed under the License is distributed on an"AS IS"BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.mikeneck.kuickcheck.generator.internal
import org.junit.Test
import org.junit.experimental.theories.DataPoints
import org.junit.experimental.theories.Theories
import org.junit.experimental.theories.Theory
import org.junit.runner.RunWith
import org.mikeneck.kuickcheck.Generator
import java.lang.reflect.Method
import java.util.*
import kotlin.reflect.KClass
class JavaMethodTest {
@Test fun comparableTest() {
val method = Comparable::class.java.getMethod("compareTo", Any::class.java)
val javaMethod = JavaMethod(method)
assert(javaMethod.isAbstract())
}
@Test fun implMethod() {
val method = JavaMethodTest::class.java.getMethod("implMethod")
val javaMethod = JavaMethod(method)
assert(javaMethod.isAbstract() == false)
}
}
@RunWith(Theories::class)
internal class JavaMethodEqualityTest {
companion object {
@DataPoints @JvmField val testData = listOf(
Pair(JavaMethod("toString", arrayOf<Class<*>>(), null),
JavaMethodTest::class.java.getMethod("toString")),
Pair(JavaMethod("equals", arrayOf(Any::class.java), Any::class.java),
JavaMethodTest::class.java.getMethod("equals", Any::class.java)),
Pair(JavaMethod("hashCode", arrayOf<Class<*>>(), null),
JavaMethodTest::class.java.getMethod("hashCode"))
)
}
@Theory fun test(data: Pair<JavaMethod, Method>) {
val method = JavaMethod(data.second)
assert(method == data.first)
}
@Theory fun declaredInAny(data: Pair<JavaMethod, Method>) {
val method = JavaMethod(data.second)
assert(method.declaredInAny())
}
}
private interface Generated<out T> {
fun generated(): T
}
class FunctionInvocationHandlerTest {
private val intGenerator = object : Generator<Int>, Generated<Int> {
var gen: Int = 0
val random = Random()
override fun generated(): Int = gen
override fun invoke(): Int {
gen = random.nextInt(200)
return gen
}
}
private val function1 = { s: String -> s.length }
private val handler: FunctionInvocationHandler<Function1<String, Int>, Int> =
FunctionInvocationHandler(function1.javaClass.kotlin, intGenerator)
@Test fun createInstance() {
assert(handler.hashCode() != 0)
}
@Test fun `invokeEquals - false`() {
val equals = Any::class.java.getMethod("equals", Any::class.java)
val any = Any()
val proxy = Any()
val result = handler(proxy, equals, arrayOf(any)) as Boolean
assert(result == false)
}
@Test fun `invokeEquals - true`() {
val equals = Any::class.java.getMethod("equals", Any::class.java)
val proxy = Any()
val result = handler(proxy, equals, arrayOf(proxy)) as Boolean
assert(result)
}
@Test fun invokeHashCode() {
val hashCode = Any::class.java.getMethod("hashCode")
val proxy = Any()
val result = handler(proxy, hashCode, emptyArray())
assert(result is Int)
assert(result == System.identityHashCode(proxy))
}
@Test fun invokeToString() {
val toString = Any::class.java.getMethod("toString")
val proxy = Any()
val result = handler(proxy, toString, emptyArray())
assert(result is String)
assert((result as String).startsWith("generated"))
}
@Test fun invokeFunction() {
val invoke = function1.javaClass.getMethod("invoke", String::class.java)
val proxy = Any()
val result = handler(proxy, invoke, arrayOf("test arg"))
assert(result is Int)
assert((result as Int) == intGenerator.generated())
}
}
class FunctionUtilTest {
fun intGenerator(): Generator<Int> {
return object : Generator<Int> {
val itor = (1..10000000).iterator()
override fun invoke(): Int = itor.nextInt()
}
}
@Test fun functionType() {
val f = { s: String, l: Long?, p: (String, Long) -> Boolean -> p(s, l ?: 0) }
println(f.javaClass)
println(f.javaClass.interfaces.map { it })
println(f.javaClass.superclass)
println(f.javaClass.kotlin)
}
@Test fun functionTypeOf() {
val f = function({ s: String -> }, intGenerator())
assert(f is Function<Int>)
}
@Test fun createFunction() {
val klass = ({ s: String -> s.length }).javaClass.kotlin
@Suppress("UNCHECKED_CAST")
val fClass = klass.java.interfaces.filter { it in functions }.first()?.kotlin as KClass<Function1<String, Int>>
val generator = intGenerator()
val f = FunctionInvocationHandler.createFunction(fClass, generator)
assert(f("tooo") == 1)
}
companion object {
val functions = listOf(
Function::class.java, Function0::class.java, Function1::class.java, Function2::class.java, Function3::class.java
)
@Suppress("UNUSED")
fun <P1, P2, R> function(@Suppress("UNUSED_PARAMETER") f: (P1, P2) -> Unit, g: Generator<R>): (P1, P2) -> R {
return { p1, p2 -> g() }
}
fun <P1, R> function(@Suppress("UNUSED_PARAMETER") f: (P1) -> Unit, g: Generator<R>): (P1) -> R {
return { p1 -> g() }
}
}
}
| apache-2.0 | a2784231dc52d8e1d62674369244ed21 | 31.704918 | 128 | 0.622556 | 4.188244 | false | true | false | false |
rhdunn/xquery-intellij-plugin | src/lang-core/main/uk/co/reecedunn/intellij/plugin/core/lexer/EntityReferences.kt | 1 | 4867 | /*
* Copyright (C) 2016-2022 Reece H. Dunn
*
* 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 uk.co.reecedunn.intellij.plugin.core.lexer
import com.google.gson.JsonParser
import uk.co.reecedunn.intellij.plugin.core.vfs.ResourceVirtualFile
import xqt.platform.xml.lexer.*
import xqt.platform.xml.model.XmlCharReader
import java.io.InputStreamReader
enum class EntityReferenceType {
EmptyEntityReference,
PartialEntityReference,
CharacterReference,
PredefinedEntityReference,
XmlEntityReference,
Html4EntityReference,
Html5EntityReference
}
fun XmlCharReader.matchEntityReference(): EntityReferenceType {
advance()
return when (currentChar) {
in NameStartChar -> {
advanceWhile { it in NameChar }
if (currentChar == Semicolon) {
advance()
EntityReferenceType.PredefinedEntityReference
} else {
EntityReferenceType.PartialEntityReference
}
}
NumberSign -> {
advance()
when (currentChar) {
LatinSmallLetterX -> {
advance()
when (currentChar) {
in HexDigits -> {
advanceWhile { it in HexDigits }
if (currentChar == Semicolon) {
advance()
EntityReferenceType.CharacterReference
} else {
EntityReferenceType.PartialEntityReference
}
}
Semicolon -> {
advance()
EntityReferenceType.EmptyEntityReference
}
else -> EntityReferenceType.PartialEntityReference
}
}
in Digits -> {
advanceWhile { it in Digits }
if (currentChar == Semicolon) {
advance()
EntityReferenceType.CharacterReference
} else {
EntityReferenceType.PartialEntityReference
}
}
Semicolon -> {
advance()
EntityReferenceType.EmptyEntityReference
}
else -> EntityReferenceType.PartialEntityReference
}
}
Semicolon -> {
advance()
EntityReferenceType.EmptyEntityReference
}
else -> EntityReferenceType.PartialEntityReference
}
}
data class EntityRef(val name: CharSequence, val value: CharSequence, val type: EntityReferenceType)
fun CharSequence.entityReferenceCodePoint(): Int = when {
startsWith("&#x") -> { // `&#x...;` hexadecimal character reference
subSequence(3, length - 1).toString().toInt(radix = 16)
}
startsWith("&#") -> { // `&#...;` decimal character reference
subSequence(2, length - 1).toString().toInt(radix = 10)
}
else -> 0xFFFE
}
private fun loadPredefinedEntities(entities: HashMap<String, EntityRef>, path: String, type: EntityReferenceType) {
val file = ResourceVirtualFile.create(EntityRef::class.java.classLoader, path)
val data = JsonParser.parseReader(InputStreamReader(file.inputStream)).asJsonObject
data.entrySet().forEach { (key, value) ->
val chars = value.asJsonObject.get("characters").asString
entities.putIfAbsent(key, EntityRef(key, chars, type))
}
}
var ENTITIES: HashMap<String, EntityRef>? = null
get() {
if (field == null) {
field = HashMap()
// Dynamically load the predefined entities on their first use. This loads the entities:
// XML ⊂ HTML 4 ⊂ HTML 5
// ensuring that the subset type is reported correctly.
loadPredefinedEntities(field!!, "predefined-entities/xml.json", EntityReferenceType.XmlEntityReference)
loadPredefinedEntities(field!!, "predefined-entities/html4.json", EntityReferenceType.Html4EntityReference)
loadPredefinedEntities(field!!, "predefined-entities/html5.json", EntityReferenceType.Html5EntityReference)
}
return field
}
| apache-2.0 | 21e56a543441120191474ed234db554d | 35.022222 | 119 | 0.587086 | 5.303162 | false | false | false | false |
exponentjs/exponent | android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/filesystem/CountingRequestBody.kt | 2 | 1356 | package abi43_0_0.expo.modules.filesystem
import okhttp3.RequestBody
import okio.Buffer
import okio.BufferedSink
import okio.ForwardingSink
import okio.Okio
import okio.Sink
import java.io.IOException
@FunctionalInterface
interface RequestBodyDecorator {
fun decorate(requestBody: RequestBody): RequestBody
}
@FunctionalInterface
interface CountingRequestListener {
fun onProgress(bytesWritten: Long, contentLength: Long)
}
private class CountingSink(
sink: Sink,
private val requestBody: RequestBody,
private val progressListener: CountingRequestListener
) : ForwardingSink(sink) {
private var bytesWritten = 0L
override fun write(source: Buffer, byteCount: Long) {
super.write(source, byteCount)
bytesWritten += byteCount
progressListener.onProgress(bytesWritten, requestBody.contentLength())
}
}
class CountingRequestBody(
private val requestBody: RequestBody,
private val progressListener: CountingRequestListener
) : RequestBody() {
override fun contentType() = requestBody.contentType()
@Throws(IOException::class)
override fun contentLength() = requestBody.contentLength()
override fun writeTo(sink: BufferedSink) {
val countingSink = CountingSink(sink, this, progressListener)
val bufferedSink = Okio.buffer(countingSink)
requestBody.writeTo(bufferedSink)
bufferedSink.flush()
}
}
| bsd-3-clause | 35ad65c5fbb6a36257aca938f370415d | 25.588235 | 74 | 0.784661 | 4.741259 | false | false | false | false |
KeenenCharles/AndroidUnplash | androidunsplash/src/main/java/com/keenencharles/unsplash/models/Photo.kt | 1 | 968 | package com.keenencharles.unsplash.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
import java.util.*
@Parcelize
data class Photo(
var id: String? = null,
var width: Int? = null,
var height: Int? = null,
var color: String? = null,
var downloads: Int? = null,
var likes: Int? = null,
var exif: Exif? = null,
var location: Location? = null,
var urls: Urls? = null,
var links: Links? = null,
var user: User? = null,
var categories: List<Category> = ArrayList(),
@SerializedName("current_user_collections") var currentUserCollections: List<Collection> = ArrayList(),
@SerializedName("liked_by_user") var likedByUser: Boolean? = null,
@SerializedName("created_at") var createdAt: String? = null,
@SerializedName("updated_at") var updatedAt: String? = null
) : Parcelable | mit | 57b8bd0b6e9bb663892d8576a24863fe | 36.269231 | 111 | 0.645661 | 4.119149 | false | false | false | false |
Unpublished/AmazeFileManager | app/src/main/java/com/amaze/filemanager/asynchronous/services/ftp/FtpService.kt | 2 | 16910 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.asynchronous.services.ftp
import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.wifi.WifiManager
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.KITKAT
import android.os.Build.VERSION_CODES.M
import android.os.Environment
import android.os.IBinder
import android.os.SystemClock
import android.provider.DocumentsContract
import androidx.preference.PreferenceManager
import com.amaze.filemanager.R
import com.amaze.filemanager.application.AppConfig
import com.amaze.filemanager.filesystem.files.CryptUtil
import com.amaze.filemanager.filesystem.ftpserver.AndroidFileSystemFactory
import com.amaze.filemanager.ui.notifications.FtpNotification
import com.amaze.filemanager.ui.notifications.NotificationConstants
import com.amaze.filemanager.utils.ObtainableServiceBinder
import org.apache.ftpserver.ConnectionConfigFactory
import org.apache.ftpserver.FtpServer
import org.apache.ftpserver.FtpServerFactory
import org.apache.ftpserver.listener.ListenerFactory
import org.apache.ftpserver.ssl.ClientAuth
import org.apache.ftpserver.ssl.impl.DefaultSslConfiguration
import org.apache.ftpserver.usermanager.impl.BaseUser
import org.apache.ftpserver.usermanager.impl.WritePermission
import org.greenrobot.eventbus.EventBus
import java.io.IOException
import java.net.InetAddress
import java.net.NetworkInterface
import java.net.UnknownHostException
import java.security.GeneralSecurityException
import java.security.KeyStore
import javax.net.ssl.KeyManagerFactory
import javax.net.ssl.TrustManagerFactory
/**
* Created by yashwanthreddyg on 09-06-2016.
*
*
* Edited by zent-co on 30-07-2019 Edited by bowiechen on 2019-10-19.
*/
class FtpService : Service(), Runnable {
private val binder: IBinder = ObtainableServiceBinder(this)
// Service will broadcast via event bus when server start/stop
enum class FtpReceiverActions {
STARTED, STARTED_FROM_TILE, STOPPED, FAILED_TO_START
}
private var username: String? = null
private var password: String? = null
private var isPasswordProtected = false
private var isStartedByTile = false
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
isStartedByTile = intent.getBooleanExtra(TAG_STARTED_BY_TILE, false)
var attempts = 10
while (serverThread != null) {
if (attempts > 0) {
attempts--
try {
Thread.sleep(1000)
} catch (ignored: InterruptedException) {
}
} else {
return START_STICKY
}
}
serverThread = Thread(this)
serverThread!!.start()
val notification = FtpNotification.startNotification(applicationContext, isStartedByTile)
startForeground(NotificationConstants.FTP_ID, notification)
return START_NOT_STICKY
}
override fun onBind(intent: Intent): IBinder {
return binder
}
@Suppress("LongMethod")
override fun run() {
val preferences = PreferenceManager.getDefaultSharedPreferences(this)
FtpServerFactory().run {
val connectionConfigFactory = ConnectionConfigFactory()
if (SDK_INT >= KITKAT &&
preferences.getBoolean(KEY_PREFERENCE_SAF_FILESYSTEM, false)
) {
fileSystem = AndroidFileSystemFactory(applicationContext)
}
val usernamePreference = preferences.getString(
KEY_PREFERENCE_USERNAME,
DEFAULT_USERNAME
)
if (usernamePreference != DEFAULT_USERNAME) {
username = usernamePreference
runCatching {
password = CryptUtil.decryptPassword(
applicationContext, preferences.getString(KEY_PREFERENCE_PASSWORD, "")
)
isPasswordProtected = true
}.onFailure {
it.printStackTrace()
AppConfig.toast(applicationContext, R.string.error)
preferences.edit().putString(KEY_PREFERENCE_PASSWORD, "").apply()
isPasswordProtected = false
}
}
val user = BaseUser()
if (!isPasswordProtected) {
user.name = "anonymous"
connectionConfigFactory.isAnonymousLoginEnabled = true
} else {
user.name = username
user.password = password
}
user.homeDirectory = preferences.getString(
KEY_PREFERENCE_PATH,
defaultPath(this@FtpService)
)
if (!preferences.getBoolean(KEY_PREFERENCE_READONLY, false)) {
user.authorities = listOf(WritePermission())
}
connectionConfig = connectionConfigFactory.createConnectionConfig()
userManager.save(user)
val fac = ListenerFactory()
if (preferences.getBoolean(KEY_PREFERENCE_SECURE, DEFAULT_SECURE)) {
try {
val keyStore = KeyStore.getInstance("BKS")
keyStore.load(resources.openRawResource(R.raw.key), KEYSTORE_PASSWORD)
val keyManagerFactory = KeyManagerFactory
.getInstance(KeyManagerFactory.getDefaultAlgorithm())
keyManagerFactory.init(keyStore, KEYSTORE_PASSWORD)
val trustManagerFactory = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm())
trustManagerFactory.init(keyStore)
fac.sslConfiguration = DefaultSslConfiguration(
keyManagerFactory,
trustManagerFactory,
ClientAuth.WANT,
"TLS",
null,
"ftpserver"
)
fac.isImplicitSsl = true
} catch (e: GeneralSecurityException) {
preferences.edit().putBoolean(KEY_PREFERENCE_SECURE, false).apply()
} catch (e: IOException) {
preferences.edit().putBoolean(KEY_PREFERENCE_SECURE, false).apply()
}
}
fac.port = getPort(preferences)
fac.idleTimeout = preferences.getInt(KEY_PREFERENCE_TIMEOUT, DEFAULT_TIMEOUT)
addListener("default", fac.createListener())
runCatching {
server = createServer().apply {
start()
EventBus.getDefault()
.post(
if (isStartedByTile)
FtpReceiverActions.STARTED_FROM_TILE
else
FtpReceiverActions.STARTED
)
}
}.onFailure {
EventBus.getDefault().post(FtpReceiverActions.FAILED_TO_START)
}
}
}
override fun onDestroy() {
serverThread?.interrupt().also {
// wait 10 sec for server thread to finish
serverThread!!.join(10000)
if (!serverThread!!.isAlive) {
serverThread = null
}
server?.stop().also {
EventBus.getDefault().post(FtpReceiverActions.STOPPED)
}
}
}
// Restart the service if the app is closed from the recent list
override fun onTaskRemoved(rootIntent: Intent) {
super.onTaskRemoved(rootIntent)
val restartService = Intent(applicationContext, this.javaClass).setPackage(packageName)
val flag = if (SDK_INT >= M) {
PendingIntent.FLAG_ONE_SHOT or PendingIntent.FLAG_IMMUTABLE
} else {
PendingIntent.FLAG_ONE_SHOT
}
val restartServicePI = PendingIntent.getService(
applicationContext, 1, restartService, flag
)
val alarmService = applicationContext.getSystemService(ALARM_SERVICE) as AlarmManager
alarmService[AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 2000] =
restartServicePI
}
companion object {
const val DEFAULT_PORT = 2211
const val DEFAULT_USERNAME = ""
const val DEFAULT_TIMEOUT = 600 // default timeout, in sec
const val DEFAULT_SECURE = true
const val PORT_PREFERENCE_KEY = "ftpPort"
const val KEY_PREFERENCE_PATH = "ftp_path"
const val KEY_PREFERENCE_USERNAME = "ftp_username"
const val KEY_PREFERENCE_PASSWORD = "ftp_password_encrypted"
const val KEY_PREFERENCE_TIMEOUT = "ftp_timeout"
const val KEY_PREFERENCE_SECURE = "ftp_secure"
const val KEY_PREFERENCE_READONLY = "ftp_readonly"
const val KEY_PREFERENCE_SAF_FILESYSTEM = "ftp_saf_filesystem"
const val INITIALS_HOST_FTP = "ftp://"
const val INITIALS_HOST_SFTP = "ftps://"
private const val WIFI_AP_ADDRESS_PREFIX = "192.168.43."
private val KEYSTORE_PASSWORD = "vishal007".toCharArray()
// RequestStartStopReceiver listens for these actions to start/stop this server
const val ACTION_START_FTPSERVER =
"com.amaze.filemanager.services.ftpservice.FTPReceiver.ACTION_START_FTPSERVER"
const val ACTION_STOP_FTPSERVER =
"com.amaze.filemanager.services.ftpservice.FTPReceiver.ACTION_STOP_FTPSERVER"
const val TAG_STARTED_BY_TILE = "started_by_tile"
// attribute of action_started, used by notification
private var serverThread: Thread? = null
private var server: FtpServer? = null
/**
* Derive the FTP server's default share path, depending the user's Android version.
*
* Default it's the internal storage's root as java.io.File; otherwise it's content://
* based URI if it's running on Android 7.0 or above.
*/
@JvmStatic
fun defaultPath(context: Context): String {
return if (PreferenceManager.getDefaultSharedPreferences(context)
.getBoolean(KEY_PREFERENCE_SAF_FILESYSTEM, false) && SDK_INT > M
) {
DocumentsContract.buildTreeDocumentUri(
"com.android.externalstorage.documents",
"primary:"
).toString()
} else {
Environment.getExternalStorageDirectory().absolutePath
}
}
/**
* Indicator whether FTP service is running
*/
@JvmStatic
fun isRunning(): Boolean = server?.let {
!it.isStopped
} ?: false
/**
* Is the device connected to local network, either Ethernet or Wifi?
*/
@JvmStatic
fun isConnectedToLocalNetwork(context: Context): Boolean {
val cm = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
var connected: Boolean
if (SDK_INT >= M) {
return cm.activeNetwork?.let { activeNetwork ->
cm.getNetworkCapabilities(activeNetwork)?.let { ni ->
ni.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) or
ni.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)
} ?: false
} ?: false
} else {
connected = cm.activeNetworkInfo?.let { ni ->
ni.isConnected && (
ni.type and (
ConnectivityManager.TYPE_WIFI
or ConnectivityManager.TYPE_ETHERNET
) != 0
)
} ?: false
if (!connected) {
connected = runCatching {
NetworkInterface.getNetworkInterfaces().toList().find { netInterface ->
netInterface.displayName.startsWith("rndis")
}
}.getOrElse { null } != null
}
}
return connected
}
/**
* Is the device connected to Wifi?
*/
@JvmStatic
fun isConnectedToWifi(context: Context): Boolean {
val cm = context.getSystemService(CONNECTIVITY_SERVICE) as ConnectivityManager
return if (SDK_INT >= M) {
cm.activeNetwork?.let {
cm.getNetworkCapabilities(it)?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)
} ?: false
} else {
cm.activeNetworkInfo?.let {
it.isConnected && it.type == ConnectivityManager.TYPE_WIFI
} ?: false
}
}
/**
* Is the device's wifi hotspot enabled?
*/
@JvmStatic
fun isEnabledWifiHotspot(context: Context): Boolean {
val wm = context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
return callIsWifiApEnabled(wm)
}
/**
* Determine device's IP address
*/
@JvmStatic
fun getLocalInetAddress(context: Context): InetAddress? {
if (!isConnectedToLocalNetwork(context) && !isEnabledWifiHotspot(context)) {
return null
}
if (isConnectedToWifi(context)) {
val wm = context.applicationContext.getSystemService(WIFI_SERVICE) as WifiManager
val ipAddress = wm.connectionInfo.ipAddress
return if (ipAddress == 0) null else intToInet(ipAddress)
}
runCatching {
NetworkInterface.getNetworkInterfaces().iterator().forEach { netinterface ->
netinterface.inetAddresses.iterator().forEach { address ->
if (address.hostAddress.startsWith(WIFI_AP_ADDRESS_PREFIX) &&
isEnabledWifiHotspot(context)
) {
return address
}
// this is the condition that sometimes gives problems
if (!address.isLoopbackAddress &&
!address.isLinkLocalAddress &&
!isEnabledWifiHotspot(context)
) {
return address
}
}
}
}.onFailure { e ->
e.printStackTrace()
}
return null
}
private fun intToInet(value: Int): InetAddress? {
val bytes = ByteArray(4)
for (i in 0..3) {
bytes[i] = byteOfInt(value, i)
}
return try {
InetAddress.getByAddress(bytes)
} catch (e: UnknownHostException) {
// This only happens if the byte array has a bad length
null
}
}
private fun byteOfInt(value: Int, which: Int): Byte {
val shift = which * 8
return (value shr shift).toByte()
}
private fun getPort(preferences: SharedPreferences): Int {
return preferences.getInt(PORT_PREFERENCE_KEY, DEFAULT_PORT)
}
private fun callIsWifiApEnabled(wifiManager: WifiManager): Boolean = runCatching {
val method = wifiManager.javaClass.getDeclaredMethod("isWifiApEnabled")
method.invoke(wifiManager) as Boolean
}.getOrElse {
it.printStackTrace()
false
}
}
}
| gpl-3.0 | c888bb9b8eba246ff7d48e7e401ce72d | 39.261905 | 107 | 0.589533 | 5.315938 | false | false | false | false |
just-4-fun/holomorph | src/test/kotlin/just4fun/holomorph/mains/Misc.kt | 1 | 1519 | package just4fun.holomorph.mains
import just4fun.kotlinkit.async.AsyncTask
fun main(a: Array<String>) {
AsyncTask{
val v: Any? = null
println("${ v as? String}")
println("${ v as String?}")
}.onComplete { AsyncTask.sharedContext.shutdown() }
}
/*
// TEST ACCESSORS PERFORMANCE
fun main(a: Array<String>) {
// getA;getA;getA;getA;getA;getA;getA;getA;getA;getA;//4000
// getF;getF;getF;getF;getF;getF;getF;getF;getF;getF;//1400
// get;get;get;get;get;get;get;get;get;get;//450
// setA;setA;setA;setA;setA;setA;setA;setA;setA;setA;//4300
// setF;setF;setF;setF;setF;setF;setF;setF;setF;setF;//1400
set;set;set;set;set;set;set;set;set;set;//500
println("measuredTimeAvg= ${measuredTimeAvg} ns")
println("${obj.x}")
}
val pty = X::class.memberProperties.find { it.name == "x" }!!
val getter = pty.getter.apply { isAccessible = true } as KCallable<Int>
val setter = (pty as KMutableProperty<*>).setter.apply { isAccessible = true } as KCallable<*>
val field = pty.javaField?.apply { isAccessible = true }!!
val obj:X = X(42)
val getA get() = measureTime("GETTER", 1, antiSurgeRate = 1.3) { getter.call(obj) }
val getF get() = measureTime("GET FIELD", 1, antiSurgeRate = 1.3) { field.get(obj) }
val setA get() = measureTime("SETTER", 1, antiSurgeRate = 1.3) { setter.call(obj, 44) }
val setF get() = measureTime("FIELD SET", 1, antiSurgeRate = 1.3) { field.set(obj, 44) }
val get get() = measureTime("GET", 1) { obj.x }
val set get() = measureTime("SET", 1) { run { obj.x = 44 } }
class X(var x: Int)
*/
| apache-2.0 | 0cb8ea30bc7c40251639ad7bb8891935 | 34.325581 | 94 | 0.674786 | 2.732014 | false | false | false | false |
ligi/PassAndroid | android/src/main/java/org/ligi/passandroid/ui/PrefsFragment.kt | 1 | 2047 | package org.ligi.passandroid.ui
import android.Manifest
import android.content.SharedPreferences
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import androidx.appcompat.app.AppCompatDelegate.MODE_NIGHT_AUTO
import androidx.core.app.ActivityCompat
import androidx.preference.PreferenceFragmentCompat
import org.koin.android.ext.android.inject
import org.ligi.passandroid.R
import org.ligi.passandroid.model.Settings
import permissions.dispatcher.NeedsPermission
import permissions.dispatcher.RuntimePermissions
@RuntimePermissions
class PrefsFragment : PreferenceFragmentCompat(), SharedPreferences.OnSharedPreferenceChangeListener {
val settings : Settings by inject()
override fun onResume() {
super.onResume()
preferenceScreen.sharedPreferences.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
preferenceScreen.sharedPreferences.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key == getString(R.string.preference_key_nightmode)) {
@AppCompatDelegate.NightMode val nightMode = settings.getNightMode()
if (nightMode == MODE_NIGHT_AUTO) {
ensureDayNightWithPermissionCheck()
}
AppCompatDelegate.setDefaultNightMode(nightMode)
activity?.let { ActivityCompat.recreate(it) }
}
}
override fun onCreatePreferences(bundle: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.preferences, rootKey)
}
@NeedsPermission(Manifest.permission.ACCESS_COARSE_LOCATION)
fun ensureDayNight() {
// Intentionally empty
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
onRequestPermissionsResult(requestCode, grantResults)
}
}
| gpl-3.0 | 9fc7b2f9f46134686595d30d80264faf | 33.694915 | 115 | 0.753298 | 5.577657 | false | false | false | false |
EliFUT/android | app/src/main/kotlin/com/elifut/services/RealGoogleApiConnectionHandler.kt | 1 | 3424 | package com.elifut.services
import android.app.Activity
import android.os.Bundle
import android.util.Log
import com.elifut.R
import com.elifut.models.GoogleApiConnectionResult
import com.elifut.util.BaseGameUtils
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.games.Games
import com.google.android.gms.games.Player
import rx.Single
import rx.subjects.PublishSubject
class RealGoogleApiConnectionHandler(private val activity: Activity) :
GoogleApiConnectionHandler,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
// Create the Google API Client with access to Games
private val googleApiClient: GoogleApiClient = GoogleApiClient.Builder(activity)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Games.API)
.addScope(Games.SCOPE_GAMES)
.build()
private var resolvingConnectionFailure = false
private var signInClicked: Boolean = false
private var autoStartSignInFlow = true
private val resultSubject: PublishSubject<GoogleApiConnectionResult> =
PublishSubject.create<GoogleApiConnectionResult>()
override fun onConnected(connectionHint: Bundle?) {
Log.d(TAG, "onConnected(): connected to Google APIs")
val player: Player? = Games.Players.getCurrentPlayer(googleApiClient)
resultSubject.onNext(GoogleApiConnectionResult(connectionHint, player, googleApiClient))
resultSubject.onCompleted()
}
override fun onConnectionSuspended(i: Int) {
Log.d(TAG, "onConnectionSuspended(): attempting to connect")
googleApiClient.connect()
}
override fun onStart() {
Log.d(TAG, "onStart(): connecting")
googleApiClient.connect()
}
override fun onStop() {
Log.d(TAG, "onStop(): disconnecting")
if (googleApiClient.isConnected) {
googleApiClient.disconnect()
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int) {
if (requestCode == RC_SIGN_IN) {
signInClicked = false
resolvingConnectionFailure = false
if (resultCode == Activity.RESULT_OK) {
googleApiClient.connect()
} else {
BaseGameUtils.showActivityResultError(activity, requestCode, resultCode,
R.string.signin_other_error)
}
}
}
override fun result(): Single<GoogleApiConnectionResult> {
return resultSubject.toSingle()
}
override fun connect() {
signInClicked = true
googleApiClient.connect()
}
override fun onConnectionFailed(connectionResult: ConnectionResult) {
Log.d(TAG, "onConnectionFailed(): attempting to resolve")
if (resolvingConnectionFailure) {
Log.d(TAG, "onConnectionFailed(): already resolving")
return
}
if (signInClicked || autoStartSignInFlow) {
autoStartSignInFlow = false
signInClicked = false
resolvingConnectionFailure = true
if (!BaseGameUtils.resolveConnectionFailure(activity, googleApiClient, connectionResult,
RC_SIGN_IN, activity.getString(R.string.signin_other_error))) {
resolvingConnectionFailure = false
}
}
resultSubject.onError(RuntimeException(connectionResult.errorMessage))
}
companion object {
private const val TAG = "GoogleApiClientCallback"
// request codes we use when invoking an external activity
private const val RC_SIGN_IN = 9001
}
}
| apache-2.0 | 440c266c6ceb54f5aa1c598ac7a59cef | 31.923077 | 94 | 0.737734 | 4.645862 | false | false | false | false |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/component/builder/base/BaseComponentBuilder.kt | 1 | 7657 | package org.hexworks.zircon.api.component.builder.base
import org.hexworks.cobalt.core.api.behavior.DisposeState
import org.hexworks.cobalt.core.api.behavior.NotDisposed
import org.hexworks.cobalt.databinding.api.property.Property
import org.hexworks.cobalt.events.api.Subscription
import org.hexworks.cobalt.logging.api.LoggerFactory
import org.hexworks.zircon.api.component.AlignmentStrategy
import org.hexworks.zircon.api.component.ColorTheme
import org.hexworks.zircon.api.component.Component
import org.hexworks.zircon.api.component.ComponentStyleSet
import org.hexworks.zircon.api.component.builder.ComponentBuilder
import org.hexworks.zircon.api.component.data.ComponentMetadata
import org.hexworks.zircon.api.component.renderer.ComponentDecorationRenderer
import org.hexworks.zircon.api.component.renderer.ComponentRenderer
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.resource.TilesetResource
import org.hexworks.zircon.api.uievent.ComponentEvent
import org.hexworks.zircon.api.uievent.ComponentEventType
import org.hexworks.zircon.api.uievent.UIEventResponse
import org.hexworks.zircon.internal.component.data.CommonComponentProperties
import org.hexworks.zircon.internal.component.renderer.DefaultComponentRenderingStrategy
import kotlin.jvm.JvmSynthetic
/**
* This class can be used as a base class for creating [ComponentBuilder]s.
* If your component has text use [ComponentWithTextBuilder] instead.
*/
@Suppress("UNCHECKED_CAST", "UNUSED_PARAMETER")
abstract class BaseComponentBuilder<T : Component, U : ComponentBuilder<T, U>>(
initialRenderer: ComponentRenderer<out T>
) : ComponentBuilder<T, U> {
override var name: String = ""
protected var props: CommonComponentProperties<T> = CommonComponentProperties(
componentRenderer = initialRenderer
)
private set
override var alignment: AlignmentStrategy
get() = props.alignmentStrategy
set(value) {
props.alignmentStrategy = value
}
override var preferredSize: Size
get() = props.preferredSize
set(value) {
if (preferredContentSize.isNotUnknown) {
preferredContentSize = Size.unknown()
}
props.preferredSize = value
}
override var preferredContentSize: Size
get() = props.preferredContentSize
set(value) {
if (preferredSize.isNotUnknown) {
preferredSize = Size.unknown()
}
props.preferredContentSize = value
}
override var decorations: List<ComponentDecorationRenderer>
get() = props.decorationRenderers
set(value) {
props.decorationRenderers = value.reversed()
}
override var updateOnAttach: Boolean
get() = props.updateOnAttach
set(value) {
props.updateOnAttach = value
}
override var componentRenderer: ComponentRenderer<out T>
get() = props.componentRenderer
set(value) {
props.componentRenderer = value
}
// properties
override val colorThemeProperty: Property<ColorTheme>
get() = props.themeProperty
override var colorTheme: ColorTheme
get() = props.theme
set(value) {
props.theme = value
}
override val componentStyleSetProperty: Property<ComponentStyleSet>
get() = props.componentStyleSetProperty
override var componentStyleSet: ComponentStyleSet
get() = props.componentStyleSet
set(value) {
props.componentStyleSet = value
}
override val tilesetProperty: Property<TilesetResource>
get() = props.tilesetProperty
override var tileset: TilesetResource
get() = props.tileset
set(value) {
props.tileset = value
}
override val disabledProperty: Property<Boolean>
get() = props.disabledProperty
override var isDisabled: Boolean
get() = props.isDisabled
set(value) {
props.isDisabled = value
}
override val hiddenProperty: Property<Boolean>
get() = props.hiddenProperty
override var isHidden: Boolean
get() = props.isHidden
set(value) {
props.isHidden = value
}
private val logger = LoggerFactory.getLogger(this::class)
private val subscriptionFutures = mutableListOf<SubscriptionFuture>()
override fun handleComponentEvents(
eventType: ComponentEventType,
handler: (event: ComponentEvent) -> UIEventResponse
): Subscription = SubscriptionFuture {
it.handleComponentEvents(eventType, handler)
}.apply {
subscriptionFutures.add(this)
}
override fun processComponentEvents(
eventType: ComponentEventType,
handler: (event: ComponentEvent) -> Unit
): Subscription = SubscriptionFuture {
it.processComponentEvents(eventType, handler)
}.apply {
subscriptionFutures.add(this)
}
protected fun T.attachListeners(): T {
subscriptionFutures.forEach {
it.complete(this)
}
return this
}
protected fun createRenderingStrategy() = DefaultComponentRenderingStrategy(
decorationRenderers = decorations,
componentRenderer = componentRenderer as ComponentRenderer<T>,
componentPostProcessors = props.postProcessors
)
protected open fun createMetadata(): ComponentMetadata {
if (updateOnAttach.not()) {
require(tileset.isNotUnknown) {
"When not updating on attach a component must have its own tileset."
}
require(colorTheme.isNotUnknown || componentStyleSet.isNotUnknown) {
"When not updating on attach a component must either have its own theme or component style set"
}
}
return ComponentMetadata(
relativePosition = position,
size = size,
name = name,
updateOnAttach = updateOnAttach,
themeProperty = colorThemeProperty,
componentStyleSetProperty = componentStyleSetProperty,
tilesetProperty = tilesetProperty,
hiddenProperty = hiddenProperty,
disabledProperty = disabledProperty
)
}
protected fun fixContentSizeFor(length: Int) {
if (length doesntFitWithin contentSize) {
this.preferredContentSize = Size.create(length, 1)
}
}
protected infix fun Size.fitsWithin(other: Size) = other.toRect().containsBoundable(toRect())
private infix fun Int.doesntFitWithin(size: Size) = this > size.width * size.height
@JvmSynthetic
internal fun withProps(props: CommonComponentProperties<T>): U {
this.props = props
return this as U
}
/**
* This [Subscription] can be used as an adapter between a [Component]
* that will be created by this [ComponentBuilder] and the component
* event listeners created by the user.
*/
private class SubscriptionFuture(
private val onComponentCreated: (Component) -> Subscription
) : Subscription {
private var delegate: Subscription? = null
private var futureDisposeState: DisposeState? = null
override val disposeState: DisposeState
get() = delegate?.disposeState ?: NotDisposed
override fun dispose(disposeState: DisposeState) {
futureDisposeState = disposeState
delegate?.dispose(disposeState)
}
fun complete(component: Component) {
delegate = onComponentCreated(component)
}
}
}
| apache-2.0 | 765da4cc70e9afe64adae21689956b6c | 33.96347 | 111 | 0.678595 | 5.044137 | false | false | false | false |
crashlytics/18thScale | app/src/main/java/com/firebase/hackweek/tank18thscale/DeviceListAdapter.kt | 1 | 2658 | package com.firebase.hackweek.tank18thscale
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.firebase.hackweek.tank18thscale.model.DeviceInfo
class DeviceListAdapter(private val deviceClickListener: DeviceClickListener) : RecyclerView.Adapter<DeviceListAdapter.DeviceInfoViewHolder>() {
interface DeviceClickListener {
fun onItemClick(deviceInfo: DeviceInfo)
}
private var devices = mutableListOf<DeviceInfo>()
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): DeviceInfoViewHolder {
val deviceView = LayoutInflater.from(parent.context).inflate(R.layout.device_list_item, parent, false)
return DeviceInfoViewHolder(deviceView)
}
override fun getItemCount(): Int {
return devices.size
}
override fun onBindViewHolder(holder: DeviceInfoViewHolder, position: Int) {
holder.bind(devices[position], deviceClickListener)
}
fun setDevices(newDevices: List<DeviceInfo>) {
val diffCallback = DevicesDiffCallback(devices, newDevices)
val diffResult = DiffUtil.calculateDiff(diffCallback)
devices.clear()
devices.addAll(newDevices)
diffResult.dispatchUpdatesTo(this)
}
class DeviceInfoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
private val deviceNameView: TextView = itemView.findViewById(R.id.device_name)
private val deviceAddressView: TextView = itemView.findViewById(R.id.device_address)
fun bind(deviceInfo: DeviceInfo, deviceClickListener: DeviceClickListener) {
deviceNameView.text = deviceInfo.name
deviceAddressView.text = deviceInfo.address
itemView.setOnClickListener { deviceClickListener.onItemClick(deviceInfo) }
}
}
class DevicesDiffCallback(private val oldList: List<DeviceInfo>, private val newList: List<DeviceInfo>) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].address == newList[newItemPosition].address
}
override fun getOldListSize(): Int {
return oldList.size
}
override fun getNewListSize(): Int {
return newList.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
}
}
| apache-2.0 | 15d81e2634b2bc934410fde1e519ef1e | 33.973684 | 144 | 0.716704 | 5.232283 | false | false | false | false |
Turbo87/intellij-rust | src/main/kotlin/org/rust/lang/RustFileType.kt | 1 | 665 | package org.rust.lang
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import org.rust.ide.icons.RustIcons
import javax.swing.Icon
object RustFileType : LanguageFileType(RustLanguage) {
public object DEFAULTS {
public val EXTENSION: String = "rs";
}
override fun getName(): String = "Rust"
override fun getIcon(): Icon = RustIcons.RUST;
override fun getDefaultExtension(): String = DEFAULTS.EXTENSION
override fun getCharset(file: VirtualFile, content: ByteArray): String =
"UTF-8"
override fun getDescription(): String {
return "Rust Files"
}
}
| mit | 5df26186ef450e1a369392dfeb735dfd | 23.62963 | 76 | 0.708271 | 4.463087 | false | false | false | false |
qoncept/TensorKotlin | test/jp/co/qoncept/tensorkotlin/TestUtils.kt | 1 | 967 | package jp.co.qoncept.tensorkotlin
internal fun floatArrayOf(vararg elements: Int): FloatArray {
val result = FloatArray(elements.size)
for (i in elements.indices) {
result[i] = elements[i].toFloat()
}
return result
}
internal fun measureBlock(procedure: () -> Unit) {
run {
val element = Thread.currentThread().stackTrace[2]
println("measureBlock: ${element.className}\$${element.methodName}")
}
val N = 10
var total: Long = 0
for (i in 1..N) {
val begin = System.currentTimeMillis()
procedure()
val end = System.currentTimeMillis()
val elapsed = end - begin
println("${i}: ${elapsed / 1000.0} [s]")
total += elapsed
}
println("avg: ${total / 1000.0 / N} [s]")
println()
}
internal fun naturalNumbers(n: Int): FloatArray {
val result = FloatArray(n)
for (i in 0 until n) {
result[i] = i.toFloat()
}
return result
} | mit | 93b519a1a6e9e3f2d57cedf1710726dd | 22.609756 | 76 | 0.592554 | 3.91498 | false | false | false | false |
mdaniel/intellij-community | jvm/jvm-analysis-kotlin-tests/testSrc/com/intellij/codeInspection/tests/kotlin/test/junit/KotlinJUnitMalformedDeclarationInspectionTest.kt | 1 | 45117 | package com.intellij.codeInspection.tests.kotlin.test.junit
import com.intellij.codeInspection.tests.ULanguage
import com.intellij.codeInspection.tests.test.junit.JUnitMalformedDeclarationInspectionTestBase
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ModifiableRootModel
import com.intellij.testFramework.LightProjectDescriptor
import com.intellij.testFramework.PsiTestUtil
import com.intellij.util.PathUtil
import java.io.File
class KotlinJUnitMalformedDeclarationInspectionTest : JUnitMalformedDeclarationInspectionTestBase() {
override fun getProjectDescriptor(): LightProjectDescriptor = object : JUnitProjectDescriptor(sdkLevel) {
override fun configureModule(module: Module, model: ModifiableRootModel, contentEntry: ContentEntry) {
super.configureModule(module, model, contentEntry)
val jar = File(PathUtil.getJarPathForClass(JvmStatic::class.java))
PsiTestUtil.addLibrary(model, "kotlin-stdlib", jar.parent, jar.name)
}
}
/* Malformed extensions */
fun `test malformed extension no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class A {
@org.junit.jupiter.api.extension.RegisterExtension
val myRule5 = Rule5()
class Rule5 : org.junit.jupiter.api.extension.Extension { }
}
""".trimIndent())
}
fun `test malformed extension highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class A {
@org.junit.jupiter.api.extension.RegisterExtension
val <warning descr="'A.Rule5' should implement 'org.junit.jupiter.api.extension.Extension'">myRule5</warning> = Rule5()
class Rule5 { }
}
""".trimIndent())
}
/* Malformed nested class */
fun `test malformed nested no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class A {
@org.junit.jupiter.api.Nested
inner class B { }
}
""".trimIndent())
}
fun `test malformed nested class highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class A {
@org.junit.jupiter.api.Nested
class <warning descr="Only non-static nested classes can serve as '@Nested' test classes">B</warning> { }
}
""".trimIndent())
}
/* Malformed parameterized */
fun `test malformed parameterized no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
enum class TestEnum { FIRST, SECOND, THIRD }
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(ints = [1])
fun testWithIntValues(i: Int) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(longs = [1L])
fun testWithIntValues(i: Long) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(doubles = [0.5])
fun testWithDoubleValues(d: Double) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = [""])
fun testWithStringValues(s: String) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["foo"])
fun implicitParameter(argument: String, testReporter: org.junit.jupiter.api.TestInfo) { }
@org.junit.jupiter.api.extension.ExtendWith(org.junit.jupiter.api.extension.TestExecutionExceptionHandler::class)
annotation class RunnerExtension { }
@RunnerExtension
abstract class AbstractValueSource { }
class ValueSourcesWithCustomProvider : AbstractValueSource() {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(ints = [1])
fun testWithIntValues(i: Int, fromExtension: String) { }
}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["FIRST"])
fun implicitConversionEnum(e: TestEnum) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["1"])
fun implicitConversionString(i: Int) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["title"])
fun implicitConversionClass(book: Book) { }
class Book(val title: String) { }
}
class MethodSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("stream")
fun simpleStream(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("iterable")
fun simpleIterable(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["stream", "iterator", "iterable"])
fun parametersArray(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["stream", "iterator"])
fun implicitValueArray(x: Int, y: Int) { System.out.println("${'$'}x, ${'$'}y") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["argumentsArrayProvider"])
fun argumentsArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["anyArrayProvider"])
fun anyArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(value = ["any2DArrayProvider"])
fun any2DArray(x: Int, s: String) { System.out.println("${'$'}x, ${'$'}s") }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("intStreamProvider")
fun intStream(x: Int) { System.out.println(x) }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("intStreamProvider")
fun injectTestReporter(x: Int, testReporter: org.junit.jupiter.api.TestReporter) {
System.out.println("${'$'}x, ${'$'}testReporter")
}
companion object {
@JvmStatic
fun stream(): java.util.stream.Stream<org.junit.jupiter.params.provider.Arguments>? { return null }
@JvmStatic
fun iterable(): Iterable<org.junit.jupiter.params.provider.Arguments>? { return null }
@JvmStatic
fun argumentsArrayProvider(): Array<org.junit.jupiter.params.provider.Arguments> {
return arrayOf(org.junit.jupiter.params.provider.Arguments.of(1, "one"))
}
@JvmStatic
fun anyArrayProvider(): Array<Any> { return arrayOf(org.junit.jupiter.params.provider.Arguments.of(1, "one")) }
@JvmStatic
fun any2DArrayProvider(): Array<Array<Any>> { return arrayOf(arrayOf(1, "s")) }
@JvmStatic
fun intStreamProvider(): java.util.stream.IntStream? { return null }
}
}
@org.junit.jupiter.api.TestInstance(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS)
class TestWithMethodSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("getParameters")
public fun shouldExecuteWithParameterizedMethodSource(arguments: String) { }
public fun getParameters(): java.util.stream.Stream<String> { return java.util.Arrays.asList( "Another execution", "Last execution").stream() }
}
class EnumSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(names = ["FIRST"])
fun runTest(value: TestEnum) { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(
value = TestEnum::class,
names = ["regexp-value"],
mode = org.junit.jupiter.params.provider.EnumSource.Mode.MATCH_ALL
)
fun disable() { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(value = TestEnum::class, names = ["SECOND", "FIRST"/*, "commented"*/])
fun array() { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(TestEnum::class)
fun testWithEnumSourceCorrect(value: TestEnum) { }
}
class CsvSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvSource(value = ["src, 1"])
fun testWithCsvSource(first: String, second: Int) { }
}
class NullSource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.NullSource
fun testWithNullSrc(o: Any) { }
}
class EmptySource {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EmptySource
fun testFooSet(input: Set<String>) {}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EmptySource
fun testFooList(input: List<String>) {}
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EmptySource
fun testFooMap(input: Map<String, String>) {}
}
""".trimIndent()
)
}
fun `test malformed parameterized value source wrong type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(booleans = [
<warning descr="No implicit conversion found to convert 'boolean' to 'int'">false</warning>
])
fun testWithBooleanSource(argument: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized enum source wrong type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
enum class TestEnum { FIRST, SECOND, THIRD }
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(<warning descr="No implicit conversion found to convert 'TestEnum' to 'int'">TestEnum::class</warning>)
fun testWithEnumSource(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized multiple types`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.<warning descr="Exactly one type of input must be provided">ValueSource</warning>(
ints = [1], strings = ["str"]
)
fun testWithMultipleValues(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized no value defined`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.<warning descr="No value source is defined">ValueSource</warning>()
fun testWithNoValues(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized no argument defined`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
<warning descr="'@NullSource' cannot provide an argument to method because method doesn't have parameters">@org.junit.jupiter.params.provider.NullSource</warning>
fun testWithNullSrcNoParam() {}
}
""".trimIndent())
}
fun `test malformed parameterized value source multiple parameters`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(strings = ["foo"])
fun <warning descr="Multiple parameters are not supported by this source">testWithMultipleParams</warning>(argument: String, i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized and test annotation defined`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ValueSource(ints = [1])
@org.junit.jupiter.api.Test
fun <warning descr="Suspicious combination of '@Test' and '@ParameterizedTest'">testWithTestAnnotation</warning>(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized and value source defined`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.provider.ValueSource(ints = [1])
@org.junit.jupiter.api.Test
fun <warning descr="Suspicious combination of '@ValueSource' and '@Test'">testWithTestAnnotationNoParameterized</warning>(i: Int) { }
}
""".trimIndent())
}
fun `test malformed parameterized no argument source provided`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.ArgumentsSources()
fun <warning descr="No sources are provided, the suite would be empty">emptyArgs</warning>(param: String) { }
}
""".trimIndent())
}
fun `test malformed parameterized method source should be static`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("<warning descr="Method source 'a' must be static">a</warning>")
fun foo(param: String) { }
fun a(): Array<String> { return arrayOf("a", "b") }
}
""".trimIndent())
}
fun `test malformed parameterized method source should have no parameters`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("<warning descr="Method source 'a' should have no parameters">a</warning>")
fun foo(param: String) { }
companion object {
@JvmStatic
fun a(i: Int): Array<String> { return arrayOf("a", i.toString()) }
}
}
""".trimIndent())
}
fun `test malformed parameterized method source wrong return type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource(
"<warning descr="Method source 'a' must have one of the following return types: 'Stream<?>', 'Iterator<?>', 'Iterable<?>' or 'Object[]'">a</warning>"
)
fun foo(param: String) { }
companion object {
@JvmStatic
fun a(): Any { return arrayOf("a", "b") }
}
}
""".trimIndent())
}
fun `test malformed parameterized method source not found`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class ValueSourcesTest {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.MethodSource("<warning descr="Cannot resolve target method source: 'a'">a</warning>")
fun foo(param: String) { }
}
""".trimIndent())
}
fun `test malformed parameterized enum source unresolvable entry`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class EnumSourceTest {
private enum class Foo { AAA, AAX, BBB }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(
value = Foo::class,
names = ["<warning descr="Can't resolve 'enum' constant reference.">invalid-value</warning>"],
mode = org.junit.jupiter.params.provider.EnumSource.Mode.INCLUDE
)
fun invalid() { }
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.EnumSource(
value = Foo::class,
names = ["<warning descr="Can't resolve 'enum' constant reference.">invalid-value</warning>"]
)
fun invalidDefault() { }
}
""".trimIndent())
}
fun `test malformed parameterized add test instance quick fix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream;
class Test {
private fun parameters(): Stream<Arguments>? { return null; }
@MethodSource("param<caret>eters")
@ParameterizedTest
fun foo(param: String) { }
}
""".trimIndent(), """
import org.junit.jupiter.api.TestInstance
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream;
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class Test {
private fun parameters(): Stream<Arguments>? { return null; }
@MethodSource("param<caret>eters")
@ParameterizedTest
fun foo(param: String) { }
}
""".trimIndent(), "Annotate as @TestInstance")
}
fun `test malformed parameterized introduce method source quick fix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.MethodSource
class Test {
@MethodSource("para<caret>meters")
@ParameterizedTest
fun foo(param: String) { }
}
""".trimIndent(), """
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import java.util.stream.Stream
class Test {
@MethodSource("parameters")
@ParameterizedTest
fun foo(param: String) { }
companion object {
@JvmStatic
fun parameters(): Stream<Arguments> {
TODO("Not yet implemented")
}
}
}
""".trimIndent(), "Add method 'parameters' to 'Test'")
}
fun `test malformed parameterized create csv source quick fix`() {
val file = myFixture.addFileToProject("CsvFile.kt", """
class CsvFile {
@org.junit.jupiter.params.ParameterizedTest
@org.junit.jupiter.params.provider.CsvFileSource(resources = "two-<caret>column.txt")
fun testWithCsvFileSource(first: String, second: Int) { }
}
""".trimIndent())
myFixture.configureFromExistingVirtualFile(file.virtualFile)
val intention = myFixture.findSingleIntention("Create file two-column.txt")
assertNotNull(intention)
myFixture.launchAction(intention)
assertNotNull(myFixture.findFileInTempDir("two-column.txt"))
}
/* Malformed repeated test*/
fun `test malformed repeated test no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
object WithRepeated {
@org.junit.jupiter.api.RepeatedTest(1)
fun repeatedTestNoParams() { }
@org.junit.jupiter.api.RepeatedTest(1)
fun repeatedTestWithRepetitionInfo(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
@org.junit.jupiter.api.BeforeEach
fun config(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
}
class WithRepeatedAndCustomNames {
@org.junit.jupiter.api.RepeatedTest(value = 1, name = "{displayName} {currentRepetition}/{totalRepetitions}")
fun repeatedTestWithCustomName() { }
}
class WithRepeatedAndTestInfo {
@org.junit.jupiter.api.BeforeEach
fun beforeEach(testInfo: org.junit.jupiter.api.TestInfo, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {}
@org.junit.jupiter.api.RepeatedTest(1)
fun repeatedTestWithTestInfo(testInfo: org.junit.jupiter.api.TestInfo) { }
@org.junit.jupiter.api.AfterEach
fun afterEach(testInfo: org.junit.jupiter.api.TestInfo, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {}
}
class WithRepeatedAndTestReporter {
@org.junit.jupiter.api.BeforeEach
fun beforeEach(testReporter: org.junit.jupiter.api.TestReporter, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {}
@org.junit.jupiter.api.RepeatedTest(1)
fun repeatedTestWithTestInfo(testReporter: org.junit.jupiter.api.TestReporter) { }
@org.junit.jupiter.api.AfterEach
fun afterEach(testReporter: org.junit.jupiter.api.TestReporter, repetitionInfo: org.junit.jupiter.api.RepetitionInfo) {}
}
""".trimIndent())
}
fun `test malformed repeated test combination of @Test and @RepeatedTest`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class WithRepeatedAndTests {
@org.junit.jupiter.api.Test
@org.junit.jupiter.api.RepeatedTest(1)
fun <warning descr="Suspicious combination of '@Test' and '@RepeatedTest'">repeatedTestAndTest</warning>() { }
}
""".trimIndent())
}
fun `test malformed repeated test with injected RepeatedInfo for @Test method`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class WithRepeatedInfoAndTest {
@org.junit.jupiter.api.BeforeEach
fun beforeEach(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
@org.junit.jupiter.api.Test
fun <warning descr="Method 'nonRepeated' annotated with '@Test' should not declare parameter 'repetitionInfo'">nonRepeated</warning>(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
}
""".trimIndent() )
}
fun `test malformed repeated test with injected RepetitionInfo for @BeforeAll method`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class WithBeforeEach {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun <warning descr="Method 'beforeAllWithRepetitionInfo' annotated with '@BeforeAll' should not declare parameter 'repetitionInfo'">beforeAllWithRepetitionInfo</warning>(repetitionInfo: org.junit.jupiter.api.RepetitionInfo) { }
}
}
""".trimIndent())
}
fun `test malformed repeated test with non-positive repetitions`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class WithRepeated {
@org.junit.jupiter.api.RepeatedTest(<warning descr="The number of repetitions must be greater than zero">-1</warning>)
fun repeatedTestNegative() { }
@org.junit.jupiter.api.RepeatedTest(<warning descr="The number of repetitions must be greater than zero">0</warning>)
fun repeatedTestBoundaryZero() { }
}
""".trimIndent())
}
/* Malformed before after */
fun `test malformed before highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.Before
fun <warning descr="Method 'before' annotated with '@Before' should be of type 'void' and not declare parameter 'i'">before</warning>(i: Int): String { return "${'$'}i" }
}
""".trimIndent())
}
fun `test malformed before each highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.jupiter.api.BeforeEach
fun <warning descr="Method 'beforeEach' annotated with '@BeforeEach' should be of type 'void' and not declare parameter 'i'">beforeEach</warning>(i: Int): String { return "" }
}
""".trimIndent())
}
fun `test malformed before each remove private quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class MainTest {
@org.junit.jupiter.api.BeforeEach
private fun bef<caret>oreEach() { }
}
""".trimIndent(), """
import org.junit.jupiter.api.BeforeEach
class MainTest {
@BeforeEach
fun bef<caret>oreEach(): Unit { }
}
""".trimIndent(), "Fix 'beforeEach' method signature")
}
fun `test malformed before class no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class BeforeClassStatic {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun beforeClass() { }
}
}
@org.junit.jupiter.api.TestInstance(org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS)
class BeforeAllTestInstancePerClass {
@org.junit.jupiter.api.BeforeAll
fun beforeAll() { }
}
class BeforeAllStatic {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll() { }
}
}
class TestParameterResolver : org.junit.jupiter.api.extension.ParameterResolver {
override fun supportsParameter(
parameterContext: org.junit.jupiter.api.extension.ParameterContext,
extensionContext: org.junit.jupiter.api.extension.ExtensionContext
): Boolean = true
override fun resolveParameter(
parameterContext: org.junit.jupiter.api.extension.ParameterContext,
extensionContext: org.junit.jupiter.api.extension.ExtensionContext
): Any = ""
}
@org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class)
class ParameterResolver {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll(foo: String) { println(foo) }
}
}
@org.junit.jupiter.api.extension.ExtendWith(value = [TestParameterResolver::class])
class ParameterResolverArray {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll(foo: String) { println(foo) }
}
}
@org.junit.jupiter.api.extension.ExtendWith(TestParameterResolver::class)
annotation class CustomTestAnnotation
@CustomTestAnnotation
class MetaParameterResolver {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun beforeAll(foo: String) { println(foo) }
}
}
""".trimIndent())
}
fun `test malformed before class method that is non-static`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.BeforeClass
fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be static">beforeClass</warning>() { }
}
""".trimIndent())
}
fun `test malformed before class method that is not private`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
private fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be public">beforeClass</warning>() { }
}
}
""".trimIndent())
}
fun `test malformed before class method that has parameters`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should not declare parameter 'i'">beforeClass</warning>(i: Int) { System.out.println(i) }
}
}
""".trimIndent())
}
fun `test malformed before class method with a non void return type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.BeforeClass
fun <warning descr="Method 'beforeClass' annotated with '@BeforeClass' should be of type 'void'">beforeClass</warning>(): String { return "" }
}
}
""".trimIndent())
}
fun `test malformed before all method that is non-static`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
@org.junit.jupiter.api.BeforeAll
fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be static">beforeAll</warning>() { }
}
""".trimIndent())
}
fun `test malformed before all method that is not private`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
private fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be public">beforeAll</warning>() { }
}
}
""".trimIndent())
}
fun `test malformed before all method that has parameters`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should not declare parameter 'i'">beforeAll</warning>(i: Int) { System.out.println(i) }
}
}
""".trimIndent())
}
fun `test malformed before all method with a non void return type`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class MainTest {
companion object {
@JvmStatic
@org.junit.jupiter.api.BeforeAll
fun <warning descr="Method 'beforeAll' annotated with '@BeforeAll' should be of type 'void'">beforeAll</warning>(): String { return "" }
}
}
""".trimIndent())
}
fun `test malformed before all quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
import org.junit.jupiter.api.BeforeAll
class MainTest {
@BeforeAll
fun before<caret>All(i: Int): String { return "" }
}
""".trimIndent(), """
import org.junit.jupiter.api.BeforeAll
class MainTest {
companion object {
@JvmStatic
@BeforeAll
fun beforeAll(): Unit {
return ""
}
}
}
""".trimIndent(), "Fix 'beforeAll' method signature")
}
/* Malformed datapoint(s) */
fun `test malformed datapoint no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
companion object {
@JvmField
@org.junit.experimental.theories.DataPoint
val f1: Any? = null
}
}
""".trimIndent())
}
fun `test malformed datapoint non-static highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
@JvmField
@org.junit.experimental.theories.DataPoint
val <warning descr="Field 'f1' annotated with '@DataPoint' should be static">f1</warning>: Any? = null
}
""".trimIndent())
}
fun `test malformed datapoint non-public highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
companion object {
@JvmStatic
@org.junit.experimental.theories.DataPoint
private val <warning descr="Field 'f1' annotated with '@DataPoint' should be public">f1</warning>: Any? = null
}
}
""".trimIndent())
}
fun `test malformed datapoint field highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoint
private val <warning descr="Field 'f1' annotated with '@DataPoint' should be static and public">f1</warning>: Any? = null
}
""".trimIndent())
}
fun `test malformed datapoint method highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoint
private fun <warning descr="Method 'f1' annotated with '@DataPoint' should be static and public">f1</warning>(): Any? = null
}
""".trimIndent())
}
fun `test malformed datapoints method highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoints
private fun <warning descr="Method 'f1' annotated with '@DataPoints' should be static and public">f1</warning>(): Any? = null
}
""".trimIndent())
}
fun `test malformed datapoint make field public quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class Test {
companion object {
@org.junit.experimental.theories.DataPoint
val f<caret>1: Any? = null
}
}
""".trimIndent(), """
class Test {
companion object {
@JvmField
@org.junit.experimental.theories.DataPoint
val f1: Any? = null
}
}
""".trimIndent(), "Fix 'f1' field signature")
}
fun `test malformed datapoint make field public and static quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoint
val f<caret>1: Any? = null
}
""".trimIndent(), """
class Test {
companion object {
@JvmField
@org.junit.experimental.theories.DataPoint
val f1: Any? = null
}
}
""".trimIndent(), "Fix 'f1' field signature")
}
fun `test malformed datapoint make method public and static quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class Test {
@org.junit.experimental.theories.DataPoint
private fun f<caret>1(): Any? = null
}
""".trimIndent(), """
class Test {
companion object {
@JvmStatic
@org.junit.experimental.theories.DataPoint
fun f1(): Any? = null
}
}
""".trimIndent(), "Fix 'f1' method signature")
}
/* Malformed setup/teardown */
fun `test malformed setup no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class C : junit.framework.TestCase() {
override fun setUp() { }
}
""".trimIndent())
}
fun `test malformed setup highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class C : junit.framework.TestCase() {
private fun <warning descr="Method 'setUp' should be a non-private, non-static, have no parameters and be of type void">setUp</warning>(i: Int) { System.out.println(i) }
}
""".trimIndent())
}
fun `test malformed setup quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class C : junit.framework.TestCase() {
private fun set<caret>Up(i: Int) { }
}
""".trimIndent(), """
class C : junit.framework.TestCase() {
fun setUp(): Unit { }
}
""".trimIndent(), "Fix 'setUp' method signature")
}
/* Malformed rule */
fun `test malformed rule field non-public highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
class PrivateRule {
@org.junit.Rule
var <warning descr="Field 'x' annotated with '@Rule' should be public">x</warning> = SomeTestRule()
}
""".trimIndent())
}
fun `test malformed rule object inherited rule highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object OtherRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object ObjRule {
@org.junit.Rule
private var <warning descr="Field 'x' annotated with '@Rule' should be non-static and public">x</warning> = SomeTestRule()
}
class ClazzRule {
@org.junit.Rule
fun x() = OtherRule
@org.junit.Rule
fun <warning descr="Method 'y' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">y</warning>() = 0
@org.junit.Rule
public fun z() = object : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
@org.junit.Rule
public fun <warning descr="Method 'a' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">a</warning>() = object { }
}
""".trimIndent())
}
fun `test malformed rule method static highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
class PrivateRule {
@org.junit.Rule
private fun <warning descr="Method 'x' annotated with '@Rule' should be public">x</warning>() = SomeTestRule()
}
""".trimIndent())
}
fun `test malformed rule method non TestRule type highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class PrivateRule {
@org.junit.Rule
fun <warning descr="Method 'x' annotated with '@Rule' should be of type 'org.junit.rules.TestRule'">x</warning>() = 0
}
""".trimIndent())
}
fun `test malformed class rule field highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object PrivateClassRule {
@org.junit.ClassRule
private var <warning descr="Field 'x' annotated with '@ClassRule' should be public">x</warning> = SomeTestRule()
@org.junit.ClassRule
private var <warning descr="Field 'y' annotated with '@ClassRule' should be public and be of type 'org.junit.rules.TestRule'">y</warning> = 0
}
""".trimIndent())
}
fun `test malformed rule make field public quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class PrivateRule {
@org.junit.Rule
var x<caret> = 0
}
""".trimIndent(), """
class PrivateRule {
@JvmField
@org.junit.Rule
var x = 0
}
""".trimIndent(), "Fix 'x' field signature")
}
fun `test malformed class rule make field public quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object PrivateClassRule {
@org.junit.ClassRule
private var x<caret> = SomeTestRule()
}
""".trimIndent(), """
class SomeTestRule : org.junit.rules.TestRule {
override fun apply(base: org.junit.runners.model.Statement, description: org.junit.runner.Description): org.junit.runners.model.Statement = base
}
object PrivateClassRule {
@JvmField
@org.junit.ClassRule
var x = SomeTestRule()
}
""".trimIndent(), "Fix 'x' field signature")
}
/* Malformed test */
fun `test malformed test for JUnit 3 highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
public class JUnit3TestMethodIsPublicVoidNoArg : junit.framework.TestCase() {
fun testOne() { }
public fun <warning descr="Method 'testTwo' should be a public, non-static, have no parameters and be of type void">testTwo</warning>(): Int { return 2 }
public fun <warning descr="Method 'testFour' should be a public, non-static, have no parameters and be of type void">testFour</warning>(i: Int) { println(i) }
public fun testFive() { }
private fun testSix(i: Int) { println(i) } //ignore when method doesn't look like test anymore
companion object {
@JvmStatic
public fun <warning descr="Method 'testThree' should be a public, non-static, have no parameters and be of type void">testThree</warning>() { }
}
}
""".trimIndent())
}
fun `test malformed test for JUnit 4 highlighting`() {
myFixture.addClass("""
package mockit;
public @interface Mocked { }
""".trimIndent())
myFixture.testHighlighting(ULanguage.KOTLIN, """
public class JUnit4TestMethodIsPublicVoidNoArg {
@org.junit.Test fun testOne() { }
@org.junit.Test public fun <warning descr="Method 'testTwo' annotated with '@Test' should be of type 'void'">testTwo</warning>(): Int { return 2 }
@org.junit.Test public fun <warning descr="Method 'testFour' annotated with '@Test' should not declare parameter 'i'">testFour</warning>(i: Int) { }
@org.junit.Test public fun testFive() { }
@org.junit.Test public fun testMock(@mockit.Mocked s: String) { }
companion object {
@JvmStatic
@org.junit.Test public fun <warning descr="Method 'testThree' annotated with '@Test' should be non-static">testThree</warning>() { }
}
}
""".trimIndent())
}
fun `test malformed test for JUnit 4 runWith highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
@org.junit.runner.RunWith(org.junit.runner.Runner::class)
class JUnit4RunWith {
@org.junit.Test public fun <warning descr="Method 'testMe' annotated with '@Test' should be of type 'void' and not declare parameter 'i'">testMe</warning>(i: Int): Int { return -1 }
}
""".trimIndent())
}
/* Malformed suite */
fun `test malformed suite no highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Junit3Suite : junit.framework.TestCase() {
companion object {
@JvmStatic
fun suite() = junit.framework.TestSuite()
}
}
""".trimIndent())
}
fun `test malformed suite highlighting`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class Junit3Suite : junit.framework.TestCase() {
fun <warning descr="Method 'suite' should be a non-private, static and have no parameters">suite</warning>() = junit.framework.TestSuite()
}
""".trimIndent())
}
fun `test malformed suite quickfix`() {
myFixture.testQuickFix(ULanguage.KOTLIN, """
class Junit3Suite : junit.framework.TestCase() {
fun sui<caret>te() = junit.framework.TestSuite()
}
""".trimIndent(), """
class Junit3Suite : junit.framework.TestCase() {
companion object {
@JvmStatic
fun suite() = junit.framework.TestSuite()
}
}
""".trimIndent(), "Fix 'suite' method signature")
}
/* Suspending test function */
fun `test malformed suspending test JUnit 3 function`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class JUnit3Test : junit.framework.TestCase() {
suspend fun <warning descr="Method 'testFoo' should not be a suspending function">testFoo</warning>() { }
}
""".trimIndent())
}
fun `test malformed suspending test JUnit 4 function`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class JUnit4Test {
@org.junit.Test
suspend fun <warning descr="Method 'testFoo' annotated with '@Test' should not be a suspending function">testFoo</warning>() { }
}
""".trimIndent())
}
fun `test malformed suspending test JUnit 5 function`() {
myFixture.testHighlighting(ULanguage.KOTLIN, """
class JUnit5Test {
@org.junit.jupiter.api.Test
suspend fun <warning descr="Method 'testFoo' annotated with '@Test' should not be a suspending function">testFoo</warning>() { }
}
""".trimIndent())
}
} | apache-2.0 | c2ad25ec6e8e9504a663e13430ba01d6 | 39.500898 | 237 | 0.641377 | 4.607066 | false | true | false | false |
MER-GROUP/intellij-community | platform/script-debugger/protocol/protocol-model-generator/src/TypeMap.kt | 3 | 1376 | package org.jetbrains.protocolModelGenerator
import gnu.trove.THashMap
import java.util.*
/**
* Keeps track of all referenced types.
* A type may be used and resolved (generated or hard-coded).
*/
internal class TypeMap {
private val map = THashMap<Pair<String, String>, TypeData>()
var domainGeneratorMap: Map<String, DomainGenerator>? = null
private val typesToGenerate = ArrayList<StandaloneTypeBinding>()
fun resolve(domainName: String, typeName: String, direction: TypeData.Direction): BoxableType? {
val domainGenerator = domainGeneratorMap!!.get(domainName) ?: throw RuntimeException("Failed to find domain generator: $domainName")
return direction.get(getTypeData(domainName, typeName)).resolve(this, domainGenerator)
}
fun addTypeToGenerate(binding: StandaloneTypeBinding) {
typesToGenerate.add(binding)
}
fun generateRequestedTypes() {
// size may grow during iteration
var list = typesToGenerate.toTypedArray()
typesToGenerate.clear()
while (true) {
for (binding in list) {
binding.generate()
}
if (typesToGenerate.isEmpty()) {
break
}
else {
list = typesToGenerate.toTypedArray()
typesToGenerate.clear()
}
}
}
fun getTypeData(domainName: String, typeName: String) = map.getOrPut(Pair(domainName, typeName)) { TypeData(typeName) }
}
| apache-2.0 | e7b85cebb8ce58a581fb8c11e6821eec | 28.913043 | 136 | 0.707122 | 4.632997 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/jvm-debugger/test/test/org/jetbrains/kotlin/idea/debugger/test/util/BreakpointCreator.kt | 1 | 10969 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.debugger.test.util
import com.intellij.debugger.DebuggerInvocationUtil
import com.intellij.debugger.engine.evaluation.CodeFragmentKind
import com.intellij.debugger.engine.evaluation.TextWithImportsImpl
import com.intellij.debugger.ui.breakpoints.Breakpoint
import com.intellij.debugger.ui.breakpoints.BreakpointManager
import com.intellij.debugger.ui.breakpoints.LineBreakpoint
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.io.FileUtilRt
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiManager
import com.intellij.psi.search.FilenameIndex
import com.intellij.xdebugger.XDebuggerManager
import com.intellij.xdebugger.XDebuggerUtil
import com.intellij.xdebugger.breakpoints.XBreakpointManager
import com.intellij.xdebugger.breakpoints.XBreakpointProperties
import com.intellij.xdebugger.breakpoints.XBreakpointType
import com.intellij.xdebugger.breakpoints.XLineBreakpointType
import org.jetbrains.java.debugger.breakpoints.properties.JavaBreakpointProperties
import org.jetbrains.java.debugger.breakpoints.properties.JavaLineBreakpointProperties
import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.isKotlinSourceFile
import org.jetbrains.kotlin.idea.debugger.breakpoints.*
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferenceKeys
import org.jetbrains.kotlin.idea.debugger.test.preference.DebuggerPreferences
import org.jetbrains.kotlin.idea.test.InTextDirectivesUtils.findLinesWithPrefixesRemoved
import org.jetbrains.kotlin.idea.util.application.runReadAction
import java.util.*
import javax.swing.SwingUtilities
internal class BreakpointCreator(
private val project: Project,
private val logger: (String) -> Unit,
private val preferences: DebuggerPreferences
) {
fun createBreakpoints(file: PsiFile) {
val document = runReadAction { PsiDocumentManager.getInstance(project).getDocument(file) } ?: return
val breakpointManager = XDebuggerManager.getInstance(project).breakpointManager
val kotlinFieldBreakpointType = findBreakpointType(KotlinFieldBreakpointType::class.java)
val virtualFile = file.virtualFile
val runnable = {
var offset = -1
while (true) {
val fileText = document.text
offset = fileText.indexOf("point!", offset + 1)
if (offset == -1) break
val commentLine = document.getLineNumber(offset)
val lineIndex = commentLine + 1
val comment = fileText
.substring(document.getLineStartOffset(commentLine), document.getLineEndOffset(commentLine))
.trim()
when {
comment.startsWith("//FieldWatchpoint!") -> {
val javaBreakpoint = createBreakpointOfType(
breakpointManager,
kotlinFieldBreakpointType,
lineIndex,
virtualFile
)
(javaBreakpoint as? KotlinFieldBreakpoint)?.apply {
val fieldName = comment.substringAfter("//FieldWatchpoint! (").substringBefore(")")
setFieldName(fieldName)
setWatchAccess(preferences[DebuggerPreferenceKeys.WATCH_FIELD_ACCESS])
setWatchModification(preferences[DebuggerPreferenceKeys.WATCH_FIELD_MODIFICATION])
setWatchInitialization(preferences[DebuggerPreferenceKeys.WATCH_FIELD_INITIALISATION])
BreakpointManager.addBreakpoint(javaBreakpoint)
logger("KotlinFieldBreakpoint created at ${file.virtualFile.name}:${lineIndex + 1}")
}
}
comment.startsWith("//Breakpoint!") -> {
val ordinal = getPropertyFromComment(comment, "lambdaOrdinal")?.toInt()
val condition = getPropertyFromComment(comment, "condition")
createLineBreakpoint(breakpointManager, file, lineIndex, ordinal, condition)
}
comment.startsWith("//FunctionBreakpoint!") -> {
createFunctionBreakpoint(breakpointManager, file, lineIndex, false)
}
else -> throw AssertionError("Cannot create breakpoint at line ${lineIndex + 1}")
}
}
}
if (!SwingUtilities.isEventDispatchThread()) {
DebuggerInvocationUtil.invokeAndWait(project, runnable, ModalityState.defaultModalityState())
} else {
runnable.invoke()
}
}
fun createAdditionalBreakpoints(fileContents: String) {
val breakpoints = findLinesWithPrefixesRemoved(fileContents, "// ADDITIONAL_BREAKPOINT: ")
for (breakpoint in breakpoints) {
val chunks = breakpoint.split('/').map { it.trim() }
val fileName = chunks.getOrNull(0) ?: continue
val lineMarker = chunks.getOrNull(1) ?: continue
val kind = chunks.getOrElse(2) { "line" }
val ordinal = chunks.getOrNull(3)?.toInt()
val breakpointManager = XDebuggerManager.getInstance(project).breakpointManager
when (kind) {
"line" -> createBreakpoint(fileName, lineMarker) { psiFile, lineNumber ->
createLineBreakpoint(breakpointManager, psiFile, lineNumber + 1, ordinal, null)
}
"fun" -> createBreakpoint(fileName, lineMarker) { psiFile, lineNumber ->
createFunctionBreakpoint(breakpointManager, psiFile, lineNumber, true)
}
else -> error("Unknown breakpoint kind: $kind")
}
}
}
private fun getPropertyFromComment(comment: String, propertyName: String): String? {
if (comment.contains("$propertyName = ")) {
val result = comment.substringAfter("$propertyName = ")
if (result.contains(", ")) {
return result.substringBefore(", ")
}
if (result.contains(")")) {
return result.substringBefore(")")
}
return result
}
return null
}
private fun createBreakpoint(fileName: String, lineMarker: String, action: (PsiFile, Int) -> Unit) {
val sourceFiles = runReadAction {
val actualType = FileUtilRt.getExtension(fileName).lowercase(Locale.getDefault())
assert(isKotlinSourceFile(fileName)) {
"Could not set a breakpoint on a non-kt file"
}
FilenameIndex.getAllFilesByExt(project, actualType)
.filter { it.name == fileName && it.contentsToByteArray().toString(Charsets.UTF_8).contains(lineMarker) }
}
val sourceFile = sourceFiles.singleOrNull()
?: error("Single source file should be found: name = $fileName, sourceFiles = $sourceFiles")
val runnable = Runnable {
val psiSourceFile = PsiManager.getInstance(project).findFile(sourceFile)
?: error("Psi file not found for $sourceFile")
val document = PsiDocumentManager.getInstance(project).getDocument(psiSourceFile)!!
val index = psiSourceFile.text!!.indexOf(lineMarker)
val lineNumber = document.getLineNumber(index)
action(psiSourceFile, lineNumber)
}
DebuggerInvocationUtil.invokeAndWait(project, runnable, ModalityState.defaultModalityState())
}
private fun createFunctionBreakpoint(breakpointManager: XBreakpointManager, file: PsiFile, lineIndex: Int, fromLibrary: Boolean) {
val breakpointType = findBreakpointType(KotlinFunctionBreakpointType::class.java)
val breakpoint = createBreakpointOfType(breakpointManager, breakpointType, lineIndex, file.virtualFile)
if (breakpoint is KotlinFunctionBreakpoint) {
val lineNumberSuffix = if (fromLibrary) "" else ":${lineIndex + 1}"
logger("FunctionBreakpoint created at ${file.virtualFile.name}$lineNumberSuffix")
}
}
private fun createLineBreakpoint(
breakpointManager: XBreakpointManager,
file: PsiFile,
lineIndex: Int,
lambdaOrdinal: Int?,
condition: String?
) {
val kotlinLineBreakpointType = findBreakpointType(KotlinLineBreakpointType::class.java)
val javaBreakpoint = createBreakpointOfType(
breakpointManager,
kotlinLineBreakpointType,
lineIndex,
file.virtualFile
)
if (javaBreakpoint is LineBreakpoint<*>) {
val properties = javaBreakpoint.xBreakpoint.properties as? JavaLineBreakpointProperties ?: return
var suffix = ""
if (lambdaOrdinal != null) {
if (lambdaOrdinal != -1) {
properties.lambdaOrdinal = lambdaOrdinal - 1
} else {
properties.lambdaOrdinal = lambdaOrdinal
}
suffix += " lambdaOrdinal = $lambdaOrdinal"
}
if (condition != null) {
javaBreakpoint.setCondition(TextWithImportsImpl(CodeFragmentKind.EXPRESSION, condition))
suffix += " condition = $condition"
}
BreakpointManager.addBreakpoint(javaBreakpoint)
logger("LineBreakpoint created at ${file.virtualFile.name}:${lineIndex + 1}$suffix")
}
}
private fun createBreakpointOfType(
breakpointManager: XBreakpointManager,
breakpointType: XLineBreakpointType<XBreakpointProperties<*>>,
lineIndex: Int,
virtualFile: VirtualFile
): Breakpoint<out JavaBreakpointProperties<*>>? {
if (!breakpointType.canPutAt(virtualFile, lineIndex, project)) return null
val xBreakpoint = runWriteAction {
breakpointManager.addLineBreakpoint(
breakpointType,
virtualFile.url,
lineIndex,
breakpointType.createBreakpointProperties(virtualFile, lineIndex)
)
}
return BreakpointManager.getJavaBreakpoint(xBreakpoint)
}
@Suppress("UNCHECKED_CAST")
private inline fun <reified T : XBreakpointType<*, *>> findBreakpointType(javaClass: Class<T>): XLineBreakpointType<XBreakpointProperties<*>> {
return XDebuggerUtil.getInstance().findBreakpointType(javaClass) as XLineBreakpointType<XBreakpointProperties<*>>
}
}
| apache-2.0 | 256d8d40555658a6d622114c200500e0 | 45.876068 | 147 | 0.64974 | 5.662881 | false | false | false | false |
mdaniel/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/actions/AddDependencyAction.kt | 2 | 4443 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.jetbrains.packagesearch.intellij.plugin.actions
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.LangDataKeys
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiFile
import com.intellij.psi.util.PsiUtilBase
import com.jetbrains.packagesearch.PackageSearchIcons
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.PackageSearchToolWindowFactory
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.ModuleModel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchProjectService
import com.jetbrains.packagesearch.intellij.plugin.util.uiStateModifier
class AddDependencyAction : AnAction(
PackageSearchBundle.message("packagesearch.actions.addDependency.text"),
PackageSearchBundle.message("packagesearch.actions.addDependency.description"),
PackageSearchIcons.Artifact
) {
override fun getActionUpdateThread() = ActionUpdateThread.BGT
override fun update(e: AnActionEvent) {
val project = e.project
val editor = e.getData(CommonDataKeys.EDITOR)
e.presentation.isEnabledAndVisible = project != null
&& editor != null
&& run {
val psiFile: PsiFile? = PsiUtilBase.getPsiFileInEditor(editor, project)
if (psiFile == null || CoroutineProjectModuleOperationProvider.forProjectPsiFileOrNull(project, psiFile) == null) {
return@run false
}
val modules = project.packageSearchProjectService.moduleModelsStateFlow.value
findSelectedModule(e, modules) != null
}
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val modules = project.packageSearchProjectService.moduleModelsStateFlow.value
if (modules.isEmpty()) return
val selectedModule = findSelectedModule(e, modules) ?: return
PackageSearchToolWindowFactory.activateToolWindow(project) {
project.uiStateModifier.setTargetModules(TargetModules.One(selectedModule))
}
}
private fun findSelectedModule(e: AnActionEvent, modules: List<ModuleModel>): ModuleModel? {
val project = e.project ?: return null
val file = obtainSelectedProjectDirIfSingle(e)?.virtualFile ?: return null
val selectedModule = runReadAction { ModuleUtilCore.findModuleForFile(file, project) } ?: return null
// Sanity check that the module we got actually exists
ModuleManager.getInstance(project).findModuleByName(selectedModule.name)
?: return null
return modules.firstOrNull { module -> module.projectModule.nativeModule == selectedModule }
}
private fun obtainSelectedProjectDirIfSingle(e: AnActionEvent): PsiDirectory? {
val dataContext = e.dataContext
val ideView = LangDataKeys.IDE_VIEW.getData(dataContext)
val selectedDirectories = ideView?.directories ?: return null
if (selectedDirectories.size != 1) return null
return selectedDirectories.first()
}
}
| apache-2.0 | f0b95c9726cf77a39ed7c2f3cba9800a | 44.336735 | 127 | 0.731713 | 5.245573 | false | false | false | false |
byu-oit/android-byu-suite-v2 | app/src/main/java/edu/byu/suite/features/galleries/controller/AlbumActivity.kt | 2 | 5953 | package edu.byu.suite.features.galleries.controller
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentStatePagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.widget.GridLayoutManager
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ViewAnimator
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.drawable.GlideDrawable
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import edu.byu.suite.R
import edu.byu.suite.features.galleries.model.ArtworkResponseWrapper
import edu.byu.suite.features.galleries.service.GalleriesClient
import edu.byu.support.ByuClickListener
import edu.byu.support.ByuViewHolder
import edu.byu.support.activity.ByuRecyclerViewActivity
import edu.byu.support.adapter.ByuRecyclerAdapter
import edu.byu.support.retrofit.ByuSuccessCallback
import edu.byu.support.utils.getDisplaySize
import edu.byu.support.utils.inflate
import kotlinx.android.synthetic.main.galleries_activity_album.*
import kotlinx.android.synthetic.main.galleries_activity_album.view.*
import kotlinx.android.synthetic.main.galleries_artwork_card.view.*
import retrofit2.Call
import retrofit2.Response
class AlbumActivity: ByuRecyclerViewActivity() {
companion object {
const val GALLERY_ID = "galleryId"
const val ALBUM_ID = "albumId"
private const val GRID_VIEW_CHILD_INDEX = 0
private const val VIEW_PAGER_CHILD_INDEX = 1
private const val NO_IMAGES_INDEX = 2
private const val NUM_COLUMNS = 3
}
private val pagerAdapter = ArtworkPagerAdapter()
private var viewPager: ViewPager? = null
private var viewAnimator: ViewAnimator? = null
private var fragmentList: List<Fragment> = mutableListOf()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Garbage collect to help make room for bitmaps
System.gc()
setContentView(R.layout.galleries_activity_album)
ArtworkFragment.visibility = View.GONE
recyclerView = image_recycler_view
recyclerView.removeHorizontalLineDivider()
recyclerView.layoutManager = GridLayoutManager(this, NUM_COLUMNS)
recyclerView.adapter = ImageRecyclerAdapter()
viewAnimator = galleries_activity_main.viewAnimator
viewPager = galleries_activity_main.viewPager
viewPager?.adapter = pagerAdapter
showProgressDialog()
loadArtwork(intent.getStringExtra(GALLERY_ID), intent.getStringExtra(ALBUM_ID))
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
onBackPressed()
return true
}
override fun onBackPressed() {
// This makes it so when you press back while viewing an image it goes back to the grid view instead of leaving the activity
if (viewPager?.visibility == View.VISIBLE) {
viewAnimator?.displayedChild = GRID_VIEW_CHILD_INDEX
} else {
super.onBackPressed()
}
}
private fun loadArtwork(galleryId: String, albumId: String) {
enqueueCall(GalleriesClient().getApi(this).getArtwork(galleryId, albumId), object: ByuSuccessCallback<ArtworkResponseWrapper>(this) {
override fun onSuccess(call: Call<ArtworkResponseWrapper>, response: Response<ArtworkResponseWrapper>) {
val artworkList = response.body()?.artworkList as? List<ArtworkResponseWrapper.Artwork>
if (artworkList?.isNotEmpty() == true) {
recyclerView.adapter.list = artworkList
fragmentList = artworkList.map { ArtworkFragment.newInstance(it) }
pagerAdapter.notifyDataSetChanged()
} else {
viewAnimator?.displayedChild = NO_IMAGES_INDEX
}
dismissProgressDialog()
}
})
}
private inner class ImageRecyclerAdapter: ByuRecyclerAdapter<ArtworkResponseWrapper.Artwork>(emptyList(), { _, _, position ->
viewPager?.setCurrentItem(position, false)
viewAnimator?.displayedChild = VIEW_PAGER_CHILD_INDEX
}) {
private var reqWidth: Int
private var reqHeight: Int
init {
// Get the width and height of the screen for thumbnails
val size = getDisplaySize()
reqWidth = size.x / (recyclerView.layoutManager as GridLayoutManager).spanCount
reqHeight = (size.y * (reqWidth.toDouble() / size.x.toDouble())).toInt()
}
private inner class ImageViewHolder(itemView: View): ByuViewHolder<ArtworkResponseWrapper.Artwork>(itemView) {
private var image = itemView.imageView
private var viewSwitcher = itemView.viewSwitcher
override fun bind(data: ArtworkResponseWrapper.Artwork, listener: ByuClickListener<ArtworkResponseWrapper.Artwork>?) {
super.bind(data, listener)
//Glide uses caching so that when this is called after the initial load it pulls the image from the cache instead of making another call to the API
Glide.with(this@AlbumActivity)
.load(data.imageUrl)
.fitCenter()
//Loads only the size of the thumbnail in this call so that we aren't pulling in images that are too large
.override(reqWidth, reqHeight)
.listener(object: RequestListener<String, GlideDrawable> {
override fun onException(e: Exception, model: String, target: Target<GlideDrawable>, isFirstResource: Boolean): Boolean {
viewSwitcher.displayedChild = VIEW_PAGER_CHILD_INDEX
return false
}
override fun onResourceReady(resource: GlideDrawable, model: String, target: Target<GlideDrawable>, isFromMemoryCache: Boolean, isFirstResource: Boolean): Boolean {
viewSwitcher.displayedChild = VIEW_PAGER_CHILD_INDEX
return false
}
})
.error(R.drawable.ic_galleries_broken_image)
.into(image)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ImageViewHolder = ImageViewHolder(inflate(parent, R.layout.galleries_artwork_card))
}
private inner class ArtworkPagerAdapter: FragmentStatePagerAdapter(supportFragmentManager) {
override fun getCount() = recyclerView.adapter.list.size
override fun getItem(position: Int) = fragmentList[position]
}
} | apache-2.0 | 519a1273fbe7043177f044358a7ad04e | 37.412903 | 171 | 0.773728 | 4.177544 | false | false | false | false |
spinnaker/orca | orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/handler/RestartStageHandler.kt | 1 | 5273 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q.handler
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.NOT_STARTED
import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.RUNNING
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.pipeline.StageDefinitionBuilderFactory
import com.netflix.spinnaker.orca.pipeline.model.PipelineTrigger
import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository
import com.netflix.spinnaker.orca.q.RestartStage
import com.netflix.spinnaker.orca.q.StartStage
import com.netflix.spinnaker.orca.q.pending.PendingExecutionService
import com.netflix.spinnaker.q.Queue
import java.time.Clock
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
@Component
class RestartStageHandler(
override val queue: Queue,
override val repository: ExecutionRepository,
override val stageDefinitionBuilderFactory: StageDefinitionBuilderFactory,
private val pendingExecutionService: PendingExecutionService,
private val clock: Clock
) : OrcaMessageHandler<RestartStage>, StageBuilderAware {
override val messageType = RestartStage::class.java
private val log: Logger get() = LoggerFactory.getLogger(javaClass)
override fun handle(message: RestartStage) {
message.withStage { stage ->
// If RestartStage is requested for a synthetic stage, operate on its parent
val topStage = stage.topLevelStage
val startMessage = StartStage(message.executionType, message.executionId, message.application, topStage.id)
if (topStage.status.isComplete || topStage.status == NOT_STARTED) {
topStage.addRestartDetails(message.user)
topStage.reset()
if (stage.execution.shouldQueue()) {
// this pipeline is already running and has limitConcurrent = true
if (topStage.execution.status == NOT_STARTED) {
log.info("Skipping queueing restart of {} {} {}", stage.execution.application, stage.execution.name, stage.execution.id)
return@withStage
}
topStage.execution.updateStatus(NOT_STARTED)
repository.updateStatus(topStage.execution)
stage.execution.pipelineConfigId?.let {
log.info("Queueing restart of {} {} {}", stage.execution.application, stage.execution.name, stage.execution.id)
pendingExecutionService.enqueue(it, message)
}
} else {
restartParentPipelineIfNeeded(message, topStage)
topStage.execution.updateStatus(RUNNING)
repository.updateStatus(topStage.execution)
queue.push(StartStage(startMessage))
}
}
}
}
private fun restartParentPipelineIfNeeded(message: RestartStage, topStage: StageExecution) {
if (topStage.execution.trigger !is PipelineTrigger) {
return
}
val trigger = topStage.execution.trigger as PipelineTrigger
if (trigger.parentPipelineStageId == null) {
// Must've been triggered by dependent pipeline, we don't restart those
return
}
// We have a copy of the parent execution, not the live one. So we retrieve the live one.
val parentExecution = repository.retrieve(trigger.parentExecution.type, trigger.parentExecution.id)
if (!parentExecution.status.isComplete()) {
// only attempt to restart the parent pipeline if it's not running
return
}
val parentStage = parentExecution.stageById(trigger.parentPipelineStageId)
parentStage.addSkipRestart()
repository.storeStage(parentStage)
queue.push(RestartStage(trigger.parentExecution, parentStage.id, message.user))
}
/**
* Inform the parent stage when it restarts that the child is already running
*/
private fun StageExecution.addSkipRestart() {
context["_skipPipelineRestart"] = true
}
private fun StageExecution.addRestartDetails(user: String?) {
context["restartDetails"] = mapOf(
"restartedBy" to (user ?: "anonymous"),
"restartTime" to clock.millis(),
"previousException" to context.remove("exception")
)
}
private fun StageExecution.reset() {
if (status.isComplete) {
status = NOT_STARTED
startTime = null
endTime = null
tasks = emptyList()
builder().prepareStageForRestart(this)
repository.storeStage(this)
removeSynthetics()
}
downstreamStages().forEach { it.reset() }
}
private fun StageExecution.removeSynthetics() {
execution
.stages
.filter { it.parentStageId == id }
.forEach {
it.removeSynthetics()
repository.removeStage(execution, it.id)
}
}
}
| apache-2.0 | 59097f401aa2acd996a9e06fc51473b8 | 36.133803 | 132 | 0.724825 | 4.506838 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/RenameKotlinFunctionProcessor.kt | 1 | 12289 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.rename
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Pass
import com.intellij.psi.*
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.listeners.RefactoringElementListener
import com.intellij.refactoring.rename.*
import com.intellij.refactoring.util.CommonRefactoringUtil
import com.intellij.refactoring.util.RefactoringUtil
import com.intellij.usageView.UsageInfo
import com.intellij.util.SmartList
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.elements.KtLightElement
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.asJava.namedUnwrappedElement
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.codegen.state.KotlinTypeMapper
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.unsafeResolveToDescriptor
import org.jetbrains.kotlin.idea.refactoring.*
import org.jetbrains.kotlin.idea.references.KtReference
import org.jetbrains.kotlin.idea.search.declarationsSearch.findDeepestSuperMethodsKotlinAware
import org.jetbrains.kotlin.idea.search.declarationsSearch.findDeepestSuperMethodsNoWrapping
import org.jetbrains.kotlin.idea.search.declarationsSearch.forEachOverridingMethod
import com.intellij.openapi.application.runReadAction
import org.jetbrains.kotlin.idea.util.liftToExpected
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.DescriptorUtils
class RenameKotlinFunctionProcessor : RenameKotlinPsiProcessor() {
private val javaMethodProcessorInstance = RenameJavaMethodProcessor()
override fun canProcessElement(element: PsiElement): Boolean {
return element is KtNamedFunction || (element is KtLightMethod && element.kotlinOrigin is KtNamedFunction) || element is FunctionWithSupersWrapper
}
override fun isToSearchInComments(psiElement: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_METHOD
override fun setToSearchInComments(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_IN_COMMENTS_FOR_METHOD = enabled
}
override fun isToSearchForTextOccurrences(element: PsiElement) = KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_METHOD
override fun setToSearchForTextOccurrences(element: PsiElement, enabled: Boolean) {
KotlinRefactoringSettings.instance.RENAME_SEARCH_FOR_TEXT_FOR_METHOD = enabled
}
private fun getJvmName(element: PsiElement): String? {
val descriptor = (element.unwrapped as? KtFunction)?.unsafeResolveToDescriptor() as? FunctionDescriptor ?: return null
return DescriptorUtils.getJvmName(descriptor)
}
protected fun processFoundReferences(
element: PsiElement,
allReferences: Collection<PsiReference>
): Collection<PsiReference> {
return when {
getJvmName(element) == null -> allReferences
element is KtElement -> allReferences.filterIsInstance<KtReference>()
element is KtLightElement<*, *> -> allReferences.filterNot { it is KtReference }
else -> emptyList()
}
}
override fun findCollisions(
element: PsiElement,
newName: String,
allRenames: Map<out PsiElement, String>,
result: MutableList<UsageInfo>
) {
val declaration = element.unwrapped as? KtNamedFunction ?: return
checkConflictsAndReplaceUsageInfos(element, allRenames, result)
result += SmartList<UsageInfo>().also { collisions ->
checkRedeclarations(declaration, newName, collisions)
checkOriginalUsagesRetargeting(declaration, newName, result, collisions)
checkNewNameUsagesRetargeting(declaration, newName, collisions)
}
}
class FunctionWithSupersWrapper(
val originalDeclaration: KtNamedFunction,
val supers: List<PsiElement>
) : KtLightElement<KtNamedFunction, KtNamedFunction>, PsiNamedElement by originalDeclaration {
override val kotlinOrigin: KtNamedFunction get() = originalDeclaration
}
private fun substituteForExpectOrActual(element: PsiElement?) =
(element?.namedUnwrappedElement as? KtNamedDeclaration)?.liftToExpected()
override fun substituteElementToRename(element: PsiElement, editor: Editor?): PsiElement? {
substituteForExpectOrActual(element)?.let { return it }
val wrappedMethod = wrapPsiMethod(element) ?: return element
val deepestSuperMethods = findDeepestSuperMethodsKotlinAware(wrappedMethod)
val substitutedJavaElement = when {
deepestSuperMethods.isEmpty() -> return element
wrappedMethod.isConstructor || deepestSuperMethods.size == 1 || element !is KtNamedFunction -> {
javaMethodProcessorInstance.substituteElementToRename(wrappedMethod, editor)
}
else -> {
val chosenElements = checkSuperMethods(element, null, KotlinBundle.message("text.rename.as.part.of.phrase"))
if (chosenElements.size > 1) FunctionWithSupersWrapper(element, chosenElements) else wrappedMethod
}
}
if (substitutedJavaElement is KtLightMethod && element is KtDeclaration) {
return substitutedJavaElement.kotlinOrigin as? KtNamedFunction
}
val canRename = try {
PsiElementRenameHandler.canRename(element.project, editor, substitutedJavaElement)
} catch (e: CommonRefactoringUtil.RefactoringErrorHintException) {
false
}
return if (canRename) substitutedJavaElement else element
}
override fun substituteElementToRename(element: PsiElement, editor: Editor, renameCallback: Pass<PsiElement>) {
fun preprocessAndPass(substitutedJavaElement: PsiElement) {
val elementToProcess = if (substitutedJavaElement is KtLightMethod && element is KtDeclaration) {
substitutedJavaElement.kotlinOrigin as? KtNamedFunction
} else {
substitutedJavaElement
}
renameCallback.pass(elementToProcess)
}
substituteForExpectOrActual(element)?.let { return preprocessAndPass(it) }
val wrappedMethod = wrapPsiMethod(element)
val deepestSuperMethods = if (wrappedMethod != null) {
findDeepestSuperMethodsKotlinAware(wrappedMethod)
} else {
findDeepestSuperMethodsNoWrapping(element)
}
when {
deepestSuperMethods.isEmpty() -> preprocessAndPass(element)
wrappedMethod != null && (wrappedMethod.isConstructor || element !is KtNamedFunction) -> {
javaMethodProcessorInstance.substituteElementToRename(wrappedMethod, editor, Pass(::preprocessAndPass))
}
else -> {
val declaration = element.unwrapped as? KtNamedFunction ?: return
checkSuperMethodsWithPopup(declaration, deepestSuperMethods.toList(), editor) {
preprocessAndPass(if (it.size > 1) FunctionWithSupersWrapper(declaration, it) else wrappedMethod ?: element)
}
}
}
}
override fun createRenameDialog(
project: Project,
element: PsiElement,
nameSuggestionContext: PsiElement?,
editor: Editor?
): RenameDialog {
val elementForDialog = (element as? FunctionWithSupersWrapper)?.originalDeclaration ?: element
return object : RenameDialog(project, elementForDialog, nameSuggestionContext, editor) {
override fun createRenameProcessor(newName: String) =
RenameProcessor(getProject(), element, newName, isSearchInComments, isSearchInNonJavaFiles)
}
}
override fun prepareRenaming(element: PsiElement, newName: String, allRenames: MutableMap<PsiElement, String>, scope: SearchScope) {
super.prepareRenaming(element, newName, allRenames, scope)
if (element is KtLightMethod && getJvmName(element) == null) {
(element.kotlinOrigin as? KtNamedFunction)?.let { allRenames[it] = newName }
}
if (element is FunctionWithSupersWrapper) {
allRenames.remove(element)
}
val originalName = (element.unwrapped as? KtNamedFunction)?.name ?: return
for (declaration in ((element as? FunctionWithSupersWrapper)?.supers ?: listOf(element))) {
val psiMethod = wrapPsiMethod(declaration) ?: continue
allRenames[declaration] = newName
val baseName = psiMethod.name
val newBaseName = if (KotlinTypeMapper.InternalNameMapper.demangleInternalName(baseName) == originalName) {
KotlinTypeMapper.InternalNameMapper.mangleInternalName(
newName,
KotlinTypeMapper.InternalNameMapper.getModuleNameSuffix(baseName)!!
)
} else newName
if (psiMethod.containingClass != null) {
psiMethod.forEachOverridingMethod(scope) {
val overrider = (it as? PsiMirrorElement)?.prototype as? PsiMethod ?: it
if (overrider is SyntheticElement) return@forEachOverridingMethod true
val overriderName = overrider.name
val newOverriderName = RefactoringUtil.suggestNewOverriderName(overriderName, baseName, newBaseName)
if (newOverriderName != null) {
RenameUtil.assertNonCompileElement(overrider)
allRenames[overrider] = newOverriderName
}
return@forEachOverridingMethod true
}
}
}
ForeignUsagesRenameProcessor.prepareRenaming(element, newName, allRenames, scope)
}
override fun renameElement(element: PsiElement, newName: String, usages: Array<UsageInfo>, listener: RefactoringElementListener?) {
val simpleUsages = ArrayList<UsageInfo>(usages.size)
val ambiguousImportUsages = SmartList<UsageInfo>()
val simpleImportUsages = SmartList<UsageInfo>()
ForeignUsagesRenameProcessor.processAll(element, newName, usages, fallbackHandler = { usage ->
if (usage is LostDefaultValuesInOverridingFunctionUsageInfo) {
usage.apply()
return@processAll
}
when (usage.importState()) {
ImportState.AMBIGUOUS -> ambiguousImportUsages += usage
ImportState.SIMPLE -> simpleImportUsages += usage
ImportState.NOT_IMPORT -> {
if (!renameMangledUsageIfPossible(usage, element, newName)) {
simpleUsages += usage
}
}
}
})
element.ambiguousImportUsages = ambiguousImportUsages
val usagesToRename = if (simpleImportUsages.isEmpty()) simpleUsages else simpleImportUsages + simpleUsages
RenameUtil.doRenameGenericNamedElement(element, newName, usagesToRename.toTypedArray(), listener)
usages.forEach { (it as? KtResolvableCollisionUsageInfo)?.apply() }
(element.unwrapped as? KtNamedDeclaration)?.let(::dropOverrideKeywordIfNecessary)
}
private fun wrapPsiMethod(element: PsiElement?): PsiMethod? = when (element) {
is PsiMethod -> element
is KtNamedFunction, is KtSecondaryConstructor -> runReadAction {
LightClassUtil.getLightClassMethod(element as KtFunction)
}
else -> throw IllegalStateException("Can't be for element $element there because of canProcessElement()")
}
override fun findReferences(
element: PsiElement,
searchScope: SearchScope,
searchInCommentsAndStrings: Boolean
): Collection<PsiReference> {
val references = super.findReferences(element, searchScope, searchInCommentsAndStrings)
return processFoundReferences(element, references)
}
}
| apache-2.0 | bd31ba12ef22edd3e29cfebefb50246c | 46.447876 | 154 | 0.699487 | 5.520665 | false | false | false | false |
ktorio/ktor | ktor-http/common/src/io/ktor/http/Url.kt | 1 | 5459 | /*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package io.ktor.http
/**
* Represents an immutable URL
*
* @property protocol
* @property host name without port (domain)
* @property port the specified port or protocol default port
* @property specifiedPort port number that was specified to override protocol's default
* @property encodedPath encoded path without query string
* @property parameters URL query parameters
* @property fragment URL fragment (anchor name)
* @property user username part of URL
* @property password password part of URL
* @property trailingQuery keep trailing question character even if there are no query parameters
*/
public class Url internal constructor(
public val protocol: URLProtocol,
public val host: String,
public val specifiedPort: Int,
public val pathSegments: List<String>,
public val parameters: Parameters,
public val fragment: String,
public val user: String?,
public val password: String?,
public val trailingQuery: Boolean,
private val urlString: String
) {
init {
require(
specifiedPort in 0..65535 ||
specifiedPort == DEFAULT_PORT
) { "port must be between 0 and 65535, or $DEFAULT_PORT if not set" }
}
public val port: Int get() = specifiedPort.takeUnless { it == DEFAULT_PORT } ?: protocol.defaultPort
public val encodedPath: String by lazy {
if (pathSegments.isEmpty()) {
return@lazy ""
}
val pathStartIndex = urlString.indexOf('/', protocol.name.length + 3)
if (pathStartIndex == -1) {
return@lazy ""
}
val pathEndIndex = urlString.indexOfAny(charArrayOf('?', '#'), pathStartIndex)
if (pathEndIndex == -1) {
return@lazy urlString.substring(pathStartIndex)
}
urlString.substring(pathStartIndex, pathEndIndex)
}
public val encodedQuery: String by lazy {
val queryStart = urlString.indexOf('?') + 1
if (queryStart == 0) return@lazy ""
val queryEnd = urlString.indexOf('#', queryStart)
if (queryEnd == -1) return@lazy urlString.substring(queryStart)
urlString.substring(queryStart, queryEnd)
}
public val encodedPathAndQuery: String by lazy {
val pathStart = urlString.indexOf('/', protocol.name.length + 3)
if (pathStart == -1) {
return@lazy ""
}
val queryEnd = urlString.indexOf('#', pathStart)
if (queryEnd == -1) {
return@lazy urlString.substring(pathStart)
}
urlString.substring(pathStart, queryEnd)
}
public val encodedUser: String? by lazy {
if (user == null) return@lazy null
if (user.isEmpty()) return@lazy ""
val usernameStart = protocol.name.length + 3
val usernameEnd = urlString.indexOfAny(charArrayOf(':', '@'), usernameStart)
urlString.substring(usernameStart, usernameEnd)
}
public val encodedPassword: String? by lazy {
if (password == null) return@lazy null
if (password.isEmpty()) return@lazy ""
val passwordStart = urlString.indexOf(':', protocol.name.length + 3) + 1
val passwordEnd = urlString.indexOf('@')
urlString.substring(passwordStart, passwordEnd)
}
public val encodedFragment: String by lazy {
val fragmentStart = urlString.indexOf('#') + 1
if (fragmentStart == 0) return@lazy ""
urlString.substring(fragmentStart)
}
override fun toString(): String = urlString
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other == null || this::class != other::class) return false
other as Url
if (urlString != other.urlString) return false
return true
}
override fun hashCode(): Int {
return urlString.hashCode()
}
public companion object
}
@Suppress("UNUSED_PARAMETER")
@Deprecated(
"Url is not a data class anymore. Please use URLBuilder(url)",
level = DeprecationLevel.ERROR,
replaceWith = ReplaceWith("URLBuilder(this)")
)
public fun Url.copy(
protocol: URLProtocol = this.protocol,
host: String = this.host,
specifiedPort: Int = this.specifiedPort,
encodedPath: String = this.encodedPath,
parameters: Parameters = this.parameters,
fragment: String = this.fragment,
user: String? = this.user,
password: String? = this.password,
trailingQuery: Boolean = this.trailingQuery
): Url = error("Please use URLBuilder(url)")
/**
* [Url] authority.
*/
public val Url.authority: String
get() = buildString {
append(encodedUserAndPassword)
if (specifiedPort == DEFAULT_PORT || specifiedPort == protocol.defaultPort) {
append(host)
} else {
append(hostWithPort)
}
}
/**
* A [Url] protocol and authority.
*/
public val Url.protocolWithAuthority: String
get() = buildString {
append(protocol.name)
append("://")
append(encodedUserAndPassword)
if (specifiedPort == DEFAULT_PORT || specifiedPort == protocol.defaultPort) {
append(host)
} else {
append(hostWithPort)
}
}
internal val Url.encodedUserAndPassword: String
get() = buildString {
appendUserAndPassword(encodedUser, encodedPassword)
}
| apache-2.0 | 52162f2fea497cd408a37d70341039c8 | 30.554913 | 119 | 0.642609 | 4.459967 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/genericMath.kt | 2 | 8530 | package imgui
import glm_.*
import unsigned.Ubyte
import unsigned.Uint
import unsigned.Ulong
import unsigned.Ushort
import java.math.BigInteger
import kotlin.div
import kotlin.minus
import kotlin.plus
import kotlin.times
import imgui.internal.lerp as ilerp
@Suppress("UNCHECKED_CAST")
//infix operator fun <N> N.plus(other: N): N where N : Number, N : Comparable<N> = when {
// this is Byte && other is Byte -> (this + other).b
// this is Ubyte && other is Ubyte -> (this + other).b
// this is Short && other is Short -> (this + other).s
// this is Ushort && other is Ushort -> (this + other).s
// this is Int && other is Int -> this + other
// this is Uint && other is Uint -> this + other
// this is Long && other is Long -> this + other
// this is Ulong && other is Ulong -> this + other
// this is Float && other is Float -> this + other
// this is Double && other is Double -> this + other
// this is BigInteger && other is BigInteger -> this + other
// else -> error("Invalid operand types")
//} as N
infix operator fun <Type> Type.minus(other: Type): Type
where Type : Number, Type : Comparable<Type> = when {
this is Byte && other is Byte -> this - other
this is Ubyte && other is Ubyte -> this - other
this is Short && other is Short -> this - other
this is Ushort && other is Ushort -> this - other
this is Int && other is Int -> this - other
this is Uint && other is Uint -> this - other
this is Long && other is Long -> this - other
this is Ulong && other is Ulong -> this - other
this is Float && other is Float -> this - other
this is Double && other is Double -> this - other
this is BigInteger && other is BigInteger -> this - other
else -> error("Invalid operand types")
} as Type
infix operator fun <N> N.times(other: N): N where N : Number, N : Comparable<N> = when {
this is Byte && other is Byte -> (this * other).b
this is Ubyte && other is Ubyte -> (this * other).b
this is Short && other is Short -> (this * other).s
this is Ushort && other is Ushort -> (this * other).s
this is Int && other is Int -> this * other
this is Uint && other is Uint -> this * other
this is Long && other is Long -> this * other
this is Ulong && other is Ulong -> this * other
this is Float && other is Float -> this * other
this is Double && other is Double -> this * other
this is BigInteger && other is BigInteger -> this * other
else -> error("Invalid operand types")
} as N
infix operator fun <N> N.div(other: N): N where N : Number, N : Comparable<N> = when {
this is Byte && other is Byte -> (this / other).b
this is Ubyte && other is Ubyte -> (this / other).b
this is Short && other is Short -> (this / other).s
this is Ushort && other is Ushort -> (this / other).s
this is Int && other is Int -> this / other
this is Uint && other is Uint -> this / other
this is Long && other is Long -> this / other
this is Ulong && other is Ulong -> this / other
this is Float && other is Float -> this / other
this is Double && other is Double -> this / other
this is BigInteger && other is BigInteger -> this / other
else -> error("Invalid operand types")
} as N
infix operator fun <N> N.plus(float: Float): N where N : Number, N : Comparable<N> = when (this) {
is Byte -> (this + float).b
is Ubyte -> (v + float).b
is Short -> (this + float).s
is Ushort -> (v + float).s
is Int -> (this + float).i
is Uint -> (v + float).i
is Long -> (this + float).L
is Ulong -> (v + float).L
is Float -> this + float
is Double -> (this + float).d
else -> error("Invalid operand types")
} as N
infix operator fun <N> N.plus(double: Double): N where N : Number, N : Comparable<N> = when (this) {
is Byte -> (this + double).b
is Ubyte -> (v + double).b
is Short -> (this + double).s
is Ushort -> (v + double).s
is Int -> (this + double).i
is Uint -> (v + double).i
is Long -> (this + double).L
is Ulong -> (v + double).L
is Float -> (this + double).f
is Double -> this + double
else -> error("Invalid operand types")
} as N
infix operator fun <N> N.plus(int: Int): N where N : Number, N : Comparable<N> = when (this) {
is Byte -> (this + int).b
is Ubyte -> (v + int).b
is Short -> (this + int).s
is Ushort -> (v + int).s
is Int -> (this + int).i
is Uint -> (v + int).i
is Long -> (this + int).L
is Ulong -> (v + int).L
is Float -> this + int
is Double -> (this + int).d
else -> error("Invalid operand types")
} as N
infix operator fun <N> N.compareTo(int: Int): Int where N : Number, N : Comparable<N> = when (this) {
is Byte -> compareTo(int)
is Ubyte -> compareTo(int)
is Short -> compareTo(int)
is Ushort -> compareTo(int)
is Int -> compareTo(int)
is Uint -> compareTo(int)
is Long -> compareTo(int)
is Ulong -> compareTo(int.L)
is Float -> compareTo(int)
is Double -> compareTo(int)
else -> error("Invalid operand types")
}
fun <N> Number.`as`(n: N): N where N : Number, N : Comparable<N> = when (n) {
is Byte -> b
is Ubyte -> n.v
is Short -> s
is Ushort -> n.v
is Int -> i
is Uint -> n.v
is Long -> L
is Ulong -> n.v
is Float -> f
is Double -> d
else -> error("invalid")
} as N
val <N> N.asSigned: N where N : Number, N : Comparable<N>
get() = when (this) {
is Byte, is Short -> i // TODO utypes
else -> this
} as N
fun <N> clamp(a: N, min: N, max: N): N where N : Number, N : Comparable<N> =
if (a < min) min else if (a > max) max else a
fun <Type> min(a: Type, b: Type): Type
where Type : Number, Type : Comparable<Type> = if (a < b) a else b
fun <Type> max(a: Type, b: Type): Type
where Type : Number, Type : Comparable<Type> = if (a > b) a else b
fun <N> lerp(a: N, b: N, t: Float): N where N : Number, N : Comparable<N> = when (a) {
is Byte -> ilerp(a.i, b.i, t).b
is Short -> ilerp(a.i, b.i, t).s
is Int -> ilerp(a, b as Int, t)
is Long -> ilerp(a, b as Long, t)
is Float -> ilerp(a, b as Float, t)
is Double -> ilerp(a, b as Double, t)
else -> error("Invalid type")
} as N
//infix operator fun <N> Float.times(n: N): N where N : Number, N : Comparable<N> = when (n) {
// is Byte -> (b * n).b
// is Short -> (s * n).s
// is Int -> i * n
// is Long -> L * n
// is Float -> this * n
// is Double -> d * n
// else -> error("Invalid operand types")
//} as N
//
//infix operator fun <N> Float.div(n: N): N where N : Number, N : Comparable<N> = when (n) {
// is Byte -> (b / n).b
// is Short -> (s / n).s
// is Int -> i / n
// is Long -> L / n
// is Float -> this / n
// is Double -> d / n
// else -> error("Invalid operand types")
//} as N
infix operator fun <Type> Type.compareTo(float: Float): Int where Type : Number, Type : Comparable<Type> = when (this) {
is Byte -> compareTo(float)
is Short -> compareTo(float)
is Int -> compareTo(float)
is Long -> compareTo(float)
is Ubyte, is Ushort, is Uint, is Ulong -> f.compareTo(float) // TODO -> unsigned
is Float -> compareTo(float)
is Double -> compareTo(float)
else -> error("invalid")
}
@JvmName("min_")
fun <Type, N> min(n: N, t: Type): Type
where Type : Number, Type : Comparable<Type>,
N : Number, N : Comparable<N> = when (t) {
is Byte -> if (n.b < t) n.b else t
is Ubyte -> if (n.ub < t) n.ub else t
is Short -> if (n.s < t) n.s else t
is Ushort -> if (n.us < t) n.us else t
is Int -> if (n.i < t) n.i else t
is Uint -> if (n.ui < t) n.ui else t
is Long -> if (n.L < t) n.L else t
is Ulong -> if (n.ul < t) n.ul else t
is Float -> if (n.f < t) n.f else t
is Double -> if (n.d < t) n.d else t
else -> error("invalid")
} as Type
@JvmName("max_")
fun <Type, N> max(n: N, t: Type): Type
where Type : Number, Type : Comparable<Type>,
N : Number, N : Comparable<N> = when (t) {
is Byte -> if (n.b > t) n.b else t
is Ubyte -> if (n.ub > t) n.ub else t
is Short -> if (n.s > t) n.s else t
is Ushort -> if (n.us > t) n.us else t
is Int -> if (n.i > t) n.i else t
is Uint -> if (n.ui > t) n.ui else t
is Long -> if (n.L > t) n.L else t
is Ulong -> if (n.ul > t) n.ul else t
is Float -> if (n.f > t) n.f else t
is Double -> if (n.d > t) n.d else t
else -> error("invalid")
} as Type
| mit | 55d3b052115262d96ef4e9e5a676e2b4 | 34.840336 | 120 | 0.571864 | 3.228615 | false | false | false | false |
mdanielwork/intellij-community | python/src/com/jetbrains/python/codeInsight/typing/PyStubPackagesAdvertiser.kt | 1 | 15992 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.typing
import com.google.common.cache.Cache
import com.intellij.codeInspection.*
import com.intellij.codeInspection.ex.EditInspectionToolsSettingsAction
import com.intellij.codeInspection.ex.ProblemDescriptorImpl
import com.intellij.codeInspection.ui.ListEditForm
import com.intellij.execution.ExecutionException
import com.intellij.notification.NotificationDisplayType
import com.intellij.notification.NotificationGroup
import com.intellij.notification.NotificationType
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.Key
import com.intellij.profile.codeInspection.ProjectInspectionProfileManager
import com.intellij.psi.PsiElementVisitor
import com.intellij.webcore.packaging.RepoPackage
import com.jetbrains.python.inspections.PyInspection
import com.jetbrains.python.inspections.PyInspectionVisitor
import com.jetbrains.python.inspections.PyPackageRequirementsInspection.PyInstallRequirementsFix
import com.jetbrains.python.packaging.*
import com.jetbrains.python.packaging.requirement.PyRequirementRelation
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.sdk.PythonSdkType
import javax.swing.JComponent
class PyStubPackagesAdvertiser : PyInspection() {
companion object {
private val WHITE_LIST = mapOf("django" to "Django", "numpy" to "numpy") // top-level package to package on PyPI
private val BALLOON_SHOWING = Key.create<Boolean>("showingStubPackagesAdvertiserBalloon")
private val BALLOON_NOTIFICATIONS = NotificationGroup("Python Stub Packages Advertiser", NotificationDisplayType.STICKY_BALLOON, false)
}
@Suppress("MemberVisibilityCanBePrivate")
var ignoredPackages: MutableList<String> = mutableListOf()
override fun createOptionsPanel(): JComponent = ListEditForm("Ignored packages", ignoredPackages).contentPanel
override fun buildVisitor(holder: ProblemsHolder,
isOnTheFly: Boolean,
session: LocalInspectionToolSession): PsiElementVisitor {
return Visitor(ignoredPackages, holder, session)
}
private class Visitor(val ignoredPackages: MutableList<String>,
holder: ProblemsHolder,
session: LocalInspectionToolSession) : PyInspectionVisitor(holder, session) {
override fun visitPyFile(node: PyFile) {
val module = ModuleUtilCore.findModuleForFile(node) ?: return
val sdk = PythonSdkType.findPythonSdk(module) ?: return
val installedPackages = PyPackageManager.getInstance(sdk).packages ?: emptyList()
if (installedPackages.isEmpty()) return
val availablePackages = PyPackageManagers.getInstance().getManagementService(node.project, sdk).allPackagesCached
if (availablePackages.isEmpty()) return
val cache = ServiceManager.getService(PyStubPackagesAdvertiserCache::class.java).forSdk(sdk)
processWhiteListedPackages(node, module, sdk, availablePackages, installedPackages, cache)
processNotWhiteListedPackages(node, module, sdk, availablePackages, installedPackages, cache)
}
private fun processWhiteListedPackages(file: PyFile,
module: Module,
sdk: Sdk,
availablePackages: List<RepoPackage>,
installedPackages: List<PyPackage>,
cache: Cache<String, Set<RepoPackage>>) {
val (sourcesToLoad, cached) = splitIntoNotCachedAndCached(whiteListedSourcesToProcess(file), cache)
val sourceToStubPkgsAvailableToInstall = sourceToStubPackagesAvailableToInstall(
whiteListedSourceToInstalledRuntimeAndStubPackages(sourcesToLoad, installedPackages),
availablePackages
)
sourceToStubPkgsAvailableToInstall.forEach { source, stubPkgs -> cache.put(source, stubPkgs) }
val (reqs, args) = toRequirementsAndExtraArgs(sourceToStubPkgsAvailableToInstall, cached)
if (reqs.isNotEmpty()) {
val plural = reqs.size > 1
val reqsToString = PyPackageUtil.requirementsToString(reqs)
registerProblem(file,
"Stub package${if (plural) "s" else ""} $reqsToString ${if (plural) "are" else "is"} not installed. " +
"${if (plural) "They" else "It"} contain${if (plural) "" else "s"} type hints needed for better code insight.",
createInstallStubPackagesQuickFix(reqs, args, module, sdk),
createIgnorePackagesQuickFix(reqs, ignoredPackages))
}
}
private fun processNotWhiteListedPackages(file: PyFile,
module: Module,
sdk: Sdk,
availablePackages: List<RepoPackage>,
installedPackages: List<PyPackage>,
cache: Cache<String, Set<RepoPackage>>) {
val project = file.project
if (project.getUserData(BALLOON_SHOWING) == true) return
val (sourcesToLoad, cached) = splitIntoNotCachedAndCached(notWhiteListedSourcesToProcess(file), cache)
val sourceToStubPkgsAvailableToInstall = sourceToStubPackagesAvailableToInstall(
notWhiteListedSourceToInstalledRuntimeAndStubPackages(sourcesToLoad, installedPackages),
availablePackages
)
sourceToStubPkgsAvailableToInstall.forEach { source, stubPkgs -> cache.put(source, stubPkgs) }
val (reqs, args) = toRequirementsAndExtraArgs(sourceToStubPkgsAvailableToInstall, cached)
if (reqs.isNotEmpty()) {
val plural = reqs.size > 1
val reqsToString = PyPackageUtil.requirementsToString(reqs)
project.putUserData(BALLOON_SHOWING, true)
BALLOON_NOTIFICATIONS
.createNotification(
"Type hints are not installed",
"They are needed for better code insight.<br/>" +
"<a href=\"#yes\">Install ${if (plural) "stub packages" else reqsToString}</a> " +
"<a href=\"#no\">Ignore</a> " +
"<a href=\"#settings\">Settings</a>",
NotificationType.INFORMATION
) { notification, event ->
try {
val problemDescriptor = ProblemDescriptorImpl(
file,
file,
"Stub package${if (plural) "s" else ""} $reqsToString ${if (plural) "are" else "is"} not installed",
LocalQuickFix.EMPTY_ARRAY,
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
true,
null,
true
)
when (event.description) {
"#yes" -> {
createInstallStubPackagesQuickFix(reqs, args, module, sdk).applyFix(project, problemDescriptor)
}
"#no" -> createIgnorePackagesQuickFix(reqs, ignoredPackages).applyFix(project, problemDescriptor)
"#settings" -> {
val profile = ProjectInspectionProfileManager.getInstance(project).currentProfile
EditInspectionToolsSettingsAction.editToolSettings(project, profile, PyStubPackagesAdvertiser::class.simpleName)
}
}
}
finally {
notification.expire()
}
}
.whenExpired { project.putUserData(BALLOON_SHOWING, false) }
.notify(project)
}
}
private fun whiteListedSourcesToProcess(file: PyFile): Set<String> {
return WHITE_LIST.keys.filterTo(mutableSetOf()) { PyPsiUtils.containsImport(file, it) }
}
private fun notWhiteListedSourcesToProcess(file: PyFile): Set<String> {
return (file.fromImports.asSequence().mapNotNull { it.importSourceQName } + file.importTargets.asSequence().mapNotNull { it.importedQName })
.mapNotNull { it.firstComponent } // to top-level
.filterNot { it in WHITE_LIST }
.toSet()
}
private fun splitIntoNotCachedAndCached(sources: Set<String>,
cache: Cache<String, Set<RepoPackage>>): Pair<Set<String>, Set<RepoPackage>> {
if (sources.isEmpty()) return emptySet<String>() to emptySet()
val notCached = mutableSetOf<String>()
val cached = mutableSetOf<RepoPackage>()
synchronized(cache) {
// despite cache is thread-safe,
// here we have sync block to guarantee only one reader
// and as a result not run processing for sources that are already evaluating
sources.forEach { source ->
cache.getIfPresent(source).let {
if (it == null) {
notCached.add(source)
// mark this source as evaluating
// if source processing failed, this value would mean that such source was handled
cache.put(source, emptySet())
}
else {
cached.addAll(it)
}
}
}
}
return notCached to cached
}
private fun whiteListedSourceToInstalledRuntimeAndStubPackages(sourcesToLoad: Set<String>,
installedPackages: List<PyPackage>): Map<String, List<Pair<PyPackage, PyPackage?>>> {
val result = mutableMapOf<String, List<Pair<PyPackage, PyPackage?>>>()
for (source in sourcesToLoad) {
val pkgName = WHITE_LIST[source] ?: continue
if (ignoredPackages.contains(pkgName)) continue
installedRuntimeAndStubPackages(pkgName, installedPackages)?.let { result.put(source, listOf(it)) }
}
return result
}
private fun notWhiteListedSourceToInstalledRuntimeAndStubPackages(sourcesToLoad: Set<String>,
installedPackages: List<PyPackage>): Map<String, List<Pair<PyPackage, PyPackage?>>> {
val result = mutableMapOf<String, List<Pair<PyPackage, PyPackage?>>>()
for (source in sourcesToLoad) {
val packageNames = PyPIPackageUtil.PACKAGES_TOPLEVEL[source] ?: listOf(source)
result[source] = packageNames.mapNotNull {
if (ignoredPackages.contains(it)) null
else installedRuntimeAndStubPackages(it, installedPackages)
}
}
return result
}
private fun sourceToStubPackagesAvailableToInstall(sourceToInstalledRuntimeAndStubPkgs: Map<String, List<Pair<PyPackage, PyPackage?>>>,
availablePackages: List<RepoPackage>): Map<String, Set<RepoPackage>> {
if (sourceToInstalledRuntimeAndStubPkgs.isEmpty()) return emptyMap()
val stubPkgsAvailableToInstall = mutableMapOf<String, RepoPackage>()
availablePackages.forEach { if (it.name.endsWith(STUBS_SUFFIX)) stubPkgsAvailableToInstall[it.name] = it }
val result = mutableMapOf<String, Set<RepoPackage>>()
sourceToInstalledRuntimeAndStubPkgs.forEach { source, runtimeAndStubPkgs ->
result[source] = runtimeAndStubPkgs
.asSequence()
.filter { it.second == null }
.mapNotNull { stubPkgsAvailableToInstall["${it.first.name}$STUBS_SUFFIX"] }
.toSet()
}
return result
}
private fun createInstallStubPackagesQuickFix(reqs: List<PyRequirement>, args: List<String>, module: Module, sdk: Sdk): LocalQuickFix {
val project = module.project
val stubPkgNamesToInstall = reqs.mapTo(mutableSetOf()) { it.name }
val installationListener = object : PyPackageManagerUI.Listener {
override fun started() {
ServiceManager.getService(project, PyStubPackagesInstallingStatus::class.java).markAsInstalling(stubPkgNamesToInstall)
}
override fun finished(exceptions: MutableList<ExecutionException>?) {
val status = ServiceManager.getService(project, PyStubPackagesInstallingStatus::class.java)
val stubPkgsToUninstall = PyStubPackagesCompatibilityInspection
.findIncompatibleRuntimeToStubPackages(sdk) { it.name in stubPkgNamesToInstall }
.map { it.second }
if (stubPkgsToUninstall.isNotEmpty()) {
val stubPkgNamesToUninstall = stubPkgsToUninstall.mapTo(mutableSetOf()) { it.name }
val uninstallationListener = object : PyPackageManagerUI.Listener {
override fun started() {}
override fun finished(exceptions: MutableList<ExecutionException>?) {
status.unmarkAsInstalling(stubPkgNamesToUninstall)
}
}
val plural = stubPkgNamesToUninstall.size > 1
val content = "Suggested ${stubPkgNamesToUninstall.joinToString { "'$it'" }} " +
"${if (plural) "are" else "is"} incompatible with your current environment.<br/>" +
"${if (plural) "These" else "This"} stub package${if (plural) "s" else ""} will be removed."
BALLOON_NOTIFICATIONS.createNotification(content, NotificationType.WARNING).notify(project)
PyPackageManagerUI(project, sdk, uninstallationListener).uninstall(stubPkgsToUninstall)
stubPkgNamesToInstall.removeAll(stubPkgNamesToUninstall)
}
status.unmarkAsInstalling(stubPkgNamesToInstall)
}
}
val name = "Install stub package" + if (reqs.size > 1) "s" else ""
return PyInstallRequirementsFix(name, module, sdk, reqs, args, installationListener)
}
private fun createIgnorePackagesQuickFix(reqs: List<PyRequirement>, ignoredPkgs: MutableList<String>): LocalQuickFix {
return object : LocalQuickFix {
override fun getFamilyName() = "Ignore package" + if (reqs.size > 1) "s" else ""
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val pkgNames = reqs.asSequence().map { it.name.removeSuffix(STUBS_SUFFIX) }
if (ignoredPkgs.addAll(pkgNames)) ProjectInspectionProfileManager.getInstance(project).fireProfileChanged()
}
}
}
private fun toRequirementsAndExtraArgs(loaded: Map<String, Set<RepoPackage>>,
cached: Set<RepoPackage>): Pair<List<PyRequirement>, List<String>> {
val reqs = mutableListOf<PyRequirement>()
val args = mutableListOf("--no-deps")
(cached.asSequence().filterNot { ignoredPackages.contains(it.name.removeSuffix(STUBS_SUFFIX)) } + loaded.values.asSequence().flatten())
.forEach {
val version = it.latestVersion
val url = it.repoUrl
reqs.add(if (version == null) pyRequirement(it.name) else pyRequirement(it.name, PyRequirementRelation.EQ, version))
if (url != null && !PyPIPackageUtil.isPyPIRepository(url)) {
with(args) {
add("--extra-index-url")
add(url)
}
}
}
return reqs to args
}
private fun installedRuntimeAndStubPackages(pkgName: String,
installedPackages: List<PyPackage>): Pair<PyPackage, PyPackage?>? {
var runtime: PyPackage? = null
var stub: PyPackage? = null
val stubPkgName = "$pkgName$STUBS_SUFFIX"
for (pkg in installedPackages) {
val name = pkg.name
if (name == pkgName) runtime = pkg
if (name == stubPkgName) stub = pkg
}
return if (runtime == null) null else runtime to stub
}
}
} | apache-2.0 | c3ec6a88058eb58725da48d2bfaca930 | 44.305949 | 155 | 0.651763 | 4.989704 | false | false | false | false |
dbrant/apps-android-wikipedia | app/src/main/java/org/wikipedia/page/GeoTypeAdapter.kt | 1 | 1071 | package org.wikipedia.page
import android.location.Location
import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonWriter
import org.wikipedia.util.log.L
import java.io.IOException
class GeoTypeAdapter : TypeAdapter<Location>() {
@Throws(IOException::class)
override fun write(out: JsonWriter, value: Location) {
out.beginObject()
out.name(GeoUnmarshaller.LATITUDE).value(value.latitude)
out.name(GeoUnmarshaller.LONGITUDE).value(value.longitude)
out.endObject()
}
@Throws(IOException::class)
override fun read(input: JsonReader): Location {
val ret = Location("")
input.beginObject()
while (input.hasNext()) {
when (val name = input.nextName()) {
GeoUnmarshaller.LATITUDE -> ret.latitude = input.nextDouble()
GeoUnmarshaller.LONGITUDE -> ret.longitude = input.nextDouble()
else -> L.d("name=$name")
}
}
input.endObject()
return ret
}
}
| apache-2.0 | b672adeeec5abc03667c4d4a8e73a41d | 31.454545 | 79 | 0.648926 | 4.301205 | false | false | false | false |
drakelord/wire | wire-schema/src/main/java/com/squareup/wire/schema/internal/parser/ProtoFileElement.kt | 1 | 2283 | /*
* Copyright (C) 2013 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.schema.internal.parser
import com.squareup.wire.schema.Location
import com.squareup.wire.schema.ProtoFile
/** A single `.proto` file. */
data class ProtoFileElement(
val location: Location,
val packageName: String? = null,
val syntax: ProtoFile.Syntax? = null,
val imports: List<String> = emptyList(),
val publicImports: List<String> = emptyList(),
val types: List<TypeElement> = emptyList(),
val services: List<ServiceElement> = emptyList(),
val extendDeclarations: List<ExtendElement> = emptyList(),
val options: List<OptionElement> = emptyList()
) {
fun toSchema() = buildString {
append("// ")
append(location)
append('\n')
if (syntax != null) {
append("syntax = \"$syntax\";\n")
}
if (packageName != null) {
append("package $packageName;\n")
}
if (imports.isNotEmpty() || publicImports.isNotEmpty()) {
append('\n')
for (file in imports) {
append("import \"$file\";\n")
}
for (file in publicImports) {
append("import public \"$file\";\n")
}
}
if (options.isNotEmpty()) {
append('\n')
for (option in options) {
append(option.toSchemaDeclaration())
}
}
if (types.isNotEmpty()) {
append('\n')
for (typeElement in types) {
append(typeElement.toSchema())
}
}
if (extendDeclarations.isNotEmpty()) {
append('\n')
for (extendDeclaration in extendDeclarations) {
append(extendDeclaration.toSchema())
}
}
if (services.isNotEmpty()) {
append('\n')
for (service in services) {
append(service.toSchema())
}
}
}
} | apache-2.0 | 75fa49cec989286a6156fcd348810d05 | 28.282051 | 75 | 0.635567 | 4.098743 | false | false | false | false |
drakelord/wire | wire-schema/src/test/java/com/squareup/wire/schema/OptionsTest.kt | 1 | 6089 | /*
* Copyright (C) 2015 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.wire.schema
import com.google.common.collect.ImmutableMap
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class OptionsTest {
@Test
fun structuredAndUnstructuredOptions() {
// From https://developers.google.com/protocol-buffers/docs/proto#options
val schema = RepoBuilder()
.add("foo.proto",
"""
|import "google/protobuf/descriptor.proto";
|message FooOptions {
| optional int32 opt1 = 1;
| optional string opt2 = 2;
|}
|
|extend google.protobuf.FieldOptions {
| optional FooOptions foo_options = 1234;
|}
|
|message Bar {
| optional int32 a = 1 [(foo_options).opt1 = 123, (foo_options).opt2 = "baz"];
| optional int32 b = 2 [(foo_options) = { opt1: 456 opt2: "quux" }];
|}
""".trimMargin()
)
.schema()
val fooOptions = ProtoMember.get(Options.FIELD_OPTIONS, "foo_options")
val opt1 = ProtoMember.get(ProtoType.get("FooOptions"), "opt1")
val opt2 = ProtoMember.get(ProtoType.get("FooOptions"), "opt2")
val bar = schema.getType("Bar") as MessageType
assertThat(bar.field("a")!!.options().map())
.isEqualTo(ImmutableMap.of(fooOptions, ImmutableMap.of(opt1, "123", opt2, "baz")))
assertThat(bar.field("b")!!.options().map())
.isEqualTo(ImmutableMap.of(fooOptions, ImmutableMap.of(opt1, "456", opt2, "quux")))
}
@Test
fun textFormatCanOmitMapValueSeparator() {
val schema = RepoBuilder()
.add("foo.proto",
"""
|import "google/protobuf/descriptor.proto";
|message FooOptions {
| optional BarOptions bar = 2;
|}
|message BarOptions {
| optional int32 baz = 2;
|}
|
|extend google.protobuf.FieldOptions {
| optional FooOptions foo = 1234;
|}
|
|message Message {
| optional int32 b = 2 [(foo) = { bar { baz: 123 } }];
|}
""".trimMargin()
)
.schema()
val foo = ProtoMember.get(Options.FIELD_OPTIONS, "foo")
val bar = ProtoMember.get(ProtoType.get("FooOptions"), "bar")
val baz = ProtoMember.get(ProtoType.get("BarOptions"), "baz")
val message = schema.getType("Message") as MessageType
assertThat(message.field("b")!!.options().map())
.isEqualTo(ImmutableMap.of(foo, ImmutableMap.of(bar, ImmutableMap.of(baz, "123"))))
}
@Test
fun fullyQualifiedOptionFields() {
val schema = RepoBuilder()
.add("a/b/more_options.proto",
"""
|syntax = "proto2";
|package a.b;
|
|import "google/protobuf/descriptor.proto";
|
|extend google.protobuf.MessageOptions {
| optional MoreOptions more_options = 17000;
|}
|
|message MoreOptions {
| extensions 100 to 200;
|}
""".trimMargin()
)
.add("a/c/event_more_options.proto",
"""
|syntax = "proto2";
|package a.c;
|
|import "a/b/more_options.proto";
|
|extend a.b.MoreOptions {
| optional EvenMoreOptions even_more_options = 100;
|}
|
|message EvenMoreOptions {
| optional string string_option = 1;
|}
""".trimMargin())
.add("a/d/message.proto",
"""
|syntax = "proto2";
|package a.d;
|
|import "a/b/more_options.proto";
|import "a/c/event_more_options.proto";
|
|message Message {
| option (a.b.more_options) = {
| [a.c.even_more_options]: {string_option: "foo"}
| };
|}
""".trimMargin())
.schema()
val moreOptionsType = ProtoType.get("a.b.MoreOptions")
val evenMoreOptionsType = ProtoType.get("a.c.EvenMoreOptions")
val moreOptions = ProtoMember.get(Options.MESSAGE_OPTIONS, "a.b.more_options")
val evenMoreOptions = ProtoMember.get(moreOptionsType, "a.c.even_more_options")
val stringOption = ProtoMember.get(evenMoreOptionsType, "string_option")
val message = schema.getType("a.d.Message") as MessageType
assertThat(message.options().map())
.isEqualTo(ImmutableMap.of(moreOptions,
ImmutableMap.of(evenMoreOptions, ImmutableMap.of(stringOption, "foo")))
)
}
@Test
fun resolveFieldPathMatchesFirstSegment() {
assertThat(Options.resolveFieldPath("a.b.c.d", setOf("a", "z", "y")))
.containsExactly("a", "b", "c", "d")
}
@Test
fun resolveFieldPathMatchesMultipleSegments() {
assertThat(Options.resolveFieldPath("a.b.c.d", setOf("a.b", "z.b", "y.b")))
.containsExactly("a.b", "c", "d")
}
@Test
fun resolveFieldPathMatchesAllSegments() {
assertThat(Options.resolveFieldPath("a.b.c.d", setOf("a.b.c.d", "z.b.c.d")))
.containsExactly("a.b.c.d")
}
@Test
fun resolveFieldPathMatchesOnlySegment() {
assertThat(Options.resolveFieldPath("a", setOf("a", "b"))).containsExactly("a")
}
@Test
fun resolveFieldPathDoesntMatch() {
assertThat(Options.resolveFieldPath("a.b", setOf("c", "d"))).isNull()
}
}
| apache-2.0 | 37aa7b2957572c0fb11263c0e27e7a23 | 32.827778 | 91 | 0.570209 | 4.040478 | false | true | false | false |
Tickaroo/tikxml | annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/annotationprocessing/elementlist/InlineListCatalogue.kt | 1 | 1337 | /*
* Copyright (C) 2015 Hannes Dorfmann
* Copyright (C) 2015 Tickaroo, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.tickaroo.tikxml.annotationprocessing.elementlist
import com.tickaroo.tikxml.annotation.Element
import com.tickaroo.tikxml.annotation.Xml
/**
* @author Hannes Dorfmann
*/
@Xml(name = "catalogue")
class InlineListCatalogue {
@Element(name = "book")
var books: List<Book>? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is InlineListCatalogue) return false
val that = other as InlineListCatalogue?
return if (books != null) books == that!!.books else that!!.books == null
}
override fun hashCode(): Int {
return if (books != null) books!!.hashCode() else 0
}
}
| apache-2.0 | 2c49da136e6d3ed9f1968e340bddd73f | 28.711111 | 81 | 0.691847 | 4.101227 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/stream-debugger/src/com/intellij/debugger/streams/trace/dsl/impl/LineSeparatedCodeBlock.kt | 23 | 910 | // Copyright 2000-2017 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.debugger.streams.trace.dsl.impl
import com.intellij.debugger.streams.trace.dsl.*
/**
* TODO: Add ability to add braces at the beginning and at the end
*
* @author Vitaliy.Bibaev
*/
abstract class LineSeparatedCodeBlock(statementFactory: StatementFactory, private val statementSeparator: String = "")
: CodeBlockBase(statementFactory) {
override fun toCode(indent: Int): String {
if (size == 0) {
return ""
}
val builder = StringBuilder()
val statements = getStatements()
for (convertable in statements) {
builder.append(convertable.toCode(indent))
if (convertable is Statement) {
builder.append(statementSeparator)
}
builder.append("\n")
}
return builder.toString()
}
} | apache-2.0 | 48323814e80ee4b337d6fdfe785fcf97 | 30.413793 | 140 | 0.701099 | 4.099099 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.