repo_name
stringlengths 7
81
| path
stringlengths 6
242
| copies
stringclasses 55
values | size
stringlengths 2
6
| content
stringlengths 55
737k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 5.44
99.8
| line_max
int64 15
979
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.93
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/SearchEverywhereClassFeaturesProvider.kt | 7 | 2192 | package com.intellij.ide.actions.searcheverywhere.ml.features
import com.intellij.ide.actions.searcheverywhere.ClassSearchEverywhereContributor
import com.intellij.ide.actions.searcheverywhere.PSIPresentationBgRendererWrapper
import com.intellij.internal.statistic.eventLog.events.EventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.navigation.TargetPresentation
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.editor.markup.EffectType
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.psi.PsiNamedElement
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
@IntellijInternalApi
class SearchEverywhereClassFeaturesProvider : SearchEverywhereElementFeaturesProvider(ClassSearchEverywhereContributor::class.java) {
companion object {
val IS_DEPRECATED = EventFields.Boolean("isDeprecated")
}
override fun getFeaturesDeclarations(): List<EventField<*>> {
return arrayListOf<EventField<*>>(IS_DEPRECATED)
}
override fun getElementFeatures(element: Any,
currentTime: Long,
searchQuery: String,
elementPriority: Int,
cache: FeaturesProviderCache?): List<EventPair<*>> {
val item = SearchEverywherePsiElementFeaturesProvider.getPsiElement(element) ?: return emptyList()
val data = arrayListOf<EventPair<*>>()
ReadAction.run<Nothing> {
(item as? PsiNamedElement)?.name?.let { elementName ->
data.addAll(getNameMatchingFeatures(elementName, searchQuery))
}
}
val presentation = (element as? PSIPresentationBgRendererWrapper.PsiItemWithPresentation)?.presentation
data.putIfValueNotNull(IS_DEPRECATED, isDeprecated(presentation))
return data
}
private fun isDeprecated(presentation: TargetPresentation?): Boolean? {
if (presentation == null) {
return null
}
val effectType = presentation.presentableTextAttributes?.effectType ?: return false
return effectType == EffectType.STRIKEOUT
}
}
| apache-2.0 | f525aa10370a6d41a8c02a2ac2cf89eb | 40.358491 | 133 | 0.749544 | 5.294686 | false | false | false | false |
GunoH/intellij-community | plugins/ide-features-trainer/src/training/featuresSuggester/listeners/DebuggerListener.kt | 8 | 1545 | package training.featuresSuggester.listeners
import com.intellij.openapi.project.Project
import com.intellij.xdebugger.XDebugProcess
import com.intellij.xdebugger.XDebugSession
import com.intellij.xdebugger.XDebugSessionListener
import com.intellij.xdebugger.XDebuggerManagerListener
import training.featuresSuggester.SuggestingUtils.handleAction
import training.featuresSuggester.actions.Action
import training.featuresSuggester.actions.DebugProcessStartedAction
import training.featuresSuggester.actions.DebugProcessStoppedAction
class DebuggerListener(val project: Project) : XDebuggerManagerListener {
private var curSessionListener: XDebugSessionListener? = null
override fun processStarted(debugProcess: XDebugProcess) {
handleDebugAction(::DebugProcessStartedAction)
}
override fun processStopped(debugProcess: XDebugProcess) {
handleDebugAction(::DebugProcessStoppedAction)
}
private fun <T : Action> handleDebugAction(actionConstructor: (Project, Long) -> T) {
handleAction(
project,
actionConstructor(project, System.currentTimeMillis())
)
}
override fun currentSessionChanged(previousSession: XDebugSession?, currentSession: XDebugSession?) {
if (previousSession != null && curSessionListener != null) {
previousSession.removeSessionListener(curSessionListener!!)
curSessionListener = null
}
if (currentSession != null) {
curSessionListener = DebugSessionListener(currentSession)
currentSession.addSessionListener(curSessionListener!!)
}
}
}
| apache-2.0 | 77eb33da5d2793e7e4c012ec908739f9 | 36.682927 | 103 | 0.801294 | 5.402098 | false | false | false | false |
GunoH/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/library/LibraryStateSnapshot.kt | 2 | 5111 | // 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.workspaceModel.ide.impl.legacyBridge.library
import com.intellij.configurationStore.ComponentSerializationUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.module.Module
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.roots.ProjectModelExternalSource
import com.intellij.openapi.roots.impl.libraries.UnknownLibraryKind
import com.intellij.openapi.roots.libraries.LibraryKindRegistry
import com.intellij.openapi.roots.libraries.LibraryProperties
import com.intellij.openapi.roots.libraries.LibraryTable
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.ArrayUtil
import com.intellij.workspaceModel.ide.JpsImportedEntitySource
import com.intellij.workspaceModel.ide.impl.legacyBridge.library.LibraryBridgeImpl.Companion.toLibraryRootType
import com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots.ModuleLibraryTableBridge
import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.FileContainerDescription
import com.intellij.workspaceModel.ide.impl.legacyBridge.watcher.JarDirectoryDescription
import com.intellij.workspaceModel.ide.toExternalSource
import com.intellij.workspaceModel.storage.EntityStorage
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryPropertiesEntity
import com.intellij.workspaceModel.storage.bridgeEntities.LibraryRoot
import java.io.StringReader
class LibraryStateSnapshot(
val libraryEntity: LibraryEntity,
val storage: EntityStorage,
val libraryTable: LibraryTable,
val parentDisposable: Disposable) {
private val roots = collectFiles(libraryEntity)
private val excludedRootsContainer = if (libraryEntity.excludedRoots.isNotEmpty()) {
FileContainerDescription(libraryEntity.excludedRoots.map { it.url }, emptyList())
}
else null
private val kindProperties by lazy {
val customProperties = libraryEntity.libraryProperties
val k = customProperties?.libraryType?.let {
LibraryKindRegistry.getInstance().findKindById(it) ?: UnknownLibraryKind.getOrCreate(it)
} as? PersistentLibraryKind<*>
val p = loadProperties(k, customProperties)
k to p
}
val kind: PersistentLibraryKind<*>?
get() = kindProperties.first
val properties: LibraryProperties<*>?
get() = kindProperties.second
private fun loadProperties(kind: PersistentLibraryKind<*>?, customProperties: LibraryPropertiesEntity?): LibraryProperties<*>? {
if (kind == null) return null
val properties = kind.createDefaultProperties()
val propertiesElement = customProperties?.propertiesXmlTag
if (propertiesElement == null) return properties
ComponentSerializationUtil.loadComponentState(properties, JDOMUtil.load(StringReader(propertiesElement)))
return properties
}
val name: String?
get() = LibraryNameGenerator.getLegacyLibraryName(libraryEntity.symbolicId)
val module: Module?
get() = (libraryTable as? ModuleLibraryTableBridge)?.module
fun getFiles(rootType: OrderRootType): Array<VirtualFile> {
return roots[rootType.toLibraryRootType()]?.getFiles() ?: VirtualFile.EMPTY_ARRAY
}
fun getUrls(rootType: OrderRootType): Array<String> = roots[rootType.toLibraryRootType()]?.getUrls() ?: ArrayUtil.EMPTY_STRING_ARRAY
val excludedRootUrls: Array<String>
get() = excludedRootsContainer?.getUrls() ?: ArrayUtil.EMPTY_STRING_ARRAY
val excludedRoots: Array<VirtualFile>
get() = excludedRootsContainer?.getFiles() ?: VirtualFile.EMPTY_ARRAY
fun isValid(url: String, rootType: OrderRootType): Boolean {
return roots[rootType.toLibraryRootType()]
?.findByUrl(url)?.isValid ?: false
}
fun getInvalidRootUrls(type: OrderRootType): List<String> {
return roots[type.toLibraryRootType()]?.getList()?.filterNot { it.isValid }?.map { it.url } ?: emptyList()
}
fun isJarDirectory(url: String) = isJarDirectory(url, OrderRootType.CLASSES)
fun isJarDirectory(url: String, rootType: OrderRootType): Boolean {
return roots[rootType.toLibraryRootType()]?.isJarDirectory(url) ?: false
}
val externalSource: ProjectModelExternalSource?
get() = (libraryEntity.entitySource as? JpsImportedEntitySource)?.toExternalSource()
companion object {
fun collectFiles(libraryEntity: LibraryEntity): Map<Any, FileContainerDescription> = libraryEntity.roots.groupBy { it.type }.mapValues { (_, roots) ->
val urls = roots.filter { it.inclusionOptions == LibraryRoot.InclusionOptions.ROOT_ITSELF }.map { it.url }
val jarDirs = roots
.filter { it.inclusionOptions != LibraryRoot.InclusionOptions.ROOT_ITSELF }
.map {
JarDirectoryDescription(it.url, it.inclusionOptions == LibraryRoot.InclusionOptions.ARCHIVES_UNDER_ROOT_RECURSIVELY)
}
FileContainerDescription(urls, jarDirs)
}
}
}
| apache-2.0 | 0725a1f8dd666962c08f89a90f905932 | 45.045045 | 154 | 0.78693 | 4.952519 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/CompletionSession.kt | 1 | 19854 | // 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.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.CompletionSorter
import com.intellij.codeInsight.completion.CompletionUtil
import com.intellij.codeInsight.completion.impl.CamelHumpMatcher
import com.intellij.codeInsight.completion.impl.RealPrefixMatchingWeigher
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.util.registry.Registry
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.StandardPatterns
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.ProcessingContext
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.caches.project.ModuleOrigin
import org.jetbrains.kotlin.idea.caches.project.OriginCapability
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.getResolveScope
import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper
import org.jetbrains.kotlin.idea.core.*
import org.jetbrains.kotlin.idea.imports.importableFqName
import org.jetbrains.kotlin.idea.project.TargetPlatformDetector
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.*
import org.jetbrains.kotlin.platform.isMultiPlatform
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.typeUtil.isUnit
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
class CompletionSessionConfiguration(
val useBetterPrefixMatcherForNonImportedClasses: Boolean,
val nonAccessibleDeclarations: Boolean,
val javaGettersAndSetters: Boolean,
val javaClassesNotToBeUsed: Boolean,
val staticMembers: Boolean,
val dataClassComponentFunctions: Boolean
)
fun CompletionSessionConfiguration(parameters: CompletionParameters) = CompletionSessionConfiguration(
useBetterPrefixMatcherForNonImportedClasses = parameters.invocationCount < 2,
nonAccessibleDeclarations = parameters.invocationCount >= 2,
javaGettersAndSetters = parameters.invocationCount >= 2,
javaClassesNotToBeUsed = parameters.invocationCount >= 2,
staticMembers = parameters.invocationCount >= 2,
dataClassComponentFunctions = parameters.invocationCount >= 2
)
abstract class CompletionSession(
protected val configuration: CompletionSessionConfiguration,
originalParameters: CompletionParameters,
resultSet: CompletionResultSet
) {
init {
CompletionBenchmarkSink.instance.onCompletionStarted(this)
}
protected val parameters = run {
val fixedPosition = addParamTypesIfNeeded(originalParameters.position)
originalParameters.withPosition(fixedPosition, fixedPosition.textOffset)
}
protected val toFromOriginalFileMapper = ToFromOriginalFileMapper.create(this.parameters)
protected val position = this.parameters.position
protected val file = position.containingFile as KtFile
protected val resolutionFacade = file.getResolutionFacade()
protected val moduleDescriptor = resolutionFacade.moduleDescriptor
protected val project = position.project
protected val isJvmModule = TargetPlatformDetector.getPlatform(originalParameters.originalFile as KtFile).isJvm()
protected val isDebuggerContext = file is KtCodeFragment
protected val nameExpression: KtSimpleNameExpression?
protected val expression: KtExpression?
init {
val reference = (position.parent as? KtSimpleNameExpression)?.mainReference
if (reference != null) {
if (reference.expression is KtLabelReferenceExpression) {
this.nameExpression = null
this.expression = reference.expression.parent.parent as? KtExpressionWithLabel
} else {
this.nameExpression = reference.expression
this.expression = nameExpression
}
} else {
this.nameExpression = null
this.expression = null
}
}
protected val bindingContext = CompletionBindingContextProvider.getInstance(project).getBindingContext(position, resolutionFacade)
protected val inDescriptor = position.getResolutionScope(bindingContext, resolutionFacade).ownerDescriptor
private val kotlinIdentifierStartPattern = StandardPatterns.character().javaIdentifierStart().andNot(singleCharPattern('$'))
private val kotlinIdentifierPartPattern = StandardPatterns.character().javaIdentifierPart().andNot(singleCharPattern('$'))
protected val prefix = CompletionUtil.findIdentifierPrefix(
originalParameters.position.containingFile,
originalParameters.offset,
kotlinIdentifierPartPattern or singleCharPattern('@'),
kotlinIdentifierStartPattern
)!!
protected val prefixMatcher = CamelHumpMatcher(prefix)
protected val descriptorNameFilter: (String) -> Boolean = prefixMatcher.asStringNameFilter()
protected val isVisibleFilter: (DeclarationDescriptor) -> Boolean =
{ isVisibleDescriptor(it, completeNonAccessible = configuration.nonAccessibleDeclarations) }
protected val isVisibleFilterCheckAlways: (DeclarationDescriptor) -> Boolean =
{ isVisibleDescriptor(it, completeNonAccessible = false) }
protected val referenceVariantsHelper = ReferenceVariantsHelper(
bindingContext,
resolutionFacade,
moduleDescriptor,
isVisibleFilter,
NotPropertiesService.getNotProperties(position)
)
protected val callTypeAndReceiver =
if (nameExpression == null) CallTypeAndReceiver.UNKNOWN else CallTypeAndReceiver.detect(nameExpression)
protected val receiverTypes = nameExpression?.let { detectReceiverTypes(bindingContext, nameExpression, callTypeAndReceiver) }
protected val basicLookupElementFactory =
BasicLookupElementFactory(project, InsertHandlerProvider(callTypeAndReceiver.callType) { expectedInfos })
// LookupElementsCollector instantiation is deferred because virtual call to createSorter uses data from derived classes
protected val collector: LookupElementsCollector by lazy(LazyThreadSafetyMode.NONE) {
LookupElementsCollector(
{ CompletionBenchmarkSink.instance.onFlush(this) },
prefixMatcher, originalParameters, resultSet,
createSorter(), (file as? KtCodeFragment)?.extraCompletionFilter,
moduleDescriptor.platform.isMultiPlatform()
)
}
protected val searchScope: GlobalSearchScope =
getResolveScope(originalParameters.originalFile as KtFile)
protected fun indicesHelper(mayIncludeInaccessible: Boolean): KotlinIndicesHelper {
val filter = if (mayIncludeInaccessible) isVisibleFilter else isVisibleFilterCheckAlways
return KotlinIndicesHelper(
resolutionFacade,
searchScope,
filter,
filterOutPrivate = !mayIncludeInaccessible,
declarationTranslator = { toFromOriginalFileMapper.toSyntheticFile(it) },
file = file
)
}
private fun isVisibleDescriptor(descriptor: DeclarationDescriptor, completeNonAccessible: Boolean): Boolean {
if (!configuration.javaClassesNotToBeUsed && descriptor is ClassDescriptor) {
if (descriptor.importableFqName?.let(::isJavaClassNotToBeUsedInKotlin) == true) return false
}
if (descriptor is TypeParameterDescriptor && !isTypeParameterVisible(descriptor)) return false
if (descriptor is DeclarationDescriptorWithVisibility) {
val visible = descriptor.isVisible(position, callTypeAndReceiver.receiver as? KtExpression, bindingContext, resolutionFacade)
if (visible) return true
return completeNonAccessible && (!descriptor.isFromLibrary() || isDebuggerContext)
}
if (descriptor.isExcludedFromAutoImport(project, file)) return false
return true
}
private fun DeclarationDescriptor.isFromLibrary(): Boolean {
if (module.getCapability(OriginCapability) == ModuleOrigin.LIBRARY) return true
if (this is CallableMemberDescriptor && kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) {
return overriddenDescriptors.all { it.isFromLibrary() }
}
return false
}
private fun isTypeParameterVisible(typeParameter: TypeParameterDescriptor): Boolean {
val owner = typeParameter.containingDeclaration
var parent: DeclarationDescriptor? = inDescriptor
while (parent != null) {
if (parent == owner) return true
if (parent is ClassDescriptor && !parent.isInner) return false
parent = parent.containingDeclaration
}
return true
}
protected fun flushToResultSet() {
collector.flushToResultSet()
}
fun complete(): Boolean {
return try {
_complete().also {
CompletionBenchmarkSink.instance.onCompletionEnded(this, false)
}
} catch (pce: ProcessCanceledException) {
CompletionBenchmarkSink.instance.onCompletionEnded(this, true)
throw pce
}
}
private fun _complete(): Boolean {
// we restart completion when prefix becomes "get" or "set" to ensure that properties get lower priority comparing to get/set functions (see KT-12299)
val prefixPattern = StandardPatterns.string().with(object : PatternCondition<String>("get or set prefix") {
override fun accepts(prefix: String, context: ProcessingContext?) = prefix == "get" || prefix == "set"
})
collector.restartCompletionOnPrefixChange(prefixPattern)
val statisticsContext = calcContextForStatisticsInfo()
if (statisticsContext != null) {
collector.addLookupElementPostProcessor { lookupElement ->
// we should put data into the original element because of DecoratorCompletionStatistician
lookupElement.putUserDataDeep(STATISTICS_INFO_CONTEXT_KEY, statisticsContext)
lookupElement
}
}
doComplete()
flushToResultSet()
return !collector.isResultEmpty
}
fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) {
collector.addLookupElementPostProcessor(processor)
}
protected abstract fun doComplete()
protected abstract val descriptorKindFilter: DescriptorKindFilter?
protected abstract val expectedInfos: Collection<ExpectedInfo>
protected val importableFqNameClassifier = ImportableFqNameClassifier(file)
protected open fun createSorter(): CompletionSorter {
var sorter = CompletionSorter.defaultSorter(parameters, prefixMatcher)!!
sorter = sorter.weighBefore(
"stats", DeprecatedWeigher, PriorityWeigher, PreferGetSetMethodsToPropertyWeigher,
NotImportedWeigher(importableFqNameClassifier),
NotImportedStaticMemberWeigher(importableFqNameClassifier),
KindWeigher, CallableWeigher
)
sorter = sorter.weighAfter("stats", VariableOrFunctionWeigher, ImportedWeigher(importableFqNameClassifier))
val preferContextElementsWeigher = PreferContextElementsWeigher(inDescriptor)
sorter =
if (callTypeAndReceiver is CallTypeAndReceiver.SUPER_MEMBERS) { // for completion after "super." strictly prefer the current member
sorter.weighBefore("kotlin.deprecated", preferContextElementsWeigher)
} else {
sorter.weighBefore("kotlin.proximity", preferContextElementsWeigher)
}
sorter = sorter.weighBefore("middleMatching", PreferMatchingItemWeigher)
// we insert one more RealPrefixMatchingWeigher because one inserted in default sorter is placed in a bad position (after "stats")
sorter = sorter.weighAfter("lift.shorter", RealPrefixMatchingWeigher())
sorter = sorter.weighAfter("kotlin.proximity", ByNameAlphabeticalWeigher, PreferLessParametersWeigher)
sorter = sorter.weighBefore("prefix", KotlinUnwantedLookupElementWeigher)
sorter = if (expectedInfos.all { it.fuzzyType?.type?.isUnit() == true }) {
sorter.weighBefore("prefix", PreferDslMembers)
} else {
sorter.weighAfter("kotlin.preferContextElements", PreferDslMembers)
}
return sorter
}
protected fun calcContextForStatisticsInfo(): String? {
if (expectedInfos.isEmpty()) return null
var context = expectedInfos
.mapNotNull { it.fuzzyType?.type?.constructor?.declarationDescriptor?.importableFqName }
.distinct()
.singleOrNull()
?.let { "expectedType=$it" }
if (context == null) {
context = expectedInfos
.mapNotNull { it.expectedName }
.distinct()
.singleOrNull()
?.let { "expectedName=$it" }
}
return context
}
protected val referenceVariantsCollector = if (nameExpression != null) {
ReferenceVariantsCollector(
referenceVariantsHelper, indicesHelper(true), prefixMatcher,
nameExpression, callTypeAndReceiver, resolutionFacade, bindingContext,
importableFqNameClassifier, configuration
)
} else {
null
}
protected fun ReferenceVariants.excludeNonInitializedVariable(): ReferenceVariants {
return ReferenceVariants(referenceVariantsHelper.excludeNonInitializedVariable(imported, position), notImportedExtensions)
}
protected fun referenceVariantsWithSingleFunctionTypeParameter(): ReferenceVariants? {
val variants = referenceVariantsCollector?.allCollected ?: return null
val filter = { descriptor: DeclarationDescriptor ->
descriptor is FunctionDescriptor && LookupElementFactory.hasSingleFunctionTypeParameter(descriptor)
}
return ReferenceVariants(variants.imported.filter(filter), variants.notImportedExtensions.filter(filter))
}
protected fun getRuntimeReceiverTypeReferenceVariants(lookupElementFactory: LookupElementFactory): Pair<ReferenceVariants, LookupElementFactory>? {
val evaluator = file.getCopyableUserData(KtCodeFragment.RUNTIME_TYPE_EVALUATOR) ?: return null
val referenceVariants = referenceVariantsCollector?.allCollected ?: return null
val explicitReceiver = callTypeAndReceiver.receiver as? KtExpression ?: return null
val type = bindingContext.getType(explicitReceiver) ?: return null
if (!TypeUtils.canHaveSubtypes(KotlinTypeChecker.DEFAULT, type)) return null
val runtimeType = evaluator(explicitReceiver)
if (runtimeType == null || runtimeType == type) return null
val expressionReceiver = ExpressionReceiver.create(explicitReceiver, runtimeType, bindingContext)
val (variants, notImportedExtensions) = ReferenceVariantsCollector(
referenceVariantsHelper, indicesHelper(true), prefixMatcher,
nameExpression!!, callTypeAndReceiver, resolutionFacade, bindingContext,
importableFqNameClassifier, configuration, runtimeReceiver = expressionReceiver
).collectReferenceVariants(descriptorKindFilter!!)
val filteredVariants = filterVariantsForRuntimeReceiverType(variants, referenceVariants.imported)
val filteredNotImportedExtensions =
filterVariantsForRuntimeReceiverType(notImportedExtensions, referenceVariants.notImportedExtensions)
val runtimeVariants = ReferenceVariants(filteredVariants, filteredNotImportedExtensions)
return Pair(runtimeVariants, lookupElementFactory.copy(receiverTypes = listOf(ReceiverType(runtimeType, 0))))
}
private fun <TDescriptor : DeclarationDescriptor> filterVariantsForRuntimeReceiverType(
runtimeVariants: Collection<TDescriptor>,
baseVariants: Collection<TDescriptor>
): Collection<TDescriptor> {
val baseVariantsByName = baseVariants.groupBy { it.name }
val result = ArrayList<TDescriptor>()
for (variant in runtimeVariants) {
val candidates = baseVariantsByName[variant.name]
if (candidates == null || candidates.none { compareDescriptors(project, variant, it) }) {
result.add(variant)
}
}
return result
}
protected open fun shouldCompleteTopLevelCallablesFromIndex(): Boolean {
if (nameExpression == null) return false
if ((descriptorKindFilter?.kindMask ?: 0).and(DescriptorKindFilter.CALLABLES_MASK) == 0) return false
if (callTypeAndReceiver is CallTypeAndReceiver.IMPORT_DIRECTIVE) return false
return callTypeAndReceiver.receiver == null
}
protected fun processTopLevelCallables(processor: (CallableDescriptor) -> Unit) {
val shadowedFilter = ShadowedDeclarationsFilter.create(bindingContext, resolutionFacade, nameExpression!!, callTypeAndReceiver)
?.createNonImportedDeclarationsFilter<CallableDescriptor>(referenceVariantsCollector!!.allCollected.imported)
indicesHelper(true).processTopLevelCallables({ prefixMatcher.prefixMatches(it) }) {
if (shadowedFilter != null) {
shadowedFilter(listOf(it)).singleOrNull()?.let(processor)
} else {
processor(it)
}
}
}
protected fun withCollectRequiredContextVariableTypes(action: (LookupElementFactory) -> Unit): Collection<FuzzyType> {
val provider = CollectRequiredTypesContextVariablesProvider()
val lookupElementFactory = createLookupElementFactory(provider)
action(lookupElementFactory)
return provider.requiredTypes
}
protected fun withContextVariablesProvider(contextVariablesProvider: ContextVariablesProvider, action: (LookupElementFactory) -> Unit) {
val lookupElementFactory = createLookupElementFactory(contextVariablesProvider)
action(lookupElementFactory)
}
protected open fun createLookupElementFactory(contextVariablesProvider: ContextVariablesProvider): LookupElementFactory {
return LookupElementFactory(
basicLookupElementFactory, receiverTypes,
callTypeAndReceiver.callType, inDescriptor, contextVariablesProvider
)
}
protected fun detectReceiverTypes(
bindingContext: BindingContext,
nameExpression: KtSimpleNameExpression,
callTypeAndReceiver: CallTypeAndReceiver<*, *>
): List<ReceiverType>? {
var receiverTypes = callTypeAndReceiver.receiverTypesWithIndex(
bindingContext, nameExpression, moduleDescriptor, resolutionFacade,
stableSmartCastsOnly = true, /* we don't include smart cast receiver types for "unstable" receiver value to mark members grayed */
withImplicitReceiversWhenExplicitPresent = true
)
if (callTypeAndReceiver is CallTypeAndReceiver.SAFE || isDebuggerContext) {
receiverTypes = receiverTypes?.map { ReceiverType(it.type.makeNotNullable(), it.receiverIndex) }
}
return receiverTypes
}
}
| apache-2.0 | 27bd8c909c0814f135546333b29c0022 | 45.496487 | 158 | 0.733908 | 5.983725 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/MayBeConstantInspection.kt | 1 | 5166 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.VariableDescriptor
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.inspections.MayBeConstantInspection.Status.*
import org.jetbrains.kotlin.idea.quickfix.AddConstModifierFix
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.propertyVisitor
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.hasActualModifier
import org.jetbrains.kotlin.psi.psiUtil.isObjectLiteral
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.constants.ErrorValue
import org.jetbrains.kotlin.resolve.constants.NullValue
import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator
import org.jetbrains.kotlin.resolve.constants.evaluate.isStandaloneOnlyConstant
import org.jetbrains.kotlin.resolve.jvm.annotations.hasJvmFieldAnnotation
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
class MayBeConstantInspection : AbstractKotlinInspection() {
enum class Status {
NONE,
MIGHT_BE_CONST,
MIGHT_BE_CONST_ERRONEOUS,
JVM_FIELD_MIGHT_BE_CONST,
JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER,
JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS
}
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return propertyVisitor { property ->
when (val status = property.getStatus()) {
NONE, JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER,
MIGHT_BE_CONST_ERRONEOUS, JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS -> return@propertyVisitor
MIGHT_BE_CONST, JVM_FIELD_MIGHT_BE_CONST -> {
holder.registerProblem(
property.nameIdentifier ?: property,
if (status == JVM_FIELD_MIGHT_BE_CONST)
KotlinBundle.message("const.might.be.used.instead.of.jvmfield")
else
KotlinBundle.message("might.be.const"),
ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
IntentionWrapper(AddConstModifierFix(property), property.containingFile)
)
}
}
}
}
companion object {
fun KtProperty.getStatus(): Status {
if (isLocal || isVar || getter != null ||
hasModifier(KtTokens.CONST_KEYWORD) || hasModifier(KtTokens.OVERRIDE_KEYWORD) || hasActualModifier()
) {
return NONE
}
val containingClassOrObject = this.containingClassOrObject
if (!isTopLevel && containingClassOrObject !is KtObjectDeclaration) return NONE
if (containingClassOrObject?.isObjectLiteral() == true) return NONE
val initializer = initializer
// For some reason constant evaluation does not work for property.analyze()
val context = (initializer ?: this).analyze(BodyResolveMode.PARTIAL)
val propertyDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? VariableDescriptor ?: return NONE
val type = propertyDescriptor.type
if (!KotlinBuiltIns.isPrimitiveType(type) && !KotlinBuiltIns.isString(type)) return NONE
val withJvmField = propertyDescriptor.hasJvmFieldAnnotation()
if (annotationEntries.isNotEmpty() && !withJvmField) return NONE
return when {
initializer != null -> {
val compileTimeConstant = ConstantExpressionEvaluator.getConstant(
initializer, context
) ?: return NONE
val erroneousConstant = compileTimeConstant.usesNonConstValAsConstant
compileTimeConstant.toConstantValue(propertyDescriptor.type).takeIf {
!it.isStandaloneOnlyConstant() && it !is NullValue && it !is ErrorValue
} ?: return NONE
when {
withJvmField ->
if (erroneousConstant) JVM_FIELD_MIGHT_BE_CONST_ERRONEOUS
else JVM_FIELD_MIGHT_BE_CONST
else ->
if (erroneousConstant) MIGHT_BE_CONST_ERRONEOUS
else MIGHT_BE_CONST
}
}
withJvmField -> JVM_FIELD_MIGHT_BE_CONST_NO_INITIALIZER
else -> NONE
}
}
}
}
| apache-2.0 | 72199dd714c8c010647f0514124a0a6d | 49.15534 | 158 | 0.656407 | 5.309353 | false | false | false | false |
alisle/Penella | src/main/java/org/penella/index/bstree/ObjectBSTreeIndex.kt | 1 | 1275 | package org.penella.index.bstree
import org.penella.index.IndexType
import org.penella.messages.IndexResultSet
import org.penella.structures.triples.HashTriple
import org.penella.structures.triples.TripleType
/**
* 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.
*
* Created by alisle on 11/29/16.
*/
class ObjectBSTreeIndex() : BSTreeIndex(IndexType.O) {
override fun add(triple: HashTriple) = addTriple(triple.hashObj, triple.hashSubject, triple.hashProperty)
override fun get(first: TripleType, second: TripleType, firstValue: Long, secondValue: Long) : IndexResultSet = throw InvalidIndexRequest()
override fun get(first: TripleType, value: Long ) : IndexResultSet = if(first == TripleType.OBJECT) getResults(value) else throw IncorrectIndexRequest()
}
| apache-2.0 | 1c615dab71135884ba48722e5c56278d | 46.222222 | 156 | 0.77098 | 4.099678 | false | false | false | false |
jwren/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/models/PackageScope.kt | 1 | 1240 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models
import com.intellij.openapi.util.NlsSafe
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
sealed class PackageScope(open val scopeName: String) : Comparable<PackageScope> {
@get:Nls
abstract val displayName: String
override fun compareTo(other: PackageScope): Int = scopeName.compareTo(other.scopeName)
object Missing : PackageScope("") {
@Nls
override val displayName = PackageSearchBundle.message("packagesearch.ui.missingScope")
@NonNls
override fun toString() = "[Missing scope]"
}
data class Named(@NlsSafe override val scopeName: String) : PackageScope(scopeName) {
init {
require(scopeName.isNotBlank()) { "A Named scope name cannot be blank." }
}
@Nls
override val displayName = scopeName
@NonNls
override fun toString() = scopeName
}
companion object {
fun from(rawScope: String?): PackageScope {
if (rawScope.isNullOrBlank()) return Missing
return Named(rawScope.trim())
}
}
}
| apache-2.0 | 6fe955225f7b0ab8e51afed956db0183 | 27.181818 | 95 | 0.680645 | 4.940239 | false | false | false | false |
Zeroami/CommonLib-Kotlin | commonlib/src/main/java/com/zeroami/commonlib/mvp/LBasePresenter.kt | 1 | 2155 | package com.zeroami.commonlib.mvp
import android.os.Bundle
import com.zeroami.commonlib.utils.LL
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Method
import java.lang.reflect.Proxy
/**
* BasePresenter,实现MvpPresenter,完成Presenter的通用操作
*
* @author Zeroami
*/
abstract class LBasePresenter<V : LMvpView>(view: V) : LMvpPresenter<V>, LRxSupport {
protected lateinit var mvpView: V
private set
private lateinit var emptyMvpView: V // 一个空实现的MvpView,避免V和P解除绑定时P持有的V的MvpView引用为空导致空指针
private val compositeDisposable: CompositeDisposable by lazy { CompositeDisposable() }
init {
attachView(view)
createEmptyMvpView()
}
/**
* 关联完成调用
*/
protected open fun onViewAttached() {}
/**
* 解除关联完成调用
*/
protected open fun onViewDetached() {}
override fun doViewInitialized() {}
override fun handleExtras(extras: Bundle) {}
override fun subscribeEvent() {}
override fun attachView(view: V) {
mvpView = view
onViewAttached()
}
override fun detachView() {
mvpView = emptyMvpView
compositeDisposable.clear()
onViewDetached()
}
override fun addDisposable(disposable: Disposable) {
compositeDisposable.add(disposable)
}
/**
* 创建空实现的MvpView
*/
@Suppress("UNCHECKED_CAST")
private fun createEmptyMvpView() {
emptyMvpView = Proxy.newProxyInstance(javaClass.classLoader, mvpView.javaClass.interfaces, object : InvocationHandler {
@Throws(Throwable::class)
override fun invoke(o: Any?, method: Method?, args: Array<Any>?): Any? {
LL.i("EmptyMvpView的%s方法被调用", method?.name ?: "")
if (method?.declaringClass == Any::class.java) {
return method.invoke(this, *args!!)
}
return null
}
}) as V
}
}
| apache-2.0 | e41f5a7677eada6b6d0b823676872522 | 25.298701 | 127 | 0.644938 | 4.490022 | false | false | false | false |
jwren/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesSmartSearchField.kt | 1 | 2874 | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.ui.SearchTextField
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.Subscription
import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI
import com.jetbrains.packagesearch.intellij.plugin.ui.util.scaled
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.withContext
import java.awt.Dimension
import java.awt.event.KeyEvent
class PackagesSmartSearchField(
searchFieldFocus: Flow<Unit>,
project: Project
) : SearchTextField(false) {
init {
@Suppress("MagicNumber") // Swing dimension constants
PackageSearchUI.setHeight(this, height = 25)
@Suppress("MagicNumber") // Swing dimension constants
minimumSize = Dimension(100.scaled(), minimumSize.height)
textEditor.setTextToTriggerEmptyTextStatus(PackageSearchBundle.message("packagesearch.search.hint"))
textEditor.emptyText.isShowAboveCenter = true
PackageSearchUI.overrideKeyStroke(textEditor, "shift ENTER", this::transferFocusBackward)
searchFieldFocus
.onEach { withContext(Dispatchers.EDT) { requestFocus() } }
.launchIn(project.lifecycleScope)
}
/**
* Trying to navigate to the first element in the brief list
* @return true in case of success; false if the list is empty
*/
var goToTable: () -> Boolean = { false }
var fieldClearedListener: (() -> Unit)? = null
private val listeners = mutableSetOf<(KeyEvent) -> Unit>()
fun registerOnKeyPressedListener(action: (KeyEvent) -> Unit): Subscription {
listeners.add(action)
return Subscription { listeners.remove(action) }
}
override fun preprocessEventForTextField(e: KeyEvent?): Boolean {
e?.let { keyEvent -> listeners.forEach { listener -> listener(keyEvent) } }
if (e?.keyCode == KeyEvent.VK_DOWN || e?.keyCode == KeyEvent.VK_PAGE_DOWN) {
goToTable() // trying to navigate to the list instead of "show history"
e.consume() // suppress default "show history" logic anyway
return true
}
return super.preprocessEventForTextField(e)
}
override fun getBackground() = PackageSearchUI.HeaderBackgroundColor
override fun onFocusLost() {
super.onFocusLost()
addCurrentTextToHistory()
}
override fun onFieldCleared() {
super.onFieldCleared()
fieldClearedListener?.invoke()
}
}
| apache-2.0 | 793633faaec4855e82f3eb1b1eba3b9b | 36.324675 | 108 | 0.723382 | 4.79 | false | false | false | false |
OnyxDevTools/onyx-database-parent | onyx-database-tests/src/main/kotlin/servers/SampleDatabaseServer.kt | 1 | 1068 | package servers
import com.onyx.application.impl.WebDatabaseServer
import com.onyx.persistence.IManagedEntity
import entities.SimpleEntity
/**
* Created by timothy.osborn on 4/1/15.
*/
class SampleDatabaseServer(databaseLocation: String) : WebDatabaseServer(databaseLocation) {
companion object {
/**
* Run Database Server
*
* ex: executable /Database/Location/On/Disk 8080 admin admin
*
* @param args
* @throws Exception
*/
@Throws(Exception::class)
@JvmStatic fun main(args: Array<String>) {
val server1 = SampleDatabaseServer("C:/Sandbox/Onyx/Tests/server.oxd")
server1.port = 8080
server1.webServicePort = 8082
server1.start()
val simpleEntity = SimpleEntity()
simpleEntity.name = "Test Name"
simpleEntity.simpleId = "ASDF"
server1.persistenceManager.saveEntity<IManagedEntity>(simpleEntity)
server1.join()
println("Started")
}
}
}
| agpl-3.0 | 195329b194c0e70abee2f439a06cd23b | 27.105263 | 92 | 0.613296 | 4.583691 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/formatter/src/org/jetbrains/kotlin/idea/formatter/trailingComma/TrailingCommaHelper.kt | 4 | 4528 | // 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.formatter.trailingComma
import com.intellij.psi.PsiElement
import com.intellij.psi.codeStyle.CodeStyleSettings
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.PsiUtil
import org.jetbrains.kotlin.idea.formatter.kotlinCustomSettings
import org.jetbrains.kotlin.idea.util.isComma
import org.jetbrains.kotlin.idea.util.isLineBreak
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespace
import org.jetbrains.kotlin.idea.util.leafIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.nextLeaf
import org.jetbrains.kotlin.psi.psiUtil.prevLeaf
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.utils.addToStdlib.cast
object TrailingCommaHelper {
fun findInvalidCommas(commaOwner: KtElement): List<PsiElement> = commaOwner.firstChild
?.siblings(withItself = false)
?.filter { it.isComma }
?.filter {
it.prevLeaf(true)?.isLineBreak() == true || it.leafIgnoringWhitespace(false) != it.leafIgnoringWhitespaceAndComments(false)
}?.toList().orEmpty()
fun trailingCommaExistsOrCanExist(psiElement: PsiElement, settings: CodeStyleSettings): Boolean =
TrailingCommaContext.create(psiElement).commaExistsOrMayExist(settings.kotlinCustomSettings)
fun trailingCommaExists(commaOwner: KtElement): Boolean = when (commaOwner) {
is KtFunctionLiteral -> commaOwner.valueParameterList?.trailingComma != null
is KtWhenEntry -> commaOwner.trailingComma != null
is KtDestructuringDeclaration -> commaOwner.trailingComma != null
else -> trailingCommaOrLastElement(commaOwner)?.isComma == true
}
fun trailingCommaOrLastElement(commaOwner: KtElement): PsiElement? {
val lastChild = commaOwner.lastSignificantChild ?: return null
val withSelf = when (PsiUtil.getElementType(lastChild)) {
KtTokens.COMMA -> return lastChild
in RIGHT_BARRIERS -> false
else -> true
}
return lastChild.getPrevSiblingIgnoringWhitespaceAndComments(withSelf)?.takeIf {
PsiUtil.getElementType(it) !in LEFT_BARRIERS
}?.takeIfIsNotError()
}
/**
* @return true if [commaOwner] has a trailing comma and hasn't a line break before the first or after the last element
*/
fun lineBreakIsMissing(commaOwner: KtElement): Boolean {
if (!trailingCommaExists(commaOwner)) return false
val first = elementBeforeFirstElement(commaOwner)
if (first?.nextLeaf(true)?.isLineBreak() == false) return true
val last = elementAfterLastElement(commaOwner)
return last?.prevLeaf(true)?.isLineBreak() == false
}
fun elementBeforeFirstElement(commaOwner: KtElement): PsiElement? = when (commaOwner) {
is KtParameterList -> {
val parent = commaOwner.parent
if (parent is KtFunctionLiteral) parent.lBrace else commaOwner.leftParenthesis
}
is KtWhenEntry -> commaOwner.parent.cast<KtWhenExpression>().openBrace
is KtDestructuringDeclaration -> commaOwner.lPar
else -> commaOwner.firstChild?.takeIfIsNotError()
}
fun elementAfterLastElement(commaOwner: KtElement): PsiElement? = when (commaOwner) {
is KtParameterList -> {
val parent = commaOwner.parent
if (parent is KtFunctionLiteral) parent.arrow else commaOwner.rightParenthesis
}
is KtWhenEntry -> commaOwner.arrow
is KtDestructuringDeclaration -> commaOwner.rPar
else -> commaOwner.lastChild?.takeIfIsNotError()
}
private fun PsiElement.takeIfIsNotError(): PsiElement? = takeIf { !PsiTreeUtil.hasErrorElements(it) }
private val RIGHT_BARRIERS = TokenSet.create(KtTokens.RBRACKET, KtTokens.RPAR, KtTokens.RBRACE, KtTokens.GT, KtTokens.ARROW)
private val LEFT_BARRIERS = TokenSet.create(KtTokens.LBRACKET, KtTokens.LPAR, KtTokens.LBRACE, KtTokens.LT)
private val PsiElement.lastSignificantChild: PsiElement?
get() = when (this) {
is KtWhenEntry -> arrow
is KtDestructuringDeclaration -> rPar
else -> lastChild
}
} | apache-2.0 | 9ee415285dffadc4602a7a34f712096c | 45.690722 | 158 | 0.728357 | 5.093363 | false | false | false | false |
smmribeiro/intellij-community | platform/platform-api/src/com/intellij/ide/browsers/BrowserLauncher.kt | 12 | 1322 | // 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.ide.browsers
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.util.ArrayUtil
import java.io.File
import java.net.URI
import java.nio.file.Path
abstract class BrowserLauncher {
companion object {
@JvmStatic
val instance: BrowserLauncher
get() = ApplicationManager.getApplication().getService(BrowserLauncher::class.java)
}
abstract fun open(url: String)
abstract fun browse(file: File)
abstract fun browse(file: Path)
fun browse(uri: URI): Unit = browse(uri.toString(), null, null)
fun browse(url: String, browser: WebBrowser?): Unit = browse(url, browser, null)
abstract fun browse(url: String, browser: WebBrowser? = null, project: Project? = null)
abstract fun browseUsingPath(url: String?,
browserPath: String? = null,
browser: WebBrowser? = null,
project: Project? = null,
openInNewWindow: Boolean = false,
additionalParameters: Array<String> = ArrayUtil.EMPTY_STRING_ARRAY): Boolean
} | apache-2.0 | 465b44b530cbc94db8fbcf78eda5ceed | 34.756757 | 140 | 0.66944 | 4.590278 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/kdoc/KDocTypedHandler.kt | 6 | 3527 | // 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.kdoc
import com.intellij.codeInsight.CodeInsightSettings
import com.intellij.codeInsight.editorActions.TypedHandlerDelegate
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.kdoc.lexer.KDocTokens
import org.jetbrains.kotlin.psi.KtFile
class KDocTypedHandler : TypedHandlerDelegate() {
override fun beforeCharTyped(c: Char, project: Project, editor: Editor, file: PsiFile, fileType: FileType): Result {
if (overwriteClosingBracket(c, editor, file)) {
EditorModificationUtil.moveCaretRelatively(editor, 1)
return Result.STOP
}
return Result.CONTINUE
}
override fun charTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Result =
if (handleBracketTyped(c, project, editor, file)) Result.STOP else Result.CONTINUE
private fun overwriteClosingBracket(c: Char, editor: Editor, file: PsiFile): Boolean {
if (c != ']' && c != ')') return false
if (file !is KtFile) return false
if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) return false
val offset = editor.caretModel.offset
val document = editor.document
val chars = document.charsSequence
if (offset < document.textLength && chars[offset] == c) {
val iterator = (editor as EditorEx).highlighter.createIterator(offset)
val elementType = iterator.tokenType
if (iterator.start == 0) return false
iterator.retreat()
val prevElementType = iterator.tokenType
return when (c) {
']' -> {
// if the bracket is not part of a link, it will be part of KDOC_TEXT, not a separate RBRACKET element
prevElementType in KDocTokens.KDOC_HIGHLIGHT_TOKENS && (elementType == KDocTokens.MARKDOWN_LINK || (offset > 0 && chars[offset - 1] == '['))
}
')' -> elementType == KDocTokens.MARKDOWN_INLINE_LINK
else -> false
}
}
return false
}
private fun handleBracketTyped(c: Char, project: Project, editor: Editor, file: PsiFile): Boolean {
if (c != '[' && c != '(') return false
if (file !is KtFile) return false
if (!CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) return false
val offset = editor.caretModel.offset
if (offset == 0) return false
val document = editor.document
PsiDocumentManager.getInstance(project).commitDocument(document)
val element = file.findElementAt(offset - 1) ?: return false
if (element.node.elementType != KDocTokens.TEXT) return false
when (c) {
'[' -> {
document.insertString(offset, "]")
return true
}
'(' -> {
if (offset > 1 && document.charsSequence[offset - 2] == ']') {
document.insertString(offset, ")")
return true
}
}
}
return false
}
}
| apache-2.0 | 45196e426e8c4c994d172bf7e37d944b | 40.011628 | 160 | 0.63425 | 4.772666 | false | false | false | false |
mglukhikh/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/processors/FindFirstProcessor.kt | 2 | 1181 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.processors
import com.intellij.psi.PsiElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.ProcessorWithHints
import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult
import org.jetbrains.plugins.groovy.lang.resolve.GrResolverProcessor
abstract class FindFirstProcessor<out T : GroovyResolveResult>(protected val name: String) : ProcessorWithHints(), GrResolverProcessor<T> {
init {
hint(NameHint.KEY, NameHint { name })
}
private var result: T? = null
final override val results: List<T> get() = result?.let { listOf(it) } ?: emptyList()
final override fun execute(element: PsiElement, state: ResolveState): Boolean {
if (shouldStop()) return false
assert(result == null)
result = result(element, state)
return !shouldStop() && result == null
}
protected abstract fun result(element: PsiElement, state: ResolveState): T?
protected open fun shouldStop(): Boolean = false
}
| apache-2.0 | 4fef1522b4f39dd37afbefe7eb7a37fa | 37.096774 | 140 | 0.757832 | 4.202847 | false | false | false | false |
smmribeiro/intellij-community | platform/lang-impl/src/com/intellij/model/presentation/impl/DefaultSymbolPresentation.kt | 12 | 806 | // 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.model.presentation.impl
import com.intellij.model.presentation.SymbolPresentation
import org.jetbrains.annotations.Nls
import javax.swing.Icon
internal class DefaultSymbolPresentation(
private val icon: Icon?,
@Nls private val typeString: String,
@Nls private val shortNameString: String,
@Nls private val longNameString: String? = shortNameString
) : SymbolPresentation {
override fun getIcon(): Icon? = icon
override fun getShortNameString(): String = shortNameString
override fun getShortDescription(): String = "$typeString '$shortNameString'"
override fun getLongDescription(): String = "$typeString '$longNameString'"
}
| apache-2.0 | 42a677f95bf13b04323133824afc4cc0 | 43.777778 | 140 | 0.784119 | 4.52809 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/main/java/fr/free/nrw/commons/nearby/fragments/CommonPlaceClickActions.kt | 1 | 3826 | package fr.free.nrw.commons.nearby.fragments
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.view.MenuItem
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.PopupMenu
import fr.free.nrw.commons.R
import fr.free.nrw.commons.Utils
import fr.free.nrw.commons.auth.LoginActivity
import fr.free.nrw.commons.contributions.ContributionController
import fr.free.nrw.commons.kvstore.JsonKvStore
import fr.free.nrw.commons.nearby.Place
import fr.free.nrw.commons.utils.ActivityUtils
import fr.free.nrw.commons.wikidata.WikidataConstants
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Named
class CommonPlaceClickActions @Inject constructor(
@Named("default_preferences") private val applicationKvStore: JsonKvStore,
private val activity: Activity,
private val contributionController: ContributionController
) {
fun onCameraClicked(): (Place) -> Unit = {
if (applicationKvStore.getBoolean("login_skipped", false)) {
showLoginDialog()
} else {
Timber.d("Camera button tapped. Image title: ${it.getName()}Image desc: ${it.longDescription}")
storeSharedPrefs(it)
contributionController.initiateCameraPick(activity)
}
}
fun onGalleryClicked(): (Place) -> Unit = {
if (applicationKvStore.getBoolean("login_skipped", false)) {
showLoginDialog()
} else {
Timber.d("Gallery button tapped. Image title: ${it.getName()}Image desc: ${it.getLongDescription()}")
storeSharedPrefs(it)
contributionController.initiateGalleryPick(activity, false)
}
}
fun onOverflowClicked(): (Place, View) -> Unit = { place, view ->
PopupMenu(view.context, view).apply {
inflate(R.menu.nearby_info_dialog_options)
enableBy(R.id.nearby_info_menu_commons_article, place.hasCommonsLink())
enableBy(R.id.nearby_info_menu_wikidata_article, place.hasWikidataLink())
enableBy(R.id.nearby_info_menu_wikipedia_article, place.hasWikipediaLink())
setOnMenuItemClickListener { item: MenuItem ->
when (item.itemId) {
R.id.nearby_info_menu_commons_article -> openWebView(place.siteLinks.commonsLink)
R.id.nearby_info_menu_wikidata_article -> openWebView(place.siteLinks.wikidataLink)
R.id.nearby_info_menu_wikipedia_article -> openWebView(place.siteLinks.wikipediaLink)
else -> false
}
}
}.show()
}
fun onDirectionsClicked(): (Place) -> Unit = {
Utils.handleGeoCoordinates(activity, it.getLocation())
}
private fun storeSharedPrefs(selectedPlace: Place) {
Timber.d("Store place object %s", selectedPlace.toString())
applicationKvStore.putJson(WikidataConstants.PLACE_OBJECT, selectedPlace)
}
private fun openWebView(link: Uri): Boolean {
Utils.handleWebUrl(activity, link)
return true;
}
private fun PopupMenu.enableBy(menuId: Int, hasLink: Boolean) {
menu.findItem(menuId).isEnabled = hasLink
}
private fun showLoginDialog() {
AlertDialog.Builder(activity)
.setMessage(R.string.login_alert_message)
.setPositiveButton(R.string.login) { dialog, which ->
ActivityUtils.startActivityWithFlags(
activity,
LoginActivity::class.java,
Intent.FLAG_ACTIVITY_CLEAR_TOP,
Intent.FLAG_ACTIVITY_SINGLE_TOP
)
applicationKvStore.putBoolean("login_skipped", false)
activity.finish()
}
.show()
}
}
| apache-2.0 | d3fd33622b08f4c44f2cb53b40514e4c | 37.646465 | 113 | 0.656038 | 4.407834 | false | false | false | false |
spring-projects/spring-security | config/src/main/kotlin/org/springframework/security/config/annotation/web/oauth2/resourceserver/OpaqueTokenDsl.kt | 1 | 3475 | /*
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 org.springframework.security.config.annotation.web.oauth2.resourceserver
import org.springframework.security.authentication.AuthenticationManager
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configurers.oauth2.server.resource.OAuth2ResourceServerConfigurer
import org.springframework.security.core.Authentication
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenAuthenticationConverter
import org.springframework.security.oauth2.server.resource.introspection.OpaqueTokenIntrospector
/**
* A Kotlin DSL to configure opaque token Resource Server Support using idiomatic Kotlin code.
*
* @author Eleftheria Stein
* @since 5.3
* @property introspectionUri the URI of the Introspection endpoint.
* @property introspector the [OpaqueTokenIntrospector] to use.
* @property authenticationManager the [AuthenticationManager] used to determine if the provided
* [Authentication] can be authenticated.
*/
@OAuth2ResourceServerSecurityMarker
class OpaqueTokenDsl {
private var _introspectionUri: String? = null
private var _introspector: OpaqueTokenIntrospector? = null
private var clientCredentials: Pair<String, String>? = null
var authenticationManager: AuthenticationManager? = null
var introspectionUri: String?
get() = _introspectionUri
set(value) {
_introspectionUri = value
_introspector = null
}
var introspector: OpaqueTokenIntrospector?
get() = _introspector
set(value) {
_introspector = value
_introspectionUri = null
clientCredentials = null
}
var authenticationConverter: OpaqueTokenAuthenticationConverter? = null
/**
* Configures the credentials for Introspection endpoint.
*
* @param clientId the clientId part of the credentials.
* @param clientSecret the clientSecret part of the credentials.
*/
fun introspectionClientCredentials(clientId: String, clientSecret: String) {
clientCredentials = Pair(clientId, clientSecret)
_introspector = null
}
internal fun get(): (OAuth2ResourceServerConfigurer<HttpSecurity>.OpaqueTokenConfigurer) -> Unit {
return { opaqueToken ->
introspectionUri?.also { opaqueToken.introspectionUri(introspectionUri) }
introspector?.also { opaqueToken.introspector(introspector) }
authenticationConverter?.also { opaqueToken.authenticationConverter(authenticationConverter) }
clientCredentials?.also { opaqueToken.introspectionClientCredentials(clientCredentials!!.first, clientCredentials!!.second) }
authenticationManager?.also { opaqueToken.authenticationManager(authenticationManager) }
}
}
}
| apache-2.0 | 83f750ca91208b75810ed5ae0b9b7717 | 42.4375 | 137 | 0.747338 | 5.171131 | false | true | false | false |
Heapy/komodo | komodo-config-dotenv/src/main/kotlin/io/heapy/komodo/config/dotenv/Dotenv.kt | 1 | 2079 | package io.heapy.komodo.config.dotenv
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* Wrapper for [System.getenv], for easy testing and extensibility.
*
* @author Ruslan Ibragimov
* @since 1.0
*/
interface Env {
/**
* Throws exception, if env not found
*/
fun get(env: String): String {
return getOrNull(env)
?: throw EnvNotDefinedException("$env not defined.")
}
/**
* Returns null, if env not found
*/
fun getOrNull(env: String): String?
}
class EnvNotDefinedException(message: String) : RuntimeException(message)
class Dotenv(
/**
* Env file location
*/
private val file: Path = Paths.get(".env"),
/**
* Env variable that overrides env file location
*/
private val fileEnv: String = "KOMODO_DOTENV_FILE",
/**
* Ignore file if it doesn't exists
*/
private val ignoreIfMissing: Boolean = true,
/**
* System env variables
*/
private val system: Map<String, String> = System.getenv()
) : Env {
private val vars = getEnvironmentVariables()
override fun getOrNull(env: String): String? {
return vars[env]
}
internal fun getEnvironmentVariables(): Map<String, String> {
val resolvedFile = system[fileEnv]?.let { Paths.get(it) } ?: file
return if (Files.exists(resolvedFile)) {
Files.readAllLines(resolvedFile)
.filterNot { it.startsWith("#") }
.filterNot { it.isNullOrEmpty() }
.map {
val (name, value) = it.split("=", limit = 2)
name to value
}
.toMap()
.plus(system)
} else {
if (ignoreIfMissing) {
mapOf<String, String>().plus(system)
} else {
throw DotenvFileNotFoundException("File ${resolvedFile.toAbsolutePath()} not exists")
}
}
}
}
class DotenvFileNotFoundException(message: String) : RuntimeException(message)
| lgpl-3.0 | 9e8e99eb1d761064bf40f480f40245c8 | 24.9875 | 101 | 0.576239 | 4.367647 | false | false | false | false |
migafgarcia/programming-challenges | advent_of_code/2018/solutions/day_12_a.kt | 1 | 1468 | import java.io.File
// 2463
fun main(args: Array<String>) {
assert(score(".#....##....#####...#######....#.#..##.", 3) == 325)
val regex = Regex(".* => .*")
val margin = 3
val lines = File(args[0]).readLines()
var leftPots = 0
var state = StringBuilder(lines[0].split(":")[1].trim())
val transitions = lines.filter { it.matches(regex) }.map { line ->
val split = line.split("=>")
Pair(split[0].trim(), split[1].trim()[0])
}.toMap()
println("0 -> $state")
for (gen in 1..20) {
val leftEmptyPots = CharArray(maxOf(margin - state.indexOf('#'), 0)) { '.' }
state.insert(0, leftEmptyPots)
leftPots += leftEmptyPots.size
val rightEmptyPots = CharArray(maxOf(margin - (state.length - state.lastIndexOf('#')), 0) + 1) { '.' }
state.append(rightEmptyPots)
val nextState = StringBuilder(state)
transitions.forEach { t, u ->
var patternIndex = state.indexOf(t, 0)
while (patternIndex != -1) {
nextState[patternIndex + 2] = u
patternIndex = state.indexOf(t, patternIndex + 1)
}
}
state = nextState
println("$gen -> $state")
}
val sum = score(state.toString(), leftPots)
println(sum)
}
private fun score(state: String, leftPots: Int): Int =
(0 until state.length)
.filter { state[it] == '#' }
.sumBy { it - leftPots }
| mit | 3772541abcd2af6f6235cff1bc57367c | 23.065574 | 110 | 0.52861 | 3.842932 | false | false | false | false |
JakeWharton/dex-method-list | diffuse/src/main/kotlin/com/jakewharton/diffuse/diff/ApkDiff.kt | 1 | 897 | package com.jakewharton.diffuse.diff
import com.jakewharton.diffuse.ApiMapping
import com.jakewharton.diffuse.Apk
import com.jakewharton.diffuse.diff.lint.resourcesArscCompression
import com.jakewharton.diffuse.report.DiffReport
import com.jakewharton.diffuse.report.text.ApkDiffTextReport
internal class ApkDiff(
val oldApk: Apk,
val oldMapping: ApiMapping,
val newApk: Apk,
val newMapping: ApiMapping
) : BinaryDiff {
val archive = ArchiveFilesDiff(oldApk.files, newApk.files)
val signatures = SignaturesDiff(oldApk.signatures, newApk.signatures)
val dex = DexDiff(oldApk.dexes, oldMapping, newApk.dexes, newMapping)
val arsc = ArscDiff(oldApk.arsc, newApk.arsc)
val manifest = ManifestDiff(oldApk.manifest, newApk.manifest)
val lintMessages = listOfNotNull(
archive.resourcesArscCompression())
override fun toTextReport(): DiffReport = ApkDiffTextReport(this)
}
| apache-2.0 | 8dfd4a71b1a89c5c0c6cd381ce581fe6 | 34.88 | 71 | 0.798216 | 3.969027 | false | false | false | false |
paoloach/zdomus | temperature_monitor/app/src/main/java/it/achdjian/paolo/temperaturemonitor/rajawali/TemperatureColorMap.kt | 1 | 1491 | package it.achdjian.paolo.temperaturemonitor.rajawali
import android.util.SparseIntArray
/**
* Created by Paolo Achdjian on 07/09/16.
*/
object TemperatureColorMap {
private val MAP_TEMP_COLOR = SparseIntArray()
init {
MAP_TEMP_COLOR.put(13, 0xFF0000E0.toInt())
MAP_TEMP_COLOR.put(14, 0xFF0000C0.toInt())
MAP_TEMP_COLOR.put(15, 0xFF0000A0.toInt())
MAP_TEMP_COLOR.put(16, 0xFF000080.toInt())
MAP_TEMP_COLOR.put(17, 0xFF000060.toInt())
MAP_TEMP_COLOR.put(18, 0xFF000040.toInt())
MAP_TEMP_COLOR.put(19, 0xFF008020.toInt())
MAP_TEMP_COLOR.put(20, 0xFF00FA00.toInt())
MAP_TEMP_COLOR.put(21, 0xFF19E100.toInt())
MAP_TEMP_COLOR.put(22, 0xFF32C800.toInt())
MAP_TEMP_COLOR.put(23, 0xFF4BAF00.toInt())
MAP_TEMP_COLOR.put(24, 0xFF649600.toInt())
MAP_TEMP_COLOR.put(25, 0xFF7D7D00.toInt())
MAP_TEMP_COLOR.put(26, 0xFF966400.toInt())
MAP_TEMP_COLOR.put(27, 0xFFAF4B00.toInt())
MAP_TEMP_COLOR.put(28, 0xFFC83200.toInt())
MAP_TEMP_COLOR.put(29, 0xFFE11900.toInt())
MAP_TEMP_COLOR.put(30, 0xFFFA0000.toInt())
}
fun getColor(temperature: Int): Int {
val temp = temperature / 100
val color: Int
if (temp < 13) {
color = 0xFF0000FF.toInt()
} else if (temp > 30) {
color = 0xFFFF0000.toInt()
} else {
color = MAP_TEMP_COLOR[temp]
}
return color
}
}
| gpl-2.0 | 06042b914f858b7ac793125338ad3fd8 | 32.886364 | 53 | 0.607646 | 3.119247 | false | false | false | false |
seventhroot/elysium | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/servlet/ProfileSignInServlet.kt | 1 | 3771 | /*
* Copyright 2019 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.servlet
import com.rpkit.core.web.Alert
import com.rpkit.core.web.Alert.Type.DANGER
import com.rpkit.core.web.RPKServlet
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.profile.RPKProfileProvider
import org.apache.velocity.VelocityContext
import org.apache.velocity.app.Velocity
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import javax.servlet.http.HttpServletResponse.SC_OK
class ProfileSignInServlet(private val plugin: RPKPlayersBukkit): RPKServlet() {
override val url = "/profiles/signin/"
override fun doGet(req: HttpServletRequest, resp: HttpServletResponse) {
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val activeProfile = profileProvider.getActiveProfile(req)
if (activeProfile != null) {
resp.sendRedirect("/profiles/")
return
}
resp.contentType = "text/html"
resp.status = SC_OK
val templateBuilder = StringBuilder()
val scanner = Scanner(javaClass.getResourceAsStream("/web/signin.html"))
while (scanner.hasNextLine()) {
templateBuilder.append(scanner.nextLine()).append('\n')
}
scanner.close()
val velocityContext = VelocityContext()
velocityContext.put("server", plugin.core.web.title)
velocityContext.put("navigationBar", plugin.core.web.navigationBar)
velocityContext.put("alerts", listOf<Alert>())
Velocity.evaluate(velocityContext, resp.writer, "/web/signin.html", templateBuilder.toString())
}
override fun doPost(req: HttpServletRequest, resp: HttpServletResponse) {
val name = req.getParameter("name")
val password = req.getParameter("password")
val profileProvider = plugin.core.serviceManager.getServiceProvider(RPKProfileProvider::class)
val profile = profileProvider.getProfile(name)
val alerts = mutableListOf<Alert>()
if (profile != null) {
if (profile.checkPassword(password.toCharArray())) {
profileProvider.setActiveProfile(req, profile)
resp.sendRedirect("/profiles/")
return
} else {
alerts.add(Alert(DANGER, "Incorrect username or password."))
}
} else {
alerts.add(Alert(DANGER, "Incorrect username or password."))
}
resp.contentType = "text/html"
resp.status = SC_OK
val templateBuilder = StringBuilder()
val scanner = Scanner(javaClass.getResourceAsStream("/web/signin.html"))
while (scanner.hasNextLine()) {
templateBuilder.append(scanner.nextLine()).append('\n')
}
scanner.close()
val velocityContext = VelocityContext()
velocityContext.put("server", plugin.core.web.title)
velocityContext.put("navigationBar", plugin.core.web.navigationBar)
velocityContext.put("alerts", alerts)
Velocity.evaluate(velocityContext, resp.writer, "/web/signin.html", templateBuilder.toString())
}
} | apache-2.0 | e8472d5cc1a477acc3e087a97a6ef3b0 | 40.911111 | 103 | 0.688942 | 4.743396 | false | false | false | false |
yousuf-haque/Titan | app/src/main/kotlin/com/yohaq/titan/ui/createWorkoutScreen/CreateWorkoutViewModel.kt | 1 | 1773 | package com.yohaq.titan.ui.createWorkoutScreen
import com.jakewharton.rxrelay.PublishRelay
import com.yohaq.titan.data.interactors.CreateWorkoutInteractor
import com.yohaq.titan.data.models.Exercise
import com.yohaq.titan.data.models.WorkoutSet
import rx.Observable
import rx.functions.Action1
import java.util.*
import javax.inject.Inject
/**
* Created by yousufhaque on 6/8/16.
*/
class CreateWorkoutViewModel
@Inject constructor(private val createWorkoutInteractor: CreateWorkoutInteractor) {
val onDateUpdate : Action1<Date>
val onExerciseUpdate : Action1<Exercise>
val onSetListUpdate: Action1<List<WorkoutSet>>
val onCreateWorkout: Action1<Unit>
private val dateObservable : Observable<Date>
private val exerciseObservable : Observable<Exercise>
private val setListObservable : Observable<List<WorkoutSet>>
private val createWorkoutObservable : Observable<Unit>
init {
val dateRelay = PublishRelay.create<Date>()
val exerciseRelay = PublishRelay.create<Exercise>()
val setListRelay = PublishRelay.create<List<WorkoutSet>>()
val createWorkoutRelay = PublishRelay.create<Unit>()
onDateUpdate = dateRelay.asAction()
onExerciseUpdate = exerciseRelay.asAction()
onSetListUpdate = setListRelay.asAction()
onCreateWorkout = createWorkoutRelay.asAction()
dateObservable = dateRelay.asObservable()
exerciseObservable = exerciseRelay.asObservable()
setListObservable = setListRelay.asObservable()
createWorkoutObservable = createWorkoutRelay.asObservable()
}
fun createWorkout(dateCreated: Date, exercise: Exercise, sets: List<WorkoutSet>) {
createWorkoutInteractor.createWorkout(dateCreated, exercise, sets)
}
} | apache-2.0 | 2c803cbb2213289386e14166ec27321c | 33.784314 | 86 | 0.753525 | 4.605195 | false | false | false | false |
diareuse/mCache | app/src/main/java/wiki/depasquale/mcachepreview/MainActivity.kt | 1 | 3292 | package wiki.depasquale.mcachepreview
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.google.gson.Gson
import com.orhanobut.logger.Logger
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.functions.Consumer
import io.reactivex.rxkotlin.addTo
import kotlinx.android.synthetic.main.activity_main.*
import wiki.depasquale.mcache.BuildConfig
import wiki.depasquale.mcache.Cache
import java.util.Locale
class MainActivity : AppCompatActivity(), Consumer<User> {
private var startTime: Long = 0
private val disposables = CompositeDisposable()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
et.setText("diareuse")
et.post { fab.performClick() }
plugin.text = BuildConfig.VERSION_NAME
fab.setOnClickListener {
message.text = null
user.text = null
responseTime.text = null
val username = et.text.toString()
if (username.isEmpty()) {
input.error = "Please fill this field :)"
input.isErrorEnabled = true
} else {
when {
username.equals(
"clean",
ignoreCase = true
) -> Cache.obtain(User::class.java).build().delete()
username.equals("removeall", ignoreCase = true) -> removeAll()
else -> retrieveUser(username)
}
}
}
}
private fun removeAll() {
startTime = System.nanoTime()
Cache.obtain(Cache::class.java)
.build()
.deleteLater()
.subscribe({ success ->
responseTime.append(if (responseTime.text.isNotEmpty()) "\n" else "")
responseTime.append(
String.format(
Locale.getDefault(), "%d ms",
(System.nanoTime() - startTime) / 1000000
)
)
message.text = if (success) "OK" else "FAILED"
})
.addTo(disposables)
}
private fun retrieveUser(username: String) {
input.isErrorEnabled = false
user.text = String.format("/users/%s", username)
startTime = System.nanoTime()
Github.user(username)
.subscribe(this,
Consumer<Throwable> { error ->
error.printStackTrace()
Toast.makeText(this, error.message, Toast.LENGTH_SHORT).show()
})
.addTo(disposables)
}
@Throws(Exception::class)
override fun accept(user: User) {
Logger.d("User@${user.login} accepted")
responseTime.append(if (responseTime.text.isNotEmpty()) "\n" else "")
responseTime.append(
String.format(
Locale.getDefault(), "%d ms",
(System.nanoTime() - startTime) / 1000000
)
)
message.text = Gson().toJson(user)
}
override fun onDestroy() {
disposables.dispose()
super.onDestroy()
}
}
| apache-2.0 | b9c8919f0e9fa05150df7026f2da3f4a | 31.27451 | 85 | 0.562272 | 4.90611 | false | false | false | false |
EMResearch/EvoMaster | core/src/main/kotlin/org/evomaster/core/problem/util/inference/model/MatchedInfo.kt | 1 | 1177 | package org.evomaster.core.problem.util.inference.model
import org.evomaster.core.problem.util.StringSimilarityComparator
import kotlin.math.min
/**
* the class is used when applying parser to derive possible relationship between two named entities (e.g., resource with table name)
* @property input for matching
* @property targetMatched presents what are matched regarding a target
* @property similarity presents a degree of similarity
* @property inputIndicator presents a depth-level of input, e.g., token on resource path is level 0, token on description is level 1
* @property outputIndicator presents a depth-level of target to match, e.g., name of table is level 0, name of a column of a table is level 1
*/
open class MatchedInfo(val input : String, val targetMatched : String, var similarity : Double, var inputIndicator : Int = 0, var outputIndicator : Int = 0){
fun modifySimilarity(times : Double = 0.9){
similarity *= times
if (similarity > 1.0) similarity = 1.0
}
fun setMax(){
similarity = 1.0
}
fun setMin(){
similarity = min(similarity, StringSimilarityComparator.SimilarityThreshold)
}
}
| lgpl-3.0 | c351527ebb1b0bceb7b30a1a2afad527 | 39.586207 | 157 | 0.729822 | 4.29562 | false | false | false | false |
grote/Liberario | app/src/main/java/de/grobox/transportr/ui/TimeDateFragment.kt | 1 | 5552 | /*
* Transportr
*
* Copyright (c) 2013 - 2018 Torsten Grote
*
* 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.grobox.transportr.ui
import android.app.DatePickerDialog
import android.app.DatePickerDialog.OnDateSetListener
import android.os.Bundle
import android.text.format.DateFormat.getDateFormat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.DatePicker
import android.widget.TimePicker
import android.widget.TimePicker.OnTimeChangedListener
import androidx.fragment.app.DialogFragment
import de.grobox.transportr.R
import kotlinx.android.synthetic.main.fragment_time_date.*
import java.util.*
import java.util.Calendar.*
class TimeDateFragment : DialogFragment(), OnDateSetListener, OnTimeChangedListener {
private var listener: TimeDateListener? = null
private lateinit var calendar: Calendar
companion object {
@JvmField
val TAG: String = TimeDateFragment::class.java.simpleName
private val CALENDAR = "calendar"
@JvmStatic
fun newInstance(calendar: Calendar): TimeDateFragment {
val f = TimeDateFragment()
val args = Bundle()
args.putSerializable(CALENDAR, calendar)
f.arguments = args
return f
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
calendar = if (savedInstanceState == null) {
arguments?.let {
it.getSerializable(CALENDAR) as Calendar
} ?: throw IllegalArgumentException("Arguments missing")
} else {
savedInstanceState.getSerializable(CALENDAR) as Calendar
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_time_date, container)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Time
timePicker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(context))
timePicker.setOnTimeChangedListener(this)
showTime(calendar)
// Date
dateView.setOnClickListener {
DatePickerDialog(context!!, this@TimeDateFragment, calendar.get(YEAR), calendar.get(MONTH), calendar.get(DAY_OF_MONTH))
.show()
}
showDate(calendar)
// Previous and Next Date
prevDateButton.setOnClickListener {
calendar.add(DAY_OF_MONTH, -1)
showDate(calendar)
}
nextDateButton.setOnClickListener {
calendar.add(DAY_OF_MONTH, 1)
showDate(calendar)
}
// Buttons
okButton.setOnClickListener {
listener?.onTimeAndDateSet(calendar)
dismiss()
}
nowButton.setOnClickListener {
listener?.onTimeAndDateSet(Calendar.getInstance())
dismiss()
}
cancelButton.setOnClickListener {
dismiss()
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putSerializable(CALENDAR, calendar)
}
override fun onTimeChanged(timePicker: TimePicker, hourOfDay: Int, minute: Int) {
calendar.set(HOUR_OF_DAY, hourOfDay)
calendar.set(MINUTE, minute)
}
override fun onDateSet(datePicker: DatePicker, year: Int, month: Int, day: Int) {
calendar.set(YEAR, year)
calendar.set(MONTH, month)
calendar.set(DAY_OF_MONTH, day)
showDate(calendar)
}
fun setTimeDateListener(listener: TimeDateListener) {
this.listener = listener
}
@Suppress("DEPRECATION")
private fun showTime(c: Calendar) {
timePicker.currentHour = c.get(HOUR_OF_DAY)
timePicker.currentMinute = c.get(MINUTE)
}
private fun showDate(c: Calendar) {
val now = Calendar.getInstance()
dateView.text = when {
c.isYesterday(now) -> getString(R.string.yesterday)
c.isToday(now) -> getString(R.string.today)
c.isTomorrow(now) -> getString(R.string.tomorrow)
else -> getDateFormat(context?.applicationContext).format(calendar.time)
}
}
private fun Calendar.isSameMonth(c: Calendar) = c.get(YEAR) == get(YEAR) && c.get(MONTH) == get(MONTH)
private fun Calendar.isYesterday(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH) - 1
private fun Calendar.isToday(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH)
private fun Calendar.isTomorrow(now: Calendar) = isSameMonth(now) && get(DAY_OF_MONTH) == now.get(DAY_OF_MONTH) + 1
interface TimeDateListener {
fun onTimeAndDateSet(calendar: Calendar)
}
}
| gpl-3.0 | 5fb196330b037ee94fc05762fd113933 | 33.7 | 131 | 0.665526 | 4.517494 | false | false | false | false |
UweTrottmann/SeriesGuide | app/src/main/java/com/battlelancer/seriesguide/dataliberation/JsonImportTask.kt | 1 | 19255 | package com.battlelancer.seriesguide.dataliberation
import android.content.ContentProviderOperation
import android.content.ContentValues
import android.content.Context
import android.content.OperationApplicationException
import android.net.Uri
import android.os.ParcelFileDescriptor
import androidx.annotation.VisibleForTesting
import com.battlelancer.seriesguide.R
import com.battlelancer.seriesguide.dataliberation.DataLiberationFragment.LiberationResultEvent
import com.battlelancer.seriesguide.dataliberation.ImportTools.toSgEpisodeForImport
import com.battlelancer.seriesguide.dataliberation.ImportTools.toSgSeasonForImport
import com.battlelancer.seriesguide.dataliberation.ImportTools.toSgShowForImport
import com.battlelancer.seriesguide.dataliberation.JsonExportTask.BackupType
import com.battlelancer.seriesguide.dataliberation.JsonExportTask.ListItemTypesExport
import com.battlelancer.seriesguide.dataliberation.model.List
import com.battlelancer.seriesguide.dataliberation.model.Movie
import com.battlelancer.seriesguide.dataliberation.model.Season
import com.battlelancer.seriesguide.dataliberation.model.Show
import com.battlelancer.seriesguide.provider.SeriesGuideContract
import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItemTypes
import com.battlelancer.seriesguide.provider.SeriesGuideContract.ListItems
import com.battlelancer.seriesguide.provider.SeriesGuideDatabase
import com.battlelancer.seriesguide.provider.SgRoomDatabase
import com.battlelancer.seriesguide.shows.database.SgEpisode2
import com.battlelancer.seriesguide.shows.database.SgEpisode2Helper
import com.battlelancer.seriesguide.shows.database.SgSeason2Helper
import com.battlelancer.seriesguide.shows.database.SgShow2Helper
import com.battlelancer.seriesguide.sync.SgSyncAdapter
import com.battlelancer.seriesguide.util.DBUtils
import com.battlelancer.seriesguide.util.Errors.Companion.logAndReport
import com.battlelancer.seriesguide.util.LanguageTools
import com.battlelancer.seriesguide.util.TaskManager
import com.google.gson.Gson
import com.google.gson.JsonParseException
import com.google.gson.stream.JsonReader
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.isActive
import kotlinx.coroutines.withContext
import org.greenrobot.eventbus.EventBus
import timber.log.Timber
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.IOException
import java.io.InputStreamReader
/**
* Imports shows, lists or movies from a human-readable JSON file replacing existing data.
*/
class JsonImportTask(
context: Context,
importShows: Boolean,
importLists: Boolean,
importMovies: Boolean,
private val database: SgRoomDatabase,
private val sgShow2Helper: SgShow2Helper,
private val sgSeason2Helper: SgSeason2Helper,
private val sgEpisode2Helper: SgEpisode2Helper
) {
private val context: Context = context.applicationContext
private val languageCodes: Array<String> =
this.context.resources.getStringArray(R.array.content_languages)
private var isImportingAutoBackup: Boolean
private val isImportShows: Boolean
private val isImportLists: Boolean
private val isImportMovies: Boolean
@VisibleForTesting
var errorCause: String? = null
private set
/**
* If set will use this file instead of opening via URI, which seems broken with Robolectric
* (openFileDescriptor throws FileNotFoundException).
*/
@VisibleForTesting
var testBackupFile: File? = null
init {
isImportingAutoBackup = false
isImportShows = importShows
isImportLists = importLists
isImportMovies = importMovies
}
constructor(
context: Context,
importShows: Boolean,
importLists: Boolean,
importMovies: Boolean
) : this(
context,
importShows,
importLists,
importMovies,
SgRoomDatabase.getInstance(context),
SgRoomDatabase.getInstance(context).sgShow2Helper(),
SgRoomDatabase.getInstance(context).sgSeason2Helper(),
SgRoomDatabase.getInstance(context).sgEpisode2Helper()
)
constructor(context: Context) : this(context, true, true, true) {
isImportingAutoBackup = true
}
suspend fun run(): Int {
return withContext(Dispatchers.IO) {
val result = doInBackground(this)
onPostExecute(result)
return@withContext result
}
}
private fun doInBackground(coroutineScope: CoroutineScope): Int {
// Ensure no large database ops are running
val tm = TaskManager.getInstance()
if (SgSyncAdapter.isSyncActive(context, false) || tm.isAddTaskRunning) {
return ERROR_LARGE_DB_OP
}
// last chance to abort
if (!coroutineScope.isActive) {
return ERROR
}
var result: Int
if (isImportShows) {
result = importData(JsonExportTask.BACKUP_SHOWS)
if (result != SUCCESS) {
return result
}
if (!coroutineScope.isActive) {
return ERROR
}
}
if (isImportLists) {
result = importData(JsonExportTask.BACKUP_LISTS)
if (result != SUCCESS) {
return result
}
if (!coroutineScope.isActive) {
return ERROR
}
}
if (isImportMovies) {
result = importData(JsonExportTask.BACKUP_MOVIES)
if (result != SUCCESS) {
return result
}
if (!coroutineScope.isActive) {
return ERROR
}
}
// Renew search table
SeriesGuideDatabase.rebuildFtsTable(context)
return SUCCESS
}
private fun onPostExecute(result: Int) {
val messageId: Int
val showIndefinite: Boolean
when (result) {
SUCCESS -> {
messageId = R.string.import_success
showIndefinite = false
}
ERROR_STORAGE_ACCESS -> {
messageId = R.string.import_failed_nosd
showIndefinite = true
}
ERROR_FILE_ACCESS -> {
messageId = R.string.import_failed_nofile
showIndefinite = true
}
ERROR_LARGE_DB_OP -> {
messageId = R.string.update_inprogress
showIndefinite = false
}
else -> {
messageId = R.string.import_failed
showIndefinite = true
}
}
EventBus.getDefault().post(
LiberationResultEvent(
context.getString(messageId), errorCause, showIndefinite
)
)
}
private fun importData(@BackupType type: Int): Int {
if (!isImportingAutoBackup) {
val testBackupFile = testBackupFile
var pfd: ParcelFileDescriptor? = null
if (testBackupFile == null) {
// make sure we have a file uri...
val backupFileUri = getDataBackupFile(type) ?: return ERROR_FILE_ACCESS
// ...and the file actually exists
try {
pfd = context.contentResolver.openFileDescriptor(backupFileUri, "r")
} catch (e: FileNotFoundException) {
Timber.e(e, "Backup file not found.")
errorCause = e.message
return ERROR_FILE_ACCESS
} catch (e: SecurityException) {
Timber.e(e, "Backup file not found.")
errorCause = e.message
return ERROR_FILE_ACCESS
}
if (pfd == null) {
Timber.e("File descriptor is null.")
return ERROR_FILE_ACCESS
}
}
if (!clearExistingData(type)) {
return ERROR
}
// Access JSON from backup file and try to import data
val inputStream = if (testBackupFile == null) {
FileInputStream(pfd!!.fileDescriptor)
} else FileInputStream(testBackupFile)
try {
importFromJson(type, inputStream)
// let the document provider know we're done.
pfd?.close()
} catch (e: JsonParseException) {
// the given Json might not be valid or unreadable
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: IOException) {
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: IllegalStateException) {
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: Exception) {
// Only report unexpected errors.
logAndReport("Import failed", e)
errorCause = e.message
return ERROR
}
} else {
// Restoring latest auto backup.
val (backupFile) = AutoBackupTools.getLatestBackupOrNull(type, context)
?: // There is no backup file to restore from.
return ERROR_FILE_ACCESS
val inputStream: FileInputStream // Closed by reader after importing.
try {
if (!backupFile.canRead()) {
return ERROR_FILE_ACCESS
}
inputStream = FileInputStream(backupFile)
} catch (e: Exception) {
Timber.e(e, "Unable to open backup file.")
errorCause = e.message
return ERROR_FILE_ACCESS
}
// Only clear data after backup file could be opened.
if (!clearExistingData(type)) {
return ERROR
}
// Access JSON from backup file and try to import data
try {
importFromJson(type, inputStream)
} catch (e: JsonParseException) {
// the given Json might not be valid or unreadable
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: IOException) {
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: IllegalStateException) {
Timber.e(e, "Import failed")
errorCause = e.message
return ERROR
} catch (e: Exception) {
// Only report unexpected errors.
logAndReport("Import failed", e)
errorCause = e.message
return ERROR
}
}
return SUCCESS
}
private fun getDataBackupFile(@BackupType type: Int): Uri? {
return BackupSettings.getImportFileUriOrExportFileUri(context, type)
}
private fun clearExistingData(@BackupType type: Int): Boolean {
val batch = ArrayList<ContentProviderOperation>()
when (type) {
JsonExportTask.BACKUP_SHOWS -> {
database.runInTransaction {
// delete episodes and seasons first to prevent violating foreign key constraints
sgEpisode2Helper.deleteAllEpisodes()
sgSeason2Helper.deleteAllSeasons()
sgShow2Helper.deleteAllShows()
}
}
JsonExportTask.BACKUP_LISTS -> {
// delete list items before lists to prevent violating foreign key constraints
batch.add(
ContentProviderOperation.newDelete(ListItems.CONTENT_URI).build()
)
batch.add(
ContentProviderOperation.newDelete(SeriesGuideContract.Lists.CONTENT_URI)
.build()
)
}
JsonExportTask.BACKUP_MOVIES -> {
batch.add(
ContentProviderOperation.newDelete(SeriesGuideContract.Movies.CONTENT_URI)
.build()
)
}
}
try {
DBUtils.applyInSmallBatches(context, batch)
} catch (e: OperationApplicationException) {
errorCause = e.message
Timber.e(e, "clearExistingData")
return false
}
return true
}
@Throws(JsonParseException::class, IOException::class, IllegalArgumentException::class)
private fun importFromJson(@BackupType type: Int, inputStream: FileInputStream) {
if (inputStream.channel.size() == 0L) {
Timber.i("Backup file is empty, nothing to import.")
inputStream.close()
return // File is empty, nothing to import.
}
val gson = Gson()
val reader = JsonReader(InputStreamReader(inputStream, "UTF-8"))
reader.beginArray()
when (type) {
JsonExportTask.BACKUP_SHOWS -> {
while (reader.hasNext()) {
val show = gson.fromJson<Show>(reader, Show::class.java)
addShowToDatabase(show)
}
}
JsonExportTask.BACKUP_LISTS -> {
while (reader.hasNext()) {
val list = gson.fromJson<List>(reader, List::class.java)
addListToDatabase(list)
}
}
JsonExportTask.BACKUP_MOVIES -> {
while (reader.hasNext()) {
val movie = gson.fromJson<Movie>(reader, Movie::class.java)
context.contentResolver.insert(
SeriesGuideContract.Movies.CONTENT_URI,
movie.toContentValues()
)
}
}
}
reader.endArray()
reader.close()
}
private fun addShowToDatabase(show: Show) {
if ((show.tmdb_id == null || show.tmdb_id!! <= 0)
&& (show.tvdb_id == null || show.tvdb_id!! <= 0)) {
// valid id required
return
}
// Map legacy language codes.
if (!show.language.isNullOrEmpty()) {
show.language = LanguageTools.mapLegacyShowCode(show.language)
}
// Reset language if it is not supported.
val languageSupported = languageCodes.find { it == show.language } != null
if (!languageSupported) {
show.language = null
}
val sgShow = show.toSgShowForImport()
val showId = sgShow2Helper.insertShow(sgShow)
if (showId == -1L) {
return // Insert failed.
}
if (show.seasons == null || show.seasons.isEmpty()) {
// no seasons (or episodes)
return
}
// Parse and insert seasons and episodes.
insertSeasonsAndEpisodes(show, showId)
}
private fun insertSeasonsAndEpisodes(show: Show, showId: Long) {
for (season in show.seasons) {
if ((season.tmdb_id == null || season.tmdb_id!!.isEmpty())
&& (season.tvdbId == null || season.tvdbId!! <= 0)) {
// valid id is required
continue
}
if (season.episodes == null || season.episodes.isEmpty()) {
// episodes required
continue
}
// Insert season.
val sgSeason = season.toSgSeasonForImport(showId)
val seasonId = sgSeason2Helper.insertSeason(sgSeason)
// If inserted, insert episodes.
if (seasonId != -1L) {
val episodes = buildEpisodeBatch(season, showId, seasonId)
sgEpisode2Helper.insertEpisodes(episodes)
}
}
}
private fun buildEpisodeBatch(
season: Season,
showId: Long,
seasonId: Long
): ArrayList<SgEpisode2> {
val episodeBatch = ArrayList<SgEpisode2>()
for (episode in season.episodes) {
if ((episode.tmdb_id == null || episode.tmdb_id!! <= 0)
&& (episode.tvdbId == null || episode.tvdbId!! <= 0)) {
// valid id is required
continue
}
episodeBatch.add(episode.toSgEpisodeForImport(showId, seasonId, season.season))
}
return episodeBatch
}
private fun addListToDatabase(list: List) {
if (list.name.isNullOrEmpty()) {
return // required
}
if (list.listId.isNullOrEmpty()) {
// rebuild from name
list.listId = SeriesGuideContract.Lists.generateListId(list.name)
}
// Insert the list
context.contentResolver.insert(
SeriesGuideContract.Lists.CONTENT_URI,
list.toContentValues()
)
if (list.items == null || list.items.isEmpty()) {
return
}
// Insert the lists items
val items = ArrayList<ContentValues>()
for (item in list.items) {
// Note: DO import legacy types (seasons and episodes),
// as e.g. older backups can still contain legacy show data to allow displaying them.
val type: Int = if (ListItemTypesExport.SHOW == item.type) {
ListItemTypes.TVDB_SHOW
} else if (ListItemTypesExport.TMDB_SHOW == item.type) {
ListItemTypes.TMDB_SHOW
} else if (ListItemTypesExport.SEASON == item.type) {
ListItemTypes.SEASON
} else if (ListItemTypesExport.EPISODE == item.type) {
ListItemTypes.EPISODE
} else {
// Unknown item type, skip
continue
}
var externalId: String? = null
if (item.externalId != null && item.externalId.isNotEmpty()) {
externalId = item.externalId
} else if (item.tvdbId > 0) {
externalId = item.tvdbId.toString()
}
if (externalId == null) continue // No external ID, skip
// Generate list item ID from values, do not trust given item ID
// (e.g. encoded list ID might not match)
item.listItemId = ListItems.generateListItemId(externalId, type, list.listId)
val itemValues = ContentValues()
itemValues.put(ListItems.LIST_ITEM_ID, item.listItemId)
itemValues.put(SeriesGuideContract.Lists.LIST_ID, list.listId)
itemValues.put(ListItems.ITEM_REF_ID, externalId)
itemValues.put(ListItems.TYPE, type)
items.add(itemValues)
}
context.contentResolver.bulkInsert(ListItems.CONTENT_URI, items.toTypedArray())
}
companion object {
const val SUCCESS = 1
private const val ERROR_STORAGE_ACCESS = 0
private const val ERROR = -1
private const val ERROR_LARGE_DB_OP = -2
private const val ERROR_FILE_ACCESS = -3
}
} | apache-2.0 | a8be4c8b5b2103a5c9f3bc2d6e5a6d58 | 35.678095 | 101 | 0.584056 | 5.21533 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/firstball/FirstBallStatistic.kt | 1 | 1991 | package ca.josephroque.bowlingcompanion.statistics.impl.firstball
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.games.Game
import ca.josephroque.bowlingcompanion.games.lane.Deck
import ca.josephroque.bowlingcompanion.games.lane.arePinsCleared
import ca.josephroque.bowlingcompanion.statistics.PercentageStatistic
import ca.josephroque.bowlingcompanion.statistics.StatisticsCategory
import ca.josephroque.bowlingcompanion.statistics.immutable.StatFrame
/**
* Copyright (C) 2018 Joseph Roque
*
* Parent class for statistics which are calculated based on the user throwing at a
* full deck of pins.
*/
abstract class FirstBallStatistic(override var numerator: Int = 0, override var denominator: Int = 0) : PercentageStatistic {
override fun isModifiedBy(frame: StatFrame) = true
override val category = StatisticsCategory.FirstBall
override val secondaryGraphDataLabelId = R.string.statistic_total_shots_at_middle
// MARK: Statistic
override fun modify(frame: StatFrame) {
// This function has a similar construction to `StrikeMiddleHitsStatistic.modify(StatFrame)
// and the two should remain aligned
// Every frame adds 1 possible hit
denominator++
numerator += if (isModifiedBy(frame.pinState[0])) 1 else 0
if (frame.zeroBasedOrdinal == Game.LAST_FRAME) {
// In the 10th frame, for each time the first or second ball cleared the lane, add
// another middle hit chance, and check if the statistic is modified
if (frame.pinState[0].arePinsCleared) {
denominator++
numerator += if (isModifiedBy(frame.pinState[1])) 1 else 0
}
if (frame.pinState[1].arePinsCleared) {
denominator++
numerator += if (isModifiedBy(frame.pinState[2])) 1 else 0
}
}
}
// MARK: FirstBallStatistic
abstract fun isModifiedBy(deck: Deck): Boolean
}
| mit | a992e9260ab7e7142df8b762f0a7416d | 38.82 | 125 | 0.70668 | 4.729216 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-chat-bukkit/src/main/kotlin/com/rpkit/chat/bukkit/irc/IRCWhitelistValidator.kt | 1 | 5334 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.chat.bukkit.irc
import com.rpkit.chat.bukkit.RPKChatBukkit
import com.rpkit.chat.bukkit.chatchannel.RPKChatChannelService
import com.rpkit.chat.bukkit.chatchannel.undirected.IRCComponent
import com.rpkit.core.service.Services
import com.rpkit.permissions.bukkit.group.hasPermission
import com.rpkit.permissions.bukkit.permissions.RPKPermissionsService
import com.rpkit.players.bukkit.profile.RPKProfile
import com.rpkit.players.bukkit.profile.RPKProfileName
import com.rpkit.players.bukkit.profile.RPKProfileService
import com.rpkit.players.bukkit.profile.irc.RPKIRCNick
import com.rpkit.players.bukkit.profile.irc.RPKIRCProfileService
import org.pircbotx.Channel
import org.pircbotx.PircBotX
import org.pircbotx.User
import java.util.concurrent.CompletableFuture
import java.util.logging.Level
class IRCWhitelistValidator(private val plugin: RPKChatBukkit) {
fun enforceWhitelist(user: User, nick: RPKIRCNick, bot: PircBotX, channel: Channel) {
val verified = user.isVerified
val chatChannelService = Services[RPKChatChannelService::class.java] ?: return
val chatChannel = chatChannelService.getChatChannelFromIRCChannel(IRCChannel(channel.name)) ?: return
if (chatChannel.undirectedPipeline
.firstNotNullOfOrNull { component -> component as? IRCComponent }
?.isIRCWhitelisted != true) return
if (!verified) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but you are not verified.",
"${nick.value} attempted to join, but was not verified."
)
}
val permissionsService = Services[RPKPermissionsService::class.java]
if (permissionsService == null) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but the permissions service could not be found.",
"${nick.value} attempted to join, but no permissions service could be found and the channel is whitelisted."
)
return
}
val profileService = Services[RPKProfileService::class.java]
if (profileService == null) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but the profile service could not be found.",
"${nick.value} attempted to join, but no profile service could be found and the channel is whitelisted."
)
return
}
val ircProfileService = Services[RPKIRCProfileService::class.java]
if (ircProfileService == null) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but the IRC profile service could not be found.",
"${nick.value} attempted to join, but no IRC profile service could be found and the channel is whitelisted."
)
return
}
CompletableFuture.runAsync {
val ircProfile = ircProfileService.getIRCProfile(nick).join() ?: ircProfileService.createIRCProfile(
profileService.createThinProfile(RPKProfileName(nick.value)),
nick
).join()
val profile = ircProfile.profile
if (profile !is RPKProfile) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, but this IRC account has not been linked to a profile.",
"${nick.value} attempted to join, but their IRC account was not linked to a profile."
)
return@runAsync
}
if (!profile.hasPermission("rpkit.chat.listen.${chatChannel.name.value}").join()) {
kick(
bot,
channel,
nick.value,
"${channel.name} is whitelisted, you do not have permission to view it.",
"${nick.value} attempted to join, but does not have permission to view the channel."
)
}
}.exceptionally { exception ->
plugin.logger.log(Level.SEVERE, "Failed to check IRC profile", exception)
throw exception
}
}
private fun kick(
bot: PircBotX,
channel: Channel,
nick: String,
kickMessage: String,
channelMessage: String
) {
bot.sendIRC().message(channel.name, "/kick ${channel.name} $nick $kickMessage")
channel.send().message(channelMessage)
}
} | apache-2.0 | 4611537a7662d96ce7b3fa613c7988ce | 40.356589 | 124 | 0.615673 | 5.022599 | false | false | false | false |
googlecodelabs/android-compose-codelabs | NavigationCodelab/app/src/main/java/com/example/compose/rally/ui/components/RallyAnimatedCircle.kt | 1 | 3641 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.compose.rally.ui.components
import androidx.compose.animation.core.CubicBezierEasing
import androidx.compose.animation.core.LinearOutSlowInEasing
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.Canvas
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
private const val DividerLengthInDegrees = 1.8f
/**
* A donut chart that animates when loaded.
*/
@Composable
fun AnimatedCircle(
proportions: List<Float>,
colors: List<Color>,
modifier: Modifier = Modifier
) {
val currentState = remember {
MutableTransitionState(AnimatedCircleProgress.START)
.apply { targetState = AnimatedCircleProgress.END }
}
val stroke = with(LocalDensity.current) { Stroke(5.dp.toPx()) }
val transition = updateTransition(currentState)
val angleOffset by transition.animateFloat(
transitionSpec = {
tween(
delayMillis = 500,
durationMillis = 900,
easing = LinearOutSlowInEasing
)
}
) { progress ->
if (progress == AnimatedCircleProgress.START) {
0f
} else {
360f
}
}
val shift by transition.animateFloat(
transitionSpec = {
tween(
delayMillis = 500,
durationMillis = 900,
easing = CubicBezierEasing(0f, 0.75f, 0.35f, 0.85f)
)
}
) { progress ->
if (progress == AnimatedCircleProgress.START) {
0f
} else {
30f
}
}
Canvas(modifier) {
val innerRadius = (size.minDimension - stroke.width) / 2
val halfSize = size / 2.0f
val topLeft = Offset(
halfSize.width - innerRadius,
halfSize.height - innerRadius
)
val size = Size(innerRadius * 2, innerRadius * 2)
var startAngle = shift - 90f
proportions.forEachIndexed { index, proportion ->
val sweep = proportion * angleOffset
drawArc(
color = colors[index],
startAngle = startAngle + DividerLengthInDegrees / 2,
sweepAngle = sweep - DividerLengthInDegrees,
topLeft = topLeft,
size = size,
useCenter = false,
style = stroke
)
startAngle += sweep
}
}
}
private enum class AnimatedCircleProgress { START, END }
| apache-2.0 | 343fa2dcea2dedd8fe1673c5c1b0df33 | 32.40367 | 75 | 0.652293 | 4.71022 | false | false | false | false |
industrial-data-space/trusted-connector | ids-webconsole/src/main/kotlin/de/fhg/aisec/ids/webconsole/api/helper/ProcessExecutor.kt | 1 | 1504 | /*-
* ========================LICENSE_START=================================
* ids-webconsole
* %%
* Copyright (C) 2019 Fraunhofer AISEC
* %%
* 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.
* =========================LICENSE_END==================================
*/
package de.fhg.aisec.ids.webconsole.api.helper
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.OutputStream
class ProcessExecutor {
@Throws(InterruptedException::class, IOException::class)
fun execute(cmd: Array<String>?, stdout: OutputStream?, stderr: OutputStream?): Int {
val rt = Runtime.getRuntime()
val proc = rt.exec(cmd)
val errorGobbler = StreamGobbler(proc.errorStream, stderr)
val outputGobbler = StreamGobbler(proc.inputStream, stdout)
errorGobbler.start()
outputGobbler.start()
return proc.waitFor()
}
companion object {
private val LOG = LoggerFactory.getLogger(ProcessExecutor::class.java)
}
}
| apache-2.0 | b4c8387c904dcf3f069119c1d80553a0 | 35.682927 | 89 | 0.655585 | 4.502994 | false | false | false | false |
carmenlau/chat-SDK-Android | chat/src/main/java/io/skygear/plugins/chat/ui/utils/ImageUtils.kt | 1 | 4840 | package io.skygear.plugins.chat.ui.utils
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.net.Uri
import android.os.Environment
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.*
import android.media.ExifInterface
import android.R.attr.path
import java.io.FileOutputStream
/**
* Created by carmenlau on 10/2/17.
*/
private val THUMBNAIL_SIZE = 80.0
private val IMAGE_SIZE = 1600.0
var mCurrentPhotoPath: String = ""
data class ImageData(val thumbnail: Bitmap,
val image: Bitmap)
fun getResizedBitmap(context: Context, uri: Uri): ImageData? {
var input = context.getContentResolver().openInputStream(uri)
val onlyBoundsOptions = BitmapFactory.Options()
onlyBoundsOptions.inJustDecodeBounds = true
onlyBoundsOptions.inPreferredConfig = Bitmap.Config.ARGB_8888//optional
BitmapFactory.decodeStream(input, null, onlyBoundsOptions)
input.close()
if (onlyBoundsOptions.outWidth == -1 || onlyBoundsOptions.outHeight == -1) {
return null
}
// get orientation exif
input = context.getContentResolver().openInputStream(uri)
val file = File.createTempFile("image_tmp", ".jpg", context.getCacheDir())
val fos = FileOutputStream(file)
var len: Int
val buffer = ByteArray(1024)
do {
len = input.read(buffer, 0, 1024)
if (len == -1)
break
fos.write(buffer, 0, len)
} while (true)
input.close()
fos.close()
val ef = ExifInterface(file.toString())
val orientation = ef.getAttributeInt(ExifInterface.TAG_ORIENTATION, 99)
val originalSize = if (onlyBoundsOptions.outHeight > onlyBoundsOptions.outWidth)
onlyBoundsOptions.outHeight else onlyBoundsOptions.outWidth
val imgRatio = if (originalSize > IMAGE_SIZE) originalSize / IMAGE_SIZE else 1.0
val bitmap = getBitmap(context, uri, imgRatio, orientation)
val thumbRatio = if (originalSize > THUMBNAIL_SIZE) originalSize / THUMBNAIL_SIZE else 1.0
val thumbBitmap = getBitmap(context, uri, thumbRatio, orientation)
return ImageData(thumbBitmap, bitmap)
}
fun getBitmap(context: Context, uri: Uri, ratio: Double, orientation: Int) : Bitmap {
val bitmapOptions = BitmapFactory.Options()
bitmapOptions.inSampleSize = getPowerOfTwoForSampleRatio(ratio)
bitmapOptions.inPreferredConfig = Bitmap.Config.ARGB_8888
val input = context.getContentResolver().openInputStream(uri)
var bitmap = BitmapFactory.decodeStream(input, null, bitmapOptions)
bitmap = rotateBitmap(bitmap, orientation)
input.close()
return bitmap
}
fun bitmapToByteArray(bmp: Bitmap): ByteArray? {
val stream = ByteArrayOutputStream()
bmp.compress(Bitmap.CompressFormat.JPEG, 70, stream)
return stream.toByteArray()
}
fun rotateBitmap(bitmap: Bitmap, orientation: Int): Bitmap? {
val matrix = Matrix()
when (orientation) {
ExifInterface.ORIENTATION_NORMAL -> return bitmap
ExifInterface.ORIENTATION_FLIP_HORIZONTAL -> matrix.setScale(-1f, 1f)
ExifInterface.ORIENTATION_ROTATE_180 -> matrix.setRotate(180f)
ExifInterface.ORIENTATION_FLIP_VERTICAL -> {
matrix.setRotate(180f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_TRANSPOSE -> {
matrix.setRotate(90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_90 -> matrix.setRotate(90f)
ExifInterface.ORIENTATION_TRANSVERSE -> {
matrix.setRotate(-90f)
matrix.postScale(-1f, 1f)
}
ExifInterface.ORIENTATION_ROTATE_270 -> matrix.setRotate(-90f)
else -> return bitmap
}
try {
val bmRotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
bitmap.recycle()
return bmRotated
} catch (e: OutOfMemoryError) {
e.printStackTrace()
return null
}
}
@Throws(IOException::class)
fun createImageFile(context: Context): File {
// Create an image file name
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
val imageFileName = "JPEG_" + timeStamp + "_"
val storageDir = context.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
val image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
)
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = image.getAbsolutePath()
return image
}
private fun getPowerOfTwoForSampleRatio(ratio: Double): Int {
val k = Integer.highestOneBit(Math.floor(ratio).toInt())
return if (k == 0) 1 else k
}
| apache-2.0 | 9fbcdc75777df027db2b6c861a8e485f | 31.483221 | 100 | 0.693182 | 4.408015 | false | false | false | false |
mabels/ipaddress | kotlin/lib/src/main/kotlin/com/adviser/ipaddress/Prefix.kt | 1 | 3753 | package com.adviser.ipaddress.kotlin
import java.math.BigInteger
/*
interface VtFrom {
fun <Prefix> run(p: Prefix, n: Byte): Result<Prefix>
}
*/
public class Prefix(val num: Int,
val ip_bits: IpBits,
val net_mask: BigInteger,
val vt_from: (p: Prefix, n: Int) -> Result<Prefix>) {
companion object {
fun new_netmask(prefix: Int, bits: Int): BigInteger {
var mask = BigInteger.ZERO
val host_prefix = bits - prefix
for (i in 0 until prefix) {
mask = mask.add((BigInteger.ONE.shiftLeft(host_prefix + i)))
}
return mask
}
}
fun clone(): Prefix {
return Prefix(this.num, this.ip_bits, this.net_mask, this.vt_from)
}
fun equal(other: Prefix): Boolean {
return this.ip_bits.version == other.ip_bits.version &&
this.num == other.num
}
fun inspect(): String {
return "Prefix: ${num}"
}
fun compare(oth: Prefix): Int {
if (this.ip_bits.version < oth.ip_bits.version) {
return -1
} else if (this.ip_bits.version > oth.ip_bits.version) {
return 1
} else {
if (this.num < oth.num) {
return -1
} else if (this.num > oth.num) {
return 1
} else {
return 0
}
}
}
fun from(num: Int): Result<Prefix> {
return this.vt_from(this, num)
}
fun to_ip_str(): String {
return this.ip_bits.vt_as_compressed_string(this.ip_bits, this.netmask())
}
fun size(): BigInteger {
return BigInteger.ONE.shiftLeft(this.ip_bits.bits - this.num)
}
fun netmask(): BigInteger {
return BigInteger.ZERO.add(this.net_mask)
}
fun get_prefix(): Int {
return this.num
}
/// The hostmask is the contrary of the subnet mask,
/// as it shows the bits that can change within the
/// hosts
///
/// prefix = IPAddress::Prefix32.new 24
///
/// prefix.hostmask
/// /// "0.0.0.255"
///
fun host_mask(): BigInteger {
var ret = BigInteger.ZERO
for (i in 0 until this.ip_bits.bits - this.num) {
ret = ret.shiftLeft(1).add(BigInteger.ONE)
}
return ret
}
///
/// Returns the length of the host portion
/// of a netmask.
///
/// prefix = Prefix128.new 96
///
/// prefix.host_prefix
/// /// 128
///
fun host_prefix(): Int {
return this.ip_bits.bits - this.num
}
///
/// Transforms the prefix into a string of bits
/// representing the netmask
///
/// prefix = IPAddress::Prefix128.new 64
///
/// prefix.bits
/// /// "1111111111111111111111111111111111111111111111111111111111111111"
/// "0000000000000000000000000000000000000000000000000000000000000000"
///
fun bits(): String {
return this.netmask().toString(2)
}
fun to_s(): String {
return "${this.get_prefix()}"
}
fun to_i(): Int {
return this.get_prefix()
}
fun add_prefix(other: Prefix): Result<Prefix> {
return this.from(this.get_prefix() + other.get_prefix())
}
fun add(other: Int): Result<Prefix> {
return this.from(this.get_prefix() + other)
}
fun sub_prefix(other: Prefix): Result<Prefix> {
return this.sub(other.get_prefix())
}
fun sub(other: Int): Result<Prefix> {
if (other > this.get_prefix()) {
return this.from(other - this.get_prefix())
}
return this.from(this.get_prefix() - other)
}
}
| mit | 8e08bd22013c50231d971b53dca045c6 | 24.358108 | 84 | 0.529443 | 3.817904 | false | false | false | false |
luxons/seven-wonders | sw-ui/src/main/kotlin/org/luxons/sevenwonders/ui/components/lobby/Lobby.kt | 1 | 7986 | package org.luxons.sevenwonders.ui.components.lobby
import com.palantir.blueprintjs.*
import kotlinx.css.*
import kotlinx.css.properties.transform
import kotlinx.css.properties.translate
import org.luxons.sevenwonders.model.api.LobbyDTO
import org.luxons.sevenwonders.model.api.PlayerDTO
import org.luxons.sevenwonders.model.wonders.*
import org.luxons.sevenwonders.ui.components.GlobalStyles
import org.luxons.sevenwonders.ui.redux.*
import react.RBuilder
import react.RComponent
import react.RProps
import react.RState
import react.dom.h2
import react.dom.h3
import react.dom.h4
import styled.css
import styled.styledDiv
import styled.styledH2
private val BOT_NAMES = listOf("Wall-E", "B-Max", "Sonny", "T-800", "HAL", "GLaDOS")
interface LobbyStateProps : RProps {
var currentGame: LobbyDTO?
var currentPlayer: PlayerDTO?
}
interface LobbyDispatchProps : RProps {
var startGame: () -> Unit
var addBot: (displayName: String) -> Unit
var leaveLobby: () -> Unit
var disbandLobby: () -> Unit
var reorderPlayers: (orderedPlayers: List<String>) -> Unit
var reassignWonders: (wonders: List<AssignedWonder>) -> Unit
}
interface LobbyProps : LobbyDispatchProps, LobbyStateProps
class LobbyPresenter(props: LobbyProps) : RComponent<LobbyProps, RState>(props) {
override fun RBuilder.render() {
val currentGame = props.currentGame
val currentPlayer = props.currentPlayer
if (currentGame == null || currentPlayer == null) {
bpNonIdealState(icon = "error", title = "Error: no current game")
return
}
styledDiv {
css {
padding(1.rem)
+GlobalStyles.fullscreen
}
h2 { +"${currentGame.name} — Lobby" }
radialPlayerList(currentGame.players, currentPlayer)
actionButtons(currentPlayer, currentGame)
if (currentPlayer.isGameOwner) {
setupPanel(currentGame)
}
}
}
private fun RBuilder.actionButtons(currentPlayer: PlayerDTO, currentGame: LobbyDTO) {
styledDiv {
css {
position = Position.fixed
bottom = 2.rem
left = 50.pct
transform { translate((-50).pct) }
}
if (currentPlayer.isGameOwner) {
bpButtonGroup {
startButton(currentGame, currentPlayer)
addBotButton(currentGame)
leaveButton()
disbandButton()
}
} else {
leaveButton()
}
}
}
private fun RBuilder.startButton(currentGame: LobbyDTO, currentPlayer: PlayerDTO) {
val startability = currentGame.startability(currentPlayer.username)
bpButton(
large = true,
intent = Intent.PRIMARY,
icon = "play",
title = startability.tooltip,
disabled = !startability.canDo,
onClick = { props.startGame() },
) {
+"START"
}
}
private fun RBuilder.setupPanel(currentGame: LobbyDTO) {
styledDiv {
css {
position = Position.fixed
top = 2.rem
right = 1.rem
width = 15.rem
}
bpCard(Elevation.TWO) {
styledH2 {
css {
margin(top = 0.px)
}
+"Game setup"
}
bpDivider()
h3 {
+"Players"
}
reorderPlayersButton(currentGame)
h3 {
+"Wonders"
}
randomizeWondersButton(currentGame)
wonderSideSelectionGroup(currentGame)
}
}
}
private fun RBuilder.addBotButton(currentGame: LobbyDTO) {
bpButton(
large = true,
icon = "plus",
rightIcon = "desktop",
title = if (currentGame.maxPlayersReached) "Max players reached" else "Add a bot to this game",
disabled = currentGame.maxPlayersReached,
onClick = { addBot(currentGame) },
)
}
private fun addBot(currentGame: LobbyDTO) {
val availableBotNames = BOT_NAMES.filter { name ->
currentGame.players.all { it.displayName != name }
}
props.addBot(availableBotNames.random())
}
private fun RBuilder.reorderPlayersButton(currentGame: LobbyDTO) {
bpButton(
icon = "random",
rightIcon = "people",
title = "Re-order players randomly",
onClick = { reorderPlayers(currentGame) },
) {
+"Reorder players"
}
}
private fun reorderPlayers(currentGame: LobbyDTO) {
props.reorderPlayers(currentGame.players.map { it.username }.shuffled())
}
private fun RBuilder.randomizeWondersButton(currentGame: LobbyDTO) {
bpButton(
icon = "random",
title = "Re-assign wonders to players randomly",
onClick = { randomizeWonders(currentGame) },
) {
+"Randomize wonders"
}
}
private fun RBuilder.wonderSideSelectionGroup(currentGame: LobbyDTO) {
h4 {
+"Select wonder sides:"
}
bpButtonGroup {
bpButton(
icon = "random",
title = "Re-roll wonder sides randomly",
onClick = { randomizeWonderSides(currentGame) },
)
bpButton(
title = "Choose side A for everyone",
onClick = { setWonderSides(currentGame, WonderSide.A) },
) {
+"A"
}
bpButton(
title = "Choose side B for everyone",
onClick = { setWonderSides(currentGame, WonderSide.B) },
) {
+"B"
}
}
}
private fun randomizeWonders(currentGame: LobbyDTO) {
props.reassignWonders(currentGame.allWonders.deal(currentGame.players.size))
}
private fun randomizeWonderSides(currentGame: LobbyDTO) {
props.reassignWonders(currentGame.players.map { currentGame.findWonder(it.wonder.name).withRandomSide() })
}
private fun setWonderSides(currentGame: LobbyDTO, side: WonderSide) {
props.reassignWonders(currentGame.players.map { currentGame.findWonder(it.wonder.name).withSide(side) })
}
private fun RBuilder.leaveButton() {
bpButton(
large = true,
intent = Intent.WARNING,
icon = "arrow-left",
title = "Leave the lobby and go back to the game browser",
onClick = { props.leaveLobby() },
) {
+"LEAVE"
}
}
private fun RBuilder.disbandButton() {
bpButton(
large = true,
intent = Intent.DANGER,
icon = "delete",
title = "Disband the group and go back to the game browser",
onClick = { props.disbandLobby() },
) {
+"DISBAND"
}
}
}
fun RBuilder.lobby() = lobby {}
private val lobby = connectStateAndDispatch<LobbyStateProps, LobbyDispatchProps, LobbyProps>(
clazz = LobbyPresenter::class,
mapStateToProps = { state, _ ->
currentGame = state.currentLobby
currentPlayer = state.currentPlayer
},
mapDispatchToProps = { dispatch, _ ->
startGame = { dispatch(RequestStartGame()) }
addBot = { name -> dispatch(RequestAddBot(name)) }
leaveLobby = { dispatch(RequestLeaveLobby()) }
disbandLobby = { dispatch(RequestDisbandLobby()) }
reorderPlayers = { orderedPlayers -> dispatch(RequestReorderPlayers(orderedPlayers)) }
reassignWonders = { wonders -> dispatch(RequestReassignWonders(wonders)) }
},
)
| mit | aefdc5b92a4afded068da84e079239ac | 31.064257 | 114 | 0.565506 | 4.847602 | false | false | false | false |
android/user-interface-samples | PerAppLanguages/views_app/app/src/main/java/com/example/views_app/MainActivity.kt | 1 | 5459 | /*
* Copyright (C) 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.views_app
import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.app.AppCompatDelegate
import androidx.core.os.LocaleListCompat
import com.example.views_app.databinding.ActivityMainBinding
import java.util.*
class MainActivity : AppCompatActivity() {
companion object {
const val PREFERENCE_NAME = "shared_preference"
const val PREFERENCE_MODE = Context.MODE_PRIVATE
const val FIRST_TIME_MIGRATION = "first_time_migration"
const val SELECTED_LANGUAGE = "selected_language"
const val STATUS_DONE = "status_done"
}
/**
* This is a sample code that explains the use of getter and setter APIs for Locales introduced
* in the Per-App language preferences. Here is an example use of the AndroidX Support Library
* */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
/* NOTE: If you were handling the locale storage on you own earlier, you will need to add a
one time migration for switching this storage from a custom way to the AndroidX storage.
This can be done in the following manner. Lets say earlier the locale preference was
stored in a SharedPreference */
// Check if the migration has already been done or not
if (getString(FIRST_TIME_MIGRATION) != STATUS_DONE) {
// Fetch the selected language from wherever it was stored. In this case its SharedPref
getString(SELECTED_LANGUAGE)?.let {
// Set this locale using the AndroidX library that will handle the storage itself
val localeList = LocaleListCompat.forLanguageTags(it)
AppCompatDelegate.setApplicationLocales(localeList)
// Set the migration flag to ensure that this is executed only once
putString(FIRST_TIME_MIGRATION, STATUS_DONE)
}
}
// Fetching the current application locale using the AndroidX support Library
val currentLocaleName = if (!AppCompatDelegate.getApplicationLocales().isEmpty) {
// Fetches the current Application Locale from the list
AppCompatDelegate.getApplicationLocales()[0]?.displayName
} else {
// Fetches the default System Locale
Locale.getDefault().displayName
}
// Displaying the selected locale on screen
binding.tvSelectedLanguage.text = currentLocaleName
// Setting app language to "English" in-app using the AndroidX support library
binding.btnSelectEnglish.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("en")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to "Hindi" in-app using the AndroidX support library
binding.btnSelectHindi.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("hi")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to "Arabic" in-app using the AndroidX support Library
// NOTE: Here the screen orientation is reversed to RTL
binding.btnSelectArabic.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("ar")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to "Japanese" in-app using the AndroidX support library
binding.btnSelectJapanese.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("ja")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to "Spanish" in-app using the AndroidX support library
binding.btnSelectSpanish.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("es")
AppCompatDelegate.setApplicationLocales(localeList)
}
// Setting app language to Traditional Chinese in-app using the AndroidX support Library
binding.btnSelectXxYy.setOnClickListener {
val localeList = LocaleListCompat.forLanguageTags("zh-Hant")
AppCompatDelegate.setApplicationLocales(localeList)
}
}
private fun putString(key: String, value: String) {
val editor = getSharedPreferences(PREFERENCE_NAME, PREFERENCE_MODE).edit()
editor.putString(key, value)
editor.apply()
}
private fun getString(key: String): String? {
val preference = getSharedPreferences(PREFERENCE_NAME, PREFERENCE_MODE)
return preference.getString(key, null)
}
}
| apache-2.0 | bbdc37e523a6a0264b615a2d1dfb1283 | 41.984252 | 99 | 0.695549 | 5.357213 | false | false | false | false |
jitsi/jibri | src/main/kotlin/org/jitsi/jibri/CallUrlInfo.kt | 1 | 1855 | /*
* Copyright @ 2018 Atlassian Pty Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.jitsi.jibri
import com.fasterxml.jackson.annotation.JsonIgnore
import java.util.Objects
/**
* We assume the 'baseUrl' represents a sort of landing page (on the same
* domain) where we can set the necessary local storage values. The call
* url will be created by joining [baseUrl] and [callName] with a "/". If
* set, a list of [urlParams] will be concatenated after the call name with
* a "#" in between.
*/
data class CallUrlInfo(
val baseUrl: String = "",
val callName: String = "",
private val urlParams: List<String> = listOf()
) {
@get:JsonIgnore
val callUrl: String
get() {
return if (urlParams.isNotEmpty()) {
"$baseUrl/$callName#${urlParams.joinToString("&")}"
} else {
"$baseUrl/$callName"
}
}
override fun equals(other: Any?): Boolean {
return when {
other == null -> false
this === other -> true
javaClass != other.javaClass -> false
else -> hashCode() == other.hashCode()
}
}
override fun hashCode(): Int {
// Purposefully ignore urlParams here
return Objects.hash(baseUrl.lowercase(), callName.lowercase())
}
}
| apache-2.0 | ab1bd55029bfca70d454752e92dae1b0 | 30.982759 | 75 | 0.638814 | 4.35446 | false | false | false | false |
Blankj/AndroidUtilCode | feature/utilcode/pkg/src/main/java/com/blankj/utilcode/pkg/feature/span/SpanActivity.kt | 1 | 12635 | package com.blankj.utilcode.pkg.feature.span
import android.animation.ValueAnimator
import android.content.Context
import android.content.Intent
import android.graphics.*
import android.os.Bundle
import android.text.Layout
import android.text.SpannableStringBuilder
import android.text.TextPaint
import android.text.style.CharacterStyle
import android.text.style.ClickableSpan
import android.text.style.UpdateAppearance
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.annotation.ColorInt
import com.blankj.common.activity.CommonActivity
import com.blankj.utilcode.pkg.R
import com.blankj.utilcode.util.SpanUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.span_activity.*
/**
* ```
* author: Blankj
* blog : http://blankj.com
* time : 2016/09/27
* desc : demo about SpanUtils
* ```
*/
class SpanActivity : CommonActivity() {
companion object {
fun start(context: Context) {
val starter = Intent(context, SpanActivity::class.java)
context.startActivity(starter)
}
}
private lateinit var mSpanUtils: SpanUtils
private lateinit var animSsb: SpannableStringBuilder
private var lineHeight: Int = 0
private var textSize: Float = 0f
private lateinit var valueAnimator: ValueAnimator
private lateinit var mShader: Shader
private var mShaderWidth: Float = 0f
private lateinit var matrix: Matrix
private lateinit var mBlurMaskFilterSpan: BlurMaskFilterSpan
private lateinit var mShadowSpan: ShadowSpan
private lateinit var mForegroundAlphaColorSpan: ForegroundAlphaColorSpan
private lateinit var mForegroundAlphaColorSpanGroup: ForegroundAlphaColorSpanGroup
private lateinit var mPrinterString: String
private var density: Float = 0f
override fun bindTitleRes(): Int {
return R.string.demo_span
}
override fun bindLayout(): Int {
return R.layout.span_activity
}
override fun initView(savedInstanceState: Bundle?, contentView: View?) {
super.initView(savedInstanceState, contentView)
val clickableSpan = object : ClickableSpan() {
override fun onClick(widget: View) {
ToastUtils.showShort("事件触发了")
}
override fun updateDrawState(ds: TextPaint) {
ds.color = Color.BLUE
ds.isUnderlineText = false
}
}
lineHeight = spanAboutTv.lineHeight
textSize = spanAboutTv.textSize
density = resources.displayMetrics.density
SpanUtils.with(spanAboutTv)
.appendLine("SpanUtils").setBackgroundColor(Color.LTGRAY).setBold().setForegroundColor(Color.YELLOW).setHorizontalAlign(Layout.Alignment.ALIGN_CENTER)
.appendLine("前景色").setForegroundColor(Color.GREEN)
// .appendLine("测试哈哈").setForegroundColor(Color.RED).setBackgroundColor(Color.LTGRAY).setFontSize(10).setLineHeight(280, SpanUtils.ALIGN_BOTTOM)
.appendLine("背景色").setBackgroundColor(Color.LTGRAY)
.appendLine("行高居中对齐").setLineHeight(2 * lineHeight, SpanUtils.ALIGN_CENTER).setBackgroundColor(Color.LTGRAY)
.appendLine("行高底部对齐").setLineHeight(2 * lineHeight, SpanUtils.ALIGN_BOTTOM).setBackgroundColor(Color.GREEN)
.appendLine("测试段落缩,首行缩进两字,其他行不缩进").setLeadingMargin(textSize.toInt() * 2, 10).setBackgroundColor(Color.GREEN)
.appendLine("测试引用,后面的字是为了凑到两行的效果").setQuoteColor(Color.GREEN, 10, 10).setBackgroundColor(Color.LTGRAY)
.appendLine("测试列表项,后面的字是为了凑到两行的效果").setBullet(Color.GREEN, 20, 10).setBackgroundColor(Color.LTGRAY).setBackgroundColor(Color.GREEN)
.appendLine("32dp 字体").setFontSize(32, true)
.appendLine("2 倍字体").setFontProportion(2f)
.appendLine("横向 2 倍字体").setFontXProportion(1.5f)
.appendLine("删除线").setStrikethrough()
.appendLine("下划线").setUnderline()
.append("测试").appendLine("上标").setSuperscript()
.append("测试").appendLine("下标").setSubscript()
.appendLine("粗体").setBold()
.appendLine("斜体").setItalic()
.appendLine("粗斜体").setBoldItalic()
.appendLine("monospace 字体").setFontFamily("monospace")
.appendLine("自定义字体").setTypeface(Typeface.createFromAsset(assets, "fonts/dnmbhs.ttf"))
.appendLine("相反对齐").setHorizontalAlign(Layout.Alignment.ALIGN_OPPOSITE)
.appendLine("居中对齐").setHorizontalAlign(Layout.Alignment.ALIGN_CENTER)
.appendLine("正常对齐").setHorizontalAlign(Layout.Alignment.ALIGN_NORMAL)
.append("测试").appendLine("点击事件").setClickSpan(clickableSpan)
.append("测试").appendLine("Url").setUrl("https://github.com/Blankj/AndroidUtilCode")
.append("测试").appendLine("模糊").setBlur(3f, BlurMaskFilter.Blur.NORMAL)
.appendLine("颜色渐变").setShader(LinearGradient(0f, 0f, 64f * density * 4f, 0f, resources.getIntArray(R.array.rainbow), null, Shader.TileMode.REPEAT)).setFontSize(64, true)
.appendLine("图片着色").setFontSize(64, true).setShader(BitmapShader(BitmapFactory.decodeResource(resources, R.drawable.span_cheetah), Shader.TileMode.REPEAT, Shader.TileMode.REPEAT))
.appendLine("阴影效果").setFontSize(64, true).setBackgroundColor(Color.BLACK).setShadow(24f, 8f, 8f, Color.WHITE)
.append("小图").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_TOP)
.append("顶部").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_CENTER)
.append("居中").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_BASELINE)
.append("底部").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_low, SpanUtils.ALIGN_BOTTOM)
.appendLine("对齐").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP)
.append("大图").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP)
.append("顶部").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_TOP)
.appendLine("对齐").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER)
.append("大图").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER)
.append("居中").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_CENTER)
.appendLine("对齐").setBackgroundColor(Color.GREEN)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM)
.append("大图").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM)
.append("底部").setBackgroundColor(Color.LTGRAY)
.appendImage(R.drawable.span_block_high, SpanUtils.ALIGN_BOTTOM)
.appendLine("对齐").setBackgroundColor(Color.LTGRAY)
.append("测试空格").appendSpace(30, Color.LTGRAY).appendSpace(50, Color.GREEN).appendSpace(100).appendSpace(30, Color.LTGRAY).appendSpace(50, Color.GREEN)
.create()
// initAnimSpan();
// startAnim();
}
private fun initAnimSpan() {
mShaderWidth = 64f * density * 4f
mShader = LinearGradient(0f, 0f,
mShaderWidth, 0f,
resources.getIntArray(R.array.rainbow), null,
Shader.TileMode.REPEAT)
matrix = Matrix()
mBlurMaskFilterSpan = BlurMaskFilterSpan(25f)
mShadowSpan = ShadowSpan(8f, 8f, 8f, Color.WHITE)
mForegroundAlphaColorSpan = ForegroundAlphaColorSpan(Color.TRANSPARENT)
mForegroundAlphaColorSpanGroup = ForegroundAlphaColorSpanGroup(0f)
mPrinterString = "打印动画,后面的文字是为了测试打印效果..."
mSpanUtils = SpanUtils()
.appendLine("彩虹动画").setFontSize(64, true).setShader(mShader)
.appendLine("模糊动画").setFontSize(64, true).setSpans(mBlurMaskFilterSpan)
.appendLine("阴影动画").setFontSize(64, true).setBackgroundColor(Color.BLACK).setSpans(mShadowSpan)
.appendLine("透明动画").setFontSize(64, true).setSpans(mForegroundAlphaColorSpan)
var i = 0
val len = mPrinterString.length
while (i < len) {
val span = ForegroundAlphaColorSpan(Color.TRANSPARENT)
mSpanUtils.append(mPrinterString.substring(i, i + 1)).setSpans(span)
mForegroundAlphaColorSpanGroup.addSpan(span)
++i
}
animSsb = mSpanUtils.create()
}
private fun startAnim() {
valueAnimator = ValueAnimator.ofFloat(0f, 1f)
valueAnimator.addUpdateListener { animation ->
// shader
matrix.reset()
matrix.setTranslate(animation.animatedValue as Float * mShaderWidth, 0f)
mShader.setLocalMatrix(matrix)
// blur
mBlurMaskFilterSpan.radius = 25 * (1.00001f - animation.animatedValue as Float)
// shadow
mShadowSpan.dx = 16 * (0.5f - animation.animatedValue as Float)
mShadowSpan.dy = 16 * (0.5f - animation.animatedValue as Float)
// alpha
mForegroundAlphaColorSpan.setAlpha((255 * animation.animatedValue as Float).toInt())
// printer
mForegroundAlphaColorSpanGroup.alpha = animation.animatedValue as Float
// showMsg
spanAboutAnimTv.text = animSsb
}
valueAnimator.interpolator = LinearInterpolator()
valueAnimator.duration = (600 * 3).toLong()
valueAnimator.repeatCount = ValueAnimator.INFINITE
valueAnimator.start()
}
override fun doBusiness() {}
override fun onDebouncingClick(view: View) {}
// override fun onDestroy() {
// if (valueAnimator.isRunning) {
// valueAnimator.cancel()
// }
// super.onDestroy()
// }
}
class BlurMaskFilterSpan(private var mRadius: Float) : CharacterStyle(), UpdateAppearance {
private var mFilter: MaskFilter? = null
var radius: Float
get() = mRadius
set(radius) {
mRadius = radius
mFilter = BlurMaskFilter(mRadius, BlurMaskFilter.Blur.NORMAL)
}
override fun updateDrawState(ds: TextPaint) {
ds.maskFilter = mFilter
}
}
class ForegroundAlphaColorSpan(@param:ColorInt private var mColor: Int) : CharacterStyle(), UpdateAppearance {
fun setAlpha(alpha: Int) {
mColor = Color.argb(alpha, Color.red(mColor), Color.green(mColor), Color.blue(mColor))
}
override fun updateDrawState(ds: TextPaint) {
ds.color = mColor
}
}
class ForegroundAlphaColorSpanGroup(private val mAlpha: Float) {
private val mSpans: ArrayList<ForegroundAlphaColorSpan> = ArrayList()
var alpha: Float
get() = mAlpha
set(alpha) {
val size = mSpans.size
var total = 1.0f * size.toFloat() * alpha
for (index in 0 until size) {
val span = mSpans[index]
if (total >= 1.0f) {
span.setAlpha(255)
total -= 1.0f
} else {
span.setAlpha((total * 255).toInt())
total = 0.0f
}
}
}
fun addSpan(span: ForegroundAlphaColorSpan) {
span.setAlpha((mAlpha * 255).toInt())
mSpans.add(span)
}
}
class ShadowSpan(private val radius: Float, var dx: Float, var dy: Float, private val shadowColor: Int) : CharacterStyle(), UpdateAppearance {
override fun updateDrawState(tp: TextPaint) {
tp.setShadowLayer(radius, dx, dy, shadowColor)
}
} | apache-2.0 | 740712ed82f0a2c2cefc20770a4c5609 | 41.750877 | 195 | 0.644176 | 4.53743 | false | false | false | false |
iarchii/trade_app | app/src/main/java/xyz/thecodeside/tradeapp/repository/remote/socket/SocketManager.kt | 1 | 1807 | package xyz.thecodeside.tradeapp.repository.remote.socket
import io.reactivex.Flowable
import xyz.thecodeside.tradeapp.helpers.Logger
import xyz.thecodeside.tradeapp.model.BaseSocket
import xyz.thecodeside.tradeapp.model.SocketRequest
import xyz.thecodeside.tradeapp.model.SocketType
class SocketManager(private val socketAddress: String,
private val socket: RxSocketWrapper,
private val packer: SocketItemPacker,
private val logger: Logger) {
companion object {
const val TAG = "SOCKET"
}
fun connect(): Flowable<RxSocketWrapper.Status> = socket
.connect(socketAddress)
.doOnError {
disconnect()
}
private fun isReady(it: RxSocketWrapper.Status) =
it == RxSocketWrapper.Status.READY
fun disconnect() = socket.disconnect()
fun send(item: SocketRequest) = socket.send(packer.pack(item))
fun observe(): Flowable<BaseSocket> = socket
.observeSocketMessages()
.flatMap { unpackItem(it) }
.map {
checkIsReady(it)
it
}
private fun checkIsReady(it: BaseSocket) {
if (isConnected() && isConnectedMessage(it)) {
socket.status = RxSocketWrapper.Status.READY
}
}
private fun isConnectedMessage(it: BaseSocket) =
it.type == SocketType.CONNECT_CONNECTED
private fun isConnected() = socket.status == RxSocketWrapper.Status.CONNECTED
fun unpackItem(envelope: String?): Flowable<BaseSocket> = Flowable
.fromCallable { (packer.unpack(envelope)) }
.onErrorResumeNext { e: Throwable ->
logger.logException(e)
Flowable.never<BaseSocket>()
}
}
| apache-2.0 | bd5469a5f6300e0e2ba54daf4b483615 | 29.116667 | 81 | 0.624792 | 4.87062 | false | false | false | false |
Lennoard/HEBF | app/src/main/java/com/androidvip/hebf/ui/main/tools/ToolsFragment2.kt | 1 | 14078 | package com.androidvip.hebf.ui.main.tools
import android.content.Context
import android.content.Intent
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.appcompat.widget.AppCompatTextView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.updateLayoutParams
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import com.androidvip.hebf.*
import com.androidvip.hebf.ui.main.tools.apps.AppsManagerActivity
import com.androidvip.hebf.ui.main.tools.apps.AutoStartDisablerActivity
import com.androidvip.hebf.databinding.FragmentTools2Binding
import com.androidvip.hebf.ui.base.binding.BaseViewBindingFragment
import com.androidvip.hebf.ui.main.LottieAnimViewModel
import com.androidvip.hebf.ui.main.tools.cleaner.CleanerActivity
import com.androidvip.hebf.utils.K
import com.androidvip.hebf.utils.Logger
import com.androidvip.hebf.utils.RootUtils
import com.androidvip.hebf.utils.Utils
import com.google.android.material.behavior.SwipeDismissBehavior
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.launch
import org.koin.androidx.viewmodel.ext.android.sharedViewModel
import java.io.File
class ToolsFragment2 : BaseViewBindingFragment<FragmentTools2Binding>(
FragmentTools2Binding::inflate
) {
private val animViewModel: LottieAnimViewModel by sharedViewModel()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.wifiSettings.setOnClickListener {
findNavController().navigate(R.id.startWiFiTweaksFragment)
}
binding.fstrim.setOnClickListener {
findNavController().navigate(R.id.startFstrimFragment)
}
binding.cleaner.setOnClickListener {
Intent(findContext(), CleanerActivity::class.java).apply {
startActivity(this)
requireActivity().overridePendingTransition(
R.anim.slide_in_right, R.anim.fragment_open_exit
)
}
}
binding.autoStartDisabler.setOnClickListener {
Intent(findContext(), AutoStartDisablerActivity::class.java).apply {
startActivity(this)
}
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.fragment_open_exit)
}
binding.appsManager.setOnClickListener {
Intent(findContext(), AppsManagerActivity::class.java).apply {
startActivity(this)
}
requireActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.fragment_open_exit)
}
lifecycleScope.launch(workerContext) {
val isRooted = isRooted()
val supportsAppOps = !Utils.runCommand(
"which appops",
""
).isNullOrEmpty()
val ipv6File = File("/proc/net/if_inet6")
val supportsIpv6 = ipv6File.exists() || ipv6File.isFile
val ipv6State = RootUtils.executeWithOutput(
"cat /proc/sys/net/ipv6/conf/all/disable_ipv6",
"0",
activity
)
val captivePortalStatus = RootUtils.executeWithOutput(
"settings get global captive_portal_detection_enabled",
"1",
activity
)
val hostnameFound = Utils.runCommand("getprop net.hostname", "")
val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
val supportsWifi5 = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && wifiManager.is5GHzBandSupported
val preferredWifiBand = RootUtils.executeWithOutput(
"settings get global wifi_frequency_band", "null", activity
)
runSafeOnUiThread {
setUpNetControls(isRooted)
setUpControls(isRooted)
setUpSwipes(isRooted)
binding.autoStartDisabler.isEnabled = supportsAppOps && isRooted
binding.hostnameField.apply {
setText(hostnameFound)
isEnabled = isRooted
}
binding.captivePortal.apply {
isEnabled = isRooted
setChecked(captivePortalStatus == "1" || captivePortalStatus == "null")
setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
runCommand("settings put global captive_portal_detection_enabled 1")
} else {
runCommand("settings put global captive_portal_detection_enabled 0")
}
}
}
binding.ipv6.apply {
if (!supportsIpv6) {
prefs.putInt(K.PREF.NET_IPV6_STATE, -1)
}
isEnabled = isRooted && supportsIpv6
binding.ipv6.setChecked(ipv6State == "0")
binding.ipv6.setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
runCommand(arrayOf(
"sysctl -w net.ipv6.conf.all.disable_ipv6=0",
"sysctl -w net.ipv6.conf.wlan0.accept_ra=1")
)
Logger.logInfo("IPv6 enabled", findContext())
prefs.putInt(K.PREF.NET_IPV6_STATE, 1)
} else {
runCommand(arrayOf(
"sysctl -w net.ipv6.conf.all.disable_ipv6=1",
"sysctl -w net.ipv6.conf.wlan0.accept_ra=0")
)
Logger.logInfo("IPv6 disabled", findContext())
prefs.putInt(K.PREF.NET_IPV6_STATE, 0)
}
}
}
binding.prefer5ghz.apply {
isEnabled = supportsWifi5 && isRooted
setChecked(preferredWifiBand == "1")
setOnCheckedChangeListener { _, isChecked ->
if (isChecked) {
runCommand("settings put global wifi_frequency_band 1")
Logger.logInfo("Set preferred Wi-Fi frequency band to 5GHz", findContext())
} else {
runCommand("settings put global wifi_frequency_band 0")
Logger.logInfo("Set preferred Wi-Fi frequency band to auto", findContext())
}
}
}
binding.zipalign.apply {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) { // Real OG's
show()
}
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.TOOLS_ZIPALIGN, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.TOOLS_ZIPALIGN, isChecked)
if (isChecked) {
Logger.logInfo("Zipalign enabled", findContext())
RootUtils.runInternalScriptAsync("zipalign_tweak", findContext())
} else {
Logger.logInfo("Zipalign disabled", findContext())
}
}
}
binding.kernelOptions.apply {
isEnabled = isRooted
setOnClickListener {
findNavController().navigate(R.id.startKernelOptionsFragment)
}
}
}
}
}
override fun onResume() {
super.onResume()
animViewModel.setAnimRes(R.raw.tools_anim)
}
private fun setUpControls(isRooted: Boolean) {
binding.kernelPanic.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.TOOLS_KERNEL_PANIC, true))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.TOOLS_KERNEL_PANIC, isChecked)
if (isChecked) {
runCommands(
"sysctl -w kernel.panic=5",
"sysctl -w kernel.panic_on_oops=1",
"sysctl -w kernel.panic=1",
"sysctl -w vm.panic_on_oom=1"
)
Snackbar.make(this, R.string.done, Snackbar.LENGTH_SHORT).apply {
view.translationY = (54.dp) * -1
show()
}
Logger.logInfo("Kernel panic enabled", findContext())
} else {
runCommands(
"sysctl -w kernel.panic=0",
"sysctl -w kernel.panic_on_oops=0",
"sysctl -w kernel.panic=0",
"sysctl -w vm.panic_on_oom=0"
)
Snackbar.make(this, R.string.panic_off, Snackbar.LENGTH_SHORT).apply {
view.translationY = (54.dp) * -1
show()
}
Logger.logInfo("Kernel panic disabled", findContext())
}
}
}
binding.disableLogging.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.TOOLS_LOGCAT, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.TOOLS_LOGCAT, isChecked)
if (isChecked) {
Logger.logInfo("Android logging disabled", findContext())
runCommand("stop logd")
} else {
Logger.logInfo("Android logging re-enabled", findContext())
runCommand("start logd")
}
}
}
}
private fun setUpNetControls(isRooted: Boolean) {
binding.tcp.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.NET_TCP, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.NET_TCP, isChecked)
if (isChecked) {
RootUtils.runInternalScriptAsync("net", findContext())
Logger.logInfo("TCP tweaks added", findContext())
} else {
Logger.logInfo("TCP tweaks removed", findContext())
}
}
}
binding.signal.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.NET_SIGNAL, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.NET_SIGNAL, isChecked)
if (isChecked) {
RootUtils.runInternalScriptAsync("3g_on", findContext())
Logger.logInfo("Added signal tweaks", findContext())
} else {
Logger.logInfo("Removed signal tweaks", findContext())
}
}
}
binding.browsing.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.NET_BUFFERS, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.NET_BUFFERS, isChecked)
if (isChecked) {
RootUtils.runInternalScriptAsync("buffer_on", findContext())
} else {
Logger.logInfo("Removed buffer tweaks", findContext())
}
}
}
binding.stream.apply {
isEnabled = isRooted
setChecked(prefs.getBoolean(K.PREF.NET_STREAM_TWEAKS, false))
setOnCheckedChangeListener { _, isChecked ->
prefs.putBoolean(K.PREF.NET_STREAM_TWEAKS, isChecked)
if (isChecked) {
RootUtils.runInternalScriptAsync("st_on", findContext())
} else {
Logger.logInfo("Removed video streaming tweaks", findContext())
}
}
}
binding.hostnameButton.apply {
isEnabled = isRooted
setOnClickListener {
val hostname = binding.hostnameField.text.toString().trim().replace(" ", "")
if (hostname.isEmpty()) {
Utils.showEmptyInputFieldSnackbar(binding.hostnameField)
} else {
val log = "Hostname set to: $hostname"
runCommand("setprop net.hostname $hostname")
Logger.logInfo(log, applicationContext)
requireContext().toast(log)
userPrefs.putString(K.PREF.NET_HOSTNAME, hostname)
}
}
}
}
private fun setUpSwipes(isRooted: Boolean) {
if (isRooted) return
binding.warningLayout.show()
binding.noRootWarning.updateLayoutParams<CoordinatorLayout.LayoutParams> {
behavior = SwipeDismissBehavior<AppCompatTextView>().apply {
setSwipeDirection(SwipeDismissBehavior.SWIPE_DIRECTION_ANY)
listener = object : SwipeDismissBehavior.OnDismissListener {
override fun onDismiss(view: View?) {
if (binding.warningLayout.childCount == 1) {
binding.warningLayout.goAway()
view?.goAway()
} else {
view?.goAway()
}
}
override fun onDragStateChanged(state: Int) {}
}
}
}
}
} | apache-2.0 | e77fffae05f5fec23a27c348bc5f7995 | 40.777448 | 120 | 0.530473 | 5.454475 | false | false | false | false |
gatheringhallstudios/MHGenDatabase | app/src/main/java/com/ghstudios/android/features/skills/detail/SkillTreeDetailPagerActivity.kt | 1 | 3260 | package com.ghstudios.android.features.skills.detail
import androidx.lifecycle.Observer
import android.view.Menu
import android.view.MenuItem
import androidx.lifecycle.ViewModelProvider
import com.ghstudios.android.AppSettings
import com.ghstudios.android.data.classes.Armor
import com.ghstudios.android.BasePagerActivity
import com.ghstudios.android.MenuSection
import com.ghstudios.android.mhgendatabase.R
class SkillTreeDetailPagerActivity : BasePagerActivity() {
companion object {
/**
* A key for passing a monster ID as a long
*/
const val EXTRA_SKILLTREE_ID = "com.daviancorp.android.android.ui.detail.skill_id"
}
/**
* Viewmodel for the entirity of this skill detail, including sub fragments
*/
private val viewModel by lazy {
ViewModelProvider(this).get(SkillDetailViewModel::class.java)
}
override fun onAddTabs(tabs: BasePagerActivity.TabAdder) {
val skillTreeId = intent.getLongExtra(EXTRA_SKILLTREE_ID, -1)
viewModel.setSkillTreeId(skillTreeId, showPenalties=AppSettings.showSkillPenalties)
viewModel.skillTreeData.observe(this, Observer { data ->
if (data != null) {
this.title = data.name
}
})
tabs.addTab(R.string.skill_tab_detail) {
SkillTreeDetailFragment.newInstance(skillTreeId)
}
tabs.addTab(R.string.type_decoration) {
SkillTreeDecorationFragment.newInstance(skillTreeId)
}
tabs.addTab(R.string.skill_tab_head) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_HEAD)
}
tabs.addTab(R.string.skill_tab_body) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_BODY)
}
tabs.addTab(R.string.skill_tab_arms) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_ARMS)
}
tabs.addTab(R.string.skill_tab_waist) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_WAIST)
}
tabs.addTab(R.string.skill_tab_legs) {
SkillTreeArmorFragment.newInstance(skillTreeId, Armor.ARMOR_SLOT_LEGS)
}
}
override fun getSelectedSection(): Int {
return MenuSection.SKILL_TREES
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu) // will inflate global actions like search
menuInflater.inflate(R.menu.menu_skill_detail, menu)
menu.findItem(R.id.show_negative).isChecked = AppSettings.showSkillPenalties
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle superclass cases first. If handled, return immediately
val handled = super.onOptionsItemSelected(item)
if (handled) {
return true
}
return when (item.itemId) {
R.id.show_negative -> {
val newSetting = !AppSettings.showSkillPenalties
AppSettings.showSkillPenalties = newSetting
viewModel.setShowPenalties(newSetting)
item.isChecked = newSetting
true
}
else -> false
}
}
}
| mit | 96c3ef25a16e3a87d5d96efde7dfc595 | 31.6 | 91 | 0.659509 | 4.611033 | false | false | false | false |
jean79/yested_fw | src/jsMain/kotlin/net/yested/core/html/htmlbind.kt | 1 | 11316 | package net.yested.core.html
import net.yested.core.properties.bind
import net.yested.core.properties.Property
import net.yested.core.properties.ReadOnlyProperty
import net.yested.core.properties.map
import net.yested.core.properties.zip
import net.yested.core.utils.*
import org.w3c.dom.*
import kotlin.browser.document
/**
* Property binding to HTML elements.
* @author Eric Pabst ([email protected])
* Date: 2/2/17
* Time: 11:00 PM
*/
fun HTMLInputElement.bind(property: Property<String>) {
var updating = false
property.onNext {
if (!updating) {
value = it
}
}
addEventListener("change", { updating = true; property.set(value); updating = false }, false)
addEventListener("keyup", { updating = true; property.set(value); updating = false }, false)
}
fun HTMLTextAreaElement.bind(property: Property<String>) {
var updating = false
property.onNext {
if (!updating) {
value = it
}
}
addEventListener("change", { updating = true; property.set(value); updating = false }, false)
addEventListener("keyup", { updating = true; property.set(value); updating = false }, false)
}
fun HTMLInputElement.bindChecked(checked: Property<Boolean>) {
val element = this
var updating = false
checked.onNext {
if (!updating) {
element.checked = it
}
}
addEventListener("change", { updating = true; checked.set(element.checked); updating = false }, false)
}
fun <T> HTMLSelectElement.bindMultiselect(selected: Property<List<T>>, options: ReadOnlyProperty<List<T>>, render: HTMLElement.(T)->Unit) {
bindMultiselect(selected, options, { selected.set(it) }, render)
}
fun <T> HTMLSelectElement.bindMultiselect(selected: ReadOnlyProperty<List<T>>, options: ReadOnlyProperty<List<T>>, onSelect: (List<T>) -> Unit, render: HTMLElement.(T)->Unit) {
val selectElement = this
options.onNext {
removeAllChildElements()
it.forEachIndexed { index, item ->
val option: HTMLOptionElement = document.createElement("option").asDynamic()
option.value = "$index"
option.render(item)
appendChild(option)
}
}
var updating = false
selected.zip(options).onNext { (selectedList, options) ->
if (!updating) {
options.forEachIndexed { index, option ->
if (index < selectElement.options.length) {
(selectElement.options.get(index) as HTMLOptionElement).selected = selectedList.contains(option)
}
}
}
}
addEventListener("change", {
val selectOptions = this.options
val selectedValues = (1..selectOptions.length)
.map { selectOptions[it - 1] }
.filter { (it as HTMLOptionElement).selected }
.map { (it as HTMLOptionElement).value }
.map { options.get()[it.toInt()] }
updating = true
onSelect.invoke(selectedValues)
updating = false
}, false)
}
fun <T> HTMLSelectElement.bind(selected: Property<T>, options: ReadOnlyProperty<List<T>>, render: HTMLElement.(T)->Unit) {
@Suppress("UNCHECKED_CAST") // T is allowed to be nullable or not-nullable.
val multipleSelected = selected.bind({ if (it == null) emptyList<T>() else listOf(it) }, { it.firstOrNull() as T })
bindMultiselect(multipleSelected, options, render)
}
fun <T> HTMLSelectElement.bind(selected: ReadOnlyProperty<T>, options: ReadOnlyProperty<List<T>>, onSelect: (T) -> Unit, render: HTMLElement.(T)->Unit) {
val multiSelected: ReadOnlyProperty<List<T>> = selected.map { if (it == null) emptyList() else listOf(it) }
@Suppress("UNCHECKED_CAST") // T is allowed to be nullable or not-nullable.
bindMultiselect(multiSelected, options, { onSelect(it.firstOrNull() as T) }, render)
}
fun <T> HTMLSelectElement.bindOptional(selected: ReadOnlyProperty<T?>, options: ReadOnlyProperty<List<T>>, onSelect: (T) -> Unit, render: HTMLElement.(T)->Unit) {
val multiSelected: ReadOnlyProperty<List<T>> = selected.map { if (it == null) emptyList() else listOf(it) }
@Suppress("UNCHECKED_CAST") // T is allowed to be nullable or not-nullable.
bindMultiselect(multiSelected, options, { onSelect(it.firstOrNull() as T) }, render)
}
fun HTMLElement.setClassPresence(className: String, present: ReadOnlyProperty<Boolean>) {
setClassPresence(className, present, true)
}
fun <T> HTMLElement.setClassPresence(className: String, property: ReadOnlyProperty<T>, presentValue: T) {
property.onNext {
if (it == presentValue) addClass2(className) else removeClass2(className)
}
}
fun HTMLButtonElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLInputElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLTextAreaElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLSelectElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLFieldSetElement.setDisabled(property: ReadOnlyProperty<Boolean>) {
property.onNext { disabled = it }
}
fun HTMLInputElement.setReadOnly(property: ReadOnlyProperty<Boolean>) {
property.onNext { readOnly = it }
}
fun HTMLTextAreaElement.setReadOnly(property: ReadOnlyProperty<Boolean>) {
property.onNext { readOnly = it }
}
/** This exists because Kotlin's ArrayList calls throwCCE() if a non-null Element doesn't extend "Any". */
private data class ElementWrapper(val element: Element?)
private fun HTMLCollection.toWrapperList(): List<ElementWrapper> {
return (0..(this.length - 1)).map { ElementWrapper(item(it)) }
}
fun <C: HTMLElement,T> C.repeatLive(orderedData: ReadOnlyProperty<Iterable<T>?>, effect: BiDirectionEffect = NoEffect, itemInit: C.(T) -> Unit) {
return repeatLive(orderedData, effect, { _, item -> itemInit(item) })
}
fun <C: HTMLElement,T> C.repeatLive(orderedData: ReadOnlyProperty<Iterable<T>?>, effect: BiDirectionEffect = NoEffect, itemInit: C.(Int, T) -> Unit) {
val containerElement = this
val itemsWithoutDelays = mutableListOf<List<ElementWrapper>>()
var operableList : DomOperableList<C,T>? = null
var elementAfter: HTMLElement? = null
orderedData.onNext { values ->
val operableListSnapshot = operableList
if (values == null) {
itemsWithoutDelays.flatten().forEach {
if (it.element?.parentElement == containerElement) {
containerElement.removeChild(it.element)
}
}
itemsWithoutDelays.clear()
operableList = null
} else if (operableListSnapshot == null) {
itemsWithoutDelays.flatten().forEach {
if (it.element?.parentElement == containerElement) {
containerElement.removeChild(it.element)
}
}
itemsWithoutDelays.clear()
val domOperableList = DomOperableList(values.toMutableList(), itemsWithoutDelays, containerElement, effect, elementAfter, itemInit)
values.forEachIndexed { index, item ->
domOperableList.addItemToContainer(containerElement, index, item, itemsWithoutDelays, elementAfter)
}
operableList = domOperableList
} else {
operableListSnapshot.reconcileTo(values.toList())
}
}
elementAfter = span() // create a <span/> to clearly indicate where to insert new elements.
operableList?.elementAfter = elementAfter
}
private class DomOperableList<C : HTMLElement,T>(
initialData: MutableList<T>,
val itemsWithoutDelays: MutableList<List<ElementWrapper>>,
val container: C,
val effect: BiDirectionEffect,
var elementAfter: HTMLElement? = null,
val itemInit: C.(Int, T) -> Unit) : InMemoryOperableList<T>(initialData) {
override fun add(index: Int, item: T) {
addItemToContainer(container, index, item, itemsWithoutDelays, elementAfter).forEach { if (it.element is HTMLElement) effect.applyIn(it.element) }
super.add(index, item)
}
override fun removeAt(index: Int): T {
val elementsForIndex = itemsWithoutDelays.removeAt(index)
elementsForIndex.forEach {
if (it.element is HTMLElement) {
effect.applyOut(it.element) {
if (it.element.parentElement == container) {
container.removeChild(it.element)
}
}
} else if (it.element?.parentElement == container) {
container.removeChild(it.element)
}
}
return super.removeAt(index)
}
override fun move(fromIndex: Int, toIndex: Int) {
val item = removeAt(fromIndex)
add(toIndex, item)
}
fun addItemToContainer(container: C, index: Int, item: T, itemsWithoutDelays: MutableList<List<ElementWrapper>>, elementAfter: HTMLElement?): List<ElementWrapper> {
val nextElement = if (index < itemsWithoutDelays.size) itemsWithoutDelays.get(index).firstOrNull()?.element else elementAfter
val childrenBefore = container.children.toWrapperList()
container.itemInit(index, item)
val childrenLater = container.children.toWrapperList()
val newChildren = childrenLater.filterNot { childrenBefore.contains(it) }
if (nextElement != null && nextElement.parentElement == container) {
newChildren.forEach { it.element?.let { container.insertBefore(it, nextElement) } }
}
itemsWithoutDelays.add(index, newChildren)
return newChildren
}
}
/**
* Bind table content to a Property<Iterable<T>>. The index and value are provided to itemInit.
* Example:<pre>
* table {
* thead {
* th { appendText("Name") }
* th { appendText("Value") }
* }
* tbody(myData, effect = Collapse()) { index, item ->
* tr { className = if (index % 2 == 0) "even" else "odd"
* td { appendText(item.name) }
* td { appendText(item.value) }
* }
* }
* }
* </pre>
*/
fun <T> HTMLTableElement.tbody(orderedData: ReadOnlyProperty<Iterable<T>?>, effect: BiDirectionEffect = NoEffect,
itemInit: HTMLTableSectionElement.(Int, T) -> Unit) {
tbody { repeatLive(orderedData, effect, itemInit) }
}
/**
* Bind table content to a Property<Iterable<T>>. The value is provided to itemInit.
* Example:<pre>
* table {
* thead {
* th { appendText("Name") }
* th { appendText("Value") }
* }
* tbody(myData, effect = Collapse()) { item ->
* tr { className = if (index % 2 == 0) "even" else "odd"
* td { appendText(item.name) }
* td { appendText(item.value) }
* }
* }
* }
* </pre>
*/
fun <T> HTMLTableElement.tbody(orderedData: ReadOnlyProperty<Iterable<T>?>, effect: BiDirectionEffect = NoEffect,
itemInit: HTMLTableSectionElement.(T) -> Unit): HTMLTableSectionElement {
return tbody { repeatLive(orderedData, effect, itemInit) }
}
| mit | b9947f4c395fc636c3f32e0b7a16b1dd | 39.270463 | 176 | 0.645634 | 4.389449 | false | false | false | false |
google-home/sample-app-for-matter-android | app/src/main/java/com/google/homesampleapp/screens/home/DeviceViewHolder.kt | 1 | 3940 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.homesampleapp.screens.home
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.homesampleapp.*
import com.google.homesampleapp.databinding.DeviceViewItemBinding
import timber.log.Timber
/**
* ViewHolder for a device item in the devices list, which is backed by RecyclerView. The ViewHolder
* is a wrapper around a View that contains the layout for an individual item in the list.
*
* When the view holder is created, it doesn't have any data associated with it. After the view
* holder is created, the RecyclerView binds it to its data. The RecyclerView requests those views,
* and binds the views to their data, by calling methods in the adapter (see DevicesAdapter).
*/
class DeviceViewHolder(private val binding: DeviceViewItemBinding) :
RecyclerView.ViewHolder(binding.root) {
// TODO: Can't this be cached somewhere?
private val lightBulbIcon = getResourceId("quantum_gm_ic_lights_gha_vd_theme_24")
private val outletIcon = getResourceId("ic_baseline_outlet_24")
private val unknownDeviceIcon = getResourceId("ic_baseline_device_unknown_24")
private val shapeOffDrawable = getDrawable("device_item_shape_off")
private val shapeOnDrawable = getDrawable("device_item_shape_on")
/**
* Binds the Device (DeviceUiModel, the model class) to the UI element (device_view_item.xml) that
* holds the Device view.
*
* TODO: change icon
* https://stackoverflow.com/questions/16906528/change-image-of-imageview-programmatically-in-android
*/
fun bind(deviceUiModel: DeviceUiModel) {
Timber.d("binding device [${deviceUiModel}]")
val iconResourceId =
when (deviceUiModel.device.deviceType) {
Device.DeviceType.TYPE_LIGHT -> lightBulbIcon
Device.DeviceType.TYPE_OUTLET -> outletIcon
else -> unknownDeviceIcon
}
val shapeDrawable =
if (deviceUiModel.isOnline && deviceUiModel.isOn) shapeOnDrawable else shapeOffDrawable
binding.zeicon.setImageResource(iconResourceId)
binding.name.text = deviceUiModel.device.name
binding.zestate.text = stateDisplayString(deviceUiModel.isOnline, deviceUiModel.isOn)
binding.rootLayout.background = shapeDrawable
if (ON_OFF_SWITCH_DISABLED_WHEN_DEVICE_OFFLINE) {
binding.onoffSwitch.isEnabled = deviceUiModel.isOnline
} else {
binding.onoffSwitch.isEnabled = true
}
binding.onoffSwitch.isChecked = deviceUiModel.isOn
}
private fun getDrawable(name: String): Drawable? {
val resources: Resources = itemView.context.resources
val resourceId = resources.getIdentifier(name, "drawable", itemView.context.packageName)
return resources.getDrawable(resourceId)
}
private fun getResourceId(name: String): Int {
val resources: Resources = itemView.context.resources
return resources.getIdentifier(name, "drawable", itemView.context.packageName)
}
companion object {
fun create(parent: ViewGroup): DeviceViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.device_view_item, parent, false)
val binding = DeviceViewItemBinding.bind(view)
return DeviceViewHolder(binding)
}
}
}
| apache-2.0 | 2f8e17afa0cd0e53bfaa48f0c32e0f0d | 40.473684 | 103 | 0.749492 | 4.363234 | false | false | false | false |
danrien/projectBlue | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/settings/ApplicationSettingsActivity.kt | 1 | 9166 | package com.lasthopesoftware.bluewater.settings
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.ProgressBar
import android.widget.RadioGroup
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.about.AboutTitleBuilder
import com.lasthopesoftware.bluewater.client.browsing.library.access.LibraryRepository
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.BrowserLibrarySelection
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectedBrowserLibraryIdentifierProvider
import com.lasthopesoftware.bluewater.client.playback.engine.selection.PlaybackEngineType
import com.lasthopesoftware.bluewater.client.playback.engine.selection.PlaybackEngineTypeSelectionPersistence
import com.lasthopesoftware.bluewater.client.playback.engine.selection.SelectedPlaybackEngineTypeAccess
import com.lasthopesoftware.bluewater.client.playback.engine.selection.broadcast.PlaybackEngineTypeChangedBroadcaster
import com.lasthopesoftware.bluewater.client.playback.engine.selection.defaults.DefaultPlaybackEngineLookup
import com.lasthopesoftware.bluewater.client.playback.engine.selection.view.PlaybackEngineTypeSelectionView
import com.lasthopesoftware.bluewater.client.playback.service.PlaybackService
import com.lasthopesoftware.bluewater.client.servers.list.ServerListAdapter
import com.lasthopesoftware.bluewater.client.servers.list.listeners.EditServerClickListener
import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository
import com.lasthopesoftware.bluewater.shared.android.messages.MessageBus
import com.lasthopesoftware.bluewater.shared.android.notifications.notificationchannel.SharedChannelProperties
import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise
import com.lasthopesoftware.bluewater.tutorials.TutorialManager
import tourguide.tourguide.Overlay
import tourguide.tourguide.Pointer
import tourguide.tourguide.ToolTip
import tourguide.tourguide.TourGuide
class ApplicationSettingsActivity : AppCompatActivity() {
private val channelConfiguration: SharedChannelProperties by lazy { SharedChannelProperties(this) }
private val progressBar = LazyViewFinder<ProgressBar>(this, R.id.recyclerLoadingProgress)
private val serverListView = LazyViewFinder<RecyclerView>(this, R.id.loadedRecyclerView)
private val notificationSettingsContainer = LazyViewFinder<LinearLayout>(this, R.id.notificationSettingsContainer)
private val modifyNotificationSettingsButton = LazyViewFinder<Button>(this, R.id.modifyNotificationSettingsButton)
private val addServerButton = LazyViewFinder<Button>(this, R.id.addServerButton)
private val killPlaybackEngineButton = LazyViewFinder<Button>(this, R.id.killPlaybackEngine)
private val settingsMenu = SettingsMenu(this, AboutTitleBuilder(this))
private val applicationSettingsRepository by lazy { getApplicationSettingsRepository() }
private val messageBus by lazy { MessageBus(LocalBroadcastManager.getInstance(this)) }
private val tutorialManager by lazy { TutorialManager(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_application_settings)
setSupportActionBar(findViewById(R.id.applicationSettingsToolbar))
HandleSyncCheckboxPreference.handle(
applicationSettingsRepository,
{ s -> s.isSyncOnPowerOnly },
{ s -> s::isSyncOnPowerOnly::set },
findViewById(R.id.syncOnPowerCheckbox))
HandleSyncCheckboxPreference.handle(
applicationSettingsRepository,
{ it.isSyncOnWifiOnly },
{ s -> s::isSyncOnWifiOnly::set },
findViewById(R.id.syncOnWifiCheckbox))
HandleCheckboxPreference.handle(
applicationSettingsRepository,
{ it.isVolumeLevelingEnabled },
{ s -> s::isVolumeLevelingEnabled::set },
findViewById(R.id.isVolumeLevelingEnabled))
val selection = PlaybackEngineTypeSelectionPersistence(
applicationSettingsRepository,
PlaybackEngineTypeChangedBroadcaster(MessageBus(LocalBroadcastManager.getInstance(this))))
val selectedPlaybackEngineTypeAccess = SelectedPlaybackEngineTypeAccess(applicationSettingsRepository, DefaultPlaybackEngineLookup())
val playbackEngineTypeSelectionView = PlaybackEngineTypeSelectionView(this)
val playbackEngineOptions = findViewById<RadioGroup>(R.id.playbackEngineOptions)
for (i in 0 until playbackEngineOptions.childCount)
playbackEngineOptions.getChildAt(i).isEnabled = false
for (rb in playbackEngineTypeSelectionView.buildPlaybackEngineTypeSelections())
playbackEngineOptions.addView(rb)
selectedPlaybackEngineTypeAccess.promiseSelectedPlaybackEngineType()
.eventually(LoopedInPromise.response({ t ->
playbackEngineOptions.check(t.ordinal)
for (i in 0 until playbackEngineOptions.childCount)
playbackEngineOptions.getChildAt(i).isEnabled = true
}, this))
playbackEngineOptions
.setOnCheckedChangeListener { _, checkedId -> selection.selectPlaybackEngine(PlaybackEngineType.values()[checkedId]) }
killPlaybackEngineButton.findView().setOnClickListener { PlaybackService.killService(this) }
addServerButton.findView().setOnClickListener(EditServerClickListener(this, -1))
updateServerList()
notificationSettingsContainer.findView().visibility = View.GONE
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
notificationSettingsContainer.findView().visibility = View.VISIBLE
tutorialManager
.promiseWasTutorialShown(TutorialManager.KnownTutorials.adjustNotificationInApplicationSettingsTutorial)
.eventually(LoopedInPromise.response({ wasTutorialShown ->
if (wasTutorialShown) {
modifyNotificationSettingsButton.findView().setOnClickListener { launchNotificationSettings() }
} else {
val displayColor = getColor(R.color.clearstream_blue)
val tourGuide = TourGuide.init(this).with(TourGuide.Technique.CLICK)
.setPointer(Pointer().setColor(displayColor))
.setToolTip(ToolTip()
.setTitle(getString(R.string.notification_settings_tutorial_title))
.setDescription(getString(R.string.notification_settings_tutorial).format(
getString(R.string.modify_notification_settings),
getString(R.string.app_name)))
.setBackgroundColor(displayColor))
.setOverlay(Overlay())
.playOn(modifyNotificationSettingsButton.findView())
modifyNotificationSettingsButton.findView().setOnClickListener {
tourGuide.cleanUp()
launchNotificationSettings()
}
tutorialManager.promiseTutorialMarked(TutorialManager.KnownTutorials.adjustNotificationInApplicationSettingsTutorial)
}
}, this))
}
override fun onCreateOptionsMenu(menu: Menu): Boolean = settingsMenu.buildSettingsMenu(menu)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
updateServerList()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean = settingsMenu.handleSettingsMenuClicks(item)
@RequiresApi(api = Build.VERSION_CODES.O)
private fun launchNotificationSettings() {
val intent = Intent(Settings.ACTION_CHANNEL_NOTIFICATION_SETTINGS)
intent.putExtra(Settings.EXTRA_APP_PACKAGE, packageName)
intent.putExtra(Settings.EXTRA_CHANNEL_ID, channelConfiguration.channelId)
startActivity(intent)
}
private fun updateServerList() {
serverListView.findView().visibility = View.INVISIBLE
progressBar.findView().visibility = View.VISIBLE
val libraryProvider = LibraryRepository(this)
val promisedLibraries = libraryProvider.allLibraries
val promisedSelectedLibrary = SelectedBrowserLibraryIdentifierProvider(applicationSettingsRepository).selectedLibraryId
val adapter = ServerListAdapter(
this,
BrowserLibrarySelection(applicationSettingsRepository, messageBus, libraryProvider))
val serverListView = serverListView.findView()
serverListView.adapter = adapter
serverListView.layoutManager = LinearLayoutManager(this)
promisedLibraries
.eventually { libraries ->
promisedSelectedLibrary
.eventually(LoopedInPromise.response({ chosenLibraryId ->
val selectedBrowserLibrary = libraries.firstOrNull { l -> l.libraryId == chosenLibraryId }
adapter.updateLibraries(libraries, selectedBrowserLibrary)
progressBar.findView().visibility = View.INVISIBLE
serverListView.visibility = View.VISIBLE
}, this))
}
}
companion object {
fun launch(context: Context) =
context.startActivity(Intent(context, ApplicationSettingsActivity::class.java))
}
}
| lgpl-3.0 | b6c3ccf15fa3c9ce7caa10fd1319cfc9 | 45.292929 | 144 | 0.826424 | 4.893753 | false | false | false | false |
samuelclay/NewsBlur | clients/android/NewsBlur/src/com/newsblur/view/StateToggleButton.kt | 1 | 2829 | package com.newsblur.view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import com.newsblur.databinding.StateToggleBinding
import com.newsblur.util.StateFilter
import com.newsblur.util.UIUtils
import com.newsblur.util.setViewGone
import com.newsblur.util.setViewVisible
class StateToggleButton(context: Context, art: AttributeSet?) : LinearLayout(context, art) {
private var state = StateFilter.SOME
private var stateChangedListener: StateChangedListener? = null
private val binding: StateToggleBinding
init {
binding = StateToggleBinding.inflate(LayoutInflater.from(context), this, true)
setState(state)
binding.toggleAll.setOnClickListener { setState(StateFilter.ALL) }
binding.toggleSome.setOnClickListener { setState(StateFilter.SOME) }
binding.toggleFocus.setOnClickListener { setState(StateFilter.BEST) }
binding.toggleSaved.setOnClickListener { setState(StateFilter.SAVED) }
}
fun setStateListener(stateChangedListener: StateChangedListener?) {
this.stateChangedListener = stateChangedListener
}
fun setState(state: StateFilter) {
this.state = state
updateButtonStates()
stateChangedListener?.changedState(this.state)
}
private fun updateButtonStates() {
binding.toggleAll.isEnabled = state != StateFilter.ALL
binding.toggleSome.isEnabled = state != StateFilter.SOME
binding.toggleSomeIcon.alpha = if (state == StateFilter.SOME) 1.0f else 0.6f
binding.toggleFocus.isEnabled = state != StateFilter.BEST
binding.toggleFocusIcon.alpha = if (state == StateFilter.BEST) 1.0f else 0.6f
binding.toggleSaved.isEnabled = state != StateFilter.SAVED
binding.toggleSavedIcon.alpha = if (state == StateFilter.SAVED) 1.0f else 0.6f
val widthDp = UIUtils.px2dp(context, context.resources.displayMetrics.widthPixels)
if (widthDp > 450) {
binding.toggleSomeText.setViewVisible()
binding.toggleFocusText.setViewVisible()
binding.toggleSavedText.setViewVisible()
} else if (widthDp > 400) {
binding.toggleSomeText.setViewVisible()
binding.toggleFocusText.setViewVisible()
binding.toggleSavedText.setViewGone()
} else if (widthDp > 350) {
binding.toggleSomeText.setViewVisible()
binding.toggleFocusText.setViewGone()
binding.toggleSavedText.setViewGone()
} else {
binding.toggleSomeText.setViewGone()
binding.toggleFocusText.setViewGone()
binding.toggleSavedText.setViewGone()
}
}
interface StateChangedListener {
fun changedState(state: StateFilter?)
}
} | mit | 78e00000f39fcee3c1520905e9423cf0 | 38.305556 | 92 | 0.707317 | 4.963158 | false | false | false | false |
JetBrains/resharper-unity | rider/src/main/kotlin/com/jetbrains/rider/plugins/unity/ui/UssDisabledEditorNotification.kt | 1 | 2799 | package com.jetbrains.rider.plugins.unity.ui
import com.intellij.ide.plugins.*
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.extensions.PluginId
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.ui.EditorNotificationPanel
import com.intellij.ui.EditorNotifications
import com.jetbrains.rider.plugins.unity.isUnityProject
class UssDisabledEditorNotification: EditorNotifications.Provider<EditorNotificationPanel>() {
companion object {
private val KEY = Key.create<EditorNotificationPanel>("unity.uss.css.plugin.disabled.notification.panel")
private const val DO_NOT_SHOW_AGAIN_KEY = "unity.uss.css.plugin.disabled.do.not.show"
private const val CSS_PLUGIN_ID = "com.intellij.css"
}
override fun getKey(): Key<EditorNotificationPanel> = KEY
override fun createNotificationPanel(file: VirtualFile, fileEditor: FileEditor, project: Project): EditorNotificationPanel? {
if (project.isUnityProject() && isUssFileSafe(file) && PluginManagerCore.isDisabled(PluginId.getId(CSS_PLUGIN_ID))) {
if (PropertiesComponent.getInstance(project).getBoolean(DO_NOT_SHOW_AGAIN_KEY, false)) {
return null
}
val panel = EditorNotificationPanel()
panel.text(UnityUIBundle.message("uss.disabled.editor.notification.panel.text"))
panel.createActionLabel(UnityUIBundle.message("uss.disabled.editor.notification.enable.css.plugin")) {
// TODO: Maybe in 2020.2 we can do this dynamically without restart?
// That would require enabling the CSS plugin dynamically, and then enabling our PluginCssPart.xml part
// dynamically, too
PluginManagerCore.enablePlugin(PluginId.getId(CSS_PLUGIN_ID))
PluginManagerMain.notifyPluginsUpdated(project)
EditorNotifications.getInstance(project).updateAllNotifications()
}
panel.createActionLabel(UnityUIBundle.message("don.t.show.again")) {
// Project level - do not show again for this project
PropertiesComponent.getInstance(project).setValue(DO_NOT_SHOW_AGAIN_KEY, true)
EditorNotifications.getInstance(project).updateAllNotifications()
}
return panel
}
return null
}
private fun isUssFileSafe(file: VirtualFile): Boolean {
// We can't check for UssFileType because it won't be loaded. The file type is part of the USS language, which
// derives from CSSLanguage, which will be unavailable.
return file.extension.equals("uss", true)
}
} | apache-2.0 | 1bf1cb28de15690cbf7730639b040a4d | 49 | 129 | 0.708467 | 4.760204 | false | false | false | false |
mplatvoet/kovenant | projects/core/src/test/kotlin/tests/api/get.kt | 1 | 4598 | /*
* Copyright (c) 2015 Mark Platvoet<[email protected]>
*
* 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,
* THE SOFTWARE.
*/
package tests.api.get
import nl.komponents.kovenant.*
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.atomic.AtomicReference
import kotlin.test.assertEquals
import kotlin.test.fail
class GetTest {
@Before fun setup() {
Kovenant.testMode {
fail(it.message)
}
}
@Test fun successResult() {
val promise = Promise.of(13)
assertEquals(13, promise.get(), "should return the proper value")
}
@Test fun errorResult() {
val promise = Promise.ofFail<Int, Int>(13)
assertEquals(13, promise.getError(), "should return the proper value")
}
@Test fun nullSuccessResult() {
val promise = Promise.of(null)
assertEquals(null, promise.get(), "should return null")
}
@Test fun nullErrorResult() {
val promise = Promise.ofFail<Int, Int?>(null)
assertEquals(null, promise.getError(), "should return null")
}
@Test fun failResultException() {
val promise = Promise.ofFail<Int, Exception>(Exception("bummer"))
var thrown : Boolean
try {
promise.get()
fail("Should not be reachable")
} catch(e: FailedException) {
fail("Exception should not be wrapped")
} catch(e: Exception) {
thrown = true
}
assert(thrown) { "should throw an exception" }
}
@Test fun failResultValue() {
val promise = Promise.ofFail<Int, String>("bummer")
var thrown : Boolean
try {
promise.get()
fail("Should not be reachable")
} catch(e: FailedException) {
thrown = true
} catch(e: Exception) {
fail("Should be of type FailedException")
}
assert(thrown) { "should throw a FailedException" }
}
}
class GetAsyncTest {
@Before fun setup() {
Kovenant.context {
val dispatcher = buildDispatcher { concurrentTasks = 1 }
callbackContext.dispatcher = dispatcher
workerContext.dispatcher = dispatcher
}
}
@After fun shutdown() {
Kovenant.stop()
}
@Test(timeout = 10000) fun blockingGet() {
val deferred = deferred<Int, Exception>()
verifyBlocking({ deferred.resolve(42) }) {
try {
val i = deferred.promise.get()
assertEquals(42, i, "Should succeed")
} catch(e: Exception) {
fail("Should not fail")
}
}
}
private fun verifyBlocking(trigger: () -> Unit, blockingAction: () -> Unit) {
val startLatch = CountDownLatch(1)
val stopLatch = CountDownLatch(1)
val ref = AtomicReference<Throwable>()
val thread = Thread {
startLatch.countDown()
try {
blockingAction()
} catch (err: Throwable) {
ref.set(err)
} finally {
stopLatch.countDown()
}
}
thread.start()
startLatch.await()
loop@while (true) when (thread.state) {
Thread.State.BLOCKED, Thread.State.WAITING, Thread.State.TIMED_WAITING -> break@loop
Thread.State.TERMINATED -> break@loop
else -> Thread.`yield`()
}
trigger()
stopLatch.await()
val throwable = ref.get()
if (throwable != null) {
throw throwable
}
}
}
| mit | e0353d3f42f16545525e7262d832418a | 29.653333 | 96 | 0.607221 | 4.556987 | false | true | false | false |
7hens/KDroid | upay/src/main/java/cn/thens/kdroid/upay/WeChatPay.kt | 1 | 4243 | package cn.thens.kdroid.upay
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.tencent.mm.opensdk.constants.Build
import com.tencent.mm.opensdk.constants.ConstantsAPI
import com.tencent.mm.opensdk.modelbase.BaseReq
import com.tencent.mm.opensdk.modelbase.BaseResp
import com.tencent.mm.opensdk.modelpay.PayReq
import com.tencent.mm.opensdk.openapi.IWXAPI
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import io.reactivex.Observable
import io.reactivex.ObservableEmitter
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.Serializable
@Suppress("SpellCheckingInspection", "unused")
object WeChatPay : Payment, IWXAPIEventHandler {
private var wxApi: IWXAPI? = null
private var observer: ObservableEmitter<PayResult>? = null
private const val CODE_SUCCESS = 0
private const val CODE_CANCEL = -2
private const val CODE_FAIL = -1
private val gson by lazy { Gson() }
fun initialize(context: Context, appId: String) {
if (wxApi == null) {
val api = WXAPIFactory.createWXAPI(context, appId)
api.registerApp(appId)
wxApi = api
}
}
fun handleIntent(intent: Intent) {
wxApi?.handleIntent(intent, this)
}
override fun pay(activity: Activity, orderInfo: String): Observable<PayResult> {
val api = wxApi
val observable = if (api == null || api.isWXAppInstalled || api.wxAppSupportAPI < Build.PAY_SUPPORTED_SDK_INT) {
Observable.just(PayResult(PayResult.FAIL, "IWXAPI 未初始化"))
} else {
Observable.create<PayResult> {
val order = gson.fromJson(orderInfo, OrderInfo::class.java)
api.sendReq(order.toPayRequest())
observer = it
}
}
return observable
.onErrorReturn { PayResult(PayResult.FAIL, "支付失败: ${it.message}") }
.subscribeOn(Schedulers.io())
.subscribeOn(AndroidSchedulers.mainThread())
}
override fun onResp(resp: BaseResp) {
if (resp.type == ConstantsAPI.COMMAND_PAY_BY_WX) {
val status = resp.errCode
val description = resp.errStr
observer?.onNext(when (status) {
CODE_SUCCESS -> PayResult(PayResult.SUCCESS, "支付成功: $status")
CODE_CANCEL -> PayResult(PayResult.CANCEL, "支付已取消: $status")
CODE_FAIL -> PayResult(PayResult.FAIL, "支付失败: $status,$description")
else -> PayResult(PayResult.FAIL, "支付失败: $status,$description")
})
}
}
override fun onReq(req: BaseReq) {
}
data class OrderInfo(
@SerializedName("appid") val appId: String,
@SerializedName("partnerid") val partnerId: String,
@SerializedName("prepayid") val prepayId: String,
@SerializedName("package") val packageValue: String,
@SerializedName("noncestr") val nonceStr: String,
@SerializedName("timestamp") val timestamp: String,
@SerializedName("sign") val sign: String
) : Serializable {
fun toPayRequest(): PayReq {
return PayReq().also {
it.appId = appId
it.partnerId = partnerId
it.prepayId = prepayId
it.packageValue = packageValue
it.nonceStr = nonceStr
it.timeStamp = timestamp
it.sign = sign
}
}
}
class CallbackActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
handleIntent(intent)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
handleIntent(intent)
}
}
} | apache-2.0 | 63fc0677decad4fa78f1fabef9473779 | 35.419643 | 120 | 0.61566 | 4.451647 | false | false | false | false |
anton-okolelov/intellij-rust | src/test/kotlin/org/rust/ide/annotator/RsTypeCheckTest.kt | 1 | 4188 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import org.rust.ide.inspections.RsExperimentalChecksInspection
import org.rust.ide.inspections.RsInspectionsTestBase
// Typecheck errors are currently shown via disabled by default inspection,
// but should be shown via error annotator when will be complete
class RsTypeCheckTest : RsInspectionsTestBase(RsExperimentalChecksInspection()) {
fun `test type mismatch E0308 primitive`() = checkByText("""
fn main () {
let _: u8 = <error>1u16</error>;
}
""")
fun `test typecheck in constant`() = checkByText("""
const A: u8 = <error>1u16</error>;
""")
fun `test typecheck in array size`() = checkByText("""
const A: [u8; <error>1u8</error>] = [0];
""")
fun `test typecheck in enum variant discriminant`() = checkByText("""
enum Foo { BAR = <error>1u8</error> }
""")
fun `test type mismatch E0308 coerce ptr mutability`() = checkByText("""
fn fn_const(p: *const u8) { }
fn fn_mut(p: *mut u8) { }
fn main () {
let mut ptr_const: *const u8;
let mut ptr_mut: *mut u8;
fn_const(ptr_const);
fn_const(ptr_mut);
fn_mut(<error>ptr_const</error>);
fn_mut(ptr_mut);
ptr_const = ptr_mut;
ptr_mut = <error>ptr_const</error>;
}
""")
fun `test type mismatch E0308 coerce reference to ptr`() = checkByText("""
fn fn_const(p: *const u8) { }
fn fn_mut(p: *mut u8) { }
fn main () {
let const_u8 = &1u8;
let mut_u8 = &mut 1u8;
fn_const(const_u8);
fn_const(mut_u8);
fn_mut(<error>const_u8</error>);
fn_mut(mut_u8);
}
""")
fun `test type mismatch E0308 struct`() = checkByText("""
struct X; struct Y;
fn main () {
let _: X = <error>Y</error>;
}
""")
fun `test type mismatch E0308 tuple`() = checkByText("""
fn main () {
let _: (u8, ) = (<error>1u16</error>, );
}
""")
// TODO error should be more local
fun `test type mismatch E0308 array`() = checkByText("""
fn main () {
let _: [u8; 1] = <error>[1u16]</error>;
}
""")
fun `test type mismatch E0308 array size`() = checkByText("""
fn main () {
let _: [u8; 1] = <error>[1, 2]</error>;
}
""")
fun `test type mismatch E0308 struct field`() = checkByText("""
struct S { f: u8 }
fn main () {
S { f: <error>1u16</error> };
}
""")
fun `test type mismatch E0308 function parameter`() = checkByText("""
fn foo(_: u8) {}
fn main () {
foo(<error>1u16</error>)
}
""")
fun `test type mismatch E0308 unconstrained integer`() = checkByText("""
struct S;
fn main () {
let mut a = 0;
a = <error>S</error>;
}
""")
// issue #1753
fun `test no type mismatch E0308 for multiple impls of the same trait`() = checkByText("""
pub trait From<T> { fn from(_: T) -> Self; }
struct A; struct B; struct C;
impl From<B> for A { fn from(_: B) -> A { unimplemented!() } }
impl From<C> for A { fn from(_: C) -> A { unimplemented!() } }
fn main() {
A::from(C);
}
""")
// issue #1790
fun `test not type mismatch E0308 with unknown size array`() = checkByText("""
struct Foo {
v: [usize; COUNT]
}
fn main() {
let x = Foo { v: [10, 20] };
}
""")
// issue 1753
fun `test no type mismatch E0308 on struct argument reference coercion`() = checkByText("""
#[lang = "deref"]
trait Deref { type Target; }
struct Wrapper<T>(T);
struct RefWrapper<'a, T : 'a>(&'a T);
impl<T> Deref for Wrapper<T> { type Target = T; }
fn foo(w: &Wrapper<u32>) {
let _: RefWrapper<u32> = RefWrapper(w);
}
""")
}
| mit | c67e3282d76ce1d019f1af92931b4416 | 27.297297 | 95 | 0.508596 | 3.814208 | false | true | false | false |
siosio/upsource-kotlin-api | src/test/java/com/github/siosio/upsource/internal/GetProjectInfoCommandTest.kt | 1 | 1770 | package com.github.siosio.upsource.internal
import com.github.siosio.upsource.*
import com.github.siosio.upsource.bean.*
import org.apache.http.*
import org.apache.http.client.methods.*
import org.apache.http.message.*
import org.hamcrest.*
import org.junit.*
import org.junit.Assert.*
import org.mockito.*
internal class GetProjectInfoCommandTest : UpsourceApiTestSupport() {
@Test
fun testGetProjectInfo() {
// -------------------------------------------------- setup
Mockito.`when`(mockResponse.entity).thenReturn(
TestData("testdata/upsourceapi/getProjectInfo_result.json").getStringEntity()
)
// -------------------------------------------------- execute
val sut = UpsourceApi("http://testserver", UpsourceAccount("user", "password"), mockHttpClient)
val project = sut.send(GetProjectInfoCommand("sample-project"))
// -------------------------------------------------- assert
assertThat(httpPost.value.uri.toASCIIString(), CoreMatchers.`is`("http://testserver/~rpc/getProjectInfo"))
assertThat(project, CoreMatchers.`is`(
ProjectInfo(
projectId = "sample-project",
projectName = "サンプルプロジェクト",
headHash = "abc123",
codeReviewIdPattern = "sample-{}",
externalLinks = listOf(
ExternalLink("http://hoge.com", "issue-"),
ExternalLink("http://hoge.com", "hotfix-")
),
issueTrackerConnections = listOf(
ExternalLink("http://hogehoge.com", "hogehoge:")
),
projectModelType = "Gradle",
defaultEffectiveCharset = "utf-8",
defaultBranch = "develop",
isConnectedToGithub = false
)
))
}
}
| mit | 1c55d74f9d00ea7736ad18a4f6e5d819 | 34 | 110 | 0.580571 | 4.847645 | false | true | false | false |
wuan/rest-demo-jersey-kotlin | src/main/java/com/tngtech/demo/weather/repositories/StationDataRepository.kt | 1 | 3287 | package com.tngtech.demo.weather.repositories
import com.tngtech.demo.weather.domain.measurement.AtmosphericData
import com.tngtech.demo.weather.domain.measurement.DataPoint
import com.tngtech.demo.weather.domain.measurement.DataPointType
import com.tngtech.demo.weather.lib.TimestampFactory
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
import java.util.concurrent.ConcurrentHashMap
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
open class StationDataRepository(
private val timestampFactory: TimestampFactory
) {
private val dataPointByType = ConcurrentHashMap<DataPointType, DataPoint>()
private var lastUpdateTime = 0L
open fun update(data: DataPoint) {
val shouldAddData = acceptanceRuleByType
.get(data.type)
?.let { rulePredicate: (DataPoint) -> Boolean -> rulePredicate.invoke(data) }
?: true
if (shouldAddData) {
dataPointByType.put(data.type, data)
lastUpdateTime = timestampFactory.currentTimestamp
}
}
open fun toData(): AtmosphericData {
var data = AtmosphericData(lastUpdateTime = lastUpdateTime)
typesWithBuilderMethods.forEach { dataTypeAndBuilderMethod ->
val dataType = dataTypeAndBuilderMethod.first
val updateAdapter = dataTypeAndBuilderMethod.second
val dataPoint: DataPoint? = dataPointByType[dataType]
if (dataPoint != null) {
data = dataPoint.let { updateAdapter.invoke(data, it) }
}
}
return data
}
companion object {
private val acceptanceRuleByType: Map<DataPointType, (DataPoint) -> Boolean> = mapOf(
Pair(DataPointType.WIND, { dataPoint -> dataPoint.mean >= 0.0 }),
Pair(DataPointType.TEMPERATURE, { dataPoint -> dataPoint.mean >= -50.0 && dataPoint.mean < 100.0 }),
Pair(DataPointType.HUMIDITY, { dataPoint -> dataPoint.mean >= 0.0 && dataPoint.mean < 100.0 }),
Pair(DataPointType.PRESSURE, { dataPoint -> dataPoint.mean >= 650.0 && dataPoint.mean < 800.0 }),
Pair(DataPointType.CLOUDCOVER, { dataPoint -> dataPoint.mean >= 0 && dataPoint.mean < 100.0 }),
Pair(DataPointType.PRECIPITATION, { dataPoint -> dataPoint.mean >= 0 && dataPoint.mean < 100.0 })
)
private val typesWithBuilderMethods = listOf(
Pair(DataPointType.WIND, { data: AtmosphericData, point: DataPoint -> data.copy(wind = point) }),
Pair(DataPointType.TEMPERATURE, { data: AtmosphericData, point: DataPoint -> data.copy(temperature = point) }),
Pair(DataPointType.HUMIDITY, { data: AtmosphericData, point: DataPoint -> data.copy(humidity = point) }),
Pair(DataPointType.PRESSURE, { data: AtmosphericData, point: DataPoint -> data.copy(pressure = point) }),
Pair(DataPointType.CLOUDCOVER, { data: AtmosphericData, point: DataPoint -> data.copy(cloudCover = point) }),
Pair(DataPointType.PRECIPITATION, { data: AtmosphericData, point: DataPoint -> data.copy(precipitation = point) })
)
}
}
| apache-2.0 | 1c30d66fece5640cd8c5637124d0af03 | 45.957143 | 130 | 0.665957 | 4.777616 | false | false | false | false |
ricardoAntolin/AndroidBluetoothDeviceListExample | app/src/main/java/com/ilaps/androidtest/main/BluetoothDeviceListActivity.kt | 1 | 6126 | package com.ilaps.androidtest.main
import android.Manifest
import android.app.Activity
import android.app.Fragment
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.content.pm.PackageManager
import android.os.Bundle
import android.os.PersistableBundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.view.View
import com.google.firebase.auth.FirebaseAuth
import com.ilaps.androidtest.R
import com.ilaps.androidtest.common.BaseActivity
import com.ilaps.androidtest.main.models.BluetoothDeviceModel
import com.ilaps.androidtest.navigation.navigateToFragment
import dagger.android.AndroidInjection
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.activity_main.view.*
import kotlinx.android.synthetic.main.view_progress.*
import org.jetbrains.anko.alert
import org.jetbrains.anko.onClick
class BluetoothDeviceListActivity : BaseActivity() {
val btAdapter:BluetoothAdapter? = BluetoothAdapter.getDefaultAdapter()
lateinit var presenter:BluetoothDeviceListPresenter
val REQUEST_BLUETOOTH = 1234
val REQUEST_BLUETOOTH_PERMISSIONS = 43221
val SAVED_STATE_KEY = "saved state"
val SAVED_FRAGMENT = "saved fragment"
val SAVED_STATE_VALUE = 12345
var savedFragment:BluetoothDeviceListFragment? = null
lateinit var fragment: BluetoothDeviceListFragment
private val bReceiver = object: BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
if (BluetoothDevice.ACTION_FOUND == intent?.action) {
val deviceReceived = intent
.getParcelableExtra<BluetoothDevice>(BluetoothDevice.EXTRA_DEVICE)
val device = BluetoothDeviceModel(deviceReceived.name ?: "NO NAMED", deviceReceived.address)
presenter.sendDevice(device)
progressLayout.visibility = View.GONE
}
if(BluetoothAdapter.ACTION_DISCOVERY_STARTED == intent?.action){
progressLayout.visibility = View.VISIBLE
}
if(BluetoothAdapter.ACTION_DISCOVERY_FINISHED == intent?.action){
progressLayout.visibility = View.GONE
}
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
if(savedInstanceState != null){
savedFragment = fragmentManager
.getFragment(savedInstanceState,SAVED_FRAGMENT) as BluetoothDeviceListFragment?
}
if(SAVED_STATE_VALUE != savedInstanceState?.getInt(SAVED_STATE_KEY)){
checkIfBluetoothPermissionIsNeeded()
checkBluetoothAdapterAvailability()
}
initFragment()
initListener()
}
private fun initListener() {
toolbar.btnScanDevices.onClick {
reloadScan()
startBluetoothScan()
}
}
fun reloadScan(){
presenter.view.clearAllDevices()
}
private fun getFragmentInstance():BluetoothDeviceListFragment{
return savedFragment ?: BluetoothDeviceListFragment.newInstance()
}
private fun initFragment() {
fragment = getFragmentInstance()
presenter = BluetoothDeviceListPresenter(fragment)
navigateToFragment(fragment, R.id.mainContainer, false)
}
private fun checkBluetoothAdapterAvailability() {
if (btAdapter == null) alert {
title(R.string.not_compatible_error)
message(R.string.not_support_bluetooth_error_message)
}else {
enableBluetooth(btAdapter)
}
}
private fun enableBluetooth(btAdapter:BluetoothAdapter){
if(!btAdapter.isEnabled) {
startActivityForResult(Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_BLUETOOTH)
}else startBluetoothScan()
}
private fun initBluetoothBroadcastReceiver() {
registerReceiver(bReceiver, IntentFilter(BluetoothDevice.ACTION_FOUND))
registerReceiver(bReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_STARTED))
registerReceiver(bReceiver, IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED))
}
fun startBluetoothScan(){
initBluetoothBroadcastReceiver()
val started = btAdapter?.startDiscovery()
Log.d("BLUETOOTH", "DISCOVERY is $started")
}
private fun checkIfBluetoothPermissionIsNeeded() {
var rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH)
rc += ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN)
rc += ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
if (rc != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_COARSE_LOCATION),
REQUEST_BLUETOOTH_PERMISSIONS)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if(REQUEST_BLUETOOTH == requestCode && Activity.RESULT_OK == resultCode)
startBluetoothScan()
if(REQUEST_BLUETOOTH_PERMISSIONS == requestCode && Activity.RESULT_OK == resultCode)
startBluetoothScan()
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.putInt(SAVED_STATE_KEY,SAVED_STATE_VALUE)
fragmentManager.putFragment(outState,SAVED_FRAGMENT,fragment)
}
override fun onDestroy() {
super.onDestroy()
try {
unregisterReceiver(bReceiver)
}catch (e: IllegalArgumentException) {
}
}
}
| apache-2.0 | d869902fd546eac7769fe2951e0e7bb4 | 37.2875 | 108 | 0.698661 | 5.209184 | false | false | false | false |
toastkidjp/Yobidashi_kt | article/src/main/java/jp/toastkid/article_viewer/article/list/view/ArticleListUi.kt | 1 | 17640 | /*
* Copyright (c) 2022 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.list.view
import android.app.Activity
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.text.format.DateFormat
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.layout.Box
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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.DropdownMenu
import androidx.compose.material.DropdownMenuItem
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.BlendMode
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.get
import androidx.paging.PagingData
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.items
import coil.compose.AsyncImage
import jp.toastkid.article_viewer.R
import jp.toastkid.article_viewer.article.data.AppDatabase
import jp.toastkid.article_viewer.article.list.ArticleListFragmentViewModel
import jp.toastkid.article_viewer.article.list.ArticleListFragmentViewModelFactory
import jp.toastkid.article_viewer.article.list.SearchResult
import jp.toastkid.article_viewer.article.list.date.DateFilterDialogUi
import jp.toastkid.article_viewer.article.list.menu.ArticleListMenuPopupActionUseCase
import jp.toastkid.article_viewer.article.list.menu.MenuPopupActionUseCase
import jp.toastkid.article_viewer.article.list.sort.SortSettingDialogUi
import jp.toastkid.article_viewer.article.list.usecase.UpdateUseCase
import jp.toastkid.article_viewer.calendar.DateSelectedActionUseCase
import jp.toastkid.article_viewer.zip.ZipFileChooserIntentFactory
import jp.toastkid.article_viewer.zip.ZipLoadProgressBroadcastIntentFactory
import jp.toastkid.lib.ContentViewModel
import jp.toastkid.lib.TabListViewModel
import jp.toastkid.lib.model.OptionMenu
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.lib.view.scroll.usecase.ScrollerUseCase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
@Composable
fun ArticleListUi() {
val context = LocalContext.current as? ComponentActivity ?: return
val dataBase = AppDatabase.find(context)
val articleRepository = dataBase.articleRepository()
val preferenceApplier = PreferenceApplier(context)
val bookmarkRepository = AppDatabase.find(context).bookmarkRepository()
val contentViewModel = ViewModelProvider(context).get(ContentViewModel::class.java)
val viewModel = remember {
ArticleListFragmentViewModelFactory(
articleRepository,
bookmarkRepository,
preferenceApplier
)
.create(ArticleListFragmentViewModel::class.java)
}
val progressBroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(p0: Context?, p1: Intent?) {
viewModel.hideProgress()
showFeedback()
}
private fun showFeedback() {
contentViewModel.snackShort(R.string.message_done_import)
}
}
context.registerReceiver(
progressBroadcastReceiver,
ZipLoadProgressBroadcastIntentFactory.makeProgressBroadcastIntentFilter()
)
contentViewModel.replaceAppBarContent {
AppBarContent(viewModel)
val openSortDialog = remember { mutableStateOf(false) }
if (openSortDialog.value) {
SortSettingDialogUi(preferenceApplier, openSortDialog, onSelect = {
viewModel.sort(it)
})
}
val openDateDialog = remember { mutableStateOf(false) }
if (openDateDialog.value) {
DateFilterDialogUi(
preferenceApplier.colorPair(),
openDateDialog,
DateSelectedActionUseCase(articleRepository, contentViewModel)
)
}
}
val itemFlowState = remember { mutableStateOf<Flow<PagingData<SearchResult>>?>(null) }
viewModel.dataSource.observe(context) {
itemFlowState.value = it.flow
}
val menuPopupUseCase = ArticleListMenuPopupActionUseCase(
articleRepository,
bookmarkRepository,
{
contentViewModel.snackWithAction(
"Deleted: \"${it.title}\".",
"UNDO"
) { CoroutineScope(Dispatchers.IO).launch { articleRepository.insert(it) } }
}
)
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
ArticleListUi(
itemFlowState.value,
rememberLazyListState(),
contentViewModel,
menuPopupUseCase
)
if (viewModel.progressVisibility.value) {
CircularProgressIndicator(color = MaterialTheme.colors.primary)
}
}
LaunchedEffect(key1 = "first_launch", block = {
viewModel.search("")
})
DisposableEffect(key1 = "unregisterReceiver", effect = {
onDispose {
context.unregisterReceiver(progressBroadcastReceiver)
}
})
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun AppBarContent(viewModel: ArticleListFragmentViewModel) {
val activityContext = LocalContext.current as? ComponentActivity ?: return
val preferenceApplier = PreferenceApplier(activityContext)
Row {
Column(Modifier.weight(1f)) {
TextField(
value = viewModel.searchInput.value,
onValueChange = {
viewModel.searchInput.value = it
CoroutineScope(Dispatchers.Default).launch {
//inputChannel.send(it)
}
},
label = {
Text(
stringResource(id = R.string.hint_search_articles),
color = MaterialTheme.colors.onPrimary
)
},
singleLine = true,
keyboardActions = KeyboardActions{
viewModel.search(viewModel.searchInput.value)
},
keyboardOptions = KeyboardOptions(
autoCorrect = true,
imeAction = ImeAction.Search
),
colors = TextFieldDefaults.textFieldColors(
textColor = Color(preferenceApplier.fontColor),
cursorColor = MaterialTheme.colors.onPrimary
),
trailingIcon = {
Icon(
Icons.Filled.Clear,
tint = Color(preferenceApplier.fontColor),
contentDescription = "clear text",
modifier = Modifier
.offset(x = 8.dp)
.clickable {
viewModel.searchInput.value = ""
}
)
},
modifier = Modifier.weight(0.7f)
)
Text(
text = viewModel.searchResult.value,
color = MaterialTheme.colors.onPrimary,
fontSize = 12.sp,
modifier = Modifier
.weight(0.3f)
.padding(start = 16.dp)
)
}
val tabListViewModel = ViewModelProvider(activityContext).get<TabListViewModel>()
Box(
Modifier
.width(40.dp)
.fillMaxHeight()
.combinedClickable(
true,
onClick = {
ViewModelProvider(activityContext)
.get(ContentViewModel::class.java)
.switchTabList()
},
onLongClick = {
tabListViewModel.openNewTabForLongTap()
}
)
) {
Image(
painter = painterResource(id = R.drawable.ic_tab),
contentDescription = stringResource(id = R.string.tab),
colorFilter = ColorFilter.tint(
MaterialTheme.colors.onPrimary,
BlendMode.SrcIn
),
modifier = Modifier.align(Alignment.Center)
)
Text(
text = tabListViewModel.tabCount.value.toString(),
fontSize = 9.sp,
color = MaterialTheme.colors.onPrimary,
modifier = Modifier
.align(Alignment.Center)
.padding(start = 2.dp, bottom = 2.dp)
)
}
}
viewModel.progress.observe(activityContext) {
it?.getContentIfNotHandled()?.let { message ->
viewModel.searchResult.value = message
}
}
viewModel.messageId.observe(activityContext) {
it?.getContentIfNotHandled()?.let { messageId ->
viewModel.searchResult.value = activityContext.getString(messageId)
}
}
val setTargetLauncher =
rememberLauncherForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode != Activity.RESULT_OK) {
return@rememberLauncherForActivityResult
}
UpdateUseCase(viewModel) { activityContext }.invokeIfNeed(it.data?.data)
}
val useTitleFilter = remember { mutableStateOf(preferenceApplier.useTitleFilter()) }
val openSortDialog = remember { mutableStateOf(false) }
val openDateDialog = remember { mutableStateOf(false) }
val contentViewModel = ViewModelProvider(activityContext).get(ContentViewModel::class.java)
LaunchedEffect(key1 = "add_option_menu", block = {
contentViewModel.optionMenus(
OptionMenu(
titleId = R.string.action_all_article,
action = {
viewModel.search("")
}
),
OptionMenu(
titleId = R.string.action_set_target,
action = {
setTargetLauncher.launch(ZipFileChooserIntentFactory()())
}
),
OptionMenu(
titleId = R.string.action_sort,
action = {
openSortDialog.value = true
}
),
OptionMenu(
titleId = R.string.action_date_filter,
action = {
openDateDialog.value = true
}
),
OptionMenu(
titleId = R.string.action_switch_title_filter,
action = {
val newState = !useTitleFilter.value
preferenceApplier.switchUseTitleFilter(newState)
useTitleFilter.value = newState
},
checkState = useTitleFilter
)
)
})
if (openSortDialog.value) {
SortSettingDialogUi(preferenceApplier, openSortDialog, onSelect = {
viewModel.sort(it)
})
}
if (openDateDialog.value) {
DateFilterDialogUi(
preferenceApplier.colorPair(),
openDateDialog,
DateSelectedActionUseCase(AppDatabase.find(activityContext).articleRepository(), contentViewModel)
)
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal fun ArticleListUi(
flow: Flow<PagingData<SearchResult>>?,
listState: LazyListState,
contentViewModel: ContentViewModel?,
menuPopupUseCase: MenuPopupActionUseCase
) {
val articles = flow?.collectAsLazyPagingItems() ?: return
LazyColumn(state = listState) {
items(articles, { it.id }) {
it ?: return@items
ListItem(it, contentViewModel, menuPopupUseCase,
Modifier.animateItemPlacement()
)
}
}
val lifecycleOwner = LocalLifecycleOwner.current
ScrollerUseCase(contentViewModel, listState).invoke(lifecycleOwner)
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun ListItem(
article: SearchResult,
contentViewModel: ContentViewModel?,
menuPopupUseCase: MenuPopupActionUseCase,
modifier: Modifier
) {
var expanded by remember { mutableStateOf(false) }
val items = listOf(
stringResource(id = R.string.action_add_to_bookmark),
stringResource(id = R.string.delete)
)
Surface(
elevation = 4.dp,
modifier = modifier
.padding(start = 8.dp, end = 8.dp, top = 2.dp, bottom = 2.dp)
.combinedClickable(
onClick = { contentViewModel?.newArticle(article.title) },
onLongClick = { contentViewModel?.newArticleOnBackground(article.title) }
)
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.padding(4.dp)
) {
Column(modifier = Modifier.weight(1f)) {
Text(
text = article.title,
fontSize = 16.sp,
overflow = TextOverflow.Ellipsis,
maxLines = 1
)
Text(
text = "Last updated: ${
DateFormat.format(
"yyyy/MM/dd(E) HH:mm:ss",
article.lastModified
)
}" +
" / ${article.length}",
maxLines = 1,
fontSize = 14.sp,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.padding(top = 4.dp)
)
}
Box(
Modifier
.width(32.dp)
.fillMaxHeight()
) {
AsyncImage(
R.drawable.ic_more,
stringResource(id = R.string.menu),
colorFilter = ColorFilter.tint(
MaterialTheme.colors.secondary,
BlendMode.SrcIn
),
modifier = Modifier
.fillMaxSize()
.clickable {
expanded = true
}
)
DropdownMenu(
expanded = expanded,
onDismissRequest = { expanded = false }
) {
items.forEachIndexed { index, s ->
DropdownMenuItem(onClick = {
when (index) {
0 -> menuPopupUseCase.addToBookmark(article.id)
1 -> menuPopupUseCase.delete(article.id)
}
expanded = false
}) { Text(text = s) }
}
}
}
}
}
} | epl-1.0 | 72985a1825c3a982eae1c48cb47fa871 | 35.448347 | 110 | 0.605329 | 5.587583 | false | false | false | false |
chrisbanes/tivi | ui/account/src/main/java/app/tivi/account/AccountUi.kt | 1 | 8216 | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 app.tivi.account
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.sizeIn
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ContentAlpha
import androidx.compose.material.Divider
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.OutlinedButton
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
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.graphics.ColorFilter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import app.tivi.common.compose.theme.foregroundColor
import app.tivi.common.compose.ui.AsyncImage
import app.tivi.data.entities.TraktUser
import app.tivi.trakt.TraktAuthState
import com.google.accompanist.flowlayout.FlowMainAxisAlignment
import com.google.accompanist.flowlayout.FlowRow
import org.threeten.bp.OffsetDateTime
import org.threeten.bp.ZoneOffset
import app.tivi.common.ui.resources.R as UiR
@Composable
fun AccountUi(
openSettings: () -> Unit
) {
AccountUi(
viewModel = hiltViewModel(),
openSettings = openSettings
)
}
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun AccountUi(
viewModel: AccountUiViewModel,
openSettings: () -> Unit
) {
val viewState by viewModel.state.collectAsState()
val loginLauncher = rememberLauncherForActivityResult(
viewModel.buildLoginActivityResult()
) { result ->
if (result != null) {
viewModel.onLoginResult(result)
}
}
AccountUi(
viewState = viewState,
openSettings = openSettings,
login = { loginLauncher.launch(Unit) },
logout = { viewModel.logout() }
)
}
@Composable
internal fun AccountUi(
viewState: AccountUiViewState,
openSettings: () -> Unit,
login: () -> Unit,
logout: () -> Unit
) {
Surface(
shape = MaterialTheme.shapes.medium,
elevation = 2.dp,
// FIXME: Force the dialog to wrap the content. Need to work out why
// this doesn't work automatically
modifier = Modifier.heightIn(min = 200.dp)
) {
Column {
Spacer(modifier = Modifier.height(16.dp))
if (viewState.user != null) {
UserRow(
user = viewState.user,
modifier = Modifier.padding(horizontal = 16.dp)
)
Spacer(modifier = Modifier.height(16.dp))
}
FlowRow(
mainAxisAlignment = FlowMainAxisAlignment.End,
mainAxisSpacing = 8.dp,
crossAxisSpacing = 4.dp,
modifier = Modifier
.padding(horizontal = 16.dp)
.wrapContentSize(Alignment.CenterEnd)
.align(Alignment.End)
) {
if (viewState.authState == TraktAuthState.LOGGED_OUT) {
OutlinedButton(onClick = login) {
Text(text = stringResource(UiR.string.login))
}
} else {
TextButton(onClick = login) {
Text(text = stringResource(UiR.string.refresh_credentials))
}
}
OutlinedButton(onClick = logout) {
Text(text = stringResource(UiR.string.logout))
}
}
Spacer(
modifier = Modifier
.height(16.dp)
.fillMaxWidth()
)
Divider()
AppAction(
label = stringResource(UiR.string.settings_title),
icon = Icons.Default.Settings,
contentDescription = stringResource(UiR.string.settings_title),
onClick = openSettings
)
Spacer(
modifier = Modifier
.height(8.dp)
.fillMaxWidth()
)
}
}
}
@Composable
private fun UserRow(
user: TraktUser,
modifier: Modifier = Modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier.fillMaxWidth()
) {
val avatarUrl = user.avatarUrl
if (avatarUrl != null) {
AsyncImage(
model = avatarUrl,
requestBuilder = { crossfade(true) },
contentDescription = stringResource(UiR.string.cd_profile_pic, user.name ?: user.username),
modifier = Modifier
.size(40.dp)
.clip(RoundedCornerShape(50))
)
}
Spacer(modifier = Modifier.width(8.dp))
Column {
Text(
text = user.name ?: stringResource(UiR.string.account_name_unknown),
style = MaterialTheme.typography.subtitle2
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = user.username,
style = MaterialTheme.typography.caption
)
}
}
}
}
@Composable
private fun AppAction(
label: String,
icon: ImageVector,
contentDescription: String?,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
.fillMaxWidth()
.sizeIn(minHeight = 48.dp)
.clickable(onClick = onClick)
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
Spacer(modifier = Modifier.width(8.dp))
Image(
imageVector = icon,
contentDescription = contentDescription,
colorFilter = ColorFilter.tint(foregroundColor())
)
Spacer(modifier = Modifier.width(16.dp))
Text(
text = label,
style = MaterialTheme.typography.body2
)
}
}
@Preview
@Composable
fun PreviewUserRow() {
UserRow(
TraktUser(
id = 0,
username = "sammendes",
name = "Sam Mendes",
location = "London, UK",
joined = OffsetDateTime.of(2019, 5, 4, 11, 12, 33, 0, ZoneOffset.UTC)
)
)
}
| apache-2.0 | 30885c3580c753ccf16bafc81b77d3f3 | 30.722008 | 107 | 0.634007 | 4.873072 | false | false | false | false |
komu/siilinkari | src/main/kotlin/siilinkari/types/TypeChecker.kt | 1 | 6691 | package siilinkari.types
import siilinkari.ast.Expression
import siilinkari.env.Binding
import siilinkari.env.StaticEnvironment
import siilinkari.env.VariableAlreadyBoundException
import siilinkari.lexer.SourceLocation
import siilinkari.objects.Value
/**
* Type-checker for expressions.
*
* Type-checker walks through the syntax tree, maintaining a [StaticEnvironment] mapping
* identifiers to their types and validates that all types agree. If type-checking
* succeeds, the checker will return a simplified and type checked tree where each
* expression is annotated with [Type]. If the checking fails, it will throw a
* [TypeCheckException].
*/
fun Expression.typeCheck(env: StaticEnvironment): TypedExpression = when (this) {
is Expression.Lit -> TypedExpression.Lit(value, value.type)
is Expression.Ref -> TypedExpression.Ref(env.lookupBinding(name, location))
is Expression.Not -> TypedExpression.Not(exp.typeCheckExpected(Type.Boolean, env))
is Expression.Binary -> typeCheck(env)
is Expression.Call -> typeCheck(env)
is Expression.Assign -> {
val binding = env.lookupBinding(variable, location)
if (!binding.mutable)
throw TypeCheckException("can't assign to immutable variable ${binding.name}", location)
val typedLhs = expression.typeCheckExpected(binding.type, env)
TypedExpression.Assign(binding, typedLhs)
}
is Expression.Var -> {
val typed = expression.typeCheck(env)
val binding = env.bindType(variable, typed.type, location, mutable)
TypedExpression.Var(binding, typed)
}
is Expression.If -> {
val typedCondition = condition.typeCheckExpected(Type.Boolean, env)
val typedConsequent = consequent.typeCheck(env)
val typedAlternative = alternative?.typeCheck(env)
val type = if (typedAlternative != null && typedConsequent.type == typedAlternative.type)
typedConsequent.type
else
Type.Unit
TypedExpression.If(typedCondition, typedConsequent, typedAlternative, type)
}
is Expression.While -> {
val typedCondition = condition.typeCheckExpected(Type.Boolean, env)
val typedBody = body.typeCheck(env)
TypedExpression.While(typedCondition, typedBody)
}
is Expression.ExpressionList -> {
val childEnv = env.newScope()
val expressions = expressions.map { it.typeCheck(childEnv) }
val lastType = expressions.lastOrNull()?.type ?: Type.Unit
TypedExpression.ExpressionList(expressions, lastType)
}
}
private fun Expression.Call.typeCheck(env: StaticEnvironment): TypedExpression {
val typedFunc = func.typeCheck(env)
if (typedFunc.type !is Type.Function)
throw TypeCheckException("expected function type for call, but got ${typedFunc.type}", location)
val expectedArgTypes = typedFunc.type.argumentTypes
if (args.size != expectedArgTypes.size)
throw TypeCheckException("expected ${expectedArgTypes.size} arguments, but got ${args.size}", location)
val typedArgs = args.mapIndexed { i, arg -> arg.typeCheckExpected(expectedArgTypes[i], env) }
return TypedExpression.Call(typedFunc, typedArgs, typedFunc.type.returnType)
}
private fun Expression.Binary.typeCheck(env: StaticEnvironment): TypedExpression = when (this) {
is Expression.Binary.Plus ->
typeCheck(env)
is Expression.Binary.Minus -> {
val typedLhs = lhs.typeCheckExpected(Type.Int, env)
val typedRhs = rhs.typeCheckExpected(Type.Int, env)
TypedExpression.Binary.Minus(typedLhs, typedRhs, Type.Int)
}
is Expression.Binary.Multiply -> {
val typedLhs = lhs.typeCheckExpected(Type.Int, env)
val typedRhs = rhs.typeCheckExpected(Type.Int, env)
TypedExpression.Binary.Multiply(typedLhs, typedRhs, Type.Int)
}
is Expression.Binary.Divide -> {
val typedLhs = lhs.typeCheckExpected(Type.Int, env)
val typedRhs = rhs.typeCheckExpected(Type.Int, env)
TypedExpression.Binary.Divide(typedLhs, typedRhs, Type.Int)
}
is Expression.Binary.And -> {
val typedLhs = lhs.typeCheckExpected(Type.Boolean, env)
val typedRhs = rhs.typeCheckExpected(Type.Boolean, env)
TypedExpression.If(typedLhs, typedRhs, TypedExpression.Lit(Value.Bool.False), Type.Boolean)
}
is Expression.Binary.Or -> {
val typedLhs = lhs.typeCheckExpected(Type.Boolean, env)
val typedRhs = rhs.typeCheckExpected(Type.Boolean, env)
TypedExpression.If(typedLhs, TypedExpression.Lit(Value.Bool.True), typedRhs, Type.Boolean)
}
is Expression.Binary.Relational -> {
val (l, r) = typeCheckMatching(env)
if (!l.type.supports(op))
throw TypeCheckException("operator $op is not supported for type ${l.type}", location)
TypedExpression.Binary.Relational(op, l, r)
}
}
private fun Expression.Binary.Plus.typeCheck(env: StaticEnvironment): TypedExpression {
val typedLhs = lhs.typeCheck(env)
return if (typedLhs.type == Type.String) {
val typedRhs = rhs.typeCheck(env)
TypedExpression.Binary.ConcatString(typedLhs, typedRhs)
} else {
val typedLhs2 = typedLhs.expectAssignableTo(Type.Int, lhs.location)
val typedRhs = rhs.typeCheckExpected(Type.Int, env)
TypedExpression.Binary.Plus(typedLhs2, typedRhs, Type.Int)
}
}
private fun Expression.Binary.typeCheckMatching(env: StaticEnvironment): Pair<TypedExpression, TypedExpression> {
val typedLhs = lhs.typeCheck(env)
val typedRhs = rhs.typeCheck(env)
if (typedLhs.type != typedRhs.type)
throw TypeCheckException("lhs type ${typedLhs.type} did not match rhs type ${typedRhs.type}", location)
return Pair(typedLhs, typedRhs)
}
fun TypedExpression.expectAssignableTo(expectedType: Type, location: SourceLocation): TypedExpression =
if (type == expectedType)
this
else
throw TypeCheckException("expected type $expectedType, but was $type", location)
fun Expression.typeCheckExpected(expectedType: Type, env: StaticEnvironment): TypedExpression =
typeCheck(env).expectAssignableTo(expectedType, location)
private fun StaticEnvironment.lookupBinding(name: String, location: SourceLocation): Binding =
this[name] ?: throw TypeCheckException("unbound variable '$name'", location)
private fun StaticEnvironment.bindType(name: String, type: Type, location: SourceLocation, mutable: Boolean): Binding {
try {
return this.bind(name, type, mutable)
} catch (e: VariableAlreadyBoundException) {
throw TypeCheckException("variable already bound '$name'", location)
}
}
| mit | c8a4ad7302135c234a8b2470af037c82 | 41.617834 | 119 | 0.712001 | 4.5118 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/users/Auth0UserListingService.kt | 1 | 5966 | /*
* Copyright (C) 2020. OpenLattice, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.users
import com.auth0.client.mgmt.ManagementAPI
import com.auth0.json.mgmt.users.User
import com.dataloom.mappers.ObjectMappers
import com.openlattice.users.export.Auth0ApiExtension
import com.openlattice.users.export.JobStatus
import com.openlattice.users.export.UserExportJobRequest
import com.openlattice.users.export.UserExportJobResult
import org.slf4j.LoggerFactory
import java.io.BufferedReader
import java.io.InputStreamReader
import java.time.Instant
import java.util.stream.Collectors
import java.util.zip.GZIPInputStream
private const val DEFAULT_PAGE_SIZE = 100
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
class Auth0UserListingService(
private val managementApi: ManagementAPI, private val auth0ApiExtension: Auth0ApiExtension
) : UserListingService {
companion object {
private val logger = LoggerFactory.getLogger(Auth0UserListingService::class.java)
}
/**
* Retrieves all users from auth0 as a result of an export job.
*/
override fun getAllUsers(): Sequence<User> {
return getUsers(auth0ApiExtension).asSequence()
}
/**
* Calls an export job to download all users from auth0 to a json and parses it to a sequence of users.
*
* Note: This export is used, because the user API has a 1000 user limitation.
* @see <a href="https://auth0.com/docs/users/search/v3/get-users-endpoint#limitations"> Auth0 user endpoint
* limitations </a>
*/
private fun getUsers(auth0ApiExtension: Auth0ApiExtension): List<User> {
val exportEntity = auth0ApiExtension.userExport()
val job = exportEntity.submitExportJob(UserExportJobRequest(AUTH0_USER_FIELDS))
// will fail if export job hangs too long with too many requests error (429 status code)
// https://auth0.com/docs/policies/rate-limits
var exportJobResult = exportEntity.getJob(job.id)
while (exportJobResult.status == JobStatus.PENDING || exportJobResult.status == JobStatus.PROCESSING) {
Thread.sleep(200) // wait before calling again for job status
exportJobResult = exportEntity.getJob(job.id)
}
Thread.sleep(1000) // TODO actually fix
return readUsersFromLocation(exportJobResult)
}
private fun readUsersFromLocation(exportJobResult: UserExportJobResult): List<User> {
val downloadUrl = exportJobResult.location.get()
try {
val mapper = ObjectMappers.getMapper(ObjectMappers.Mapper.valueOf(exportJobResult.format.name.toUpperCase()))
val connection = downloadUrl.openConnection()
connection.setRequestProperty("Accept-Encoding", "gzip")
val input = GZIPInputStream(connection.getInputStream())
val buffered = BufferedReader(InputStreamReader(input, "UTF-8"))
// export json format has a line by line user object format
// if at any point we have too many users, we might have to download the file
return buffered.lines().map { line -> mapper.readValue(line, User::class.java) }.collect(Collectors.toList())
} catch (e: Exception) {
logger.error("Couldn't read list of users from download url $downloadUrl.",e)
throw e
}
}
/**
* Retrieves users from auth0 where the updated_at property is larger than [from] (exclusive) and smaller than
* [to] (inclusive) as a sequence.
*/
override fun getUpdatedUsers(from: Instant, to: Instant): Sequence<User> {
return Auth0UserListingResult(managementApi, from, to).asSequence()
}
}
class Auth0UserListingResult(
private val managementApi: ManagementAPI, private val from: Instant, private val to: Instant
) : Iterable<User> {
override fun iterator(): Iterator<User> {
return Auth0UserListingIterator(managementApi, from, to)
}
}
class Auth0UserListingIterator(
private val managementApi: ManagementAPI, private val from: Instant, private val to: Instant
) : Iterator<User> {
companion object {
private val logger = LoggerFactory.getLogger(Auth0UserListingIterator::class.java)
}
var page = 0
private var pageOfUsers = getNextPage()
private var pageIterator = pageOfUsers.iterator()
override fun hasNext(): Boolean {
if (!pageIterator.hasNext()) {
if (pageOfUsers.size == DEFAULT_PAGE_SIZE) {
pageOfUsers = getNextPage()
pageIterator = pageOfUsers.iterator()
} else {
return false
}
}
return pageIterator.hasNext()
}
override fun next(): User {
return pageIterator.next()
}
private fun getNextPage(): List<User> {
return try {
val nextPage = getUpdatedUsersPage(managementApi, from, to, page++, DEFAULT_PAGE_SIZE).items
?: listOf()
logger.info("Loaded page {} of {} auth0 users", page - 1, nextPage.size)
nextPage
} catch (ex: Exception) {
logger.error("Retrofit called failed during auth0 sync task.", ex)
listOf()
}
}
}
| gpl-3.0 | a486c0a725ba0c6da2defaf4a2bdb1a0 | 36.055901 | 121 | 0.68354 | 4.429102 | false | false | false | false |
dataloom/conductor-client | src/main/java/com/openlattice/edm/EdmDiffService.kt | 1 | 9195 | /*
* Copyright (C) 2018. OpenLattice, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.edm
import com.openlattice.datastore.services.EdmManager
/**
*
* @author Matthew Tamayo-Rios <[email protected]>
*/
class EdmDiffService(private val edm: EdmManager) {
fun diff(otherDataModel: EntityDataModel): EdmDiff {
val currentDataModel = edm.entityDataModel!!
return matchingVersionDiff(currentDataModel, otherDataModel)
}
private fun differentVersionDiff(currentDataModel: EntityDataModel, otherDataModel: EntityDataModel): EdmDiff {
//Since the versions are different we will do our best using FQNs.
val currentPropertyTypes = currentDataModel.propertyTypes.asSequence().map { it.type to it }.toMap()
val currentEntityTypes = currentDataModel.entityTypes.asSequence().map { it.type to it }.toMap()
val currentAssociationTypes = currentDataModel.associationTypes.asSequence().map { it.associationEntityType.type to it }.toMap()
val currentSchemas = currentDataModel.schemas.map { it.fqn to it }.toMap()
val currentNamespaces = currentDataModel.namespaces.toSet()
val presentPropertyTypes = otherDataModel.propertyTypes.filter { currentPropertyTypes.keys.contains(it.type) }
val presentEntityTypes = otherDataModel.entityTypes.filter { currentEntityTypes.keys.contains(it.type) }
val presentAssociationTypes = otherDataModel.associationTypes.filter {
currentAssociationTypes.keys.contains(
it.associationEntityType.type
)
}
val presentSchemas = otherDataModel.schemas.asIterable().filter { currentSchemas.contains(it.fqn) }
val presentNamespaces = otherDataModel.namespaces.minus(currentNamespaces)
val missingPropertyTypes = currentDataModel.propertyTypes.filter { !currentPropertyTypes.contains(it.type) }
val missingEntityTypes = currentDataModel.entityTypes.filter { !currentEntityTypes.contains(it.type) }
val missingAssociationTypes = currentDataModel.associationTypes.filter {
!currentAssociationTypes.contains(
it.associationEntityType.type
)
}
val missingSchemas = currentDataModel.schemas.filter { !currentSchemas.contains(it.fqn) }
val missingNamespaces = currentDataModel.namespaces.minus(currentNamespaces)
val conflictingPropertyTypes = otherDataModel.propertyTypes
.asSequence()
.map { it to currentPropertyTypes[it.type] }
.filter { it.first == it.second }
.map { it.first }
.toSet()
val conflictingEntityTypes = otherDataModel.entityTypes
.asSequence()
.mapNotNull {
it to currentEntityTypes[it.type]
}
.filter { it.second != null && it.first == it.second }
.map { it.first }
.toSet()
val conflictingAssociationTypes = otherDataModel.associationTypes
.asSequence()
.map { it to currentAssociationTypes[it.associationEntityType.type] }
.filter { it.second != null && it.first == it.second }
.map { it.first }
.toSet()
val conflictingSchemas = otherDataModel.schemas.filter {
currentSchemas.containsKey(it.fqn)
&& it.propertyTypes == currentSchemas[it.fqn]?.propertyTypes
&& it.entityTypes == currentSchemas[it.fqn]?.entityTypes
}
//Namespaces cannot conflict.
return EdmDiff(
EntityDataModel(
presentNamespaces,
presentSchemas,
presentEntityTypes,
presentAssociationTypes,
presentPropertyTypes
),
EntityDataModel(
missingNamespaces,
missingSchemas,
missingEntityTypes,
missingAssociationTypes,
missingPropertyTypes
),
EntityDataModel(
listOf(),
conflictingSchemas,
conflictingEntityTypes,
conflictingAssociationTypes,
conflictingPropertyTypes
)
)
}
private fun matchingVersionDiff(currentDataModel: EntityDataModel, otherDataModel: EntityDataModel): EdmDiff {
//Since the versions are same we use ids
val currentPropertyTypes = currentDataModel.propertyTypes.asSequence().map { it.id to it }.toMap()
val currentEntityTypes = currentDataModel.entityTypes.asSequence().map { it.id to it }.toMap()
val currentAssociationTypes = currentDataModel.associationTypes.asSequence().map { it.associationEntityType.id to it }.toMap()
val currentSchemas = currentDataModel.schemas.map { it.fqn to it }.toMap()
val currentNamespaces = currentDataModel.namespaces.toSet()
val presentPropertyTypes = otherDataModel.propertyTypes.filter { currentPropertyTypes.keys.contains(it.id) }
val presentEntityTypes = otherDataModel.entityTypes.filter { currentEntityTypes.keys.contains(it.id) }
val presentAssociationTypes = otherDataModel.associationTypes.filter {
currentAssociationTypes.keys.contains(
it.associationEntityType.id
)
}
val presentSchemas = otherDataModel.schemas.asIterable().filter { currentSchemas.contains(it.fqn) }
val presentNamespaces = otherDataModel.namespaces.minus(currentNamespaces)
val missingPropertyTypes = currentDataModel.propertyTypes.filter { !currentPropertyTypes.contains(it.id) }
val missingEntityTypes = currentDataModel.entityTypes.filter { !currentEntityTypes.contains(it.id) }
val missingAssociationTypes = currentDataModel.associationTypes.filter {
!currentAssociationTypes.contains(
it.associationEntityType.id
)
}
val missingSchemas = currentDataModel.schemas.filter { !currentSchemas.contains(it.fqn) }
val missingNamespaces = currentDataModel.namespaces.minus(currentNamespaces)
val conflictingPropertyTypes = otherDataModel.propertyTypes
.asSequence()
.map { it to currentPropertyTypes[it.id] }
.filter { it.first == it.second }
.map { it.first }
.toSet()
val conflictingEntityTypes = otherDataModel.entityTypes
.asSequence()
.mapNotNull {
it to currentEntityTypes[it.id]
}
.filter { it.second != null && it.first == it.second }
.map { it.first }
.toSet()
val conflictingAssociationTypes = otherDataModel.associationTypes
.asSequence()
.map { it to currentAssociationTypes[it.associationEntityType.id] }
.filter { it.second != null && it.first == it.second }
.map { it.first }
.toSet()
val conflictingSchemas = otherDataModel.schemas.filter {
currentSchemas.containsKey(it.fqn)
&& it.propertyTypes == currentSchemas[it.fqn]?.propertyTypes
&& it.entityTypes == currentSchemas[it.fqn]?.entityTypes
}
//Namespaces cannot conflict.
return EdmDiff(
EntityDataModel(
presentNamespaces,
presentSchemas,
presentEntityTypes,
presentAssociationTypes,
presentPropertyTypes
),
EntityDataModel(
missingNamespaces,
missingSchemas,
missingEntityTypes,
missingAssociationTypes,
missingPropertyTypes
),
EntityDataModel(
listOf(),
conflictingSchemas,
conflictingEntityTypes,
conflictingAssociationTypes,
conflictingPropertyTypes
)
)
}
} | gpl-3.0 | 1a881491078ae02000c19292ebaae4ec | 45.918367 | 136 | 0.611202 | 5.928433 | false | false | false | false |
http4k/http4k | http4k-template/dust/src/main/kotlin/org/http4k/template/dust/Dust.kt | 1 | 4656 | package org.http4k.template.dust
import jdk.nashorn.api.scripting.JSObject
import org.apache.commons.pool2.BasePooledObjectFactory
import org.apache.commons.pool2.impl.DefaultPooledObject
import org.apache.commons.pool2.impl.GenericObjectPool
import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import java.io.StringWriter
import java.net.URL
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.SimpleBindings
typealias TemplateLoader = (templateName: String) -> String?
interface TemplateExpansion {
fun expandTemplate(
templateName: String,
params: Any,
onMissingTemplate: (templateName: String) -> Nothing = ::missingTemplateIllegalArgument
): String
}
interface TemplateExpansionService : AutoCloseable, TemplateExpansion
private object TEMPLATE_NOT_FOUND
private fun missingTemplateIllegalArgument(templateName: String): Nothing = throw IllegalArgumentException("template $templateName not found")
private fun ScriptEngine.eval(srcUrl: URL) {
eval(srcUrl.readText())
}
// Must only be used on one thread.
private class SingleThreadedDust(
private val js: ScriptEngine,
private val cacheTemplates: Boolean = true,
private val dustPluginScripts: List<URL>,
private val notifyOnClosed: (SingleThreadedDust) -> Unit
) : TemplateExpansionService {
private val dust: JSObject = run {
js.eval(javaClass.getResource("dust-full-2.7.5.js"))
dustPluginScripts.forEach(js::eval)
js.eval(
//language=JavaScript
"""
// This lets Dust iterate over Java collections.
dust.isArray = function(o) {
return Array.isArray(o) || o instanceof java.util.List;
};
dust.config.cache = $cacheTemplates;
dust.onLoad = function(templateName, callback) {
var template = loader.invoke(templateName);
if (template === null) {
callback(TEMPLATE_NOT_FOUND, null)
} else {
callback(null, template);
}
}
""")
js["dust"] as? JSObject ?: throw IllegalStateException("could not initialise Dust")
}
override fun close() {
notifyOnClosed(this)
}
override fun expandTemplate(
templateName: String,
params: Any,
onMissingTemplate: (templateName: String) -> Nothing
): String {
val writer = StringWriter()
var error: Any? = null
val bindings = SimpleBindings(mapOf(
"dust" to dust,
"templateName" to templateName,
"templateParams" to params,
"writer" to writer,
"reportError" to { e: Any -> error = e }
))
js.eval(
//language=JavaScript
"""
dust.render(templateName, templateParams, function(err, result) {
if (err) {
reportError.invoke(err);
} else {
writer.write(result, 0, result.length);
}
});
""", bindings)
return when (error) {
null -> writer.toString()
TEMPLATE_NOT_FOUND -> onMissingTemplate(templateName)
else -> throw IllegalStateException(error.toString())
}
}
}
class Dust(
private val cacheTemplates: Boolean,
private val precachePoolSize: Int,
private val dustPluginScripts: List<URL>,
loader: TemplateLoader
) {
private val scriptEngineManager = ScriptEngineManager().apply {
bindings = SimpleBindings(mapOf(
"loader" to loader,
"TEMPLATE_NOT_FOUND" to TEMPLATE_NOT_FOUND))
}
private val pool = GenericObjectPool(
object : BasePooledObjectFactory<SingleThreadedDust>() {
override fun create(): SingleThreadedDust = SingleThreadedDust(
js = scriptEngineManager.getEngineByName("nashorn"),
cacheTemplates = cacheTemplates,
dustPluginScripts = dustPluginScripts,
notifyOnClosed = { returnDustEngine(it) })
override fun wrap(obj: SingleThreadedDust) = DefaultPooledObject(obj)
},
GenericObjectPoolConfig<SingleThreadedDust>().apply {
minIdle = precachePoolSize
})
private fun returnDustEngine(dustEngine: SingleThreadedDust) {
pool.returnObject(dustEngine)
}
fun openTemplates(): TemplateExpansionService = pool.borrowObject()
inline fun <T> withTemplates(block: (TemplateExpansion) -> T): T = openTemplates().use(block)
}
| apache-2.0 | 0792278c59c22c3aa67c31cbc6eaa1c6 | 32.257143 | 142 | 0.631873 | 4.865204 | false | false | false | false |
pacien/tincapp | app/src/main/java/org/pacien/tincapp/commands/TincApp.kt | 1 | 3182 | /*
* Tinc App, an Android binding and user interface for the tinc mesh VPN daemon
* Copyright (C) 2017-2020 Pacien TRAN-GIRARD
*
* 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 <https://www.gnu.org/licenses/>.
*/
package org.pacien.tincapp.commands
import org.pacien.tincapp.R
import org.pacien.tincapp.commands.Executor.runAsyncTask
import org.pacien.tincapp.context.App
import org.pacien.tincapp.context.AppPaths
import org.pacien.tincapp.data.TincConfiguration
import org.pacien.tincapp.data.VpnInterfaceConfiguration
import org.pacien.tincapp.utils.PemUtils
import java.io.FileNotFoundException
/**
* @author pacien
*/
object TincApp {
private val SCRIPT_SUFFIXES = listOf("-up", "-down", "-created", "-accepted")
private val STATIC_SCRIPTS = listOf("tinc", "host", "subnet", "invitation").flatMap { s -> SCRIPT_SUFFIXES.map { s + it } }
private fun listScripts(netName: String) =
AppPaths.confDir(netName).listFiles { f -> f.name in STATIC_SCRIPTS }!! +
AppPaths.hostsDir(netName).listFiles { f -> SCRIPT_SUFFIXES.any { f.name.endsWith(it) } }!!
fun listPrivateKeys(netName: String) = try {
TincConfiguration.fromTincConfiguration(AppPaths.existing(AppPaths.tincConfFile(netName))).let {
listOf(
it.privateKeyFile ?: AppPaths.defaultRsaPrivateKeyFile(netName),
it.ed25519PrivateKeyFile ?: AppPaths.defaultEd25519PrivateKeyFile(netName))
}
} catch (e: FileNotFoundException) {
throw FileNotFoundException(App.getResources().getString(R.string.notification_error_message_network_config_not_found_format, e.message!!))
}
fun removeScripts(netName: String) = runAsyncTask {
listScripts(netName).forEach { it.delete() }
}
fun generateIfaceCfg(netName: String) = runAsyncTask {
VpnInterfaceConfiguration
.fromInvitation(AppPaths.invitationFile(netName))
.write(AppPaths.netConfFile(netName))
}
fun generateIfaceCfgTemplate(netName: String) = runAsyncTask {
App.getResources().openRawResource(R.raw.network).use { inputStream ->
AppPaths.netConfFile(netName).outputStream().use { inputStream.copyTo(it) }
}
}
fun setPassphrase(netName: String, currentPassphrase: String? = null, newPassphrase: String?) = runAsyncTask {
listPrivateKeys(netName)
.filter { it.exists() }
.map { Pair(PemUtils.read(it), it) }
.map { Pair(PemUtils.decrypt(it.first, currentPassphrase), it.second) }
.map { Pair(if (newPassphrase?.isNotEmpty() == true) PemUtils.encrypt(it.first, newPassphrase) else it.first, it.second) }
.forEach { PemUtils.write(it.first, it.second.writer()) }
}
}
| gpl-3.0 | f22204abb04ffeeaff7223645812b9f8 | 41.426667 | 143 | 0.73193 | 3.918719 | false | true | false | false |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/oneway/AddOneway.kt | 1 | 5071 | package de.westnordost.streetcomplete.quests.oneway
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.ALL_ROADS
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.mapdata.Way
import de.westnordost.streetcomplete.quests.cycleway.createCyclewaySides
import de.westnordost.streetcomplete.quests.cycleway.estimatedWidth
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CAR
import de.westnordost.streetcomplete.quests.oneway.OnewayAnswer.*
import de.westnordost.streetcomplete.quests.parking_lanes.*
class AddOneway : OsmElementQuestType<OnewayAnswer> {
/** find all roads */
private val allRoadsFilter by lazy { """
ways with highway ~ ${ALL_ROADS.joinToString("|")} and area != yes
""".toElementFilterExpression() }
/** find only those roads eligible for asking for oneway */
private val elementFilter by lazy { """
ways with highway ~ living_street|residential|service|tertiary|unclassified
and !oneway and area != yes and junction != roundabout
and (access !~ private|no or (foot and foot !~ private|no))
and lanes <= 1 and width
""".toElementFilterExpression() }
override val commitMessage = "Add whether this road is a one-way road because it is quite slim"
override val wikiLink = "Key:oneway"
override val icon = R.drawable.ic_quest_oneway
override val hasMarkersAtEnds = true
override val isSplitWayEnabled = true
override val questTypeAchievements = listOf(CAR)
override fun getTitle(tags: Map<String, String>) = R.string.quest_oneway2_title
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> {
val allRoads = mapData.ways.filter { allRoadsFilter.matches(it) && it.nodeIds.size >= 2 }
val connectionCountByNodeIds = mutableMapOf<Long, Int>()
val onewayCandidates = mutableListOf<Way>()
for (road in allRoads) {
for (nodeId in road.nodeIds) {
val prevCount = connectionCountByNodeIds[nodeId] ?: 0
connectionCountByNodeIds[nodeId] = prevCount + 1
}
if (isOnewayRoadCandidate(road)) {
onewayCandidates.add(road)
}
}
return onewayCandidates.filter {
/* ways that are simply at the border of the download bounding box are treated as if
they are dead ends. This is fine though, because it only leads to this quest not
showing up for those streets (which is better than the other way round)
*/
// check if the way has connections to other roads at both ends
(connectionCountByNodeIds[it.nodeIds.first()] ?: 0) > 1 &&
(connectionCountByNodeIds[it.nodeIds.last()] ?: 0) > 1
}
}
override fun isApplicableTo(element: Element): Boolean? {
if (!isOnewayRoadCandidate(element)) return false
/* return null because oneway candidate roads must also be connected on both ends with other
roads for which we'd need to look at surrounding geometry */
return null
}
private fun isOnewayRoadCandidate(road: Element): Boolean {
if (!elementFilter.matches(road)) return false
// check if the width of the road minus the space consumed by other stuff is quite narrow
val width = road.tags["width"]?.toFloatOrNull()
val isNarrow = width != null && width <= estimatedWidthConsumedByOtherThings(road.tags) + 4f
return isNarrow
}
private fun estimatedWidthConsumedByOtherThings(tags: Map<String, String>): Float {
return estimateWidthConsumedByParkingLanes(tags) +
estimateWidthConsumedByCycleLanes(tags)
}
private fun estimateWidthConsumedByParkingLanes(tags: Map<String, String>): Float {
val sides = createParkingLaneSides(tags) ?: return 0f
return (sides.left?.estimatedWidthOnRoad ?: 0f) + (sides.right?.estimatedWidthOnRoad ?: 0f)
}
private fun estimateWidthConsumedByCycleLanes(tags: Map<String, String>): Float {
/* left or right hand traffic is irrelevant here because we don't make a difference between
left and right side */
val sides = createCyclewaySides(tags, false) ?: return 0f
return (sides.left?.estimatedWidth ?: 0f) + (sides.right?.estimatedWidth ?: 0f)
}
override fun createForm() = AddOnewayForm()
override fun applyAnswerTo(answer: OnewayAnswer, changes: StringMapChangesBuilder) {
changes.add("oneway", when(answer) {
FORWARD -> "yes"
BACKWARD -> "-1"
NO_ONEWAY -> "no"
})
}
}
| gpl-3.0 | 1b2c4bd62c288759b7f704cf057bdbb4 | 45.522936 | 100 | 0.695918 | 4.779453 | false | false | false | false |
jamieadkins95/Roach | database/src/main/java/com/jamieadkins/gwent/database/entity/DeckCardEntity.kt | 1 | 893 | package com.jamieadkins.gwent.database.entity
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.jamieadkins.gwent.database.GwentDatabase
@Entity(foreignKeys = [
(ForeignKey(entity = CardEntity::class,
onDelete = ForeignKey.NO_ACTION,
parentColumns = arrayOf("id"),
childColumns = arrayOf("cardId"))),
(ForeignKey(entity = DeckEntity::class,
onDelete = ForeignKey.CASCADE,
parentColumns = arrayOf("id"),
childColumns = arrayOf("deckId")))],
tableName = GwentDatabase.DECK_CARD_TABLE,
indices = [Index(value = ["cardId"]), Index(value = ["deckId"])],
primaryKeys = ["deckId", "cardId"])
data class DeckCardEntity(
val deckId: String,
val cardId: String,
val count: Int = 0) | apache-2.0 | 49a89f507cf937d5df10084c85b2aaad | 36.25 | 73 | 0.643897 | 4.651042 | false | false | false | false |
gpolitis/jitsi-videobridge | jvb/src/test/kotlin/org/jitsi/videobridge/websocket/config/WebsocketServiceConfigTest.kt | 1 | 3078 | /*
* Copyright @ 2018 - present 8x8, 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 org.jitsi.videobridge.websocket.config
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.test.TestCase
import io.kotest.matchers.shouldBe
import org.jitsi.ConfigTest
import org.jitsi.metaconfig.ConfigException
class WebsocketServiceConfigTest : ConfigTest() {
private lateinit var config: WebsocketServiceConfig
override fun beforeTest(testCase: TestCase) {
super.beforeTest(testCase)
config = WebsocketServiceConfig()
}
init {
context("when websockets are disabled") {
withNewConfig("videobridge.websockets.enabled = false") {
context("accessing domain should throw") {
shouldThrow<ConfigException.UnableToRetrieve.ConditionNotMet> {
config.domain
}
}
context("accessing useTls should throw") {
shouldThrow<ConfigException.UnableToRetrieve.ConditionNotMet> {
config.useTls
}
}
}
}
context("when websockets are enabled") {
context("accessing domain") {
withNewConfig(newConfigWebsocketsEnabledDomain) {
should("get the right value") {
config.domain shouldBe "new_domain"
}
}
}
context("accessing useTls") {
context("when no value has been set") {
withNewConfig(newConfigWebsocketsEnabled) {
should("return null") {
config.useTls shouldBe null
}
}
}
context("when a value has been set") {
withNewConfig(newConfigWebsocketsEnableduseTls) {
should("get the right value") {
config.useTls shouldBe true
}
}
}
}
}
}
}
private val newConfigWebsocketsEnabled = """
videobridge.websockets.enabled = true
""".trimIndent()
private val newConfigWebsocketsEnabledDomain = newConfigWebsocketsEnabled + "\n" + """
videobridge.websockets.domain = "new_domain"
""".trimIndent()
private val newConfigWebsocketsEnableduseTls = newConfigWebsocketsEnabled + "\n" + """
videobridge.websockets.tls = true
""".trimIndent()
| apache-2.0 | ece7277ebaa6ec82fda8c48ec30b0c8b | 35.211765 | 86 | 0.587394 | 5.526032 | false | true | false | false |
didi/DoraemonKit | Android/dokit/src/main/java/com/didichuxing/doraemonkit/kit/core/DoKitManager.kt | 1 | 6066 | package com.didichuxing.doraemonkit.kit.core
import com.didichuxing.doraemonkit.BuildConfig
import com.didichuxing.doraemonkit.DoKitCallBack
import com.didichuxing.doraemonkit.config.GlobalConfig
import com.didichuxing.doraemonkit.constant.DoKitModule
import com.didichuxing.doraemonkit.kit.network.bean.WhiteHostBean
import com.didichuxing.doraemonkit.kit.network.room_db.DokitDbManager
import com.didichuxing.doraemonkit.kit.toolpanel.KitWrapItem
import com.didichuxing.doraemonkit.util.LogHelper
import com.didichuxing.doraemonkit.util.NetworkUtils
import com.didichuxing.doraemonkit.util.PathUtils
import java.io.File
import java.util.*
import kotlin.collections.LinkedHashMap
/**
* ================================================
* 作 者:jint(金台)
* 版 本:1.0
* 创建日期:2019-12-19-10:21
* 描 述:
* 修订历史:
* ================================================
*/
object DoKitManager {
const val TAG = "DoKitConstant"
const val GROUP_ID_PLATFORM = "dk_category_platform"
const val GROUP_ID_COMM = "dk_category_comms"
const val GROUP_ID_WEEX = "dk_category_weex"
const val GROUP_ID_PERFORMANCE = "dk_category_performance"
const val GROUP_ID_UI = "dk_category_ui"
const val GROUP_ID_LBS = "dk_category_lbs"
/**
* DoKit 模块能力
*/
private val mDokitModuleAbilityMap: MutableMap<DoKitModule, DokitAbility.DokitModuleProcessor> by lazy {
val doKitAbilities =
ServiceLoader.load(DokitAbility::class.java, javaClass.classLoader).toList()
val abilityMap = mutableMapOf<DoKitModule, DokitAbility.DokitModuleProcessor>()
doKitAbilities.forEach {
it.init()
abilityMap[it.moduleName()] = it.getModuleProcessor()
}
abilityMap
}
/**
* 获取ModuleProcessor
*/
fun getModuleProcessor(module: DoKitModule): DokitAbility.DokitModuleProcessor? {
if (mDokitModuleAbilityMap[module] == null) {
return null
}
return mDokitModuleAbilityMap[module]
}
val SYSTEM_KITS_BAK_PATH: String by lazy {
"${PathUtils.getInternalAppFilesPath()}${File.separator}system_kit_bak_${BuildConfig.DOKIT_VERSION}.json"
}
/**
* 工具面板RV上次的位置
*/
var TOOL_PANEL_RV_LAST_DY = 0
/**
* 全局的Kits
*/
@JvmField
val GLOBAL_KITS: LinkedHashMap<String, MutableList<KitWrapItem>> = LinkedHashMap()
/**
* 全局系统内置kit
*/
@JvmField
val GLOBAL_SYSTEM_KITS: LinkedHashMap<String, MutableList<KitWrapItem>> = LinkedHashMap()
/**
* 加密数据库账号密码配置
*/
var DATABASE_PASS = mapOf<String, String>()
/**
* 平台端文件管理端口号
*/
var FILE_MANAGER_HTTP_PORT = 8089
/**
* 一机多控长连接端口号
*/
var MC_WS_PORT = 4444
/**
* 产品id
*/
@JvmField
var PRODUCT_ID = ""
/**
* 是否处于健康体检中
*/
@JvmField
var APP_HEALTH_RUNNING = GlobalConfig.getAppHealth()
/**
* 是否是普通的浮标模式
*/
@JvmField
var IS_NORMAL_FLOAT_MODE = true
/**
* 是否显示icon主入口
*/
@JvmField
var ALWAYS_SHOW_MAIN_ICON = true
/**
* icon主入口是否处于显示状态
*/
@JvmField
var MAIN_ICON_HAS_SHOW = false
/**
* 流量监控白名单
*/
@JvmField
var WHITE_HOSTS = mutableListOf<WhiteHostBean>()
/**
* h5 js 注入代码开关
*/
@JvmField
var H5_JS_INJECT = false
/**
* h5 vConsole 注入代码开关
*/
@JvmField
var H5_VCONSOLE_INJECT = false
/**
* h5 dokit for web 注入代码开关
*/
@JvmField
var H5_DOKIT_MC_INJECT = false
@JvmField
var H5_MC_JS_INJECT_MODE = "file"
@JvmField
var H5_MC_JS_INJECT_URL = "http://120.55.183.20/dokit/mc/dokit.js"
/**
* 是否允许上传统计信息
*/
var ENABLE_UPLOAD = true
val ACTIVITY_LIFECYCLE_INFOS: MutableMap<String, ActivityLifecycleStatusInfo?> by lazy {
mutableMapOf<String, ActivityLifecycleStatusInfo?>()
}
/**
* 一机多控从机自定义处理器
*/
var MC_CLIENT_PROCESSOR: McClientProcessor? = null
/**
* 全局回调
*/
var CALLBACK: DoKitCallBack? = null
/**
* 一机多控地址
*/
@JvmField
var MC_CONNECT_URL: String = ""
/**
* Wifi IP 地址
*/
val IP_ADDRESS_BY_WIFI: String
get() {
return try {
NetworkUtils.getIpAddressByWifi()
} catch (e: Exception) {
LogHelper.e(TAG, "get wifi address error===>${e.message}")
"0.0.0.0"
}
}
/**
* 判断接入的是否是滴滴内部的rpc sdk
*
* @return
*/
@JvmStatic
val isRpcSDK: Boolean
get() {
return try {
Class.forName("com.didichuxing.doraemonkit.DoraemonKitRpc")
true
} catch (e: ClassNotFoundException) {
false
}
}
/**
* 兼容滴滴内部外网映射环境 该环境的 path上会多一级/kop_xxx/路径
*
* @param oldPath
* @param fromSDK
* @return
*/
@JvmStatic
fun dealDidiPlatformPath(oldPath: String, fromSDK: Int): String {
if (fromSDK == DokitDbManager.FROM_SDK_OTHER) {
return oldPath
}
var newPath = oldPath
//包含多级路径
if (oldPath.contains("/kop") && oldPath.split("\\/").toTypedArray().size > 1) {
//比如/kop_stable/a/b/gateway 分解以后为 "" "kop_stable" "a" "b" "gateway"
val childPaths = oldPath.split("\\/").toTypedArray()
val firstPath = childPaths[1]
if (firstPath.contains("kop")) {
newPath = oldPath.replace("/$firstPath", "")
}
}
return newPath
}
}
| apache-2.0 | a8e2b86ae4b1c2110fae16b8f46f38d9 | 22.596639 | 113 | 0.580484 | 3.756522 | false | false | false | false |
robertwb/incubator-beam | examples/kotlin/src/test/java/org/apache/beam/examples/kotlin/cookbook/DistinctExampleTest.kt | 8 | 2250 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.examples.kotlin.cookbook
import org.apache.beam.sdk.coders.StringUtf8Coder
import org.apache.beam.sdk.testing.PAssert
import org.apache.beam.sdk.testing.TestPipeline
import org.apache.beam.sdk.testing.ValidatesRunner
import org.apache.beam.sdk.transforms.Create
import org.apache.beam.sdk.transforms.Distinct
import org.junit.Rule
import org.junit.Test
import org.junit.experimental.categories.Category
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/** Unit tests for [Distinct]. */
@RunWith(JUnit4::class)
class DistinctExampleTest {
private val pipeline: TestPipeline = TestPipeline.create()
@Rule
fun pipeline(): TestPipeline = pipeline
@Test
@Category(ValidatesRunner::class)
fun testDistinct() {
val strings = listOf("k1", "k5", "k5", "k2", "k1", "k2", "k3")
val input = pipeline.apply(Create.of(strings).withCoder(StringUtf8Coder.of()))
val output = input.apply(Distinct.create())
PAssert.that(output).containsInAnyOrder("k1", "k5", "k2", "k3")
pipeline.run().waitUntilFinish()
}
@Test
@Category(ValidatesRunner::class)
fun testDistinctEmpty() {
val strings = listOf<String>()
val input = pipeline.apply(Create.of(strings).withCoder(StringUtf8Coder.of()))
val output = input.apply(Distinct.create())
PAssert.that(output).empty()
pipeline.run().waitUntilFinish()
}
} | apache-2.0 | 4c6e7e694196df12da8830fb08e4b462 | 36.516667 | 86 | 0.723556 | 3.947368 | false | true | false | false |
michaelgallacher/intellij-community | platform/configuration-store-impl/testSrc/MockStreamProvider.kt | 3 | 1527 | package com.intellij.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.util.io.*
import java.io.InputStream
import java.nio.file.NoSuchFileException
import java.nio.file.Path
class MockStreamProvider(private val dir: Path) : StreamProvider {
override fun write(fileSpec: String, content: ByteArray, size: Int, roamingType: RoamingType) {
dir.resolve(fileSpec).write(content, 0, size)
}
override fun read(fileSpec: String, roamingType: RoamingType): InputStream? {
val file = dir.resolve(fileSpec)
try {
return file.inputStream()
}
catch (e: NoSuchFileException) {
return null
}
}
override fun processChildren(path: String, roamingType: RoamingType, filter: (name: String) -> Boolean, processor: (name: String, input: InputStream, readOnly: Boolean) -> Boolean) {
dir.resolve(path).directoryStreamIfExists({ filter(it.fileName.toString()) }) {
for (file in it) {
val attributes = file.basicAttributesIfExists()
if (attributes == null || attributes.isDirectory || file.isHidden()) {
continue
}
// we ignore empty files as well - delete if corrupted
if (attributes.size() == 0L) {
file.delete()
continue
}
if (!file.inputStream().use { processor(file.fileName.toString(), it, false) }) {
break
}
}
}
}
override fun delete(fileSpec: String, roamingType: RoamingType) {
dir.resolve(fileSpec).delete()
}
}
| apache-2.0 | cd36ace072130df99d63acf91588db8e | 30.8125 | 184 | 0.665357 | 4.375358 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-delivery-metrics/src/main/java/net/nemerosa/ontrack/extension/dm/export/PromotionLevelLeadTimeMetrics.kt | 1 | 1405 | package net.nemerosa.ontrack.extension.dm.export
import net.nemerosa.ontrack.extension.dm.model.EndToEndPromotionRecord
import net.nemerosa.ontrack.model.metrics.Metric
import org.springframework.stereotype.Component
import java.time.Duration
@Component
class PromotionLevelLeadTimeMetrics : PromotionMetricsCollector {
override fun createWorker() = object : PromotionMetricsWorker {
override fun process(record: EndToEndPromotionRecord, recorder: (Metric) -> Unit) {
val refPromotionCreation = record.ref.promotionCreation
val targetPromotionCreation = record.target.promotionCreation
if (record.ref.promotion != null && refPromotionCreation != null && targetPromotionCreation != null) {
val maxPromotionTime = maxOf(refPromotionCreation, targetPromotionCreation)
val time = Duration.between(record.ref.buildCreation, maxPromotionTime)
val value = time.toSeconds().toDouble()
recorder(
Metric(
metric = EndToEndPromotionMetrics.PROMOTION_LEAD_TIME,
tags = EndToEndPromotionMetrics.endToEndMetricTags(record, record.ref.promotion),
fields = mapOf("value" to value),
timestamp = record.ref.buildCreation
)
)
}
}
}
} | mit | f722d64cbb93c1b4be87ee0e66c99a60 | 45.866667 | 114 | 0.651957 | 5.403846 | false | false | false | false |
d9n/intellij-rust | src/main/kotlin/org/rust/cargo/runconfig/test/CargoTestRunConfigurationProducer.kt | 1 | 3670 | package org.rust.cargo.runconfig.test
import com.intellij.execution.Location
import com.intellij.execution.actions.ConfigurationContext
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.openapi.util.Ref
import com.intellij.psi.PsiElement
import org.rust.cargo.CargoConstants
import org.rust.cargo.project.workspace.CargoWorkspace
import org.rust.cargo.runconfig.cargoArgumentSpeck
import org.rust.cargo.runconfig.command.CargoCommandConfiguration
import org.rust.cargo.runconfig.command.CargoCommandConfigurationType
import org.rust.cargo.runconfig.mergeWithDefault
import org.rust.cargo.toolchain.CargoCommandLine
import org.rust.lang.core.psi.ext.RsCompositeElement
import org.rust.lang.core.psi.RsFunction
import org.rust.lang.core.psi.ext.RsMod
import org.rust.lang.core.psi.ext.containingCargoTarget
import org.rust.lang.core.psi.ext.isTest
import org.rust.lang.core.psi.ext.parentOfType
class CargoTestRunConfigurationProducer : RunConfigurationProducer<CargoCommandConfiguration>(CargoCommandConfigurationType()) {
override fun isConfigurationFromContext(
configuration: CargoCommandConfiguration,
context: ConfigurationContext
): Boolean {
val location = context.location ?: return false
val test = findTest(location) ?: return false
return configuration.configurationModule.module == context.module &&
configuration.cargoCommandLine == test.cargoCommandLine
}
override fun setupConfigurationFromContext(
configuration: CargoCommandConfiguration,
context: ConfigurationContext,
sourceElement: Ref<PsiElement>
): Boolean {
val location = context.location ?: return false
val test = findTest(location) ?: return false
sourceElement.set(test.sourceElement)
configuration.configurationModule.module = context.module
configuration.name = test.configurationName
configuration.cargoCommandLine = test.cargoCommandLine.mergeWithDefault(configuration.cargoCommandLine)
return true
}
private class TestConfig(
val sourceElement: RsCompositeElement,
val configurationName: String,
testPath: String,
target: CargoWorkspace.Target
) {
val cargoCommandLine: CargoCommandLine = CargoCommandLine(
CargoConstants.Commands.TEST,
target.cargoArgumentSpeck + testPath
)
}
private fun findTest(location: Location<*>): TestConfig? =
findTestFunction(location)
?: findTestMod(location)
private fun findTestFunction(location: Location<*>): TestConfig? {
val fn = location.psiElement.parentOfType<RsFunction>(strict = false) ?: return null
val name = fn.name ?: return null
val target = fn.containingCargoTarget ?: return null
return if (fn.isTest) TestConfig(fn, "Test $name", name, target) else null
}
private fun findTestMod(location: Location<*>): TestConfig? {
val mod = location.psiElement.parentOfType<RsMod>(strict = false) ?: return null
val testName = if (mod.modName == "test" || mod.modName == "tests")
"Test ${mod.`super`?.modName}::${mod.modName}"
else
"Test ${mod.modName}"
// We need to chop off heading colon `::`, since `crateRelativePath`
// always returns fully-qualified path
val testPath = (mod.crateRelativePath ?: "").toString().removePrefix("::")
val target = mod.containingCargoTarget ?: return null
if (!mod.functionList.any { it.isTest }) return null
return TestConfig(mod, testName, testPath, target)
}
}
| mit | 758224eda93588346955981275a0061d | 40.704545 | 128 | 0.720436 | 5.048143 | false | true | false | false |
hewking/HUILibrary | app/src/main/java/com/hewking/custom/pointerpanel/RotateGestureDetector.kt | 1 | 4500 | package com.hewking.pointerpanel
import android.view.MotionEvent
import kotlin.math.atan2
import kotlin.math.roundToInt
/**
* 旋转手势处理类
*/
class RotateGestureDetector {
/**
* 循环旋转(默认开启)
*/
var isCycle = true
/**
* 当前旋转角度
*/
var rotateAngle = 0f
/**
* 角度偏移值
*/
var offsetAngle = 0f
/**
* 设置起始角,非循环旋转有效
*/
var startAngle = 0f
/**
* 设置结束角,非循环旋转有效
*/
var endAngle = 360f
/**
* 上次旋转角度
*/
var _lastAngle = 0f
/**
* 是否正在旋转
*/
var _isRotate = false
/**
* 旋转回调
*
* @param angleStep 旋转的角度
* @param angle 当前手势对应的角度
* @param pivotX 旋转中心点x坐标
* @param pivotY 旋转中心点y坐标
*/
var onRotateListener: (angleStep: Float, angle: Float, pivotX: Int, pivotY: Int) -> Unit =
{ _, _, _, _ ->
}
/**
* 代理手势处理
* @param pivotX 中心点坐标
* @param pivotY 中心点坐标
* */
fun onTouchEvent(event: MotionEvent, pivotX: Int, pivotY: Int): Boolean {
val pointerCount = event.pointerCount
if (pointerCount == 1) {
return doOnePointerRotate(event, pivotX, pivotY)
} else if (pointerCount == 2) {
return doTwoPointerRotate(event)
}
return false
}
/**
* 一根手指绕中心点旋转
*/
fun doOnePointerRotate(ev: MotionEvent, pivotX: Int, pivotY: Int): Boolean {
val deltaX = ev.getX(0) - pivotX
val deltaY = ev.getY(0) - pivotY
val degrees = Math.toDegrees(
atan2(
deltaY.toDouble(),
deltaX.toDouble()
)
).roundToInt()
doEvent(ev, pivotX, pivotY, degrees.toFloat())
return true
}
/**
* 两根手指绕中心点旋转
*/
fun doTwoPointerRotate(ev: MotionEvent): Boolean {
val pivotX = (ev.getX(0) + ev.getX(1)).toInt() / 2
val pivotY = (ev.getY(0) + ev.getY(1)).toInt() / 2
val deltaX = ev.getX(0) - ev.getX(1)
val deltaY = ev.getY(0) - ev.getY(1)
val degrees = Math.toDegrees(
atan2(
deltaY.toDouble(),
deltaX.toDouble()
)
).roundToInt()
doEvent(ev, pivotX, pivotY, degrees.toFloat())
return true
}
fun doEvent(ev: MotionEvent, pivotX: Int, pivotY: Int, degrees: Float) {
when (ev.actionMasked) {
MotionEvent.ACTION_DOWN -> {
_lastAngle = degrees
_isRotate = false
}
MotionEvent.ACTION_UP -> _isRotate = false
MotionEvent.ACTION_POINTER_DOWN -> {
_lastAngle = degrees
_isRotate = false
}
MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_POINTER_UP -> {
_isRotate = false
upRotate(pivotX, pivotY)
_lastAngle = degrees
}
MotionEvent.ACTION_MOVE -> {
_isRotate = true
val degreesValue = degrees - _lastAngle
if (degreesValue > 45) {
rotate(-5f, degrees, pivotX, pivotY)
} else if (degreesValue < -45) {
rotate(5f, degrees, pivotX, pivotY)
} else {
rotate(degreesValue, degrees, pivotX, pivotY)
}
_lastAngle = degrees
}
else -> {
}
}
}
/**
* 实时旋转回调
*/
fun rotate(degree: Float, angle: Float, pivotX: Int, pivotY: Int) {
rotateAngle += degree
if (isCycle) {
if (rotateAngle > 360) {
rotateAngle -= 360
} else if (rotateAngle < 0) {
rotateAngle += 360
}
} else {
if (rotateAngle < startAngle) {
rotateAngle = startAngle
} else if (rotateAngle > endAngle) {
rotateAngle = endAngle
}
}
onRotateListener(
rotateAngle + offsetAngle,
if (angle < 0) 360 + angle else angle,
pivotX, pivotY
)
}
/**
* 手指抬起回调
*/
fun upRotate(pivotX: Int, pivotY: Int) {
}
} | mit | 408c5274172b77d0b8883962ccc20c99 | 24.251497 | 94 | 0.484108 | 4.153695 | false | false | false | false |
soywiz/korge | korge-swf/src/commonMain/kotlin/com/soywiz/korfl/AbcConstantPool.kt | 1 | 2076 | package com.soywiz.korfl
import com.soywiz.korio.lang.*
import com.soywiz.korio.stream.*
class AbcConstantPool {
var ints = listOf<Int>()
var uints = listOf<Int>()
var doubles = listOf<Double>()
var strings = listOf<String>()
var namespaces = listOf<ABC.Namespace>()
var namespaceSets = listOf<List<ABC.Namespace>>()
var multinames = listOf<ABC.AbstractMultiname>()
fun readConstantPool(s: SyncStream) {
val intCount = s.readU30()
ints = listOf(0) + (1 until intCount).map { s.readU30() }
val uintCount = s.readU30()
uints = listOf(0) + (1 until uintCount).map { s.readU30() }
val doubleCount = s.readU30()
doubles = listOf(0.0) + (1 until doubleCount).map { s.readF64LE() }
val stringCount = s.readU30()
strings = listOf("") + (1 until stringCount).map { s.readStringz(s.readU30()) }
namespaces = listOf(ABC.Namespace.EMPTY) + (1 until s.readU30()).map {
val kind = s.readU8()
val name = strings[s.readU30()]
ABC.Namespace(kind, name)
}
namespaceSets = listOf(listOf<ABC.Namespace>()) + (1 until s.readU30()).map {
(0 until s.readU30()).map { namespaces[s.readU30()] }
}
multinames = listOf(ABC.EmptyMultiname) + (1 until s.readU30()).map {
val kind = s.readU8()
when (kind) {
0x07 -> ABC.ABCQName(namespaces[s.readU30()], strings[s.readU30()])
0x0D -> ABC.QNameA(namespaces[s.readU30()], strings[s.readU30()])
0x0F -> ABC.RTQName(strings[s.readU30()])
0x10 -> ABC.RTQNameA(strings[s.readU30()])
0x11 -> ABC.RTQNameL
0x12 -> ABC.RTQNameLA
0x09 -> ABC.Multiname(strings[s.readU30()], namespaceSets[s.readU30()])
0x0E -> ABC.MultinameA(strings[s.readU30()], namespaceSets[s.readU30()])
0x1B -> ABC.MultinameL(namespaceSets[s.readU30()])
0x1C -> ABC.MultinameLA(namespaceSets[s.readU30()])
0x1D -> ABC.TypeName(s.readU30(), (0 until s.readU30()).map { s.readU30() })
else -> invalidOp("Unsupported $kind")
}
}
//println(ints)
//println(uints)
//println(doubles)
//println(strings)
//println(namespaces)
//println(namespaceSets)
//println(multinames)
}
}
| apache-2.0 | 4f79374093415f7a42d9a4be9aa3def4 | 34.793103 | 81 | 0.662331 | 2.867403 | false | false | false | false |
Orchextra/orchextra-android-sdk | core/src/main/java/com/gigigo/orchextra/core/domain/datasources/SessionManager.kt | 1 | 1353 | /*
* Created by Orchextra
*
* Copyright (C) 2017 Gigigo Mobile Services SL
*
* 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.gigigo.orchextra.core.domain.datasources
import android.content.Context
import com.gigigo.orchextra.core.Orchextra
import com.gigigo.orchextra.core.data.datasources.session.SessionManagerImp
interface SessionManager {
fun saveSession(token: String)
fun getSession(): String
fun hasSession(): Boolean
fun clearSession()
companion object Factory {
var sessionManager: SessionManager? = null
fun create(context: Context): SessionManager {
if (sessionManager == null) {
val sharedPreferences = Orchextra.provideSharedPreferences(context)
sessionManager = SessionManagerImp(sharedPreferences)
}
return sessionManager as SessionManager
}
}
} | apache-2.0 | 44f25443776461c6cc2e5dc59618edc6 | 26.632653 | 75 | 0.744272 | 4.602041 | false | false | false | false |
karollewandowski/aem-intellij-plugin | src/main/kotlin/co/nums/intellij/aem/htl/completion/provider/insertHandler/HtlExprOptionBracketsInsertHandler.kt | 1 | 1187 | package co.nums.intellij.aem.htl.completion.provider.insertHandler
import co.nums.intellij.aem.extensions.hasText
import co.nums.intellij.aem.extensions.moveCaret
import com.intellij.codeInsight.completion.InsertHandler
import com.intellij.codeInsight.completion.InsertionContext
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.editor.Document
object HtlExprOptionBracketsInsertHandler : InsertHandler<LookupElement> {
private const val INTO_BRACKETS_OFFSET = 2
override fun handleInsert(context: InsertionContext, item: LookupElement) {
val document = context.editor.document
val offset = context.editor.caretModel.offset
if (!document.hasBracketsAt(offset)) {
document.insertBrackets(offset, context)
}
}
private fun Document.hasBracketsAt(offset: Int) = this.hasText(offset, "=[")
private fun Document.insertBrackets(offset: Int, context: InsertionContext) {
this.insertString(offset, "=[]")
if (context.completionChar == '=') {
context.setAddCompletionChar(false) // IDEA-19449
}
context.editor.moveCaret(INTO_BRACKETS_OFFSET)
}
}
| gpl-3.0 | 378f2e1e222694e5960676260d1db3aa | 36.09375 | 81 | 0.73631 | 4.445693 | false | false | false | false |
StoneMain/Shortranks | ShortranksBukkit/src/main/kotlin/eu/mikroskeem/shortranks/bukkit/scoreboard/ScoreboardManager.kt | 1 | 5086 | /*
* This file is part of project Shortranks, licensed under the MIT License (MIT).
*
* Copyright (c) 2017-2019 Mark Vainomaa <[email protected]>
* Copyright (c) Contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package eu.mikroskeem.shortranks.bukkit.scoreboard
import eu.mikroskeem.shortranks.api.ScoreboardTeam
import eu.mikroskeem.shortranks.api.ShortranksPlugin
import eu.mikroskeem.shortranks.api.player.ShortranksPlayer
import eu.mikroskeem.shortranks.bukkit.common.asPlayer
import eu.mikroskeem.shortranks.bukkit.common.onlinePlayers
import eu.mikroskeem.shortranks.bukkit.common.shortranks
import eu.mikroskeem.shortranks.bukkit.player.ShortranksPlayerBukkit
import eu.mikroskeem.shortranks.common.scoreboard.AbstractScoreboardManager
import eu.mikroskeem.shortranks.common.shortranksPluginInstance
import eu.mikroskeem.shortranks.common.toUnmodifiableList
import org.bukkit.Server
import org.bukkit.entity.Player
import java.util.UUID
/**
* Simple scoreboard team manager
*
* @author Mark Vainomaa
*/
class ScoreboardManagerImpl(plugin: ShortranksPlugin<Server, Player>): AbstractScoreboardManager<Player, ScoreboardTeamImpl>(plugin) {
// Create new team for player
override fun createTeam(player: Player): ScoreboardTeamImpl {
/* Create own team for player */
val team = ScoreboardTeamImpl(ShortranksPlayerBukkit(player))
synchronized(teamsMap) {
// Send all teams to player
teamsMap.values.forEach { it.toNewTeamPacket().sendPacket(player) }
/* Register team */
val newTeamPacket = team.toNewTeamPacket()
val addPlayerPacket = team.toAddMemberPacket(listOf(player.name))
newTeamPacket.sendPacket(player)
addPlayerPacket.sendPacket(player)
teamsMap.keys.forEach { otherPlayer ->
newTeamPacket.sendPacket(otherPlayer)
addPlayerPacket.sendPacket(otherPlayer)
}
// Add to teams list
teamsMap.put(player.uniqueId, team)
}
return team
}
// Gets team for player
fun getTeam(player: Player): ScoreboardTeam = synchronized(teamsMap) {
return teamsMap.computeIfAbsent(player.uniqueId) { createTeam(player).also(this::updateTeam) }
}
// Unregister team
fun removePlayer(player: Player) {
val team = teamsMap[player.uniqueId] ?: return
removeMembers(team, team.members)
val deletePacket = team.toRemoveTeamPacket()
synchronized(teamsMap) {
teamsMap.keys.forEach(deletePacket::sendPacket)
teamsMap.remove(player.uniqueId)
}
}
fun removePlayer(uuid: UUID) = removePlayer(shortranks.findOnlinePlayer(uuid)!!.base)
// Update team
override fun updateTeam(team: ScoreboardTeam) {
team as ScoreboardTeamImpl
processors.forEach { it.accept(team) }
val updatePacket = team.toUpdateTeamPacket()
synchronized(teamsMap) {
teamsMap.keys.forEach(updatePacket::sendPacket)
}
}
// Pushes out member add packet
override fun addMembers(team: ScoreboardTeamImpl, members: Collection<String>) {
val addMemberPacket = team.toAddMemberPacket(members)
synchronized(teamsMap) {
teamsMap.keys.forEach(addMemberPacket::sendPacket)
}
}
// Pushes out member remove packet
override fun removeMembers(team: ScoreboardTeamImpl, members: Collection<String>) {
val removeMemberPacket = team.toRemoveMemberPacket(members)
synchronized(teamsMap) {
teamsMap.keys.forEach(removeMemberPacket::sendPacket)
}
}
// Resets all teams
override fun resetTeams(): Unit = synchronized(teamsMap) {
teamsMap.keys.toUnmodifiableList().forEach(this::removePlayer)
onlinePlayers.map(this::getTeam).forEach(this::updateTeam)
}
// Methods to implemet ScoreboardManager API interface
override fun removeTeam(player: UUID) = removePlayer(player.asPlayer)
} | mit | c674fda6f90c78b461175453ca69cd6c | 38.742188 | 134 | 0.718443 | 4.696214 | false | false | false | false |
panpf/sketch | sketch-extensions/src/main/java/com/github/panpf/sketch/SketchImageView.kt | 1 | 4529 | /*
* Copyright (C) 2022 panpf <[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 com.github.panpf.sketch
import android.content.Context
import android.util.AttributeSet
import com.github.panpf.sketch.fetch.newResourceUri
import com.github.panpf.sketch.internal.ImageXmlAttributes
import com.github.panpf.sketch.internal.parseImageXmlAttributes
import com.github.panpf.sketch.request.DisplayRequest
import com.github.panpf.sketch.request.DisplayResult.Error
import com.github.panpf.sketch.request.DisplayResult.Success
import com.github.panpf.sketch.request.ImageOptions
import com.github.panpf.sketch.request.ImageOptionsProvider
import com.github.panpf.sketch.request.Listener
import com.github.panpf.sketch.request.internal.Listeners
import com.github.panpf.sketch.request.ProgressListener
import com.github.panpf.sketch.request.internal.ProgressListeners
import com.github.panpf.sketch.viewability.AbsAbilityImageView
open class SketchImageView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyle: Int = 0
) : AbsAbilityImageView(context, attrs, defStyle), ImageOptionsProvider {
override var displayImageOptions: ImageOptions? = null
private var displayListenerList: MutableList<Listener<DisplayRequest, Success, Error>>? = null
private var displayProgressListenerList: MutableList<ProgressListener<DisplayRequest>>? = null
private val imageXmlAttributes: ImageXmlAttributes
init {
imageXmlAttributes = parseImageXmlAttributes(context, attrs)
@Suppress("LeakingThis")
displayImageOptions = imageXmlAttributes.options
displaySrc()
}
private fun displaySrc() {
val displaySrcResId = imageXmlAttributes.srcResId
if (displaySrcResId != null) {
if (isInEditMode) {
setImageResource(displaySrcResId)
} else {
post {
displayImage(newResourceUri(displaySrcResId))
}
}
}
}
override fun submitRequest(request: DisplayRequest) {
context.sketch.enqueue(request)
}
override fun getDisplayListener(): Listener<DisplayRequest, Success, Error>? {
val myListeners = displayListenerList?.takeIf { it.isNotEmpty() }
val superListener = super.getDisplayListener()
if (myListeners == null && superListener == null) return superListener
val listenerList = (myListeners?.toMutableList() ?: mutableListOf()).apply {
if (superListener != null) add(superListener)
}.toList()
return Listeners(listenerList)
}
override fun getDisplayProgressListener(): ProgressListener<DisplayRequest>? {
val myProgressListeners = displayProgressListenerList?.takeIf { it.isNotEmpty() }
val superProgressListener = super.getDisplayProgressListener()
if (myProgressListeners == null && superProgressListener == null) return superProgressListener
val progressListenerList = (myProgressListeners?.toMutableList() ?: mutableListOf()).apply {
if (superProgressListener != null) add(superProgressListener)
}.toList()
return ProgressListeners(progressListenerList)
}
fun registerDisplayListener(listener: Listener<DisplayRequest, Success, Error>) {
this.displayListenerList = (this.displayListenerList ?: mutableListOf()).apply {
add(listener)
}
}
fun unregisterDisplayListener(listener: Listener<DisplayRequest, Success, Error>) {
this.displayListenerList?.remove(listener)
}
fun registerDisplayProgressListener(listener: ProgressListener<DisplayRequest>) {
this.displayProgressListenerList =
(this.displayProgressListenerList ?: mutableListOf()).apply {
add(listener)
}
}
fun unregisterDisplayProgressListener(listener: ProgressListener<DisplayRequest>) {
this.displayProgressListenerList?.remove(listener)
}
} | apache-2.0 | b2d4188211393d74746de805ba4b9c93 | 40.181818 | 102 | 0.724884 | 5.04343 | false | false | false | false |
dtarnawczyk/modernlrs | src/main/org/lrs/kmodernlrs/domain/XapiObject.kt | 1 | 1002 | package org.lrs.kmodernlrs.domain
import com.google.gson.annotations.SerializedName
import java.io.Serializable
data class XapiObject(
var id: String? = "",
var objectType: String? = "",
var definition: Activity? = null,
// when the Object is an Agent/Group - attributes of an Actor
var name: String? = "",
var mbox: String? = "",
var mbox_sha1sum: String? = "",
var openid: String? = "",
var member: List<Actor> = listOf(),
var account: Account? = null,
// when an Object is an Substatement - attributes of a Statement
var actor: Actor? = null,
var verb: Verb? = null,
@SerializedName("object")
var xapiObj: XapiObject? = null,
var result: Result? = null,
var context: Context? = null,
var timestamp: String? = null,
var attachments: List<Attachment>? = listOf()) : Serializable {
companion object {
private val serialVersionUID:Long = 1
}
} | apache-2.0 | 71baa1b4e7f51b937a2c92a73a178c3d | 31.354839 | 71 | 0.601796 | 4.05668 | false | false | false | false |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/page/references/ReferenceDialog.kt | 1 | 5075 | package org.wikipedia.page.references
import android.app.Dialog
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayoutMediator
import org.wikipedia.R
import org.wikipedia.activity.FragmentUtil.getCallback
import org.wikipedia.databinding.FragmentReferencesPagerBinding
import org.wikipedia.databinding.ViewReferencePagerItemBinding
import org.wikipedia.page.ExtendedBottomSheetDialogFragment
import org.wikipedia.page.LinkHandler
import org.wikipedia.page.LinkMovementMethodExt
import org.wikipedia.util.DimenUtil
import org.wikipedia.util.L10nUtil
import org.wikipedia.util.StringUtil
import java.util.*
class ReferenceDialog : ExtendedBottomSheetDialogFragment() {
interface Callback {
val linkHandler: LinkHandler
val referencesGroup: List<PageReferences.Reference>?
val selectedReferenceIndex: Int
}
private var _binding: FragmentReferencesPagerBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
_binding = FragmentReferencesPagerBinding.inflate(inflater, container, false)
callback()?.let {
it.referencesGroup?.run {
binding.referenceTitleText.text = requireContext().getString(R.string.reference_title, "")
binding.referencePager.offscreenPageLimit = 2
binding.referencePager.adapter = ReferencesAdapter(this)
TabLayoutMediator(binding.pageIndicatorView, binding.referencePager) { _, _ -> }.attach()
binding.referencePager.setCurrentItem(it.selectedReferenceIndex, true)
L10nUtil.setConditionalLayoutDirection(binding.root, it.linkHandler.wikiSite.languageCode)
} ?: return@let null
} ?: run {
dismiss()
}
return binding.root
}
override fun onStart() {
super.onStart()
if (callback()?.referencesGroup?.size == 1) {
binding.pageIndicatorView.visibility = View.GONE
binding.indicatorDivider.visibility = View.GONE
}
BottomSheetBehavior.from(binding.root.parent as View).peekHeight = DimenUtil.displayHeightPx
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
private fun processLinkTextWithAlphaReferences(linkText: String): String {
var newLinkText = linkText
val isLowercase = newLinkText.contains("lower")
if (newLinkText.contains("alpha ")) {
val strings = newLinkText.split(" ")
var alphaReference = StringUtil.getBase26String(strings.last().replace("]", "").toInt())
alphaReference = if (isLowercase) alphaReference.lowercase(Locale.getDefault()) else alphaReference
newLinkText = alphaReference
}
return newLinkText.replace("[\\[\\]]".toRegex(), "") + "."
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
return object : BottomSheetDialog(requireActivity(), theme) {
override fun onBackPressed() {
if (binding.referencePager.currentItem > 0) {
binding.referencePager.setCurrentItem(binding.referencePager.currentItem - 1, true)
} else {
super.onBackPressed()
}
}
}
}
private inner class ViewHolder constructor(val binding: ViewReferencePagerItemBinding) : RecyclerView.ViewHolder(binding.root) {
init {
binding.referenceText.movementMethod = LinkMovementMethodExt(callback()?.linkHandler)
}
fun bindItem(idText: CharSequence?, contents: CharSequence?) {
binding.referenceId.text = idText
binding.root.post {
if (isAdded) {
binding.referenceText.text = contents
}
}
}
}
private inner class ReferencesAdapter constructor(val references: List<PageReferences.Reference>) : RecyclerView.Adapter<ViewHolder>() {
override fun getItemCount(): Int {
return references.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(ViewReferencePagerItemBinding.inflate(LayoutInflater.from(context), parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bindItem(processLinkTextWithAlphaReferences(references[position].text),
StringUtil.fromHtml(StringUtil.removeCiteMarkup(StringUtil.removeStyleTags(references[position].html))))
}
}
private fun callback(): Callback? {
return getCallback(this, Callback::class.java)
}
}
| apache-2.0 | 563147861c6623db52e3edb836d0663d | 40.598361 | 140 | 0.682759 | 5.314136 | false | false | false | false |
slartus/4pdaClient-plus | forum/forum-data/src/main/java/org/softeg/slartus/forpdaplus/forum/data/db/ForumEntity.kt | 1 | 813 | package org.softeg.slartus.forpdaplus.forum.data.db
import androidx.room.Entity
import androidx.room.PrimaryKey
import ru.softeg.slartus.forum.api.ForumItem
@Entity(tableName = "forum")
data class ForumEntity(
@PrimaryKey(autoGenerate = true)
val _id: Int? = null,
val id: String,
val title: String,
val description: String,
val isHasTopics: Boolean,
val isHasForums: Boolean,
val iconUrl: String?,
val parentId: String?
)
fun ForumEntity.mapToItem() = ForumItem(
this.id,
this.title,
this.description,
this.isHasTopics,
this.isHasForums,
this.iconUrl,
this.parentId
)
fun ForumItem.mapToDb() = ForumEntity(null,
this.id,
this.title,
this.description,
this.isHasTopics,
this.isHasForums,
this.iconUrl,
this.parentId
) | apache-2.0 | c9e813b2183768f0431e74c6d45db623 | 20.421053 | 51 | 0.693727 | 3.581498 | false | false | false | false |
ejeinc/VR-MultiView-UDP | controller-android/src/main/java/com/eje_c/multilink/controller/db/DeviceEntity.kt | 1 | 627 | package com.eje_c.multilink.controller.db
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
/**
* Represents a record in DeviceEntity table in local SQLite DB.
*/
@Entity
class DeviceEntity {
/**
* Device's IMEI
*/
@PrimaryKey
var imei: String = ""
/**
* Device's display name
*/
@ColumnInfo(name = "name")
var name: String? = null
/**
* Update time for this record based on SystemClock.uptimeMillis().
*/
@ColumnInfo(name = "updated_at")
var updatedAt: Long = 0
} | apache-2.0 | 5b2f3a4967c1d01810a22687fb0c70df | 19.933333 | 71 | 0.655502 | 3.968354 | false | false | false | false |
stripe/stripe-android | paymentsheet/src/main/java/com/stripe/android/paymentsheet/addresselement/InputAddressViewModel.kt | 1 | 9766 | package com.stripe.android.paymentsheet.addresselement
import androidx.annotation.VisibleForTesting
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.stripe.android.core.injection.NonFallbackInjectable
import com.stripe.android.core.injection.NonFallbackInjector
import com.stripe.android.paymentsheet.PaymentSheet
import com.stripe.android.paymentsheet.addresselement.analytics.AddressLauncherEventReporter
import com.stripe.android.paymentsheet.injection.InputAddressViewModelSubcomponent
import com.stripe.android.ui.core.FormController
import com.stripe.android.ui.core.elements.AddressSpec
import com.stripe.android.ui.core.elements.AddressType
import com.stripe.android.ui.core.elements.IdentifierSpec
import com.stripe.android.ui.core.elements.LayoutSpec
import com.stripe.android.ui.core.elements.PhoneNumberState
import com.stripe.android.ui.core.forms.FormFieldEntry
import com.stripe.android.ui.core.injection.FormControllerSubcomponent
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Provider
internal class InputAddressViewModel @Inject constructor(
val args: AddressElementActivityContract.Args,
val navigator: AddressElementNavigator,
private val eventReporter: AddressLauncherEventReporter,
formControllerProvider: Provider<FormControllerSubcomponent.Builder>
) : ViewModel() {
private val _collectedAddress = MutableStateFlow(args.config?.address)
val collectedAddress: StateFlow<AddressDetails?> = _collectedAddress
private val _formController = MutableStateFlow<FormController?>(null)
val formController: StateFlow<FormController?> = _formController
private val _formEnabled = MutableStateFlow(true)
val formEnabled: StateFlow<Boolean> = _formEnabled
private val _checkboxChecked = MutableStateFlow(false)
val checkboxChecked: StateFlow<Boolean> = _checkboxChecked
init {
viewModelScope.launch {
navigator.getResultFlow<AddressDetails?>(AddressDetails.KEY)?.collect {
val oldAddress = _collectedAddress.value
val autocompleteAddress = AddressDetails(
name = oldAddress?.name ?: it?.name,
address = oldAddress?.address?.copy(
city = oldAddress.address.city ?: it?.address?.city,
country = oldAddress.address.country ?: it?.address?.country,
line1 = oldAddress.address.line1 ?: it?.address?.line1,
line2 = oldAddress.address.line2 ?: it?.address?.line2,
postalCode = oldAddress.address.postalCode ?: it?.address?.postalCode,
state = oldAddress.address.state ?: it?.address?.state
) ?: it?.address,
phoneNumber = oldAddress?.phoneNumber ?: it?.phoneNumber,
isCheckboxSelected = oldAddress?.isCheckboxSelected
?: it?.isCheckboxSelected
)
_collectedAddress.emit(autocompleteAddress)
}
}
viewModelScope.launch {
collectedAddress.collect { addressDetails ->
val initialValues: Map<IdentifierSpec, String?> = addressDetails
?.toIdentifierMap()
?: emptyMap()
_formController.value = formControllerProvider.get()
.viewOnlyFields(emptySet())
.viewModelScope(viewModelScope)
.stripeIntent(null)
.merchantName("")
.shippingValues(null)
.formSpec(buildFormSpec(addressDetails?.address?.line1 == null))
.initialValues(initialValues)
.build().formController
}
}
// allows merchants to check the box by default and to restore the value later.
args.config?.address?.isCheckboxSelected?.let {
_checkboxChecked.value = it
}
}
private suspend fun getCurrentAddress(): AddressDetails? {
return formController.value
?.formValues
?.stateIn(viewModelScope)
?.value
?.let {
AddressDetails(
name = it[IdentifierSpec.Name]?.value,
address = PaymentSheet.Address(
city = it[IdentifierSpec.City]?.value,
country = it[IdentifierSpec.Country]?.value,
line1 = it[IdentifierSpec.Line1]?.value,
line2 = it[IdentifierSpec.Line2]?.value,
postalCode = it[IdentifierSpec.PostalCode]?.value,
state = it[IdentifierSpec.State]?.value
),
phoneNumber = it[IdentifierSpec.Phone]?.value
)
}
}
private fun buildFormSpec(condensedForm: Boolean): LayoutSpec {
val phoneNumberState = parsePhoneNumberConfig(args.config?.additionalFields?.phone)
val addressSpec = if (condensedForm) {
AddressSpec(
showLabel = false,
type = AddressType.ShippingCondensed(
googleApiKey = args.config?.googlePlacesApiKey,
autocompleteCountries = args.config?.autocompleteCountries,
phoneNumberState = phoneNumberState
) {
viewModelScope.launch {
val addressDetails = getCurrentAddress()
addressDetails?.let {
_collectedAddress.emit(it)
}
addressDetails?.address?.country?.let {
navigator.navigateTo(
AddressElementScreen.Autocomplete(
country = it
)
)
}
}
}
)
} else {
AddressSpec(
showLabel = false,
type = AddressType.ShippingExpanded(
phoneNumberState = phoneNumberState
)
)
}
val addressSpecWithAllowedCountries = args.config?.allowedCountries?.run {
addressSpec.copy(allowedCountryCodes = this)
}
return LayoutSpec(
listOf(
addressSpecWithAllowedCountries ?: addressSpec
)
)
}
fun clickPrimaryButton(
completedFormValues: Map<IdentifierSpec, FormFieldEntry>?,
checkboxChecked: Boolean
) {
_formEnabled.value = false
dismissWithAddress(
AddressDetails(
name = completedFormValues?.get(IdentifierSpec.Name)?.value,
address = PaymentSheet.Address(
city = completedFormValues?.get(IdentifierSpec.City)?.value,
country = completedFormValues?.get(IdentifierSpec.Country)?.value,
line1 = completedFormValues?.get(IdentifierSpec.Line1)?.value,
line2 = completedFormValues?.get(IdentifierSpec.Line2)?.value,
postalCode = completedFormValues?.get(IdentifierSpec.PostalCode)?.value,
state = completedFormValues?.get(IdentifierSpec.State)?.value
),
phoneNumber = completedFormValues?.get(IdentifierSpec.Phone)?.value,
isCheckboxSelected = checkboxChecked
)
)
}
@VisibleForTesting
fun dismissWithAddress(addressDetails: AddressDetails) {
addressDetails.address?.country?.let { country ->
eventReporter.onCompleted(
country = country,
autocompleteResultSelected = collectedAddress.value?.address?.line1 != null,
editDistance = addressDetails.editDistance(collectedAddress.value)
)
}
navigator.dismiss(
AddressLauncherResult.Succeeded(addressDetails)
)
}
fun clickCheckbox(newValue: Boolean) {
_checkboxChecked.value = newValue
}
internal class Factory(
private val injector: NonFallbackInjector
) : ViewModelProvider.Factory, NonFallbackInjectable {
@Inject
lateinit var subComponentBuilderProvider:
Provider<InputAddressViewModelSubcomponent.Builder>
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
injector.inject(this)
return subComponentBuilderProvider.get()
.build().inputAddressViewModel as T
}
}
internal companion object {
// This mapping is required to prevent merchants from depending on ui-core
fun parsePhoneNumberConfig(
configuration: AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration?
): PhoneNumberState {
return when (configuration) {
AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.HIDDEN ->
PhoneNumberState.HIDDEN
AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.OPTIONAL ->
PhoneNumberState.OPTIONAL
AddressLauncher.AdditionalFieldsConfiguration.FieldConfiguration.REQUIRED ->
PhoneNumberState.REQUIRED
null -> PhoneNumberState.OPTIONAL
}
}
}
}
| mit | ef54bfd29e2cbd958013ff48adf617c6 | 41.833333 | 94 | 0.609257 | 5.922377 | false | true | false | false |
deeplearning4j/deeplearning4j | nd4j/samediff-import/samediff-import-onnx/src/main/kotlin/org/nd4j/samediff/frameworkimport/onnx/rule/tensor/OnnxMultiInputIndexMappingRule.kt | 1 | 2690 | /*
* ******************************************************************************
* *
* *
* * This program and the accompanying materials are made available under the
* * terms of the Apache License, Version 2.0 which is available at
* * https://www.apache.org/licenses/LICENSE-2.0.
* *
* * See the NOTICE file distributed with this work for additional
* * information regarding copyright ownership.
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* * License for the specific language governing permissions and limitations
* * under the License.
* *
* * SPDX-License-Identifier: Apache-2.0
* *****************************************************************************
*/
package org.nd4j.samediff.frameworkimport.onnx.rule.tensor
import onnx.Onnx
import org.nd4j.ir.OpNamespace
import org.nd4j.ir.TensorNamespace
import org.nd4j.samediff.frameworkimport.findOp
import org.nd4j.samediff.frameworkimport.onnx.ir.OnnxIRTensor
import org.nd4j.samediff.frameworkimport.opdefs.OpDescriptorLoaderHolder
import org.nd4j.samediff.frameworkimport.rule.MappingRule
import org.nd4j.samediff.frameworkimport.rule.tensor.MultiInputIndexMappingRule
@MappingRule("onnx","multiinputindex","tensor")
class OnnxMultiInputIndexMappingRule(mappingNamesToPerform: MutableMap<String,String>,
transformerArgs: Map<String, List<OpNamespace.ArgDescriptor>> = emptyMap()):
MultiInputIndexMappingRule<Onnx.GraphProto, Onnx.NodeProto, Onnx.NodeProto, Onnx.AttributeProto, Onnx.AttributeProto,
Onnx.TensorProto, Onnx.TensorProto.DataType>(mappingNamesToPerform = mappingNamesToPerform, transformerArgs = transformerArgs) {
override fun createTensorProto(input: Onnx.TensorProto): TensorNamespace.TensorProto {
return OnnxIRTensor(input).toArgTensor()
}
override fun isInputTensorName(inputName: String): Boolean {
val onnxOp = OpDescriptorLoaderHolder.listForFramework<Onnx.NodeProto>("onnx")[mappingProcess!!.inputFrameworkOpName()]!!
return onnxOp.inputList.contains(inputName)
}
override fun isOutputTensorName(outputName: String): Boolean {
val nd4jOpDescriptor = OpDescriptorLoaderHolder.nd4jOpDescriptor.findOp(mappingProcess!!.opName())
return nd4jOpDescriptor.argDescriptorList.filter { inputDescriptor -> inputDescriptor.argType == OpNamespace.ArgDescriptor.ArgType.INPUT_TENSOR }
.map {inputDescriptor -> inputDescriptor.name }.contains(outputName)
}
} | apache-2.0 | 1014f9c1c3cbe0db1ce630dc02575ead | 49.773585 | 153 | 0.714126 | 4.761062 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/SimplifyBooleanExpressionFix.kt | 4 | 1018 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.ide.utils.BooleanExprSimplifier
import org.rust.ide.utils.isPure
import org.rust.lang.core.psi.RsExpr
class SimplifyBooleanExpressionFix(expr: RsExpr) : LocalQuickFixOnPsiElement(expr) {
override fun getText(): String = "Simplify boolean expression"
override fun getFamilyName() = text
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
val expr = startElement as? RsExpr ?: return
if (expr.isPure() == true && BooleanExprSimplifier.canBeSimplified(expr)) {
val simplified = BooleanExprSimplifier(project).simplify(expr) ?: return
expr.replace(simplified)
}
}
}
| mit | b268415e09031fda9e3e6f756b0d11ee | 36.703704 | 108 | 0.74558 | 4.387931 | false | false | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RsWrongLifetimeParametersNumberInspection.kt | 2 | 2026 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections
import org.rust.lang.core.psi.RsPathType
import org.rust.lang.core.psi.RsRefLikeType
import org.rust.lang.core.psi.RsVisitor
import org.rust.lang.core.psi.ext.RsGenericDeclaration
import org.rust.lang.core.psi.ext.lifetimeArguments
import org.rust.lang.core.psi.ext.lifetimeParameters
import org.rust.lang.core.types.lifetimeElidable
import org.rust.lang.utils.RsDiagnostic
import org.rust.lang.utils.addToHolder
class RsWrongLifetimeParametersNumberInspection : RsLocalInspectionTool() {
override fun buildVisitor(holder: RsProblemsHolder, isOnTheFly: Boolean): RsVisitor =
object : RsVisitor() {
override fun visitPathType(type: RsPathType) {
val path = type.path
// Don't apply generic declaration checks to Fn-traits and `Self`
if (path.valueParameterList != null) return
if (path.cself != null) return
val paramsDecl = path.reference?.resolve() as? RsGenericDeclaration ?: return
val expectedLifetimes = paramsDecl.lifetimeParameters.size
val actualLifetimes = path.lifetimeArguments.size
if (expectedLifetimes == actualLifetimes) return
if (actualLifetimes == 0 && !type.lifetimeElidable) {
RsDiagnostic.MissingLifetimeSpecifier(type).addToHolder(holder)
} else if (actualLifetimes > 0) {
RsDiagnostic.WrongNumberOfLifetimeArguments(type, expectedLifetimes, actualLifetimes)
.addToHolder(holder)
}
}
override fun visitRefLikeType(type: RsRefLikeType) {
if (type.mul == null && !type.lifetimeElidable && type.lifetime == null) {
RsDiagnostic.MissingLifetimeSpecifier(type.and ?: type).addToHolder(holder)
}
}
}
}
| mit | a61ba7683cd1f8f13e626bfb9ea61835 | 41.208333 | 105 | 0.654985 | 4.700696 | false | false | false | false |
Undin/intellij-rust | src/test/kotlin/org/rust/lang/core/psi/RsCodeStatusTest.kt | 3 | 2847 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi
import org.intellij.lang.annotations.Language
import org.rust.MockAdditionalCfgOptions
import org.rust.RsTestBase
import org.rust.WithExperimentalFeatures
import org.rust.ide.experiments.RsExperiments.EVALUATE_BUILD_SCRIPTS
import org.rust.ide.experiments.RsExperiments.PROC_MACROS
import org.rust.lang.core.psi.ext.RsCodeStatus
import org.rust.lang.core.psi.ext.RsElement
import org.rust.lang.core.psi.ext.getCodeStatus
@WithExperimentalFeatures(EVALUATE_BUILD_SCRIPTS, PROC_MACROS)
class RsCodeStatusTest : RsTestBase() {
@MockAdditionalCfgOptions("intellij_rust")
fun `test enabled`() = doTest("""
#[cfg(intellij_rust)]
mod foo {
#[allow()]
mod bar {
//^ CODE
}
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled wins 1`() = doTest("""
#[cfg(not(intellij_rust))]
mod foo {
#[attr]
mod bar {
//^ CFG_DISABLED
}
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled wins 2`() = doTest("""
#[cfg(not(intellij_rust))]
#[attr]
mod bar {
//^ CFG_DISABLED
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled wins 3`() = doTest("""
#[attr]
#[cfg(not(intellij_rust))]
mod bar {
//^ CFG_DISABLED
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test proc macro wins`() = doTest("""
#[attr]
mod foo {
#[cfg(not(intellij_rust))]
mod bar {
//^ ATTR_PROC_MACRO_CALL
}
}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled cfg_attr`() = doTest("""
#[cfg_attr(not(intellij_rust), attr)]
mod foo {} //^ CFG_DISABLED
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test proc macro argument is enabled`() = doTest("""
#[attr(arg)]
//^ CODE
mod foo {}
""")
@MockAdditionalCfgOptions("intellij_rust")
fun `test cfg disabled wins for proc macro argument`() = doTest("""
#[cfg(not(intellij_rust))]
mod foo {
#[attr(arg)]
//^ CFG_DISABLED
mod foo {}
}
""")
private fun doTest(@Language("Rust") code: String) {
InlineFile(code)
val (element, data) = findElementAndDataInEditor<RsElement>()
val expectedCS = RsCodeStatus.values().find { it.name == data }!!
val actualCS = element.getCodeStatus(null)
assertEquals(expectedCS, actualCS)
}
}
| mit | 3a0a2a85d04eb09a6da8e10d930aab58 | 26.911765 | 73 | 0.566913 | 4.434579 | false | true | false | false |
Undin/intellij-rust | src/main/kotlin/org/rust/cargo/project/model/impl/UserDisabledFeatures.kt | 3 | 2430 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.project.model.impl
import org.rust.cargo.project.workspace.*
import org.rust.stdext.exhaustive
abstract class UserDisabledFeatures {
abstract val pkgRootToDisabledFeatures: Map<PackageRoot, Set<FeatureName>>
fun getDisabledFeatures(packages: Iterable<CargoWorkspace.Package>): List<PackageFeature> {
return packages.flatMap { pkg ->
pkgRootToDisabledFeatures[pkg.rootDirectory]
?.mapNotNull { name -> PackageFeature(pkg, name).takeIf { it in pkg.features } }
?: emptyList()
}
}
fun isEmpty(): Boolean {
return pkgRootToDisabledFeatures.isEmpty() || pkgRootToDisabledFeatures.values.all { it.isEmpty() }
}
fun toMutable(): MutableUserDisabledFeatures = MutableUserDisabledFeatures(
pkgRootToDisabledFeatures
.mapValues { (_, v) -> v.toMutableSet() }
.toMutableMap()
)
fun retain(packages: Iterable<CargoWorkspace.Package>): UserDisabledFeatures {
val newMap = EMPTY.toMutable()
for (disabledFeature in getDisabledFeatures(packages)) {
newMap.setFeatureState(disabledFeature, FeatureState.Disabled)
}
return newMap
}
companion object {
val EMPTY: UserDisabledFeatures = ImmutableUserDisabledFeatures(emptyMap())
fun of(pkgRootToDisabledFeatures: Map<PackageRoot, Set<FeatureName>>): UserDisabledFeatures =
ImmutableUserDisabledFeatures(pkgRootToDisabledFeatures)
}
}
private class ImmutableUserDisabledFeatures(
override val pkgRootToDisabledFeatures: Map<PackageRoot, Set<FeatureName>>
) : UserDisabledFeatures()
class MutableUserDisabledFeatures(
override val pkgRootToDisabledFeatures: MutableMap<PackageRoot, MutableSet<FeatureName>>
) : UserDisabledFeatures() {
fun setFeatureState(
feature: PackageFeature,
state: FeatureState
) {
val packageRoot = feature.pkg.rootDirectory
when (state) {
FeatureState.Enabled -> {
pkgRootToDisabledFeatures[packageRoot]?.remove(feature.name)
}
FeatureState.Disabled -> {
pkgRootToDisabledFeatures.getOrPut(packageRoot) { hashSetOf() }
.add(feature.name)
}
}.exhaustive
}
}
| mit | 078cca95b2669db29489d791e8851b72 | 33.225352 | 107 | 0.67572 | 5.485327 | false | false | false | false |
jvsegarra/kotlin-koans | src/i_introduction/_1_Java_To_Kotlin_Converter/JavaToKotlinConverter.kt | 1 | 1166 | package i_introduction._1_Java_To_Kotlin_Converter
import util.TODO
import java.util.*
fun todoTask1(collection: Collection<Int>): Nothing = TODO(
"""
Task 1.
Rewrite JavaCode1.task1 in Kotlin.
In IntelliJ, you can just copy-paste the code and agree to automatically convert it to Kotlin,
but only for this task!
""",
references = { JavaCode1().task1(collection) })
fun createStringFromCollectionWithStringJoiner(collection: Collection<Int>): String {
val joiner: StringJoiner = StringJoiner(", ", "{", "}");
for (item in collection) {
joiner.add(item.toString());
}
return joiner.toString();
}
fun convertCodeFromJavaCollection(collection: Collection<Int>): String {
val sb = StringBuilder()
sb.append("{")
val iterator = collection.iterator()
while (iterator.hasNext()) {
val element = iterator.next()
sb.append(element)
if (iterator.hasNext()) {
sb.append(", ")
}
}
sb.append("}")
return sb.toString()
}
fun task1(collection: Collection<Int>): String = createStringFromCollectionWithStringJoiner(collection)
| mit | aa0b352e9da3c6dd3a0ea06ecdecaad8 | 28.15 | 103 | 0.64837 | 4.302583 | false | false | false | false |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/media/recommendation/RecommendationAdapter.kt | 1 | 6406 | package me.proxer.app.media.recommendation
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.view.updateLayoutParams
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.mikepenz.iconics.utils.colorRes
import com.mikepenz.iconics.utils.paddingDp
import com.mikepenz.iconics.utils.sizeDp
import com.uber.autodispose.autoDisposable
import io.reactivex.subjects.PublishSubject
import kotterknife.bindView
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.base.AutoDisposeViewHolder
import me.proxer.app.base.BaseAdapter
import me.proxer.app.media.recommendation.RecommendationAdapter.ViewHolder
import me.proxer.app.util.extension.colorAttr
import me.proxer.app.util.extension.defaultLoad
import me.proxer.app.util.extension.getQuantityString
import me.proxer.app.util.extension.mapAdapterPosition
import me.proxer.app.util.extension.toAppDrawable
import me.proxer.app.util.extension.toAppString
import me.proxer.library.entity.info.Recommendation
import me.proxer.library.enums.Category
import me.proxer.library.util.ProxerUrls
/**
* @author Ruben Gees
*/
class RecommendationAdapter : BaseAdapter<Recommendation, ViewHolder>() {
var glide: GlideRequests? = null
val clickSubject: PublishSubject<Pair<ImageView, Recommendation>> = PublishSubject.create()
init {
setHasStableIds(true)
}
override fun getItemId(position: Int) = data[position].id.toLong()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_recommendation, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(data[position])
override fun onViewRecycled(holder: ViewHolder) {
glide?.clear(holder.image)
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
glide = null
}
inner class ViewHolder(itemView: View) : AutoDisposeViewHolder(itemView) {
internal val container: ViewGroup by bindView(R.id.container)
internal val title: TextView by bindView(R.id.title)
internal val medium: TextView by bindView(R.id.medium)
internal val image: ImageView by bindView(R.id.image)
internal val ratingContainer: ViewGroup by bindView(R.id.ratingContainer)
internal val rating: RatingBar by bindView(R.id.rating)
internal val state: ImageView by bindView(R.id.state)
internal val episodes: TextView by bindView(R.id.episodes)
internal val english: ImageView by bindView(R.id.english)
internal val german: ImageView by bindView(R.id.german)
internal val upvotesImage: ImageView by bindView(R.id.upvotesImage)
internal val upvotesText: TextView by bindView(R.id.upvotesText)
internal val downvotesImage: ImageView by bindView(R.id.downvotesImage)
internal val downvotesText: TextView by bindView(R.id.downvotesText)
init {
upvotesImage.setImageDrawable(generateUpvotesImage())
downvotesImage.setImageDrawable(generateDownvotesImage())
}
fun bind(item: Recommendation) {
container.clicks()
.mapAdapterPosition({ adapterPosition }) { image to data[it] }
.autoDisposable(this)
.subscribe(clickSubject)
ViewCompat.setTransitionName(image, "recommendation_${item.id}")
title.text = item.name
medium.text = item.medium.toAppString(medium.context)
episodes.text = episodes.context.getQuantityString(
when (item.category) {
Category.ANIME -> R.plurals.media_episode_count
Category.MANGA, Category.NOVEL -> R.plurals.media_chapter_count
},
item.episodeAmount
)
if (item.rating > 0) {
ratingContainer.isVisible = true
rating.rating = item.rating / 2.0f
episodes.updateLayoutParams<RelativeLayout.LayoutParams> {
addRule(RelativeLayout.ALIGN_BOTTOM, 0)
addRule(RelativeLayout.BELOW, R.id.state)
}
} else {
ratingContainer.isGone = true
episodes.updateLayoutParams<RelativeLayout.LayoutParams> {
addRule(RelativeLayout.ALIGN_BOTTOM, R.id.languageContainer)
addRule(RelativeLayout.BELOW, R.id.medium)
}
}
when (item.userVote) {
true -> upvotesImage.setImageDrawable(generateUpvotesImage(true))
false -> downvotesImage.setImageDrawable(generateUpvotesImage(true))
}
upvotesText.text = item.positiveVotes.toString()
downvotesText.text = item.negativeVotes.toString()
state.setImageDrawable(item.state.toAppDrawable(state.context))
glide?.defaultLoad(image, ProxerUrls.entryImage(item.id))
}
private fun generateUpvotesImage(userVoted: Boolean = false) = IconicsDrawable(upvotesImage.context)
.icon(CommunityMaterial.Icon.cmd_thumb_up)
.sizeDp(32)
.paddingDp(4)
.apply {
when (userVoted) {
true -> colorRes(R.color.md_green_500)
false -> colorAttr(upvotesImage.context, R.attr.colorIcon)
}
}
private fun generateDownvotesImage(userVoted: Boolean = false) = IconicsDrawable(downvotesImage.context)
.icon(CommunityMaterial.Icon.cmd_thumb_down)
.sizeDp(32)
.paddingDp(4)
.apply {
when (userVoted) {
true -> colorRes(R.color.md_red_500)
false -> colorAttr(upvotesImage.context, R.attr.colorIcon)
}
}
}
}
| gpl-3.0 | 2bd4285d96ebc38f84caca03e7a95b94 | 39.544304 | 115 | 0.679051 | 4.703377 | false | false | false | false |
CruGlobal/android-gto-support | gto-support-sync/src/main/java/org/ccci/gto/android/common/sync/SyncRegistry.kt | 2 | 627 | package org.ccci.gto.android.common.sync
import android.util.SparseBooleanArray
import java.util.concurrent.atomic.AtomicInteger
private const val INITIAL_SYNC_ID = 1
object SyncRegistry {
private val syncsRunning = SparseBooleanArray()
private val nextSyncId = AtomicInteger(INITIAL_SYNC_ID)
fun startSync() = nextSyncId.getAndIncrement().also { synchronized(syncsRunning) { syncsRunning.put(it, true) } }
fun isSyncRunning(id: Int) = id >= INITIAL_SYNC_ID && synchronized(syncsRunning) { syncsRunning.get(id, false) }
fun finishSync(id: Int) = synchronized(syncsRunning) { syncsRunning.delete(id) }
}
| mit | eea97989780e36aa93c3bd627b0e04b5 | 40.8 | 117 | 0.757576 | 3.87037 | false | false | false | false |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/modules/award/overview/AwardOverviewPresenter.kt | 2 | 1602 | package ru.fantlab.android.ui.modules.award.overview
import android.os.Bundle
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.Award
import ru.fantlab.android.data.dao.response.AwardResponse
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getAwardPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class AwardOverviewPresenter : BasePresenter<AwardOverviewMvp.View>(),
AwardOverviewMvp.Presenter {
override fun onFragmentCreated(bundle: Bundle) {
val awardId = bundle.getInt(BundleConstant.EXTRA)
makeRestCall(
getAwardInternal(awardId).toObservable(),
Consumer { award -> sendToView { it.onInitViews(award) } }
)
}
private fun getAwardInternal(awardId: Int) =
getAwardFromServer(awardId)
.onErrorResumeNext {
getAwardFromDb(awardId)
}
.onErrorResumeNext { ext -> Single.error(ext) }
.doOnError { err -> sendToView { it.onShowErrorView(err.message) } }
private fun getAwardFromServer(awardId: Int): Single<Award> =
DataManager.getAward(awardId, false, false)
.map { getAward(it) }
private fun getAwardFromDb(awardId: Int): Single<Award> =
DbProvider.mainDatabase
.responseDao()
.get(getAwardPath(awardId, false, false))
.map { it.response }
.map { AwardResponse.Deserializer().deserialize(it) }
.map { getAward(it) }
private fun getAward(response: AwardResponse): Award = response.award
} | gpl-3.0 | ea04017dc316ff33b2fba14e93028356 | 33.847826 | 73 | 0.757179 | 3.850962 | false | false | false | false |
bastman/kotlin-spring-jpa-examples | src/main/kotlin/com/example/demo/api/realestate/domain/jpa/services/JpaPropertyService.kt | 1 | 2710 | package com.example.demo.api.realestate.domain.jpa.services
import com.example.demo.api.common.EntityAlreadyExistException
import com.example.demo.api.common.EntityNotFoundException
import com.example.demo.api.realestate.domain.jpa.entities.Property
import com.example.demo.api.realestate.domain.jpa.entities.QueryDslEntity.qProperty
import com.example.demo.api.realestate.domain.jpa.repositories.PropertyRepository
import com.example.demo.util.optionals.toNullable
import com.querydsl.jpa.impl.JPAQuery
import org.springframework.stereotype.Component
import java.util.*
import javax.persistence.EntityManager
import javax.validation.Valid
@Component
class JpaPropertyService(
private val propertyRepository: PropertyRepository,
private val entityManager: EntityManager
) {
fun exists(propertyId: UUID): Boolean = propertyRepository.exists(propertyId)
fun findById(propertyId: UUID): Property? =
propertyRepository
.getById(propertyId)
.toNullable()
fun getById(propertyId: UUID): Property =
findById(propertyId) ?: throw EntityNotFoundException(
"ENTITY NOT FOUND! query: property.id=$propertyId"
)
fun requireExists(propertyId: UUID): UUID =
if (exists(propertyId)) {
propertyId
} else throw EntityNotFoundException(
"ENTITY NOT FOUND! query: property.id=$propertyId"
)
fun requireDoesNotExist(propertyId: UUID): UUID =
if (!exists(propertyId)) {
propertyId
} else throw EntityAlreadyExistException(
"ENTITY ALREADY EXIST! query: property.id=$propertyId"
)
fun insert(@Valid property: Property): Property {
requireDoesNotExist(property.id)
return propertyRepository.save(property)
}
fun update(@Valid property: Property): Property {
requireExists(property.id)
return propertyRepository.save(property)
}
fun findByIdList(propertyIdList: List<UUID>): List<Property> {
val query = JPAQuery<Property>(entityManager)
val resultSet = query.from(qProperty)
.where(
qProperty.id.`in`(propertyIdList)
)
.fetchResults()
return resultSet.results
}
fun findByClusterId(clusterId: UUID): List<Property> {
val query = JPAQuery<Property>(entityManager)
val resultSet = query.from(qProperty)
.where(
qProperty.clusterId.eq(clusterId)
)
.fetchResults()
return resultSet.results
}
} | mit | c6455e92eb9a3903c8f7b7be2c93e68a | 34.207792 | 83 | 0.652399 | 5.046555 | false | false | false | false |
ligee/kotlin-jupyter | jupyter-lib/lib-ext/src/main/kotlin/org/jetbrains/kotlinx/jupyter/ext/graph/structure/UndirectedEdge.kt | 1 | 675 | package org.jetbrains.kotlinx.jupyter.ext.graph.structure
import org.jetbrains.kotlinx.jupyter.api.graphs.GraphNode
data class UndirectedEdge<out T>(
val fromNode: GraphNode<T>,
val toNode: GraphNode<T>,
) {
override fun equals(other: Any?): Boolean {
return other is UndirectedEdge<*> && (
(fromNode == other.fromNode) && (toNode == other.toNode) ||
(fromNode == other.toNode) && (toNode == other.fromNode)
)
}
override fun hashCode(): Int {
var h1 = fromNode.hashCode()
var h2 = toNode.hashCode()
if (h1 > h2) { val t = h2; h2 = h1; h1 = t }
return 31 * h1 + h2
}
}
| apache-2.0 | 33bf69ed2876e065b6ed983144a16651 | 29.681818 | 72 | 0.585185 | 3.515625 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/reflection/functions/declaredVsInheritedFunctions.kt | 1 | 2561 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
// FILE: J.java
public class J {
public void publicMemberJ() {}
private void privateMemberJ() {}
public static void publicStaticJ() {}
private static void privateStaticJ() {}
}
// FILE: K.kt
import kotlin.reflect.*
import kotlin.test.assertEquals
open class K : J() {
public fun publicMemberK() {}
private fun privateMemberK() {}
public fun Any.publicMemberExtensionK() {}
private fun Any.privateMemberExtensionK() {}
}
class L : K()
fun Collection<KFunction<*>>.names(): Set<String> =
this.map { it.name }.toSet()
fun check(c: Collection<KFunction<*>>, names: Set<String>) {
assertEquals(names, c.names())
}
fun box(): String {
val any = setOf("equals", "hashCode", "toString")
val j = J::class
check(j.staticFunctions,
setOf("publicStaticJ", "privateStaticJ"))
check(j.declaredFunctions,
setOf("publicMemberJ", "privateMemberJ", "publicStaticJ", "privateStaticJ"))
check(j.declaredMemberFunctions,
setOf("publicMemberJ", "privateMemberJ"))
check(j.declaredMemberExtensionFunctions,
emptySet())
check(j.functions, any + j.declaredFunctions.names())
check(j.memberFunctions, any + j.declaredMemberFunctions.names())
check(j.memberExtensionFunctions, emptySet())
val k = K::class
check(k.staticFunctions,
emptySet())
check(k.declaredFunctions,
setOf("publicMemberK", "privateMemberK", "publicMemberExtensionK", "privateMemberExtensionK"))
check(k.declaredMemberFunctions,
setOf("publicMemberK", "privateMemberK"))
check(k.declaredMemberExtensionFunctions,
setOf("publicMemberExtensionK", "privateMemberExtensionK"))
check(k.memberFunctions, any + setOf("publicMemberJ") + k.declaredMemberFunctions.names())
check(k.memberExtensionFunctions, k.declaredMemberExtensionFunctions.names())
check(k.functions, any + (k.memberFunctions + k.memberExtensionFunctions).names())
val l = L::class
check(l.staticFunctions, emptySet())
check(l.declaredFunctions, emptySet())
check(l.declaredMemberFunctions, emptySet())
check(l.declaredMemberExtensionFunctions, emptySet())
check(l.memberFunctions, any + setOf("publicMemberJ", "publicMemberK"))
check(l.memberExtensionFunctions, setOf("publicMemberExtensionK"))
check(l.functions, any + (l.memberFunctions + l.memberExtensionFunctions).names())
return "OK"
}
| apache-2.0 | 3230e4b9ad4aadb96108748c9cfbeecf | 31.0125 | 104 | 0.695431 | 4.423143 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/lower/Autoboxing.kt | 1 | 10155 | /*
* Copyright 2010-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.kotlin.backend.konan.lower
import org.jetbrains.kotlin.backend.common.AbstractValueUsageTransformer
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.descriptors.isSuspend
import org.jetbrains.kotlin.backend.konan.*
import org.jetbrains.kotlin.backend.konan.descriptors.target
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.declarations.IrFile
import org.jetbrains.kotlin.ir.declarations.IrFunction
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrCallImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrTypeOperatorCallImpl
import org.jetbrains.kotlin.ir.util.getPropertyGetter
import org.jetbrains.kotlin.ir.util.isNullConst
import org.jetbrains.kotlin.ir.util.render
import org.jetbrains.kotlin.ir.util.type
import org.jetbrains.kotlin.ir.visitors.transformChildrenVoid
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.makeNullable
/**
* Boxes and unboxes values of value types when necessary.
*/
internal class Autoboxing(val context: Context) : FileLoweringPass {
private val transformer = AutoboxingTransformer(context)
override fun lower(irFile: IrFile) {
irFile.transformChildrenVoid(transformer)
}
}
private class AutoboxingTransformer(val context: Context) : AbstractValueUsageTransformer(context.builtIns) {
val symbols = context.ir.symbols
// TODO: should we handle the cases when expression type
// is not equal to e.g. called function return type?
/**
* @return type to use for runtime type checks instead of given one (e.g. `IntBox` instead of `Int`)
*/
private fun getRuntimeReferenceType(type: KotlinType): KotlinType {
ValueType.values().forEach {
if (type.notNullableIsRepresentedAs(it)) {
return getBoxType(it).makeNullableAsSpecified(TypeUtils.isNullableType(type))
}
}
return type
}
override fun IrExpression.useInTypeOperator(operator: IrTypeOperator, typeOperand: KotlinType): IrExpression {
return if (operator == IrTypeOperator.IMPLICIT_COERCION_TO_UNIT ||
operator == IrTypeOperator.IMPLICIT_INTEGER_COERCION) {
this
} else {
// Codegen expects the argument of type-checking operator to be an object reference:
this.useAs(builtIns.nullableAnyType)
}
}
override fun visitTypeOperator(expression: IrTypeOperatorCall): IrExpression {
super.visitTypeOperator(expression).let {
// Assume that the transformer doesn't replace the entire expression for simplicity:
assert (it === expression)
}
val newTypeOperand = getRuntimeReferenceType(expression.typeOperand)
return when (expression.operator) {
IrTypeOperator.IMPLICIT_COERCION_TO_UNIT,
IrTypeOperator.IMPLICIT_INTEGER_COERCION -> expression
IrTypeOperator.CAST, IrTypeOperator.IMPLICIT_CAST,
IrTypeOperator.IMPLICIT_NOTNULL, IrTypeOperator.SAFE_CAST -> {
val newExpressionType = if (expression.operator == IrTypeOperator.SAFE_CAST) {
newTypeOperand.makeNullable()
} else {
newTypeOperand
}
IrTypeOperatorCallImpl(expression.startOffset, expression.endOffset,
newExpressionType, expression.operator, newTypeOperand,
expression.argument).useAs(expression.type)
}
IrTypeOperator.INSTANCEOF, IrTypeOperator.NOT_INSTANCEOF -> if (newTypeOperand == expression.typeOperand) {
// Do not create new expression if nothing changes:
expression
} else {
IrTypeOperatorCallImpl(expression.startOffset, expression.endOffset,
expression.type, expression.operator, newTypeOperand, expression.argument)
}
}
}
private var currentFunctionDescriptor: FunctionDescriptor? = null
override fun visitFunction(declaration: IrFunction): IrStatement {
currentFunctionDescriptor = declaration.descriptor
val result = super.visitFunction(declaration)
currentFunctionDescriptor = null
return result
}
override fun IrExpression.useAsReturnValue(returnTarget: CallableDescriptor): IrExpression {
if (returnTarget.isSuspend && returnTarget == currentFunctionDescriptor)
return this.useAs(context.builtIns.nullableAnyType)
val returnType = returnTarget.returnType
?: return this
return this.useAs(returnType)
}
override fun IrExpression.useAs(type: KotlinType): IrExpression {
val interop = context.interopBuiltIns
if (this.isNullConst() && interop.nullableInteropValueTypes.any { type.isRepresentedAs(it) }) {
return IrCallImpl(startOffset, endOffset, symbols.getNativeNullPtr).uncheckedCast(type)
}
val actualType = when (this) {
is IrCall -> {
if (this.descriptor.isSuspend) context.builtIns.nullableAnyType
else this.callTarget.returnType ?: this.type
}
is IrGetField -> this.descriptor.original.type
is IrTypeOperatorCall -> when (this.operator) {
IrTypeOperator.IMPLICIT_INTEGER_COERCION ->
// TODO: is it a workaround for inconsistent IR?
this.typeOperand
else -> this.type
}
else -> this.type
}
return this.adaptIfNecessary(actualType, type)
}
private val IrMemberAccessExpression.target: CallableDescriptor get() = when (this) {
is IrCall -> this.callTarget
is IrDelegatingConstructorCall -> this.descriptor.original
else -> TODO(this.render())
}
private val IrCall.callTarget: FunctionDescriptor
get() = if (superQualifier == null && descriptor.isOverridable) {
// A virtual call.
descriptor.original
} else {
descriptor.target
}
override fun IrExpression.useAsDispatchReceiver(expression: IrMemberAccessExpression): IrExpression {
return this.useAsArgument(expression.target.dispatchReceiverParameter!!)
}
override fun IrExpression.useAsExtensionReceiver(expression: IrMemberAccessExpression): IrExpression {
return this.useAsArgument(expression.target.extensionReceiverParameter!!)
}
override fun IrExpression.useAsValueArgument(expression: IrMemberAccessExpression,
parameter: ValueParameterDescriptor): IrExpression {
return this.useAsArgument(expression.target.valueParameters[parameter.index])
}
override fun IrExpression.useForField(field: PropertyDescriptor): IrExpression {
return this.useForVariable(field.original)
}
private fun IrExpression.adaptIfNecessary(actualType: KotlinType, expectedType: KotlinType): IrExpression {
val actualValueType = actualType.correspondingValueType
val expectedValueType = expectedType.correspondingValueType
return when {
actualValueType == expectedValueType -> this
actualValueType == null && expectedValueType != null -> {
// This may happen in the following cases:
// 1. `actualType` is `Nothing`;
// 2. `actualType` is incompatible.
this.unbox(expectedValueType)
}
actualValueType != null && expectedValueType == null -> this.box(actualValueType)
else -> throw IllegalArgumentException("actual type is $actualType, expected $expectedType")
}
}
/**
* Casts this expression to `type` without changing its representation in generated code.
*/
@Suppress("UNUSED_PARAMETER")
private fun IrExpression.uncheckedCast(type: KotlinType): IrExpression {
// TODO: apply some cast if types are incompatible; not required currently.
return this
}
private val ValueType.shortName
get() = this.classFqName.shortName()
private fun getBoxType(valueType: ValueType) =
context.getInternalClass("${valueType.shortName}Box").defaultType
private fun IrExpression.box(valueType: ValueType): IrExpression {
val boxFunction = symbols.boxFunctions[valueType]!!
return IrCallImpl(startOffset, endOffset, boxFunction).apply {
putValueArgument(0, this@box)
}.uncheckedCast(this.type) // Try not to bring new type incompatibilities.
}
private fun IrExpression.unbox(valueType: ValueType): IrExpression {
symbols.unboxFunctions[valueType]?.let {
return IrCallImpl(startOffset, endOffset, it).apply {
putValueArgument(0, [email protected](it.owner.valueParameters[0].type))
}.uncheckedCast(this.type)
}
val boxGetter = symbols.boxClasses[valueType]!!.getPropertyGetter("value")!!
return IrCallImpl(startOffset, endOffset, boxGetter).apply {
dispatchReceiver = [email protected](boxGetter.descriptor.dispatchReceiverParameter!!.type)
}.uncheckedCast(this.type) // Try not to bring new type incompatibilities.
}
}
| apache-2.0 | b1e9b5e4ed765a93ec82a04e6356b1cc | 38.980315 | 119 | 0.683998 | 5.199693 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/adaptive/ui/animations/SupportViewPropertyAnimator.kt | 2 | 1604 | package org.stepic.droid.adaptive.ui.animations
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.animation.TimeInterpolator
import android.view.View
class SupportViewPropertyAnimator(private val view: View) {
private val animators = ArrayList<Animator>()
private val set = AnimatorSet()
private var endAction: Runnable? = null
fun withEndAction(action: Runnable) = apply {
endAction = action
}
fun setInterpolator(interpolator: TimeInterpolator) = apply {
set.interpolator = interpolator
}
fun setStartDelay(duration: Long) = apply {
set.startDelay = duration
}
fun setDuration(duration: Long) = apply {
set.duration = duration
}
fun rotation(angle: Float) = apply {
animators.add(ObjectAnimator.ofFloat(view, View.ROTATION, angle))
}
fun translationX(value: Float) = apply {
animators.add(ObjectAnimator.ofFloat(view, View.TRANSLATION_X, value))
}
fun translationY(value: Float) = apply {
animators.add(ObjectAnimator.ofFloat(view, View.TRANSLATION_Y, value))
}
fun alpha(value: Float) = apply {
animators.add(ObjectAnimator.ofFloat(view, View.ALPHA, value))
}
fun start() = set.apply {
playTogether(animators)
addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator?) {
endAction?.run()
}
})
start()
}
} | apache-2.0 | 2dedcda90abebf78805d78d045c48be0 | 27.157895 | 78 | 0.675187 | 4.635838 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/step_quiz_review/ui/delegate/StepQuizReviewDelegate.kt | 1 | 17723 | package org.stepik.android.view.step_quiz_review.ui.delegate
import android.view.View
import android.view.ViewGroup
import androidx.annotation.PluralsRes
import androidx.annotation.StringRes
import androidx.core.view.isVisible
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.error_no_connection_with_button_small.view.*
import kotlinx.android.synthetic.main.fragment_step_quiz_review_peer.*
import kotlinx.android.synthetic.main.layout_step_quiz_review_footer.*
import kotlinx.android.synthetic.main.layout_step_quiz_review_header.*
import org.stepic.droid.R
import org.stepik.android.model.ReviewStrategyType
import org.stepik.android.model.Submission
import org.stepik.android.presentation.step_quiz.StepQuizFeature
import org.stepik.android.presentation.step_quiz_review.StepQuizReviewFeature
import org.stepik.android.view.progress.ui.mapper.ProgressTextMapper
import org.stepik.android.view.step_quiz.mapper.StepQuizFeedbackMapper
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizDelegate
import org.stepik.android.view.step_quiz.ui.delegate.StepQuizFeedbackBlocksDelegate
import org.stepik.android.view.step_quiz_review.ui.widget.ReviewStatusView
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import ru.nobird.android.core.model.safeCast
class StepQuizReviewDelegate(
override val containerView: View,
private val instructionType: ReviewStrategyType,
private val actionListener: ActionListener,
private val blockName: String?,
private val quizView: View,
private val quizDelegate: StepQuizDelegate,
private val quizFeedbackBlocksDelegate: StepQuizFeedbackBlocksDelegate
) : LayoutContainer {
private val stepQuizFeedbackMapper = StepQuizFeedbackMapper()
private val resources = containerView.resources
private val step1viewStateDelegate = ViewStateDelegate<StepQuizReviewFeature.State>()
.apply {
addState<StepQuizReviewFeature.State.SubmissionNotMade>(
reviewStep1DividerBottom, reviewStep1Container, reviewStep1Discounting,
reviewStep1ActionButton, reviewStep1ActionRetry
)
}
private val step1QuizViewStateDelegate = ViewStateDelegate<StepQuizFeature.State>()
.apply {
addState<StepQuizFeature.State.Loading>(stepQuizProgress)
addState<StepQuizFeature.State.AttemptLoading>(stepQuizProgress)
addState<StepQuizFeature.State.AttemptLoaded>(reviewStep1Discounting, reviewStep1QuizContainer, reviewStep1ActionButton, reviewStep1ActionRetry)
addState<StepQuizFeature.State.NetworkError>(stepQuizNetworkError)
}
private val step2viewStateDelegate = ViewStateDelegate<StepQuizReviewFeature.State>()
.apply {
addState<StepQuizReviewFeature.State.SubmissionNotSelected>(
reviewStep2DividerBottom, reviewStep2Container, reviewStep2Loading,
reviewStep2CreateSession, reviewStep2SelectSubmission, reviewStep2Retry
)
addState<StepQuizReviewFeature.State.SubmissionSelected>(reviewStep2DividerBottom, reviewStep2Container)
addState<StepQuizReviewFeature.State.Completed>(reviewStep2DividerBottom, reviewStep2Container)
}
init {
stepQuizNetworkError.tryAgain.setOnClickListener { actionListener.onQuizTryAgainClicked() }
reviewStep2SelectSubmission.setOnClickListener { actionListener.onSelectDifferentSubmissionClicked() }
reviewStep2CreateSession.setOnClickListener { actionListener.onCreateSessionClicked() }
reviewStep2Retry.setOnClickListener { actionListener.onSolveAgainClicked() }
if (instructionType == ReviewStrategyType.PEER) {
reviewStep3Container.setOnClickListener { actionListener.onStartReviewClicked() }
}
}
fun render(state: StepQuizReviewFeature.State) {
if (state is StepQuizReviewFeature.State.WithQuizState) {
quizFeedbackBlocksDelegate.setState(stepQuizFeedbackMapper.mapToStepQuizFeedbackState(blockName, state.quizState))
}
renderStep1(state)
renderStep2(state)
if (instructionType == ReviewStrategyType.PEER) {
renderStep3(state)
renderStep4(state)
}
renderStep5(state)
}
private fun renderStep1(state: StepQuizReviewFeature.State) {
step1viewStateDelegate.switchState(state)
when (state) {
is StepQuizReviewFeature.State.SubmissionNotMade -> {
val submissionStatus = state.quizState.safeCast<StepQuizFeature.State.AttemptLoaded>()
?.submissionState
?.safeCast<StepQuizFeature.SubmissionState.Loaded>()
?.submission
?.status
reviewStep1Status.status =
if (submissionStatus == Submission.Status.WRONG) {
ReviewStatusView.Status.ERROR
} else {
ReviewStatusView.Status.IN_PROGRESS
}
stepQuizDescription.isEnabled = true
step1QuizViewStateDelegate.switchState(state.quizState)
if (state.quizState is StepQuizFeature.State.AttemptLoaded) {
quizDelegate.setState(state.quizState)
}
setQuizViewParent(quizView, reviewStep1QuizContainer)
setQuizViewParent(quizFeedbackView, reviewStep1QuizContainer)
}
else -> {
stepQuizDescription.isEnabled = false
reviewStep1Status.status = ReviewStatusView.Status.COMPLETED
}
}
}
private fun renderStep2(state: StepQuizReviewFeature.State) {
step2viewStateDelegate.switchState(state)
when (state) {
is StepQuizReviewFeature.State.SubmissionNotMade -> {
reviewStep2Title.setText(R.string.step_quiz_review_send_pending)
setStepStatus(reviewStep2Title, reviewStep2Link, reviewStep2Status, ReviewStatusView.Status.PENDING)
}
is StepQuizReviewFeature.State.SubmissionNotSelected -> {
reviewStep2Title.setText(R.string.step_quiz_review_send_in_progress)
setStepStatus(reviewStep2Title, reviewStep2Link, reviewStep2Status, ReviewStatusView.Status.IN_PROGRESS)
quizDelegate.setState(state.quizState)
reviewStep2Loading.isVisible = state.isSessionCreationInProgress
reviewStep2CreateSession.isVisible = !state.isSessionCreationInProgress
reviewStep2SelectSubmission.isVisible = !state.isSessionCreationInProgress
reviewStep2Retry.isVisible = !state.isSessionCreationInProgress
setQuizViewParent(quizView, reviewStep2Container)
setQuizViewParent(quizFeedbackView, reviewStep2Container)
}
else -> {
reviewStep2Title.setText(R.string.step_quiz_review_send_completed)
setStepStatus(reviewStep2Title, reviewStep2Link, reviewStep2Status, ReviewStatusView.Status.COMPLETED)
state.safeCast<StepQuizReviewFeature.State.WithQuizState>()
?.quizState
?.safeCast<StepQuizFeature.State.AttemptLoaded>()
?.let(quizDelegate::setState)
setQuizViewParent(quizView, reviewStep2Container)
setQuizViewParent(quizFeedbackView, reviewStep2Container)
quizFeedbackView.isVisible = false
}
}
}
private fun setQuizViewParent(view: View, parent: ViewGroup) {
val currentParentViewGroup = view.parent.safeCast<ViewGroup>()
if (currentParentViewGroup == parent) return
currentParentViewGroup?.removeView(view)
parent.addView(view)
}
private fun renderStep3(state: StepQuizReviewFeature.State) {
val reviewCount = state.safeCast<StepQuizReviewFeature.State.WithInstruction>()?.instruction?.minReviews ?: 0
when (state) {
is StepQuizReviewFeature.State.SubmissionNotMade,
is StepQuizReviewFeature.State.SubmissionNotSelected -> {
reviewStep3Title.setText(R.string.step_quiz_review_given_pending_zero)
setStepStatus(reviewStep3Title, reviewStep3Link, reviewStep3Status, ReviewStatusView.Status.PENDING)
reviewStep3Container.isVisible = false
reviewStep3Loading.isVisible = false
}
is StepQuizReviewFeature.State.SubmissionSelected -> {
val givenReviewCount = state.session.givenReviews.size
val remainingReviewCount = reviewCount - givenReviewCount
val text =
buildString {
if (remainingReviewCount > 0) {
@PluralsRes
val pluralRes =
if (givenReviewCount > 0) {
R.plurals.step_quiz_review_given_in_progress
} else {
R.plurals.step_quiz_review_given_pending
}
append(resources.getQuantityString(pluralRes, remainingReviewCount, remainingReviewCount))
}
if (givenReviewCount > 0) {
if (isNotEmpty()) {
append(" ")
}
append(resources.getQuantityString(R.plurals.step_quiz_review_given_completed, givenReviewCount, givenReviewCount))
}
}
reviewStep3Title.text = text
reviewStep3Container.isVisible = remainingReviewCount > 0 && !state.isReviewCreationInProgress
if (reviewStep3Container.isVisible) {
reviewStep3Container.isEnabled = remainingReviewCount <= 0 || state.session.isReviewAvailable
reviewStep3Container.setText(if (reviewStep3Container.isEnabled) R.string.step_quiz_review_given_start_review else R.string.step_quiz_review_given_no_review)
}
reviewStep3Loading.isVisible = state.isReviewCreationInProgress
setStepStatus(reviewStep3Title, reviewStep3Link, reviewStep3Status, ReviewStatusView.Status.IN_PROGRESS)
}
is StepQuizReviewFeature.State.Completed -> {
val givenReviewCount = state.session.givenReviews.size
reviewStep3Title.text = resources.getQuantityString(R.plurals.step_quiz_review_given_completed, givenReviewCount, givenReviewCount)
reviewStep3Container.isVisible = false
reviewStep3Loading.isVisible = false
setStepStatus(reviewStep3Title, reviewStep3Link, reviewStep3Status, ReviewStatusView.Status.COMPLETED)
}
}
}
private fun renderStep4(state: StepQuizReviewFeature.State) {
val reviewCount = state.safeCast<StepQuizReviewFeature.State.WithInstruction>()?.instruction?.minReviews ?: 0
when (state) {
is StepQuizReviewFeature.State.SubmissionNotMade,
is StepQuizReviewFeature.State.SubmissionNotSelected -> {
reviewStep4Title.setText(R.string.step_quiz_review_taken_pending_zero)
setStepStatus(reviewStep4Title, reviewStep4Link, reviewStep4Status, ReviewStatusView.Status.PENDING)
reviewStep4Container.isVisible = false
reviewStep4Hint.isVisible = false
}
is StepQuizReviewFeature.State.SubmissionSelected -> {
val takenReviewCount = state.session.takenReviews.size
val remainingReviewCount = reviewCount - takenReviewCount
val text =
buildString {
if (remainingReviewCount > 0) {
@PluralsRes
val pluralRes =
if (takenReviewCount > 0) {
R.plurals.step_quiz_review_taken_in_progress
} else {
R.plurals.step_quiz_review_taken_pending
}
append(resources.getQuantityString(pluralRes, remainingReviewCount, remainingReviewCount))
}
if (takenReviewCount > 0) {
if (isNotEmpty()) {
append(" ")
}
append(resources.getQuantityString(R.plurals.step_quiz_review_taken_completed, takenReviewCount, takenReviewCount))
}
}
val status =
if (remainingReviewCount > 0) {
ReviewStatusView.Status.IN_PROGRESS
} else {
ReviewStatusView.Status.COMPLETED
}
reviewStep4Title.text = text
setStepStatus(reviewStep4Title, reviewStep4Link, reviewStep4Status, status)
reviewStep4Container.isVisible = takenReviewCount > 0
reviewStep4Container.setOnClickListener { actionListener.onTakenReviewClicked(state.session.id) }
reviewStep4Hint.isVisible = takenReviewCount == 0
}
is StepQuizReviewFeature.State.Completed -> {
val takenReviewCount = state.session.takenReviews.size
reviewStep4Title.text = resources.getQuantityString(R.plurals.step_quiz_review_taken_completed, takenReviewCount, takenReviewCount)
setStepStatus(reviewStep4Title, reviewStep4Link, reviewStep4Status, ReviewStatusView.Status.COMPLETED)
reviewStep4Container.isVisible = takenReviewCount > 0
reviewStep4Container.setOnClickListener { actionListener.onTakenReviewClicked(state.session.id) }
reviewStep4Hint.isVisible = false
}
}
}
private fun renderStep5(state: StepQuizReviewFeature.State) {
reviewStep5Status.position =
when (instructionType) {
ReviewStrategyType.PEER -> 5
ReviewStrategyType.INSTRUCTOR -> 3
}
when (state) {
is StepQuizReviewFeature.State.Completed -> {
val receivedPoints = state.progress?.score?.toFloatOrNull() ?: 0f
reviewStep5Title.text = ProgressTextMapper
.mapProgressToText(
containerView.context,
receivedPoints,
state.progress?.cost ?: 0,
R.string.step_quiz_review_peer_completed,
R.string.step_quiz_review_peer_completed,
R.plurals.points
)
when (instructionType) {
ReviewStrategyType.PEER ->
reviewStep5Container.isVisible = false
ReviewStrategyType.INSTRUCTOR -> {
reviewStep5Container.setOnClickListener { actionListener.onTakenReviewClicked(state.session.id) }
reviewStep5Container.isVisible = true
}
}
setStepStatus(reviewStep5Title, reviewStep5Link, reviewStep5Status, ReviewStatusView.Status.IN_PROGRESS)
reviewStep5Status.status = ReviewStatusView.Status.COMPLETED
reviewStep5Hint.isVisible = false
}
else -> {
val cost = state.safeCast<StepQuizReviewFeature.State.WithProgress>()?.progress?.cost ?: 0L
@StringRes
val stringRes =
when (instructionType) {
ReviewStrategyType.PEER ->
R.string.step_quiz_review_peer_pending
ReviewStrategyType.INSTRUCTOR ->
R.string.step_quiz_review_instructor_pending
}
reviewStep5Title.text = resources.getString(stringRes, resources.getQuantityString(R.plurals.points, cost.toInt(), cost))
reviewStep5Container.isVisible = false
val status =
if (state is StepQuizReviewFeature.State.SubmissionSelected && instructionType == ReviewStrategyType.INSTRUCTOR) {
ReviewStatusView.Status.IN_PROGRESS
} else {
ReviewStatusView.Status.PENDING
}
reviewStep5Hint.isVisible = instructionType == ReviewStrategyType.INSTRUCTOR && status == ReviewStatusView.Status.IN_PROGRESS
setStepStatus(reviewStep5Title, reviewStep5Link, reviewStep5Status, status)
}
}
}
private fun setStepStatus(titleView: View, linkView: View, statusView: ReviewStatusView, status: ReviewStatusView.Status) {
titleView.isEnabled = status == ReviewStatusView.Status.IN_PROGRESS
linkView.isEnabled = status.ordinal >= ReviewStatusView.Status.IN_PROGRESS.ordinal
statusView.status = status
}
interface ActionListener {
fun onSelectDifferentSubmissionClicked()
fun onCreateSessionClicked()
fun onSolveAgainClicked()
fun onQuizTryAgainClicked()
fun onStartReviewClicked()
fun onTakenReviewClicked(sessionId: Long)
}
} | apache-2.0 | 3565105ac8eceee7ec1930538ebfc5da | 46.645161 | 177 | 0.631609 | 5.88413 | false | false | false | false |
farmerbb/Notepad | app/src/main/java/com/farmerbb/notepad/ui/content/EditNoteContent.kt | 1 | 4109 | /* Copyright 2021 Braden Farmer
*
* 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.farmerbb.notepad.ui.content
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.text.BasicText
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.input.KeyboardCapitalization
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.farmerbb.notepad.R
import com.farmerbb.notepad.ui.components.RtlTextWrapper
import com.farmerbb.notepad.ui.previews.EditNotePreview
import kotlinx.coroutines.delay
private fun String.toTextFieldValue() = TextFieldValue(
text = this,
selection = TextRange(length)
)
@Composable
fun EditNoteContent(
text: String,
baseTextStyle: TextStyle = TextStyle(),
isLightTheme: Boolean = true,
isPrinting: Boolean = false,
waitForAnimation: Boolean = false,
rtlLayout: Boolean = false,
onTextChanged: (String) -> Unit = {}
) {
val textStyle = if (isPrinting) {
baseTextStyle.copy(color = Color.Black)
} else baseTextStyle
val focusRequester = remember { FocusRequester() }
var value by remember { mutableStateOf(text.toTextFieldValue()) }
LaunchedEffect(text) {
if (text != value.text) {
value = text.toTextFieldValue()
}
}
val brush = SolidColor(
value = when {
isPrinting -> Color.Transparent
isLightTheme -> Color.Black
else -> Color.White
}
)
RtlTextWrapper(text, rtlLayout) {
BasicTextField(
value = value,
onValueChange = {
value = it
onTextChanged(it.text)
},
textStyle = textStyle,
cursorBrush = brush,
keyboardOptions = KeyboardOptions(
capitalization = KeyboardCapitalization.Sentences
),
modifier = Modifier
.padding(
horizontal = 16.dp,
vertical = 12.dp
)
.fillMaxSize()
.focusRequester(focusRequester)
)
}
if(value.text.isEmpty()) {
BasicText(
text = stringResource(id = R.string.edit_text),
style = TextStyle(
fontSize = 16.sp,
color = Color.LightGray
),
modifier = Modifier
.padding(
horizontal = 16.dp,
vertical = 12.dp
)
)
}
LaunchedEffect(Unit) {
if (waitForAnimation) {
delay(200)
}
focusRequester.requestFocus()
}
}
@Preview
@Composable
fun EditNoteContentPreview() = EditNotePreview() | apache-2.0 | e8fa9bc3c2d7f147f3271c0398cb57d7 | 30.374046 | 75 | 0.667559 | 4.717566 | false | false | false | false |
dovydasvenckus/jFX-Console | src/main/kotlin/com/dovydasvenckus/jfxconsole/ui/JFXConsole.kt | 1 | 897 | package com.dovydasvenckus.jfxconsole.ui
import com.dovydasvenckus.jfxconsole.jmx.JMXConnector
import javafx.application.Application
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.stage.Stage
class JFXConsole : Application() {
var mainController: MainWindowController? = null
var connector: JMXConnector = JMXConnector("localhost", 1234)
override fun start(stage: Stage) {
val loader = FXMLLoader(javaClass.classLoader.getResource("templates/main.fxml"))
val root = loader.load<Parent>()
mainController = loader.getController()
val scene = Scene(root, 800.0, 800.0)
mainController!!.initTree(connector)
stage.title = "jFX Console!"
stage.scene = scene
stage.show()
}
fun init(args: Array<String>) {
launch(*args)
connector.close()
}
} | gpl-2.0 | eaba13ef7d94ad19d1401ac99519fa0f | 25.411765 | 89 | 0.693423 | 4.040541 | false | false | false | false |
Heiner1/AndroidAPS | core/src/main/java/info/nightscout/androidaps/plugins/constraints/versionChecker/VersionCheckerUtils.kt | 1 | 7286 | package info.nightscout.androidaps.plugins.constraints.versionChecker
import android.os.Build
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.interfaces.Config
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
import info.nightscout.androidaps.plugins.general.overview.notifications.Notification
import info.nightscout.androidaps.receivers.ReceiverStatusStore
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.sharedPreferences.SP
import java.io.IOException
import java.net.URL
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class VersionCheckerUtils @Inject constructor(
private val aapsLogger: AAPSLogger,
private val sp: SP,
private val rh: ResourceHelper,
private val rxBus: RxBus,
private val config: Config,
private val receiverStatusStore: ReceiverStatusStore,
private val dateUtil: DateUtil
) {
fun isConnected(): Boolean = receiverStatusStore.isConnected
fun triggerCheckVersion() {
if (!sp.contains(R.string.key_last_time_this_version_detected_as_ok)) {
// On a new installation, set it as 30 days old in order to warn that there is a new version.
sp.putLong(R.string.key_last_time_this_version_detected_as_ok, dateUtil.now() - TimeUnit.DAYS.toMillis(30))
}
// If we are good, only check once every day.
if (dateUtil.now() > sp.getLong(R.string.key_last_time_this_version_detected_as_ok, 0) + CHECK_EVERY) {
checkVersion()
}
}
private fun checkVersion() =
if (isConnected()) {
Thread {
try {
val definition: String = URL("https://raw.githubusercontent.com/nightscout/AndroidAPS/versions/definition.json").readText()
val version: String? = AllowedVersions().findByApi(definition, Build.VERSION.SDK_INT)?.optString("supported")
compareWithCurrentVersion(version, config.VERSION_NAME)
// App expiration
var endDate = sp.getLong(rh.gs(R.string.key_app_expiration) + "_" + config.VERSION_NAME, 0)
AllowedVersions().findByVersion(definition, config.VERSION_NAME)?.let { expirationJson ->
AllowedVersions().endDateToMilliseconds(expirationJson.getString("endDate"))?.let { ed ->
endDate = ed + T.days(1).msecs()
sp.putLong(rh.gs(R.string.key_app_expiration) + "_" + config.VERSION_NAME, endDate)
}
}
if (endDate != 0L) onExpireDateDetected(config.VERSION_NAME, dateUtil.dateString(endDate))
} catch (e: IOException) {
aapsLogger.error(LTag.CORE, "Github master version check error: $e")
}
}.start()
} else
aapsLogger.debug(LTag.CORE, "Github master version not checked. No connectivity")
@Suppress("SameParameterValue")
fun compareWithCurrentVersion(newVersion: String?, currentVersion: String) {
val newVersionElements = newVersion.toNumberList()
val currentVersionElements = currentVersion.toNumberList()
if (newVersionElements == null || newVersionElements.isEmpty()) {
onVersionNotDetectable()
return
}
if (currentVersionElements == null || currentVersionElements.isEmpty()) {
// current version scrambled?!
onNewVersionDetected(currentVersion, newVersion)
return
}
newVersionElements.take(3).forEachIndexed { i, newElem ->
val currElem: Int = currentVersionElements.getOrNull(i)
?: return onNewVersionDetected(currentVersion, newVersion)
(newElem - currElem).let {
when {
it > 0 -> return onNewVersionDetected(currentVersion, newVersion)
it < 0 -> return onOlderVersionDetected()
it == 0 -> Unit
}
}
}
onSameVersionDetected()
}
private fun onOlderVersionDetected() {
aapsLogger.debug(LTag.CORE, "Version newer than master. Are you developer?")
sp.putLong(R.string.key_last_time_this_version_detected_as_ok, dateUtil.now())
}
private fun onSameVersionDetected() {
sp.putLong(R.string.key_last_time_this_version_detected_as_ok, dateUtil.now())
}
private fun onVersionNotDetectable() {
aapsLogger.debug(LTag.CORE, "fetch failed")
}
private fun onNewVersionDetected(currentVersion: String, newVersion: String?) {
val now = dateUtil.now()
if (now > sp.getLong(R.string.key_last_versionchecker_warning, 0) + WARN_EVERY) {
aapsLogger.debug(LTag.CORE, "Version $currentVersion outdated. Found $newVersion")
rxBus.send(EventNewNotification(Notification(Notification.NEW_VERSION_DETECTED, rh.gs(R.string.versionavailable, newVersion.toString()), Notification.LOW)))
sp.putLong(R.string.key_last_versionchecker_warning, now)
}
}
private fun onExpireDateDetected(currentVersion: String, endDate: String?) {
val now = dateUtil.now()
if (now > sp.getLong(R.string.key_last_expired_versionchecker_warning, 0) + WARN_EVERY) {
aapsLogger.debug(LTag.CORE, rh.gs(R.string.version_expire, currentVersion, endDate))
rxBus.send(EventNewNotification(Notification(Notification.VERSION_EXPIRE, rh.gs(R.string.version_expire, currentVersion, endDate), Notification.LOW)))
sp.putLong(R.string.key_last_expired_versionchecker_warning, now)
}
}
private fun String?.toNumberList() =
this?.numericVersionPart().takeIf { !it.isNullOrBlank() }?.split(".")?.map { it.toInt() }
fun versionDigits(versionString: String?): IntArray {
val digits = mutableListOf<Int>()
versionString?.numericVersionPart().toNumberList()?.let {
digits.addAll(it.take(4))
}
return digits.toIntArray()
}
fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }
?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
}
companion object {
private val CHECK_EVERY = TimeUnit.DAYS.toMillis(1)
private val WARN_EVERY = TimeUnit.DAYS.toMillis(1)
}
}
fun String.numericVersionPart(): String =
"(((\\d+)\\.)+(\\d+))(\\D(.*))?".toRegex().matchEntire(this)?.groupValues?.getOrNull(1)
?: ""
@Suppress("unused") fun findVersion(file: String?): String? {
val regex = "(.*)version(.*)\"(((\\d+)\\.)+(\\d+))\"(.*)".toRegex()
return file?.lines()?.filter { regex.matches(it) }
?.mapNotNull { regex.matchEntire(it)?.groupValues?.getOrNull(3) }?.firstOrNull()
}
| agpl-3.0 | 9963746c87d76b753c83f5393921a2e1 | 42.369048 | 168 | 0.647131 | 4.55375 | false | false | false | false |
Heiner1/AndroidAPS | database/src/main/java/info/nightscout/androidaps/database/daos/ExtendedBolusDao.kt | 1 | 4432 | package info.nightscout.androidaps.database.daos
import androidx.room.Dao
import androidx.room.Query
import info.nightscout.androidaps.database.TABLE_CARBS
import info.nightscout.androidaps.database.TABLE_EXTENDED_BOLUSES
import info.nightscout.androidaps.database.embedments.InterfaceIDs
import info.nightscout.androidaps.database.entities.Carbs
import info.nightscout.androidaps.database.entities.ExtendedBolus
import io.reactivex.rxjava3.core.Maybe
import io.reactivex.rxjava3.core.Single
@Suppress("FunctionName")
@Dao
internal interface ExtendedBolusDao : TraceableDao<ExtendedBolus> {
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id = :id")
override fun findById(id: Long): ExtendedBolus?
@Query("DELETE FROM $TABLE_EXTENDED_BOLUSES")
override fun deleteAllEntries()
@Query("SELECT id FROM $TABLE_EXTENDED_BOLUSES ORDER BY id DESC limit 1")
fun getLastId(): Maybe<Long>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp = :timestamp AND referenceId IS NULL")
fun findByTimestamp(timestamp: Long): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE nightscoutId = :nsId AND referenceId IS NULL")
fun findByNSId(nsId: String): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE pumpId = :pumpId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL")
fun findByPumpIds(pumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE endId = :endPumpId AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL")
fun findByPumpEndIds(endPumpId: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp <= :timestamp AND (timestamp + duration) > :timestamp AND pumpType = :pumpType AND pumpSerial = :pumpSerial AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1")
fun getExtendedBolusActiveAt(timestamp: Long, pumpType: InterfaceIDs.PumpType, pumpSerial: String): Maybe<ExtendedBolus>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp <= :timestamp AND (timestamp + duration) > :timestamp AND referenceId IS NULL AND isValid = 1 ORDER BY timestamp DESC LIMIT 1")
fun getExtendedBolusActiveAt(timestamp: Long): Maybe<ExtendedBolus>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp >= :timestamp AND isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC")
fun getExtendedBolusDataFromTime(timestamp: Long): Single<List<ExtendedBolus>>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp >= :from AND timestamp <= :to AND isValid = 1 AND referenceId IS NULL ORDER BY timestamp ASC")
fun getExtendedBolusDataFromTimeToTime(from: Long, to: Long): Single<List<ExtendedBolus>>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp >= :timestamp AND referenceId IS NULL ORDER BY timestamp ASC")
fun getExtendedBolusDataIncludingInvalidFromTime(timestamp: Long): Single<List<ExtendedBolus>>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE timestamp >= :from AND timestamp <= :to AND referenceId IS NULL ORDER BY timestamp ASC")
fun getExtendedBolusDataIncludingInvalidFromTimeToTime(from: Long, to: Long): Single<List<ExtendedBolus>>
// This query will be used with v3 to get all changed records
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id > :id AND referenceId IS NULL OR id IN (SELECT DISTINCT referenceId FROM $TABLE_EXTENDED_BOLUSES WHERE id > :id) ORDER BY id ASC")
fun getModifiedFrom(id: Long): Single<List<ExtendedBolus>>
// for WS we need 1 record only
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id > :id ORDER BY id ASC limit 1")
fun getNextModifiedOrNewAfter(id: Long): Maybe<ExtendedBolus>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE id = :referenceId")
fun getCurrentFromHistoric(referenceId: Long): Maybe<ExtendedBolus>
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE isValid = 1 AND referenceId IS NULL ORDER BY id ASC LIMIT 1")
fun getOldestRecord(): ExtendedBolus?
@Query("SELECT * FROM $TABLE_EXTENDED_BOLUSES WHERE dateCreated > :since AND dateCreated <= :until LIMIT :limit OFFSET :offset")
suspend fun getNewEntriesSince(since: Long, until: Long, limit: Int, offset: Int): List<ExtendedBolus>
} | agpl-3.0 | 5da1754799ec3cb062d7188e9e319f7b | 59.726027 | 247 | 0.761507 | 4.531697 | false | false | false | false |
rolandvitezhu/TodoCloud | app/src/main/java/com/rolandvitezhu/todocloud/ui/activity/main/bindingutils/GeneralBindingUtils.kt | 1 | 3527 | package com.rolandvitezhu.todocloud.ui.activity.main.bindingutils
import android.annotation.SuppressLint
import android.content.res.ColorStateList
import android.text.Editable
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.inputmethod.EditorInfo
import android.widget.Button
import android.widget.ImageView
import android.widget.TextView
import androidx.appcompat.widget.AppCompatCheckBox
import androidx.databinding.BindingAdapter
import androidx.fragment.app.FragmentActivity
import com.google.android.material.textfield.TextInputEditText
import com.google.android.material.textfield.TextInputLayout
import com.rolandvitezhu.todocloud.R
@BindingAdapter("textChangedListener")
fun TextInputEditText.addTextChangedListener(fragmentActivity: FragmentActivity) {
var textInputLayout: TextInputLayout? = null
if (parent.parent is TextInputLayout)
textInputLayout = parent.parent as TextInputLayout
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
validateTitle(textInputLayout, text, fragmentActivity)
}
})
}
private fun validateTitle(textInputLayout: TextInputLayout?,
text: Editable?,
fragmentActivity: FragmentActivity) {
fragmentActivity.invalidateOptionsMenu()
if (text.isNullOrBlank())
textInputLayout?.error = textInputLayout?.context?.getString(R.string.all_entertitle)
else
textInputLayout?.isErrorEnabled = false
}
@BindingAdapter("emptyFieldValidator")
fun TextInputEditText.addEmptyFieldValidator(error: String) {
var textInputLayout: TextInputLayout? = null
if (parent.parent is TextInputLayout)
textInputLayout = parent.parent as TextInputLayout
addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {}
override fun afterTextChanged(s: Editable) {
validateField(text, textInputLayout, error)
}
})
}
private fun validateField(text: Editable?, textInputLayout: TextInputLayout?, error: String) {
if (text.isNullOrBlank())
textInputLayout?.error = error
else
textInputLayout?.isErrorEnabled = false
}
@BindingAdapter("doneButtonListener")
fun TextInputEditText.addDoneButtonListener(button: Button) {
setOnEditorActionListener(
TextView.OnEditorActionListener { v, actionId, event ->
val pressDone = actionId == EditorInfo.IME_ACTION_DONE
var pressEnter = false
if (event != null) {
val keyCode = event.keyCode
pressEnter = keyCode == KeyEvent.KEYCODE_ENTER
}
if (pressEnter || pressDone) {
button.performClick()
return@OnEditorActionListener true
}
false
})
}
@BindingAdapter("dynamicTint")
fun ImageView.setDynamicTint(color: Int) = setColorFilter(color)
@SuppressLint("RestrictedApi")
@BindingAdapter("dynamicButtonTint")
fun AppCompatCheckBox.setDynamicButtonTint(color: Int) {
supportButtonTintList = ColorStateList.valueOf(color)
} | mit | c1d966ce8780447d49f0f08aa0c667c3 | 37.347826 | 94 | 0.711653 | 5.256334 | false | false | false | false |
PolymerLabs/arcs | java/arcs/core/analysis/BoundedAbstractElement.kt | 1 | 3422 | /*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.analysis
/**
* A class that lifts any type [V] with a special bottom and top value.
*
* This class may be used to represent the elements of a lattice when implementing the
* [AbstractValue] interface. Specifically, it provides helpers for various methods in the
* [AbstractValue] interface that have well-known semantics with respect to bottom (the smallest
* value) and top (the largest value) in the lattice. For example, `bottom.join(other)` is always
* equal to `other` for any value of `other`, because `bottom` is the lowest value in the lattice.
*
* Here is a sample use of this class for implementing an abstract domain of integer elements,
* where the elements are ordered by [Int]'s `<=` operator.
* ```
* class IntegerDomain(
* val abstractInt: BoundedAbstractElement<Int>
* ) : AbstractValue<IntegerDomain> {
* override infix fun join(other: IntegerDomain): IntegerDomain {
* return abstractInt.join(other.abstractInt) { a, b -> maxOf(a, b) }
* }
* // . . .
* }
* ```
*/
data class BoundedAbstractElement<V : Any> private constructor(
private val kind: Kind,
val value: V?
) {
private enum class Kind { TOP, BOTTOM, VALUE }
/** True if this is top. */
val isTop: Boolean
get() = kind == Kind.TOP
/** True if this is bottom. */
val isBottom: Boolean
get() = kind == Kind.BOTTOM
/** A helper for implementing [AbstractValue.join]. */
fun join(other: BoundedAbstractElement<V>, joiner: (V, V) -> V): BoundedAbstractElement<V> {
return when (this.kind) {
Kind.BOTTOM -> other
Kind.TOP -> this /* returns top */
Kind.VALUE -> when (other.kind) {
Kind.VALUE -> makeValue(
joiner(requireNotNull(this.value), requireNotNull(other.value))
)
Kind.TOP -> other /* returns top */
Kind.BOTTOM -> this
}
}
}
/** A helper for implementing [AbstractValue.meet]. */
fun meet(other: BoundedAbstractElement<V>, meeter: (V, V) -> V): BoundedAbstractElement<V> {
return when (this.kind) {
Kind.BOTTOM -> this /* returns bottom */
Kind.TOP -> other
Kind.VALUE -> when (other.kind) {
Kind.VALUE -> makeValue(
meeter(requireNotNull(this.value), requireNotNull(other.value))
)
Kind.TOP -> this
Kind.BOTTOM -> other /* returns bottom */
}
}
}
/** A helper for implementing [AbstractValue.isEquivalentTo]. */
fun isEquivalentTo(
other: BoundedAbstractElement<V>,
comparator: (V, V) -> Boolean
) = when (kind) {
other.kind -> if (kind != Kind.VALUE) true else comparator(
requireNotNull(this.value), requireNotNull(other.value)
)
else -> false
}
companion object {
/** Returns a canonical top value. */
fun <V : Any> getTop() = BoundedAbstractElement<V>(Kind.TOP, null)
/** Returns a canonical bottom value. */
fun <V : Any> getBottom() = BoundedAbstractElement<V>(Kind.BOTTOM, null)
/** Returns an instance that wraps [value]. */
fun <V : Any> makeValue(value: V) = BoundedAbstractElement<V>(Kind.VALUE, value)
}
}
| bsd-3-clause | cbd16ff3be0534ad65b4fe1e89817fb9 | 32.881188 | 98 | 0.649912 | 3.988345 | false | false | false | false |
peterholak/graphql-ws-kotlin | src/test/kotlin/net/holak/graphql/ws/test/PublisherTests.kt | 1 | 4739 | package net.holak.graphql.ws.test
import com.nhaarman.mockito_kotlin.*
import graphql.ExecutionInput
import graphql.ExecutionResult
import graphql.GraphQL
import net.holak.graphql.ws.*
import org.eclipse.jetty.websocket.api.Session
import org.jetbrains.spek.api.Spek
import org.jetbrains.spek.api.dsl.describe
import org.jetbrains.spek.api.dsl.it
import org.junit.Assert.assertEquals
import org.junit.Assert.assertSame
import org.junit.platform.runner.JUnitPlatform
import org.junit.runner.RunWith
import org.mockito.ArgumentCaptor
@RunWith(JUnitPlatform::class)
object DefaultPublisherSpec : Spek({
class TransportCall(val session: Session, val data: Data)
@Suppress("unused")
val subject = {
object {
val graphQL = mock<GraphQL>()
val subscriptions = mock<Subscriptions<Session>>()
val transportCalls = mutableListOf<TransportCall>()
val transport: Transport<Session> = { session, data -> transportCalls.add(TransportCall(session, data)) }
val publisher = DefaultPublisher(graphQL, subscriptions, transport)
init {
whenever(graphQL.execute(any<ExecutionInput>())).thenReturn(MockGraphQLResult)
}
fun subscribeTheOnlyClient(id: String = "1"): Session {
val client = mock<Session>()
whenever(subscriptions.subscriptions)
.thenReturn(helloSubscriptionData(client, id))
whenever(subscriptions.subscriptionsByClient)
.thenReturn(helloSubscriptionByClientData(client, id))
return client
}
}
}
describe("publish") {
it("does nothing when no one is subscribed to the subscription name") { with(subject()) {
val client = mock<Session>()
whenever(subscriptions.subscriptions)
.thenReturn(mapOf("somethingElse" to listOf(Identifier(client, "1"))))
publisher.publish("hello")
verifyZeroInteractions(graphQL)
assertEquals(0, transportCalls.size)
}}
it("runs the query with the data as context") { with(subject()) {
subscribeTheOnlyClient()
publisher.publish("hello", "data")
val input = ArgumentCaptor.forClass(ExecutionInput::class.java)
verify(graphQL).execute(input.capture())
assertEquals("subscription { hello { text } }", input.value.query)
assertEquals("S", input.value.operationName)
assertEquals("data", input.value.context)
assertEquals(null, input.value.root)
assertEquals(mapOf("arg" to 1), input.value.variables)
}}
it("sends a GQL_DATA response") { with(subject()) {
val client = subscribeTheOnlyClient("3")
publisher.publish("hello")
assertEquals(1, transportCalls.size)
assertSame(client, transportCalls[0].session)
assertEquals(Type.GQL_DATA, transportCalls[0].data.type)
assertEquals("3", transportCalls[0].data.id)
}}
it("applies the filter") { with(subject()) {
subscribeTheOnlyClient()
publisher.publish("hello") {
false
}
assertEquals(0, transportCalls.size)
publisher.publish("hello") {
true
}
assertEquals(1, transportCalls.size)
}}
}
describe("inline publish version") {
it("infers the subscription name from the class name") {
data class HelloSubscription(val world: String)
val mockPublisher = mock<Publisher>()
mockPublisher.publish(HelloSubscription("world"))
verify(mockPublisher).publish("helloSubscription", HelloSubscription("world"))
}
}
})
fun helloSubscriptionData(client: Session, id: String) = mapOf(
"hello" to listOf(
Identifier(client, id)
)
)
fun helloSubscriptionByClientData(client: Session, id: String) = mapOf(
client to mapOf(id to Subscription(
client = client,
start = Start(id = id, payload = Start.Payload(
query = "subscription { hello { text } }",
operationName = "S",
variables = mapOf("arg" to 1)
)),
subscriptionName = "hello"
))
)
object MockGraphQLResult : ExecutionResult {
override fun toSpecification() = mapOf("data" to null, "errors" to null, "extensions" to null)
override fun getErrors() = null
override fun getExtensions() = null
override fun <T : Any?> getData(): T? = null
}
| mit | fcddfd059cd292e2c83aa9a265a74350 | 35.736434 | 117 | 0.609833 | 4.850563 | false | false | false | false |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/comments/unified/UnifiedCommentsEditViewModel.kt | 1 | 17421 | package org.wordpress.android.ui.comments.unified
import androidx.annotation.StringRes
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.delay
import kotlinx.coroutines.withContext
import org.wordpress.android.R
import org.wordpress.android.analytics.AnalyticsTracker.Stat.COMMENT_EDITED
import org.wordpress.android.datasets.wrappers.ReaderCommentTableWrapper
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity
import org.wordpress.android.fluxc.store.CommentsStore
import org.wordpress.android.models.usecases.LocalCommentCacheUpdateHandler
import org.wordpress.android.modules.BG_THREAD
import org.wordpress.android.modules.UI_THREAD
import org.wordpress.android.ui.comments.unified.CommentIdentifier.NotificationCommentIdentifier
import org.wordpress.android.ui.comments.unified.CommentIdentifier.ReaderCommentIdentifier
import org.wordpress.android.ui.comments.unified.CommentIdentifier.SiteCommentIdentifier
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.EditCommentActionEvent.CANCEL_EDIT_CONFIRM
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.EditCommentActionEvent.CLOSE
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.EditCommentActionEvent.DONE
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.FieldType.COMMENT
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.FieldType.USER_EMAIL
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.FieldType.USER_NAME
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.FieldType.WEB_ADDRESS
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.ProgressState.LOADING
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.ProgressState.NOT_VISIBLE
import org.wordpress.android.ui.comments.unified.UnifiedCommentsEditViewModel.ProgressState.SAVING
import org.wordpress.android.ui.comments.unified.extension.isNotEqualTo
import org.wordpress.android.ui.comments.unified.usecase.GetCommentUseCase
import org.wordpress.android.ui.notifications.utils.NotificationsActionsWrapper
import org.wordpress.android.ui.pages.SnackbarMessageHolder
import org.wordpress.android.ui.utils.UiString
import org.wordpress.android.ui.utils.UiString.UiStringRes
import org.wordpress.android.util.NetworkUtilsWrapper
import org.wordpress.android.util.analytics.AnalyticsUtils.AnalyticsCommentActionSource
import org.wordpress.android.util.analytics.AnalyticsUtilsWrapper
import org.wordpress.android.util.validateEmail
import org.wordpress.android.util.validateUrl
import org.wordpress.android.viewmodel.Event
import org.wordpress.android.viewmodel.ResourceProvider
import org.wordpress.android.viewmodel.ScopedViewModel
import javax.inject.Inject
import javax.inject.Named
class UnifiedCommentsEditViewModel @Inject constructor(
@Named(UI_THREAD) private val mainDispatcher: CoroutineDispatcher,
@Named(BG_THREAD) private val bgDispatcher: CoroutineDispatcher,
private val commentsStore: CommentsStore,
private val resourceProvider: ResourceProvider,
private val networkUtilsWrapper: NetworkUtilsWrapper,
private val localCommentCacheUpdateHandler: LocalCommentCacheUpdateHandler,
private val getCommentUseCase: GetCommentUseCase,
private val notificationActionsWrapper: NotificationsActionsWrapper,
private val readerCommentTableWrapper: ReaderCommentTableWrapper,
private val analyticsUtilsWrapper: AnalyticsUtilsWrapper
) : ScopedViewModel(mainDispatcher) {
private val _uiState = MutableLiveData<EditCommentUiState>()
private val _uiActionEvent = MutableLiveData<Event<EditCommentActionEvent>>()
private val _onSnackbarMessage = MutableLiveData<Event<SnackbarMessageHolder>>()
val uiState: LiveData<EditCommentUiState> = _uiState
val uiActionEvent: LiveData<Event<EditCommentActionEvent>> = _uiActionEvent
val onSnackbarMessage: LiveData<Event<SnackbarMessageHolder>> = _onSnackbarMessage
private var isStarted = false
private lateinit var site: SiteModel
private lateinit var commentIdentifier: CommentIdentifier
data class EditErrorStrings(
val userNameError: String? = null,
val commentTextError: String? = null,
val userUrlError: String? = null,
val userEmailError: String? = null
)
data class EditCommentUiState(
val canSaveChanges: Boolean,
val shouldInitComment: Boolean,
val shouldInitWatchers: Boolean,
val showProgress: Boolean = false,
val progressText: UiString? = null,
val originalComment: CommentEssentials,
val editedComment: CommentEssentials,
val editErrorStrings: EditErrorStrings,
val inputSettings: InputSettings
)
data class InputSettings(
val enableEditName: Boolean,
val enableEditUrl: Boolean,
val enableEditEmail: Boolean,
val enableEditComment: Boolean
)
enum class ProgressState(val show: Boolean, val progressText: UiString?) {
NOT_VISIBLE(false, null),
LOADING(true, UiStringRes(R.string.loading)),
SAVING(true, UiStringRes(R.string.saving_changes))
}
enum class FieldType(@StringRes val errorStringRes: Int, val isValid: (String) -> Boolean) {
USER_NAME(R.string.comment_edit_user_name_error, { isValidUserName(it) }),
USER_EMAIL(R.string.comment_edit_user_email_error, { isValidUserEmail(it) }),
WEB_ADDRESS(R.string.comment_edit_web_address_error, { isValidWebAddress(it) }),
COMMENT(R.string.comment_edit_comment_error, { isValidComment(it) });
// This is here for testing purposes
fun matches(expectedField: FieldType): Boolean {
return this == expectedField
}
companion object {
private fun isValidUserName(userName: String): Boolean {
return userName.isNotBlank()
}
private fun isValidUserEmail(email: String): Boolean {
return email.isBlank() || validateEmail(email)
}
private fun isValidWebAddress(url: String): Boolean {
return url.isBlank() || validateUrl(url)
}
private fun isValidComment(comment: String): Boolean {
return comment.isNotBlank()
}
}
}
enum class EditCommentActionEvent {
CLOSE,
DONE,
CANCEL_EDIT_CONFIRM
}
fun start(site: SiteModel, commentIdentifier: CommentIdentifier) {
if (isStarted) {
// If we are here, the fragment view was recreated (like in a configuration change)
// so we reattach the watchers.
_uiState.value = _uiState.value?.copy(shouldInitWatchers = true)
return
}
isStarted = true
this.site = site
this.commentIdentifier = commentIdentifier
initViews()
}
private suspend fun setLoadingState(state: ProgressState) {
val uiState = _uiState.value ?: EditCommentUiState(
canSaveChanges = false,
shouldInitComment = false,
shouldInitWatchers = false,
showProgress = LOADING.show,
progressText = LOADING.progressText,
originalComment = CommentEssentials(),
editedComment = CommentEssentials(),
editErrorStrings = EditErrorStrings(),
inputSettings = mapInputSettings(CommentEssentials())
)
withContext(mainDispatcher) {
_uiState.value = uiState.copy(
showProgress = state.show,
progressText = state.progressText
)
}
}
fun onActionMenuClicked() {
if (!networkUtilsWrapper.isNetworkAvailable()) {
_onSnackbarMessage.value = Event(SnackbarMessageHolder(UiStringRes(R.string.no_network_message)))
return
}
_uiState.value?.let { uiState ->
val editedCommentEssentials = uiState.editedComment
launch(bgDispatcher) {
setLoadingState(SAVING)
updateComment(editedCommentEssentials)
}
}
}
fun onBackPressed() {
_uiState.value?.let {
if (it.editedComment.isNotEqualTo(it.originalComment)) {
_uiActionEvent.value = Event(CANCEL_EDIT_CONFIRM)
} else {
_uiActionEvent.value = Event(CLOSE)
}
}
}
fun onConfirmEditingDiscard() {
_uiActionEvent.value = Event(CLOSE)
}
private fun initViews() {
launch {
setLoadingState(LOADING)
val commentEssentials = withContext(bgDispatcher) {
mapCommentEssentials()
}
if (commentEssentials.isValid()) {
_uiState.value =
EditCommentUiState(
canSaveChanges = false,
shouldInitComment = true,
shouldInitWatchers = true,
showProgress = LOADING.show,
progressText = LOADING.progressText,
originalComment = commentEssentials,
editedComment = commentEssentials,
editErrorStrings = EditErrorStrings(),
inputSettings = mapInputSettings(commentEssentials)
)
} else {
_onSnackbarMessage.value = Event(SnackbarMessageHolder(
message = UiStringRes(R.string.error_load_comment),
onDismissAction = { _uiActionEvent.value = Event(CLOSE) }
))
}
delay(LOADING_DELAY_MS)
setLoadingState(NOT_VISIBLE)
}
}
private suspend fun mapCommentEssentials(): CommentEssentials {
val commentEntity = getCommentUseCase.execute(site, commentIdentifier.remoteCommentId)
return if (commentEntity != null) {
CommentEssentials(
commentId = commentEntity.id,
userName = commentEntity.authorName ?: "",
commentText = commentEntity.content ?: "",
userUrl = commentEntity.authorUrl ?: "",
userEmail = commentEntity.authorEmail ?: "",
isFromRegisteredUser = commentEntity.authorId > 0
)
} else {
CommentEssentials()
}
}
private suspend fun updateComment(editedCommentEssentials: CommentEssentials) {
val commentEntity =
commentsStore.getCommentByLocalSiteAndRemoteId(site.id, commentIdentifier.remoteCommentId).firstOrNull()
commentEntity?.run {
val isCommentEntityUpdated = updateCommentEntity(this, editedCommentEssentials)
if (isCommentEntityUpdated) {
analyticsUtilsWrapper.trackCommentActionWithSiteDetails(
COMMENT_EDITED,
commentIdentifier.toCommentActionSource(),
site
)
when (commentIdentifier) {
is NotificationCommentIdentifier -> {
updateNotificationEntity()
}
is ReaderCommentIdentifier -> {
updateReaderEntity(editedCommentEssentials)
}
else -> {
_uiActionEvent.postValue(Event(DONE))
localCommentCacheUpdateHandler.requestCommentsUpdate()
}
}
} else {
showUpdateCommentError()
}
} ?: showUpdateCommentError()
}
private suspend fun updateCommentEntity(
comment: CommentEntity,
editedCommentEssentials: CommentEssentials
): Boolean {
val updatedComment = comment.copy(
authorUrl = editedCommentEssentials.userUrl,
authorName = editedCommentEssentials.userName,
authorEmail = editedCommentEssentials.userEmail,
content = editedCommentEssentials.commentText
)
val result = commentsStore.updateEditComment(site, updatedComment)
return !result.isError
}
private suspend fun updateNotificationEntity() {
with(commentIdentifier as NotificationCommentIdentifier) {
val isNotificationEntityUpdated = notificationActionsWrapper.downloadNoteAndUpdateDB(noteId)
if (isNotificationEntityUpdated) {
_uiActionEvent.postValue(Event(DONE))
localCommentCacheUpdateHandler.requestCommentsUpdate()
} else {
showUpdateNotificationError()
}
}
}
private suspend fun updateReaderEntity(commentEssentials: CommentEssentials) {
val readerCommentIdentifier = commentIdentifier as ReaderCommentIdentifier
val readerComment = readerCommentTableWrapper.getComment(
site.siteId,
readerCommentIdentifier.postId,
readerCommentIdentifier.remoteCommentId
)
readerComment?.apply {
text = commentEssentials.commentText
authorName = commentEssentials.userName
authorEmail = commentEssentials.userEmail
authorUrl = commentEssentials.userUrl
readerCommentTableWrapper.addOrUpdateComment(readerComment)
}
_uiActionEvent.postValue(Event(DONE))
localCommentCacheUpdateHandler.requestCommentsUpdate()
}
private suspend fun showUpdateCommentError() {
setLoadingState(NOT_VISIBLE)
_onSnackbarMessage.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.error_edit_comment)))
)
}
private suspend fun showUpdateNotificationError() {
setLoadingState(NOT_VISIBLE)
_onSnackbarMessage.postValue(
Event(SnackbarMessageHolder(UiStringRes(R.string.error_edit_notification)))
)
}
fun onValidateField(field: String, fieldType: FieldType) {
_uiState.value?.let {
val fieldError = if (fieldType.isValid.invoke(field)) {
null
} else {
resourceProvider.getString(fieldType.errorStringRes)
}
val previousComment = it.editedComment
val previousErrors = it.editErrorStrings
val editedComment = previousComment.copy(
userName = if (fieldType.matches(USER_NAME)) field else previousComment.userName,
commentText = if (fieldType.matches(COMMENT)) field else previousComment.commentText,
userUrl = if (fieldType.matches(WEB_ADDRESS)) field else previousComment.userUrl,
userEmail = if (fieldType.matches(USER_EMAIL)) field else previousComment.userEmail
)
val errors = previousErrors.copy(
userNameError = if (fieldType.matches(USER_NAME)) fieldError else previousErrors.userNameError,
commentTextError = if (fieldType.matches(COMMENT)) fieldError else previousErrors.commentTextError,
userUrlError = if (fieldType.matches(WEB_ADDRESS)) fieldError else previousErrors.userUrlError,
userEmailError = if (fieldType.matches(USER_EMAIL)) fieldError else previousErrors.userEmailError
)
_uiState.value = it.copy(
canSaveChanges = editedComment.isNotEqualTo(it.originalComment) && !errors.hasError(),
shouldInitComment = false,
shouldInitWatchers = false,
editedComment = editedComment,
editErrorStrings = errors
)
}
}
private fun mapInputSettings(commentEssentials: CommentEssentials) = InputSettings(
enableEditName = !commentEssentials.isFromRegisteredUser,
enableEditUrl = !commentEssentials.isFromRegisteredUser,
enableEditEmail = !commentEssentials.isFromRegisteredUser,
enableEditComment = true
)
private fun EditErrorStrings.hasError(): Boolean {
return listOf(
this.commentTextError,
this.userEmailError,
this.userNameError,
this.userUrlError
).any { !it.isNullOrEmpty() }
}
private fun CommentIdentifier.toCommentActionSource(): AnalyticsCommentActionSource {
return when (this) {
is NotificationCommentIdentifier -> {
AnalyticsCommentActionSource.NOTIFICATIONS
}
is ReaderCommentIdentifier -> {
AnalyticsCommentActionSource.READER
}
is SiteCommentIdentifier -> {
AnalyticsCommentActionSource.SITE_COMMENTS
}
}
}
companion object {
private const val LOADING_DELAY_MS = 300L
}
}
| gpl-2.0 | d8654012e8957ed8d3d7c34074840bec | 41.490244 | 120 | 0.65731 | 5.834226 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.