repo_name
stringlengths 7
79
| path
stringlengths 8
206
| copies
stringclasses 36
values | size
stringlengths 2
6
| content
stringlengths 55
523k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 7.18
99.5
| line_max
int64 16
979
| alpha_frac
float64 0.3
0.87
| ratio
float64 2.01
8.07
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
siosio/intellij-community | plugins/kotlin/analysis/src/org/jetbrains/kotlin/idea/klib/KlibMetadataDecompiler.kt | 1 | 5807 | // 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.klib
import com.intellij.openapi.fileTypes.FileType
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiManager
import com.intellij.psi.compiled.ClassFileDecompilers
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.idea.decompiler.KotlinDecompiledFileViewProvider
import org.jetbrains.kotlin.idea.decompiler.common.createIncompatibleAbiVersionDecompiledText
import org.jetbrains.kotlin.idea.decompiler.textBuilder.DecompiledText
import org.jetbrains.kotlin.idea.decompiler.textBuilder.buildDecompiledText
import org.jetbrains.kotlin.idea.decompiler.textBuilder.defaultDecompilerRendererOptions
import org.jetbrains.kotlin.library.metadata.KlibMetadataProtoBuf
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.BinaryVersion
import org.jetbrains.kotlin.metadata.deserialization.NameResolverImpl
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.serialization.SerializerExtensionProtocol
import org.jetbrains.kotlin.serialization.deserialization.ClassDeserializer
import org.jetbrains.kotlin.serialization.deserialization.FlexibleTypeDeserializer
import org.jetbrains.kotlin.serialization.deserialization.getClassId
import org.jetbrains.kotlin.utils.addIfNotNull
import java.io.IOException
abstract class KlibMetadataDecompiler<out V : BinaryVersion>(
private val fileType: FileType,
private val serializerProtocol: () -> SerializerExtensionProtocol,
private val flexibleTypeDeserializer: FlexibleTypeDeserializer,
private val expectedBinaryVersion: () -> V,
private val invalidBinaryVersion: () -> V,
stubVersion: Int
) : ClassFileDecompilers.Full() {
private val metadataStubBuilder: KlibMetadataStubBuilder =
KlibMetadataStubBuilder(
stubVersion,
fileType,
serializerProtocol,
::readFileSafely
)
private val renderer: DescriptorRenderer by lazy {
DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() }
}
protected abstract fun doReadFile(file: VirtualFile): FileWithMetadata?
override fun accepts(file: VirtualFile) = file.fileType == fileType
override fun getStubBuilder() = metadataStubBuilder
override fun createFileViewProvider(file: VirtualFile, manager: PsiManager, physical: Boolean) =
KotlinDecompiledFileViewProvider(manager, file, physical) { provider ->
KlibDecompiledFile(
provider,
::buildDecompiledText
)
}
private fun readFileSafely(file: VirtualFile): FileWithMetadata? {
if (!file.isValid) return null
return try {
doReadFile(file)
} catch (e: IOException) {
// This is needed because sometimes we're given VirtualFile instances that point to non-existent .jar entries.
// Such files are valid (isValid() returns true), but an attempt to read their contents results in a FileNotFoundException.
// Note that although calling "refresh()" instead of catching an exception would seem more correct here,
// it's not always allowed and also is likely to degrade performance
null
}
}
private fun buildDecompiledText(virtualFile: VirtualFile): DecompiledText {
assert(virtualFile.fileType == fileType) { "Unexpected file type ${virtualFile.fileType}" }
return when (val file = readFileSafely(virtualFile)) {
is FileWithMetadata.Incompatible -> createIncompatibleAbiVersionDecompiledText(expectedBinaryVersion(), file.version)
is FileWithMetadata.Compatible -> decompiledText(
file,
serializerProtocol(),
flexibleTypeDeserializer,
renderer
)
null -> createIncompatibleAbiVersionDecompiledText(expectedBinaryVersion(), invalidBinaryVersion())
}
}
}
sealed class FileWithMetadata {
class Incompatible(val version: BinaryVersion) : FileWithMetadata()
open class Compatible(val proto: ProtoBuf.PackageFragment) : FileWithMetadata() {
val nameResolver = NameResolverImpl(proto.strings, proto.qualifiedNames)
val packageFqName = FqName(proto.getExtension(KlibMetadataProtoBuf.fqName))
open val classesToDecompile: List<ProtoBuf.Class> =
proto.class_List.filter { proto ->
val classId = nameResolver.getClassId(proto.fqName)
!classId.isNestedClass && classId !in ClassDeserializer.BLACK_LIST
}
}
}
//todo: this function is extracted for KotlinNativeMetadataStubBuilder, that's the difference from Big Kotlin.
fun decompiledText(
file: FileWithMetadata.Compatible,
serializerProtocol: SerializerExtensionProtocol,
flexibleTypeDeserializer: FlexibleTypeDeserializer,
renderer: DescriptorRenderer
): DecompiledText {
val packageFqName = file.packageFqName
val resolver = KlibMetadataDeserializerForDecompiler(
packageFqName, file.proto, file.nameResolver,
serializerProtocol, flexibleTypeDeserializer
)
val declarations = arrayListOf<DeclarationDescriptor>()
declarations.addAll(resolver.resolveDeclarationsInFacade(packageFqName))
for (classProto in file.classesToDecompile) {
val classId = file.nameResolver.getClassId(classProto.fqName)
declarations.addIfNotNull(resolver.resolveTopLevelClass(classId))
}
return buildDecompiledText(packageFqName, declarations, renderer)
}
| apache-2.0 | 09528354bcb0938fe060e5c61bcd1e0b | 44.724409 | 158 | 0.747718 | 5.567593 | false | false | false | false |
jwren/intellij-community | plugins/kotlin/jvm/src/org/jetbrains/kotlin/idea/run/KotlinFE10MainFunctionLocatingService.kt | 1 | 1435 | package org.jetbrains.kotlin.idea.run
import org.jetbrains.kotlin.idea.MainFunctionDetector
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.caches.resolve.safeAnalyzeNonSourceRootCode
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
internal class KotlinFE10MainFunctionLocatingService : KotlinMainFunctionLocatingService {
override fun isMain(function: KtNamedFunction): Boolean {
val bindingContext =
function.safeAnalyzeNonSourceRootCode(BodyResolveMode.FULL).takeIf { it != BindingContext.EMPTY } ?: return false
val mainFunctionDetector = MainFunctionDetector(bindingContext, function.languageVersionSettings)
return mainFunctionDetector.isMain(function)
}
override fun hasMain(declarations: List<KtDeclaration>): Boolean {
if (declarations.isEmpty()) return false
val languageVersionSettings = declarations.first().languageVersionSettings
val mainFunctionDetector =
MainFunctionDetector(languageVersionSettings) { it.resolveToDescriptorIfAny(BodyResolveMode.FULL) }
return declarations.any { it is KtNamedFunction && mainFunctionDetector.isMain(it) }
}
} | apache-2.0 | a43c775295ebc9962bc7eae0e0a8ab61 | 48.517241 | 125 | 0.8 | 5.519231 | false | false | false | false |
vovagrechka/fucking-everything | phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/codeInsight/typing/PyTypeShed.kt | 1 | 4802 | /*
* Copyright 2000-2016 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 vgrechka.phizdetsidea.phizdets.codeInsight.typing
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.QualifiedName
import vgrechka.phizdetsidea.phizdets.PhizdetsHelpersLocator
import vgrechka.phizdetsidea.phizdets.packaging.PyPIPackageUtil
import vgrechka.phizdetsidea.phizdets.packaging.PyPackageManagers
import vgrechka.phizdetsidea.phizdets.packaging.PyPackageUtil
import vgrechka.phizdetsidea.phizdets.psi.LanguageLevel
import vgrechka.phizdetsidea.phizdets.sdk.PhizdetsSdkType
import java.io.File
/**
* Utilities for managing the local copy of the typeshed repository.
*
* The original Git repo is located [here](https://github.com/JetBrains/typeshed).
*
* @author vlan
*/
object PyTypeShed {
private val ONLY_SUPPORTED_PY2_MINOR = 7
private val SUPPORTED_PY3_MINORS = 2..6
// TODO: Warn about unresolved `import typing` but still resolve it internally for type inference
val WHITE_LIST = setOf("typing", "six", "__builtin__", "builtins", "exceptions", "types")
private val BLACK_LIST = setOf<String>()
/**
* Returns true if we allow to search typeshed for a stub for [name].
*/
fun maySearchForStubInRoot(name: QualifiedName, root: VirtualFile, sdk : Sdk): Boolean {
val topLevelPackage = name.firstComponent ?: return false
if (topLevelPackage in BLACK_LIST) {
return false
}
if (topLevelPackage !in WHITE_LIST) {
return false
}
if (isInStandardLibrary(root)) {
return true
}
if (isInThirdPartyLibraries(root)) {
val pyPIPackage = PyPIPackageUtil.PACKAGES_TOPLEVEL[topLevelPackage] ?: topLevelPackage
val packages = PyPackageManagers.getInstance().forSdk(sdk).packages ?: return true
return PyPackageUtil.findPackage(packages, pyPIPackage) != null
}
return false
}
/**
* Returns the list of roots in typeshed for the Phizdets language level of [sdk].
*/
fun findRootsForSdk(sdk: Sdk): List<VirtualFile> {
val level = PhizdetsSdkType.getLanguageLevelForSdk(sdk)
val dir = directory ?: return emptyList()
return findRootsForLanguageLevel(level)
.asSequence()
.map { dir.findFileByRelativePath(it) }
.filterNotNull()
.toList()
}
/**
* Returns the list of roots in typeshed for the specified Phizdets language [level].
*/
fun findRootsForLanguageLevel(level: LanguageLevel): List<String> {
val minor = when (level.major) {
2 -> ONLY_SUPPORTED_PY2_MINOR
3 -> Math.min(Math.max(level.minor, SUPPORTED_PY3_MINORS.start), SUPPORTED_PY3_MINORS.endInclusive)
else -> return emptyList()
}
return listOf("stdlib/${level.major}.${minor}",
"stdlib/${level.major}",
"stdlib/2and3",
"third_party/${level.major}",
"third_party/2and3")
}
/**
* Checks if the [file] is located inside the typeshed directory.
*/
fun isInside(file: VirtualFile): Boolean {
val dir = directory
return dir != null && VfsUtilCore.isAncestor(dir, file, true)
}
/**
* The actual typeshed directory.
*/
val directory: VirtualFile? by lazy {
val path = directoryPath ?: return@lazy null
StandardFileSystems.local().findFileByPath(path)
}
val directoryPath: String?
get() {
val paths = listOf("${PathManager.getConfigPath()}/typeshed",
"${PathManager.getConfigPath()}/../typeshed",
PhizdetsHelpersLocator.getHelperPath("typeshed"))
return paths.asSequence()
.filter { File(it).exists() }
.firstOrNull()
}
/**
* A shallow check for a [file] being located inside the typeshed third-party stubs.
*/
fun isInThirdPartyLibraries(file: VirtualFile) = "third_party" in file.path
private fun isInStandardLibrary(file: VirtualFile) = "stdlib" in file.path
private val LanguageLevel.major: Int
get() = this.version / 10
private val LanguageLevel.minor: Int
get() = this.version % 10
}
| apache-2.0 | 2ce249ff0edf0eb29b414a7a71f3d860 | 34.57037 | 105 | 0.699084 | 4.377393 | false | false | false | false |
androidx/androidx | compose/integration-tests/demos/src/main/java/androidx/compose/integration/demos/settings/SoftInputModeSetting.kt | 3 | 3839 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.integration.demos.settings
import android.content.Context
import android.view.Window
import android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN
import android.view.WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE
import androidx.compose.integration.demos.settings.SoftInputMode.AdjustPan
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.withFrameMillis
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.lifecycle.Lifecycle.State.RESUMED
import androidx.lifecycle.repeatOnLifecycle
import androidx.preference.DropDownPreference
import androidx.preference.Preference.SummaryProvider
internal enum class SoftInputMode(val flagValue: Int, val summary: String) {
@Suppress("DEPRECATION")
AdjustResize(
SOFT_INPUT_ADJUST_RESIZE,
summary = "The content view will resize to accommodate the IME.",
),
AdjustPan(
SOFT_INPUT_ADJUST_PAN,
summary = "The content view will pan up to accommodate the IME.",
),
}
/**
* Setting that determines which soft input mode the demo activity's window is configured with.
*/
internal object SoftInputModeSetting : DemoSetting<SoftInputMode> {
private const val Key = "softInputMode"
override fun createPreference(context: Context) = DropDownPreference(context).apply {
title = "Soft input mode"
key = Key
SoftInputMode.values().map { it.name }.toTypedArray().also {
entries = it
entryValues = it
}
summaryProvider = SummaryProvider<DropDownPreference> {
val mode = SoftInputMode.valueOf(value)
"""
${mode.name}
${mode.summary}
""".trimIndent()
}
setDefaultValue(AdjustPan.name)
}
@Composable
fun asState() = preferenceAsState(Key) {
val value = getString(Key, AdjustPan.name) ?: AdjustPan.name
SoftInputMode.valueOf(value)
}
}
/**
* Sets the window's [softInputMode][android.view.Window.setSoftInputMode] to [mode] as long as this
* function is composed.
*/
@Composable
internal fun SoftInputModeEffect(mode: SoftInputMode, window: Window) {
val updatedMode by rememberUpdatedState(mode)
val lifecycle = LocalLifecycleOwner.current
LaunchedEffect(lifecycle, window) {
lifecycle.repeatOnLifecycle(RESUMED) {
// During the first frame, the window may have its soft input mode set to a special
// "forwarding input" mode. After the first frame, it will be reset to whatever is in
// the theme. If we set the value during the first frame, it will get immediately
// cleared, so wait until the second frame to set it. This is super hacky but no real
// app should need to dynamically change its soft input mode like we do.
withFrameMillis {}
snapshotFlow { updatedMode }.collect { mode ->
window.setSoftInputMode(mode.flagValue)
}
}
}
} | apache-2.0 | ba1f9b7f172eeb15b935406da760f9b3 | 37.787879 | 100 | 0.710341 | 4.64208 | false | false | false | false |
GunoH/intellij-community | python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyModuleNameCompletionContributor.kt | 8 | 4408 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.completion
import com.intellij.codeInsight.completion.CompletionContributor
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.completion.PrioritizedLookupElement
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.openapi.project.DumbAware
import com.intellij.psi.MultiplePsiFilesPerDocumentFileViewProvider
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.QualifiedName
import com.intellij.util.ProcessingContext
import com.jetbrains.python.PyNames
import com.jetbrains.python.PythonRuntimeService
import com.jetbrains.python.codeInsight.completion.PythonCompletionWeigher.NOT_IMPORTED_MODULE_WEIGHT
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyImportStatementBase
import com.jetbrains.python.psi.PyReferenceExpression
import com.jetbrains.python.psi.resolve.fromFoothold
import com.jetbrains.python.psi.resolve.resolveQualifiedName
import com.jetbrains.python.psi.types.PyModuleType
import com.jetbrains.python.psi.types.PyType
import org.jetbrains.annotations.TestOnly
/**
* Adds completion variants for modules and packages, inserts a dot after and calls completion on the result,
* see [PyUnresolvedModuleAttributeCompletionContributor]
*/
class PyModuleNameCompletionContributor : CompletionContributor(), DumbAware {
companion object {
// temporary solution for tests that are not prepared for module name completion firing everywhere
@TestOnly
@JvmField
var ENABLED = true
}
/**
* Checks whether completion should be performed for a given [parameters] and delegates actual work to [doFillCompletionVariants].
*/
override fun fillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet) {
if (!shouldDoCompletion(parameters)) return
val otherVariants = mutableSetOf<String>()
result.runRemainingContributors(parameters) {
otherVariants.add(it.lookupElement.lookupString)
result.passResult(it)
}
doFillCompletionVariants(parameters, result, otherVariants)
}
private fun doFillCompletionVariants(parameters: CompletionParameters, result: CompletionResultSet, otherVariants: Set<String>) {
getCompletionVariants(parameters.position.parent, parameters.originalFile, otherVariants).asSequence()
.filterIsInstance<LookupElement>()
.filterNot { it.lookupString.startsWith('_') }
.filter { result.prefixMatcher.isStartMatch(it) }
.forEach { result.addElement(PrioritizedLookupElement.withPriority(it, NOT_IMPORTED_MODULE_WEIGHT.toDouble())) }
}
private fun getCompletionVariants(element: PsiElement, file: PsiElement, otherVariants: Set<String>): List<Any> {
val alreadyAddedNames = HashSet<String>(otherVariants)
val result = ArrayList<Any>()
resolveQualifiedName(QualifiedName.fromComponents(), fromFoothold(file))
.asSequence()
.filterIsInstance<PsiDirectory>()
.forEach {
val initPy = it.findFile(PyNames.INIT_DOT_PY)
if (initPy is PyFile) {
val moduleType = PyModuleType(initPy)
val context = ProcessingContext()
context.put(PyType.CTX_NAMES, alreadyAddedNames)
val completionVariants = moduleType.getCompletionVariants("", element, context)
result.addAll(listOf(*completionVariants))
}
else {
result.addAll(PyModuleType.getSubModuleVariants(it, element, alreadyAddedNames))
}
}
return result
}
private fun shouldDoCompletion(parameters: CompletionParameters): Boolean {
if (!ENABLED || PythonRuntimeService.getInstance().isInPydevConsole(parameters.originalFile)) {
return false
}
val element = parameters.position
val parent = element.parent
val provider = element.containingFile.viewProvider
if (provider is MultiplePsiFilesPerDocumentFileViewProvider) {
return false
}
return parent is PyReferenceExpression
&& !parent.isQualified
&& PsiTreeUtil.getParentOfType(element, PyImportStatementBase::class.java) == null
}
}
| apache-2.0 | 657119e9784edcbbb5c972cc3b1375a0 | 42.215686 | 140 | 0.773593 | 4.859978 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/transformers/interceptors/Interceptor.kt | 4 | 3897 | // 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.tools.projectWizard.transformers.interceptors
import org.jetbrains.kotlin.tools.projectWizard.Identificator
import org.jetbrains.kotlin.tools.projectWizard.ir.buildsystem.BuildFileIR
import org.jetbrains.kotlin.tools.projectWizard.templates.Template
import org.jetbrains.kotlin.tools.projectWizard.transformers.Predicate
import org.jetbrains.kotlin.tools.projectWizard.transformers.TransformerFunction
interface Interceptor
typealias InterceptionPointValues = Map<InterceptionPoint<Any>, Any>
typealias SourcesetInterceptionPointValues = Map<Identificator, InterceptionPointValues>
data class TemplateInterceptionApplicationState(
val buildFileIR: BuildFileIR,
val moduleToSettings: SourcesetInterceptionPointValues
)
data class TemplateInterceptor(
val template: Template,
val applicabilityCheckers: List<Predicate<BuildFileIR>>,
val buildFileTransformers: List<TransformerFunction<BuildFileIR>>,
val interceptionPointModifiers: List<InterceptionPointModifier<Any>>
) : Interceptor {
fun applyTo(state: TemplateInterceptionApplicationState): TemplateInterceptionApplicationState {
if (applicabilityCheckers.any { checker -> !checker(state.buildFileIR) }) return state
val modulesWithTemplate = state.buildFileIR.modules.modules.filter { it.template?.id == template.id }
if (modulesWithTemplate.isEmpty()) return state
val transformedBuildFile = applyBuildFileTransformers(state.buildFileIR)
val mutableValues = state.moduleToSettings.toMutableMap()
for (module in modulesWithTemplate) {
mutableValues.compute(module.originalModule.identificator) { _, values ->
applyInterceptionPointModifiers(values.orEmpty())
}
}
return TemplateInterceptionApplicationState(transformedBuildFile, mutableValues)
}
private fun applyInterceptionPointModifiers(values: InterceptionPointValues): InterceptionPointValues {
val mutableValues = values.toMutableMap()
for (modifier in interceptionPointModifiers) {
mutableValues.compute(modifier.point) { _, value ->
modifier.modifier(value ?: modifier.point.initialValue)
}
}
return mutableValues
}
private fun applyBuildFileTransformers(buildFile: BuildFileIR): BuildFileIR =
buildFileTransformers.fold(buildFile) { result, transformer ->
transformer(result) ?: result
}
}
fun List<TemplateInterceptor>.applyAll(state: TemplateInterceptionApplicationState) =
fold(state) { currentState, interceptor ->
interceptor.applyTo(currentState)
}
class TemplateInterceptorBuilder<T : Template>(val template: T) {
private val buildFileTransformers = mutableListOf<TransformerFunction<BuildFileIR>>()
fun transformBuildFile(transform: TransformerFunction<BuildFileIR>) {
buildFileTransformers += transform
}
private val applicabilityCheckers = mutableListOf<Predicate<BuildFileIR>>()
fun applicableIf(checker: Predicate<BuildFileIR>) {
applicabilityCheckers += checker
}
private val interceptionPointModifiers = mutableListOf<InterceptionPointModifier<Any>>()
fun <T : Any> interceptAtPoint(point: InterceptionPoint<T>, modifier: (T) -> T) {
interceptionPointModifiers.add(InterceptionPointModifier(point, modifier))
}
fun build() = TemplateInterceptor(
template,
applicabilityCheckers,
buildFileTransformers,
interceptionPointModifiers
)
}
fun <T : Template> interceptTemplate(template: T, builder: TemplateInterceptorBuilder<T>.() -> Unit) =
TemplateInterceptorBuilder(template).apply(builder).build() | apache-2.0 | db2cb8aafd9575debf2e53fac36b4d70 | 40.913978 | 158 | 0.752374 | 5.047927 | false | false | false | false |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/statistics/VcsOptionsUsagesCollector.kt | 4 | 8309 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.statistics
import com.intellij.ide.util.PropertiesComponent
import com.intellij.internal.statistic.beans.*
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventId1
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.*
import com.intellij.openapi.vcs.ignore.IgnoredToExcludedSynchronizerConstants.ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY
import org.jetbrains.annotations.NonNls
import java.util.*
@NonNls
class VcsOptionsUsagesCollector : ProjectUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
override fun getMetrics(project: Project): MutableSet<MetricEvent> {
val set = HashSet<MetricEvent>()
val conf = VcsConfiguration.getInstance(project)
val confDefault = VcsConfiguration()
addConfirmationIfDiffers(set, conf, confDefault, { it.REMOVE_EMPTY_INACTIVE_CHANGELISTS }, OFFER_REMOVE_EMPTY_CHANGELIST)
addBoolIfDiffers(set, conf, confDefault, { it.MAKE_NEW_CHANGELIST_ACTIVE }, CHANGELIST_MAKE_NEW_ACTIVE)
addBoolIfDiffers(set, conf, confDefault, { it.PRESELECT_EXISTING_CHANGELIST }, CHANGELIST_PRESELECT_EXISTING)
addBoolIfDiffers(set, conf, confDefault, { it.CHECK_CODE_SMELLS_BEFORE_PROJECT_COMMIT }, COMMIT_BEFORE_CHECK_CODE_SMELL)
addBoolIfDiffers(set, conf, confDefault, { it.CHECK_CODE_CLEANUP_BEFORE_PROJECT_COMMIT }, COMMIT_BEFORE_CHECK_CODE_CLEANUP)
addBoolIfDiffers(set, conf, confDefault, { it.CHECK_NEW_TODO }, COMMIT_BEFORE_CHECK_TODO)
addBoolIfDiffers(set, conf, confDefault, { it.OPTIMIZE_IMPORTS_BEFORE_PROJECT_COMMIT }, COMMIT_BEFORE_OPTIMIZE_IMPORTS)
addBoolIfDiffers(set, conf, confDefault, { it.REFORMAT_BEFORE_PROJECT_COMMIT }, COMMIT_BEFORE_REFORMAT_PROJECT)
addBoolIfDiffers(set, conf, confDefault, { it.REARRANGE_BEFORE_PROJECT_COMMIT }, COMMIT_BEFORE_REARRANGE)
addBoolIfDiffers(set, conf, confDefault, { it.CLEAR_INITIAL_COMMIT_MESSAGE }, COMMIT_CLEAR_INITIAL_COMMENT)
addBoolIfDiffers(set, conf, confDefault, { it.USE_COMMIT_MESSAGE_MARGIN }, COMMIT_USE_RIGHT_MARGIN)
addBoolIfDiffers(set, conf, confDefault, { it.LOCAL_CHANGES_DETAILS_PREVIEW_SHOWN }, SHOW_CHANGES_PREVIEW)
addBoolIfDiffers(set, conf, confDefault, { it.INCLUDE_TEXT_INTO_SHELF }, INCLUDE_TEXT_INTO_SHELF)
addBoolIfDiffers(set, conf, confDefault, { it.CHECK_LOCALLY_CHANGED_CONFLICTS_IN_BACKGROUND }, CHECK_CONFLICTS_IN_BACKGROUND)
addExternalFilesActionsStatistics(project, set, conf, confDefault)
addProjectConfigurationFilesActionsStatistics(project, set)
addIgnoredToExcludeSynchronizerActionsStatistics(project, set)
return set
}
private fun addIgnoredToExcludeSynchronizerActionsStatistics(project: Project, set: HashSet<MetricEvent>) {
addBooleanPropertyIfDiffers(project, set, ASKED_MARK_IGNORED_FILES_AS_EXCLUDED_PROPERTY, false, ASKED_ADD_EXTERNAL_FILES)
}
private fun addProjectConfigurationFilesActionsStatistics(project: Project, set: HashSet<MetricEvent>) {
//SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY can be set automatically to true without ASKED_SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY
//Such case should be filtered in order to check only a user manual interaction.
val askedToShare = booleanPropertyIfDiffers(project, ASKED_SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY, false)
if (askedToShare != null) {
if (!addBooleanPropertyIfDiffers(project, set, SHARE_PROJECT_CONFIGURATION_FILES_PROPERTY, false, SHARE_PROJECT_CONFIGURATION_FILES)) {
set.add(ASKED_SHARE_PROJECT_CONFIGURATION_FILES.metric(askedToShare))
}
}
}
private fun addExternalFilesActionsStatistics(project: Project, set: HashSet<MetricEvent>, conf: VcsConfiguration, confDefault: VcsConfiguration) {
addBoolIfDiffers(set, conf, confDefault, { it.ADD_EXTERNAL_FILES_SILENTLY }, ADD_EXTERNAL_FILES_SILENTLY)
if (!conf.ADD_EXTERNAL_FILES_SILENTLY) {
addBooleanPropertyIfDiffers(project, set, ASKED_ADD_EXTERNAL_FILES_PROPERTY, false, ASKED_ADD_EXTERNAL_FILES)
}
}
private fun addBooleanPropertyIfDiffers(project: Project, set: HashSet<MetricEvent>,
property: String, defaultValue: Boolean, eventId: EventId1<Boolean>): Boolean {
val value = booleanPropertyIfDiffers(project, property, defaultValue)
if (value != null) {
return set.add(eventId.metric(value))
}
return false
}
private fun booleanPropertyIfDiffers(project: Project, property: String, defaultValue: Boolean): Boolean? {
val value = PropertiesComponent.getInstance(project).getBoolean(property, defaultValue)
return if (value != defaultValue) value else null
}
companion object {
private val GROUP = EventLogGroup("vcs.settings", 4)
private val OFFER_REMOVE_EMPTY_CHANGELIST = GROUP.registerEvent("offer.remove.empty.changelist", EventFields.Enum("value", ConfirmationOption::class.java))
private val CHANGELIST_MAKE_NEW_ACTIVE = GROUP.registerVarargEvent("changelist.make.new.active", EventFields.Enabled)
private val CHANGELIST_PRESELECT_EXISTING = GROUP.registerVarargEvent("changelist.preselect.existing", EventFields.Enabled)
private val COMMIT_BEFORE_CHECK_CODE_SMELL = GROUP.registerVarargEvent("commit.before.check.code.smell", EventFields.Enabled)
private val COMMIT_BEFORE_CHECK_CODE_CLEANUP = GROUP.registerVarargEvent("commit.before.check.code.cleanup", EventFields.Enabled)
private val COMMIT_BEFORE_CHECK_TODO = GROUP.registerVarargEvent("commit.before.check.todo", EventFields.Enabled)
private val COMMIT_BEFORE_OPTIMIZE_IMPORTS = GROUP.registerVarargEvent("commit.before.optimize.imports", EventFields.Enabled)
private val COMMIT_BEFORE_REFORMAT_PROJECT = GROUP.registerVarargEvent("commit.before.reformat.project", EventFields.Enabled)
private val COMMIT_BEFORE_REARRANGE = GROUP.registerVarargEvent("commit.before.rearrange", EventFields.Enabled)
private val COMMIT_CLEAR_INITIAL_COMMENT = GROUP.registerVarargEvent("commit.clear.initial.comment", EventFields.Enabled)
private val COMMIT_USE_RIGHT_MARGIN = GROUP.registerVarargEvent("commit.use.right.margin", EventFields.Enabled)
private val SHOW_CHANGES_PREVIEW = GROUP.registerVarargEvent("show.changes.preview", EventFields.Enabled)
private val INCLUDE_TEXT_INTO_SHELF = GROUP.registerVarargEvent("include.text.into.shelf", EventFields.Enabled)
private val CHECK_CONFLICTS_IN_BACKGROUND = GROUP.registerVarargEvent("check.conflicts.in.background", EventFields.Enabled)
private val ADD_EXTERNAL_FILES_SILENTLY = GROUP.registerVarargEvent("add.external.files.silently", EventFields.Enabled)
private val ASKED_ADD_EXTERNAL_FILES = GROUP.registerEvent("asked.add.external.files", EventFields.Enabled)
private val SHARE_PROJECT_CONFIGURATION_FILES = GROUP.registerEvent("share.project.configuration.files", EventFields.Enabled)
private val ASKED_SHARE_PROJECT_CONFIGURATION_FILES = GROUP.registerEvent("asked.share.project.configuration.files", EventFields.Enabled)
private fun <T> addConfirmationIfDiffers(set: MutableSet<in MetricEvent>, settingsBean: T, defaultSettingsBean: T,
valueFunction: Function1<T, VcsShowConfirmationOption.Value>, eventId: EventId1<ConfirmationOption>) {
addMetricIfDiffers(set, settingsBean, defaultSettingsBean, valueFunction) {
val value = when (it) {
VcsShowConfirmationOption.Value.SHOW_CONFIRMATION -> ConfirmationOption.ask // NON-NLS
VcsShowConfirmationOption.Value.DO_NOTHING_SILENTLY -> ConfirmationOption.disabled // NON-NLS
VcsShowConfirmationOption.Value.DO_ACTION_SILENTLY -> ConfirmationOption.silently // NON-NLS
else -> ConfirmationOption.unknown // NON-NLS
}
return@addMetricIfDiffers eventId.metric(value)
}
}
@Suppress("EnumEntryName")
private enum class ConfirmationOption {
ask, disabled, silently, unknown
}
}
}
| apache-2.0 | 4514ee463970b114ca0f78f9f72a935d | 62.915385 | 159 | 0.772175 | 4.234964 | false | true | false | false |
GunoH/intellij-community | plugins/search-everywhere-ml/src/com/intellij/ide/actions/searcheverywhere/ml/features/statistician/SearchEverywhereStatisticianService.kt | 7 | 1287 | package com.intellij.ide.actions.searcheverywhere.ml.features.statistician
import com.intellij.openapi.components.Service
import com.intellij.openapi.util.Key
import com.intellij.psi.statistics.StatisticsManager
@Service(Service.Level.APP)
class SearchEverywhereStatisticianService {
companion object {
val KEY: Key<SearchEverywhereStatistician<in Any>> = Key.create("searchEverywhere")
}
fun increaseUseCount(element: Any) = getSerializedInfo(element)?.let { StatisticsManager.getInstance().incUseCount(it) }
fun getCombinedStats(element: Any): SearchEverywhereStatisticianStats? {
val statisticsManager = StatisticsManager.getInstance()
val info = getSerializedInfo(element) ?: return null
val allValues = statisticsManager.getAllValues(info.context).associateWith { statisticsManager.getUseCount(it) }
val useCount = allValues.entries.firstOrNull { it.key.value == info.value }?.value ?: 0
val isMostPopular = useCount > 0 && useCount == allValues.maxOf { it.value }
val recency = statisticsManager.getLastUseRecency(info)
return SearchEverywhereStatisticianStats(useCount, isMostPopular, recency)
}
private fun getSerializedInfo(element: Any) = StatisticsManager.serialize(KEY, element, "") // location is obtained from element
}
| apache-2.0 | 043c2f0605a996aa58bdf0934e506f20 | 43.37931 | 131 | 0.781663 | 4.453287 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/highlighter/markers/JavaPsiUtils.kt | 2 | 1972 | // 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.highlighter.markers
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.CommonClassNames
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.caches.lightClasses.KtFakeLightClass
import org.jetbrains.kotlin.idea.caches.lightClasses.KtFakeLightMethod
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtNamedFunction
import org.jetbrains.kotlin.psi.KtSecondaryConstructor
fun collectContainingClasses(methods: Collection<PsiMethod>): Set<PsiClass> {
val classes = HashSet<PsiClass>()
for (method in methods) {
ProgressManager.checkCanceled()
val parentClass = method.containingClass
if (parentClass != null && CommonClassNames.JAVA_LANG_OBJECT != parentClass.qualifiedName) {
classes.add(parentClass)
}
}
return classes
}
internal tailrec fun getPsiClass(element: PsiElement?): PsiClass? {
return when {
element == null -> null
element is PsiClass -> element
element is KtClass -> element.toLightClass() ?: KtFakeLightClass(element)
element.parent is KtClass -> getPsiClass(element.parent)
else -> null
}
}
internal fun getPsiMethod(element: PsiElement?): PsiMethod? {
val parent = element?.parent
return when {
element == null -> null
element is PsiMethod -> element
parent is KtNamedFunction || parent is KtSecondaryConstructor ->
LightClassUtil.getLightClassMethod(parent as KtFunction) ?: KtFakeLightMethod.get(parent)
else -> null
}
}
| apache-2.0 | cad92f80cc4f80374e1359f78d58a561 | 37.666667 | 158 | 0.741379 | 4.695238 | false | false | false | false |
juzraai/ted-xml-model | src/main/kotlin/hu/juzraai/ted/xml/model/tedexport/CodedDataSection.kt | 1 | 667 | package hu.juzraai.ted.xml.model.tedexport
import hu.juzraai.ted.xml.model.tedexport.coded.CodifData
import hu.juzraai.ted.xml.model.tedexport.coded.NoticeData
import hu.juzraai.ted.xml.model.tedexport.coded.RefOjs
import org.simpleframework.xml.Element
import org.simpleframework.xml.Root
/**
* Model of CODED_DATA_SECTION element.
*
* @author Zsolt Jurányi
*/
@Root(name = "CODED_DATA_SECTION")
data class CodedDataSection(
@field:Element(name = "REF_OJS")
var refOjs: RefOjs = RefOjs(),
@field:Element(name = "NOTICE_DATA")
var noticeData: NoticeData = NoticeData(),
@field:Element(name = "CODIF_DATA")
var codifData: CodifData = CodifData()
) | apache-2.0 | 7000ddf92cac43ce2a26227350181aba | 26.791667 | 58 | 0.750751 | 2.810127 | false | false | false | false |
aosp-mirror/platform_frameworks_support | core/ktx/src/main/java/androidx/core/util/Range.kt | 1 | 2038 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("NOTHING_TO_INLINE") // Aliases to public API.
package androidx.core.util
import android.util.Range
import androidx.annotation.RequiresApi
/**
* Creates a range from this [Comparable] value to [that].
*
* @throws IllegalArgumentException if this value is comparatively smaller than [that].
*/
@RequiresApi(21)
inline infix fun <T : Comparable<T>> T.rangeTo(that: T): Range<T> = Range(this, that)
/** Return the smallest range that includes this and [value]. */
@RequiresApi(21)
inline operator fun <T : Comparable<T>> Range<T>.plus(value: T): Range<T> = extend(value)
/** Return the smallest range that includes this and [other]. */
@RequiresApi(21)
inline operator fun <T : Comparable<T>> Range<T>.plus(other: Range<T>): Range<T> = extend(other)
/**
* Return the intersection of this range and [other].
*
* @throws IllegalArgumentException if this is disjoint from [other].
*/
@RequiresApi(21)
inline infix fun <T : Comparable<T>> Range<T>.and(other: Range<T>): Range<T> = intersect(other)
/** Returns this [Range] as a [ClosedRange]. */
@RequiresApi(21)
fun <T : Comparable<T>> Range<T>.toClosedRange(): ClosedRange<T> = object : ClosedRange<T> {
override val endInclusive get() = upper
override val start get() = lower
}
/** Returns this [ClosedRange] as a [Range]. */
@RequiresApi(21)
fun <T : Comparable<T>> ClosedRange<T>.toRange(): Range<T> = Range(start, endInclusive)
| apache-2.0 | 151b9c919fddce80f58833bf074753c9 | 34.754386 | 96 | 0.713445 | 3.69873 | false | false | false | false |
JakeWharton/dex-method-list | diffuse/src/main/kotlin/com/jakewharton/diffuse/report/text/AabDiffTextReport.kt | 1 | 2536 | package com.jakewharton.diffuse.report.text
import com.jakewharton.diffuse.diff.AabDiff
import com.jakewharton.diffuse.diff.toDetailReport
import com.jakewharton.diffuse.diffuseTable
import com.jakewharton.diffuse.report.DiffReport
import com.jakewharton.picnic.TextAlignment.BottomLeft
import com.jakewharton.picnic.TextAlignment.MiddleCenter
import com.jakewharton.picnic.TextAlignment.MiddleRight
internal class AabDiffTextReport(private val aabDiff: AabDiff) : DiffReport {
override fun write(appendable: Appendable) {
appendable.apply {
append("OLD: ")
appendln(aabDiff.oldAab.filename)
append("NEW: ")
appendln(aabDiff.newAab.filename)
appendln()
appendln(diffuseTable {
cellStyle {
alignment = MiddleCenter
}
header {
cellStyle {
alignment = BottomLeft
}
row {
cell("MODULES")
cell("old")
cell("new")
}
}
row {
cell("base") {
alignment = MiddleRight
}
cell("✓")
cell("✓")
}
for (name in aabDiff.featureModuleNames) {
row {
cell(name) {
alignment = MiddleRight
}
cell(if (name in aabDiff.oldAab.featureModules) "✓" else "")
cell(if (name in aabDiff.newAab.featureModules) "✓" else "")
}
}
}.toString())
// TODO base module
for (name in (aabDiff.featureModuleNames - aabDiff.removedFeatureModules.keys)) {
appendln()
appendln()
appendln("==============${"=".repeat(name.length)}")
appendln("==== $name ====")
appendln("==============${"=".repeat(name.length)}")
appendln()
val addedModule = aabDiff.addedFeatureModules[name]
val changedModule = aabDiff.changedFeatureModules[name]
assert((addedModule != null) xor (changedModule != null))
if (addedModule != null) {
// TODO
}
if (changedModule != null) {
if (changedModule.archive.changed) {
appendln(changedModule.archive.toDetailReport())
}
if (changedModule.dex.changed) {
appendln(changedModule.dex.toDetailReport())
}
if (changedModule.manifest.changed) {
appendln(changedModule.manifest.toDetailReport())
}
}
}
}
}
override fun toString() = buildString { write(this) }
}
| apache-2.0 | 73afe1beae4c004aeded62b50ec3f363 | 27.404494 | 87 | 0.571598 | 4.450704 | false | false | false | false |
KotlinThree/kotlin_zhihu | app/src/main/java/io/kotlinthree/ui/NewsListActivity.kt | 1 | 2797 | package io.kotlinthree.ui
import android.os.Bundle
import android.support.v4.widget.SwipeRefreshLayout
import android.view.View
import android.widget.AdapterView
import android.widget.ListView
import io.kotlinthree.R
import io.kotlinthree.api.ApiUtil
import io.kotlinthree.api.News
import io.kotlinthree.api.NewsListData
import io.kotlinthree.extension.addPair
import io.kotlinthree.extension.findView
import io.kotlinthree.extension.showToast
import io.kotlinthree.extension.start
import io.kotlinthree.ui.base.BaseActivity
import io.kotlinthree.util.DateUtil
import io.kotlinthree.util.LogUtils
import retrofit.Callback
import retrofit.Response
import retrofit.Retrofit
import java.util.*
/**
* Created by jameson on 12/19/15.
*/
class NewsListActivity : BaseActivity(), AdapterView.OnItemClickListener, SwipeRefreshLayout.OnRefreshListener {
private lateinit var mSwipeRefreshLayout: SwipeRefreshLayout
private lateinit var mListView: ListView
private lateinit var mAdapter: NewsListAdapter
private var mList: List<News> = ArrayList()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_news_list)
initViews()
loadData()
}
private fun initViews() {
mSwipeRefreshLayout = findView<SwipeRefreshLayout>(R.id.swipeRefreshLayout)
mListView = findView<ListView>(R.id.listView)
mAdapter = NewsListAdapter(this, mList)
mListView.adapter = mAdapter
mListView.onItemClickListener = this
mSwipeRefreshLayout.setOnRefreshListener(this)
}
private fun loadData() {
val date = DateUtil.getDateStr(System.currentTimeMillis(), "yyyyMMdd")
val call = ApiUtil.getService().listNews(date)
call.enqueue(object : Callback<NewsListData> {
override fun onResponse(response: Response<NewsListData>, retrofit: Retrofit) {
mSwipeRefreshLayout.isRefreshing = false
val statusCode = response.code()
LogUtils.i(statusCode.toString())
if (response.isSuccess) {
mList = response.body().stories
mAdapter.notifyDataSetChanged(mList)
}
}
override fun onFailure(t: Throwable) {
mSwipeRefreshLayout.isRefreshing = false
if (t.message != null) {
showToast(t.message.toString())
}
}
})
}
override fun onRefresh() {
mListView.postDelayed({ loadData() }, 1000)
}
override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
start<NewsDetailActivity>(Bundle().addPair("news_id", mList[position].id))
}
}
| apache-2.0 | a5c2e43bbec494556367c4f67aa0cfb7 | 32.698795 | 112 | 0.684662 | 4.976868 | false | false | false | false |
wuan/bo-android | app/src/main/java/org/blitzortung/android/app/controller/ButtonColumnHandler.kt | 1 | 2274 | /*
Copyright 2015 Andreas Würl
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.blitzortung.android.app.controller
import android.view.View
import android.widget.RelativeLayout
import org.blitzortung.android.app.helper.ViewHelper.pxFromSp
class ButtonColumnHandler<V : View, G : Enum<G>>(private val buttonSize: Float) {
data class GroupedView<V, G>(val view: V, val groups: Set<G>) {
}
private val elements: MutableList<GroupedView<V, G>>
init {
elements = arrayListOf()
}
fun addElement(element: V, vararg groups: G) {
elements.add(GroupedView(element, groups.toSet()))
}
fun addAllElements(elements: Collection<V>, vararg groups: G) {
this.elements.addAll(elements.map { GroupedView(it, groups.toSet()) })
}
fun updateButtonColumn() {
var previousIndex = -1
for (currentIndex in elements.indices) {
val element = elements[currentIndex]
val view = element.view
if (view.visibility == View.VISIBLE) {
val lp = RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT)
lp.width = pxFromSp(view.context, buttonSize).toInt()
lp.height = pxFromSp(view.context, buttonSize).toInt()
lp.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 1)
if (previousIndex < 0) {
lp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 1)
} else {
lp.addRule(RelativeLayout.BELOW, elements[previousIndex].view.id)
}
view.layoutParams = lp
previousIndex = currentIndex
}
}
}
}
| apache-2.0 | 27c21abe1572311c59f0ac2e6910fd57 | 32.925373 | 107 | 0.643203 | 4.582661 | false | false | false | false |
misty000/kotlinfx | kotlinfx-core/src/main/kotlin/kotlinfx/properties/Manual.kt | 2 | 2353 | // These are extension properties that had to be provided by hand
// as the generation script could not handle them correctly.
package kotlinfx.properties
// javafx.print.JobSettings
[suppress("UNNECESSARY_NOT_NULL_ASSERTION", "CAST_NEVER_SUCCEEDS")]
public var javafx.print.JobSettings.pageRanges: Array<javafx.print.PageRange>
get() = getPageRanges()!!
set(v) = setPageRanges(*(v as Array<javafx.print.PageRange?>))
// javafx.scene.control.TableColumnBase
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public val <S, T> javafx.scene.control.TableColumnBase<S, T>.columns: javafx.collections.ObservableList<out javafx.scene.control.TableColumnBase<S,*>?>
get() = getColumns()!!
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public val <S, T> javafx.scene.control.TableColumnBase<S, T>.parentColumn: javafx.scene.control.TableColumnBase<S,*>
get() = getParentColumn()!!
// javafx.scene.control.TablePosition
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public val <S, T> javafx.scene.control.TablePosition<S, T>.tableColumn: javafx.scene.control.TableColumnBase<S,*>
get() = getTableColumn()!!
// javafx.fxml.FXMLLoader
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public var <T> javafx.fxml.FXMLLoader.root: T
get() = getRoot()!!
set(v) = setRoot(v)
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public var javafx.fxml.FXMLLoader.controllerFactory: javafx.util.Callback<Class<*>, Any>
get() = getControllerFactory()!!
set(v) = setControllerFactory(v)
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public var <T> javafx.fxml.FXMLLoader.controller: T
get() = getController()!!
set(v) = setController(v)
// javafx.scene.control.ResizeFeaturesBase
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public val <S> javafx.scene.control.ResizeFeaturesBase<S>.column: javafx.scene.control.TableColumnBase<S,*>
get() = getColumn()!!
// javafx.scene.control.SplitPane
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public var javafx.scene.control.SplitPane.dividerPositions: DoubleArray
get() = getDividerPositions()!!
set(v) = setDividerPositions(*v)
// javafx.scene.control.TableSelectionModel
[suppress("UNNECESSARY_NOT_NULL_ASSERTION")]
public val <T> javafx.scene.control.TableSelectionModel<T>.selectedIndices: javafx.collections.ObservableList<Int>
get() = getSelectedIndices()!!
| mit | 199e696a5c0f6c8cb7cc2392a089e08b | 33.602941 | 151 | 0.745006 | 3.729002 | false | false | false | false |
proxer/ProxerLibAndroid | library/src/main/kotlin/me/proxer/library/enums/ConferenceType.kt | 2 | 409 | package me.proxer.library.enums
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Enum holding the available conference types.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = false)
enum class ConferenceType {
@Json(name = "favour")
FAVORITE,
@Json(name = "block")
BLOCKED,
@Json(name = "group")
GROUP,
@Json(name = "default")
DEFAULT
}
| gpl-3.0 | 3c719c6d323e9bb47e6527e73450048e | 15.36 | 47 | 0.662592 | 3.587719 | false | false | false | false |
BoD/OpenCurrentActivityIntelliJPlugin | src/org/jraf/intellijplugin/opencurrentactivity/OpenCurrentActivityAction.kt | 1 | 12866 | /*
* This source is part of the
* _____ ___ ____
* __ / / _ \/ _ | / __/___ _______ _
* / // / , _/ __ |/ _/_/ _ \/ __/ _ `/
* \___/_/|_/_/ |_/_/ (_)___/_/ \_, /
* /___/
* repository.
*
* Copyright (C) 2015-present Benoit 'BoD' Lubek ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.jraf.intellijplugin.opencurrentactivity
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.fileEditor.OpenFileDescriptor
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.ProjectJdkTable
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.SystemInfo
import com.intellij.openapi.wm.StatusBar
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.search.PsiShortNamesCache
import org.jraf.intellijplugin.opencurrentactivity.exception.ExecutionAdbException
import org.jraf.intellijplugin.opencurrentactivity.exception.MultipleDevicesAdbException
import org.jraf.intellijplugin.opencurrentactivity.exception.NoDevicesAdbException
import org.jraf.intellijplugin.opencurrentactivity.exception.ParseAdbException
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.util.ArrayList
import java.util.regex.Pattern
@Suppress("unused")
class OpenCurrentActivityAction : AnAction() {
companion object {
private const val PATTERN_RESUMED_ACTIVITY = "ResumedActivity"
private val PATTERN_ACTIVITY_NAME = Pattern.compile(".* ([a-zA-Z0-9.]+)/([a-zA-Z0-9.]+).*")
private const val PATTERN_MULTIPLE_DEVICE = "more than one device"
private const val PATTERN_DEVICE_LIST_HEADER = "List"
private val PATTERN_DEVICE_LIST_ITEM = Pattern.compile("(.+)\\p{Space}+(.+)")
private const val PATTERN_DEVICE_NOT_FOUND = "device not found"
private const val ANDROID_SDK_TYPE_NAME = "Android SDK"
private const val ADB_SUBPATH = "/platform-tools/"
private const val ADB_WINDOWS = "adb.exe"
private const val ADB_UNIX = "adb"
private const val UI_NO_SDK_MESSAGE = "Could not find the path for the Android SDK. Have you configured it?"
private const val UI_GENERIC_WARNING = "Warning"
private const val EXT_JAVA = ".java"
private const val EXT_KOTLIN = ".kt"
private val log = Logger.getInstance(OpenCurrentActivityAction::class.java)
}
private lateinit var statusBar: StatusBar
/**
* Find the path for the Android SDK (so we can deduce the path for adb).
*
* @return The found path, or `null` if it was not found (for instance if the Android SDK has not yet been configured.
*/
private val androidSdkPath: String?
get() {
val allSdks = ProjectJdkTable.getInstance().allJdks
log.info("allSdks=${allSdks.contentToString()}")
for (sdk in allSdks) {
val sdkTypeName = sdk.sdkType.name
log.info(sdkTypeName)
if (ANDROID_SDK_TYPE_NAME == sdkTypeName) {
return sdk.homePath
}
}
return null
}
override fun actionPerformed(event: AnActionEvent) {
val project = event.getData(PlatformDataKeys.PROJECT) ?: run {
log.warn("project is null, which should never happen: give up")
return
}
statusBar = WindowManager.getInstance().getStatusBar(project) ?: run {
log.warn("statusBar is null, which should never happen: give up")
return
}
val androidSdkPath = androidSdkPath ?: run {
log.warn("Could not find Android sdk path")
Messages.showWarningDialog(project, UI_NO_SDK_MESSAGE, UI_GENERIC_WARNING)
return
}
var activityName: String
try {
activityName = getCurrentActivityName(null, androidSdkPath)
openActivityFile(project, activityName)
} catch (e: MultipleDevicesAdbException) {
log.info("Multiple devices detected, get the list and try again")
try {
val deviceIdList = getDeviceIdList(androidSdkPath)
for (deviceId in deviceIdList) {
try {
activityName = getCurrentActivityName(deviceId, androidSdkPath)
openActivityFile(project, activityName)
} catch (e: ExecutionAdbException) {
statusBar.info = "Could not execute adb (${e.cause?.message})"
} catch (e: ParseAdbException) {
statusBar.info = "Could not parse adb output"
} catch (e: MultipleDevicesAdbException) {
// This should never happen since we passed a device id
log.error("Got a multiple devices message when passing a device id!?", e)
statusBar.info = "Something went wrong!"
}
}
} catch (e: ExecutionAdbException) {
statusBar.info = "Could not execute adb (${e.cause?.message})"
} catch (e: ParseAdbException) {
statusBar.info = "Could not parse adb output"
} catch (e: NoDevicesAdbException) {
// This should never happen since we have multiple devices
log.error("Got a no devices message when passing a device id!?", e)
statusBar.info = "Something went wrong!"
}
} catch (e: ExecutionAdbException) {
statusBar.info = "Could not execute adb (${e.cause?.message})"
} catch (e: ParseAdbException) {
statusBar.info = "Could not parse adb output"
} catch (e: NoDevicesAdbException) {
statusBar.info = "Could not find any devices or emulators"
}
}
private fun openActivityFile(project: Project, originalActivityName: String) {
var activityName = originalActivityName
log.info("activityName=$activityName")
// Keep only the class name
val dotIndex = activityName.lastIndexOf('.')
if (dotIndex != -1) {
activityName = activityName.substring(dotIndex + 1)
}
val fileNameJava = activityName + EXT_JAVA
val fileNameKotlin = activityName + EXT_KOTLIN
// Open the file (try .java first then .kt)
ApplicationManager.getApplication().invokeLater {
ApplicationManager.getApplication().runReadAction {
var foundFiles = PsiShortNamesCache.getInstance(project).getFilesByName(fileNameJava)
if (foundFiles.isEmpty()) {
log.info("No file with name $fileNameJava found")
// Java not found, try Kotlin
foundFiles = PsiShortNamesCache.getInstance(project).getFilesByName(fileNameKotlin)
if (foundFiles.isEmpty()) {
log.info("No file with name $fileNameKotlin found")
statusBar.info = "Could not find $fileNameJava or $fileNameKotlin in project"
return@runReadAction
}
}
if (foundFiles.size > 1) log.warn("Found more than one file with name $fileNameJava or $fileNameKotlin")
// Will open all files if several are found
for (foundFile in foundFiles) {
log.info("Opening file " + foundFile.name)
val descriptor = OpenFileDescriptor(project, foundFile.virtualFile)
descriptor.navigate(true)
}
}
}
}
private fun getAdbPath(androidSdkPath: String): String {
val adb = if (SystemInfo.isWindows) ADB_WINDOWS else ADB_UNIX
val adbPath = androidSdkPath + ADB_SUBPATH + adb
log.info("adbPath='$adbPath'")
return adbPath
}
/**
* Runs `adb shell dumpsys activity activities` and parses the results to retrieve the name of the current foremost Activity.
*
* @param androidSdkPath Path of the Android SDK (where to find adb).
* @return The name of the foremost ("focused") Activity.
*/
@Throws(ExecutionAdbException::class, MultipleDevicesAdbException::class, ParseAdbException::class, NoDevicesAdbException::class)
private fun getCurrentActivityName(deviceId: String?, androidSdkPath: String): String {
val adbPath = getAdbPath(androidSdkPath)
val processBuilder: ProcessBuilder = if (deviceId == null) {
ProcessBuilder(adbPath, "shell", "dumpsys", "activity", "activities")
} else {
ProcessBuilder(adbPath, "-s", deviceId, "shell", "dumpsys", "activity", "activities")
}
processBuilder.redirectErrorStream(true)
var process: Process? = null
try {
process = processBuilder.start()
val bufferedReader = BufferedReader(InputStreamReader(process!!.inputStream))
var line: String?
while (true) {
line = bufferedReader.readLine()
if (line == null) break
log.info("line='$line'")
when {
line.contains(PATTERN_MULTIPLE_DEVICE) -> throw MultipleDevicesAdbException()
line.contains(PATTERN_DEVICE_NOT_FOUND) -> throw NoDevicesAdbException()
line.contains(PATTERN_RESUMED_ACTIVITY) -> {
val matcher = PATTERN_ACTIVITY_NAME.matcher(line)
if (!matcher.matches()) {
log.error("Could not find the focused Activity in the line")
throw ParseAdbException("Could not find the focused Activity in the line")
}
return matcher.group(2)
}
}
}
} catch (e: IOException) {
log.error("Could not exec adb or read from its process", e)
throw ExecutionAdbException(e)
} finally {
process?.destroy()
}
// Reached the end of lines, none of them had info about the focused activity
throw ParseAdbException("Could not find the focused Activity in the output")
}
/**
* Runs `adb devices` and parses the results to retrieve the list of device ids.
*
* @param androidSdkPath Path of the Android SDK (where to find adb).
* @return The list of device ids.
*/
@Throws(ExecutionAdbException::class, ParseAdbException::class)
private fun getDeviceIdList(androidSdkPath: String): List<String> {
val adbPath = getAdbPath(androidSdkPath)
val processBuilder = ProcessBuilder(adbPath, "devices")
processBuilder.redirectErrorStream(true)
var process: Process? = null
val res = ArrayList<String>(4)
try {
process = processBuilder.start()
val bufferedReader = BufferedReader(InputStreamReader(process.inputStream))
var line: String?
while (true) {
line = bufferedReader.readLine()
if (line == null) break
log.info("line='$line'")
if (line.contains(PATTERN_DEVICE_LIST_HEADER)) continue
val matcher = PATTERN_DEVICE_LIST_ITEM.matcher(line)
if (!matcher.matches()) {
continue
}
val deviceId = matcher.group(1)
res.add(deviceId)
}
} catch (e: IOException) {
log.error("Could not exec adb or read from its process", e)
throw ExecutionAdbException(e)
} finally {
process?.destroy()
}
if (res.isEmpty()) {
// Reached the end of lines, there was no device
throw ParseAdbException("Could not find devices in the output")
}
return res
}
}
| gpl-3.0 | 621599b3eb7a0405775e72e26216f8ad | 43.365517 | 133 | 0.608192 | 4.827767 | false | false | false | false |
VerifAPS/verifaps-lib | symbex/src/test/kotlin/edu/kit/iti/formal/automation/blocks/AnalyzeKtTest.kt | 1 | 4949 | package edu.kit.iti.formal.automation.blocks
import edu.kit.iti.formal.automation.IEC61131Facade.expr
import edu.kit.iti.formal.automation.IEC61131Facade.statements
import edu.kit.iti.formal.automation.datatypes.INT
import edu.kit.iti.formal.automation.scope.Scope
import edu.kit.iti.formal.automation.st.ast.StatementList
import edu.kit.iti.formal.automation.st.ast.VariableDeclaration
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
internal class AnalyzeKtTest {
@Test
fun emptyProgram() {
val block = splitUpByLabel(StatementList())
println(writeDotFile(block))
}
@Test
fun smallestJumpProgram() {
val prg = """
JMP A;
A: a:=1;
""".trimIndent()
val s = statements(prg)
val block = splitUpByLabel(s)
splitGotoBlocks(block)
println(writeDotFile(block))
}
@Test
fun smallestLoopWithJumpProgram() {
val prg = """
A:
a:=1;
B:
JMP A;
""".trimIndent()
val s = statements(prg)
val block = splitUpByLabel(s)
splitGotoBlocks(block)
block.unrollLoop(block.blocks.subList(1, 3).toMutableList(), 1)
println(writeDotFile(block))
}
@Test
fun selfLoopWithJumpProgram() {
val prg = """
A:
a:=1;
JMP A;
""".trimIndent()
val s = statements(prg)
val block = splitUpByLabel(s)
splitGotoBlocks(block)
println(writeDotFile(block))
block.unrollLoops()
println(writeDotFile(block))
}
@Test
fun ifProgram() {
val prg = """
IF abc THEN
JMP A;
ELSEIF q=2 THEN
JMP B;
END_IF
A: a:=1;
B: b:=1;
""".trimIndent()
val s = statements(prg)
val block = splitUpByLabel(s)
Assertions.assertEquals(4, block.blocks.size)
Assertions.assertEquals(3, block.edges.size)
//Assert.assertEquals(s[1], block.blocks[1].statements.first())
splitGotoBlocks(block)
println(writeDotFile(block))
}
@Test @Disabled
fun ifGotoProgram() {
val prg = """
LBL:
IF A=B THEN
A:=1;
B:=2;
C:=3;
IF a=1 THEN
JMP LBL;
ELSE
B:=4;
END_IF
D:=5;
ELSEIF E=B THEN
E:=3;
END_IF
""".trimIndent()
val s = statements(prg)
val block = splitUpByLabel(s)
Assertions.assertEquals(3, block.blocks.size)
Assertions.assertEquals(2, block.edges.size)
Assertions.assertEquals(s[1], block.blocks[1].statements.first())
splitGotoBlocks(block)
val scope = Scope()
scope.variables.add(VariableDeclaration("A", INT))
scope.variables.add(VariableDeclaration("B", INT))
scope.variables.add(VariableDeclaration("C", INT))
scope.variables.add(VariableDeclaration("D", INT))
scope.variables.add(VariableDeclaration("E", INT))
block.ssa()
println(writeDotFile(block))
}
@Test @Disabled
fun testSSA() {
val bp = BlockProgram()
val b1 = Block("b1", statements = statements("c:= (a=1); e := 7+e;"))
val b2 = Block("b2", expr("c"), statements("b := e/6;"))
val b3 = Block("b3", expr("NOT c"), statements("a:=1; b := e+2;"))
val b4 = Block("b4", expr("TRUE"), statements("a:=5+a; b := 3+a+b;"))
bp.blocks.add(b1)
bp.blocks.add(b2)
bp.blocks.add(b3)
bp.blocks.add(b4)
bp.edges += b1 to b2
bp.edges += b1 to b3
bp.edges += b2 to b4
bp.edges += b3 to b4
bp.scope.variables.add(VariableDeclaration("a", INT))
bp.scope.variables.add(VariableDeclaration("b", INT))
bp.scope.variables.add(VariableDeclaration("c", INT))
bp.scope.variables.add(VariableDeclaration("d", INT))
bp.scope.variables.add(VariableDeclaration("e", INT))
println(writeDotFile(bp))
bp.ssa()
println(writeDotFile(bp))
val actual = StringBuilder()
bp.endBlock.ssaMutation.forEach { t, u ->
actual.append("${t.name} ==> ${u.repr()}\n\n")
}
val expected = """__ERROR__ ==> __ERROR__
a ==> 0sd16_5 + (case
a = 0sd16_1 : a; !(a = 0sd16_1) : 0sd16_1;
esac)
b ==> 0sd16_3 + 0sd16_5 + (case
a = 0sd16_1 : a; !(a = 0sd16_1) : 0sd16_1;
esac) + (case
a = 0sd16_1 : (0sd16_7 + e) / 0sd16_6; !(a = 0sd16_1) : 0sd16_7 + e + 0sd16_2;
esac)
c ==> a = 0sd16_1
d ==> d
e ==> 0sd16_7 + e
""".trimIndent()
Assertions.assertEquals(expected.trim(), actual.trim())
}
} | gpl-3.0 | 947158dc057dd18090c6a86773dbc950 | 26.808989 | 79 | 0.541524 | 3.517413 | false | true | false | false |
axbaretto/beam | examples/kotlin/src/test/java/org/apache/beam/examples/WindowedWordCountITKotlin.kt | 1 | 9431 | /*
* 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
import org.apache.beam.examples.kotlin.WindowedWordCount
import org.apache.beam.examples.kotlin.common.ExampleUtils
import org.apache.beam.examples.kotlin.common.WriteOneFilePerWindow.PerWindowFiles
import org.apache.beam.sdk.PipelineResult
import org.apache.beam.sdk.io.FileBasedSink
import org.apache.beam.sdk.io.FileSystems
import org.apache.beam.sdk.io.fs.ResolveOptions.StandardResolveOptions
import org.apache.beam.sdk.options.PipelineOptionsFactory
import org.apache.beam.sdk.options.StreamingOptions
import org.apache.beam.sdk.testing.SerializableMatcher
import org.apache.beam.sdk.testing.StreamingIT
import org.apache.beam.sdk.testing.TestPipeline
import org.apache.beam.sdk.testing.TestPipelineOptions
import org.apache.beam.sdk.transforms.windowing.IntervalWindow
import org.apache.beam.sdk.util.*
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.MoreObjects
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Description
import org.hamcrest.Matchers.equalTo
import org.hamcrest.TypeSafeMatcher
import org.joda.time.Duration
import org.joda.time.Instant
import org.junit.BeforeClass
import org.junit.Rule
import org.junit.Test
import org.junit.experimental.categories.Category
import org.junit.rules.TestName
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.util.*
import java.util.concurrent.ThreadLocalRandom
/** End-to-end integration test of [WindowedWordCount]. */
@RunWith(JUnit4::class)
class WindowedWordCountITKotlin {
@Rule
var testName = TestName()
/** Options for the [WindowedWordCount] Integration Test. */
interface WindowedWordCountITOptions : WindowedWordCount.Options, TestPipelineOptions, StreamingOptions
@Test
@Throws(Exception::class)
fun testWindowedWordCountInBatchDynamicSharding() {
val options = batchOptions()
// This is the default value, but make it explicit.
options.numShards = null
testWindowedWordCountPipeline(options)
}
@Test
@Throws(Exception::class)
fun testWindowedWordCountInBatchStaticSharding() {
val options = batchOptions()
options.numShards = 3
testWindowedWordCountPipeline(options)
}
// TODO: add a test with streaming and dynamic sharding after resolving
// https://issues.apache.org/jira/browse/BEAM-1438
@Test
@Category(StreamingIT::class)
@Throws(Exception::class)
fun testWindowedWordCountInStreamingStaticSharding() {
val options = streamingOptions()
options.numShards = 3
testWindowedWordCountPipeline(options)
}
@Throws(Exception::class)
private fun defaultOptions(): WindowedWordCountITOptions {
val options = TestPipeline.testingPipelineOptions().`as`(WindowedWordCountITOptions::class.java)
options.inputFile = DEFAULT_INPUT
options.testTimeoutSeconds = 1200L
options.minTimestampMillis = 0L
options.minTimestampMillis = Duration.standardHours(1).millis
options.windowSize = 10
options.output = FileSystems.matchNewResource(options.tempRoot, true)
.resolve(
String.format(
"WindowedWordCountITKotlin.%s-%tFT%<tH:%<tM:%<tS.%<tL+%s",
testName.methodName, Date(), ThreadLocalRandom.current().nextInt()),
StandardResolveOptions.RESOLVE_DIRECTORY)
.resolve("output", StandardResolveOptions.RESOLVE_DIRECTORY)
.resolve("results", StandardResolveOptions.RESOLVE_FILE)
.toString()
return options
}
@Throws(Exception::class)
private fun streamingOptions(): WindowedWordCountITOptions {
val options = defaultOptions()
options.isStreaming = true
return options
}
@Throws(Exception::class)
private fun batchOptions(): WindowedWordCountITOptions {
val options = defaultOptions()
// This is the default value, but make it explicit
options.isStreaming = false
return options
}
@Throws(Exception::class)
private fun testWindowedWordCountPipeline(options: WindowedWordCountITOptions) {
val output = FileBasedSink.convertToFileResourceIfPossible(options.output)
val filenamePolicy = PerWindowFiles(output)
val expectedOutputFiles = Lists.newArrayListWithCapacity<ShardedFile>(6)
for (startMinute in ImmutableList.of(0, 10, 20, 30, 40, 50)) {
val windowStart = Instant(options.minTimestampMillis).plus(Duration.standardMinutes(startMinute.toLong()))
val filePrefix = filenamePolicy.filenamePrefixForWindow(
IntervalWindow(windowStart, windowStart.plus(Duration.standardMinutes(10))))
expectedOutputFiles.add(
NumberedShardedFile(
output
.currentDirectory
.resolve(filePrefix, StandardResolveOptions.RESOLVE_FILE)
.toString() + "*"))
}
val inputFile = ExplicitShardedFile(setOf(options.inputFile))
// For this integration test, input is tiny and we can build the expected counts
val expectedWordCounts = TreeMap<String, Long>()
for (line in inputFile.readFilesWithRetries(Sleeper.DEFAULT, BACK_OFF_FACTORY.backoff())) {
val words = line.split(ExampleUtils.TOKENIZER_PATTERN.toRegex()).toTypedArray()
for (word in words) {
if (word.isNotEmpty()) {
expectedWordCounts[word] = MoreObjects.firstNonNull(expectedWordCounts[word], 0L) + 1L
}
}
}
options.onSuccessMatcher = WordCountsMatcher(expectedWordCounts, expectedOutputFiles)
WindowedWordCount.runWindowedWordCount(options)
}
/**
* A matcher that bakes in expected word counts, so they can be read directly via some other
* mechanism, and compares a sharded output file with the result.
*/
private class WordCountsMatcher(
private val expectedWordCounts: SortedMap<String, Long>, private val outputFiles: List<ShardedFile>) : TypeSafeMatcher<PipelineResult>(), SerializableMatcher<PipelineResult> {
private var actualCounts: SortedMap<String, Long>? = null
public override fun matchesSafely(pipelineResult: PipelineResult): Boolean {
try {
// Load output data
val outputLines = ArrayList<String>()
for (outputFile in outputFiles) {
outputLines.addAll(
outputFile.readFilesWithRetries(Sleeper.DEFAULT, BACK_OFF_FACTORY.backoff()))
}
// Since the windowing is nondeterministic we only check the sums
actualCounts = TreeMap()
for (line in outputLines) {
val splits = line.split(": ".toRegex()).toTypedArray()
val word = splits[0]
val count = java.lang.Long.parseLong(splits[1])
(actualCounts as java.util.Map<String, Long>).merge(word, count) { a, b -> a + b }
}
return actualCounts == expectedWordCounts
} catch (e: Exception) {
throw RuntimeException(
String.format("Failed to read from sharded output: %s due to exception", outputFiles), e)
}
}
override fun describeTo(description: Description) {
equalTo(expectedWordCounts).describeTo(description)
}
public override fun describeMismatchSafely(pResult: PipelineResult, description: Description) {
equalTo(expectedWordCounts).describeMismatch(actualCounts, description)
}
}
companion object {
private const val DEFAULT_INPUT = "gs://apache-beam-samples/shakespeare/sonnets.txt"
private const val MAX_READ_RETRIES = 4
private val DEFAULT_SLEEP_DURATION = Duration.standardSeconds(10L)
internal val BACK_OFF_FACTORY = FluentBackoff.DEFAULT
.withInitialBackoff(DEFAULT_SLEEP_DURATION)
.withMaxRetries(MAX_READ_RETRIES)
@BeforeClass
fun setUp() {
PipelineOptionsFactory.register(TestPipelineOptions::class.java)
}
}
}
| apache-2.0 | c610d733f73f66ec8718dcd1a7f66b86 | 40.915556 | 187 | 0.679143 | 4.591529 | false | true | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/Appearance.kt | 1 | 9843 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle
import org.joml.Vector2d
import org.joml.Vector4f
import uk.co.nickthecoder.tickle.collision.PixelTouching
import uk.co.nickthecoder.tickle.graphics.Renderer
import uk.co.nickthecoder.tickle.graphics.TextStyle
import uk.co.nickthecoder.tickle.util.Rectd
import uk.co.nickthecoder.tickle.util.rotate
/**
* An [Appearance] is responsible for drawing an [Actor]. The most common type of Appearance is a [PoseAppearance],
* which draw a single image for each Actor. There are also [NinePatchAppearance], [TextAppearance] and [InvisibleAppearance].
*/
interface Appearance {
val directionRadians: Double
val directionDegrees
get() = Math.toDegrees(directionRadians)
/**
* The natural direction. i.e. if the Actor moved "forward", which mathematical angle would that be?
* For the default value of 0, the image is pointing to the right.
*/
fun draw(renderer: Renderer)
/**
* The width of the pose or the text (before scaling/rotating)
*/
fun width(): Double
/**
* The height of the pose or the text (before scaling/rotating)
*/
fun height(): Double
/**
* The offset position of the pose or the text (before scaling/rotating/flipping)
*/
fun offsetX(): Double
/**
* The offset position of the pose or the text (before scaling/rotating/flipping)
*/
fun offsetY(): Double
/**
* The bounding rectangle of the actor after scaling, rotating, flipping etc.
* Note, that this is a rectangle aligned with the x,y axis, and therefore when a long, thin object
* is rotated, the rectangle can be substantially larger that the object.
*/
fun worldRect(): Rectd
/**
* Is [point] contained withing the non-axis aligned bounding rectangle.
* As this is a non-axis aligned bounding rectangle, it still works well with rotated objects.
*
* [point] is in Tickle's coordinate system. i.e. (0,0) will be the bottom left of the screen when the view hasn't
* been panned.
*/
fun contains(point: Vector2d): Boolean
/**
* Is the Actor's pixel at [point] opaque.
* Note, this uses [PixelTouching.instance], which has a default threshold of 0. If you wish to change this
* threshold :
* PixelTouching.instance = PixelTouching( myThreshold )
*
* [point] is in Tickle's coordinate system. i.e. (0,0) will be the bottom left of the screen when the view hasn't
* been panned.
*/
fun pixelTouching(point: Vector2d): Boolean
/**
* Is [point] touching the actor. For TextAppearances, this is the same as [contains]. For PoseAppearance, it
* the same as [pixelTouching].
*
* [point] is in Tickle's coordinate system. i.e. (0,0) will be the bottom left of the screen when the view hasn't
* been panned.
*/
fun touching(point: Vector2d): Boolean
fun resize(width: Double, height: Double)
fun updateBody() {}
}
private val INVISIBLE_RECT = Rectd(0.0, 0.0, 0.0, 0.0)
class InvisibleAppearance : Appearance {
override val directionRadians = 0.0
override fun draw(renderer: Renderer) {
// Do nothing
}
override fun width(): Double = 0.0
override fun height(): Double = 0.0
override fun offsetX(): Double = 0.0
override fun offsetY(): Double = 0.0
override fun worldRect() = INVISIBLE_RECT
override fun contains(point: Vector2d): Boolean = false
override fun pixelTouching(point: Vector2d): Boolean = false
override fun touching(point: Vector2d): Boolean = false
override fun resize(width: Double, height: Double) {}
override fun toString() = "InvisibleAppearance"
}
abstract class AbstractAppearance(val actor: Actor) : Appearance {
private val worldRect = Rectd()
override fun worldRect(): Rectd {
// TODO. It would be good to cache this info similar to getModelMatrix.
worldRect.left = actor.x - offsetX()
worldRect.bottom = actor.y - offsetY()
worldRect.right = worldRect.left + width()
worldRect.top = worldRect.bottom + height()
if (!actor.isSimpleImage()) {
// Rotates/scale/flip each corner of the rectangle...
val a = Vector4f(worldRect.left.toFloat(), worldRect.top.toFloat(), 0f, 1f)
val b = Vector4f(worldRect.left.toFloat(), worldRect.bottom.toFloat(), 0f, 1f)
val c = Vector4f(worldRect.right.toFloat(), worldRect.top.toFloat(), 0f, 1f)
val d = Vector4f(worldRect.right.toFloat(), worldRect.bottom.toFloat(), 0f, 1f)
val matrix = actor.calculateModelMatrix()
a.mul(matrix)
b.mul(matrix)
c.mul(matrix)
d.mul(matrix)
// Find the rectangle containing the transformed corners.
worldRect.left = Math.min(Math.min(a.x, b.x), Math.min(c.x, d.x)).toDouble()
worldRect.bottom = Math.min(Math.min(a.y, b.y), Math.min(c.y, d.y)).toDouble()
worldRect.right = Math.max(Math.max(a.x, b.x), Math.max(c.x, d.x)).toDouble()
worldRect.top = Math.max(Math.max(a.y, b.y), Math.max(c.y, d.y)).toDouble()
}
return worldRect
}
override fun contains(point: Vector2d): Boolean {
tempVector.set(point)
tempVector.sub(actor.position)
if (actor.direction.radians != directionRadians) {
tempVector.rotate(-actor.direction.radians + directionRadians)
}
tempVector.x /= actor.scale.x
tempVector.y /= actor.scale.y
val offsetX = offsetX()
val offsetY = offsetY()
return tempVector.x >= -offsetX && tempVector.x < width() - offsetX && tempVector.y > -offsetY && tempVector.y < height() - offsetY
}
// TODO Most of the time, this will return false, so if contains() is faster than PixelTouching.touching(), then
// this is the fastest solution. However, I haven't tested if this assumption is correct, so maybe omitting
// the contains() will be faster.
override fun pixelTouching(point: Vector2d): Boolean = contains(point) && PixelTouching.instance.touching(actor, point)
override fun resize(width: Double, height: Double) {
actor.scale.x = width / this.width()
actor.scale.y = height / this.height()
}
}
class PoseAppearance(actor: Actor, var pose: Pose)
: AbstractAppearance(actor) {
override val directionRadians
get() = pose.direction.radians
override fun draw(renderer: Renderer) {
val left = actor.x - offsetX
val bottom = actor.y - offsetY
if (actor.isSimpleImage()) {
renderer.drawTexture(
pose.texture,
left, bottom, left + pose.rect.width, bottom + pose.rect.height,
pose.rectd,
color = actor.color)
} else {
renderer.drawTexture(
pose.texture,
left, bottom, left + pose.rect.width, bottom + pose.rect.height,
pose.rectd,
color = actor.color,
modelMatrix = actor.calculateModelMatrix())
}
}
/**
* Initially, this is the Pose's offset, but can be changed, to allow rotation about a
* different point. Note, consider changing the Actor's so that it appears to stays in the same place.
*/
var offsetX = pose.offsetX
/**
* Changes the offset, and adjusting the actor's position, so that the actor appears not to have moved.
*/
fun changeOffset(newX: Double, newY: Double) {
val delta = Vector2d(newX - offsetX, newY - offsetY)
delta.rotate(actor.direction.radians - directionRadians)
delta.mul(actor.scale)
actor.position.x += delta.x
actor.position.y += delta.y
offsetX = newX
offsetY = newY
}
/**
* Initially, this is the Pose's offset, but can be changed, to allow rotation about a
* different point. Note, consider changing the Actor's so that it appears to stays in the same place.
*/
var offsetY = pose.offsetY
override fun width(): Double = pose.rect.width.toDouble()
override fun height(): Double = pose.rect.height.toDouble()
override fun offsetX() = offsetX
override fun offsetY() = offsetY
override fun touching(point: Vector2d): Boolean = pixelTouching(point)
override fun toString() = "PoseAppearance pose=$pose"
}
class TextAppearance(actor: Actor, var text: String, var textStyle: TextStyle)
: AbstractAppearance(actor) {
override val directionRadians = 0.0
override fun draw(renderer: Renderer) {
textStyle.draw(renderer, text, actor)
}
override fun width(): Double = textStyle.width(text)
override fun height(): Double = textStyle.height(text)
override fun offsetX(): Double = textStyle.offsetX(text)
override fun offsetY(): Double = textStyle.height(text) - textStyle.offsetY(text)
override fun touching(point: Vector2d): Boolean = contains(point)
override fun toString() = "TextAppearance '$text'"
}
private val tempVector = Vector2d()
| gpl-3.0 | be3380b08c66b05c0ede2cc87d31f03c | 33.658451 | 139 | 0.65417 | 4.092723 | false | false | false | false |
dfernandez79/swtlin | examples/src/main/kotlin/swtlin/examples/HelloWorld.kt | 1 | 531 | package swtlin.examples
import org.eclipse.swt.SWT
import org.eclipse.swt.widgets.Shell
import swtlin.children
import swtlin.fillLayout
import swtlin.label
import swtlin.systemColor
fun main(args: Array<String>) {
example {
val shell = Shell()
shell.setSize(300, 200)
shell.children {
layout = fillLayout()
label {
text = "Hello World!"
style = SWT.CENTER
background = systemColor(SWT.COLOR_CYAN)
}
}
}
} | apache-2.0 | 971dadac1f17a052c8623f6262e28034 | 21.166667 | 56 | 0.585687 | 4.214286 | false | false | false | false |
emce/smog | app/src/main/java/mobi/cwiklinski/smog/ui/extension/DelegatesExtensions.kt | 1 | 772 | package mobi.cwiklinski.bloodline.ui.extension
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
public object DelegatesExt {
fun <T : Any> notNullSingleValue(): ReadWriteProperty<Any?, T> = NotNullSingleValueVar()
}
private class NotNullSingleValueVar<T : Any>() : ReadWriteProperty<Any?, T> {
private var settledValue: T? = null
override fun setValue(thisRef: Any?, property: KProperty<*>, value: T) {
this.settledValue = if (this.settledValue == null) value
else throw IllegalStateException("${property.name} already initialized")
}
override fun getValue(thisRef: Any?, property: KProperty<*>): T {
return settledValue ?: throw IllegalStateException("${property.name} not initialized")
}
}
| apache-2.0 | ef97c2fcb7ee735916f99470e2ea35f6 | 34.090909 | 94 | 0.720207 | 4.436782 | false | false | false | false |
avenwu/jk-address-book | android/app/src/main/kotlin/com/jikexueyuan/mobile/address/Utils.kt | 1 | 10333 | package com.jikexueyuan.mobile.address
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.Uri
import android.os.AsyncTask
import android.support.v4.os.AsyncTaskCompat
import android.util.Log
import com.jikexueyuan.mobile.address.bean.User
import com.jikexueyuan.mobile.address.extention.launchApp
import com.jikexueyuan.mobile.address.extention.openPlayMarket
import com.jikexueyuan.mobile.address.extention.startActivitySafely
import com.jikexueyuan.mobile.address.extention.toast
import net.sourceforge.pinyin4j.PinyinHelper
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType
import org.json.JSONObject
import java.io.File
import java.io.ObjectInputStream
import java.io.ObjectOutputStream
import java.util.*
/**
* Created by aven on 10/23/15.
*/
public fun saveUserList2Cache(context: Context, list: List<User>, filter: ((List<User>) -> List<User>)? = null) {
AsyncTaskCompat.executeParallel(object : AsyncTask<Any, Void, Void>() {
override fun doInBackground(vararg params: Any): Void? {
params[0].let {
try {
var fos = (params[0] as File).outputStream()
var os = ObjectOutputStream(fos);
var filterData: List<User>? = null
filter?.let {
filterData = filter(params[1] as List<User>)
}
Log.d("File", "save user list:${filterData?.size}")
os.writeObject(filterData ?: params[1]);
os.close();
fos.close();
} catch(e: Exception) {
e.printStackTrace()
Log.d("File", "save user failed")
}
}
return null
}
}, File(context.filesDir, "user-list"), list)
}
public fun getUserListFromCache(context: Context, listener: (List<User>) -> Unit, filter: ((List<User>) -> List<User>)? = null) {
AsyncTaskCompat.executeParallel(object : AsyncTask<Any, Void, List<User>>() {
override fun doInBackground(vararg params: Any?): List<User>? {
var dataList: List<User>? = emptyList()
try {
var fis = (params[0] as File).inputStream()
var inStream = ObjectInputStream(fis)
fis.available()
var data = inStream.readObject() as List<User>;
inStream.close();
fis.close();
filter?.let {
dataList = filter(data)
}
if (dataList == null || (dataList?.size == 0 && data.size > 0)) {
dataList = data
}
Log.d("File", "get user cache:${dataList?.size}")
} catch(e: Exception) {
e.printStackTrace()
Log.d("File", "get user cache failed")
}
return dataList
}
override fun onPostExecute(result: List<User>) {
super.onPostExecute(result)
listener(result)
}
}, File(context.filesDir, "user-list"))
}
public fun checkUserListCache(context: Context, block: (Boolean) -> Unit) {
AsyncTaskCompat.executeParallel(object : AsyncTask<File, Void, Boolean>() {
override fun doInBackground(vararg params: File?): Boolean? {
var hasContent = false
try {
params[0].let {
var fis = (params[0] as File).inputStream()
var inStream = ObjectInputStream(fis)
fis.available()
var data = inStream.readObject() as List<User>;
inStream.close();
fis.close();
if ((data.size) > 0) {
hasContent = true
}
}
} catch(e: Throwable) {
e.printStackTrace()
Log.d("File", "check user cache failed")
}
return hasContent
}
override fun onPostExecute(result: Boolean) {
super.onPostExecute(result)
block(result)
}
}, File(context.filesDir, "user-list"))
}
public fun json2User(json: String): User? {
val jsonObject = JSONObject(json)
return User(jsonObject.optString("username"), jsonObject.optString("email"),
jsonObject.optString("phone"), jsonObject.optString("qq"), jsonObject.optString("wechat"))
}
public fun mockUserList(): List<User> {
return listOf(User("A", "zhangsan", "[email protected]"),
User("B", "b", "b"),
User("C", "c", "c"),
User("D", "c", "c"),
User("E", "c", "c"),
User("F", "c", "c"),
User("G", "c", "c"),
User("H", "c", "c"),
User("I", "c", "c"),
User("J", "c", "c"),
User("K", "c", "c"),
User("L", "c", "c"),
User("M", "c", "c"),
User("N", "c", "c"),
User("O", "c", "c"),
User("P", "c", "c"))
}
public fun isNetWorkAvailable(context: Context): Boolean {
val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val info = manager.activeNetworkInfo
return info != null && info.isAvailable
}
public fun makeCall(context: Context, phone: CharSequence) {
context.startActivitySafely(Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone)), {
toast(it, "无法唤起拨号面板")
})
}
public fun sendEmail(context: Context, email: CharSequence) {
context.startActivitySafely(Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$email")), {
toast(it, "没有邮件客户端")
})
}
public fun openQQ(context: Context, qq: CharSequence) {
val packageName = "com.tencent.mobileqq"
if (context.launchApp(packageName)) {
val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
manager.primaryClip = ClipData.newPlainText("QQ号码", qq)
toast(context, "QQ号已复制,可长按粘贴在QQ搜索栏内")
} else {
toast(context, "壮士,没有检测到QQ客户端")
context.openPlayMarket(packageName)
}
}
public fun openWeChat(context: Context, weChat: CharSequence) {
val packageName = "com.tencent.mm"
if (context.launchApp(packageName)) {
val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
manager.primaryClip = ClipData.newPlainText("微信号码", weChat)
toast(context, "微信号已复制,可长按粘贴在微信搜索栏内")
} else {
toast(context, "壮士,没有检测到微信客户端")
context.openPlayMarket(packageName)
}
}
public fun skipSameUserFilter(oldData: List<User>): List<User> {
var dataList = ArrayList<User>()
Log.w("Filter", "过滤重复号码")
var phoneSet = HashSet<String>()
for (user in oldData) {
if (phoneSet.contains(user.phone)) {
Log.w("Filter", "跳过重复号:${user.json()}")
continue
}
phoneSet.add(user.phone)
dataList.add(user.copy())
}
return dataList
}
public fun export2VCard(context: Context, user: List<User>, block: (File?) -> Unit) {
AsyncTaskCompat.executeParallel(object : AsyncTask<Any, Void, File>() {
override fun doInBackground(vararg params: Any?): File? {
params[0]?.let {
var file = params[0] as File
var userInVCardFormat = user2VCardFormatString(params[1] as List<User>)
file.writeText(userInVCardFormat)
return file
}
return null
}
override fun onPostExecute(result: File?) {
super.onPostExecute(result)
block(result)
}
}, File(context.externalCacheDir, "极客学院联系人.vcf"), user)
}
fun user2VCardFormatString(users: List<User>): String {
var data = StringBuilder()
for (user in users) {
data.append("BEGIN:VCARD\n" +
"VERSION:2.1\n" +
"FN:${user.username}\n" +
"ORG:极客学院\n" +
"TEL;TYPE=cell:${user.phone}\n" +
"EMAIL:${user.email}\n" +
"X-QQ:${user.qq}\n" +
"X-WECHAT:${user.wechat}\n" +
"END:VCARD\n")
}
return data.toString()
}
public fun chinese2Pinyin(chinese: String): String {
val pinyingBuffer = StringBuffer()
val defaultFormat = HanyuPinyinOutputFormat()
defaultFormat.caseType = HanyuPinyinCaseType.UPPERCASE
defaultFormat.toneType = HanyuPinyinToneType.WITHOUT_TONE
for (c in chinese.toCharArray()) {
if (c.toInt() > 128) {
try {
var array = PinyinHelper.toHanyuPinyinStringArray(c, defaultFormat)
array?.let {
pinyingBuffer.append(array[0])
}
} catch(e: Throwable) {
e.printStackTrace()
}
} else {
pinyingBuffer.append(c)
}
}
return pinyingBuffer.toString()
}
fun sortUserList(raw: List<User>, block: (List<User>) -> Unit) {
AsyncTaskCompat.executeParallel(object : AsyncTask<List<User>, Void, List<User>>() {
override fun doInBackground(vararg params: List<User>?): List<User>? {
return params[0]?.sortedWith(Comparator { left, right ->
left.pinying.compareTo(right.pinying)
})
}
override fun onPostExecute(result: List<User>?) {
super.onPostExecute(result)
block(result ?: emptyList())
}
}, raw)
}
public fun updateLoginTimestamp(context: Context, mills: Long) {
var sp = context.getSharedPreferences("user_info", Context.MODE_PRIVATE)
sp.edit().putLong("login_timestamp", mills).apply()
}
public fun getLoginTimestamp(context: Context): Long {
return context.getSharedPreferences("user_info", Context.MODE_PRIVATE).getLong("login_timestamp", 0)
} | apache-2.0 | f4fdefa0c65e268943783a452a431ff1 | 35.308244 | 129 | 0.578241 | 4.061347 | false | false | false | false |
EZTEQ/rbtv-firetv | app/src/main/java/de/markhaehnel/rbtv/rocketbeanstv/api/ApiResponse.kt | 1 | 1207 | package de.markhaehnel.rbtv.rocketbeanstv.api
import retrofit2.Response
/**
* Common class used by API responses.
* @param <T> the type of the response object
</T> */
@Suppress("unused") // T is used in extending classes
sealed class ApiResponse<T> {
companion object {
fun <T> create(error: Throwable): ApiErrorResponse<T> {
return ApiErrorResponse(error.message ?: "unknown error")
}
fun <T> create(response: Response<T>): ApiResponse<T> {
return if (response.isSuccessful) {
val body = response.body()
if (body == null || response.code() == 204) {
ApiEmptyResponse()
} else {
ApiSuccessResponse(body = body)
}
} else {
ApiErrorResponse("Error while fetching resource (${response.code()})")
}
}
}
}
/**
* separate class for HTTP 204 responses so that we can make ApiSuccessResponse's body non-null.
*/
class ApiEmptyResponse<T> : ApiResponse<T>()
data class ApiSuccessResponse<T>(val body: T) : ApiResponse<T>()
data class ApiErrorResponse<T>(val errorMessage: String) : ApiResponse<T>() | mit | 4bcef588de44a7fa9c4c6dee9f391d9e | 30.789474 | 96 | 0.598177 | 4.421245 | false | false | false | false |
ReactiveCircus/FlowBinding | flowbinding-android/src/androidTest/java/reactivecircus/flowbinding/android/widget/AutoCompleteTextViewDismissFlowTest.kt | 1 | 2055 | package reactivecircus.flowbinding.android.widget
import android.os.Build
import android.widget.ArrayAdapter
import android.widget.AutoCompleteTextView
import androidx.test.filters.LargeTest
import androidx.test.filters.SdkSuppress
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import reactivecircus.blueprint.testing.action.clearTextInView
import reactivecircus.blueprint.testing.action.enterTextIntoView
import reactivecircus.flowbinding.android.fixtures.widget.AutoCompleteViewFragment
import reactivecircus.flowbinding.android.test.R
import reactivecircus.flowbinding.testing.FlowRecorder
import reactivecircus.flowbinding.testing.launchTest
import reactivecircus.flowbinding.testing.recordWith
@SdkSuppress(minSdkVersion = Build.VERSION_CODES.JELLY_BEAN_MR1)
@LargeTest
class AutoCompleteTextViewDismissFlowTest {
@Test
fun autoCompleteTextViewDismisses() {
launchTest<AutoCompleteViewFragment> {
val recorder = FlowRecorder<Unit>(testScope)
val textView = getViewById<AutoCompleteTextView>(R.id.autoCompleteTextView).apply {
runOnUiThread {
val values = arrayOf("A", "AB", "ABC")
val adapter = ArrayAdapter(context, android.R.layout.simple_list_item_1, values)
setAdapter(adapter)
}
}
textView.dismisses().recordWith(recorder)
recorder.assertNoMoreValues()
enterTextIntoView(R.id.autoCompleteTextView, "AB")
runOnUiThread { textView.dismissDropDown() }
assertThat(recorder.takeValue())
.isEqualTo(Unit)
recorder.assertNoMoreValues()
cancelTestScope()
clearTextInView(R.id.autoCompleteTextView)
enterTextIntoView(R.id.autoCompleteTextView, "AB")
runOnUiThread { textView.dismissDropDown() }
recorder.assertNoMoreValues()
}
}
}
| apache-2.0 | b64203ede4d0e85554dce63a8f340a17 | 37.055556 | 100 | 0.719221 | 5.310078 | false | true | false | false |
idanarye/nisui | gui/src/test/kotlin/nisui/gui/TestsBase.kt | 1 | 1002 | package nisui.gui
import java.io.File
import org.junit.Rule
import org.junit.rules.TemporaryFolder
import nisui.core.*
import nisui.h2_store.H2ResultsStorage
import nisui.java_runner.JavaExperimentFunction
abstract class TestsBase {
@Rule
fun _dbFolder() = TemporaryFolder()
val dbFolder = _dbFolder()
fun tmpDbFileName() = File(dbFolder.getRoot(), "test-db").getAbsolutePath()
protected val factory = TestsFactory()
protected inner class TestsFactory: NisuiFactory {
val runner: JavaExperimentFunction<Any?, Any?>
init {
val url = javaClass.getClassLoader().getResource("DiceRoller.java")
runner = JavaExperimentFunction.load(url.toURI())
}
override fun createExperimentFunction(): ExperimentFunction<*, *>? = null
override fun createResultsStorage() = H2ResultsStorage(tmpDbFileName(), createExperimentFunction()?.getDataPointHandler(), createExperimentFunction()?.getExperimentResultHandler())
}
}
| mit | a8e2e5e30af2c61462f66516d7eadeea | 30.3125 | 188 | 0.719561 | 4.453333 | false | true | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/cargo/runconfig/command/RunClippyAction.kt | 1 | 881 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.cargo.runconfig.command
import com.intellij.openapi.actionSystem.AnActionEvent
import org.rust.cargo.icons.CargoIcons
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.toolchain.CargoCommandLine
import org.rust.cargo.toolchain.RustChannel
class RunClippyAction : RunCargoCommandActionBase(CargoIcons.CLIPPY) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val toolchain = project.toolchain ?: return
val cargoProject = getAppropriateCargoProject(e) ?: return
val channel = if (toolchain.isRustupAvailable) RustChannel.NIGHTLY else RustChannel.DEFAULT
runCommand(project, CargoCommandLine.forProject(cargoProject, "clippy", channel = channel))
}
}
| mit | ef42829a9afc22d03128e3611e90526a | 37.304348 | 99 | 0.76504 | 4.339901 | false | false | false | false |
owncloud/android | owncloudApp/src/main/java/com/owncloud/android/ui/fragment/FileDetailViewModel.kt | 2 | 3228 | /**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2022 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.owncloud.android.authentication.AccountUtils
import com.owncloud.android.domain.capabilities.model.OCCapability
import com.owncloud.android.domain.capabilities.usecases.GetCapabilitiesAsLiveDataUseCase
import com.owncloud.android.domain.capabilities.usecases.RefreshCapabilitiesFromServerAsyncUseCase
import com.owncloud.android.domain.files.GetUrlToOpenInWebUseCase
import com.owncloud.android.domain.utils.Event
import com.owncloud.android.extensions.ViewModelExt.runUseCaseWithResult
import com.owncloud.android.presentation.UIResult
import com.owncloud.android.providers.ContextProvider
import com.owncloud.android.providers.CoroutinesDispatcherProvider
import kotlinx.coroutines.launch
class FileDetailViewModel(
private val openInWebUseCase: GetUrlToOpenInWebUseCase,
refreshCapabilitiesFromServerAsyncUseCase: RefreshCapabilitiesFromServerAsyncUseCase,
getCapabilitiesAsLiveDataUseCase: GetCapabilitiesAsLiveDataUseCase,
val coroutinesDispatcherProvider: CoroutinesDispatcherProvider,
val contextProvider: ContextProvider,
) : ViewModel() {
private val currentAccountName: String = AccountUtils.getCurrentOwnCloudAccount(contextProvider.getContext()).name
var capabilities: LiveData<OCCapability?> =
getCapabilitiesAsLiveDataUseCase.execute(GetCapabilitiesAsLiveDataUseCase.Params(currentAccountName))
private val _openInWebUriLiveData: MediatorLiveData<Event<UIResult<String>>> = MediatorLiveData()
val openInWebUriLiveData: LiveData<Event<UIResult<String>>> = _openInWebUriLiveData
init {
viewModelScope.launch(coroutinesDispatcherProvider.io) {
refreshCapabilitiesFromServerAsyncUseCase.execute(RefreshCapabilitiesFromServerAsyncUseCase.Params(currentAccountName))
}
}
fun isOpenInWebAvailable(): Boolean = capabilities.value?.isOpenInWebAllowed() ?: false
fun openInWeb(fileId: String) {
runUseCaseWithResult(
coroutineDispatcher = coroutinesDispatcherProvider.io,
liveData = _openInWebUriLiveData,
useCase = openInWebUseCase,
useCaseParams = GetUrlToOpenInWebUseCase.Params(openWebEndpoint = capabilities.value?.filesOcisProviders?.openWebUrl!!, fileId = fileId),
showLoading = false,
requiresConnection = true,
)
}
}
| gpl-2.0 | 23abe0a6fe26ca8f894ea470a358474d | 45.768116 | 149 | 0.792997 | 4.91172 | false | false | false | false |
jksiezni/xpra-client | xpra-client-android/src/main/java/com/github/jksiezni/xpra/view/Intents.kt | 1 | 1629 | /*
* Copyright (C) 2020 Jakub Ksiezniak
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.github.jksiezni.xpra.view
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.text.TextUtils
internal object Intents {
@JvmStatic
fun createXpraIntent(context: Context, windowId: Int): Intent {
return Intent(context, XpraActivity::class.java).apply {
//addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
data = Uri.parse("xpra://window/$windowId")
}
}
@JvmStatic
fun isValidXpraActivityIntent(intent: Intent): Boolean {
val uri = intent.data
return uri != null && "xpra" == uri.scheme && "window" == uri.authority && TextUtils.isDigitsOnly(uri.lastPathSegment)
}
@JvmStatic
fun getWindowId(intent: Intent): Int {
return intent.data?.lastPathSegment?.toInt() ?: -1
}
} | gpl-3.0 | d53bed40fb54f926e5369a3961463996 | 35.222222 | 126 | 0.686924 | 4.042184 | false | false | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/store/ActivityLogStoreTest.kt | 1 | 20547 | package org.wordpress.android.fluxc.store
import com.yarolegovich.wellsql.SelectQuery
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.action.ActivityLogAction
import org.wordpress.android.fluxc.annotations.action.Action
import org.wordpress.android.fluxc.generated.ActivityLogActionBuilder
import org.wordpress.android.fluxc.model.SiteModel
import org.wordpress.android.fluxc.model.activity.ActivityLogModel
import org.wordpress.android.fluxc.model.activity.BackupDownloadStatusModel
import org.wordpress.android.fluxc.model.activity.RewindStatusModel
import org.wordpress.android.fluxc.network.rest.wpcom.activity.ActivityLogRestClient
import org.wordpress.android.fluxc.persistence.ActivityLogSqlUtils
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadRequestTypes
import org.wordpress.android.fluxc.store.ActivityLogStore.BackupDownloadResultPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.DismissBackupDownloadPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.DismissBackupDownloadResultPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchActivityLogPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchBackupDownloadStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchRewindStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedActivityLogPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedBackupDownloadStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.FetchedRewindStatePayload
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindPayload
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindRequestTypes
import org.wordpress.android.fluxc.store.ActivityLogStore.RewindResultPayload
import org.wordpress.android.fluxc.test
import org.wordpress.android.fluxc.tools.initCoroutineEngine
@RunWith(MockitoJUnitRunner::class)
class ActivityLogStoreTest {
@Mock private lateinit var activityLogRestClient: ActivityLogRestClient
@Mock private lateinit var activityLogSqlUtils: ActivityLogSqlUtils
@Mock private lateinit var dispatcher: Dispatcher
@Mock private lateinit var siteModel: SiteModel
private lateinit var activityLogStore: ActivityLogStore
@Before
fun setUp() {
activityLogStore = ActivityLogStore(activityLogRestClient, activityLogSqlUtils,
initCoroutineEngine(), dispatcher)
}
@Test
fun onFetchActivityLogFirstPageActionCleanupDbAndCallRestClient() = test {
val payload = FetchActivityLogPayload(siteModel)
whenever(activityLogRestClient.fetchActivity(eq(payload), any(), any())).thenReturn(
FetchedActivityLogPayload(
listOf(),
siteModel,
0,
0,
0
)
)
val action = ActivityLogActionBuilder.newFetchActivitiesAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).fetchActivity(payload, PAGE_SIZE, OFFSET)
}
@Test
fun onFetchActivityLogNextActionReadCurrentDataAndCallRestClient() = test {
val payload = FetchActivityLogPayload(siteModel, loadMore = true)
whenever(activityLogRestClient.fetchActivity(eq(payload), any(), any())).thenReturn(
FetchedActivityLogPayload(
listOf(),
siteModel,
0,
0,
0
)
)
val existingActivities = listOf<ActivityLogModel>(mock())
whenever(activityLogSqlUtils.getActivitiesForSite(siteModel, SelectQuery.ORDER_ASCENDING))
.thenReturn(existingActivities)
val action = ActivityLogActionBuilder.newFetchActivitiesAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).fetchActivity(payload, PAGE_SIZE, existingActivities.size)
}
@Test
fun onFetchRewindStatusActionCallRestClient() = test {
val payload = FetchRewindStatePayload(siteModel)
whenever(activityLogRestClient.fetchActivityRewind(siteModel)).thenReturn(
FetchedRewindStatePayload(
null,
siteModel
)
)
val action = ActivityLogActionBuilder.newFetchRewindStateAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).fetchActivityRewind(siteModel)
}
@Test
fun onRewindActionCallRestClient() = test {
whenever(activityLogRestClient.rewind(eq(siteModel), any(), anyOrNull())).thenReturn(
RewindResultPayload(
"rewindId",
null,
siteModel
)
)
val rewindId = "rewindId"
val payload = RewindPayload(siteModel, rewindId, null)
val action = ActivityLogActionBuilder.newRewindAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).rewind(siteModel, rewindId)
}
@Test
fun storeFetchedActivityLogToDbAndSetsLoadMoreToFalse() = test {
val rowsAffected = 1
val activityModels = listOf<ActivityLogModel>(mock())
val action = initRestClient(activityModels, rowsAffected)
activityLogStore.onAction(action)
verify(activityLogSqlUtils).insertOrUpdateActivities(siteModel, activityModels)
val expectedChangeEvent = ActivityLogStore.OnActivityLogFetched(rowsAffected,
false,
ActivityLogAction.FETCH_ACTIVITIES)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
verify(activityLogSqlUtils).deleteActivityLog(siteModel)
}
@Test
fun cannotLoadMoreWhenResponseEmpty() = test {
val rowsAffected = 0
val activityModels = listOf<ActivityLogModel>(mock())
val action = initRestClient(activityModels, rowsAffected)
activityLogStore.onAction(action)
val expectedChangeEvent = ActivityLogStore.OnActivityLogFetched(0,
false,
ActivityLogAction.FETCH_ACTIVITIES)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun setsLoadMoreToTrueOnMoreItems() = test {
val rowsAffected = 1
val activityModels = listOf<ActivityLogModel>(mock())
val action = initRestClient(activityModels, rowsAffected, totalItems = 500)
whenever(activityLogSqlUtils.insertOrUpdateActivities(any(), any())).thenReturn(rowsAffected)
activityLogStore.onAction(action)
val expectedChangeEvent = ActivityLogStore.OnActivityLogFetched(rowsAffected,
true,
ActivityLogAction.FETCH_ACTIVITIES)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun returnActivitiesFromDb() {
val activityModels = listOf<ActivityLogModel>(mock())
whenever(activityLogSqlUtils.getActivitiesForSite(siteModel, SelectQuery.ORDER_DESCENDING))
.thenReturn(activityModels)
val activityModelsFromDb = activityLogStore.getActivityLogForSite(
site = siteModel,
ascending = false,
rewindableOnly = false
)
verify(activityLogSqlUtils).getActivitiesForSite(siteModel, SelectQuery.ORDER_DESCENDING)
assertEquals(activityModels, activityModelsFromDb)
}
@Test
fun returnRewindableOnlyActivitiesFromDb() {
val rewindableActivityModels = listOf<ActivityLogModel>(mock())
whenever(activityLogSqlUtils.getRewindableActivitiesForSite(siteModel, SelectQuery.ORDER_DESCENDING))
.thenReturn(rewindableActivityModels)
val activityModelsFromDb = activityLogStore.getActivityLogForSite(
site = siteModel,
ascending = false,
rewindableOnly = true
)
verify(activityLogSqlUtils).getRewindableActivitiesForSite(siteModel, SelectQuery.ORDER_DESCENDING)
assertEquals(rewindableActivityModels, activityModelsFromDb)
}
@Test
fun storeFetchedRewindStatusToDb() = test {
val rewindStatusModel = mock<RewindStatusModel>()
val payload = FetchedRewindStatePayload(rewindStatusModel, siteModel)
whenever(activityLogRestClient.fetchActivityRewind(siteModel)).thenReturn(payload)
val fetchAction = ActivityLogActionBuilder.newFetchRewindStateAction(FetchRewindStatePayload(siteModel))
activityLogStore.onAction(fetchAction)
verify(activityLogSqlUtils).replaceRewindStatus(siteModel, rewindStatusModel)
val expectedChangeEvent = ActivityLogStore.OnRewindStatusFetched(ActivityLogAction.FETCH_REWIND_STATE)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun returnRewindStatusFromDb() {
val rewindStatusModel = mock<RewindStatusModel>()
whenever(activityLogSqlUtils.getRewindStatusForSite(siteModel))
.thenReturn(rewindStatusModel)
val rewindStatusFromDb = activityLogStore.getRewindStatusForSite(siteModel)
verify(activityLogSqlUtils).getRewindStatusForSite(siteModel)
assertEquals(rewindStatusModel, rewindStatusFromDb)
}
@Test
fun emitsRewindResult() = test {
val rewindId = "rewindId"
val restoreId = 10L
val payload = RewindResultPayload(rewindId, restoreId, siteModel)
whenever(activityLogRestClient.rewind(siteModel, rewindId)).thenReturn(payload)
activityLogStore.onAction(ActivityLogActionBuilder.newRewindAction(RewindPayload(
siteModel,
rewindId,
null)))
val expectedChangeEvent = ActivityLogStore.OnRewind(rewindId, restoreId, ActivityLogAction.REWIND)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun returnsActivityLogItemFromDbByRewindId() {
val rewindId = "rewindId"
val activityLogModel = mock<ActivityLogModel>()
whenever(activityLogSqlUtils.getActivityByRewindId(rewindId)).thenReturn(activityLogModel)
val returnedItem = activityLogStore.getActivityLogItemByRewindId(rewindId)
assertEquals(activityLogModel, returnedItem)
verify(activityLogSqlUtils).getActivityByRewindId(rewindId)
}
@Test
fun returnsActivityLogItemFromDbByActivityId() {
val rewindId = "activityId"
val activityLogModel = mock<ActivityLogModel>()
whenever(activityLogSqlUtils.getActivityByActivityId(rewindId)).thenReturn(activityLogModel)
val returnedItem = activityLogStore.getActivityLogItemByActivityId(rewindId)
assertEquals(activityLogModel, returnedItem)
verify(activityLogSqlUtils).getActivityByActivityId(rewindId)
}
@Test
fun onRewindActionWithTypesCallRestClient() = test {
whenever(activityLogRestClient.rewind(eq(siteModel), any(), any())).thenReturn(
RewindResultPayload(
"rewindId",
null,
siteModel
)
)
val rewindId = "rewindId"
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
val payload = RewindPayload(siteModel, rewindId, types)
val action = ActivityLogActionBuilder.newRewindAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).rewind(siteModel, rewindId, types)
}
@Test
fun emitsRewindResultWhenSendingTypes() = test {
val rewindId = "rewindId"
val restoreId = 10L
val types = RewindRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
val payload = RewindResultPayload(rewindId, restoreId, siteModel)
whenever(activityLogRestClient.rewind(siteModel, rewindId, types)).thenReturn(payload)
activityLogStore.onAction(ActivityLogActionBuilder.newRewindAction(RewindPayload(siteModel, rewindId, types)))
val expectedChangeEvent = ActivityLogStore.OnRewind(rewindId, restoreId, ActivityLogAction.REWIND)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun onBackupDownloadActionCallRestClient() = test {
whenever(activityLogRestClient.backupDownload(eq(siteModel), any(), any())).thenReturn(
BackupDownloadResultPayload(
"rewindId",
10L,
"backupPoint",
"startedAt",
50,
siteModel
)
)
val types = BackupDownloadRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
val rewindId = "rewindId"
val payload = BackupDownloadPayload(siteModel, rewindId, types)
val action = ActivityLogActionBuilder.newBackupDownloadAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).backupDownload(siteModel, rewindId, types)
}
@Test
fun emitsBackupDownloadResult() = test {
val rewindId = "rewindId"
val downloadId = 10L
val backupPoint = "backup_point"
val startedAt = "started_at"
val progress = 50
val types = BackupDownloadRequestTypes(themes = true,
plugins = true,
uploads = true,
sqls = true,
roots = true,
contents = true)
val payload = BackupDownloadResultPayload(
rewindId,
downloadId,
backupPoint,
startedAt,
progress,
siteModel)
whenever(activityLogRestClient.backupDownload(siteModel, rewindId, types)).thenReturn(payload)
activityLogStore.onAction(ActivityLogActionBuilder.newBackupDownloadAction(BackupDownloadPayload(
siteModel,
rewindId,
types)))
val expectedChangeEvent = ActivityLogStore.OnBackupDownload(
rewindId,
downloadId,
backupPoint,
startedAt,
progress,
ActivityLogAction.BACKUP_DOWNLOAD)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun onFetchBackupDownloadStatusActionCallRestClient() = test {
val payload = FetchBackupDownloadStatePayload(siteModel)
whenever(activityLogRestClient.fetchBackupDownloadState(siteModel)).thenReturn(
FetchedBackupDownloadStatePayload(
null,
siteModel
)
)
val action = ActivityLogActionBuilder.newFetchBackupDownloadStateAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).fetchBackupDownloadState(siteModel)
}
@Test
fun storeFetchedBackupDownloadStatusToDb() = test {
val backupDownloadStatusModel = mock<BackupDownloadStatusModel>()
val payload = FetchedBackupDownloadStatePayload(backupDownloadStatusModel, siteModel)
whenever(activityLogRestClient.fetchBackupDownloadState(siteModel)).thenReturn(payload)
val fetchAction =
ActivityLogActionBuilder.newFetchBackupDownloadStateAction(FetchBackupDownloadStatePayload(siteModel))
activityLogStore.onAction(fetchAction)
verify(activityLogSqlUtils).replaceBackupDownloadStatus(siteModel, backupDownloadStatusModel)
val expectedChangeEvent =
ActivityLogStore.OnBackupDownloadStatusFetched(ActivityLogAction.FETCH_BACKUP_DOWNLOAD_STATE)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
@Test
fun returnBackupDownloadStatusFromDb() {
val backupDownloadStatusModel = mock<BackupDownloadStatusModel>()
whenever(activityLogSqlUtils.getBackupDownloadStatusForSite(siteModel))
.thenReturn(backupDownloadStatusModel)
val backDownloadStatusFromDb = activityLogStore.getBackupDownloadStatusForSite(siteModel)
verify(activityLogSqlUtils).getBackupDownloadStatusForSite(siteModel)
assertEquals(backupDownloadStatusModel, backDownloadStatusFromDb)
}
@Test
fun storeFetchedEmptyRewindStatusRemoveFromDb() = test {
whenever(activityLogRestClient.fetchActivityRewind(siteModel))
.thenReturn(FetchedRewindStatePayload(null, siteModel))
val fetchAction = ActivityLogActionBuilder.newFetchRewindStateAction(FetchRewindStatePayload(siteModel))
activityLogStore.onAction(fetchAction)
verify(activityLogSqlUtils).deleteRewindStatus(siteModel)
}
@Test
fun storeFetchedEmptyBackupDownloadStatusRemoveFromDb() = test {
whenever(activityLogRestClient.fetchBackupDownloadState(siteModel))
.thenReturn(FetchedBackupDownloadStatePayload(null, siteModel))
val fetchAction =
ActivityLogActionBuilder.newFetchBackupDownloadStateAction(FetchBackupDownloadStatePayload(siteModel))
activityLogStore.onAction(fetchAction)
verify(activityLogSqlUtils).deleteBackupDownloadStatus(siteModel)
}
@Test
fun onDismissBackupDownloadActionCallRestClient() = test {
whenever(activityLogRestClient.dismissBackupDownload(eq(siteModel), any())).thenReturn(
DismissBackupDownloadResultPayload(
100L,
10L,
true
)
)
val downloadId = 10L
val payload = DismissBackupDownloadPayload(siteModel, downloadId)
val action = ActivityLogActionBuilder.newDismissBackupDownloadAction(payload)
activityLogStore.onAction(action)
verify(activityLogRestClient).dismissBackupDownload(siteModel, downloadId)
}
@Test
fun emitsDismissBackupDownloadResult() = test {
val downloadId = 10L
val isDismissed = true
val payload = DismissBackupDownloadResultPayload(
siteModel.siteId,
downloadId,
isDismissed)
whenever(activityLogRestClient.dismissBackupDownload(siteModel, downloadId)).thenReturn(payload)
activityLogStore.onAction(ActivityLogActionBuilder.newDismissBackupDownloadAction(DismissBackupDownloadPayload(
siteModel,
downloadId)))
val expectedChangeEvent = ActivityLogStore.OnDismissBackupDownload(
downloadId,
isDismissed,
ActivityLogAction.DISMISS_BACKUP_DOWNLOAD)
verify(dispatcher).emitChange(eq(expectedChangeEvent))
}
private suspend fun initRestClient(
activityModels: List<ActivityLogModel>,
rowsAffected: Int,
offset: Int = OFFSET,
number: Int = PAGE_SIZE,
totalItems: Int = PAGE_SIZE
): Action<*> {
val requestPayload = FetchActivityLogPayload(siteModel)
val action = ActivityLogActionBuilder.newFetchActivitiesAction(requestPayload)
val payload = FetchedActivityLogPayload(activityModels, siteModel, totalItems, number, offset)
whenever(activityLogRestClient.fetchActivity(requestPayload, number, offset)).thenReturn(payload)
whenever(activityLogSqlUtils.insertOrUpdateActivities(any(), any())).thenReturn(rowsAffected)
return action
}
companion object {
private const val OFFSET = 0
private const val PAGE_SIZE = 100
}
}
| gpl-2.0 | a7a0563c7ef7c0ba57cc9b7b105f05c2 | 38.974708 | 119 | 0.687886 | 5.737783 | false | true | false | false |
wordpress-mobile/WordPress-FluxC-Android | example/src/test/java/org/wordpress/android/fluxc/network/rest/wpcom/products/ProductsRestClientTest.kt | 1 | 3734 | package org.wordpress.android.fluxc.network.rest.wpcom.products
import com.android.volley.RequestQueue
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.KArgumentCaptor
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.eq
import org.mockito.kotlin.whenever
import org.wordpress.android.fluxc.Dispatcher
import org.wordpress.android.fluxc.model.products.Product
import org.wordpress.android.fluxc.model.products.ProductsResponse
import org.wordpress.android.fluxc.network.BaseRequest.BaseNetworkError
import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR
import org.wordpress.android.fluxc.network.UserAgent
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequest.WPComGsonNetworkError
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Error
import org.wordpress.android.fluxc.network.rest.wpcom.WPComGsonRequestBuilder.Response.Success
import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken
import org.wordpress.android.fluxc.test
@RunWith(MockitoJUnitRunner::class)
class ProductsRestClientTest {
@Mock private lateinit var dispatcher: Dispatcher
@Mock private lateinit var wpComGsonRequestBuilder: WPComGsonRequestBuilder
@Mock private lateinit var requestQueue: RequestQueue
@Mock private lateinit var accessToken: AccessToken
@Mock private lateinit var userAgent: UserAgent
private lateinit var urlCaptor: KArgumentCaptor<String>
private lateinit var paramsCaptor: KArgumentCaptor<Map<String, String>>
private lateinit var productsRestClient: ProductsRestClient
@Before
fun setUp() {
urlCaptor = argumentCaptor()
paramsCaptor = argumentCaptor()
productsRestClient = ProductsRestClient(
dispatcher,
wpComGsonRequestBuilder,
null,
requestQueue,
accessToken,
userAgent
)
}
@Test
fun `returns products on successful fetch`() = test {
initRequest(data = Success(ProductsResponse(listOf(Product()))))
val response = productsRestClient.fetchProducts()
assertThat(response).isNotNull
assertThat(response).isInstanceOf(Success::class.java)
assertThat((response as Success).data.products).isNotEmpty
}
@Test
fun `returns error on unsuccessful fetch`() = test {
initRequest(error = WPComGsonNetworkError(BaseNetworkError(NETWORK_ERROR)))
val response = productsRestClient.fetchProducts()
assertThat(response).isNotNull
assertThat(response).isNotInstanceOf(Success::class.java)
assertThat(response).isInstanceOf(Error::class.java)
}
private suspend fun initRequest(
data: Response<ProductsResponse>? = null,
error: WPComGsonNetworkError? = null
) {
val response = if (error != null) Error(error) else data
whenever(
wpComGsonRequestBuilder.syncGetRequest(
eq(productsRestClient),
urlCaptor.capture(),
paramsCaptor.capture(),
eq(ProductsResponse::class.java),
eq(false),
any(),
eq(false)
)
).thenReturn(response)
}
}
| gpl-2.0 | 6f2d1ff894bff1120f164db98b1ce9bd | 37.494845 | 94 | 0.717461 | 5.07337 | false | true | false | false |
duncanleo/dpi-android | app/src/main/java/com/duncan/dpi/adapter/DeviceRVAdapter.kt | 1 | 1825 | package com.duncan.dpi.adapter
import android.graphics.Typeface
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.duncan.dpi.R
import com.duncan.dpi.`interface`.ItemClickListener
import com.duncan.dpi.model.Device
import kotlinx.android.synthetic.main.list_entry.view.*
/**
* Created by duncanleo on 13/11/16.
*/
class DeviceRVAdapter(data: List<Device>) : RecyclerView.Adapter<DeviceRVAdapter.ViewHolder>() {
private val data: List<Device>
var itemClickListener: ItemClickListener<Device>? = null
init {
this.data = data
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
val device = data[position]
holder?.deviceName?.text = device.name
holder?.deviceSpecs?.text = "${device.width}x${device.height} @ ${String.format("%.1f", device.screenSize)}\""
when(position) {
0 -> holder?.deviceName?.setTypeface(null, Typeface.BOLD)
else -> holder?.deviceName?.setTypeface(null, Typeface.NORMAL)
}
holder?.itemView?.setOnClickListener { view ->
itemClickListener?.onItemClick(view, device)
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent?.context).inflate(R.layout.list_entry, parent, false))
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val deviceName: TextView
val deviceSpecs: TextView
init {
this.deviceName = itemView.labelDeviceName
this.deviceSpecs = itemView.labelDeviceSpecs
}
}
} | mit | 04885a50278a6541303947cf02f7a6ae | 31.035088 | 118 | 0.687123 | 4.418886 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/command/control/CommandRecovery.kt | 1 | 1901 | package me.mrkirby153.KirBot.command.control
import me.mrkirby153.KirBot.Bot
import me.mrkirby153.KirBot.backfill.RecoveryManager
import me.mrkirby153.KirBot.command.CommandException
import me.mrkirby153.KirBot.command.annotations.AdminCommand
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.kcutils.Time
import javax.inject.Inject
class CommandRecovery @Inject constructor(private val recoveryManager: RecoveryManager) {
@AdminCommand
@Command(name = "global", arguments = ["<duration:string>", "[pool:int]"], parent = "recover")
fun globalRecovery(context: Context, cmdContext: CommandContext) {
val duration = try {
Time.parse(cmdContext.getNotNull("duration"))
} catch (e: IllegalArgumentException) {
throw CommandException(e.message)
}
val pool = cmdContext.get<Int>("pool") ?: 10
context.channel.sendMessage("Recovery started with $pool threads").complete()
val ar = recoveryManager.globalRecovery(duration, pool)
val msg = context.channel.sendMessage(
"Recovery status: ${ar.completed.size}/${ar.channels.size}").complete()
val start = System.currentTimeMillis()
Bot.scheduler.submit {
val end: Long
while (true) {
msg.editMessage("Recovery status: ${ar.completed.size}/${ar.channels.size}").queue()
if (ar.completed.size == ar.channels.size) {
end = System.currentTimeMillis()
break
}
Thread.sleep(5000)
}
context.channel.sendMessage("Recovery completed! (Took ${Time.format(1,
end - start)} and recovered ${ar.recoveredMessages} messages)").queue()
}
}
} | mit | dfa7ed903b130777d3efb23b8935f20a | 43.232558 | 100 | 0.657549 | 4.483491 | false | false | false | false |
mmorihiro/larger-circle | core/src/mmorihiro/matchland/view/HomeView.kt | 2 | 1351 | package mmorihiro.matchland.view
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.badlogic.gdx.scenes.scene2d.ui.Image
import ktx.actors.centerPosition
import ktx.assets.asset
import mmorihiro.matchland.model.ItemType
import mmorihiro.matchland.model.Values
class HomeView : View() {
val backGround = Image(asset<Texture>("homeBackground.png"))
private val itemLoader = ImageLoader(32, "items.png")
val icons = ItemType.values()
.filterNot { it == ItemType.WATER }
.mapIndexed { index, it ->
val item = itemLoader.load(it.position).apply {
x = 55 + 51f * index
y = 55f
color = Color.BLACK
}
Image(asset<Texture>("tile.png")).apply {
color = it.color
setPosition(item.x - 9, item.y - 9)
setOrigin(width / 2, height / 2)
} to item
}
val playButton = Button(Image(asset<Texture>("play.png")).drawable).apply {
centerPosition(Values.width, Values.height)
}
val battleButton = Button(Image(asset<Texture>("online.png")).drawable).apply {
x = playButton.x
y = playButton.y - height - 32
}
} | apache-2.0 | cdc142008c85a3a4b42cf8f8113ab8f9 | 34.578947 | 83 | 0.599556 | 4.169753 | false | false | false | false |
google/ksp | common-util/src/test/kotlin/com/google/devtools/ksp/processing/impl/CodeGeneratorImplTest.kt | 1 | 5178 | package com.google.devtools.ksp.processing.impl
import com.google.devtools.ksp.AnyChanges
import com.google.devtools.ksp.processing.Dependencies
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.io.File
import java.nio.file.Files
class CodeGeneratorImplTest {
lateinit var codeGenerator: CodeGeneratorImpl
lateinit var baseDir: File
@Before
fun setup() {
baseDir = Files.createTempDirectory("project").toFile()
val classesDir = File(baseDir, "classes")
classesDir.mkdir()
val javaDir = File(baseDir, "java")
javaDir.mkdir()
val kotlinDir = File(baseDir, "kotlin")
kotlinDir.mkdir()
val resourcesDir = File(baseDir, "resources")
resourcesDir.mkdir()
codeGenerator = CodeGeneratorImpl(
classesDir,
javaDir,
kotlinDir,
resourcesDir,
baseDir,
AnyChanges(baseDir),
emptyList(),
true
)
}
@Test
fun testCreatingAFile() {
codeGenerator.createNewFile(Dependencies.ALL_FILES, "a.b.c", "Test", "java")
codeGenerator.createNewFile(Dependencies.ALL_FILES, "a.b.c", "Test", "kt")
codeGenerator.createNewFile(Dependencies.ALL_FILES, "a.b.c", "Test", "class")
codeGenerator.createNewFile(Dependencies.ALL_FILES, "a.b.c", "Test", "")
val files = codeGenerator.generatedFile.toList()
Assert.assertEquals(File(baseDir, "java/a/b/c/Test.java"), files[0])
Assert.assertEquals(File(baseDir, "kotlin/a/b/c/Test.kt"), files[1])
Assert.assertEquals(File(baseDir, "classes/a/b/c/Test.class"), files[2])
Assert.assertEquals(File(baseDir, "resources/a/b/c/Test"), files[3])
try {
codeGenerator.outputs
} catch (e: Exception) {
Assert.fail("Failed to get outputs: ${e.message}")
}
}
@Test
fun testCreatingAFileWithSlash() {
codeGenerator.createNewFile(Dependencies.ALL_FILES, "a/b/c", "Test", "java")
codeGenerator.createNewFile(Dependencies.ALL_FILES, "a/b/c", "Test", "kt")
codeGenerator.createNewFile(Dependencies.ALL_FILES, "a/b/c", "Test", "class")
codeGenerator.createNewFile(Dependencies.ALL_FILES, "a/b/c", "Test", "")
val files = codeGenerator.generatedFile.toList()
Assert.assertEquals(File(baseDir, "java/a/b/c/Test.java"), files[0])
Assert.assertEquals(File(baseDir, "kotlin/a/b/c/Test.kt"), files[1])
Assert.assertEquals(File(baseDir, "classes/a/b/c/Test.class"), files[2])
Assert.assertEquals(File(baseDir, "resources/a/b/c/Test"), files[3])
try {
codeGenerator.outputs
} catch (e: Exception) {
Assert.fail("Failed to get outputs: ${e.message}")
}
}
@Test
fun testCreatingAFileWithPath() {
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "a/b/c/Test", "java")
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "a/b/c/Test")
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "a/b/c/Test", "class")
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "a/b/c/Test", "")
val files = codeGenerator.generatedFile.toList()
Assert.assertEquals(File(baseDir, "java/a/b/c/Test.java"), files[0])
Assert.assertEquals(File(baseDir, "kotlin/a/b/c/Test.kt"), files[1])
Assert.assertEquals(File(baseDir, "classes/a/b/c/Test.class"), files[2])
Assert.assertEquals(File(baseDir, "resources/a/b/c/Test"), files[3])
try {
codeGenerator.outputs
} catch (e: Exception) {
Assert.fail("Failed to get outputs: ${e.message}")
}
}
@Test
fun testCreatingAFileWithPathAndDots() {
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "a/b/c/dir.with.dot/Test", "java")
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "a/b/c/dir.with.dot/Test")
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "a/b/c/dir.with.dot/Test", "class")
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "a/b/c/dir.with.dot/Test", "")
val files = codeGenerator.generatedFile.toList()
Assert.assertEquals(File(baseDir, "java/a/b/c/dir.with.dot/Test.java"), files[0])
Assert.assertEquals(File(baseDir, "kotlin/a/b/c/dir.with.dot/Test.kt"), files[1])
Assert.assertEquals(File(baseDir, "classes/a/b/c/dir.with.dot/Test.class"), files[2])
Assert.assertEquals(File(baseDir, "resources/a/b/c/dir.with.dot/Test"), files[3])
try {
codeGenerator.outputs
} catch (e: Exception) {
Assert.fail("Failed to get outputs: ${e.message}")
}
}
@Test
fun testCreatingAFileByPathWithInvalidPath() {
try {
codeGenerator.createNewFileByPath(Dependencies.ALL_FILES, "../../b/c/Test", "java")
Assert.fail()
} catch (e: java.lang.IllegalStateException) {
Assert.assertEquals(e.message, "requested path is outside the bounds of the required directory")
}
}
}
| apache-2.0 | 3207062c516135a4588caa5dd0003a41 | 39.453125 | 108 | 0.638277 | 3.810155 | false | true | false | false |
google/prefab | ndk-build-plugin/src/main/kotlin/com/google/prefab/ndkbuild/NdkBuildPlugin.kt | 1 | 9230 | /*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.prefab.ndkbuild
import com.google.prefab.api.Android
import com.google.prefab.api.BuildSystemInterface
import com.google.prefab.api.LibraryReference
import com.google.prefab.api.Module
import com.google.prefab.api.NoMatchingLibraryException
import com.google.prefab.api.Package
import com.google.prefab.api.PlatformDataInterface
import java.io.File
import java.nio.file.Path
/**
* Sanitizes a path for use in an Android.mk file.
*
* Convert backslash separated paths to forward slash separated paths on
* Windows. Even on Windows, it's the norm to use forward slash separated paths
* for ndk-build.
*
* TODO: Figure out if we should be using split/join instead.
* It's not clear how that will behave with Windows \\?\ paths.
*/
fun Path.sanitize(): String = toString().replace('\\', '/')
/**
* The requested packages are mutually incompatible in ndk-build because module
* names are not unique across all packages.
*/
class DuplicateModuleNameException(a: Module, b: Module) : RuntimeException(
"Duplicate module name found (${a.canonicalName} and " +
"${b.canonicalName}). ndk-build does not support fully qualified " +
"module names."
)
/**
* The build plugin for
* [ndk-build](https://developer.android.com/ndk/guides/ndk-build).
*/
class NdkBuildPlugin(
override val outputDirectory: File,
override val packages: List<Package>
) : BuildSystemInterface {
override fun generate(requirements: Collection<PlatformDataInterface>) {
val androidRequirements =
requirements.filterIsInstance<Android>()
if (androidRequirements != requirements) {
throw UnsupportedOperationException(
"ndk-build only supports Android targets"
)
}
// ndk-build does not support fully-qualified module names, so verify
// that module names are unique across all packages.
val seenNames = mutableMapOf<String, Module>()
for (pkg in packages) {
for (module in pkg.modules) {
val dupModule = seenNames[module.name]
if (dupModule != null) {
throw DuplicateModuleNameException(module, dupModule)
}
seenNames[module.name] = module
}
}
prepareOutputDirectory(outputDirectory)
for (pkg in packages) {
val packageDir = outputDirectory.resolve(pkg.name)
packageDir.mkdir()
generatePackage(pkg, androidRequirements, packageDir)
}
}
private fun generatePackage(
pkg: Package,
requirements: Collection<Android>,
packageDirectory: File
) {
val androidMk = packageDirectory.resolve("Android.mk")
androidMk.writeText(
"""
LOCAL_PATH := $(call my-dir)
""".trimIndent()
)
for (requirement in requirements) {
androidMk.appendText(
"""
ifeq ($(TARGET_ARCH_ABI),${requirement.abi.targetArchAbi})
""".trimIndent()
)
for (module in pkg.modules.sortedBy { it.name }) {
emitModule(module, requirement, androidMk)
}
androidMk.appendText(
"""
endif # ${requirement.abi.targetArchAbi}
""".trimIndent()
)
}
for (dep in pkg.dependencies.sorted()) {
emitDependency(dep, androidMk)
}
}
private fun emitModule(
module: Module,
requirement: Android,
androidMk: File
) {
val ldLibs = mutableListOf<String>()
val sharedLibraries = mutableListOf<String>()
val staticLibraries = mutableListOf<String>()
for (reference in module.linkLibsForPlatform(requirement)) {
if (reference is LibraryReference.Literal) {
ldLibs.add(reference.arg)
} else {
val referredModule = findReferredModule(reference, module)
if (referredModule.isHeaderOnly) {
staticLibraries.add(referredModule.name)
} else {
try {
val prebuilt = referredModule.getLibraryFor(requirement)
when (val extension =
prebuilt.path.toFile().extension) {
"so" -> sharedLibraries.add(referredModule.name)
"a" -> staticLibraries.add(referredModule.name)
else -> throw RuntimeException(
"Unrecognized library extension: $extension"
)
}
} catch (ex: NoMatchingLibraryException) {
System.err.println(
"Skipping ${module.canonicalName} because it " +
"depends on an incompatible library:")
System.err.print(ex)
return
}
}
}
}
val exportLdLibs =
ldLibs.joinToString(" ", prefix = " ").trimEnd()
val exportSharedLibraries =
sharedLibraries.joinToString(" ", prefix = " ").trimEnd()
val exportStaticLibraries =
staticLibraries.joinToString(" ", prefix = " ").trimEnd()
if (module.isHeaderOnly) {
// ndk-build doesn't have an explicit header-only library type; it's
// just a static library with no sources.
val escapedHeaders = module.includePath.sanitize()
androidMk.appendText(
"""
include $(CLEAR_VARS)
LOCAL_MODULE := ${module.name}
LOCAL_EXPORT_C_INCLUDES := $escapedHeaders
LOCAL_EXPORT_SHARED_LIBRARIES :=$exportSharedLibraries
LOCAL_EXPORT_STATIC_LIBRARIES :=$exportStaticLibraries
LOCAL_EXPORT_LDLIBS :=$exportLdLibs
include $(BUILD_STATIC_LIBRARY)
""".trimIndent()
)
} else {
try {
val prebuilt = module.getLibraryFor(requirement)
val escapedLibrary = prebuilt.path.sanitize()
val escapedHeaders = prebuilt.includePath.sanitize()
val prebuiltType: String =
when (val extension = prebuilt.path.toFile().extension) {
"so" -> "PREBUILT_SHARED_LIBRARY"
"a" -> "PREBUILT_STATIC_LIBRARY"
else -> throw RuntimeException(
"Unrecognized library extension: $extension"
)
}
androidMk.appendText(
"""
include $(CLEAR_VARS)
LOCAL_MODULE := ${module.name}
LOCAL_SRC_FILES := $escapedLibrary
LOCAL_EXPORT_C_INCLUDES := $escapedHeaders
LOCAL_EXPORT_SHARED_LIBRARIES :=$exportSharedLibraries
LOCAL_EXPORT_STATIC_LIBRARIES :=$exportStaticLibraries
LOCAL_EXPORT_LDLIBS :=$exportLdLibs
include $($prebuiltType)
""".trimIndent()
)
} catch (ex: NoMatchingLibraryException) {
// Libraries that do not match our requirements should be logged
// and ignored.
System.err.println(ex)
}
}
}
private fun emitDependency(dependency: String, androidMk: File) {
androidMk.appendText(
"""
$(call import-module,prefab/$dependency)
""".trimIndent()
)
}
/**
* Finds the module matching a given library reference.
*/
private fun findReferredModule(
reference: LibraryReference,
currentModule: Module
): Module = when (reference) {
is LibraryReference.Local -> packages.find {
it.name == currentModule.pkg.name
}?.modules?.find { it.name == reference.name }
is LibraryReference.External -> packages.find {
it.name == reference.pkg
}?.modules?.find { it.name == reference.module }
is LibraryReference.Literal -> throw IllegalArgumentException(
"Literal library references do not have types"
)
} ?: throw RuntimeException(
"Could not find a module matching $reference"
)
}
| apache-2.0 | 74d5f810420ecc372261692dae5beb45 | 34.5 | 80 | 0.56533 | 5.054765 | false | false | false | false |
geckour/Egret | app/src/main/java/com/geckour/egret/view/adapter/BlockAccountAdapter.kt | 1 | 1927 | package com.geckour.egret.view.adapter
import android.databinding.DataBindingUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import com.geckour.egret.R
import com.geckour.egret.api.model.Account
import com.geckour.egret.databinding.ItemRecycleBlockAccountBinding
class BlockAccountAdapter: RecyclerView.Adapter<BlockAccountAdapter.ViewHolder>() {
private val items: ArrayList<Account> = ArrayList()
inner class ViewHolder(val binding: ItemRecycleBlockAccountBinding): RecyclerView.ViewHolder(binding.root) {
fun bindData(item: Account) {
binding.item = item
}
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ViewHolder {
val binding: ItemRecycleBlockAccountBinding =
DataBindingUtil.inflate(LayoutInflater.from(parent?.context), R.layout.item_recycle_block_account, parent, false)
return ViewHolder(binding)
}
override fun onBindViewHolder(holder: ViewHolder?, position: Int) {
val item = this.items[position]
holder?.bindData(item)
}
override fun getItemCount(): Int = this.items.size
fun getItems(): List<Account> = this.items
fun addItem(item: Account) {
this.items.add(item)
notifyItemInserted(this.items.lastIndex)
}
fun addAllItems(items: List<Account>) {
if (items.isNotEmpty()) {
val size = this.items.size
this.items.addAll(size, items)
notifyItemRangeInserted(0, items.size)
}
}
fun removeItemsByIndex(index: Int) {
items.removeAt(index)
notifyItemRemoved(index)
}
fun clearItems() {
val size = this.items.size
this.items.clear()
notifyItemRangeRemoved(0, size)
}
fun resetItems(items: List<Account>) {
clearItems()
addAllItems(items)
}
} | gpl-3.0 | 181456588ddd338f5a1ef5282c20a16f | 29.125 | 129 | 0.681889 | 4.460648 | false | false | false | false |
http4k/http4k | src/docs/guide/howto/integrate_with_openapi/example.kt | 1 | 4584 | package guide.howto.integrate_with_openapi
import org.http4k.contract.bind
import org.http4k.contract.contract
import org.http4k.contract.div
import org.http4k.contract.meta
import org.http4k.contract.openapi.ApiInfo
import org.http4k.contract.openapi.v3.ApiServer
import org.http4k.contract.openapi.v3.OpenApi3
import org.http4k.contract.security.ApiKeySecurity
import org.http4k.core.Body
import org.http4k.core.ContentType.Companion.TEXT_PLAIN
import org.http4k.core.Filter
import org.http4k.core.HttpHandler
import org.http4k.core.HttpTransaction
import org.http4k.core.Method.GET
import org.http4k.core.Response
import org.http4k.core.Status.Companion.OK
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.core.with
import org.http4k.filter.CachingFilters.Response.NoCache
import org.http4k.filter.CorsPolicy
import org.http4k.filter.ResponseFilters
import org.http4k.filter.ServerFilters
import org.http4k.format.Argo
import org.http4k.format.Jackson
import org.http4k.lens.Path
import org.http4k.lens.Query
import org.http4k.lens.int
import org.http4k.lens.string
import org.http4k.routing.ResourceLoader.Companion.Classpath
import org.http4k.routing.bind
import org.http4k.routing.routes
import org.http4k.routing.static
import org.http4k.server.Jetty
import org.http4k.server.asServer
import java.time.Clock
fun main() {
fun add(value1: Int, value2: Int): HttpHandler = {
Response(OK).with(
Body.string(TEXT_PLAIN).toLens() of (value1 + value2).toString()
)
}
val ageQuery = Query.int().required("age")
fun echo(name: String): HttpHandler = {
Response(OK).with(
Body.string(TEXT_PLAIN).toLens() of "hello $name you are ${ageQuery(it)}"
)
}
val filter: Filter =
ResponseFilters.ReportHttpTransaction(Clock.systemUTC()) { tx: HttpTransaction ->
println(tx.labels.toString() + " took " + tx.duration)
}
val mySecurity = ApiKeySecurity(Query.int().required("apiKey"), { it == 42 })
val contract = contract {
renderer = OpenApi3(
ApiInfo("my great api", "v1.0"),
Argo,
servers = listOf(ApiServer(Uri.of("http://localhost:8000"), "the greatest server"))
)
descriptionPath = "/docs/swagger.json"
security = mySecurity
routes += "/ping" meta {
summary = "add"
description = "Adds 2 numbers together"
returning(OK to "The result")
} bindContract GET to { _ -> Response(OK).body("pong") }
routes += "/add" / Path.int().of("value1") / Path.int().of("value2") meta {
summary = "add"
description = "Adds 2 numbers together"
returning(OK to "The result")
} bindContract GET to ::add
// note here that the trailing parameter can be ignored - it would simply be the value "divide".
routes += Path.int().of("value1") / Path.int().of("value2") / "divide" meta {
summary = "divide"
description = "Divides 2 numbers"
returning(OK to "The result")
} bindContract GET to { first, second, _ ->
{ Response(OK).body((first / second).toString()) }
}
routes += "/echo" / Path.of("name") meta {
summary = "echo"
queries += ageQuery
} bindContract GET to ::echo
}
val handler = routes(
"/context" bind filter.then(contract),
"/static" bind NoCache().then(static(Classpath("guide/howto/nestable_routes"))),
"/" bind contract {
renderer = OpenApi3(ApiInfo("my great super api", "v1.0"), Jackson)
routes += "/echo" / Path.of("name") meta {
summary = "echo"
queries += ageQuery
} bindContract GET to ::echo
}
)
ServerFilters.Cors(CorsPolicy.UnsafeGlobalPermissive).then(handler).asServer(Jetty(8000))
.start()
}
// Ping! curl -v "http://localhost:8000/context/ping?apiKey=42"
// Adding 2 numbers: curl -v "http://localhost:8000/context/add/123/564?apiKey=42"
// Echo (fail): curl -v "http://localhost:8000/context/echo/myName?age=notANumber&apiKey=42"
// API Key enforcement: curl -v "http://localhost:8000/context/add/123/564?apiKey=444"
// Static content: curl -v "http://localhost:8000/static/someStaticFile.txt"
// OpenApi/Swagger documentation: curl -v "http://localhost:8000/context/docs/swagger.json"
// Echo endpoint (at root): curl -v "http://localhost:8000/echo/hello?age=123"
| apache-2.0 | 7d77db160396dac498d219f5723ac7a5 | 37.2 | 104 | 0.653141 | 3.629454 | false | false | false | false |
Bodo1981/swapi.co | app/src/main/java/com/christianbahl/swapico/details/DetailsActivity.kt | 1 | 1192 | package com.christianbahl.swapico.details
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import com.christianbahl.appkit.core.activity.CBActivityFragment
import com.christianbahl.swapico.list.model.ListType
/**
* @author Christian Bahl
*/
class DetailsActivity : CBActivityFragment() {
lateinit private var listType: ListType
private var detailsId: Int = 1
companion object {
val INTENT_EXTRA_DETAILS_TYPE = "details_type"
val INTENT_EXTRA_DETAILS_ID = "details_id"
fun getStartIntent(context: Context, detailsType: ListType, detailsId: Int): Intent {
val i = Intent(context, DetailsActivity::class.java)
i.putExtra(INTENT_EXTRA_DETAILS_TYPE, detailsType.name)
i.putExtra(INTENT_EXTRA_DETAILS_ID, detailsId);
return i
}
}
override fun createFragmentToDisplay(): Fragment? {
return DetailsFragmentBuilder(detailsId, listType).build()
}
override fun readExtras(bundle: Bundle) {
super.readExtras(bundle)
listType = ListType.valueOf(bundle.getString(INTENT_EXTRA_DETAILS_TYPE))
detailsId = bundle.getInt(INTENT_EXTRA_DETAILS_ID, 1)
}
} | apache-2.0 | 4789eb87afc2b3af7089240f40fc3168 | 28.825 | 89 | 0.749161 | 3.908197 | false | false | false | false |
lbbento/pitchup | app/src/main/kotlin/com/lbbento/pitchupapp/ui/view/PitchUpNoteViewPresenter.kt | 1 | 781 | package com.lbbento.pitchupapp.ui.view
internal class PitchUpNoteViewPresenter {
val NOTE_PROPERTY = "note"
val notes: List<String>
get() = listOf("C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B")
val adapterNotes: List<Map<String, String>>
get() = notes.map { mapOf(NOTE_PROPERTY to it) }
lateinit var pitchUpNoteView: PitchUpNote
fun onAttachView(pitchUpNoteView: PitchUpNote) {
this.pitchUpNoteView = pitchUpNoteView
}
fun onFinishInflate() {
pitchUpNoteView.showNotesList(adapterNotes)
}
fun onSmoothScrollToNote(note: String) {
when {
notes.indexOf(note) >= 0 -> {
pitchUpNoteView.scrollToPosition(notes.indexOf(note))
}
}
}
} | apache-2.0 | 95a39fdea9c73ad58199d147b85267e0 | 25.965517 | 87 | 0.595391 | 3.632558 | false | false | false | false |
joan-domingo/Podcasts-RAC1-Android | app/src/main/java/cat/xojan/random1/feature/browser/SectionListAdapter.kt | 1 | 2285 | package cat.xojan.random1.feature.browser
import android.support.v4.media.MediaBrowserCompat
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import cat.xojan.random1.R
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.section_item.*
import java.util.*
class SectionListAdapter(private val activity: BrowseActivity)
: RecyclerView.Adapter<SectionListAdapter.MediaItemViewHolder>() {
var sections: List<MediaBrowserCompat.MediaItem> = emptyList()
set(value) {
field = value
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MediaItemViewHolder {
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.section_item, parent, false)
return MediaItemViewHolder(itemView)
}
override fun onBindViewHolder(holder: MediaItemViewHolder, position: Int) {
holder.bind(sections[position], activity)
}
override fun getItemCount(): Int = sections.size
class MediaItemViewHolder(override val containerView: View)
: RecyclerView.ViewHolder(containerView),LayoutContainer {
fun bind(item: MediaBrowserCompat.MediaItem, activity: BrowseActivity) {
itemView.setOnClickListener {
val podcastListFragment = SectionPodcastListFragment.newInstance(item.mediaId)
activity.addFragment(podcastListFragment, SectionPodcastListFragment.TAG, true)
}
val section = item.description
section_title.text = section.title
Glide.with(itemView.context)
.load(section.iconUri.toString() + "?w=" + getWeekOfTheYear())
.apply(RequestOptions()
.override(200, 200)
.circleCrop()
.placeholder(R.drawable.placeholder))
.into(section_image)
}
private fun getWeekOfTheYear(): Int {
val cal = Calendar.getInstance()
return cal.get(Calendar.WEEK_OF_YEAR)
}
}
} | mit | 221013f73475b13f4c10e558ac3947c3 | 37.1 | 104 | 0.674398 | 5.04415 | false | false | false | false |
fan123199/V2ex-simple | app/src/main/java/im/fdx/v2ex/ui/member/ReplyAdapter.kt | 1 | 2252 | package im.fdx.v2ex.ui.member
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import im.fdx.v2ex.R
import im.fdx.v2ex.ui.topic.TopicActivity
import im.fdx.v2ex.utils.Keys
import im.fdx.v2ex.utils.TimeUtil
import im.fdx.v2ex.view.GoodTextView
import org.jetbrains.anko.startActivity
/**
* Created by fdx on 2017/7/15.
* fdx will maintain it
* 在用户信息的回复页面
*/
class ReplyAdapter(val activity: Activity,
var list: MutableList<MemberReplyModel> = mutableListOf())
: androidx.recyclerview.widget.RecyclerView.Adapter<ReplyAdapter.ReplyViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
ReplyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_reply_member, parent, false))
override fun onBindViewHolder(holder: ReplyViewHolder, position: Int) {
val reply = list[position]
holder.tvTitle.text = reply.topic.title
holder.tvContent.setGoodText(reply.content, true)
holder.tvTime.text = TimeUtil.getRelativeTime(reply.create)
holder.itemView.setOnClickListener {
activity.startActivity<TopicActivity>(Keys.KEY_TOPIC_ID to reply.topic.id)
}
}
fun updateItem(newItems: List<MemberReplyModel>) {
// val diffResult = DiffUtil.calculateDiff(DiffReply(list, newItems))
list.clear()
list.addAll(newItems)
notifyDataSetChanged()
// diffResult.dispatchUpdatesTo(this)
}
fun addItems(newItems: List<MemberReplyModel>) {
val old = list.toList()
list.addAll(newItems)
val diffResult = DiffUtil.calculateDiff(DiffReply(old, list))
diffResult.dispatchUpdatesTo(this)
}
override fun getItemCount() = list.size
inner class ReplyViewHolder(itemView: View) : androidx.recyclerview.widget.RecyclerView.ViewHolder(itemView) {
val tvTitle: TextView = itemView.findViewById(R.id.tv_title)
val tvContent: GoodTextView = itemView.findViewById(R.id.tv_content_reply)
val tvTime: TextView = itemView.findViewById(R.id.tv_create)
}
} | apache-2.0 | d8c9846df4cc337bef66f12cea772478 | 33.890625 | 115 | 0.722222 | 4.028881 | false | false | false | false |
Aidanvii7/Toolbox | adapterviews-databinding-recyclerview/src/test/java/com/aidanvii/toolbox/adapterviews/databinding/recyclerview/AdapterNotifierDelegateTest.kt | 1 | 10805 | package com.aidanvii.toolbox.adapterviews.databinding.recyclerview
import com.aidanvii.toolbox.boundInt
import com.aidanvii.toolbox.databinding.NotifiableObservable
import com.nhaarman.mockito_kotlin.argumentCaptor
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.never
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import org.amshove.kluent.`should be equal to`
import org.amshove.kluent.`should be`
import org.amshove.kluent.any
import org.amshove.kluent.mock
import org.junit.Test
import java.util.*
class AdapterNotifierDelegateTest {
val random = Random()
val expectedAdapterPosition = random.nextInt()
val mockNotifiable = mock<NotifiableObservable>()
val mockAdapter = mock<BindingRecyclerViewAdapter<*>>().apply {
whenever(getItemPositionFromBindableItem(any())).thenReturn(expectedAdapterPosition)
}
val tested = AdapterNotifier.delegate().apply {
initAdapterNotifierDelegator(mockNotifiable)
}
@Test
fun `given the adapter is bound and outwith bind phase, when notifyAdapterPropertyChanged is called with fullRebind false, notifyItemChanged is called on adapter with correct data`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
notifyAdapterPropertiesChanged(fullRebind = false, expectedPropertyIds = expectedPropertyIds)
verifyAdapterNotifiedWithCorrectPayload(expectedPropertyIds = *expectedPropertyIds)
}
@Test
fun `given the adapter is bound and outwith bind phase, when notifyAdapterPropertyChanged is called with fullRebind true, notifyItemChanged is called on adapter with correct data`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
notifyAdapterPropertiesChanged(fullRebind = true, expectedPropertyIds = expectedPropertyIds)
verifyAdapterNotifiedWithoutPayload(expectedPropertyIds = *expectedPropertyIds)
}
@Test
fun `given the adapter is bound and during bind phase, when notifyAdapterPropertyChanged is called with fullRebind false, notifyPropertyChanged is called on given NotifiableObservable with correct data`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.adapterBindStart(mockAdapter)
notifyAdapterPropertiesChanged(fullRebind = false, expectedPropertyIds = expectedPropertyIds)
verifyAdapterNeverNotified()
verifyObservableNotifiedWithCorrectPayload(expectedPropertyIds = *expectedPropertyIds)
}
@Test
fun `given the adapter is bound and during bind phase, when notifyAdapterPropertyChanged is called with fullRebind true, notifyPropertyChanged is called on given NotifiableObservable with correct data`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.adapterBindStart(mockAdapter)
notifyAdapterPropertiesChanged(fullRebind = true, expectedPropertyIds = expectedPropertyIds)
verifyAdapterNeverNotified()
verifyObservableNotified(times = expectedPropertyIds.size)
}
@Test
fun `given the adapter is bound, outwith bind phase and paused, when notifyAdapterPropertyChanged is called with fullRebind false, no notifications are fired`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.beginBatchedUpdates()
notifyAdapterPropertiesChanged(fullRebind = false, expectedPropertyIds = expectedPropertyIds)
verifyAdapterNeverNotified()
verifyObservableNeverNotified()
}
@Test
fun `given the adapter is bound, outwith bind phase and paused, when notifyAdapterPropertyChanged is called with fullRebind true, no notifications are fired`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.beginBatchedUpdates()
notifyAdapterPropertiesChanged(fullRebind = true, expectedPropertyIds = expectedPropertyIds)
verifyAdapterNeverNotified()
verifyObservableNeverNotified()
}
@Test
fun `given the adapter is bound, outwith bind phase, paused and has pending property changes with fullRebind false, when endBatchedUpdates is called, notifyItemChanged is called on adapter with correct data`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.beginBatchedUpdates()
notifyAdapterPropertiesChanged(fullRebind = false, expectedPropertyIds = expectedPropertyIds)
tested.endBatchedUpdates()
verifyAdapterNotifiedWithCorrectPayloadWhileBatched(*expectedPropertyIds)
}
@Test
fun `given the adapter is bound, outwith bind phase, paused and has pending property changes with fullRebind true, when endBatchedUpdates is called, notifyItemChanged is called on adapter with correct data`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.beginBatchedUpdates()
notifyAdapterPropertiesChanged(fullRebind = true, expectedPropertyIds = expectedPropertyIds)
tested.endBatchedUpdates()
verifyAdapterNotifiedWithoutPayload()
}
@Test
fun `given the adapter is bound, during bind phase and paused, when notifyAdapterPropertyChanged is called with fullRebind false, no notifications are fired`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.adapterBindStart(mockAdapter)
tested.beginBatchedUpdates()
notifyAdapterPropertiesChanged(fullRebind = false, expectedPropertyIds = expectedPropertyIds)
verifyAdapterNeverNotified()
verifyObservableNeverNotified()
}
@Test
fun `given the adapter is bound, during bind phase and paused, when notifyAdapterPropertyChanged is called with fullRebind true, no notifications are fired`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.adapterBindStart(mockAdapter)
tested.beginBatchedUpdates()
notifyAdapterPropertiesChanged(fullRebind = true, expectedPropertyIds = expectedPropertyIds)
verifyAdapterNeverNotified()
verifyObservableNeverNotified()
}
@Test
fun `given the adapter is bound, during bind phase, paused and has pending property changes with fullRebind false, when endBatchedUpdates is called, notifyPropertyChanged is called on given NotifiableObservable with correct data`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.adapterBindStart(mockAdapter)
tested.beginBatchedUpdates()
notifyAdapterPropertiesChanged(fullRebind = false, expectedPropertyIds = expectedPropertyIds)
tested.endBatchedUpdates()
verifyAdapterNeverNotified()
verifyObservableNotifiedWithCorrectPayload(expectedPropertyIds = *expectedPropertyIds)
}
@Test
fun `given the adapter is bound, during bind phase, paused and has pending property changes with fullRebind true, when endBatchedUpdates is called, notifyPropertyChanged is called on given NotifiableObservable with correct data`() {
val expectedPropertyIds = nextRandomIds()
tested.bindAdapter(mockAdapter)
tested.adapterBindStart(mockAdapter)
tested.beginBatchedUpdates()
notifyAdapterPropertiesChanged(fullRebind = true, expectedPropertyIds = expectedPropertyIds)
tested.endBatchedUpdates()
verifyAdapterNeverNotified()
verifyObservableNotified(times = 1)
}
fun nextRandomIds(): IntArray = (0..random.boundInt(1, 20)).distinct().toIntArray()
fun notifyAdapterPropertiesChanged(fullRebind: Boolean, expectedPropertyIds: IntArray) {
expectedPropertyIds.forEach {
tested.notifyAdapterPropertyChanged(it, fullRebind)
}
}
fun verifyObservableNeverNotified() {
verify(mockNotifiable, never()).notifyPropertyChanged(any())
}
fun verifyAdapterNeverNotified() {
verify(mockAdapter, never()).notifyItemChanged(any(), any())
}
fun verifyAdapterNotifiedWithCorrectPayload(vararg expectedPropertyIds: Int) {
inOrder(mockAdapter).apply {
for (expectedPropertyId in expectedPropertyIds) {
argumentCaptor<Int>().apply {
verify(mockAdapter).notifyItemChanged(capture(), any())
firstValue `should be equal to` expectedAdapterPosition
}
}
}
inOrder(mockAdapter).apply {
for (expectedPropertyId in expectedPropertyIds) {
argumentCaptor<AdapterNotifier.ChangePayload>().apply {
verify(mockAdapter).notifyItemChanged(any(), capture())
firstValue.apply {
sender `should be` tested
changedProperties.size `should be equal to` 1
changedProperties[0] `should be equal to` expectedPropertyId
}
}
}
}
}
fun verifyAdapterNotifiedWithoutPayload(vararg expectedPropertyIds: Int) {
inOrder(mockAdapter).apply {
for (expectedPropertyId in expectedPropertyIds) {
argumentCaptor<Int>().apply {
verify(mockAdapter).notifyItemChanged(capture())
firstValue `should be equal to` expectedAdapterPosition
}
}
}
}
fun verifyAdapterNotifiedWithCorrectPayloadWhileBatched(vararg expectedPropertyIds: Int) {
argumentCaptor<Int>().apply {
verify(mockAdapter).notifyItemChanged(capture(), any())
firstValue `should be equal to` expectedAdapterPosition
}
argumentCaptor<AdapterNotifier.ChangePayload>().apply {
verify(mockAdapter).notifyItemChanged(any(), capture())
firstValue.apply {
sender `should be` tested
changedProperties.size `should be equal to` expectedPropertyIds.size
expectedPropertyIds.forEachIndexed { index, expectedPropertyIds ->
changedProperties[index] `should be equal to` expectedPropertyIds
}
}
}
}
fun verifyObservableNotifiedWithCorrectPayload(vararg expectedPropertyIds: Int) {
for (expectedPropertyId in expectedPropertyIds) {
verify(mockNotifiable).notifyPropertyChanged(expectedPropertyId)
}
}
fun verifyObservableNotified(times: Int) {
verify(mockNotifiable, times(times)).notifyChange()
}
} | apache-2.0 | ed766c5de5fe8a908ae4d9f1bc707a6e | 41.376471 | 237 | 0.715965 | 5.150143 | false | true | false | false |
sephiroth74/android-target-tooltip | xtooltip/src/main/java/it/sephiroth/android/library/xtooltip/Utils.kt | 1 | 5338 | package it.sephiroth.android.library.xtooltip
import android.animation.Animator
import android.graphics.Rect
import android.view.View
import android.view.ViewPropertyAnimator
import android.view.animation.Animation
/**
* Created by alessandro crugnola on 12/12/15.
* [email protected]
*
*
* LICENSE
* Copyright 2015 Alessandro Crugnola
* 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.
*/
internal inline fun Rect.rectContainsWithTolerance(childRect: Rect, t: Int): Boolean {
return this.contains(childRect.left + t, childRect.top + t, childRect.right - t, childRect.bottom - t)
}
internal inline fun View.addOnAttachStateChangeListener(func: AttachStateChangeListener.() -> Unit): View {
val listener = AttachStateChangeListener()
listener.func()
addOnAttachStateChangeListener(listener)
return this
}
internal class AttachStateChangeListener : View.OnAttachStateChangeListener {
private var _onViewAttachedToWindow: ((view: View?, listener: View.OnAttachStateChangeListener) -> Unit)? = null
private var _onViewDetachedFromWindow: ((view: View?, listener: View.OnAttachStateChangeListener) -> Unit)? = null
fun onViewDetachedFromWindow(func: (view: View?, listener: View.OnAttachStateChangeListener) -> Unit) {
_onViewDetachedFromWindow = func
}
fun onViewAttachedToWindow(func: (view: View?, listener: View.OnAttachStateChangeListener) -> Unit) {
_onViewAttachedToWindow = func
}
override fun onViewDetachedFromWindow(v: View?) {
_onViewDetachedFromWindow?.invoke(v, this)
}
override fun onViewAttachedToWindow(v: View?) {
_onViewAttachedToWindow?.invoke(v, this)
}
}
internal inline fun ViewPropertyAnimator.setListener(
func: ViewPropertyAnimatorListener.() -> Unit
): ViewPropertyAnimator {
val listener = ViewPropertyAnimatorListener()
listener.func()
setListener(listener)
return this
}
internal inline fun Animation.setListener(func: AnimationListener.() -> Unit): Animation {
val listener = AnimationListener()
listener.func()
setAnimationListener(listener)
return this
}
internal class AnimationListener : Animation.AnimationListener {
private var _onAnimationRepeat: ((animation: Animation?) -> Unit)? = null
private var _onAnimationEnd: ((animation: Animation?) -> Unit)? = null
private var _onAnimationStart: ((animation: Animation?) -> Unit)? = null
override fun onAnimationRepeat(animation: Animation?) {
_onAnimationRepeat?.invoke(animation)
}
override fun onAnimationEnd(animation: Animation?) {
_onAnimationEnd?.invoke(animation)
}
override fun onAnimationStart(animation: Animation?) {
_onAnimationStart?.invoke(animation)
}
fun onAnimationEnd(func: (animation: Animation?) -> Unit) {
_onAnimationEnd = func
}
fun onAnimationRepeat(func: (animation: Animation?) -> Unit) {
_onAnimationRepeat = func
}
fun onAnimationStart(func: (animation: Animation?) -> Unit) {
_onAnimationStart = func
}
}
@Suppress("unused")
internal class ViewPropertyAnimatorListener : Animator.AnimatorListener {
private var _onAnimationRepeat: ((animation: Animator) -> Unit)? = null
private var _onAnimationEnd: ((animation: Animator) -> Unit)? = null
private var _onAnimationStart: ((animation: Animator) -> Unit)? = null
private var _onAnimationCancel: ((animation: Animator) -> Unit)? = null
override fun onAnimationRepeat(animation: Animator) {
_onAnimationRepeat?.invoke(animation)
}
override fun onAnimationCancel(animation: Animator) {
_onAnimationCancel?.invoke(animation)
}
override fun onAnimationEnd(animation: Animator) {
_onAnimationEnd?.invoke(animation)
}
override fun onAnimationStart(animation: Animator) {
_onAnimationStart?.invoke(animation)
}
fun onAnimationRepeat(func: (animation: Animator) -> Unit) {
_onAnimationRepeat = func
}
fun onAnimationCancel(func: (animation: Animator) -> Unit) {
_onAnimationCancel = func
}
fun onAnimationEnd(func: (animation: Animator) -> Unit) {
_onAnimationEnd = func
}
fun onAnimationStart(func: (animation: Animator) -> Unit) {
_onAnimationStart = func
}
} | mit | 6f6e49753b9f684daaebbf8b64f2a27a | 35.568493 | 130 | 0.721619 | 4.861566 | false | false | false | false |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientUpdateJigsawBlockDecoder.kt | 1 | 1199 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientUpdateJigsawBlockPacket
object ClientUpdateJigsawBlockDecoder : PacketDecoder<ClientUpdateJigsawBlockPacket> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): ClientUpdateJigsawBlockPacket {
val position = buf.readBlockPosition()
val name = buf.readString()
val target = buf.readString()
val pool = buf.readString()
val finalState = buf.readString()
val jointType = buf.readString()
return ClientUpdateJigsawBlockPacket(position, name, target, pool, finalState, jointType)
}
}
| mit | a4689b14c0a44db52e354bdb56d1f53c | 40.344828 | 97 | 0.753962 | 4.221831 | false | false | false | false |
jensim/kotlin-koans | src/ii_collections/_21_Partition_.kt | 1 | 626 | package ii_collections
fun example8() {
val numbers = listOf(1, 3, -4, 2, -11)
// The details (how multi-assignment works) will be explained later in the 'Conventions' task
val (positive, negative) = numbers.partition { it > 0 }
positive == listOf(1, 3, 2)
negative == listOf(-4, -11)
}
fun Shop.getCustomersWithMoreUndeliveredOrdersThanDelivered(): Set<Customer> {
// Return customers who have more undelivered orders than delivered
val (pos, neg) = customers.partition {
c -> c.orders.sumBy {
o -> if (o.isDelivered) 1 else -1
} < 0
}
return pos.toSet()
}
| mit | bd0aa02f371e9c21fb3f4b6aae25f8d0 | 28.809524 | 97 | 0.635783 | 3.793939 | false | false | false | false |
sabi0/intellij-community | platform/testGuiFramework/src/com/intellij/testGuiFramework/impl/ComponentFixtureUtils.kt | 1 | 21856 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.testGuiFramework.impl
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.ui.ComponentWithBrowseButton
import com.intellij.testGuiFramework.cellReader.ExtendedJComboboxCellReader
import com.intellij.testGuiFramework.cellReader.ExtendedJListCellReader
import com.intellij.testGuiFramework.util.FinderPredicate
import com.intellij.testGuiFramework.fixtures.*
import com.intellij.testGuiFramework.fixtures.extended.ExtendedButtonFixture
import com.intellij.testGuiFramework.fixtures.extended.ExtendedJTreePathFixture
import com.intellij.testGuiFramework.fixtures.extended.ExtendedTableFixture
import com.intellij.testGuiFramework.framework.GuiTestUtil
import com.intellij.testGuiFramework.framework.Timeouts.defaultTimeout
import com.intellij.testGuiFramework.util.Predicate
import com.intellij.ui.CheckboxTree
import com.intellij.ui.HyperlinkLabel
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBList
import com.intellij.ui.components.labels.LinkLabel
import com.intellij.ui.treeStructure.treetable.TreeTable
import com.intellij.util.ui.AsyncProcessIcon
import org.fest.swing.core.GenericTypeMatcher
import org.fest.swing.core.Robot
import org.fest.swing.exception.ComponentLookupException
import org.fest.swing.fixture.JLabelFixture
import org.fest.swing.fixture.JListFixture
import org.fest.swing.fixture.JSpinnerFixture
import org.fest.swing.fixture.JTextComponentFixture
import org.fest.swing.timing.Timeout
import org.junit.Assert
import java.awt.Component
import java.awt.Container
import java.util.concurrent.TimeUnit
import javax.swing.*
//*********FIXTURES METHODS WITHOUT ROBOT and TARGET; KOTLIN ONLY
/**
* Finds a JList component in hierarchy of context component with a containingItem and returns JListFixture.
*
* @timeout in seconds to find JList component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.jList(containingItem: String? = null, timeout: Timeout = defaultTimeout): JListFixture =
if (target() is Container) {
val extCellReader = ExtendedJListCellReader()
val myJList = waitUntilFound(target() as Container, JList::class.java, timeout) { jList: JList<*> ->
if (containingItem == null) true //if were searching for any jList()
else {
val elements = (0 until jList.model.size).map { it: Int -> extCellReader.valueAt(jList as JList<Any?>, it) }
elements.any { it.toString() == containingItem } && jList.isShowing
}
}
val jListFixture = JListFixture(robot(), myJList)
jListFixture.replaceCellReader(extCellReader)
jListFixture
}
else throw unableToFindComponent("JList")
/**
* Finds a JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture.
*
* @timeout in seconds to find JButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.button(name: String, timeout: Timeout = defaultTimeout): ExtendedButtonFixture =
if (target() is Container) {
val jButton = waitUntilFound(target() as Container, JButton::class.java, timeout) {
it.isShowing && it.isVisible && it.text == name
}
ExtendedButtonFixture(robot(), jButton)
}
else throw unableToFindComponent("""JButton named by $name""")
/**
* Finds a list of JButton component in hierarchy of context component with a name and returns ExtendedButtonFixture.
* There can be cases when there are several the same named components and it's OK
*
* @timeout in seconds to find JButton component
* @throws ComponentLookupException if no component has not been found or timeout exceeded
* @return list of JButton components sorted by locationOnScreen (left to right, top to down)
*/
fun <S, C : Component> ComponentFixture<S, C>.buttons(name: String, timeout: Timeout = defaultTimeout): List<ExtendedButtonFixture> =
if (target() is Container) {
val jButtons = waitUntilFoundList(target() as Container, JButton::class.java, timeout) {
it.isShowing && it.isVisible && it.text == name
}
jButtons
.map { ExtendedButtonFixture(GuiRobotHolder.robot, it) }
.sortedBy { it.target().locationOnScreen.x }
.sortedBy { it.target().locationOnScreen.y }
}
else throw unableToFindComponent("""JButton named by $name""")
fun <S, C : Component> ComponentFixture<S, C>.componentWithBrowseButton(boundedLabelText: String,
timeout: Timeout = defaultTimeout): ComponentWithBrowseButtonFixture {
if (target() is Container) {
val boundedLabel = waitUntilFound(target() as Container, JLabel::class.java, timeout) {
it.text == boundedLabelText && it.isShowing
}
val component = boundedLabel.labelFor
if (component is ComponentWithBrowseButton<*>) {
return ComponentWithBrowseButtonFixture(component, robot())
}
}
throw unableToFindComponent("ComponentWithBrowseButton with labelFor=$boundedLabelText")
}
fun <S, C : Component> ComponentFixture<S, C>.treeTable(timeout: Timeout = defaultTimeout): TreeTableFixture {
if (target() is Container) {
val table = GuiTestUtil.waitUntilFound(robot(), target() as Container,
GuiTestUtilKt.typeMatcher(TreeTable::class.java) { true },
timeout
)
return TreeTableFixture(robot(), table)
}
else throw UnsupportedOperationException(
"Sorry, unable to find inspections tree with ${target()} as a Container")
}
fun <S, C : Component> ComponentFixture<S, C>.spinner(boundedLabelText: String, timeout: Timeout = defaultTimeout): JSpinnerFixture {
if (target() is Container) {
val boundedLabel = waitUntilFound(target() as Container, JLabel::class.java, timeout) { it.text == boundedLabelText }
val component = boundedLabel.labelFor
if (component is JSpinner)
return JSpinnerFixture(robot(), component)
}
throw unableToFindComponent("""JSpinner with $boundedLabelText bounded label""")
}
/**
* Finds a JComboBox component in hierarchy of context component by text of label and returns ComboBoxFixture.
*
* @timeout in seconds to find JComboBox component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.combobox(labelText: String, timeout: Timeout = defaultTimeout): ComboBoxFixture =
if (target() is Container) {
val comboBox = GuiTestUtilKt.findBoundedComponentByText(robot(), target() as Container, labelText, JComboBox::class.java)
val comboboxFixture = ComboBoxFixture(robot(), comboBox)
comboboxFixture.replaceCellReader(ExtendedJComboboxCellReader())
comboboxFixture
}
else throw unableToFindComponent("""JComboBox near label by "$labelText"""")
/**
* Finds a JCheckBox component in hierarchy of context component by text of label and returns CheckBoxFixture.
*
* @timeout in seconds to find JCheckBox component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.checkbox(labelText: String, timeout: Timeout = defaultTimeout): CheckBoxFixture =
if (target() is Container) {
val jCheckBox = waitUntilFound(target() as Container, JCheckBox::class.java, timeout) {
it.isShowing && it.isVisible && it.text == labelText
}
CheckBoxFixture(robot(), jCheckBox)
}
else throw unableToFindComponent("""JCheckBox label by "$labelText""")
/**
* Finds a ActionLink component in hierarchy of context component by name and returns ActionLinkFixture.
*
* @timeout in seconds to find ActionLink component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.actionLink(name: String, timeout: Timeout = defaultTimeout): ActionLinkFixture =
if (target() is Container) {
ActionLinkFixture.findActionLinkByName(name, robot(), target() as Container, timeout)
}
else throw unableToFindComponent("""ActionLink by name "$name"""")
/**
* Finds a ActionButton component in hierarchy of context component by action name and returns ActionButtonFixture.
*
* @actionName text or action id of an action button (@see com.intellij.openapi.actionSystem.ActionManager#getId())
* @timeout in seconds to find ActionButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.actionButton(actionName: String, timeout: Timeout = defaultTimeout): ActionButtonFixture =
if (target() is Container) {
try {
ActionButtonFixture.findByText(actionName, robot(), target() as Container, timeout)
}
catch (componentLookupException: ComponentLookupException) {
ActionButtonFixture.findByActionId(actionName, robot(), target() as Container, timeout)
}
}
else throw unableToFindComponent("""ActionButton by action name "$actionName"""")
/**
* Finds a InplaceButton component in hierarchy of context component by icon and returns InplaceButtonFixture.
*
* @icon of InplaceButton component.
* @timeout in seconds to find InplaceButton component. It is better to use static cached icons from (@see com.intellij.openapi.util.IconLoader.AllIcons)
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.inplaceButton(icon: Icon, timeout: Timeout = defaultTimeout): InplaceButtonFixture {
val target = target()
return if (target is Container) {
InplaceButtonFixture.findInplaceButtonFixture(target, robot(), icon, timeout)
}
else throw unableToFindComponent("""InplaceButton by icon "$icon"""")
}
/**
* Finds a ActionButton component in hierarchy of context component by action class name and returns ActionButtonFixture.
*
* @actionClassName qualified name of class for action
* @timeout in seconds to find ActionButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.actionButtonByClass(actionClassName: String,
timeout: Timeout = defaultTimeout): ActionButtonFixture =
if (target() is Container) {
ActionButtonFixture.findByActionClassName(actionClassName, robot(), target() as Container, timeout)
}
else throw unableToFindComponent("""ActionButton by action class name "$actionClassName"""")
/**
* Finds a JRadioButton component in hierarchy of context component by label text and returns JRadioButtonFixture.
*
* @timeout in seconds to find JRadioButton component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.radioButton(textLabel: String, timeout: Timeout = defaultTimeout): RadioButtonFixture =
if (target() is Container) GuiTestUtil.findRadioButton(target() as Container, textLabel, timeout)
else throw unableToFindComponent("""RadioButton by label "$textLabel"""")
/**
* Finds a JTextComponent component (JTextField) in hierarchy of context component by text of label and returns JTextComponentFixture.
*
* @textLabel could be a null if label is absent
* @timeout in seconds to find JTextComponent component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.textfield(textLabel: String?, timeout: Timeout = defaultTimeout): JTextComponentFixture {
val target = target()
if (target is Container) {
return GuiTestUtil.textfield(textLabel, target, timeout)
}
else throw unableToFindComponent("""JTextComponent (JTextField) by label "$textLabel"""")
}
/**
* Finds a JTree component in hierarchy of context component by a path and returns ExtendedTreeFixture.
*
* @pathStrings comma separated array of Strings, representing path items: jTree("myProject", "src", "Main.java")
* @timeout in seconds to find JTree component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.jTree(
vararg pathStrings: String,
timeout: Timeout = defaultTimeout,
predicate: FinderPredicate = Predicate.equality
): ExtendedJTreePathFixture =
if (target() is Container) ExtendedJTreePathFixture(GuiTestUtil.jTreeComponent(
container = target() as Container,
timeout = timeout,
pathStrings = *pathStrings,
predicate = predicate
), pathStrings.toList(), predicate)
else throw unableToFindComponent("""JTree "${if (pathStrings.isNotEmpty()) "by path $pathStrings" else ""}"""")
/**
* Finds a CheckboxTree component in hierarchy of context component by a path and returns CheckboxTreeFixture.
*
* @pathStrings comma separated array of Strings, representing path items: checkboxTree("JBoss", "JBoss Drools")
* @timeout in seconds to find JTree component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.checkboxTree(
vararg pathStrings: String,
timeout: Timeout = defaultTimeout,
predicate: FinderPredicate = Predicate.equality
): CheckboxTreeFixture =
if (target() is Container) {
val tree = GuiTestUtil.jTreeComponent(
container = target() as Container,
timeout = timeout,
predicate = predicate,
pathStrings = *pathStrings
) as? CheckboxTree ?: throw ComponentLookupException("Found JTree but not a CheckboxTree")
CheckboxTreeFixture(tree, pathStrings.toList(), predicate, robot())
}
else throw unableToFindComponent("""CheckboxTree "${if (pathStrings.isNotEmpty()) "by path ${pathStrings.joinToString()}" else ""}"""")
/**
* Finds a JTable component in hierarchy of context component by a cellText and returns JTableFixture.
*
* @timeout in seconds to find JTable component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.table(cellText: String, timeout: Timeout = defaultTimeout): ExtendedTableFixture =
if (target() is Container) {
var tableFixture: ExtendedTableFixture? = null
waitUntilFound(target() as Container, JTable::class.java, timeout) {
tableFixture = com.intellij.testGuiFramework.fixtures.extended.ExtendedTableFixture(robot(), it)
try {
tableFixture?.cell(cellText)
tableFixture != null
}
catch (e: org.fest.swing.exception.ActionFailedException) {
false
}
}
tableFixture ?: throw unableToFindComponent("""JTable with cell text "$cellText"""")
}
else throw unableToFindComponent("""JTable with cell text "$cellText"""")
fun popupMenu(
item: String,
robot: Robot,
root: Container? = null,
timeout: Timeout = defaultTimeout,
predicate: FinderPredicate = Predicate.equality
): JBListPopupFixture{
val jbList = GuiTestUtil.waitUntilFound(
robot,
root,
object : GenericTypeMatcher<JBList<*>>(JBList::class.java) {
override fun isMatching(component: JBList<*>): Boolean {
return JBListPopupFixture(component, item, predicate, robot).isSearchedItemPresent()
}
},
timeout)
return JBListPopupFixture(jbList, item, predicate, robot)
}
fun <S, C : Component> ComponentFixture<S, C>.popupMenu(
item: String,
timeout: Timeout = defaultTimeout,
predicate: FinderPredicate = Predicate.equality
): JBListPopupFixture {
if (target() is Container) {
val root: Container? = GuiTestUtil.getRootContainer(target())
Assert.assertNotNull(root)
return popupMenu(item, robot(), root, timeout, predicate)
}
else throw unableToFindComponent("JBList with item '${item}' not found")
}
/**
* Finds a LinkLabel component in hierarchy of context component by a link name and returns fixture for it.
*
* @timeout in seconds to find LinkLabel component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.linkLabel(linkName: String, timeout: Timeout = defaultTimeout) =
if (target() is Container) {
val myLinkLabel = GuiTestUtil.waitUntilFound(
robot(), target() as Container,
GuiTestUtilKt.typeMatcher(LinkLabel::class.java) { it.isShowing && (it.text == linkName) },
timeout)
ComponentFixture(ComponentFixture::class.java, robot(), myLinkLabel)
}
else throw unableToFindComponent("LinkLabel")
fun <S, C : Component> ComponentFixture<S, C>.hyperlinkLabel(labelText: String, timeout: Timeout = defaultTimeout): HyperlinkLabelFixture =
if (target() is Container) {
val hyperlinkLabel = GuiTestUtil.waitUntilFound(robot(), target() as Container,
GuiTestUtilKt.typeMatcher(HyperlinkLabel::class.java) {
it.isShowing && (it.text == labelText)
}, timeout)
HyperlinkLabelFixture(robot(), hyperlinkLabel)
}
else throw unableToFindComponent("""HyperlinkLabel by label text: "$labelText"""")
/**
* Finds a table of plugins component in hierarchy of context component by a link name and returns fixture for it.
*
* @timeout in seconds to find table of plugins component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.pluginTable(timeout: Timeout = defaultTimeout) =
if (target() is Container) PluginTableFixture.find(robot(), target() as Container, timeout)
else throw unableToFindComponent("PluginTable")
/**
* Finds a Message component in hierarchy of context component by a title MessageFixture.
*
* @timeout in seconds to find component for Message
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.message(title: String, timeout: Timeout = defaultTimeout) =
if (target() is Container) MessagesFixture.findByTitle(robot(), target() as Container, title, timeout)
else throw unableToFindComponent("Message")
/**
* Finds a Message component in hierarchy of context component by a title MessageFixture.
*
* @timeout in seconds to find component for Message
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.message(title: String, timeout: Timeout = defaultTimeout, func: MessagesFixture.() -> Unit) {
if (target() is Container) func(MessagesFixture.findByTitle(robot(), target() as Container, title, timeout))
else throw unableToFindComponent("Message")
}
/**
* Finds a JBLabel component in hierarchy of context component by a label name and returns fixture for it.
*
* @timeout in seconds to find JBLabel component
* @throws ComponentLookupException if component has not been found or timeout exceeded
*/
fun <S, C : Component> ComponentFixture<S, C>.label(labelName: String, timeout: Timeout = defaultTimeout): JLabelFixture =
if (target() is Container) {
val jbLabel = GuiTestUtil.waitUntilFound(
robot(), target() as Container,
GuiTestUtilKt.typeMatcher(JBLabel::class.java) { it.isShowing && (it.text == labelName || labelName in it.text) },
timeout)
JLabelFixture(robot(), jbLabel)
}
else throw unableToFindComponent("JBLabel")
private fun <S, C : Component> ComponentFixture<S, C>.unableToFindComponent(component: String): ComponentLookupException =
ComponentLookupException("""Sorry, unable to find $component component with ${target()} as a Container""")
/**
* Find an AsyncProcessIcon component in a current context (gets by receiver) and returns a fixture for it.
* Indexing processIcon is excluded from this search
*
* @timeout timeout in seconds to find AsyncProcessIcon
*/
fun <S, C : Component> ComponentFixture<S, C>.asyncProcessIcon(timeout: Timeout = defaultTimeout): AsyncProcessIconFixture {
val indexingProcessIconTooltipText = ActionsBundle.message("action.ShowProcessWindow.double.click")
val asyncProcessIcon = GuiTestUtil.waitUntilFound(
robot(),
target() as Container,
GuiTestUtilKt.typeMatcher(AsyncProcessIcon::class.java) {
it.isShowing &&
it.isVisible &&
it.toolTipText != indexingProcessIconTooltipText
},
timeout)
return AsyncProcessIconFixture(robot(), asyncProcessIcon)
}
internal fun Long.toFestTimeout(): Timeout = if (this == 0L) Timeout.timeout(50, TimeUnit.MILLISECONDS)
else Timeout.timeout(this, TimeUnit.SECONDS)
fun <ComponentType : Component> waitUntilFound(container: Container?,
componentClass: Class<ComponentType>,
timeout: Timeout,
matcher: (ComponentType) -> Boolean): ComponentType {
return GuiTestUtil.waitUntilFound(GuiRobotHolder.robot, container, GuiTestUtilKt.typeMatcher(componentClass) { matcher(it) },
timeout)
}
fun <ComponentType : Component> waitUntilFoundList(container: Container?,
componentClass: Class<ComponentType>,
timeout: Timeout,
matcher: (ComponentType) -> Boolean): List<ComponentType> {
return GuiTestUtil.waitUntilFoundList(container, timeout, GuiTestUtilKt.typeMatcher(componentClass) { matcher(it) })
}
| apache-2.0 | df7d68d20cb561d675effd265670045d | 46.307359 | 153 | 0.730189 | 4.794034 | false | true | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/data/api/model/RatePreInfo.kt | 1 | 6008 | package me.ykrank.s1next.data.api.model
import com.fasterxml.jackson.core.JsonParseException
import com.github.ykrank.androidtools.util.L
import me.ykrank.s1next.data.api.ApiUtil
import me.ykrank.s1next.data.api.model.wrapper.HtmlDataWrapper
import org.jsoup.Jsoup
import paperparcel.PaperParcel
import paperparcel.PaperParcelable
import java.util.*
/**
* Created by ykrank on 2017/3/19.
*/
@PaperParcel
class RatePreInfo : PaperParcelable {
var formHash: String? = null
var tid: String? = null
var pid: String? = null
var refer: String? = null
var handleKey: String? = null
var minScore: Int = 0
var maxScore: Int = 0
var totalScore: String? = null
var reasons: List<String> = arrayListOf()
var isChecked: Boolean = false
var isDisabled: Boolean = false
var scoreChoices: List<String> = arrayListOf()
fun setScoreChoices() {
val list = ArrayList<String>()
for (i in minScore..maxScore) {
if (i != 0) {
list.add(i.toString())
}
}
this.scoreChoices = list
}
override fun toString(): String {
return "RatePreInfo{" +
"formHash='" + formHash + '\''.toString() +
", tid='" + tid + '\''.toString() +
", pid='" + pid + '\''.toString() +
", refer='" + refer + '\''.toString() +
", handleKey='" + handleKey + '\''.toString() +
", minScore=" + minScore +
", maxScore=" + maxScore +
", totalScore=" + totalScore +
", reasons=" + reasons +
", checked=" + isChecked +
", disabled=" + isDisabled +
", scoreChoices=" + scoreChoices +
'}'.toString()
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as RatePreInfo
if (formHash != other.formHash) return false
if (tid != other.tid) return false
if (pid != other.pid) return false
if (refer != other.refer) return false
if (handleKey != other.handleKey) return false
if (minScore != other.minScore) return false
if (maxScore != other.maxScore) return false
if (totalScore != other.totalScore) return false
if (reasons != other.reasons) return false
if (isChecked != other.isChecked) return false
if (isDisabled != other.isDisabled) return false
if (scoreChoices != other.scoreChoices) return false
return true
}
override fun hashCode(): Int {
var result = formHash?.hashCode() ?: 0
result = 31 * result + (tid?.hashCode() ?: 0)
result = 31 * result + (pid?.hashCode() ?: 0)
result = 31 * result + (refer?.hashCode() ?: 0)
result = 31 * result + (handleKey?.hashCode() ?: 0)
result = 31 * result + (minScore?.hashCode() ?: 0)
result = 31 * result + (maxScore?.hashCode() ?: 0)
result = 31 * result + (totalScore?.hashCode() ?: 0)
result = 31 * result + (reasons?.hashCode() ?: 0)
result = 31 * result + isChecked.hashCode()
result = 31 * result + isDisabled.hashCode()
result = 31 * result + (scoreChoices?.hashCode() ?: 0)
return result
}
companion object {
@JvmField
val CREATOR = PaperParcelRatePreInfo.CREATOR
fun fromHtml(html: String): RatePreInfo {
var html = html
val info = RatePreInfo()
//remove html wrap
html = ApiUtil.replaceAjaxHeader(html)
try {
val document = Jsoup.parse(html)
HtmlDataWrapper.preAlertAjaxHtml(document)
var elements = document.select("#rateform>input")
if (elements.size != 5) {
throw JsonParseException(null, "#rateform>input size is " + elements.size)
}
info.formHash = elements[0].attr("value")
info.tid = elements[1].attr("value")
info.pid = elements[2].attr("value")
info.refer = elements[3].attr("value")
info.handleKey = elements[4].attr("value")
//score
elements = document.select(".dt.mbm>tbody>tr")
if (elements.size != 2) {
throw JsonParseException(null, ".dt.mbm>tbody>tr size is " + elements.size)
}
val scoreElements = elements[1].children()
val minMaxScoreString = scoreElements[2].text().trim { it <= ' ' }
val splitResult = minMaxScoreString.split("~".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
info.minScore = splitResult[0].trim { it <= ' ' }.toIntOrNull() ?: 0
info.maxScore = splitResult[1].trim { it <= ' ' }.toIntOrNull() ?: 0
info.totalScore = scoreElements[3].text().trim { it <= ' ' }
//reasons
val reasons = ArrayList<String>()
elements = document.select("#reasonselect>li")
for (element in elements) {
reasons.add(element.text())
}
info.reasons = reasons
//checkbox
elements = document.select("#sendreasonpm")
if (elements.size != 1) {
throw JsonParseException(null, "#sendreasonpm size is " + elements.size)
}
val checkBoxElement = elements[0]
info.isChecked = "checked".equals(checkBoxElement.attr("checked"), ignoreCase = true)
info.isDisabled = "disabled".equals(checkBoxElement.attr("disabled"), ignoreCase = true)
info.setScoreChoices()
} catch (e: Exception) {
L.report(e)
throw e
}
return info
}
}
}
| apache-2.0 | 828e7be8e310825bdb1420b35b4cb390 | 38.012987 | 118 | 0.539947 | 4.493642 | false | false | false | false |
ykrank/S1-Next | app/src/main/java/me/ykrank/s1next/view/fragment/WebViewFragment.kt | 1 | 6004 | package me.ykrank.s1next.view.fragment
import android.annotation.SuppressLint
import androidx.databinding.DataBindingUtil
import android.os.Build
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.webkit.WebChromeClient
import android.webkit.WebSettings
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.ProgressBar
import com.github.ykrank.androidtools.util.WebViewUtils
import me.ykrank.s1next.App
import me.ykrank.s1next.R
import me.ykrank.s1next.databinding.FragmentWebviewBinding
import me.ykrank.s1next.view.internal.BackPressDelegate
import me.ykrank.s1next.viewmodel.WebPageViewModel
import java.net.CookieManager
import javax.inject.Inject
/**
* Local WebView for PC web site and sync OkHttp cookie
* Created by ykrank on 2017/6/8.
*/
class WebViewFragment : BaseFragment(), BackPressDelegate {
private lateinit var url: String
private var enableJs: Boolean = false
private var pcAgent: Boolean = false
@Inject
internal lateinit var mCookieManager: CookieManager
private lateinit var binding: FragmentWebviewBinding
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
App.appComponent.inject(this)
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_webview, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val bundle = arguments!!
url = bundle.getString(ARG_URL)!!
enableJs = bundle.getBoolean(ARG_ENABLE_JS)
pcAgent = bundle.getBoolean(ARG_PC_AGENT)
binding.webPageViewModel = WebPageViewModel()
initWebViewSetting()
initWebViewClient()
// restore the state of WebView when configuration changes
// see http://www.devahead.com/blog/2012/01/preserving-the-state-of-an-android-webview-on-screen-orientation-change/
if (savedInstanceState == null) {
binding.webView.loadUrl(url)
} else {
binding.webView.restoreState(savedInstanceState)
// if we haven't finished loading before
if (binding.webView.url == null) {
binding.webView.loadUrl(url)
}
}
//Only one webView instance in application, so we should resume timers because we stop it onDestroy
binding.webView.resumeTimers()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
binding.webView.saveState(outState)
}
override fun onDestroy() {
super.onDestroy()
binding.layoutRoot.removeAllViews()
if (binding.webView != null) {
binding.webView.clearHistory()
binding.webView.loadUrl("about:blank")
binding.webView.freeMemory()
binding.webView.pauseTimers()
}
}
override fun onBackPressed(): Boolean {
if (binding.webView.canGoBack()) {
binding.webView.goBack()
return true
}
return false
}
@SuppressLint("SetJavaScriptEnabled")
private fun initWebViewSetting() {
val webSettings = binding.webView.settings
webSettings.javaScriptEnabled = enableJs
webSettings.cacheMode = WebSettings.LOAD_DEFAULT
webSettings.setSupportZoom(true) //支持缩放
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING
} else {
webSettings.layoutAlgorithm = WebSettings.LayoutAlgorithm.SINGLE_COLUMN
}
webSettings.javaScriptCanOpenWindowsAutomatically = true //支持通过JS打开新窗口
if (pcAgent) {
webSettings.userAgentString = "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:51.0) Gecko/20100101 Firefox/51.0"
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
//Since Lollipop (API 21), WebView blocks all mixed content by default.
//But login page need load mixed content
webSettings.mixedContentMode = WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE
}
}
private fun initWebViewClient() {
binding.webView.webViewClient = object : WebViewClient() {
override fun onPageFinished(view: WebView, url: String) {
binding.webPageViewModel?.setFinishedLoading(true)
super.onPageFinished(view, url)
}
}
binding.webView.webChromeClient = ProgressWebChromeClient(binding.progressBar)
WebViewUtils.syncWebViewCookies(context!!, mCookieManager.cookieStore)
}
companion object {
val TAG: String = WebViewFragment::class.java.name
const val ARG_URL = "arg_url"
const val ARG_ENABLE_JS = "arg_enable_js"
const val ARG_PC_AGENT = "arg_pc_agent"
fun getInstance(url: String, enableJS: Boolean = false, pcAgent: Boolean = true): WebViewFragment {
val fragment = WebViewFragment()
val bundle = Bundle()
bundle.putString(ARG_URL, url)
bundle.putBoolean(ARG_ENABLE_JS, enableJS)
bundle.putBoolean(ARG_PC_AGENT, pcAgent)
fragment.arguments = bundle
return fragment
}
}
}
open class ProgressWebChromeClient(private val mProgressBar: ProgressBar) : WebChromeClient() {
override fun onProgressChanged(view: WebView, newProgress: Int) {
if (newProgress == 100) {
mProgressBar.visibility = View.INVISIBLE
} else {
if (View.INVISIBLE == mProgressBar.visibility) {
mProgressBar.visibility = View.VISIBLE
}
mProgressBar.progress = newProgress
}
super.onProgressChanged(view, newProgress)
}
} | apache-2.0 | fb187a2d7d5cc731ba2508a7006a1fde | 35.236364 | 124 | 0.67464 | 4.688627 | false | false | false | false |
colriot/anko | preview/idea-plugin/src/org/jetbrains/kotlin/android/dslpreview/RobowrapperContext.kt | 1 | 6684 | /*
* Copyright 2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.android.dslpreview
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiClass
import java.io.File
import java.util.*
class RobowrapperContext(description: PreviewClassDescription) {
internal val androidFacet = description.androidFacet
internal val activityClassName = description.qualifiedName
private val mainSourceProvider = androidFacet.mainIdeaSourceProvider
private val applicationPackage = androidFacet.manifest?.`package`?.xmlAttributeValue?.value ?: "app"
private val assetsDirectory = mainSourceProvider.assetsDirectories.firstOrNull()
private val resDirectory = mainSourceProvider.resDirectories.firstOrNull()
private val activities by lazy {
androidFacet.manifest?.application?.activities ?: listOf()
}
private val manifest by lazy { generateManifest() }
private fun <T> runReadAction(action: () -> T): T {
return ApplicationManager.getApplication().runReadAction<T>(action)
}
private fun generateManifest() = runReadAction {
val activityEntries = activities.map {
val clazz = it.activityClass
val theme = if (clazz.value.isAppCompatActivity()) "android:theme=\"@style/Theme.AppCompat\"" else ""
"<activity android:name=\"${clazz.toString()}\" $theme />"
}.joinToString("\n")
val manifestFile = File.createTempFile("AndroidManifest", ".xml")
manifestFile.writeText(
"""<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="%PACKAGE%">
<uses-sdk android:targetSdkVersion="21"/>
<application>
%ACTIVITIES%
</application>
</manifest>""".replace("%PACKAGE%", applicationPackage).replace("%ACTIVITIES%", activityEntries))
manifestFile
}
// `manifest` is already initialized at this point
internal fun removeManifest() {
if (manifest.exists()) {
manifest.delete()
}
}
private fun ArrayList<String>.add(name: String, value: String) = add(name + escape(value))
private fun ArrayList<String>.add(name: String, value: VirtualFile) = add(name + escape(value.path))
private fun ArrayList<String>.add(name: String, value: File) = add(name + escape(value.absolutePath))
fun makeArguments(): List<String> {
val module = androidFacet.module
val roots = ModuleRootManager.getInstance(module).orderEntries().classes().roots
val androidSdkDirectory = androidFacet.sdkData?.location?.getPath()
val pluginJarPath = PathManager.getJarPathForClass(javaClass)!!
val pluginDirectory = File(pluginJarPath).getParent()
val robowrapperDirectory = File(
File(pluginJarPath).parentFile.parentFile, "robowrapper/")
val robolectricMavenDependencies = RobowrapperDependencies.DEPENDENCIES.map { it.file.absolutePath }.joinToString(":")
val robowrapperDependencies = listOf(
"gson-2.3.jar",
"jeromq-0.3.4.jar")
.map { File(pluginDirectory, it).absolutePath }.joinToString(":", prefix = ":")
val robolectricDependencies = robowrapperDirectory
.listFiles { it.name.endsWith(".jar") }
?.map { it.absolutePath }?.joinToString(":", prefix = ":") ?: ""
val androidDependencies = resolveAndroidDependencies(roots, androidSdkDirectory)
val dependencyDirectory = RobowrapperDependencies.DEPENDENCIES_DIRECTORY
val sdk = ModuleRootManager.getInstance(module).sdk
val sdkType = sdk?.sdkType
val pathToJava = if (sdk != null && sdkType is JavaSdkType) {
sdkType.getVMExecutablePath(sdk)
} else "java"
val a = arrayListOf(escape(pathToJava), "-cp")
with (a) {
add(robolectricMavenDependencies + robowrapperDependencies + robolectricDependencies + androidDependencies)
add("-Djava.io.tmpdir=", File(dependencyDirectory, "tmp"))
add("-Drobolectric.offline=true")
add("-Drobolectric.dependency.dir=", dependencyDirectory)
add("-Drobo.activityClass=", activityClassName)
add("-Drobo.packageName=", applicationPackage)
add("-Dandroid.manifest=", manifest)
add("-Dandroid.resources=", resDirectory!!)
if (assetsDirectory != null) {
add("-Dandroid.assets=", assetsDirectory)
} else {
add("-Dandroid.assets=", File(resDirectory.parent.path, "assets"))
}
//TODO: check policy file loading
//add("-Djava.security.manager=default")
//add("-Djava.security.policy=", File(dependencyDirectory, "robowrapper.policy"))
add("org.jetbrains.kotlin.android.robowrapper.Robowrapper")
this
}
return a
}
private fun resolveAndroidDependencies(roots: Array<VirtualFile>, androidSdkDirectory: String?): String {
val sb = StringBuilder()
for (root in roots) {
var item = root.path
if (androidSdkDirectory != null && item.startsWith(androidSdkDirectory)) {
continue
}
if (item.endsWith("!/")) {
item = item.substring(0, item.length - 2)
}
sb.append(':').append(item.replace(":", "\":"))
}
return sb.toString()
}
private fun escape(v: String?): String {
return (v ?: "").replace("\"", "\\\"").replace(" ", "\\ ")
}
private fun PsiClass?.isAppCompatActivity(): Boolean {
if (this == null) return false
if (qualifiedName == "android.support.v7.app.AppCompatActivity") return true
else return superClass?.isAppCompatActivity() ?: false
}
} | apache-2.0 | 9828114a59c93fd7890f573e8d6a2eaf | 40.521739 | 126 | 0.652902 | 4.723675 | false | false | false | false |
brayvqz/ejercicios_kotlin | edad_persona/main.kt | 1 | 865 | package edad_persona
import java.util.*
/**
* Created by brayan on 16/04/2017.
*/
fun main(args: Array<String>) {
var scan = Scanner(System.`in`)
println("Digite su nombre : ")
var nombre = scan.next()
println("Digite su edad : ")
var edad = scan.nextInt()
println("Digite su sexo: \nM=>masculino \nF=>Femenino \nO=>Otro - indefinido")
var sexo = scan.next()
println("Digite su estado civil: \nS=>soltero/a \nC=>casado/a \nV=>viudo/a")
var civil = scan.next()
verificarEdad(nombre,edad,sexo,civil)
}
fun verificarEdad(nombre:String="",edad:Int=0,sexo:String="M",civil:String=""){
if(edad>30 && sexo=="M" && civil == "S"){
println("${nombre} es un hombre soltero mayor de 30 años")
}else if(edad<50 && sexo=="F" && civil=="V"){
println("${nombre} es una mujer viuda menor de 50 años")
}
}
| mit | 143bd6f809c622e6fecd46b5a4141ffb | 28.758621 | 82 | 0.616454 | 2.713836 | false | false | false | false |
cedardevs/onestop | buildSrc/src/main/kotlin/EsMapping.kt | 1 | 15058 | import com.sun.codemodel.JCodeModel
import org.gradle.api.DefaultTask
/* import org.gradle.api.tasks.Input */
import org.gradle.api.tasks.TaskAction
import org.jsonschema2pojo.DefaultGenerationConfig
import org.jsonschema2pojo.GenerationConfig
import org.jsonschema2pojo.SchemaMapper
import org.jsonschema2pojo.rules.RuleFactory
import org.jsonschema2pojo.Jackson2Annotator
import org.jsonschema2pojo.SchemaStore
import org.jsonschema2pojo.SchemaGenerator
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.Path
import java.io.File
import java.net.URL
import com.google.gson.Gson
import com.google.gson.JsonObject
import com.google.gson.JsonArray
open class ESMappingTask : DefaultTask() {
fun keyIndicatesArray(key:String) :Boolean {
return key == "errors" || key == "links" || key == "checksums" || key == "dataFormats" || key == "serviceLinks" || key == "legalConstraints" || key == "citeAsStatements" || key == "largerWorks" || key == "crossReferences"
}
fun keyIndicatesSet(key:String) :Boolean {
return key == "individualNames" || key == "organizationNames" || key == "dataFormat" || key == "linkProtocol" || key == "serviceLinkProtocol" || key == "keywords" || key.startsWith("gcmd")
}
fun buildJsonSchemaProperties(mappingObject: JsonObject, isGranule:Boolean, overrideNoArrays:Boolean): JsonObject {
val properties = JsonObject()
for (key in mappingObject.keySet()) {
val prop = mappingObject.get(key).getAsJsonObject()
if (prop.get("type") == null || prop.get("type").getAsString() == "nested") {
val desc = JsonObject()
val childOverrideNoArrays : Boolean
desc.addProperty("type", "object")
// automatically makes java class in the correct package and name
if(prop.get("properties").getAsJsonObject().keySet().contains("linkName")) {
// hack it to only produce one link class instead of several
desc.addProperty("javaType", "org.cedar.onestop.mapping.Link")
childOverrideNoArrays = true
} else {
childOverrideNoArrays = overrideNoArrays
}
if(key == "crossReferences" || key == "largerWorks") {
desc.addProperty("javaType", "org.cedar.onestop.mapping.search.Reference")
}
if(key == "identification") { // note this is the only place where the 2 analysisError indices differ
if (isGranule) {
desc.addProperty("javaType", "org.cedar.onestop.mapping.analysis.GranuleIdentification")
} else {
desc.addProperty("javaType", "org.cedar.onestop.mapping.analysis.CollectionIdentification")
}
}
desc.add("properties", buildJsonSchemaProperties(prop.get("properties").getAsJsonObject(), isGranule, childOverrideNoArrays)) // TODO overrideNoArrays hack to prevent Link object getting called with linkProtocol as a list...
properties.add(key, desc)
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
} else if (prop.get("type").getAsString() == "text" || prop.get("type").getAsString() == "keyword") {
val desc = JsonObject()
desc.addProperty("type", "string")
properties.add(key, desc)
if (key == "dataFormat" || key == "linkProtocol" || key == "serviceLinkProtocol") {
desc.addProperty("description", "DEPRECATED (see OpenAPI for details)")
}
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
} else if (prop.get("type").getAsString() == "long" ) {
val desc = JsonObject()
desc.addProperty("type", "object") // using "object" instead of "integer" because I can specify javaType which is more specific than making everything a long
desc.addProperty("existingJavaType", "java.lang.Long")
properties.add(key, desc)
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
} else if (prop.get("type").getAsString() == "byte") {
val desc = JsonObject()
desc.addProperty("type", "object") // using "object" instead of "integer" because I can specify javaType which is more specific than making everything a long
desc.addProperty("existingJavaType", "java.lang.Byte")
properties.add(key, desc)
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
} else if (prop.get("type").getAsString() == "short") {
val desc = JsonObject()
desc.addProperty("type", "object") // using "object" instead of "integer" because I can specify javaType which is more specific than making everything a long
desc.addProperty("existingJavaType", "java.lang.Short")
properties.add(key, desc)
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
} else if (prop.get("type").getAsString() == "float") {
val desc = JsonObject()
desc.addProperty("type", "object") // using "object" instead of "integer" because I can specify javaType which is more specific than making everything a long
desc.addProperty("existingJavaType", "java.lang.Float")
properties.add(key, desc)
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
}
else if (prop.get("type").getAsString() == "date") {
val desc = JsonObject()
desc.addProperty("type", "object")
desc.addProperty("existingJavaType", "java.lang.String")
if(key == "stagedDate") {
desc.addProperty("existingJavaType", "java.lang.Long")
}
properties.add(key, desc)
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
}
else if (prop.get("type").getAsString() == "boolean") {
val desc = JsonObject()
desc.addProperty("type", "boolean")
properties.add(key, desc)
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
}
/* else if (prop.get("type").getAsString() == "half_float") {
// TODO figure out what type to use!!!
// impacts description and titles reading scores
} */
else if (prop.get("type").getAsString() == "geo_shape") {
val desc = JsonObject()
desc.addProperty("type", "object")
// TODO add mapbox Geometry to schemas instead of Object? desc.addProperty("existingJavaType", "com.mapbox.geojson.Geometry")
// TODO note that having it directly use the avro generated pojos isn't working
desc.addProperty("existingJavaType", "java.lang.Object")
properties.add(key, desc)
if (!overrideNoArrays && keyIndicatesArray(key)) {
val arr = JsonObject()
arr.addProperty("type", "array")
arr.add("items", desc)
properties.add(key, arr)
}
if (!overrideNoArrays && keyIndicatesSet(key)) { // TODO rename overrideNoArrays to overrideNoCollections
val arr = JsonObject()
arr.addProperty("type", "array")
arr.addProperty("uniqueItems", true) // turns array into set
arr.add("items", desc)
properties.add(key, arr)
}
} else {
logger.lifecycle("WARNING: Unhandled property: ${key}:${prop}")
}
}
return properties
}
fun generateClasses(filename:String, mapper:SchemaMapper, dest: File) {
var source: String
source = Files.readString(Path.of(filename))
// create Gson instance for deserializing/serializing
val gson = Gson()
// deserialize JSON file into JsonObject
val mappingObject = gson.fromJson(source, JsonObject::class.java)
val schemaObject = JsonObject()
schemaObject.addProperty("type", "object")
val index = filename.replace(Regex(".*/"),"").replace("Index.json","").replace("_"," ")
schemaObject.addProperty("description", "Mapping for ${index} index.")
val classname = filename.replace(Regex(".*/"),"").replace("Index.json","").splitToSequence("_").map { it.capitalize() }.joinToString("")
val packagename = filename.replace(Regex(".*/"),"").replace("Index.json","").split("_")[0] // use the naming convention to loosely package related index code - analysis has a different SpatialBounding than search, but all the search indices *should* share a SpatialBounding, as should all the analysis indices.
if (packagename == "search") {
val interfaces = JsonArray()
/* interfaces.add("org.cedar.onestop.mapping.search.SearchObject" as String) */
interfaces.add("org.cedar.onestop.mapping.search.SearchObjectWithDates" as String)
interfaces.add("org.cedar.onestop.mapping.search.SearchObjectWithKeywords" as String)
if (classname != "SearchGranule"){
interfaces.add("org.cedar.onestop.mapping.search.SearchObjectWithResponsibleParties" as String)
}
/* interfaces.add("org.cedar.onestop.mapping.search.SearchObjectExpanded" as String) */
schemaObject.add("javaInterfaces", interfaces)
}
logger.lifecycle("Generating $classname")
/* schemaObject.addProperty("javaType", "org.cedar.onestop.mapping.${classname}") */
schemaObject.add("properties", buildJsonSchemaProperties(mappingObject.getAsJsonObject("mappings").getAsJsonObject("properties"), filename.contains("granule"), false))
val codeModel = JCodeModel()
mapper.generate(codeModel, classname, "org.cedar.onestop.mapping.${packagename}", gson.newBuilder().setPrettyPrinting().create().toJson(schemaObject))
codeModel.build(dest) // TODO multiple mappings to dest means last-one-in clobbers other objects (in theory this is fine because they should be the same across mappings but.... who knows)
}
@TaskAction
fun update() {
logger.lifecycle("Running 'updateESMapping' task on ${project.name}")
open class ESGenerationConfig() : DefaultGenerationConfig() {
override fun isGenerateBuilders(): Boolean {
return true
}
override fun isIncludeAdditionalProperties(): Boolean {
return false
}
override fun isUseTitleAsClassname(): Boolean {
return true
}
override fun isUseLongIntegers(): Boolean {
return true
}
//isIncludeDynamicBuilders()
//isIncludeDynamicAccessors()
//isIncludeGetters()
//isIncludeSetters()
// isUseInnerClassBuilders()
}
val config = ESGenerationConfig()
val mapper = SchemaMapper(RuleFactory(config, Jackson2Annotator(config), SchemaStore()), SchemaGenerator())
/* logger.lifecycle("trying to make dir ${project.projectDir.absolutePath + "/build/esGenerated"}") */
val dest = Files.createDirectories(Paths.get(project.projectDir.absolutePath + "/build/esGenerated")).toFile()
/* logger.lifecycle("writing generated files to ${dest}") */
var dir = File(project.projectDir.absolutePath + "/src/main/resources/mappings/")
for (f in dir.listFiles()) {
/* logger.lifecycle("mappings: ${f} ${f.getAbsolutePath()}") */
/* logger.lifecycle("??? ${f.getPath()}") */
val filename : String
filename = f.getPath()
logger.lifecycle(filename)
generateClasses(filename, mapper, dest)
/* val tmp = f.getAbsolutePath(::)
logger.lifecycle("???: ${tmp}")
generateClasses("asdf", mapper, dest) */
}
}
}
| gpl-2.0 | 24d6f7e5c6a6b4ff76d7d4dc4dca4aa1 | 44.756839 | 314 | 0.637505 | 4.298686 | false | false | false | false |
tasks/tasks | app/src/main/java/org/tasks/data/PlaceUsage.kt | 1 | 709 | package org.tasks.data
import androidx.room.Embedded
class PlaceUsage {
@Embedded lateinit var place: Place
var count = 0
val color: Int
get() = place.color
val icon: Int
get() = place.getIcon()
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is PlaceUsage) return false
if (place != other.place) return false
if (count != other.count) return false
return true
}
override fun hashCode(): Int {
var result = place.hashCode()
result = 31 * result + count
return result
}
override fun toString(): String = "PlaceUsage(place=$place, count=$count)"
} | gpl-3.0 | 896334c8df0ace8f9dc59d1a2c7af824 | 21.1875 | 78 | 0.600846 | 4.323171 | false | false | false | false |
ExMCL/ExMCL | ExMCL Updater/src/main/kotlin/com/n9mtq4/exmcl/updater/UpdateFinder.kt | 1 | 3771 | /*
* MIT License
*
* Copyright (c) 2016 Will (n9Mtq4) Bresnahan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.n9mtq4.exmcl.updater
import com.n9mtq4.exmcl.api.BUILD_NUMBER
import com.n9mtq4.exmcl.api.tabs.events.SafeForTabCreationEvent
import com.n9mtq4.exmcl.api.updater.UpdateAvailable
import com.n9mtq4.kotlin.extlib.ignore
import com.n9mtq4.kotlin.extlib.io.errPrintln
import com.n9mtq4.kotlin.extlib.io.open
import com.n9mtq4.logwindow.BaseConsole
import com.n9mtq4.logwindow.annotation.Async
import com.n9mtq4.logwindow.annotation.ListensFor
import com.n9mtq4.logwindow.listener.GenericListener
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
import org.jsoup.Jsoup
/**
* Created by will on 2/16/16 at 2:41 PM.
*
* @author Will "n9Mtq4" Bresnahan
*/
class UpdateFinder : GenericListener {
companion object {
/*
* These flags are a development feature that allows us to
* test the updating ability without actually making a new update.
* Both of these should be false in an actual release
* */
private const val FORCE_UPDATE = false
private const val IGNORE_SKIP = false
}
/**
* Having it wait for the tab ready instead of the enabled
* gives us the ability to modify the launcher rather than
* displaying a popup
* */
@Async
@Suppress("unused", "UNUSED_PARAMETER")
@ListensFor
fun listenForTabReady(e: SafeForTabCreationEvent, baseConsole: BaseConsole) {
checkForUpdate(e.initiatingBaseConsole)
baseConsole.disableListenerAttribute(this)
}
private fun checkForUpdate(baseConsole: BaseConsole) {
try {
// Download the json data
val jsonRaw = Jsoup.connect(API_UPDATE_URL).ignoreContentType(true).execute().body()
// parse it
val parser = JSONParser()
val latestVersion = parser.parse(jsonRaw) as JSONObject //maybe HashMap<*, *>
// get the tag name
val tagName = latestVersion["tag_name"] as String
val tokens = tagName.split("-")
val targetBuildNumber = tokens[tokens.size - 1].toInt() // get the build number
// ignore this update if the IGNORE_UPDATE_FILE has the targetBuildNumber in it
if (IGNORE_UPDATE_FILE.exists() && !IGNORE_SKIP) {
ignore {
val versionIgnore = open(IGNORE_UPDATE_FILE, "r").use { it.readText()!!.trim().toInt() }
if (versionIgnore == targetBuildNumber) return
else IGNORE_UPDATE_FILE.deleteOnExit() // the ignore update file is for an older version; we can remove it
}
}
if (BUILD_NUMBER < targetBuildNumber || FORCE_UPDATE) baseConsole.pushEvent(UpdateAvailable(baseConsole, latestVersion, targetBuildNumber))
}catch (e: Exception) {
errPrintln("Failed to get update status")
e.printStackTrace()
}
}
}
| mit | 3fa3a2e9c276a348f10b0943cc76832a | 33.916667 | 142 | 0.740122 | 3.797583 | false | false | false | false |
arturbosch/detekt | detekt-rules-empty/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/empty/EmptyBlocksMultiRuleSpec.kt | 1 | 1954 | package io.gitlab.arturbosch.detekt.rules.empty
import io.github.detekt.test.utils.compileForTest
import io.github.detekt.test.utils.resourceAsPath
import io.gitlab.arturbosch.detekt.test.compileAndLint
import io.gitlab.arturbosch.detekt.test.lint
import io.gitlab.arturbosch.detekt.test.yamlConfig
import org.assertj.core.api.Assertions.assertThat
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class EmptyBlocksMultiRuleSpec : Spek({
val subject by memoized { EmptyBlocks() }
val file by memoized { compileForTest(resourceAsPath("Empty.kt")) }
describe("multi rule with all empty block rules") {
it("should report one finding per rule") {
val findings = subject.lint(file)
// -1 because the empty kt file rule doesn't get triggered in the 'Empty' test file
val rulesSize = subject.rules.size - 1
assertThat(findings).hasSize(rulesSize)
}
it("should not report any as all empty block rules are deactivated") {
val config = yamlConfig("deactivated-empty-blocks.yml")
val ruleSet = EmptyCodeProvider().instance(config)
@Suppress("DEPRECATION")
val findings = ruleSet.accept(file)
assertThat(findings).isEmpty()
}
it("reports an empty kt file") {
assertThat(subject.compileAndLint("")).hasSize(1)
}
it("reports no duplicated findings - issue #1605") {
val findings = subject.compileAndLint(
"""
class EmptyBlocks {
class EmptyClass {}
fun exceptionHandling() {
try {
println()
} finally {
}
}
}
"""
)
assertThat(findings).hasSize(2)
}
}
})
| apache-2.0 | 8f3dfe7a8975cb880577e8e35cd1d7d9 | 32.689655 | 95 | 0.592119 | 4.934343 | false | true | false | false |
SeunAdelekan/Kanary | examples/Kanary-Mini-Twitter-Clone/src/curious/cwitter/util.kt | 1 | 1514 | package curious.cwitter
import com.fasterxml.jackson.databind.JsonNode
import java.math.BigInteger
import java.security.SecureRandom
import javax.servlet.http.Cookie
fun getOrigin(scheme: String): String {
// Not really doing anything right now
// cos request scheme apparently always seem to be http
val origins = arrayOf("http://cwitter.curious.com.ng", "https://cwitter.curious.com.ng")
//val origins = arrayOf("", "http://localhost:8000")
if (scheme == "https"){
return origins[1]
}
return origins[1]
}
// bare bones request json fields validation
fun validateJSON(data: JsonNode?, fields: Array<String>): Boolean {
(0..fields.size-1).forEach { i ->
if (data?.get(fields[i]) == null || data.get(fields[i]).asText() == ""){
return false
}
}
return true
}
class CweetSessionMaker {
private val random = SecureRandom()
val db = DataHandler()
fun randomId(): String {
return BigInteger(130, random).toString(32)
}
fun cookie(user_id: Int): Cookie {
// shhh, don't even think this is cryptographically secure at all, it's not!!
val sessionId = this.randomId()+this.randomId()
db.updateSessionId(user_id, sessionId)
val cookie: Cookie = Cookie("cweet_user", sessionId)
//cookie.secure = true
cookie.path = "/"
cookie.maxAge = 86400 // 60*60*24, let the crude cookie expire after a day
cookie.isHttpOnly = true
return cookie
}
} | apache-2.0 | 8acf1f58ccd2e8e3a4873bc763b4eba0 | 29.3 | 92 | 0.643329 | 3.932468 | false | false | false | false |
ivw/tinyscript | compiler-core/src/main/kotlin/tinyscript/compiler/core/Type.kt | 1 | 4265 | package tinyscript.compiler.core
// see the "type" rule in the grammar
interface Type {
fun final(): FinalType
}
interface FinalType : Type {
override fun final(): FinalType = this
/**
* @return true if `type` is equal to this, or if it is a subtype of this
*/
fun accepts(type: FinalType): Boolean
}
abstract class DeferredType : Type {
var finalType: FinalType? = null
final override fun final(): FinalType {
finalType?.let { return it }
val finalType = createFinalType()
this.finalType = finalType
return finalType
}
protected abstract fun createFinalType(): FinalType
override fun toString(): String {
return "DeferredType<$finalType>"
}
}
// AnyType accepts anything; objects, functions, etc.
// Nothing can be done with values of Any type, not even casting.
object AnyType : FinalType {
override fun accepts(type: FinalType): Boolean = true
override fun toString(): String {
return "AnyType"
}
}
// see the "objectType" rule in the grammar
open class ObjectType(
val signatures: SignatureCollection = SignatureCollection(),
val identities: MutableSet<ClassType> = HashSet()
) : FinalType {
fun inheritFromObject(objectType: ObjectType) {
signatures.addSignatures(objectType.signatures)
identities.addAll(objectType.identities)
}
fun inheritFromClass(classType: ClassType) {
identities.add(classType)
classType.objectType?.let { inheritFromObject(it) }
}
override fun accepts(type: FinalType): Boolean {
if (type !is ObjectType) return false
if (!type.identities.containsAll(identities)) return false
for ((name, symbol) in signatures.symbols) {
val subSymbol = type.signatures.symbols[name]
if (subSymbol == null) {
if (symbol.isAbstract)
return false
} else {
if (!symbol.type.final().accepts(subSymbol.type.final()))
return false
}
}
return true
}
override fun toString(): String {
return "ObjectType<signatures = $signatures, identities.size = ${identities.size}>"
}
}
fun unionObjectType(a: ObjectType, b: ObjectType): ObjectType {
val objectType = ObjectType()
objectType.inheritFromObject(a)
objectType.inheritFromObject(b)
return objectType
}
fun intersectObjectType(a: ObjectType, b: ObjectType): ObjectType {
val objectType = ObjectType()
val commonIdentities = a.identities.intersect(b.identities)
commonIdentities.forEach { identity ->
objectType.inheritFromClass(identity)
}
return objectType
}
class ClassType(val objectType: ObjectType? = null) : FinalType {
val simpleInstanceType: ObjectType = ObjectType().apply {
inheritFromClass(this@ClassType)
}
override fun accepts(type: FinalType): Boolean = false
override fun toString(): String {
return "ClassType"
}
}
// see the "NullableType" rule in the grammar
class NullableType(val nonNullType: FinalType) : FinalType {
override fun accepts(type: FinalType): Boolean {
if (type is NullableType) {
return nonNullType.accepts(type.nonNullType)
}
return nonNullType.accepts(type)
}
override fun toString(): String {
return "NullableType<$nonNullType>"
}
}
// see the "FunctionType" rule in the grammar
class FunctionType(val params: ObjectType, val returnType: Type) : FinalType {
override fun accepts(type: FinalType): Boolean {
if (type !is FunctionType) return false
// [d: Dog] -> Dog accepts [d: Animal] -> SpecialDog
return type.params.accepts(params) && returnType.final().accepts(type.returnType.final())
}
override fun toString(): String {
return "FunctionType<$params -> $returnType>"
}
}
fun intersectTypes(a: FinalType, b: FinalType): FinalType {
if (a === b) return a
val nonNullA: FinalType = if (a is NullableType) a.nonNullType else a
val nonNullB: FinalType = if (b is NullableType) b.nonNullType else b
val nonNullIntersectType: FinalType = if (nonNullA is ObjectType && nonNullB is ObjectType) {
intersectObjectType(nonNullA, nonNullB)
} else if (nonNullA is FunctionType && nonNullB is FunctionType) {
FunctionType(
unionObjectType(nonNullA.params, nonNullB.params),
intersectTypes(nonNullA.returnType.final(), nonNullB.returnType.final())
)
} else {
AnyType
}
return if (a is NullableType || b is NullableType) NullableType(nonNullIntersectType) else nonNullIntersectType
}
| mit | 968bd4d75b6b61c4210f4ef3041fe507 | 25.006098 | 112 | 0.731067 | 3.673557 | false | false | false | false |
nemerosa/ontrack | ontrack-extension-auto-versioning/src/main/java/net/nemerosa/ontrack/extension/av/queue/AsyncAutoVersioningQueueConfig.kt | 1 | 2663 | package net.nemerosa.ontrack.extension.av.queue
import net.nemerosa.ontrack.extension.av.AutoVersioningConfigProperties
import net.nemerosa.ontrack.extension.av.dispatcher.AutoVersioningOrder
import org.springframework.amqp.core.*
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
/**
* Configuration of the queues.
*/
@Configuration
class AsyncAutoVersioningQueueConfig(
private val autoVersioningConfigProperties: AutoVersioningConfigProperties,
) {
@Bean
fun autoVersioningTopicBindings(): Declarables {
val declarables = mutableListOf<Declarable>()
// Topic exchange for the auto versioning
val exchange = DirectExchange(TOPIC).apply {
declarables += this
}
// Default queues
(1..autoVersioningConfigProperties.queue.scale).forEach { no ->
val queue = Queue("$QUEUE_PREFIX.$DEFAULT.$no", true)
val binding = BindingBuilder
.bind(queue)
.to(exchange)
.with("$DEFAULT.$no")
declarables += queue
declarables += binding
}
// Project queues
autoVersioningConfigProperties.queue.projects.forEach { config ->
val queue = Queue("$QUEUE_PREFIX.$PROJECT.$config", true)
val binding = BindingBuilder
.bind(queue)
.to(exchange)
.with("$PROJECT.$config")
declarables += queue
declarables += binding
}
// OK
return Declarables(declarables)
}
companion object {
/**
* Getting the routing key for a given payload
*/
fun getRoutingKey(
autoVersioningConfigProperties: AutoVersioningConfigProperties,
order: AutoVersioningOrder,
): String =
autoVersioningConfigProperties.queue.projects.find {
it == order.branch.project.name
}
// Specific project queue
?.let { config ->
"$PROJECT.$config"
}
// Default queue
?: "$DEFAULT.${(order.branch.id() % autoVersioningConfigProperties.queue.scale) + 1}"
/**
* Topic exchange name
*/
const val TOPIC = "auto-versioning"
/**
* Prefix for the queue names
*/
const val QUEUE_PREFIX = TOPIC
/**
* Default queuing
*/
const val DEFAULT = "default"
/**
* Project queuing
*/
const val PROJECT = "project"
}
} | mit | bb93ca61b6370fd94490c918113693fb | 28.932584 | 101 | 0.577169 | 5.262846 | false | true | false | false |
rsiebert/TVHClient | data/src/main/java/org/tvheadend/data/dao/ChannelDao.kt | 1 | 5159 | package org.tvheadend.data.dao
import androidx.lifecycle.LiveData
import androidx.room.*
import org.tvheadend.data.entity.ChannelEntity
import org.tvheadend.data.entity.EpgChannelEntity
@Dao
internal interface ChannelDao {
@get:Query("SELECT COUNT (*) FROM channels AS c " +
" WHERE $CONNECTION_IS_ACTIVE")
val itemCount: LiveData<Int>
@get:Query("SELECT COUNT (*) FROM channels AS c " +
" WHERE $CONNECTION_IS_ACTIVE")
val itemCountSync: Int
@Query("SELECT c.* FROM channels AS c " +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND c.id = :id")
fun loadChannelByIdSync(id: Int): ChannelEntity?
@Transaction
@Query(CHANNEL_BASE_QUERY +
" LEFT JOIN programs AS program ON program.start <= :time AND program.stop > :time AND program.channel_id = c.id " +
" LEFT JOIN programs AS next_program ON next_program.start = program.stop AND next_program.channel_id = c.id " +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND c.id = :id")
fun loadChannelByIdWithProgramsSync(id: Int, time: Long): ChannelEntity?
@Query("SELECT c.* FROM channels AS c " +
" WHERE $CONNECTION_IS_ACTIVE" +
" GROUP BY c.id " +
ORDER_BY)
fun loadAllChannelsSync(sortOrder: Int): List<ChannelEntity>
@Transaction
@Query(CHANNEL_BASE_QUERY +
" LEFT JOIN programs AS program ON program.start <= :time AND program.stop > :time AND program.channel_id = c.id " +
" LEFT JOIN programs AS next_program ON next_program.start = program.stop AND next_program.channel_id = c.id " +
" WHERE $CONNECTION_IS_ACTIVE" +
" GROUP BY c.id " +
ORDER_BY)
fun loadAllChannelsByTime(time: Long, sortOrder: Int): LiveData<List<ChannelEntity>>
@Transaction
@Query(CHANNEL_BASE_QUERY +
" LEFT JOIN programs AS program ON program.start <= :time AND program.stop > :time AND program.channel_id = c.id " +
" LEFT JOIN programs AS next_program ON next_program.start = program.stop AND next_program.channel_id = c.id " +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND c.id IN (SELECT channel_id FROM tags_and_channels WHERE tag_id IN (:tagIds)) " +
" GROUP BY c.id " +
ORDER_BY)
fun loadAllChannelsByTimeAndTag(time: Long, sortOrder: Int, tagIds: List<Int>): LiveData<List<ChannelEntity>>
@Transaction
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(channel: ChannelEntity)
@Transaction
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insert(channels: List<ChannelEntity>)
@Update
fun update(channel: ChannelEntity)
@Delete
fun delete(channel: ChannelEntity)
@Query("DELETE FROM channels " +
" WHERE id = :id " +
" AND connection_id IN (SELECT id FROM connections WHERE active = 1)")
fun deleteById(id: Int)
@Query("DELETE FROM channels")
fun deleteAll()
@Query(EPG_CHANNEL_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
ORDER_BY)
fun loadAllEpgChannels(sortOrder: Int): LiveData<List<EpgChannelEntity>>
@Query(EPG_CHANNEL_BASE_QUERY +
" WHERE $CONNECTION_IS_ACTIVE" +
" AND c.id IN (SELECT channel_id FROM tags_and_channels WHERE tag_id IN (:tagIds)) " +
ORDER_BY)
fun loadAllEpgChannelsByTag(sortOrder: Int, tagIds: List<Int>): LiveData<List<EpgChannelEntity>>
companion object {
const val CHANNEL_BASE_QUERY = "SELECT DISTINCT c.*, " +
"program.id AS program_id, " +
"program.title AS program_title, " +
"program.subtitle AS program_subtitle, " +
"program.start AS program_start, " +
"program.stop AS program_stop, " +
"program.content_type AS program_content_type, " +
"next_program.id AS next_program_id, " +
"next_program.title AS next_program_title " +
"FROM channels AS c "
const val EPG_CHANNEL_BASE_QUERY = "SELECT c.id, " +
"c.name, " +
"c.icon, " +
"c.number, " +
"c.number_minor, " +
"c.display_number " +
"FROM channels AS c "
const val ORDER_BY = " ORDER BY " +
"CASE :sortOrder WHEN 0 THEN c.server_order END ASC," +
"CASE :sortOrder WHEN 1 THEN c.server_order END DESC," +
"CASE :sortOrder WHEN 2 THEN c.id END ASC," +
"CASE :sortOrder WHEN 3 THEN c.id END DESC," +
"CASE :sortOrder WHEN 4 THEN c.name END ASC," +
"CASE :sortOrder WHEN 5 THEN c.name END DESC," +
"CASE :sortOrder WHEN 6 THEN " +
" CASE (c.display_number + 0) WHEN 0 THEN 999999999 ELSE (c.display_number + 0) END " +
"END ASC," +
"CASE :sortOrder WHEN 7 THEN (c.display_number + 0) END DESC"
const val CONNECTION_IS_ACTIVE = " c.connection_id IN (SELECT id FROM connections WHERE active = 1) "
}
}
| gpl-3.0 | 6969159fdfb515e9013edff66ca65421 | 40.272 | 128 | 0.593138 | 4.021044 | false | false | false | false |
BOINC/boinc | android/BOINC/app/src/main/java/edu/berkeley/boinc/ui/eventlog/EventLogActivity.kt | 2 | 7549 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.ui.eventlog
import android.content.ClipData
import android.content.ClipboardManager
import android.content.ComponentName
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.getSystemService
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.tabs.TabLayoutMediator
import edu.berkeley.boinc.R
import edu.berkeley.boinc.adapter.ClientLogRecyclerViewAdapter
import edu.berkeley.boinc.client.IMonitor
import edu.berkeley.boinc.client.Monitor
import edu.berkeley.boinc.databinding.ActivityEventLogBinding
import edu.berkeley.boinc.rpc.Message
import edu.berkeley.boinc.utils.Logging
import java.util.*
class EventLogActivity : AppCompatActivity() {
private lateinit var binding: ActivityEventLogBinding
private var monitor: IMonitor? = null
private var mIsBound = false
lateinit var clientLogList: RecyclerView
lateinit var clientLogRecyclerViewAdapter: ClientLogRecyclerViewAdapter
val clientLogData: MutableList<Message> = ArrayList()
val guiLogData: List<String> = ArrayList()
private val mConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
Logging.logDebug(Logging.Category.GUI_ACTIVITY, "EventLogActivity onServiceConnected")
monitor = IMonitor.Stub.asInterface(service)
mIsBound = true
// initialize default fragment
(supportFragmentManager.findFragmentByTag("f0") as EventLogClientFragment).init()
}
override fun onServiceDisconnected(className: ComponentName) {
monitor = null
mIsBound = false
}
}
val monitorService: IMonitor
get() {
if (!mIsBound) {
Logging.logWarning(Logging.Category.MONITOR, "Fragment trying to obtain service reference, but Monitor" +
" not bound in EventLogActivity")
}
return monitor!!
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityEventLogBinding.inflate(layoutInflater)
setContentView(binding.root)
val eventLogPagerAdapter = EventLogPagerAdapter(this)
binding.viewPager.adapter = eventLogPagerAdapter
TabLayoutMediator(binding.tabs, binding.viewPager) { tab, position ->
tab.text = if (position == 0)
getString(R.string.eventlog_client_header)
else
getString(R.string.eventlog_gui_header)
}.attach()
doBindService()
}
override fun onDestroy() {
doUnbindService()
super.onDestroy()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.eventlog_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.refresh -> {
updateCurrentFragment()
return true
}
R.id.email_to -> {
onEmailTo()
return true
}
R.id.copy -> {
onCopy()
return true
}
}
return super.onOptionsItemSelected(item)
}
private fun doBindService() {
if (!mIsBound) {
applicationContext.bindService(Intent(this, Monitor::class.java), mConnection, 0) //calling within Tab needs getApplicationContext() for bindService to work!
}
}
private fun doUnbindService() {
if (mIsBound) {
applicationContext.unbindService(mConnection)
mIsBound = false
}
}
private fun updateCurrentFragment() {
val currentFragment = supportFragmentManager.findFragmentByTag("f${binding.viewPager.currentItem}")
if (currentFragment is EventLogClientFragment) {
currentFragment.update()
} else if (currentFragment is EventLogGuiFragment) {
currentFragment.update()
}
}
private fun onCopy() {
try {
val clipboard = getSystemService<ClipboardManager>()!!
val clipData = ClipData.newPlainText("log", getLogDataAsString())
clipboard.setPrimaryClip(clipData)
Toast.makeText(applicationContext, R.string.eventlog_copy_toast, Toast.LENGTH_SHORT).show()
} catch (e: Exception) {
Logging.logError(Logging.Category.USER_ACTION, "onCopy failed")
}
}
private fun onEmailTo() {
try {
val emailText = getLogDataAsString()
val emailIntent = Intent(Intent.ACTION_SEND)
// Put together the email intent
emailIntent.type = "plain/text"
emailIntent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.eventlog_email_subject))
emailIntent.putExtra(Intent.EXTRA_TEXT, emailText)
// Send it off to the Activity-Chooser
startActivity(Intent.createChooser(emailIntent, "Send mail..."))
} catch (e: Exception) {
Logging.logError(Logging.Category.USER_ACTION, "onEmailTo failed")
}
}
// returns the content of the log as string
// clientLog = true: client log
// clientlog = false: gui log
private fun getLogDataAsString(): String {
val text = StringBuilder()
val type = binding.viewPager.currentItem
when {
type == 0 -> {
text.append(getString(R.string.eventlog_client_header)).append("\n\n")
for (index in 0 until clientLogList.adapter?.itemCount!!) {
text.append(clientLogRecyclerViewAdapter.getDateTimeString(index))
text.append("|")
text.append(clientLogRecyclerViewAdapter.getProject(index))
text.append("|")
text.append(clientLogRecyclerViewAdapter.getMessage(index))
text.append("\n")
}
}
type == 1 -> {
text.append(getString(R.string.eventlog_gui_header)).append("\n\n")
for (line in guiLogData) {
text.append(line)
text.append("\n")
}
}
else -> {
Logging.logError(Logging.Category.GUI_ACTIVITY, "EventLogActivity could not determine which log active.")
}
}
return text.toString()
}
}
| lgpl-3.0 | 5175310fcece2c16b1e284cbc177721b | 35.293269 | 169 | 0.641409 | 4.940445 | false | false | false | false |
gameofbombs/kt-postgresql-async | postgresql-async/src/main/kotlin/com/github/mauricio/async/db/postgresql/column/PostgreSQLIntervalEncoderDecoder.kt | 2 | 5557 | /*
* Copyright 2013 Maurício Linhares
* Copyright 2013 Dylan Simon
*
* Maurício Linhares 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 com.github.mauricio.async.db.postgresql.column
import com.github.mauricio.async.db.column.ColumnEncoderDecoder
import com.github.mauricio.async.db.exceptions.DateEncoderNotAvailableException
import mu.KLogging
import sun.reflect.generics.reflectiveObjects.NotImplementedException
import java.time.Duration
import java.time.Period
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.temporal.ChronoField
//TODO: support all other formats, not only ISO
object PostgreSQLIntervalEncoderDecoder : ColumnEncoderDecoder, KLogging() {
override fun encode(value: Any): String =
when (value) {
is Duration -> value.toString()
is Period -> value.toString()
else -> throw DateEncoderNotAvailableException(value)
}
/* these should only be used for parsing: */
// private fun postgresYMDBuilder(builder: DateTimeFormatterBuilder) = builder
// .appendValue(ChronoField).appendSuffix(" year", " years").appendSeparator(" ")
// .appendMonths().appendSuffix(" mon", " mons").appendSeparator(" ")
// .appendDays().appendSuffix(" day", " days").appendSeparator(" ")
//
// private val postgres_verboseParser =
// postgresYMDBuilder(new PeriodFormatterBuilder ().appendLiteral("@ "))
// .appendHours.appendSuffix(" hour", " hours").appendSeparator(" ")
// .appendMinutes.appendSuffix(" min", " mins").appendSeparator(" ")
// .appendSecondsWithOptionalMillis.appendSuffix(" sec", " secs")
// .toFormatter
//
// private fun postgresHMSBuilder(builder: PeriodFormatterBuilder) = builder
// // .printZeroAlways // really all-or-nothing
// .rejectSignedValues(true) // XXX: sign should apply to all
// .appendHours.appendSuffix(":")
// .appendMinutes.appendSuffix(":")
// .appendSecondsWithOptionalMillis
//
// private val hmsParser =
// postgresHMSBuilder(DateTimeFormatter().)
// .toFormatter
//
// private val postgresParser =
// postgresHMSBuilder(postgresYMDBuilder(new PeriodFormatterBuilder ()))
// .toFormatter
//
// /* These sql_standard parsers don't handle negative signs correctly. */
// private fun sqlDTBuilder(builder: PeriodFormatterBuilder) =
// postgresHMSBuilder(builder
// .appendDays.appendSeparator(" "))
//
// private val sqlDTParser =
// sqlDTBuilder(new PeriodFormatterBuilder ())
// .toFormatter
//
// private val sqlParser =
// sqlDTBuilder(new PeriodFormatterBuilder ()
// .printZeroAlways
// .rejectSignedValues(true) // XXX: sign should apply to both
// .appendYears.appendSeparator("-").appendMonths
// .rejectSignedValues(false)
// .printZeroNever
// .appendSeparator(" "))
// .toFormatter
/* This supports all positive intervals, and intervalstyle of postgres_verbose, and iso_8601 perfectly.
* If intervalstyle is set to postgres or sql_standard, some negative intervals may be rejected.
*/
override fun decode(value: String): Duration =
if (value.isEmpty()) /* huh? */
Duration.ZERO
else {
if (value[0].equals('P')) /* iso_8601 */
Duration.parse(value)
else throw NotImplementedError("Sorry, java.time does not support it")
}
// val format = (
// if (value(0).equals('P')) /* iso_8601 */
// formatter
// else if (value.startsWith("@ "))
// postgres_verboseParser
// else {
// /* try to guess based on what comes after the first number */
// val i = value.indexWhere(!_.isDigit, if ("-+".contains(value(0))) 1 else 0)
// if (i < 0 || ":.".contains(value(i))) /* simple HMS (to support group negation) */
// hmsParser
// else if (value(i).equals('-')) /* sql_standard: Y-M */
// sqlParser
// else if (value(i).equals(' ') && i+1 < value.length && value(i+1).isDigit) /* sql_standard: D H:M:S */
// sqlDTParser
// else
// postgresParser
// }
// )
// if ((format eq hmsParser) && value(0).equals('-'))
// format.parsePeriod(value.substring(1)).negated
// else if (value.endsWith(" ago")) /* only really applies to postgres_verbose, but shouldn't hurt */
// format.parsePeriod(value.stripSuffix(" ago")).negated
// else
// format.parsePeriod(value)
}
| apache-2.0 | dd4ebee133c09af246a552fe4d02cb15 | 43.44 | 120 | 0.60396 | 4.451122 | false | false | false | false |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/animate/serialization/AniFile.kt | 1 | 364 | package com.soywiz.korge.animate.serialization
object AniFile {
const val MAGIC = "KORGEANI"
const val VERSION = 16
const val SYMBOL_TYPE_EMPTY = 0
const val SYMBOL_TYPE_SOUND = 1
const val SYMBOL_TYPE_TEXT = 2
const val SYMBOL_TYPE_SHAPE = 3
const val SYMBOL_TYPE_BITMAP = 4
const val SYMBOL_TYPE_MOVIE_CLIP = 5
const val SYMBOL_TYPE_MORPH_SHAPE = 6
}
| apache-2.0 | 0b17f2628e207fac91b86a1b17f218df | 25 | 46 | 0.739011 | 3.033333 | false | false | false | false |
vanita5/twittnuker | twittnuker/src/main/kotlin/org/mariotaku/ktextension/ActivityExtensions.kt | 1 | 1894 | /*
* Twidere - Twitter client for Android
*
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mariotaku.ktextension
import android.app.Activity
import android.content.ComponentName
import android.content.pm.ActivityInfo
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
val Activity.activityIcon: Drawable?
get() {
val info = activityInfo
val activityLabelRes = info.icon
if (activityLabelRes != 0) return ContextCompat.getDrawable(this, activityLabelRes)
val appLabelRes = applicationInfo.icon
if (appLabelRes != 0) return ContextCompat.getDrawable(this, appLabelRes)
return info.loadIcon(packageManager)
}
val Activity.activityLabel: CharSequence?
get() {
val info = activityInfo
val activityLabelRes = info.labelRes
if (activityLabelRes != 0) return getText(activityLabelRes)
val appLabelRes = applicationInfo.labelRes
if (appLabelRes != 0) return getText(appLabelRes)
return info.loadLabel(packageManager)
}
val Activity.activityInfo: ActivityInfo
get() = packageManager.getActivityInfo(ComponentName(this, javaClass), 0) | gpl-3.0 | 9e82b1e0b374796fa3c056c1f341a397 | 36.9 | 91 | 0.727561 | 4.285068 | false | false | false | false |
BilledTrain380/sporttag-psa | app/shared/src/test/kotlin/ch/schulealtendorf/psa/shared/rulebook/SkippingRuleSetTest.kt | 1 | 923 | package ch.schulealtendorf.psa.shared.rulebook
import ch.schulealtendorf.psa.dto.participation.GenderDto
import ch.schulealtendorf.psa.dto.participation.athletics.SEILSPRINGEN
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Tag
import org.junit.jupiter.api.Test
@Tag("unit-test")
internal class SkippingRuleSetTest {
private val ruleSet = SkippingRuleSet()
@Test
internal fun onFemaleCompetitors() {
val model = FormulaModel(SEILSPRINGEN, null, 170.0, GenderDto.FEMALE)
val points: Int = ruleSet.getRules().first { it.whenever(model) }.then(model)
assertThat(points).isEqualTo(598)
}
@Test
internal fun onMaleCompetitors() {
val model = FormulaModel(SEILSPRINGEN, null, 88.0, GenderDto.MALE)
val points: Int = ruleSet.getRules().first { it.whenever(model) }.then(model)
assertThat(points).isEqualTo(275)
}
}
| gpl-3.0 | ae937b09da1dfba8a953c63ce438af8a | 29.766667 | 85 | 0.72481 | 3.782787 | false | true | false | false |
doerfli/hacked | app/src/main/kotlin/li/doerf/hacked/ui/fragments/BreachesFragment.kt | 1 | 2532 | package li.doerf.hacked.ui.fragments
import android.content.Context
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.reactivex.processors.PublishProcessor
import li.doerf.hacked.HackedApplication
import li.doerf.hacked.R
import li.doerf.hacked.db.entities.BreachedSite
import li.doerf.hacked.ui.adapters.BreachedSitesAdapter
import li.doerf.hacked.ui.viewmodels.BreachedSitesViewModel
import li.doerf.hacked.util.NavEvent
import java.util.*
/**
* A simple [Fragment] subclass.
* create an instance of this fragment.
*/
class BreachesFragment : Fragment() {
private val breachedSitesViewModel: BreachedSitesViewModel by viewModels()
private lateinit var navEvents: PublishProcessor<NavEvent>
private lateinit var breachedSitesAdapter: BreachedSitesAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val fragmentRootView = inflater.inflate(R.layout.fragment_breaches, container, false)
val headingChevron = fragmentRootView.findViewById<ImageView>(R.id.show_details)
headingChevron.setOnClickListener {
navEvents.onNext(NavEvent(NavEvent.Destination.ALL_BREACHES, null, null))
}
val breachedSites: RecyclerView = fragmentRootView.findViewById(R.id.breached_sites_list)
// breachedSites.setHasFixedSize(true)
val lmbs = LinearLayoutManager(context)
breachedSites.layoutManager = lmbs
breachedSites.adapter = breachedSitesAdapter
return fragmentRootView
}
override fun onAttach(context: Context) {
super.onAttach(context)
breachedSitesAdapter = BreachedSitesAdapter(requireActivity().applicationContext, ArrayList(), true)
breachedSitesViewModel.breachesSitesMostRecent!!.observe(this, Observer { sites: List<BreachedSite> -> breachedSitesAdapter.addItems(sites) })
navEvents = (requireActivity().applicationContext as HackedApplication).navEvents
}
override fun onResume() {
super.onResume()
if (breachedSitesAdapter.itemCount == 0 ) {
AllBreachesFragment.reloadBreachedSites(requireActivity())
}
}
}
| apache-2.0 | 3376044d5004f123ec865520cc67ad2b | 37.953846 | 150 | 0.759479 | 4.497336 | false | false | false | false |
SchibstedSpain/Leku | leku/src/main/java/com/schibstedspain/leku/geocoder/api/NetworkClient.kt | 1 | 2145 | package com.schibstedspain.leku.geocoder.api
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStream
import java.net.URL
import java.net.UnknownHostException
import javax.net.ssl.HttpsURLConnection
private const val REPONSE_MAX_LENGTH = 1024
private const val READ_TIMEOUT = 3000
private const val CONNECT_TIMEOUT = 3000
class NetworkClient {
fun requestFromLocationName(request: String): String? {
var result: String? = null
var stream: InputStream? = null
var connection: HttpsURLConnection? = null
try {
val url = URL(request)
connection = url.openConnection() as HttpsURLConnection
connection.readTimeout = READ_TIMEOUT
connection.connectTimeout = CONNECT_TIMEOUT
connection.requestMethod = "GET"
connection.doInput = true
connection.connect()
val responseCode = connection.responseCode
if (responseCode != HttpsURLConnection.HTTP_OK) {
throw NetworkException("HTTP error code: $responseCode")
}
stream = connection.inputStream
if (stream != null) {
result = readStream(stream, REPONSE_MAX_LENGTH)
}
} catch (ignore: UnknownHostException) {
} catch (ioException: IOException) {
throw NetworkException(ioException)
} finally {
if (stream != null) {
try {
stream.close()
} catch (ioException: IOException) {
throw NetworkException(ioException)
}
}
connection?.disconnect()
}
return result
}
@Throws(IOException::class)
private fun readStream(stream: InputStream, maxLength: Int): String {
val result = ByteArrayOutputStream()
val buffer = ByteArray(maxLength)
var length = stream.read(buffer)
while (length != -1) {
result.write(buffer, 0, length)
length = stream.read(buffer)
}
return result.toString("UTF-8")
}
}
| apache-2.0 | 463f64082187129d9f5af65e42f896b4 | 33.047619 | 73 | 0.603263 | 5.070922 | false | false | false | false |
stripe/stripe-android | financial-connections/src/main/java/com/stripe/android/financialconnections/presentation/CreateBrowserIntentForUrl.kt | 1 | 1517 | package com.stripe.android.financialconnections.presentation
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import androidx.browser.customtabs.CustomTabsIntent
/**
* Constructs an intent to launch the given [Uri] on a CustomTab or in a regular browser,
* based on the default browser set for this device.
*/
internal object CreateBrowserIntentForUrl {
operator fun invoke(context: Context, uri: Uri): Intent {
val browserIntent = Intent(Intent.ACTION_VIEW, uri)
val resolveInfo: String? = context.packageManager
.resolveActivity(browserIntent, PackageManager.MATCH_DEFAULT_ONLY)
?.activityInfo
?.packageName
return when {
/**
* Firefox browser has a redirect issue when launching as a custom tab.
* @see [BANKCON-3846]
*/
resolveInfo?.contains(FIREFOX_PACKAGE) == true -> browserIntent
resolveInfo?.contains(CHROME_PACKAGE) == true -> createCustomTabIntent(uri)
else -> createCustomTabIntent(uri)
}
}
private fun createCustomTabIntent(uri: Uri): Intent {
return CustomTabsIntent.Builder()
.setShareState(CustomTabsIntent.SHARE_STATE_OFF)
.build()
.also { it.intent.data = uri }
.intent
}
private const val FIREFOX_PACKAGE = "org.mozilla"
private const val CHROME_PACKAGE = "com.android.chrome"
}
| mit | 70007b0ab8af356f50eb1cd39a4fda39 | 35.119048 | 89 | 0.664469 | 4.682099 | false | false | false | false |
wendigo/chrome-reactive-kotlin | src/main/kotlin/pl/wendigo/chrome/protocol/websocket/WebSocketFramesStream.kt | 1 | 4232 | package pl.wendigo.chrome.protocol.websocket
import io.reactivex.rxjava3.core.BackpressureStrategy
import io.reactivex.rxjava3.core.Flowable
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import io.reactivex.rxjava3.subjects.ReplaySubject
import io.reactivex.rxjava3.subjects.Subject
import kotlinx.serialization.KSerializer
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import org.slf4j.LoggerFactory
import java.io.Closeable
import java.io.EOFException
/**
* WebSocketFramesStream represents connection to remote WebSocket endpoint of the DevTools Protocol
* (either inspectable page debugger url http://localhost:9222/json or browser debugger url http://localhost:9222/json/version)
*
* @param webSocketUri WebSocket debugger uri to connect to
* @param framesBufferSize Frames buffer size (how many [ResponseFrame]s will be replayed prior to subscribing to stream)
* @param mapper FrameMapper that will serialize/deserialize frames exchanged by protocol
* @param webSocketClient WebSocket client for exchanging WebSocket frames.
*/
class WebSocketFramesStream(
webSocketUri: String,
framesBufferSize: Int,
private val mapper: FrameMapper,
webSocketClient: OkHttpClient
) : WebSocketListener(), Closeable, AutoCloseable {
private val messages: Subject<WebSocketFrame> = ReplaySubject.createWithSize(framesBufferSize)
private val connection: WebSocket = webSocketClient.newWebSocket(Request.Builder().url(webSocketUri).build(), this)
private val client: OkHttpClient = webSocketClient
/**
* onMessage is called when new frame arrives on WebSocket.
*/
override fun onMessage(webSocket: WebSocket, text: String) {
messages.onNext(mapper.deserializeWebSocketMessage(text))
}
/**
* onClosed is called when WebSocket is being closed.
*/
override fun onClosed(webSocket: WebSocket, code: Int, reason: String): Unit = closeSilently()
/**
* onFailure is called when WebSocket protocol error occurs.
*/
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
if (t !is EOFException) {
logger.warn("Caught WebSocket exception: $t")
}
}
/**
* Returns protocol response for given request frame (if any).
*/
fun <T> getResponse(requestFrame: RequestFrame, serializer: KSerializer<T>): Single<T> {
return frames()
.ofType(ResponseFrame::class.java)
.filter { it.matches(requestFrame) }
.map { frame -> mapper.deserializeResponseFrame(requestFrame, frame, serializer) }
.subscribeOn(Schedulers.io())
.firstOrError()
}
/**
* Sends frame over the WebSocket connection.
*/
fun send(frame: RequestFrame): Single<Boolean> {
return Single.just(connection.send(mapper.serialize(frame)))
}
/**
* Returns all frames that represent events from WebSocket connection.
*/
fun eventFrames(): Flowable<EventResponseFrame> = frames().ofType(EventResponseFrame::class.java)
/**
* Returns all frames received from WebSocket connection.
*/
fun frames(): Flowable<WebSocketFrame> = messages.toFlowable(BackpressureStrategy.BUFFER)
/**
* Closes WebSocket connection.
*/
override fun close() {
try {
connection.close(1000, "Goodbye!")
client.connectionPool.evictAll()
client.dispatcher.executorService.shutdown()
} catch (e: Exception) {
logger.warn("Caught exception while closing WebSocket stream: ${e.message}")
}
try {
closeSilently()
} catch (e: Exception) {
logger.warn("Caught exception while completing subject: ${e.message}")
}
}
/**
* Completes frames stream.
*/
private fun closeSilently() {
if (!(messages.hasComplete() || messages.hasThrowable())) {
return messages.onComplete()
}
}
companion object {
private val logger = LoggerFactory.getLogger(WebSocketFramesStream::class.java)!!
}
}
| apache-2.0 | 7210107623966ad2a804cf81b9866cff | 34.563025 | 127 | 0.694707 | 4.717949 | false | false | false | false |
ivanTrogrlic/LeagueStats | app/src/main/java/com/ivantrogrlic/leaguestats/main/summoner/games/GamesAdapter.kt | 1 | 3780 | package com.ivantrogrlic.leaguestats.main.summoner.games
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import com.ivantrogrlic.leaguestats.R
import com.ivantrogrlic.leaguestats.model.Match
import com.ivantrogrlic.leaguestats.model.queueName
import com.ivantrogrlic.leaguestats.web.getChampionIconUrl
import com.ivantrogrlic.leaguestats.web.getItemIconUrl
import com.ivantrogrlic.leaguestats.web.getSummonerIconUrl
import com.squareup.picasso.Picasso.with
import kotlinx.android.synthetic.main.game_item.view.*
/**
* Created by ivan on 8/11/2017.
*/
class GamesAdapter(val context: Context) : RecyclerView.Adapter<GamesAdapter.GameHolder>() {
private var matches: List<Match> = emptyList()
fun setMatches(matches: List<Match>) {
this.matches = matches
notifyDataSetChanged()
}
class GameHolder(v: View) : RecyclerView.ViewHolder(v) {
private var matchType: TextView = v.match_type
private var matchTime: TextView = v.match_time
private var matchLength: TextView = v.match_length
private var championIcon: ImageView = v.champion_icon
private var summonerSpell1: ImageView = v.summoner_spell_1
private var summonerSpell2: ImageView = v.summoner_spell_2
private var score: TextView = v.score
private var kda: TextView = v.kda
private var cs: TextView = v.cs
private var item1: ImageView = v.item_1
private var item2: ImageView = v.item_2
private var item3: ImageView = v.item_3
private var item4: ImageView = v.item_4
private var item5: ImageView = v.item_5
private var item6: ImageView = v.item_6
private var trinket: ImageView = v.trinket
fun bindMatch(context: Context, match: Match) {
val participant = match.participants.first()
val stats = participant.stats
matchType.text = queueName(context, match.queue)
matchTime.text = match.gameCreation.toString()
matchLength.text = match.gameDuration.toString()
matchLength.text = match.gameDuration.toString()
score.text = stats.kills.toString()
kda.text = ((stats.kills + stats.assists) / stats.deaths).toString()
cs.text = stats.totalMinionsKilled.toString()
with(context).load(getChampionIconUrl(participant.championName!!)).into(championIcon)
with(context).load(getSummonerIconUrl(participant.spell1Name!!)).into(summonerSpell1)
with(context).load(getSummonerIconUrl(participant.spell2Name!!)).into(summonerSpell2)
with(context).load(getItemIconUrl(stats.item0)).into(item1)
with(context).load(getItemIconUrl(stats.item1)).into(item2)
with(context).load(getItemIconUrl(stats.item2)).into(item3)
with(context).load(getItemIconUrl(stats.item3)).into(item4)
with(context).load(getItemIconUrl(stats.item4)).into(item5)
with(context).load(getItemIconUrl(stats.item5)).into(item6)
with(context).load(getItemIconUrl(stats.item6)).into(trinket)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): GameHolder {
val inflatedView = LayoutInflater
.from(parent.context)
.inflate(R.layout.game_item, parent, false)
return GameHolder(inflatedView)
}
override fun onBindViewHolder(holder: GameHolder, position: Int) {
matches.let { holder.bindMatch(context, it[position]) }
}
override fun getItemCount(): Int {
return matches.size
}
}
| apache-2.0 | 331b6e4bda4db869a34fcd4a81f0d460 | 41.954545 | 97 | 0.69418 | 3.822042 | false | false | false | false |
codeka/wwmmo | client/src/main/kotlin/au/com/codeka/warworlds/client/opengl/BitmapTexture.kt | 1 | 3732 | package au.com.codeka.warworlds.client.opengl
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.opengl.GLES20
import android.opengl.GLUtils
import au.com.codeka.warworlds.client.App
import au.com.codeka.warworlds.client.concurrency.Threads
import au.com.codeka.warworlds.common.Log
import com.google.common.base.Preconditions
import com.squareup.picasso.Picasso
import com.squareup.picasso.Picasso.LoadedFrom
import com.squareup.picasso.Target
import java.io.IOException
/** Represents a texture image. */
class BitmapTexture private constructor(loader: Loader) : Texture() {
private var loader: Loader?
override fun bind() {
val l = loader
if (l != null && l.isLoaded) {
setTextureId(l.createGlTexture())
loader = null
}
super.bind()
}
/** Handles loading a texture into a [BitmapTexture]. */
private class Loader internal constructor(
private val context: Context, fileName: String?, url: String?) {
private val fileName: String?
private val url: String?
private var bitmap: Bitmap? = null
fun load() {
if (fileName != null) {
App.taskRunner.runTask(Runnable {
try {
log.info("Loading resource: %s", fileName)
val ins = context.assets.open(fileName)
// BitmapFactory.decodeStream defaults to premultiplied alpha but since we're going to
// render these with OpenGL, we don't want premultiplied alpha.
val opt = BitmapFactory.Options()
opt.inPremultiplied = false
bitmap = BitmapFactory.decodeStream(ins, null, opt)
} catch (e: IOException) {
log.error("Error loading texture '%s'", fileName, e)
}
}, Threads.BACKGROUND)
} else {
App.taskRunner.runTask(
Runnable { Picasso.get().load(url).into(picassoTarget) },
Threads.UI)
}
}
val isLoaded: Boolean
get() = bitmap != null
fun createGlTexture(): Int {
Preconditions.checkState(bitmap != null)
val textureHandleBuffer = IntArray(1)
GLES20.glGenTextures(1, textureHandleBuffer, 0)
GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandleBuffer[0])
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_LINEAR)
GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_LINEAR)
GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0)
return textureHandleBuffer[0]
}
/**
* This is our callback for when Picasso finishes loading an image.
*
* We need to keep a strong reference to this, otherwise it gets GC'd before Picasso returns.
*/
val picassoTarget: Target = object : Target {
override fun onBitmapLoaded(loadedBitmap: Bitmap, from: LoadedFrom) {
bitmap = loadedBitmap
}
override fun onBitmapFailed(e: Exception, errorDrawable: Drawable?) {
log.warning("error loading bitmap: %s", url, e)
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
}
init {
Preconditions.checkState(fileName != null || url != null)
this.fileName = fileName
this.url = url
}
}
companion object {
private val log = Log("TextureBitmap")
fun load(context: Context, fileName: String?): BitmapTexture {
return BitmapTexture(Loader(context, fileName, null /* url */))
}
fun loadUrl(context: Context, url: String?): BitmapTexture {
return BitmapTexture(Loader(context, null /* fileName */, url))
}
}
init {
loader.load()
this.loader = loader
}
} | mit | 1e1e95c8ef45cd8ec7d3ddfbab713897 | 31.745614 | 98 | 0.668274 | 4.151279 | false | false | false | false |
pdvrieze/darwin-android-auth | src/main/java/uk/ac/bournemouth/darwin/auth/HttpResponseException.kt | 1 | 2536 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 2.1 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package uk.ac.bournemouth.darwin.auth
import java.io.IOException
import java.io.InputStreamReader
import java.net.HttpURLConnection
/**
* An exception thrown when a http response is thrown that was unexpected. This class will actually attempt to get the
* http response body as part of the message.
* @constructor Create a new exception. Read the status from the given connection.
* @param connection The connection that caused the exception.
*/
class HttpResponseException(connection: HttpURLConnection) : IOException(getMessage(connection)) {
companion object {
private const val serialVersionUID = -1709759910920830203L
private const val RESPONSE_BASE = "Unexpected HTTP Response:"
private fun getMessage(connection: HttpURLConnection) = buildString {
try {
append(RESPONSE_BASE)
append(connection.responseCode)
append(' ').append(connection.responseMessage)
append("\n\n")
InputStreamReader(connection.errorStream, UTF8).useLines { line ->
append(line).append('\n')
}
} catch (e: IOException) {
if (length <= RESPONSE_BASE.length) {
return "$RESPONSE_BASE No details possible"
} else {
val s = toString()
if (s.startsWith(RESPONSE_BASE)) {
setLength(RESPONSE_BASE.length)
append("Partial details only: ")
.append(s.substring(RESPONSE_BASE.length))
} else {
setLength(0)
append("$RESPONSE_BASE Partial details only: ")
.append(s)
}
}
}
}
}
}
| lgpl-2.1 | 07613f6ea05799ea296b774629392ff7 | 36.294118 | 118 | 0.612776 | 5.04175 | false | false | false | false |
Gh0u1L5/WechatMagician | app/src/main/kotlin/com/gh0u1l5/wechatmagician/frontend/fragments/DonateFragment.kt | 1 | 2759 | package com.gh0u1l5.wechatmagician.frontend.fragments
import android.app.Fragment
import android.content.ComponentName
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.View.GONE
import android.view.ViewGroup
import android.widget.Toast
import com.gh0u1l5.wechatmagician.Global.WECHAT_PACKAGE_NAME
import com.gh0u1l5.wechatmagician.R
import com.gh0u1l5.wechatmagician.frontend.fragments.StatusFragment.Companion.requireHookStatus
import com.gh0u1l5.wechatmagician.spellbook.WechatStatus.StatusFlag.STATUS_FLAG_URI_ROUTER
import com.gh0u1l5.wechatmagician.util.AlipayUtil
import kotlinx.android.synthetic.main.fragment_donate.*
class DonateFragment : Fragment() {
private val alipayCode = "FKX04114Q6YBQLKYU0KS09"
private val tenpayCode = "f2f00-2YC_1Sfo3jM1G--Zj8kC2Z7koDXC8r"
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
inflater.inflate(R.layout.fragment_donate, container, false)
override fun onStart() {
super.onStart()
// Hide Tenpay if the URI router is not hijacked.
requireHookStatus(activity!!, { status ->
if (!status.contains(STATUS_FLAG_URI_ROUTER)) {
donate_tenpay.visibility = GONE
}
})
// Set onClick listeners for donation buttons.
donate_alipay.setOnClickListener { view ->
if (!AlipayUtil.hasInstalledAlipayClient(view.context)) {
Toast.makeText(view.context, R.string.prompt_alipay_not_found, Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
Toast.makeText(view.context, R.string.prompt_wait, Toast.LENGTH_SHORT).show()
AlipayUtil.startAlipayClient(view.context, alipayCode)
}
donate_tenpay.setOnClickListener { view ->
val className = "$WECHAT_PACKAGE_NAME.plugin.base.stub.WXCustomSchemeEntryActivity"
val componentName = ComponentName(WECHAT_PACKAGE_NAME, className)
try {
view.context.startActivity(Intent(Intent.ACTION_VIEW).apply {
component = componentName
data = Uri.parse("weixin://magician/donate/$tenpayCode")
flags = Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP
})
Toast.makeText(view.context, R.string.prompt_wait, Toast.LENGTH_SHORT).show()
} catch (t: Throwable) {
Toast.makeText(view.context, t.localizedMessage, Toast.LENGTH_SHORT).show()
}
}
}
companion object {
fun newInstance(): DonateFragment = DonateFragment()
}
}
| gpl-3.0 | effec4be9f26472fe5bc524072bc697b | 40.80303 | 116 | 0.685031 | 4.063328 | false | false | false | false |
Gh0u1L5/WechatMagician | app/src/main/kotlin/com/gh0u1l5/wechatmagician/backend/storage/Strings.kt | 1 | 5188 | package com.gh0u1l5.wechatmagician.backend.storage
import com.gh0u1l5.wechatmagician.Global.SETTINGS_MODULE_LANGUAGE
import com.gh0u1l5.wechatmagician.R
import com.gh0u1l5.wechatmagician.backend.WechatHook
import de.robv.android.xposed.XposedBridge.log
import java.util.*
object Strings {
private val pref = WechatHook.settings
@Volatile var language: String = Locale.getDefault().language
// Use hard coded strings if the module cannot load resources from its APK
private val hardcodedStrings: Map<String, Map<Int, String>> = mapOf (
// NOTE: Replace <string name="(.*?)">(.*?)</string> to R.string.$1 to "$2",
"en" to mapOf (
R.string.button_ok to "Okay",
R.string.button_update to "Update",
R.string.button_cancel to "Cancel",
R.string.button_clean_unread to "Mark All as Read",
R.string.button_hide_chatroom to "Hide Useless Chatroom",
R.string.button_unhide_chatroom to "Unhide Chatroom",
R.string.button_hide_friend to "Hide Friend",
R.string.button_select_all to "All",
R.string.button_sns_forward to "Forward",
R.string.button_sns_screenshot to "Screenshot",
R.string.prompt_alipay_not_found to "Alipay Not Found",
R.string.prompt_load_component_status_failed to "Failed to retrieve the status of components.",
R.string.prompt_message_recall to "want to recall the message, idiot.",
R.string.prompt_need_reboot to "Take effect after reboot.",
R.string.prompt_screenshot to "The screenshot has been saved to",
R.string.prompt_sns_invalid to "Record is invalid or deleted.",
R.string.prompt_update_discovered to "Update Discovered",
R.string.prompt_wait to "Please wait for a while.....",
R.string.prompt_setup_password to "Enter a new password",
R.string.prompt_verify_password to "Enter your password",
R.string.prompt_user_not_found to "User Not Found!",
R.string.prompt_password_missing to "Please set your password first!",
R.string.prompt_correct_password to "Correct Password!",
R.string.prompt_wrong_password to "Wrong Password!",
R.string.label_deleted to "[Deleted]",
R.string.label_unnamed to "[Unnamed]",
R.string.title_secret_friend to "Secret Friend"
),
"zh" to mapOf (
R.string.button_ok to "确定",
R.string.button_update to "更新",
R.string.button_cancel to "取消",
R.string.button_clean_unread to "清空全部未读提醒",
R.string.button_hide_chatroom to "隐藏无用群聊",
R.string.button_unhide_chatroom to "还原群聊",
R.string.button_hide_friend to "隐藏好友",
R.string.button_select_all to "全选",
R.string.button_sns_forward to "转发",
R.string.button_sns_screenshot to "截图",
R.string.prompt_alipay_not_found to "未发现支付宝手机客户端",
R.string.prompt_load_component_status_failed to "组件状态检查失败",
R.string.prompt_message_recall to "妄图撤回一条消息,啧啧",
R.string.prompt_need_reboot to "重启后生效",
R.string.prompt_screenshot to "截图已保存至",
R.string.prompt_sns_invalid to "数据失效或已删除",
R.string.prompt_update_discovered to "发现更新",
R.string.prompt_wait to "请稍候片刻……",
R.string.prompt_setup_password to "请设定新密码",
R.string.prompt_verify_password to "请输入解锁密码",
R.string.prompt_user_not_found to "用户不存在",
R.string.prompt_password_missing to "请先设置密码",
R.string.prompt_correct_password to "密码正确",
R.string.prompt_wrong_password to "密码错误",
R.string.label_deleted to "[已删除]",
R.string.label_unnamed to "[未命名]",
R.string.title_secret_friend to "密友"
)
)
fun getString(id: Int): String {
val resources = WechatHook.resources
if (resources != null) {
return resources.getString(id)
}
val language = pref.getString(SETTINGS_MODULE_LANGUAGE, language)
if (language !in hardcodedStrings) {
log("Unknown Language: $language")
}
val strings = hardcodedStrings[language] ?: hardcodedStrings["en"]
if (id !in strings!!) {
log("Unknown String ID: $id")
}
return strings[id] ?: "???"
}
} | gpl-3.0 | 35246e7da010b7b0c20cf982b7d57153 | 49.214286 | 115 | 0.557927 | 4.082988 | false | false | false | false |
RSDT/Japp16 | app/src/main/java/nl/rsdt/japp/jotial/maps/management/transformation/async/AsyncTransduceTask.kt | 2 | 918 | package nl.rsdt.japp.jotial.maps.management.transformation.async
import android.os.AsyncTask
import nl.rsdt.japp.jotial.maps.management.transformation.AbstractTransducer
/**
* @author Dingenis Sieger Sinke
* @version 1.0
* @since 4-9-2016
* Description...
*/
class AsyncTransduceTask<I, O : AbstractTransducer.Result> : AsyncTask<Int, Int, O>() {
var transducer: AbstractTransducer<I, O>? = null
var data: I? = null
var callback: OnTransduceCompletedCallback<O>? = null
protected override fun doInBackground(vararg integers: Int?): O? {
return data?.let { transducer?.generate(it) }
}
override fun onPostExecute(output: O?) {
if (output != null && callback != null) {
callback!!.onTransduceCompleted(output)
}
}
interface OnTransduceCompletedCallback<O : AbstractTransducer.Result> {
fun onTransduceCompleted(result: O)
}
}
| apache-2.0 | a2c36e96e36b409ffafb6232a704dac8 | 26 | 87 | 0.684096 | 3.906383 | false | false | false | false |
yzbzz/beautifullife | app/src/main/java/com/ddu/help/LifeCycleHandler.kt | 2 | 1309 | package com.ddu.help
import android.os.Handler
import android.os.Message
import android.util.Log
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import java.lang.ref.WeakReference
/**
* Created by yzbzz on 2019/11/23.
*/
open class LifeCycleHandler(owner: LifecycleOwner, val block: (Message) -> Unit) : Handler(), LifecycleObserver {
private val mOwner: WeakReference<LifecycleOwner> = WeakReference(owner)
init {
mOwner.get()?.apply {
lifecycle.addObserver(LifecycleBoundObserver())
}
}
inner class LifecycleBoundObserver : LifecycleEventObserver {
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
val state = source.lifecycle.currentState
if (state == Lifecycle.State.DESTROYED) {
removeCallbacksAndMessages(null)
source.lifecycle.removeObserver(this)
Log.v("lhz", "LifeCycleHandle removeCallbacksAndMessages")
}
}
}
override fun handleMessage(msg: Message) {
super.handleMessage(msg)
val owner = mOwner.get()
if (owner != null) {
block(msg)
}
}
} | apache-2.0 | 310a84749101a3c59095598f5f1e46f0 | 29.465116 | 113 | 0.673797 | 4.848148 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/UserStatComputer.kt | 1 | 5049 | package com.habitrpg.android.habitica.helpers
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.models.Avatar
import com.habitrpg.android.habitica.models.inventory.Equipment
import com.habitrpg.android.habitica.models.user.Stats
class UserStatComputer {
interface StatsRow
inner class AttributeRow : StatsRow {
var labelId: Int = 0
var strVal: Float = 0.toFloat()
var intVal: Float = 0.toFloat()
var conVal: Float = 0.toFloat()
var perVal: Float = 0.toFloat()
var roundDown: Boolean = false
var summary: Boolean = false
}
inner class EquipmentRow : StatsRow {
var gearKey: String? = null
var text: String? = null
var stats: String? = null
}
fun computeClassBonus(equipmentList: List<Equipment>, user: Avatar): List<StatsRow> {
val skillRows = ArrayList<StatsRow>()
var strAttributes = 0f
var intAttributes = 0f
var conAttributes = 0f
var perAttributes = 0f
var strClassBonus = 0f
var intClassBonus = 0f
var conClassBonus = 0f
var perClassBonus = 0f
// Summarize stats and fill equipment table
for (i in equipmentList) {
val strength = i.str
val intelligence = i._int
val constitution = i.con
val perception = i.per
strAttributes += strength.toFloat()
intAttributes += intelligence.toFloat()
conAttributes += constitution.toFloat()
perAttributes += perception.toFloat()
val sb = StringBuilder()
if (strength != 0) {
sb.append("STR ").append(strength).append(", ")
}
if (intelligence != 0) {
sb.append("INT ").append(intelligence).append(", ")
}
if (constitution != 0) {
sb.append("CON ").append(constitution).append(", ")
}
if (perception != 0) {
sb.append("PER ").append(perception).append(", ")
}
// remove the last comma
if (sb.length > 2) {
sb.delete(sb.length - 2, sb.length)
}
val equipmentRow = EquipmentRow()
equipmentRow.gearKey = i.key
equipmentRow.text = i.text
equipmentRow.stats = sb.toString()
skillRows.add(equipmentRow)
// Calculate class bonus
var itemClass: String? = i.klass
val itemSpecialClass = i.specialClass
val classDoesNotExist = itemClass == null || itemClass.isEmpty()
val specialClassDoesNotExist = itemSpecialClass.isEmpty()
if (classDoesNotExist && specialClassDoesNotExist) {
continue
}
var classBonus = 0.5f
val userClassMatchesGearClass = !classDoesNotExist && itemClass == user.stats?.habitClass
val userClassMatchesGearSpecialClass = !specialClassDoesNotExist && itemSpecialClass == user.stats?.habitClass
if (!userClassMatchesGearClass && !userClassMatchesGearSpecialClass) classBonus = 0f
if (itemClass == null || itemClass.isEmpty() || itemClass == "special") {
itemClass = itemSpecialClass
}
when (itemClass) {
Stats.ROGUE -> {
strClassBonus += strength * classBonus
perClassBonus += perception * classBonus
}
Stats.HEALER -> {
conClassBonus += constitution * classBonus
intClassBonus += intelligence * classBonus
}
Stats.WARRIOR -> {
strClassBonus += strength * classBonus
conClassBonus += constitution * classBonus
}
Stats.MAGE -> {
intClassBonus += intelligence * classBonus
perClassBonus += perception * classBonus
}
}
}
val attributeRow = AttributeRow()
attributeRow.labelId = R.string.battle_gear
attributeRow.strVal = strAttributes
attributeRow.intVal = intAttributes
attributeRow.conVal = conAttributes
attributeRow.perVal = perAttributes
attributeRow.roundDown = true
attributeRow.summary = false
skillRows.add(attributeRow)
val attributeRow2 = AttributeRow()
attributeRow2.labelId = R.string.profile_class_bonus
attributeRow2.strVal = strClassBonus
attributeRow2.intVal = intClassBonus
attributeRow2.conVal = conClassBonus
attributeRow2.perVal = perClassBonus
attributeRow2.roundDown = false
attributeRow2.summary = false
skillRows.add(attributeRow2)
return skillRows
}
}
| gpl-3.0 | 172089440b8fbeab72f894846903c474 | 33.556338 | 122 | 0.557734 | 5.298006 | false | false | false | false |
charleskorn/batect | app/src/main/kotlin/batect/config/TaskMap.kt | 1 | 1545 | /*
Copyright 2017-2020 Charles Korn.
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 batect.config
import kotlinx.serialization.KSerializer
import kotlinx.serialization.SerialDescriptor
import kotlinx.serialization.Serializer
import kotlinx.serialization.internal.HashMapClassDesc
class TaskMap(contents: Iterable<Task>) : NamedObjectMap<Task>("task", contents) {
constructor(vararg contents: Task) : this(contents.asIterable())
override fun nameFor(value: Task): String = value.name
@Serializer(forClass = TaskMap::class)
companion object : NamedObjectMapSerializer<TaskMap, Task>(Task.serializer()), KSerializer<TaskMap> {
override fun addName(name: String, element: Task): Task = element.copy(name = name)
override fun getName(element: Task): String = element.name
override fun createCollection(elements: Set<Task>): TaskMap = TaskMap(elements)
override val descriptor: SerialDescriptor = HashMapClassDesc(keySerializer.descriptor, elementSerializer.descriptor)
}
}
| apache-2.0 | d7e57099e51ff35bc73b87979b8247de | 40.756757 | 124 | 0.757282 | 4.63964 | false | false | false | false |
nimakro/tornadofx | src/main/java/tornadofx/Slideshow.kt | 1 | 5009 | package tornadofx
import javafx.beans.property.ObjectProperty
import javafx.beans.property.ReadOnlyIntegerProperty
import javafx.beans.property.SimpleIntegerProperty
import javafx.beans.property.SimpleObjectProperty
import javafx.collections.FXCollections
import javafx.collections.ListChangeListener
import javafx.collections.ObservableList
import javafx.scene.input.KeyCombination
import javafx.scene.input.KeyEvent
import javafx.scene.layout.BorderPane
import javafx.util.Duration
import tornadofx.ViewTransition.Direction.RIGHT
import java.util.*
import kotlin.concurrent.timerTask
import kotlin.reflect.KClass
class Slideshow(val scope: Scope = DefaultScope, defaultTimeout: Duration? = null) : BorderPane() {
val slides: ObservableList<Slide> = FXCollections.observableArrayList<Slide>()
var defaultTimeoutProperty = SimpleObjectProperty<Duration>(defaultTimeout)
var defaultTimeout by defaultTimeoutProperty
val defaultTransitionProperty: ObjectProperty<ViewTransition> = SimpleObjectProperty(ViewTransition.Swap(.3.seconds))
var defaultTransition: ViewTransition? by defaultTransitionProperty
val defaultBackTransitionProperty: ObjectProperty<ViewTransition> = SimpleObjectProperty(ViewTransition.Swap(.3.seconds, RIGHT))
var defaultBackTransition: ViewTransition? by defaultBackTransitionProperty
val currentSlideProperty: ObjectProperty<Slide?> = SimpleObjectProperty()
var currentSlide: Slide? by currentSlideProperty
val nextKeyProperty: ObjectProperty<KeyCombination> = SimpleObjectProperty(KeyCombination.valueOf("Alt+Right"))
var nextKey: KeyCombination by nextKeyProperty
val previousKeyProperty: ObjectProperty<KeyCombination> = SimpleObjectProperty(KeyCombination.valueOf("Alt+Left"))
var previousKey: KeyCombination by previousKeyProperty
private val realIndexProperty = SimpleIntegerProperty(-1)
val indexProperty: ReadOnlyIntegerProperty = ReadOnlyIntegerProperty.readOnlyIntegerProperty(realIndexProperty)
val index by indexProperty
inline fun <reified T : UIComponent> slide(transition: ViewTransition? = null, timeout: Duration? = defaultTimeout) = slide(T::class, transition, timeout)
fun slide(view: KClass<out UIComponent>, transition: ViewTransition? = null, timeout: Duration? = defaultTimeout) = slides.addAll(Slide(view, transition, timeout))
fun hasNext() = index < (slides.size - 1)
private var timer: Timer? = null
private var task: TimerTask? = null
fun next(): Boolean {
if (!hasNext()) return false
goto(slides[index + 1], true)
return true
}
fun previous(): Boolean {
if (index <= 0) return false
goto(slides[index - 1], false)
return true
}
init {
showFirstSlideWhenAvailable()
hookNavigationShortcuts()
listenForNextSlide()
}
private fun listenForNextSlide() {
currentSlideProperty.onChange { slide ->
slide?.timeout?.let { timeout ->
if (timer == null) {
timer = Timer("SlideshowTimer${this@Slideshow}")
}
task?.cancel()
task = timerTask {
runLater {
next()
}
}
timer!!.schedule(task, timeout.toMillis().toLong())
}
}
}
private fun hookNavigationShortcuts() {
sceneProperty().onChange {
scene?.addEventHandler(KeyEvent.KEY_PRESSED) {
if (!it.isConsumed) {
if (nextKey.match(it)) next()
else if (previousKey.match(it)) previous()
}
}
}
}
private fun showFirstSlideWhenAvailable() {
slides.addListener { change: ListChangeListener.Change<out Slide> ->
while (change.next()) {
if (change.wasAdded() && currentSlide == null)
next()
}
}
}
private fun goto(slide: Slide, forward: Boolean) {
val nextUI = slide.getUI(scope)
// Avoid race conditions if last transition is still in progress
val centerRightNow = center
if (centerRightNow == null) {
center = nextUI.root
} else {
val transition = if (forward) slide.transition ?: defaultTransition else defaultBackTransition
nextUI.root.removeFromParent()
centerRightNow.replaceWith(nextUI.root, transition)
}
val delta = if (forward) 1 else -1
val newIndex = index + delta
currentSlide = slides[newIndex]
realIndexProperty.value = newIndex
}
class Slide(val view: KClass<out UIComponent>, val transition: ViewTransition? = null, val timeout: Duration? = null) {
private lateinit var ui: UIComponent
fun getUI(scope: Scope): UIComponent {
if (!::ui.isInitialized) ui = find(view, scope)
return ui
}
}
} | apache-2.0 | ccb3f36c7cb8d21ea6c7a24ab7e60a27 | 36.669173 | 167 | 0.667598 | 5.190674 | false | false | false | false |
yschimke/okhttp | mockwebserver/src/main/kotlin/mockwebserver3/MockResponse.kt | 2 | 11149 | /*
* Copyright (C) 2011 Google 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 mockwebserver3
import java.util.concurrent.TimeUnit
import okhttp3.Headers
import okhttp3.WebSocketListener
import okhttp3.internal.addHeaderLenient
import okhttp3.internal.http2.Settings
import mockwebserver3.internal.duplex.DuplexResponseBody
import okio.Buffer
/** A scripted response to be replayed by the mock web server. */
class MockResponse : Cloneable {
/** Returns the HTTP response line, such as "HTTP/1.1 200 OK". */
@set:JvmName("status")
var status: String = ""
private var headersBuilder = Headers.Builder()
private var trailersBuilder = Headers.Builder()
/** The HTTP headers, such as "Content-Length: 0". */
@set:JvmName("headers")
var headers: Headers
get() = headersBuilder.build()
set(value) {
this.headersBuilder = value.newBuilder()
}
@set:JvmName("trailers")
var trailers: Headers
get() = trailersBuilder.build()
set(value) {
this.trailersBuilder = value.newBuilder()
}
private var body: Buffer? = null
var throttleBytesPerPeriod: Long = Long.MAX_VALUE
private set
private var throttlePeriodAmount = 1L
private var throttlePeriodUnit = TimeUnit.SECONDS
@set:JvmName("socketPolicy")
var socketPolicy: SocketPolicy = SocketPolicy.KEEP_OPEN
/**
* Sets the [HTTP/2 error code](https://tools.ietf.org/html/rfc7540#section-7) to be
* returned when resetting the stream.
* This is only valid with [SocketPolicy.RESET_STREAM_AT_START] and
* [SocketPolicy.DO_NOT_READ_REQUEST_BODY].
*/
@set:JvmName("http2ErrorCode")
var http2ErrorCode: Int = -1
private var bodyDelayAmount = 0L
private var bodyDelayUnit = TimeUnit.MILLISECONDS
private var headersDelayAmount = 0L
private var headersDelayUnit = TimeUnit.MILLISECONDS
private var promises = mutableListOf<PushPromise>()
var settings: Settings = Settings()
private set
var webSocketListener: WebSocketListener? = null
private set
var duplexResponseBody: DuplexResponseBody? = null
private set
val isDuplex: Boolean
get() = duplexResponseBody != null
/** Returns the streams the server will push with this response. */
val pushPromises: List<PushPromise>
get() = promises
/** Creates a new mock response with an empty body. */
init {
setResponseCode(200)
setHeader("Content-Length", 0L)
}
public override fun clone(): MockResponse {
val result = super.clone() as MockResponse
result.headersBuilder = headersBuilder.build().newBuilder()
result.promises = promises.toMutableList()
return result
}
@JvmName("-deprecated_getStatus")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "status"),
level = DeprecationLevel.ERROR)
fun getStatus(): String = status
/**
* Sets the status and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [status] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setStatus(status: String) = apply {
this.status = status
}
fun setResponseCode(code: Int): MockResponse {
val reason = when (code) {
in 100..199 -> "Informational"
in 200..299 -> "OK"
in 300..399 -> "Redirection"
in 400..499 -> "Client Error"
in 500..599 -> "Server Error"
else -> "Mock Response"
}
return apply { status = "HTTP/1.1 $code $reason" }
}
/**
* Removes all HTTP headers including any "Content-Length" and "Transfer-encoding" headers that
* were added by default.
*/
fun clearHeaders() = apply {
headersBuilder = Headers.Builder()
}
/**
* Adds [header] as an HTTP header. For well-formed HTTP [header] should contain a
* name followed by a colon and a value.
*/
fun addHeader(header: String) = apply {
headersBuilder.add(header)
}
/**
* Adds a new header with the name and value. This may be used to add multiple headers with the
* same name.
*/
fun addHeader(name: String, value: Any) = apply {
headersBuilder.add(name, value.toString())
}
/**
* Adds a new header with the name and value. This may be used to add multiple headers with the
* same name. Unlike [addHeader] this does not validate the name and
* value.
*/
fun addHeaderLenient(name: String, value: Any) = apply {
addHeaderLenient(headersBuilder, name, value.toString())
}
/**
* Removes all headers named [name], then adds a new header with the name and value.
*/
fun setHeader(name: String, value: Any) = apply {
removeHeader(name)
addHeader(name, value)
}
/** Removes all headers named [name]. */
fun removeHeader(name: String) = apply {
headersBuilder.removeAll(name)
}
/** Returns a copy of the raw HTTP payload. */
fun getBody(): Buffer? = body?.clone()
fun setBody(body: Buffer) = apply {
setHeader("Content-Length", body.size)
this.body = body.clone() // Defensive copy.
}
/** Sets the response body to the UTF-8 encoded bytes of [body]. */
fun setBody(body: String): MockResponse = setBody(Buffer().writeUtf8(body))
fun setBody(duplexResponseBody: DuplexResponseBody) = apply {
this.duplexResponseBody = duplexResponseBody
}
/**
* Sets the response body to [body], chunked every [maxChunkSize] bytes.
*/
fun setChunkedBody(body: Buffer, maxChunkSize: Int) = apply {
removeHeader("Content-Length")
headersBuilder.add(CHUNKED_BODY_HEADER)
val bytesOut = Buffer()
while (!body.exhausted()) {
val chunkSize = minOf(body.size, maxChunkSize.toLong())
bytesOut.writeHexadecimalUnsignedLong(chunkSize)
bytesOut.writeUtf8("\r\n")
bytesOut.write(body, chunkSize)
bytesOut.writeUtf8("\r\n")
}
bytesOut.writeUtf8("0\r\n") // Last chunk. Trailers follow!
this.body = bytesOut
}
/**
* Sets the response body to the UTF-8 encoded bytes of [body],
* chunked every [maxChunkSize] bytes.
*/
fun setChunkedBody(body: String, maxChunkSize: Int): MockResponse =
setChunkedBody(Buffer().writeUtf8(body), maxChunkSize)
@JvmName("-deprecated_getHeaders")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "headers"),
level = DeprecationLevel.ERROR)
fun getHeaders(): Headers = headers
/**
* Sets the headers and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [headers] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setHeaders(headers: Headers) = apply { this.headers = headers }
@JvmName("-deprecated_getTrailers")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "trailers"),
level = DeprecationLevel.ERROR)
fun getTrailers(): Headers = trailers
/**
* Sets the trailers and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [trailers] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setTrailers(trailers: Headers) = apply { this.trailers = trailers }
@JvmName("-deprecated_getSocketPolicy")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "socketPolicy"),
level = DeprecationLevel.ERROR)
fun getSocketPolicy(): SocketPolicy = socketPolicy
/**
* Sets the socket policy and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [socketPolicy] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setSocketPolicy(socketPolicy: SocketPolicy) = apply {
this.socketPolicy = socketPolicy
}
@JvmName("-deprecated_getHttp2ErrorCode")
@Deprecated(
message = "moved to var",
replaceWith = ReplaceWith(expression = "http2ErrorCode"),
level = DeprecationLevel.ERROR)
fun getHttp2ErrorCode(): Int = http2ErrorCode
/**
* Sets the HTTP/2 error code and returns this.
*
* This was deprecated in OkHttp 4.0 in favor of the [http2ErrorCode] val. In OkHttp 4.3 it is
* un-deprecated because Java callers can't chain when assigning Kotlin vals. (The getter remains
* deprecated).
*/
fun setHttp2ErrorCode(http2ErrorCode: Int) = apply {
this.http2ErrorCode = http2ErrorCode
}
/**
* Throttles the request reader and response writer to sleep for the given period after each
* series of [bytesPerPeriod] bytes are transferred. Use this to simulate network behavior.
*/
fun throttleBody(bytesPerPeriod: Long, period: Long, unit: TimeUnit) = apply {
throttleBytesPerPeriod = bytesPerPeriod
throttlePeriodAmount = period
throttlePeriodUnit = unit
}
fun getThrottlePeriod(unit: TimeUnit): Long =
unit.convert(throttlePeriodAmount, throttlePeriodUnit)
/**
* Set the delayed time of the response body to [delay]. This applies to the response body
* only; response headers are not affected.
*/
fun setBodyDelay(delay: Long, unit: TimeUnit) = apply {
bodyDelayAmount = delay
bodyDelayUnit = unit
}
fun getBodyDelay(unit: TimeUnit): Long =
unit.convert(bodyDelayAmount, bodyDelayUnit)
fun setHeadersDelay(delay: Long, unit: TimeUnit) = apply {
headersDelayAmount = delay
headersDelayUnit = unit
}
fun getHeadersDelay(unit: TimeUnit): Long =
unit.convert(headersDelayAmount, headersDelayUnit)
/**
* When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this attaches a
* pushed stream to this response.
*/
fun withPush(promise: PushPromise) = apply {
promises.add(promise)
}
/**
* When [protocols][MockWebServer.protocols] include [HTTP_2][okhttp3.Protocol], this pushes
* [settings] before writing the response.
*/
fun withSettings(settings: Settings) = apply {
this.settings = settings
}
/**
* Attempts to perform a web socket upgrade on the connection.
* This will overwrite any previously set status or body.
*/
fun withWebSocketUpgrade(listener: WebSocketListener) = apply {
status = "HTTP/1.1 101 Switching Protocols"
setHeader("Connection", "Upgrade")
setHeader("Upgrade", "websocket")
body = null
webSocketListener = listener
}
override fun toString(): String = status
companion object {
private const val CHUNKED_BODY_HEADER = "Transfer-encoding: chunked"
}
}
| apache-2.0 | 86bb33c3a3467a40bbb6f76898497197 | 30.583569 | 99 | 0.693067 | 4.239163 | false | false | false | false |
androidx/androidx | compose/ui/ui-text/src/commonMain/kotlin/androidx/compose/ui/text/style/TextAlign.kt | 3 | 2598 | /*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.text.style
/**
* Defines how to align text horizontally. `TextAlign` controls how text aligns in the space it
* appears.
*/
@kotlin.jvm.JvmInline
value class TextAlign internal constructor(internal val value: Int) {
override fun toString(): String {
return when (this) {
Left -> "Left"
Right -> "Right"
Center -> "Center"
Justify -> "Justify"
Start -> "Start"
End -> "End"
else -> "Invalid"
}
}
companion object {
/** Align the text on the left edge of the container. */
val Left = TextAlign(1)
/** Align the text on the right edge of the container. */
val Right = TextAlign(2)
/** Align the text in the center of the container. */
val Center = TextAlign(3)
/**
* Stretch lines of text that end with a soft line break to fill the width of
* the container.
*
* Lines that end with hard line breaks are aligned towards the [Start] edge.
*/
val Justify = TextAlign(4)
/**
* Align the text on the leading edge of the container.
*
* For Left to Right text ([ResolvedTextDirection.Ltr]), this is the left edge.
*
* For Right to Left text ([ResolvedTextDirection.Rtl]), like Arabic, this is the right edge.
*/
val Start = TextAlign(5)
/**
* Align the text on the trailing edge of the container.
*
* For Left to Right text ([ResolvedTextDirection.Ltr]), this is the right edge.
*
* For Right to Left text ([ResolvedTextDirection.Rtl]), like Arabic, this is the left edge.
*/
val End = TextAlign(6)
/**
* Return a list containing all possible values of TextAlign.
*/
fun values(): List<TextAlign> = listOf(Left, Right, Center, Justify, Start, End)
}
}
| apache-2.0 | 286ab03669afc2dcc3f9b57374f16368 | 32.307692 | 101 | 0.606236 | 4.5026 | false | false | false | false |
dropbox/Store | filesystem/src/main/java/com/dropbox/android/external/fs3/FileSystemRecordPersister.kt | 1 | 1618 | package com.dropbox.android.external.fs3
import com.dropbox.android.external.fs3.filesystem.FileSystem
import okio.BufferedSource
import kotlin.time.Duration
import kotlin.time.ExperimentalTime
/**
* FileSystemRecordPersister is used when persisting to/from file system while being stale aware
* PathResolver will be used in creating file system paths based on cache keys.
* Make sure to have keys containing same data resolve to same "path"
*
* @param <Key> key type
</Key> */
@ExperimentalTime
class FileSystemRecordPersister<Key> private constructor(
private val fileSystem: FileSystem,
private val pathResolver: PathResolver<Key>,
private val expirationDuration: Duration
) : Persister<BufferedSource, Key>, RecordProvider<Key> {
private val fileReader: FSReader<Key> = FSReader(fileSystem, pathResolver)
private val fileWriter: FSWriter<Key> = FSWriter(fileSystem, pathResolver)
override fun getRecordState(key: Key): RecordState =
fileSystem.getRecordState(expirationDuration, pathResolver.resolve(key))
override suspend fun read(key: Key): BufferedSource? = fileReader.read(key)
override suspend fun write(key: Key, raw: BufferedSource): Boolean = fileWriter.write(key, raw)
companion object {
fun <T> create(
fileSystem: FileSystem,
pathResolver: PathResolver<T>,
expirationDuration: Duration
): FileSystemRecordPersister<T> = FileSystemRecordPersister(
fileSystem = fileSystem,
pathResolver = pathResolver,
expirationDuration = expirationDuration
)
}
}
| apache-2.0 | 601cfab5c2e542002851942da3209685 | 36.627907 | 99 | 0.732386 | 4.801187 | false | false | false | false |
ealva-com/ealvalog | ealvalog-java/src/main/java/com/ealva/ealvalog/java/NullJLogger.kt | 1 | 3540 | /*
* Copyright 2017 Eric A. Snell
*
* This file is part of eAlvaLog.
*
* 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.ealva.ealvalog.java
import com.ealva.ealvalog.LogEntry
import com.ealva.ealvalog.LogLevel
import com.ealva.ealvalog.LoggerFilter
import com.ealva.ealvalog.Marker
import com.ealva.ealvalog.MdcContext
import com.ealva.ealvalog.NullLogEntry
import com.ealva.ealvalog.filter.AlwaysNeutralFilter
import java.util.function.Supplier
/**
* Created by Eric A. Snell on 8/10/18.
*/
object NullJLogger : JLogger {
override var filter: LoggerFilter = AlwaysNeutralFilter
override fun isLoggable(level: LogLevel) = false
override fun isLoggable(level: LogLevel, marker: Marker): Boolean = false
override fun isLoggable(level: LogLevel, throwable: Throwable): Boolean = false
override fun log(level: LogLevel, msg: String) {}
override fun log(level: LogLevel, throwable: Throwable, msg: String) {}
override fun log(level: LogLevel, marker: Marker, format: String, vararg formatArgs: Any) {}
override fun caught(level: LogLevel, throwable: Throwable) {}
override val effectiveLogLevel = LogLevel.NONE
override var includeLocation = false
override fun shouldIncludeLocation(logLevel: LogLevel, marker: Marker?, throwable: Throwable?) =
false
override fun isLoggable(level: LogLevel, marker: Marker?, throwable: Throwable?) = false
override fun log(level: LogLevel, marker: Marker, msg: String) {}
override fun log(level: LogLevel, marker: Marker, throwable: Throwable, msg: String) {}
override fun log(level: LogLevel, throwable: Throwable, format: String, vararg formatArgs: Any) {}
override fun log(
level: LogLevel,
marker: Marker,
throwable: Throwable,
format: String,
vararg formatArgs: Any
) {
}
override fun log(level: LogLevel, format: String, arg1: Any) {}
override fun log(level: LogLevel, format: String, arg1: Any, arg2: Any) {}
override fun log(level: LogLevel, format: String, arg1: Any, arg2: Any, arg3: Any) {}
override fun log(level: LogLevel, format: String, arg1: Any, arg2: Any, arg3: Any, arg4: Any) {}
override fun log(
level: LogLevel,
format: String,
arg1: Any,
arg2: Any,
arg3: Any,
arg4: Any,
vararg remaining: Any
) {
}
override fun log(level: LogLevel, supplier: Supplier<*>) {}
override fun log(level: LogLevel, marker: Marker, supplier: Supplier<*>) {}
override fun log(level: LogLevel, throwable: Throwable, supplier: Supplier<*>) {}
override fun log(
level: LogLevel,
marker: Marker,
throwable: Throwable,
supplier: Supplier<*>
) {
}
override fun <T : Throwable> throwing(level: LogLevel, throwable: T) = throwable
override val name = "NullJLogger"
override var marker: Marker? = null
override var logLevel: LogLevel? = LogLevel.NONE
override fun getLogEntry(
logLevel: LogLevel,
marker: Marker?,
throwable: Throwable?,
mdcContext: MdcContext?
) = NullLogEntry
override fun logImmediate(entry: LogEntry) {}
} | apache-2.0 | 16dde3514c010b7daa5c81302676133e | 35.132653 | 100 | 0.721751 | 3.81877 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/timeline/meta/TimelineTitle.kt | 1 | 5863 | /*
* Copyright (c) 2016-2018 yvolk (Yuri Volkov), http://yurivolkov.com
*
* 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.andstatus.app.timeline.meta
import org.andstatus.app.MyActivity
import org.andstatus.app.R
import org.andstatus.app.account.MyAccount
import org.andstatus.app.context.MyContext
import org.andstatus.app.util.MyLog
import org.andstatus.app.util.MyStringBuilder
/**
* Data to show on UI. May be created on UI thread
* @author [email protected]
*/
class TimelineTitle private constructor(val title: String, val subTitle: String?, // Optional names
val accountName: String?, val originName: String?) {
enum class Destination {
TIMELINE_ACTIVITY, DEFAULT
}
fun updateActivityTitle(activity: MyActivity, additionalTitleText: String?) {
activity.setTitle(if (!additionalTitleText.isNullOrEmpty() && subTitle.isNullOrEmpty())
MyStringBuilder.of(title).withSpace(additionalTitleText) else title)
activity.setSubtitle(if (subTitle.isNullOrEmpty()) "" else MyStringBuilder.of(subTitle).withSpace(additionalTitleText))
MyLog.v(activity) { "Title: " + toString() }
}
override fun toString(): String {
return MyStringBuilder.of(title).withSpace(subTitle).toString()
}
companion object {
@JvmOverloads
fun from(myContext: MyContext, timeline: Timeline, accountToHide: MyAccount = MyAccount.EMPTY,
namesAreHidden: Boolean = true, destination: Destination = Destination.DEFAULT): TimelineTitle {
return TimelineTitle(
calcTitle(myContext, timeline, accountToHide, namesAreHidden, destination),
calcSubtitle(myContext, timeline, accountToHide, namesAreHidden, destination),
if (timeline.timelineType.isForUser() && timeline.myAccountToSync.isValid) timeline.myAccountToSync.toAccountButtonText() else "",
if (timeline.timelineType.isAtOrigin() && timeline.getOrigin().isValid) timeline.getOrigin().name else ""
)
}
private fun calcTitle(myContext: MyContext, timeline: Timeline, accountToHide: MyAccount,
namesAreHidden: Boolean, destination: Destination): String {
if (timeline.isEmpty && destination == Destination.TIMELINE_ACTIVITY) {
return "AndStatus"
}
val title = MyStringBuilder()
if (showActor(timeline, accountToHide, namesAreHidden)) {
if (isActorMayBeShownInSubtitle(timeline)) {
title.withSpace(timeline.timelineType.title(myContext.context))
} else {
title.withSpace(
timeline.timelineType.title(myContext.context, getActorName(timeline)))
}
} else {
title.withSpace(timeline.timelineType.title(myContext.context))
if (showOrigin(timeline, namesAreHidden)) {
title.withSpaceQuoted(timeline.getSearchQuery())
}
}
return title.toString()
}
private fun isActorMayBeShownInSubtitle(timeline: Timeline): Boolean {
return !timeline.hasSearchQuery() && timeline.timelineType.titleResWithParamsId == 0
}
private fun calcSubtitle(myContext: MyContext, timeline: Timeline, accountToHide: MyAccount,
namesAreHidden: Boolean, destination: Destination): String {
if (timeline.isEmpty && destination == Destination.TIMELINE_ACTIVITY) {
return ""
}
val title = MyStringBuilder()
if (showActor(timeline, accountToHide, namesAreHidden)) {
if (isActorMayBeShownInSubtitle(timeline)) {
title.withSpace(getActorName(timeline))
}
} else if (showOrigin(timeline, namesAreHidden)) {
title.withSpace(timeline.timelineType.scope.timelinePreposition(myContext))
title.withSpace(timeline.getOrigin().name)
}
if (!showOrigin(timeline, namesAreHidden)) {
title.withSpaceQuoted(timeline.getSearchQuery())
}
if (timeline.isCombined) {
title.withSpace(if (myContext.isEmpty) "combined" else myContext.context.getText(R.string.combined_timeline_on))
}
return title.toString()
}
private fun getActorName(timeline: Timeline): String {
return if (timeline.isSyncedByOtherUser()) timeline.actor.actorNameInTimeline
else timeline.myAccountToSync.toAccountButtonText()
}
private fun showActor(timeline: Timeline, accountToHide: MyAccount, namesAreHidden: Boolean): Boolean {
return (timeline.timelineType.isForUser()
&& !timeline.isCombined && timeline.actor.nonEmpty
&& timeline.actor.notSameUser(accountToHide.actor)
&& (timeline.actor.user.isMyUser.untrue || namesAreHidden))
}
private fun showOrigin(timeline: Timeline, namesAreHidden: Boolean): Boolean {
return timeline.timelineType.isAtOrigin() && !timeline.isCombined && namesAreHidden
}
}
}
| apache-2.0 | 0d5ab7819e1202ff15837a6fe20e9cc7 | 46.666667 | 150 | 0.642163 | 4.951858 | false | false | false | false |
hpedrorodrigues/GZMD | app/src/main/kotlin/com/hpedrorodrigues/gzmd/util/GizmodoMail.kt | 1 | 2618 | /*
* Copyright 2016 Pedro Rodrigues
*
* 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.hpedrorodrigues.gzmd.util
import android.app.Activity
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import com.hpedrorodrigues.gzmd.R
import com.hpedrorodrigues.gzmd.constant.GizmodoConstant
object GizmodoMail {
fun sendImproveAppEmail(activity: Activity) = send(activity, R.string.suggestions)
fun sendReportBugEmail(activity: Activity) = send(activity, R.string.new_bug)
fun sendFeedbackEmail(activity: Activity) = send(activity, R.string.feedback)
fun sendContactUsEmail(activity: Activity) = send(activity, R.string.contact)
private fun send(activity: Activity, resSubjectId: Int) {
try {
val intent = buildEmailIntent(activity, resSubjectId)
intent.setClassName(GizmodoConstant.GMAIL_PACKAGE_NAME, GizmodoConstant.GMAIL_CLASS_NAME)
activity.startActivity(intent)
} catch (e: ActivityNotFoundException) {
val intent = buildEmailIntent(activity, resSubjectId)
if (isIntentAvailable(activity, intent)) {
activity.startActivity(Intent.createChooser(intent, activity.getString(R.string.choose_app)))
}
}
}
private fun buildEmailIntent(activity: Activity, resSubjectId: Int): Intent {
val intent = Intent(Intent.ACTION_SEND)
intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(GizmodoConstant.EMAIL))
val subject = "${GizmodoConstant.DEFAULT_SUBJECT} ${activity.getString(resSubjectId)}"
intent.putExtra(Intent.EXTRA_SUBJECT, subject)
intent.putExtra(Intent.EXTRA_TEXT, DeviceInfo.DETAILS)
intent.type = GizmodoConstant.DEFAULT_EMAIL_TYPE
return intent
}
private fun isIntentAvailable(activity: Activity, intent: Intent): Boolean {
val packageManager = activity.packageManager
val list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY)
return list.size > 0
}
} | apache-2.0 | f38db03f9e0ec22f8b4b2d9ceeed9fe3 | 35.887324 | 109 | 0.724599 | 4.305921 | false | false | false | false |
jeffgbutler/mybatis-dynamic-sql | src/main/kotlin/org/mybatis/dynamic/sql/util/kotlin/JoinCollector.kt | 1 | 2120 | /*
* Copyright 2016-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.mybatis.dynamic.sql.util.kotlin
import org.mybatis.dynamic.sql.BasicColumn
import org.mybatis.dynamic.sql.SqlBuilder
import org.mybatis.dynamic.sql.select.join.JoinCondition
import org.mybatis.dynamic.sql.select.join.JoinCriterion
import org.mybatis.dynamic.sql.util.Messages
typealias JoinReceiver = JoinCollector.() -> Unit
@MyBatisDslMarker
class JoinCollector {
private var onJoinCriterion: JoinCriterion? = null
internal val andJoinCriteria = mutableListOf<JoinCriterion>()
internal fun onJoinCriterion() : JoinCriterion =
onJoinCriterion?: throw KInvalidSQLException(Messages.getString("ERROR.22")) //$NON-NLS-1$
fun on(leftColumn: BasicColumn): RightColumnCollector = RightColumnCollector {
onJoinCriterion = JoinCriterion.Builder()
.withConnector("on") //$NON-NLS-1$
.withJoinColumn(leftColumn)
.withJoinCondition(it)
.build()
}
fun and(leftColumn: BasicColumn): RightColumnCollector = RightColumnCollector {
andJoinCriteria.add(
JoinCriterion.Builder()
.withConnector("and") //$NON-NLS-1$
.withJoinColumn(leftColumn)
.withJoinCondition(it)
.build()
)
}
}
class RightColumnCollector(private val joinConditionConsumer: (JoinCondition) -> Unit) {
infix fun equalTo(rightColumn: BasicColumn) = joinConditionConsumer.invoke(SqlBuilder.equalTo(rightColumn))
}
| apache-2.0 | ace0f3c667c9cabc685b8088ab0c8e61 | 37.545455 | 111 | 0.704717 | 4.231537 | false | false | false | false |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/ui/dialogs/VideoQualityDetailedDialog.kt | 2 | 4520 | package org.stepic.droid.ui.dialogs
import android.app.Activity
import android.app.Dialog
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ArrayAdapter
import android.widget.CheckBox
import android.widget.ListView
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.concurrency.MainHandler
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.preferences.UserPreferences
import org.stepik.android.model.Course
import org.stepik.android.model.Section
import org.stepik.android.model.Unit
import java.util.concurrent.ThreadPoolExecutor
import javax.inject.Inject
class VideoQualityDetailedDialog : VideoQualityDialogBase() {
companion object {
const val TAG = "VideoQualityDetailedDialog"
const val VIDEO_QUALITY_REQUEST_CODE = 9048
const val UNIT_KEY = "unit"
const val SECTION_KEY = "section"
const val COURSE_KEY = "course"
const val VIDEO_QUALITY = "video_quality"
fun newInstance(course: Course? = null, section: Section? = null, unit: Unit? = null): VideoQualityDetailedDialog {
val dialog = VideoQualityDetailedDialog()
dialog.arguments = Bundle(1)
.apply {
course?.let { putParcelable(COURSE_KEY, it) }
section?.let { putParcelable(SECTION_KEY, it) }
unit?.let { putParcelable(UNIT_KEY, it) }
}
return dialog
}
}
@Inject
lateinit var analytic: Analytic
@Inject
lateinit var userPreferences: UserPreferences
@Inject
lateinit var threadPoolExecutor: ThreadPoolExecutor
@Inject
lateinit var mainHandler: MainHandler
@Inject
lateinit var sharedPreferencesHelper: SharedPreferenceHelper
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
init()
val explanationView = View.inflate(context, R.layout.dialog_video_quality_detailed, null)
val checkbox = explanationView.findViewById<CheckBox>(R.id.video_quality_do_not_ask_checkbox)
val selectionItems = explanationView.findViewById<ListView>(R.id.video_quality_list_choices)
var chosenOptionPosition = qualityToPositionMap[userPreferences.qualityVideo]!!
selectionItems.adapter = ArrayAdapter(requireContext(), com.google.android.material.R.layout.mtrl_alert_select_dialog_singlechoice, resources.getStringArray(R.array.video_quality))
selectionItems.choiceMode = ListView.CHOICE_MODE_SINGLE
selectionItems.setItemChecked(chosenOptionPosition, true)
selectionItems.setOnItemClickListener { _, _, position, _ ->
chosenOptionPosition = position
}
val builder = MaterialAlertDialogBuilder(requireContext())
builder
.setTitle(R.string.video_quality)
.setView(explanationView)
.setNegativeButton(R.string.cancel) { _, _ ->
analytic.reportEvent(Analytic.Interaction.CANCEL_VIDEO_QUALITY_DETAILED)
}
.setPositiveButton(R.string.ok) { _, _ ->
val qualityString = positionToQualityMap[chosenOptionPosition]
analytic.reportEventWithIdName(Analytic.Preferences.VIDEO_QUALITY, chosenOptionPosition.toString(), qualityString)
threadPoolExecutor.execute {
userPreferences.storeQualityVideo(qualityString)
mainHandler.post {
val args = arguments
?: return@post
targetFragment
?.onActivityResult(
VIDEO_QUALITY_REQUEST_CODE,
Activity.RESULT_OK,
Intent()
.putExtras(args)
.putExtra(VIDEO_QUALITY, qualityString)
)
}
}
val isNeedExplanation = !checkbox.isChecked
threadPoolExecutor.execute {
sharedPreferencesHelper.isNeedToShowVideoQualityExplanation = isNeedExplanation
}
}
return builder.create()
}
override fun injectDependencies() {
App.component().inject(this)
}
}
| apache-2.0 | 4a984ce8bc1082da19192c0c7b927664 | 37.965517 | 188 | 0.644248 | 5.2194 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/descriptors/DeepPrintVisitor.kt | 1 | 3749 | /*
* 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.descriptors
import org.jetbrains.kotlin.backend.konan.llvm.*
import org.jetbrains.kotlin.backend.konan.util.nTabs
import org.jetbrains.kotlin.renderer.*
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
public class DeepPrintVisitor(worker: DeclarationDescriptorVisitor<Boolean, Int>): DeepVisitor< Int>(worker) {
override public fun visitChildren(descriptor: DeclarationDescriptor?, data: Int): Boolean {
return super.visitChildren(descriptor, data+1)
}
override public fun visitChildren(descriptors: Collection<DeclarationDescriptor>, data: Int): Boolean {
return super.visitChildren(descriptors, data+1)
}
}
public class PrintVisitor: DeclarationDescriptorVisitor<Boolean, Int> {
fun printDescriptor(descriptor: DeclarationDescriptor, amount: Int): Boolean {
println("${nTabs(amount)} ${descriptor.toString()}")
return true;
}
override fun visitPackageFragmentDescriptor(descriptor: PackageFragmentDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitPackageViewDescriptor(descriptor: PackageViewDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitVariableDescriptor(descriptor: VariableDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitFunctionDescriptor(descriptor: FunctionDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitTypeParameterDescriptor(descriptor: TypeParameterDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitClassDescriptor(descriptor: ClassDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitTypeAliasDescriptor(descriptor: TypeAliasDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitModuleDeclaration(descriptor: ModuleDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitConstructorDescriptor(descriptor: ConstructorDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitScriptDescriptor(descriptor: ScriptDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitPropertyDescriptor(descriptor: PropertyDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitValueParameterDescriptor(descriptor: ValueParameterDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitPropertyGetterDescriptor(descriptor: PropertyGetterDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitPropertySetterDescriptor(descriptor: PropertySetterDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
override fun visitReceiverParameterDescriptor(descriptor: ReceiverParameterDescriptor, data: Int): Boolean
= printDescriptor(descriptor, data)
}
| apache-2.0 | b3e7dce9c83df3170cc3bd1c4347e63d | 40.655556 | 110 | 0.763137 | 5.163912 | false | false | false | false |
jiaminglu/kotlin-native | backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/llvm/LlvmUtils.kt | 1 | 9129 | /*
* 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.llvm
import kotlinx.cinterop.*
import llvm.*
internal val LLVMValueRef.type: LLVMTypeRef
get() = LLVMTypeOf(this)!!
/**
* Represents the value which can be emitted as bitcode const value
*/
internal interface ConstValue {
val llvm: LLVMValueRef
}
internal val ConstValue.llvmType: LLVMTypeRef
get() = this.llvm.type
internal interface ConstPointer : ConstValue {
fun getElementPtr(index: Int): ConstPointer = ConstGetElementPtr(this, index)
}
internal fun constPointer(value: LLVMValueRef) = object : ConstPointer {
init {
assert (LLVMIsConstant(value) == 1)
}
override val llvm = value
}
private class ConstGetElementPtr(val pointer: ConstPointer, val index: Int) : ConstPointer {
override val llvm = LLVMConstInBoundsGEP(pointer.llvm, cValuesOf(Int32(0).llvm, Int32(index).llvm), 2)!!
// TODO: squash multiple GEPs
}
internal fun ConstPointer.bitcast(toType: LLVMTypeRef) = constPointer(LLVMConstBitCast(this.llvm, toType)!!)
internal class ConstArray(val elemType: LLVMTypeRef?, val elements: List<ConstValue>) : ConstValue {
override val llvm = LLVMConstArray(elemType, elements.map { it.llvm }.toCValues(), elements.size)!!
}
internal open class Struct(val type: LLVMTypeRef?, val elements: List<ConstValue>) : ConstValue {
constructor(type: LLVMTypeRef?, vararg elements: ConstValue) : this(type, elements.toList())
constructor(vararg elements: ConstValue) : this(structType(elements.map { it.llvmType }), *elements)
override val llvm = LLVMConstNamedStruct(type, elements.map { it.llvm }.toCValues(), elements.size)!!
}
internal class Int1(val value: Byte) : ConstValue {
override val llvm = LLVMConstInt(LLVMInt1Type(), value.toLong(), 1)!!
}
internal class Int8(val value: Byte) : ConstValue {
override val llvm = LLVMConstInt(LLVMInt8Type(), value.toLong(), 1)!!
}
internal class Char16(val value: Char) : ConstValue {
override val llvm = LLVMConstInt(LLVMInt16Type(), value.toLong(), 1)!!
}
internal class Int32(val value: Int) : ConstValue {
override val llvm = LLVMConstInt(LLVMInt32Type(), value.toLong(), 1)!!
}
internal class Int64(val value: Long) : ConstValue {
override val llvm = LLVMConstInt(LLVMInt64Type(), value, 1)!!
}
internal class Zero(val type: LLVMTypeRef) : ConstValue {
override val llvm = LLVMConstNull(type)!!
}
internal class NullPointer(val pointeeType: LLVMTypeRef): ConstPointer {
override val llvm = LLVMConstNull(pointerType(pointeeType))!!
}
internal fun constValue(value: LLVMValueRef) = object : ConstValue {
init {
assert (LLVMIsConstant(value) == 1)
}
override val llvm = value
}
internal val int1Type = LLVMInt1Type()!!
internal val int8Type = LLVMInt8Type()!!
internal val int32Type = LLVMInt32Type()!!
internal val int8TypePtr = pointerType(int8Type)
internal val voidType = LLVMVoidType()!!
internal val RuntimeAware.kTypeInfo: LLVMTypeRef
get() = runtime.typeInfoType
internal val RuntimeAware.kObjHeader: LLVMTypeRef
get() = runtime.objHeaderType
internal val RuntimeAware.kObjHeaderPtr: LLVMTypeRef
get() = pointerType(kObjHeader)
internal val RuntimeAware.kObjHeaderPtrPtr: LLVMTypeRef
get() = pointerType(kObjHeaderPtr)
internal val RuntimeAware.kArrayHeader: LLVMTypeRef
get() = runtime.arrayHeaderType
internal val RuntimeAware.kArrayHeaderPtr: LLVMTypeRef
get() = pointerType(kArrayHeader)
internal val RuntimeAware.kTypeInfoPtr: LLVMTypeRef
get() = pointerType(kTypeInfo)
internal val kInt1 = LLVMInt1Type()!!
internal val kBoolean = kInt1
internal val kInt64 = LLVMInt64Type()!!
internal val kInt8Ptr = pointerType(int8Type)
internal val kInt8PtrPtr = pointerType(kInt8Ptr)
internal val kNullInt8Ptr = LLVMConstNull(kInt8Ptr)!!
internal val kImmInt32One = Int32(1).llvm
internal val kImmInt64One = Int64(1).llvm
internal val ContextUtils.kNullObjHeaderPtr: LLVMValueRef
get() = LLVMConstNull(this.kObjHeaderPtr)!!
internal val ContextUtils.kNullObjHeaderPtrPtr: LLVMValueRef
get() = LLVMConstNull(this.kObjHeaderPtrPtr)!!
// Nothing type has no values, but we do generate unreachable code and thus need some fake value:
internal val ContextUtils.kNothingFakeValue: LLVMValueRef
get() = LLVMGetUndef(kObjHeaderPtr)!!
internal fun pointerType(pointeeType: LLVMTypeRef) = LLVMPointerType(pointeeType, 0)!!
internal fun structType(vararg types: LLVMTypeRef): LLVMTypeRef = structType(types.toList())
internal fun structType(types: List<LLVMTypeRef>): LLVMTypeRef =
LLVMStructType(types.toCValues(), types.size, 0)!!
internal fun ContextUtils.numParameters(functionType: LLVMTypeRef) : Int {
// Note that type is usually function pointer, so we have to dereference it.
return LLVMCountParamTypes(LLVMGetElementType(functionType))
}
internal fun ContextUtils.isObjectReturn(functionType: LLVMTypeRef) : Boolean {
// Note that type is usually function pointer, so we have to dereference it.
val returnType = LLVMGetReturnType(LLVMGetElementType(functionType))!!
return isObjectType(returnType)
}
internal fun ContextUtils.isObjectRef(value: LLVMValueRef): Boolean {
return isObjectType(value.type)
}
internal fun RuntimeAware.isObjectType(type: LLVMTypeRef): Boolean {
return type == kObjHeaderPtr || type == kArrayHeaderPtr
}
/**
* Reads [size] bytes contained in this array.
*/
internal fun CArrayPointer<ByteVar>.getBytes(size: Long) =
(0 .. size-1).map { this[it] }.toByteArray()
internal fun getFunctionType(ptrToFunction: LLVMValueRef): LLVMTypeRef {
return getGlobalType(ptrToFunction)
}
internal fun getGlobalType(ptrToGlobal: LLVMValueRef): LLVMTypeRef {
return LLVMGetElementType(ptrToGlobal.type)!!
}
internal fun ContextUtils.addGlobal(name: String, type: LLVMTypeRef, isExported: Boolean,
threadLocal: Boolean = false): LLVMValueRef {
if (isExported)
assert(LLVMGetNamedGlobal(context.llvmModule, name) == null)
val result = LLVMAddGlobal(context.llvmModule, type, name)!!
if (threadLocal)
LLVMSetThreadLocalMode(result, runtime.tlsMode)
return result
}
internal fun ContextUtils.importGlobal(name: String, type: LLVMTypeRef,
threadLocal: Boolean = false): LLVMValueRef {
val found = LLVMGetNamedGlobal(context.llvmModule, name)
if (found != null) {
assert (getGlobalType(found) == type)
assert (LLVMGetInitializer(found) == null)
if (threadLocal)
assert(LLVMGetThreadLocalMode(found) == runtime.tlsMode)
return found
} else {
val result = LLVMAddGlobal(context.llvmModule, type, name)!!
if (threadLocal)
LLVMSetThreadLocalMode(result, runtime.tlsMode)
return result
}
}
internal fun functionType(returnType: LLVMTypeRef, isVarArg: Boolean = false, vararg paramTypes: LLVMTypeRef) =
LLVMFunctionType(
returnType,
cValuesOf(*paramTypes), paramTypes.size,
if (isVarArg) 1 else 0
)!!
fun llvm2string(value: LLVMValueRef?): String {
if (value == null) return "<null>"
return LLVMPrintValueToString(value)!!.toKString()
}
fun llvmtype2string(type: LLVMTypeRef?): String {
if (type == null) return "<null type>"
return LLVMPrintTypeToString(type)!!.toKString()
}
fun getStructElements(type: LLVMTypeRef): List<LLVMTypeRef> {
val count = LLVMCountStructElementTypes(type)
return (0 until count).map {
LLVMStructGetTypeAtIndex(type, it)!!
}
}
fun parseBitcodeFile(path: String): LLVMModuleRef = memScoped {
val bufRef = alloc<LLVMMemoryBufferRefVar>()
val errorRef = allocPointerTo<ByteVar>()
val res = LLVMCreateMemoryBufferWithContentsOfFile(path, bufRef.ptr, errorRef.ptr)
if (res != 0) {
throw Error(errorRef.value?.toKString())
}
val memoryBuffer = bufRef.value
try {
val moduleRef = alloc<LLVMModuleRefVar>()
val parseRes = LLVMParseBitcode2(memoryBuffer, moduleRef.ptr)
if (parseRes != 0) {
throw Error(parseRes.toString())
}
moduleRef.value!!
} finally {
LLVMDisposeMemoryBuffer(memoryBuffer)
}
}
internal fun String.mdString() = LLVMMDString(this, this.length)!!
internal fun node(vararg it:LLVMValueRef) = LLVMMDNode(it.toList().toCValues(), it.size)
internal fun LLVMValueRef.setUnaligned() = apply { LLVMSetAlignment(this, 1) }
| apache-2.0 | e1f40d97fba1473b7b26bd2895162abc | 33.711027 | 111 | 0.721328 | 4.079088 | false | false | false | false |
schneppd/lab.schneppd.android2017.opengl2 | MyApplication/app/src/main/java/com/schneppd/myopenglapp/OpenGl2v3/CustomGLRenderer.kt | 1 | 11323 | package com.schneppd.myopenglapp.OpenGl2v3
import android.opengl.GLES20
import android.opengl.GLSurfaceView
import android.opengl.Matrix
import android.os.SystemClock
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer
import javax.microedition.khronos.egl.EGLConfig
import javax.microedition.khronos.opengles.GL10
/**
* Created by schneppd on 7/11/17.
*/
class CustomGLRenderer : GLSurfaceView.Renderer{
companion object Static {
val platformBytesPerFloat = 4
val strideBytes = platformBytesPerFloat * 7
val positionDataSize = 3
val colorDataSize = 4
val normalDataSize = 3
val vertexShaderCode:String = """
uniform mat4 u_MVPMatrix;
uniform mat4 u_MVMatrix;
uniform vec3 u_LightPos;
attribute vec4 a_Position;
attribute vec4 a_Color;
attribute vec3 a_Normal;
varying vec4 v_Color;
void main() {
vec3 modelViewVertex = vec3(u_MVMatrix * a_Position);
vec3 modelViewNormal = vec3(u_MVMatrix * vec4(a_Normal, 0.0));
float distance = length(u_LightPos - modelViewVertex);
vec3 lightVector = normalize(u_LightPos - modelViewVertex);
float diffuse = max(dot(modelViewNormal, lightVector), 0.1);
diffuse = diffuse * (1.0 / (1.0 + (0.25 * distance * distance)));
v_Color = a_Color * diffuse;
gl_Position = u_MVPMatrix * a_Position;
}
"""
val fragmentShaderCode:String = """
precision mediump float;
varying vec4 v_Color;
void main() {
gl_FragColor = v_Color;
}
"""
val pointVertexShaderCode:String = """
uniform mat4 u_MVPMatrix;
attribute vec4 a_Position;
void main() {
gl_Position = u_MVPMatrix * a_Position;
gl_PointSize = 5.0;
}
"""
val pointFragmentShaderCode:String = """
precision mediump float;
void main() {
gl_FragColor = vec4(1.0, 1.0, 1.0, 1.0);
}
"""
}
//matricies
var modelMatrix = FloatArray(16)
var viewMatrix = FloatArray(16)
var projectionMatrix = FloatArray(16)
var shaderMatrix = FloatArray(16)
var lightMatrix = FloatArray(16)
//element to draw
lateinit var cubePositions: FloatBuffer
lateinit var cubeColors: FloatBuffer
lateinit var cubeNormals: FloatBuffer
//GL handles
var mVPMatrixHandle = 0
var mVMatrixHandle = 0
var lightHandle = 0
var positionHandle = 0
var colorHandle = 0
var normalHandle = 0
//light data
val lightPosInModelSpace = floatArrayOf(0.0f, 0.0f, 0.0f, 1.0f)
var lightPosInWorldSpace = FloatArray(4)
var lightPosInEyeSpace = FloatArray(4)
//program handle
var perVertexProgramHandle = 0
var pointProgramHandle = 0
init{
val cubePositionData = floatArrayOf(
// Front face
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
// Right face
1.0f, 1.0f, 1.0f,
1.0f, -1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
1.0f, -1.0f, -1.0f,
1.0f, 1.0f, -1.0f,
// Back face
1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, -1.0f,
// Left face
-1.0f, 1.0f, -1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, 1.0f, 1.0f,
// Top face
-1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
-1.0f, 1.0f, 1.0f,
1.0f, 1.0f, 1.0f,
1.0f, 1.0f, -1.0f,
// Bottom face
1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f,
1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, 1.0f,
-1.0f, -1.0f, -1.0f
)
val cubeColorData = floatArrayOf(
// Front face (red)
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
1.0f, 0.0f, 0.0f, 1.0f,
// Right face (green)
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
0.0f, 1.0f, 0.0f, 1.0f,
// Back face (blue)
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
0.0f, 0.0f, 1.0f, 1.0f,
// Left face (yellow)
1.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f, 1.0f,
1.0f, 1.0f, 0.0f, 1.0f,
// Top face (cyan)
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
0.0f, 1.0f, 1.0f, 1.0f,
// Bottom face (magenta)
1.0f, 0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f, 1.0f,
1.0f, 0.0f, 1.0f, 1.0f
)
val cubeNormalData = floatArrayOf(
// Front face
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
0.0f, 0.0f, 1.0f,
// Right face
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
1.0f, 0.0f, 0.0f,
// Back face
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
0.0f, 0.0f, -1.0f,
// Left face
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
-1.0f, 0.0f, 0.0f,
// Top face
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
0.0f, 1.0f, 0.0f,
// Bottom face
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f,
0.0f, -1.0f, 0.0f
)
cubePositions = initBuffer(cubePositionData)
cubeColors = initBuffer(cubeColorData)
cubeNormals = initBuffer(cubeNormalData)
}
protected fun initBuffer(verticesData:FloatArray): FloatBuffer {
val buffer = ByteBuffer.allocateDirect(verticesData.size * platformBytesPerFloat).order(ByteOrder.nativeOrder()).asFloatBuffer()
buffer.put(verticesData).position(0)
return buffer
}
override fun onSurfaceCreated(p0: GL10, p1: EGLConfig?) {
GLES20.glClearColor(0.0f, 0.0f, 0.0f, 0.0f)
GLES20.glEnable(GLES20.GL_CULL_FACE)
GLES20.glEnable(GLES20.GL_DEPTH_TEST)
val eyeX = 0.0f
val eyeY = 0.0f
val eyeZ = -0.5f
val lookX = 0.0f
val lookY = 0.0f
val lookZ = -5.0f
val upX = 0.0f
val upY = 1.0f
val upZ = 0.0f
Matrix.setLookAtM(viewMatrix, 0, eyeX, eyeY, eyeZ, lookX, lookY, lookZ, upX, upY, upZ)
val vertexShaderHandle = createShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode)
val fragmentShaderHandle = createShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode)
perVertexProgramHandle = createGlProgram(vertexShaderHandle, fragmentShaderHandle, arrayOf("a_Position", "a_Color", "a_Normal"))
val pointVertexShaderHandle = createShader(GLES20.GL_VERTEX_SHADER, pointVertexShaderCode)
val pointFragmentShaderHandle = createShader(GLES20.GL_FRAGMENT_SHADER, pointFragmentShaderCode)
pointProgramHandle = createGlProgram(pointVertexShaderHandle, pointFragmentShaderHandle, arrayOf("a_Position"))
}
fun createShader(typeShade:Int, code:String) : Int{
var shaderHandle = GLES20.glCreateShader(typeShade)
if(shaderHandle != 0){
GLES20.glShaderSource(shaderHandle, code)
GLES20.glCompileShader(shaderHandle)
var compileStatus:IntArray = IntArray(1)
GLES20.glGetShaderiv(shaderHandle, GLES20.GL_COMPILE_STATUS, compileStatus, 0)
if(compileStatus[0] == 0){
GLES20.glDeleteShader(shaderHandle)
shaderHandle = 0
}
}
if (shaderHandle == 0)
throw RuntimeException("Error creating shader.")
return shaderHandle
}
fun createGlProgram(vertexShaderHandle:Int, fragmentShaderHandle:Int, bindAttributes:Array<String>) : Int{
var programHandle = GLES20.glCreateProgram()
if (programHandle != 0){
GLES20.glAttachShader(programHandle, vertexShaderHandle)
GLES20.glAttachShader(programHandle, fragmentShaderHandle)
for(attribute in bindAttributes.withIndex()){
GLES20.glBindAttribLocation(programHandle, attribute.index, attribute.value)
}
GLES20.glBindAttribLocation(programHandle, 0, "a_Position")
GLES20.glBindAttribLocation(programHandle, 1, "a_Color")
GLES20.glLinkProgram(programHandle)
var linkStatus:IntArray = IntArray(1)
GLES20.glGetProgramiv(programHandle, GLES20.GL_LINK_STATUS, linkStatus, 0)
if (linkStatus[0] == 0){
GLES20.glDeleteProgram(programHandle)
programHandle = 0
}
}
if (programHandle == 0)
throw RuntimeException("Error creating program.")
return programHandle
}
override fun onDrawFrame(p0: GL10) {
GLES20.glClear(GLES20.GL_DEPTH_BUFFER_BIT or GLES20.GL_COLOR_BUFFER_BIT)
val time = SystemClock.uptimeMillis() % 10000L
val angleInDegrees = 360.0f / 10000.0f * time.toInt()
// Draw the triangle facing straight on.
Matrix.setIdentityM(modelMatrix, 0)
Matrix.rotateM(modelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f)
drawTriangle(triangle1Verticies)
// Draw one translated a bit down and rotated to be flat on the ground.
Matrix.setIdentityM(modelMatrix, 0)
Matrix.translateM(modelMatrix, 0, 0.0f, -1.0f, 0.0f)
Matrix.rotateM(modelMatrix, 0, 90.0f, 1.0f, 0.0f, 0.0f)
Matrix.rotateM(modelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f)
drawTriangle(triangle1Verticies)
// Draw one translated a bit to the right and rotated to be facing to the left.
Matrix.setIdentityM(modelMatrix, 0)
Matrix.translateM(modelMatrix, 0, 1.0f, 0.0f, 0.0f)
Matrix.rotateM(modelMatrix, 0, 90.0f, 0.0f, 1.0f, 0.0f)
Matrix.rotateM(modelMatrix, 0, angleInDegrees, 0.0f, 0.0f, 1.0f)
drawTriangle(triangle1Verticies)
}
override fun onSurfaceChanged(p0: GL10, width: Int, height: Int) {
GLES20.glViewport(0, 0, width, height)
val ratio = width.toFloat() / height.toFloat()
val left = -ratio
val right = ratio
val bottom = -1.0f
val top = 1.0f
val near = 1.0f
val far = 10.0f
Matrix.frustumM(projectionMatrix, 0, left, right, bottom, top, near, far)
}
private fun drawTriangle(triangle: FloatBuffer){
triangle.position(positionOffset)
GLES20.glVertexAttribPointer(positionHandle, positionDataSize, GLES20.GL_FLOAT, false, strideBytes, triangle)
GLES20.glEnableVertexAttribArray(positionHandle)
// Pass in the color information
triangle.position(colorOffset)
GLES20.glVertexAttribPointer(colorHandle, colorDataSize, GLES20.GL_FLOAT, false,
strideBytes, triangle)
GLES20.glEnableVertexAttribArray(colorHandle)
// This multiplies the view matrix by the model matrix, and stores the result in the MVP matrix
// (which currently contains model * view).
Matrix.multiplyMM(shaderMatrix, 0, viewMatrix, 0, modelMatrix, 0)
// This multiplies the modelview matrix by the projection matrix, and stores the result in the MVP matrix
// (which now contains model * view * projection).
Matrix.multiplyMM(shaderMatrix, 0, projectionMatrix, 0, shaderMatrix, 0)
GLES20.glUniformMatrix4fv(shaderHandle, 1, false, shaderMatrix, 0)
GLES20.glDrawArrays(GLES20.GL_TRIANGLES, 0, 3)
}
} | gpl-3.0 | a97356469dce0b0b6c1063f37917fe43 | 26.754902 | 131 | 0.639142 | 2.426184 | false | false | false | false |
Heiner1/AndroidAPS | app/src/main/java/info/nightscout/androidaps/utils/ActivityMonitor.kt | 1 | 5429 | package info.nightscout.androidaps.utils
import android.app.Activity
import android.app.Application
import android.content.Context
import android.graphics.Typeface
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import android.widget.TableLayout
import android.widget.TableRow
import android.widget.TextView
import info.nightscout.androidaps.R
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.SafeParse
import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ActivityMonitor @Inject constructor(
private var aapsLogger: AAPSLogger,
private val rh: ResourceHelper,
private val sp: SP,
private val dateUtil: DateUtil
) : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity) {
val name = activity.javaClass.simpleName
val resumed = sp.getLong("Monitor_" + name + "_" + "resumed", 0)
if (resumed == 0L) {
aapsLogger.debug(LTag.UI, "onActivityPaused: $name resumed == 0")
return
}
val elapsed = dateUtil.now() - resumed
val total = sp.getLong("Monitor_" + name + "_total", 0)
if (total == 0L) {
sp.putLong("Monitor_" + name + "_start", dateUtil.now())
}
sp.putLong("Monitor_" + name + "_total", total + elapsed)
aapsLogger.debug(LTag.UI, "onActivityPaused: $name elapsed=$elapsed total=${total + elapsed}")
}
override fun onActivityResumed(activity: Activity) {
val name = activity.javaClass.simpleName
aapsLogger.debug(LTag.UI, "onActivityResumed: $name")
sp.putLong("Monitor_" + name + "_" + "resumed", dateUtil.now())
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityDestroyed(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
}
fun stats(context: Context): TableLayout =
TableLayout(context).also { layout ->
layout.layoutParams = TableLayout.LayoutParams(0, ViewGroup.LayoutParams.WRAP_CONTENT, 1f)
layout.addView(
TextView(context).apply {
text = rh.gs(R.string.activitymonitor)
setTypeface(typeface, Typeface.BOLD)
gravity = Gravity.CENTER_HORIZONTAL
setTextAppearance(android.R.style.TextAppearance_Material_Medium)
})
layout.addView(
TableRow(context).also { row ->
val lp = TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT).apply { weight = 1f }
row.layoutParams = TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)
row.gravity = Gravity.CENTER_HORIZONTAL
row.addView(TextView(context).apply { layoutParams = lp.apply { column = 0 }; text = rh.gs(R.string.activity) })
row.addView(TextView(context).apply { layoutParams = lp.apply { column = 1 }; text = rh.gs(R.string.duration) })
row.addView(TextView(context).apply { layoutParams = lp.apply { column = 2 } })
}
)
val keys: Map<String, *> = sp.getAll()
for ((key, value) in keys)
if (key.startsWith("Monitor") && key.endsWith("total")) {
val v = if (value is Long) value else SafeParse.stringToLong(value as String)
val activity = key.split("_")[1].replace("Activity", "")
val duration = dateUtil.niceTimeScalar(v, rh)
val start = sp.getLong(key.replace("total", "start"), 0)
val days = T.msecs(dateUtil.now() - start).days()
layout.addView(
TableRow(context).also { row ->
val lp = TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT).apply { weight = 1f }
row.layoutParams = TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)
row.gravity = Gravity.CENTER_HORIZONTAL
row.addView(TextView(context).apply { layoutParams = lp.apply { column = 0 }; text = activity })
row.addView(TextView(context).apply { layoutParams = lp.apply { column = 1 }; text = duration })
row.addView(TextView(context).apply { layoutParams = lp.apply { column = 2 }; text = rh.gs(R.string.in_days, days.toDouble()) })
}
)
}
}
fun reset() {
val keys: Map<String, *> = sp.getAll()
for ((key, _) in keys)
if (key.startsWith("Monitor") && key.endsWith("total")) {
sp.remove(key)
sp.remove(key.replace("total", "start"))
sp.remove(key.replace("total", "resumed"))
}
}
} | agpl-3.0 | 54cf92afc768d03af4047ca416c8a48a | 45.016949 | 156 | 0.610794 | 4.676141 | false | false | false | false |
Heiner1/AndroidAPS | openhumans/src/main/java/info/nightscout/androidaps/plugin/general/openhumans/ui/OHLoginActivity.kt | 1 | 4443 | package info.nightscout.androidaps.plugin.general.openhumans.ui
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.widget.CheckBox
import androidx.activity.viewModels
import androidx.browser.customtabs.CustomTabsIntent
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.view.updatePadding
import androidx.core.widget.NestedScrollView
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.button.MaterialButton
import dagger.android.support.DaggerAppCompatActivity
import info.nightscout.androidaps.plugin.general.openhumans.R
import info.nightscout.androidaps.plugin.general.openhumans.di.AuthUrl
import info.nightscout.androidaps.plugin.general.openhumans.di.ViewModelFactory
import javax.inject.Inject
class OHLoginActivity : DaggerAppCompatActivity() {
@Inject
internal lateinit var viewModelFactory: ViewModelFactory
@Inject
@AuthUrl
internal lateinit var authUrl: String
private val viewModel by viewModels<OHLoginViewModel> { viewModelFactory }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_open_humans_login_new)
val toolbar = findViewById<MaterialToolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
supportActionBar!!.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.setDisplayShowHomeEnabled(true)
WindowCompat.setDecorFitsSystemWindows(window, false)
ViewCompat.setOnApplyWindowInsetsListener(toolbar) { view, insets ->
view.updatePadding(top = insets.getInsets(WindowInsetsCompat.Type.systemBars()).top)
insets
}
val accept = findViewById<CheckBox>(R.id.accept)
val login = findViewById<MaterialButton>(R.id.login)
accept.setOnCheckedChangeListener { _, value -> login.isEnabled = value }
login.setOnClickListener {
CustomTabsIntent.Builder().build().launchUrl(this, Uri.parse(authUrl))
}
val cancel = findViewById<MaterialButton>(R.id.cancel)
cancel.setOnClickListener { viewModel.cancel() }
val proceed = findViewById<MaterialButton>(R.id.proceed)
proceed.setOnClickListener { viewModel.finish() }
val close = findViewById<MaterialButton>(R.id.close)
close.setOnClickListener { finish() }
val welcome = findViewById<NestedScrollView>(R.id.welcome)
val consent = findViewById<NestedScrollView>(R.id.consent)
val confirm = findViewById<NestedScrollView>(R.id.confirm)
val finishing = findViewById<NestedScrollView>(R.id.finishing)
val done = findViewById<NestedScrollView>(R.id.done)
val welcomeNext = findViewById<MaterialButton>(R.id.welcome_next)
welcomeNext.setOnClickListener {
viewModel.goToConsent()
}
viewModel.state.observe(this) { state ->
welcome.visibility =
if (state == OHLoginViewModel.State.WELCOME) View.VISIBLE else View.GONE
consent.visibility =
if (state == OHLoginViewModel.State.CONSENT) View.VISIBLE else View.GONE
confirm.visibility =
if (state == OHLoginViewModel.State.CONFIRM) View.VISIBLE else View.GONE
finishing.visibility =
if (state == OHLoginViewModel.State.FINISHING) View.VISIBLE else View.GONE
done.visibility =
if (state == OHLoginViewModel.State.DONE) View.VISIBLE else View.GONE
}
val code = intent.data?.getQueryParameter("code")
if (code != null) {
viewModel.submitBearerToken(code)
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
val code = intent.data?.getQueryParameter("code")
if (code != null) {
viewModel.submitBearerToken(code)
}
}
override fun onBackPressed() {
if (!viewModel.goBack()) {
super.onBackPressed()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean =
if (item.itemId == android.R.id.home) {
onBackPressed()
true
} else {
super.onOptionsItemSelected(item)
}
} | agpl-3.0 | dc9cf8433a2e7bdf9d79d592d56823ba | 35.727273 | 96 | 0.694576 | 4.936667 | false | false | false | false |
exponentjs/exponent | packages/expo-modules-core/android/src/main/java/expo/modules/kotlin/ModuleHolder.kt | 2 | 1586 | package expo.modules.kotlin
import com.facebook.react.bridge.ReadableArray
import expo.modules.kotlin.events.BasicEventListener
import expo.modules.kotlin.events.EventListenerWithPayload
import expo.modules.kotlin.events.EventListenerWithSenderAndPayload
import expo.modules.kotlin.events.EventName
import expo.modules.kotlin.exception.FunctionCallException
import expo.modules.kotlin.exception.MethodNotFoundException
import expo.modules.kotlin.exception.exceptionDecorator
import expo.modules.kotlin.modules.Module
class ModuleHolder(val module: Module) {
val definition = module.definition()
val name get() = definition.name
fun call(methodName: String, args: ReadableArray, promise: Promise) = exceptionDecorator({
FunctionCallException(methodName, definition.name, it)
}) {
val method = definition.methods[methodName]
?: throw MethodNotFoundException()
method.call(args, promise)
}
fun post(eventName: EventName) {
val listener = definition.eventListeners[eventName] ?: return
(listener as? BasicEventListener)?.call()
}
@Suppress("UNCHECKED_CAST")
fun <Payload> post(eventName: EventName, payload: Payload) {
val listener = definition.eventListeners[eventName] ?: return
(listener as? EventListenerWithPayload<Payload>)?.call(payload)
}
@Suppress("UNCHECKED_CAST")
fun <Sender, Payload> post(eventName: EventName, sender: Sender, payload: Payload) {
val listener = definition.eventListeners[eventName] ?: return
(listener as? EventListenerWithSenderAndPayload<Sender, Payload>)?.call(sender, payload)
}
}
| bsd-3-clause | 973cdce382d0ff83e65153ff075549f9 | 36.761905 | 92 | 0.776797 | 4.381215 | false | false | false | false |
PolymerLabs/arcs | javatests/arcs/core/data/ReferenceTypeTest.kt | 1 | 8344 | /*
* 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.data
import arcs.core.type.Tag
import arcs.core.type.Type
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
@RunWith(Parameterized::class)
class ReferenceTypeTest(val params: TestParameters) {
@Test
fun tag_isReference() {
assertThat(params.actual.tag).isEqualTo(Tag.Reference)
}
@Test
fun containedType() {
assertThat(params.actual.containedType).isEqualTo(params.expected.containedType)
}
@Test
fun entitySchema() {
assertThat(params.actual.entitySchema).isEqualTo(params.expected.entitySchema)
}
@Test
fun toString_simple() {
assertThat(params.actual.toString()).isEqualTo(params.expected.stringRepr)
}
@Test
fun toString_withOptions_showFields_notPretty() {
val options = Type.ToStringOptions(hideFields = false, pretty = false)
assertThat(params.actual.toStringWithOptions(options))
.isEqualTo("&${params.expected.containedType.toStringWithOptions(options)}")
}
@Test
fun toString_withOptions_showFields_pretty() {
val options = Type.ToStringOptions(hideFields = false, pretty = true)
assertThat(params.actual.toStringWithOptions(options))
.isEqualTo("&${params.expected.containedType.toStringWithOptions(options)}")
}
@Test
fun toString_withOptions_hideFields_notPretty() {
val options = Type.ToStringOptions(hideFields = true, pretty = false)
assertThat(params.actual.toStringWithOptions(options))
.isEqualTo("&${params.expected.containedType.toStringWithOptions(options)}")
}
@Test
fun toString_withOptions_hideFields_pretty() {
val options = Type.ToStringOptions(hideFields = true, pretty = true)
assertThat(params.actual.toStringWithOptions(options))
.isEqualTo("&${params.expected.containedType.toStringWithOptions(options)}")
}
data class TestParameters(
val name: String,
val actual: ReferenceType<*>,
val expected: ExpectedValues
) {
override fun toString(): String = name
}
data class ExpectedValues(
val containedType: Type,
val entitySchema: Schema?,
val stringRepr: String
)
private data class FakeTypeWithDifferentResolvedType(override val tag: Tag = Tag.Count) : Type {
override fun isAtLeastAsSpecificAs(other: Type): Boolean = true
override fun toStringWithOptions(options: Type.ToStringOptions): String = toString()
}
companion object {
private val ENTITY_SCHEMA = Schema(
names = setOf(SchemaName("name 1"), SchemaName("name 2")),
fields = SchemaFields(
singletons = mapOf(
"primitive" to FieldType.Int,
"reference" to FieldType.EntityRef("1234"),
"inline" to FieldType.InlineEntity("1234"),
"list_primitive" to FieldType.ListOf(FieldType.Instant),
"list_inline" to FieldType.ListOf(FieldType.InlineEntity("abcd")),
"list_reference" to FieldType.ListOf(FieldType.EntityRef("abcd")),
"tuple" to FieldType.Tuple(FieldType.Int, FieldType.Text)
),
collections = mapOf(
"primitive" to FieldType.Int,
"reference" to FieldType.EntityRef("1234"),
"inline" to FieldType.InlineEntity("1234"),
"list_primitive" to FieldType.ListOf(FieldType.Instant),
"list_inline" to FieldType.ListOf(FieldType.InlineEntity("abcd")),
"list_reference" to FieldType.ListOf(FieldType.EntityRef("abcd")),
"tuple" to FieldType.Tuple(FieldType.Int, FieldType.Text)
)
),
hash = "myEntityHash1234"
)
@get:JvmStatic
@get:Parameterized.Parameters(name = "{0}")
val PARAMETERS: Array<TestParameters> = arrayOf(
TestParameters(
name = "Collection of Count",
actual = ReferenceType(CollectionType(CountType())),
expected = ExpectedValues(
containedType = CollectionType(collectionType = CountType()),
entitySchema = null,
stringRepr = "&CollectionType(collectionType=CountType(tag=Count))"
)
),
TestParameters(
name = "Singleton of Count",
actual = ReferenceType(SingletonType(CountType())),
expected = ExpectedValues(
containedType = SingletonType(CountType()),
entitySchema = null,
stringRepr = "&${SingletonType(CountType())}"
)
),
TestParameters(
name = "Count",
actual = ReferenceType(CountType()),
expected = ExpectedValues(
containedType = CountType(),
entitySchema = null,
stringRepr = "&CountType(tag=Count)"
)
),
TestParameters(
name = "Entity",
actual = ReferenceType(EntityType(ENTITY_SCHEMA)),
expected = ExpectedValues(
containedType = EntityType(ENTITY_SCHEMA),
entitySchema = ENTITY_SCHEMA,
stringRepr = "&${EntityType(ENTITY_SCHEMA)}"
)
),
TestParameters(
name = "Collection of Entities",
actual = ReferenceType(CollectionType(EntityType(ENTITY_SCHEMA))),
expected = ExpectedValues(
containedType = CollectionType(EntityType(ENTITY_SCHEMA)),
entitySchema = ENTITY_SCHEMA,
stringRepr = "&${CollectionType(EntityType(ENTITY_SCHEMA))}"
)
),
TestParameters(
name = "Reference of Entity",
actual = ReferenceType(ReferenceType(EntityType(ENTITY_SCHEMA))),
expected = ExpectedValues(
containedType = ReferenceType(EntityType(ENTITY_SCHEMA)),
entitySchema = ENTITY_SCHEMA,
stringRepr = "&${ReferenceType(EntityType(ENTITY_SCHEMA))}"
)
),
TestParameters(
name = "Singleton of Entity",
actual = ReferenceType(SingletonType(EntityType(ENTITY_SCHEMA))),
expected = ExpectedValues(
containedType = SingletonType(EntityType(ENTITY_SCHEMA)),
entitySchema = ENTITY_SCHEMA,
stringRepr = "&${SingletonType(EntityType(ENTITY_SCHEMA))}"
)
),
TestParameters(
name = "Mux of Count",
actual = ReferenceType(MuxType(CountType())),
expected = ExpectedValues(
containedType = MuxType(CountType()),
entitySchema = null,
stringRepr = "&${MuxType(CountType())}"
)
),
TestParameters(
name = "Mux of Entity",
actual = ReferenceType(MuxType(EntityType(ENTITY_SCHEMA))),
expected = ExpectedValues(
containedType = MuxType(EntityType(ENTITY_SCHEMA)),
entitySchema = ENTITY_SCHEMA,
stringRepr = "&${MuxType(EntityType(ENTITY_SCHEMA))}"
)
),
TestParameters(
name = "Empty Tuple",
actual = ReferenceType(TupleType()),
expected = ExpectedValues(
containedType = TupleType(),
entitySchema = null,
stringRepr = "&${TupleType()}"
)
),
TestParameters(
name = "Type Variable, no max type allowed",
actual = ReferenceType(TypeVariable("a", CountType(), false)),
expected = ExpectedValues(
containedType = TypeVariable("a", CountType(), false),
entitySchema = null,
stringRepr = "&${TypeVariable("a", CountType(), false)}"
)
),
TestParameters(
name = "Type Variable, max type allowed",
actual = ReferenceType(TypeVariable("a", CountType(), true)),
expected = ExpectedValues(
containedType = TypeVariable("a", CountType(), true),
entitySchema = null,
stringRepr = "&${TypeVariable("a", CountType(), true)}"
)
),
TestParameters(
name = "Fake type with different resolved type",
actual = ReferenceType(FakeTypeWithDifferentResolvedType()),
expected = ExpectedValues(
containedType = FakeTypeWithDifferentResolvedType(),
entitySchema = null,
stringRepr = "&${FakeTypeWithDifferentResolvedType()}"
)
)
)
}
}
| bsd-3-clause | a56384cf90b5f34421eceb572efd7114 | 34.058824 | 98 | 0.643696 | 4.661453 | false | true | false | false |
blindpirate/gradle | subprojects/kotlin-dsl-plugins/src/main/kotlin/org/gradle/kotlin/dsl/plugins/precompiled/PrecompiledScriptPlugins.kt | 1 | 2514 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.plugins.precompiled
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.file.SourceDirectorySet
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.api.tasks.TaskProvider
import org.gradle.kotlin.dsl.*
import org.gradle.kotlin.dsl.provider.PrecompiledScriptPluginsSupport
import org.gradle.kotlin.dsl.provider.gradleKotlinDslJarsOf
import org.gradle.kotlin.dsl.support.serviceOf
import org.jetbrains.kotlin.gradle.plugin.KotlinSourceSet
/**
* Exposes `*.gradle.kts` scripts from regular Kotlin source-sets as binary Gradle plugins.
*
* @see PrecompiledScriptPluginsSupport
*/
class PrecompiledScriptPlugins : Plugin<Project> {
override fun apply(project: Project): Unit = project.run {
if (serviceOf<PrecompiledScriptPluginsSupport>().enableOn(Target(project))) {
dependencies {
"kotlinCompilerPluginClasspath"(gradleKotlinDslJarsOf(project))
"kotlinCompilerPluginClasspath"(gradleApi())
}
}
}
private
class Target(override val project: Project) : PrecompiledScriptPluginsSupport.Target {
override val kotlinSourceDirectorySet: SourceDirectorySet
get() = project.sourceSets["main"].kotlin
@Deprecated("No longer used.", ReplaceWith(""))
override val kotlinCompileTask: TaskProvider<out Task>
get() = error("No longer used")
@Deprecated("No longer used.", ReplaceWith(""))
override fun applyKotlinCompilerArgs(args: List<String>) =
error("No longer used.")
}
}
private
val Project.sourceSets
get() = project.the<SourceSetContainer>()
private
val SourceSet.kotlin: SourceDirectorySet
get() = @Suppress("deprecation") withConvention(KotlinSourceSet::class) { kotlin }
| apache-2.0 | 4b1d0e1630a423db9a32db7e50a0b0b4 | 32.078947 | 91 | 0.729117 | 4.47331 | false | false | false | false |
AcornUI/Acorn | acornui-core/src/main/kotlin/com/acornui/io/loadUtils.kt | 1 | 5147 | /*
* Copyright 2019 Poly Forest, 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.
*/
@file:Suppress("MemberVisibilityCanBePrivate", "unused")
package com.acornui.io
import com.acornui.async.MutableProgress
import com.acornui.async.ProgressReporter
import com.acornui.async.ProgressReporterImpl
import com.acornui.browser.UrlParams
import com.acornui.browser.toUrlParams
import org.w3c.files.Blob
import kotlin.time.Duration
import kotlin.time.seconds
/**
* A model with the necessary information to make a request.
*/
data class UrlRequestData(
val url: String = "",
val method: String = UrlRequestMethod.GET,
val headers: Map<String, String> = HashMap(),
val user: String? = null,
val password: String? = null,
val formData: MultipartFormData? = null,
val variables: UrlParams? = null,
var body: String? = null
)
private val absolutePathRegex = Regex("""^([a-z0-9]*:|.{0})//.*${'$'}""", RegexOption.IGNORE_CASE)
/**
* Returns true if the requested path starts with a scheme. (e.g. https://, http://, ftp://)
* Note - This is case insensitive and does not validate if it's a known scheme.
*/
val UrlRequestData.isAbsolutePath: Boolean
get() = url.matches(absolutePathRegex)
/**
* @return Returns `!isAbsolutePath`
*/
val UrlRequestData.isRelativePath: Boolean
get() = !isAbsolutePath
fun UrlRequestData.toUrlStr(rootPath: String): String {
val prependedUrl = if (isRelativePath) rootPath + url else url
return if (method == UrlRequestMethod.GET && variables != null)
prependedUrl + "?" + variables.queryString else prependedUrl
}
/**
* Parses a string into [UrlRequestData]
*/
fun String.toUrlRequestData(): UrlRequestData {
val qIndex = indexOf("?")
if (qIndex == -1) return UrlRequestData(this)
val urlStr = substring(0, qIndex)
val queryStr = substring(qIndex + 1)
return UrlRequestData(urlStr, variables = queryStr.toUrlParams())
}
/**
* The possible values for [UrlRequestData.method].
*/
object UrlRequestMethod {
const val GET: String = "GET"
const val POST: String = "POST"
const val PUT: String = "PUT"
const val DELETE: String = "DELETE"
}
open class ResponseConnectTimeoutException(
val requestData: UrlRequestData,
val connectTimeout: Duration
) : Throwable("The request ${requestData.url} timed out after $connectTimeout")
open class ResponseException(val status: Short, message: String?, val detail: String) : Throwable(message) {
override fun toString(): String {
return "ResponseException(status=$status, message=$message, detail=$detail)"
}
}
data class MultipartFormData(val items: List<FormDataItem>)
/**
* A marker interface for items that can be in the list of [MultipartFormData.items]
*/
sealed class FormDataItem {
abstract val name: String
}
class ByteArrayFormItem(
override val name: String,
val value: Blob,
val filename: String?
) : FormDataItem()
class StringFormItem(
override val name: String,
val value: String
) : FormDataItem()
interface Loader<out T> {
/**
* Default request settings.
*/
val requestSettings: RequestSettings
/**
* Begins loading the given request.
*
* @param settings Configuration for the request. To change settings, use [RequestSettings.copy] on the
* [requestSettings] object.
*/
suspend fun load(requestData: UrlRequestData, settings: RequestSettings = requestSettings): T
}
suspend fun <T> Loader<T>.load(path: String, settings: RequestSettings = requestSettings): T =
load(path.toUrlRequestData(), settings)
data class RequestSettings(
/**
* If the request is to a relative path, this value will be prepended.
*/
val rootPath: String = "",
/**
* The progress reporter allows the loader to report its progress.
*/
val progressReporter: ProgressReporter = ProgressReporterImpl(),
/**
* Before a connection has been made, a guess can be made for how long the request will take. This will
* affect the total values given by the progress reporter until the actual estimate is calculated.
*/
val initialTimeEstimate: Duration = 1.seconds,
/**
* If the connection hasn't been made within this timespan, a [com.acornui.io.ResponseConnectTimeoutException]
* will be thrown.
* This is just the timeout for the connection, not the total request. To add a read timeout, wrap your request
* in [com.acornui.async.withTimeout].
*/
val connectTimeout: Duration = 30.seconds
)
/**
* Using the set [RequestSettings.progressReporter] and [RequestSettings.initialTimeEstimate], creates a
* [MutableProgress] object for tracking load progress.
*/
fun RequestSettings.createProgress(): MutableProgress = progressReporter.createReporter(initialTimeEstimate) | apache-2.0 | 8fb3a67295827bc48bf561fc7853f149 | 28.25 | 112 | 0.738488 | 3.867017 | false | false | false | false |
TomsUsername/Phoenix | src/main/kotlin/phoenix/bot/pogo/nRnMK9r/tasks/Export.kt | 1 | 12222 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package phoenix.bot.pogo.nRnMK9r.tasks
import POGOProtos.Enums.PokemonIdOuterClass
import POGOProtos.Enums.PokemonMoveOuterClass
import com.google.common.geometry.S2CellId
import com.google.common.geometry.S2LatLng
import phoenix.bot.pogo.api.cache.BagPokemon
import phoenix.bot.pogo.api.util.PokemonMetaRegistry
import phoenix.bot.pogo.api.util.PokemonMoveMetaRegistry
import phoenix.bot.pogo.nRnMK9r.Bot
import phoenix.bot.pogo.nRnMK9r.Context
import phoenix.bot.pogo.nRnMK9r.Settings
import phoenix.bot.pogo.nRnMK9r.Task
import phoenix.bot.pogo.nRnMK9r.util.Log
import phoenix.bot.pogo.nRnMK9r.util.io.ExportCSVWriter
import phoenix.bot.pogo.nRnMK9r.util.io.ExportJSONWriter
import phoenix.bot.pogo.nRnMK9r.util.pokemon.*
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.atomic.AtomicInteger
class Export : Task {
override fun run(bot: Bot, ctx: Context, settings: Settings) {
val compareName = Comparator<BagPokemon> { a, b ->
a.pokemonData.pokemonId.name.compareTo(b.pokemonData.pokemonId.name)
}
val compareIv = Comparator<BagPokemon> { a, b ->
// compare b to a to get it descending
if (settings.sortByIv) {
b.pokemonData.getIv().compareTo(a.pokemonData.getIv())
} else {
b.pokemonData.cp.compareTo(a.pokemonData.cp)
}
}
try {
val dateFormatter = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
// Output player information
val profile: Map<String, String> = mapOf(
Pair("Name", ctx.api.playerData.username),
Pair("Team", ctx.api.playerData.team.name),
Pair("Pokecoin", "${ctx.api.inventory.currencies.getOrPut("POKECOIN", { AtomicInteger(0) }).get()}"),
Pair("Stardust", "${ctx.api.inventory.currencies.getOrPut("STARDUST", { AtomicInteger(0) }).get()}"),
Pair("Level", "${ctx.api.inventory.playerStats.level}"),
Pair("Experience", "${ctx.api.inventory.playerStats.experience}"),
Pair("Previous Level Experience", "${ctx.api.inventory.playerStats.prevLevelXp}"),
Pair("Next Level Experience", "${ctx.api.inventory.playerStats.nextLevelXp}"),
Pair("Km walked", ds("${ctx.api.inventory.playerStats.kmWalked}", settings)),
Pair("Pokemons Encountered", "${ctx.api.inventory.playerStats.pokemonsEncountered}"),
Pair("Pokemons Captured", "${ctx.api.inventory.playerStats.pokemonsCaptured}"),
Pair("Unique Pokedex Entries", "${ctx.api.inventory.playerStats.uniquePokedexEntries}"),
Pair("Evolutions", "${ctx.api.inventory.playerStats.evolutions}"),
Pair("Pokestop Visits", "${ctx.api.inventory.playerStats.pokeStopVisits}"),
Pair("Pokeballs Thrown", "${ctx.api.inventory.playerStats.pokeballsThrown}"),
Pair("Eggs Hatched", "${ctx.api.inventory.playerStats.eggsHatched}"),
Pair("Battle Attack Won", "${ctx.api.inventory.playerStats.battleAttackWon}"),
Pair("Battle Attack Total", "${ctx.api.inventory.playerStats.battleAttackTotal}"),
Pair("Battle Defended Won", "${ctx.api.inventory.playerStats.battleDefendedWon}"),
Pair("Battle Training Won", "${ctx.api.inventory.playerStats.battleTrainingTotal}"),
Pair("Battle Training Total", "${ctx.api.inventory.playerStats.battleTrainingTotal}"),
Pair("Prestige Raised Total", "${ctx.api.inventory.playerStats.prestigeRaisedTotal}"),
Pair("Prestige Dropped Total", "${ctx.api.inventory.playerStats.prestigeDroppedTotal}"),
Pair("Pokemon Deployed", "${ctx.api.inventory.playerStats.pokemonDeployed}"),
Pair("Pokebank Size", "${ctx.api.inventory.pokemon.size + ctx.api.inventory.eggs.size}"),
Pair("Maximum Pokebank Storage", "${ctx.api.playerData.maxPokemonStorage}"),
Pair("Inventory Size", "${ctx.api.inventory.size}"),
Pair("Maximum Inventory Storage", "${ctx.api.playerData.maxItemStorage}"),
Pair("Last Update", dateFormatter.format(Date())),
Pair("Location Latitude", ds("${ctx.lat.get()}", settings)),
Pair("Location Longitude", ds("${ctx.lng.get()}", settings))
)
// Output Eggs
val eggs = ArrayList<Map<String, String>>()
for (egg in ctx.api.inventory.eggs) {
val latLng = S2LatLng(S2CellId(egg.value.pokemonData.capturedCellId).toPoint())
eggs.add(mapOf(
Pair("Walked [km]", ds("${egg.value.pokemonData.eggKmWalked(ctx.api)}", settings)),
Pair("Target [km]", ds("${egg.value.pokemonData.eggKmWalkedTarget}", settings)),
Pair("Incubated?", "${egg.value.pokemonData.incubated}"),
Pair("Found", dateFormatter.format(Date(egg.value.pokemonData.creationTimeMs))),
Pair("Location Latitude", ds("${latLng.latDegrees()}", settings)),
Pair("Location Longitude", ds("${latLng.lngDegrees()}", settings))
))
}
// Output Items
val items = ArrayList<Map<String, String>>()
for (item in ctx.api.inventory.items) {
items.add(mapOf(
Pair("Item", item.key.name),
Pair("Count", "${item.value.get()}")
))
}
// Output Pokebank
val pokemons = ArrayList<Map<String, String>>()
ctx.api.inventory.pokemon.map { it.value }.sortedWith(compareName.thenComparing(compareIv)).map {
val latLng = S2LatLng(S2CellId(it.pokemonData.capturedCellId).toPoint())
val pmeta = PokemonMetaRegistry.getMeta(PokemonIdOuterClass.PokemonId.forNumber(it.pokemonData.pokemonId.number))
val pmmeta1 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(it.pokemonData.move1.number))
val pmmeta2 = PokemonMoveMetaRegistry.getMeta(PokemonMoveOuterClass.PokemonMove.forNumber(it.pokemonData.move2.number))
mapOf(
Pair("Number", "${it.pokemonData.pokemonId.number}"),
Pair("Name", it.pokemonData.pokemonId.name),
Pair("Nickname", it.pokemonData.nickname),
Pair("Favorite?", "${it.pokemonData.favorite}"),
Pair("CP", "${it.pokemonData.cp}"),
Pair("IV [%]", "${it.pokemonData.getIvPercentage()}"),
Pair("Stamina (HP)", "${it.pokemonData.stamina}"),
Pair("Max Stamina (HP)", "${it.pokemonData.staminaMax}"),
Pair("Class", pmeta.pokemonClass.name),
Pair("Type", formatType(pmeta.type1.name, pmeta.type2.name)),
Pair("Move 1", it.pokemonData.move1.name),
Pair("Move 1 Type", pmmeta1.type.name),
Pair("Move 1 Power", "${pmmeta1.power}"),
Pair("Move 1 Accuracy", "${pmmeta1.accuracy}"),
Pair("Move 1 Crit Chance", ds("${pmmeta1.critChance}", settings)),
Pair("Move 1 Time", "${pmmeta1.time}"),
Pair("Move 1 Energy", "${pmmeta1.energy}"),
Pair("Move 2", it.pokemonData.move2.name),
Pair("Move 2 Type", pmmeta2.type.name),
Pair("Move 2 Power", "${pmmeta2.power}"),
Pair("Move 2 Accuracy", "${pmmeta2.accuracy}"),
Pair("Move 2 Crit Chance", ds("${pmmeta2.critChance}", settings)),
Pair("Move 2 Time", "${pmmeta2.time}"),
Pair("Move 2 Energy", "${pmmeta2.energy}"),
Pair("iStamina", "${it.pokemonData.individualStamina}"),
Pair("iAttack", "${it.pokemonData.individualAttack}"),
Pair("iDefense", "${it.pokemonData.individualDefense}"),
Pair("cpMultiplier", ds("${it.pokemonData.cpMultiplier}", settings)),
Pair("Height [m]", ds("${it.pokemonData.heightM}", settings)),
Pair("Weight [kg]", ds("${it.pokemonData.weightKg}", settings)),
Pair("Candy", "${ctx.api.inventory.candies.getOrPut(pmeta.family, { AtomicInteger(0) }).get()}"),
Pair("Candies to evolve", "${pmeta.candyToEvolve}"),
Pair("Candy costs for powerup", "${it.pokemonData.candyCostsForPowerup}"),
Pair("Stardust costs for powerup", "${it.pokemonData.stardustCostsForPowerup}"),
Pair("Found", dateFormatter.format(Date(it.pokemonData.creationTimeMs))),
Pair("Found Latitude", ds("${latLng.latDegrees()}", settings)),
Pair("Found Longitude", ds("${latLng.lngDegrees()}", settings)),
Pair("Base Capture Rate", ds("${pmeta.baseCaptureRate}", settings)),
Pair("Base Flee Rate", ds("${pmeta.baseFleeRate}", settings)),
Pair("Battles Attacked", "${it.pokemonData.battlesAttacked}"),
Pair("Battles Defended", "${it.pokemonData.battlesDefended}"),
Pair("Injured?", "${it.pokemonData.injured}"),
Pair("Fainted?", "${it.pokemonData.fainted}"),
Pair("Level", ds("${it.pokemonData.level}", settings)),
Pair("CP after powerup", "${it.pokemonData.cpAfterPowerup}"),
Pair("Max CP", "${it.pokemonData.maxCp}"),
Pair("ID", "${it.pokemonData.id}")
)
}.forEach { pokemons.add(it) }
when (settings.export) {
"CSV" -> {
val filename = "export_${settings.name}.csv"
val writer = ExportCSVWriter(filename)
writer.write(profile, eggs, items, pokemons)
Log.normal("Wrote export $filename.")
}
"DSV" -> {
val filename = "export_${settings.name}.csv"
val writer = ExportCSVWriter(filename, ";")
writer.write(profile, eggs, items, pokemons)
Log.normal("Wrote export $filename.")
}
"JSON" -> {
val filename = "export_${settings.name}.json"
val writer = ExportJSONWriter(filename)
writer.write(profile, eggs, items, pokemons)
Log.normal("Wrote export $filename.")
}
else -> {
Log.red("Invalid export configuration!")
}
}
} catch (e: Exception) {
Log.red("Error writing export: ${e.message}")
}
}
// Detect if the "float" fields need to be forced to use "," instead of "." (DSV export)
private fun ds(string: String, settings: Settings): String {
var result = string
if (settings.export.equals("DSV")) {
result = result.replace(".", ",")
}
return result
}
// Don't concat 2nd pokemon type "NONE"
private fun formatType(type1: String, type2: String): String {
if (type2.equals("NONE")) return type1
return "$type1/$type2"
}
}
| gpl-3.0 | 266f51d636d191c80fdadc96e8e23096 | 56.380282 | 135 | 0.557028 | 4.570681 | false | false | false | false |
Yusuzhan/kotlin-koans | src/iii_conventions/_30_DestructuringDeclarations.kt | 1 | 573 | package iii_conventions.multiAssignemnt
import util.TODO
import util.doc30
fun todoTask30(): Nothing = TODO(
"""
Task 30.
Read about destructuring declarations and make the following code compile by adding one word (after uncommenting it).
""",
documentation = doc30()
)
data class MyDate(val year: Int, val month: Int, val dayOfMonth: Int)
fun isLeapDay(date: MyDate): Boolean {
//todoTask30()
val (year, month, dayOfMonth) = date
//
// // 29 February of a leap year
return year % 4 == 0 && month == 2 && dayOfMonth == 29
} | mit | 78d346cc8a47dd408cdd0e71deffabb0 | 22.916667 | 125 | 0.661431 | 3.871622 | false | false | false | false |
theScrabi/NewPipe | app/src/main/java/org/schabi/newpipe/database/feed/dao/FeedDAO.kt | 1 | 4842 | package org.schabi.newpipe.database.feed.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Transaction
import androidx.room.Update
import io.reactivex.rxjava3.core.Flowable
import org.schabi.newpipe.database.feed.model.FeedEntity
import org.schabi.newpipe.database.feed.model.FeedLastUpdatedEntity
import org.schabi.newpipe.database.stream.model.StreamEntity
import org.schabi.newpipe.database.subscription.SubscriptionEntity
import java.time.OffsetDateTime
@Dao
abstract class FeedDAO {
@Query("DELETE FROM feed")
abstract fun deleteAll(): Int
@Query(
"""
SELECT s.* FROM streams s
INNER JOIN feed f
ON s.uid = f.stream_id
ORDER BY s.upload_date IS NULL DESC, s.upload_date DESC, s.uploader ASC
LIMIT 500
"""
)
abstract fun getAllStreams(): Flowable<List<StreamEntity>>
@Query(
"""
SELECT s.* FROM streams s
INNER JOIN feed f
ON s.uid = f.stream_id
INNER JOIN feed_group_subscription_join fgs
ON fgs.subscription_id = f.subscription_id
INNER JOIN feed_group fg
ON fg.uid = fgs.group_id
WHERE fgs.group_id = :groupId
ORDER BY s.upload_date IS NULL DESC, s.upload_date DESC, s.uploader ASC
LIMIT 500
"""
)
abstract fun getAllStreamsFromGroup(groupId: Long): Flowable<List<StreamEntity>>
@Query(
"""
DELETE FROM feed WHERE
feed.stream_id IN (
SELECT s.uid FROM streams s
INNER JOIN feed f
ON s.uid = f.stream_id
WHERE s.upload_date < :offsetDateTime
)
"""
)
abstract fun unlinkStreamsOlderThan(offsetDateTime: OffsetDateTime)
@Query(
"""
DELETE FROM feed
WHERE feed.subscription_id = :subscriptionId
AND feed.stream_id IN (
SELECT s.uid FROM streams s
INNER JOIN feed f
ON s.uid = f.stream_id
WHERE s.stream_type = "LIVE_STREAM" OR s.stream_type = "AUDIO_LIVE_STREAM"
)
"""
)
abstract fun unlinkOldLivestreams(subscriptionId: Long)
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insert(feedEntity: FeedEntity)
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract fun insertAll(entities: List<FeedEntity>): List<Long>
@Insert(onConflict = OnConflictStrategy.IGNORE)
internal abstract fun insertLastUpdated(lastUpdatedEntity: FeedLastUpdatedEntity): Long
@Update(onConflict = OnConflictStrategy.IGNORE)
internal abstract fun updateLastUpdated(lastUpdatedEntity: FeedLastUpdatedEntity)
@Transaction
open fun setLastUpdatedForSubscription(lastUpdatedEntity: FeedLastUpdatedEntity) {
val id = insertLastUpdated(lastUpdatedEntity)
if (id == -1L) {
updateLastUpdated(lastUpdatedEntity)
}
}
@Query(
"""
SELECT MIN(lu.last_updated) FROM feed_last_updated lu
INNER JOIN feed_group_subscription_join fgs
ON fgs.subscription_id = lu.subscription_id AND fgs.group_id = :groupId
"""
)
abstract fun oldestSubscriptionUpdate(groupId: Long): Flowable<List<OffsetDateTime>>
@Query("SELECT MIN(last_updated) FROM feed_last_updated")
abstract fun oldestSubscriptionUpdateFromAll(): Flowable<List<OffsetDateTime>>
@Query("SELECT COUNT(*) FROM feed_last_updated WHERE last_updated IS NULL")
abstract fun notLoadedCount(): Flowable<Long>
@Query(
"""
SELECT COUNT(*) FROM subscriptions s
INNER JOIN feed_group_subscription_join fgs
ON s.uid = fgs.subscription_id AND fgs.group_id = :groupId
LEFT JOIN feed_last_updated lu
ON s.uid = lu.subscription_id
WHERE lu.last_updated IS NULL
"""
)
abstract fun notLoadedCountForGroup(groupId: Long): Flowable<Long>
@Query(
"""
SELECT s.* FROM subscriptions s
LEFT JOIN feed_last_updated lu
ON s.uid = lu.subscription_id
WHERE lu.last_updated IS NULL OR lu.last_updated < :outdatedThreshold
"""
)
abstract fun getAllOutdated(outdatedThreshold: OffsetDateTime): Flowable<List<SubscriptionEntity>>
@Query(
"""
SELECT s.* FROM subscriptions s
INNER JOIN feed_group_subscription_join fgs
ON s.uid = fgs.subscription_id AND fgs.group_id = :groupId
LEFT JOIN feed_last_updated lu
ON s.uid = lu.subscription_id
WHERE lu.last_updated IS NULL OR lu.last_updated < :outdatedThreshold
"""
)
abstract fun getAllOutdatedForGroup(groupId: Long, outdatedThreshold: OffsetDateTime): Flowable<List<SubscriptionEntity>>
}
| gpl-3.0 | 23fb5e35b31617d689679978a6c7206c | 27.821429 | 125 | 0.658819 | 4.43813 | false | false | false | false |
TomsUsername/Phoenix | src/main/kotlin/phoenix/bot/pogo/nRnMK9r/tasks/Walk.kt | 1 | 11034 | /**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package phoenix.bot.pogo.nRnMK9r.tasks
import com.google.common.geometry.S2LatLng
import com.google.common.util.concurrent.AtomicDouble
import phoenix.bot.pogo.api.cache.Pokestop
import phoenix.bot.pogo.nRnMK9r.Bot
import phoenix.bot.pogo.nRnMK9r.Context
import phoenix.bot.pogo.nRnMK9r.Settings
import phoenix.bot.pogo.nRnMK9r.Task
import phoenix.bot.pogo.nRnMK9r.util.Log
import phoenix.bot.pogo.nRnMK9r.util.directions.getRouteCoordinates
import phoenix.bot.pogo.nRnMK9r.util.map.canLoot
import phoenix.bot.pogo.nRnMK9r.util.pokemon.inRange
import java.text.DecimalFormat
import java.util.concurrent.atomic.AtomicBoolean
class Walk(val sortedPokestops: List<Pokestop>, val lootTimeouts: Map<String, Long>) : Task {
override fun run(bot: Bot, ctx: Context, settings: Settings) {
if (!ctx.walking.compareAndSet(false, true)) {
return
}
if (ctx.server.coordinatesToGoTo.size > 0) {
val coordinates = ctx.server.coordinatesToGoTo.first()
ctx.server.coordinatesToGoTo.removeAt(0)
Log.normal("Walking to ${coordinates.latDegrees()}, ${coordinates.lngDegrees()}")
walk(bot, ctx, settings, coordinates, settings.speed, true, null)
} else {
val nearestUnused: List<Pokestop> = sortedPokestops.filter {
val canLoot = it.canLoot(ignoreDistance = true, lootTimeouts = lootTimeouts)
if (settings.spawnRadius == -1) {
canLoot
} else {
val distanceToStart = settings.startingLocation.getEarthDistance(S2LatLng.fromDegrees(it.fortData.latitude, it.fortData.longitude))
canLoot && distanceToStart < settings.spawnRadius
}
}
if (nearestUnused.isNotEmpty()) {
// Select random pokestop from the 5 nearest while taking the distance into account
val chosenPokestop = selectRandom(nearestUnused.take(settings.randomNextPokestopSelection), ctx)
ctx.server.sendPokestop(chosenPokestop)
if (settings.displayPokestopName) {
Log.normal("Walking to pokestop \"${chosenPokestop.name}\"")
}
walk(bot, ctx, settings, S2LatLng.fromDegrees(chosenPokestop.fortData.latitude, chosenPokestop.fortData.longitude), settings.speed, false, chosenPokestop)
}
}
}
private fun walk(bot: Bot, ctx: Context, settings: Settings, end: S2LatLng, speed: Double, sendDone: Boolean, pokestop: Pokestop?) {
if (settings.followStreets.isNotEmpty()) {
walkRoute(bot, ctx, settings, end, speed, sendDone, pokestop)
} else {
walkDirectly(bot, ctx, settings, end, speed, sendDone)
}
}
private fun walkDirectly(bot: Bot, ctx: Context, settings: Settings, end: S2LatLng, speed: Double, sendDone: Boolean) {
walkPath(bot, ctx, settings, mutableListOf(end), speed, sendDone, null)
}
private fun walkRoute(bot: Bot, ctx: Context, settings: Settings, end: S2LatLng, speed: Double, sendDone: Boolean, pokestop: Pokestop?) {
val coordinatesList = getRouteCoordinates(S2LatLng.fromDegrees(ctx.lat.get(), ctx.lng.get()), end, settings, ctx.geoApiContext!!)
if (coordinatesList.size > 0) {
walkPath(bot, ctx, settings, coordinatesList, speed, sendDone, pokestop)
} else {
walkDirectly(bot, ctx, settings, end, speed, sendDone)
}
}
//all walk functions should call this one
private fun walkPath(bot: Bot, ctx: Context, settings: Settings, path: MutableList<S2LatLng>, speed: Double, sendDone: Boolean, pokestop: Pokestop?) {
if (speed.equals(0)) {
return
}
if (path.isEmpty()) {
return
}
//random waiting
if (Math.random() * 100 < settings.waitChance) {
val waitTimeMin = settings.waitTimeMin
val waitTimeMax = settings.waitTimeMax
if (waitTimeMax > waitTimeMin) {
val sleepTime: Long = (Math.random() * (waitTimeMax - waitTimeMin) + waitTimeMin).toLong()
Log.yellow("Trainer grew tired, needs to rest a little (for $sleepTime seconds)")
Thread.sleep(sleepTime * 1000)
}
}
val randomSpeed = randomizeSpeed(speed, settings.randomSpeedRange, ctx)
Log.green("Your character now moves at ${DecimalFormat("#0.0").format(randomSpeed)} m/s")
ctx.walkingSpeed = AtomicDouble(randomSpeed)
val timeout = 200L
var remainingSteps = 0.0
var deltaLat = 0.0
var deltaLng = 0.0
val pauseWalk: AtomicBoolean = AtomicBoolean(false)
var pauseCounter = 2
bot.runLoop(timeout, "WalkingLoop") { cancel ->
// check if other task really needs us to stop for a second.
// other task is responsible of unlocking this!
if (ctx.pauseWalking.get()) {
return@runLoop
}
if (remainingSteps <= 0) {
if (path.isEmpty()) {
Log.normal("Destination reached.")
if (sendDone) {
ctx.server.sendGotoDone()
}
// Destination reached, if we follow streets, but the pokestop is not on a available from street, go directly
if (pokestop != null && settings.followStreets.isNotEmpty() && pokestop.canLoot(true, lootTimeouts) && !pokestop.canLoot(false, lootTimeouts)) {
Log.normal("Pokestop is too far using street, go directly!")
walkDirectly(bot, ctx, settings, S2LatLng.fromDegrees(pokestop.fortData.latitude, pokestop.fortData.longitude), speed, false)
} else {
ctx.walking.set(false)
}
cancel()
} else {
//calculate delta lat/long for next step
val start = S2LatLng.fromDegrees(ctx.lat.get(), ctx.lng.get())
val nextPoint = path.first()
path.removeAt(0)
val diff = nextPoint.sub(start)
val distance = start.getEarthDistance(nextPoint)
val timeRequired = distance / randomSpeed
val stepsRequired = timeRequired / (timeout.toDouble() / 1000.toDouble())
deltaLat = diff.latDegrees() / stepsRequired
deltaLng = diff.lngDegrees() / stepsRequired
if (settings.displayKeepalive) Log.normal("Walking to ${nextPoint.toStringDegrees()} in ${Math.round(stepsRequired)} steps.")
remainingSteps = stepsRequired
}
}
if (pauseWalk.get()) {
Thread.sleep(timeout * 2)
pauseCounter--
if (!(ctx.api.inventory.hasPokeballs && bot.api.map.getPokemon(bot.api.latitude, bot.api.longitude, 3).filter {
!ctx.blacklistedEncounters.contains(it.encounterId) && it.inRange
}.size > 0 && settings.catchPokemon)) {
// api break free
pauseWalk.set(false)
pauseCounter = 0
}
// fixed tries break free
if (pauseCounter > 0) {
return@runLoop
} else {
pauseWalk.set(false)
}
}
// don't run away when there are still Pokemon around
if (remainingSteps.toInt().mod(20) == 0 && pauseCounter > 0) {
if (ctx.api.inventory.hasPokeballs && bot.api.map.getPokemon(bot.api.latitude, bot.api.longitude, 3).filter {
!ctx.blacklistedEncounters.contains(it.encounterId) && it.inRange
}.size > 0 && settings.catchPokemon) {
// Stop walking
Log.normal("Pausing to catch pokemon...")
pauseCounter = 2
pauseWalk.set(true)
return@runLoop
}
}
pauseCounter = 2
val lat = ctx.lat.addAndGet(deltaLat)
val lng = ctx.lng.addAndGet(deltaLng)
ctx.server.setLocation(lat, lng)
remainingSteps--
}
}
private fun selectRandom(pokestops: List<Pokestop>, ctx: Context): Pokestop {
// Select random pokestop while taking the distance into account
// E.g. pokestop is closer to the user -> higher probabilty to be chosen
if (pokestops.size < 2)
return pokestops.first()
val currentPosition = S2LatLng.fromDegrees(ctx.lat.get(), ctx.lng.get())
val distances = pokestops.map {
val end = S2LatLng.fromDegrees(it.fortData.latitude, it.fortData.longitude)
currentPosition.getEarthDistance(end)
}
val totalDistance = distances.sum()
// Get random value between 0 and 1
val random = Math.random()
var cumulativeProbability = 0.0
for ((index, pokestop) in pokestops.withIndex()) {
// Calculate probabilty proportional to the closeness
val probability = (1 - distances[index] / totalDistance) / (pokestops.size - 1)
cumulativeProbability += probability
if (random <= cumulativeProbability) {
return pokestop
}
}
// should not happen
return pokestops.first()
}
// The speed changes always in the desired range, meaning if you already have a low speed and it goes lower, it will change less
private fun randomizeSpeed(speed: Double, speedRange: Double, ctx: Context): Double {
if (speedRange > speed) {
return speed
}
var speedDiff: Double = 0.0
val minSpeed = speed - speedRange
val maxSpeed = speed + speedRange
// random value between -1 and +1. There is always a 50:50 chance it will be slower or faster
// The speedChange is now twice math.random so that it prefers small/slow acceleration, but has still a low chance of abruptly changing (like a human)
val speedChangeNormalized = (Math.random() * 2 - 1) * Math.random()
if (speedChangeNormalized > 0) {
speedDiff = maxSpeed - ctx.walkingSpeed.toDouble()
} else if (speedChangeNormalized < 0) {
speedDiff = ctx.walkingSpeed.toDouble() - minSpeed
}
return ctx.walkingSpeed.toDouble() + speedChangeNormalized * speedDiff
}
}
| gpl-3.0 | a4e1bddcc8d3fa6c4d481b3a3b11b1e0 | 43.136 | 170 | 0.597064 | 4.40479 | false | false | false | false |
mdaniel/intellij-community | plugins/kotlin/completion/src/org/jetbrains/kotlin/idea/completion/ToFromOriginalFileMapper.kt | 6 | 3456 | // 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.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import kotlin.math.min
class ToFromOriginalFileMapper private constructor(
val originalFile: KtFile,
val syntheticFile: KtFile,
val completionOffset: Int
) {
companion object {
fun create(parameters: CompletionParameters): ToFromOriginalFileMapper {
val originalFile = parameters.originalFile as KtFile
val syntheticFile = parameters.position.containingFile as KtFile
return ToFromOriginalFileMapper(originalFile, syntheticFile, parameters.offset)
}
}
private val syntheticLength: Int
private val originalLength: Int
private val tailLength: Int
private val shift: Int
private val typeParamsOffset: Int
private val typeParamsShift: Int
//TODO: lazy initialization?
init {
val (originalText, syntheticText) = runReadAction {
originalFile.text to syntheticFile.text
}
typeParamsOffset = (0 until completionOffset).firstOrNull { originalText[it] != syntheticText[it] } ?: 0
if (typeParamsOffset > 0) {
val typeParamsEnd = (typeParamsOffset until completionOffset).first { originalText[typeParamsOffset] == syntheticText[it] }
typeParamsShift = typeParamsEnd - typeParamsOffset
} else {
typeParamsShift = 0
}
syntheticLength = syntheticText.length
originalLength = originalText.length
val minLength = min(originalLength, syntheticLength)
tailLength = (0 until minLength).firstOrNull {
syntheticText[syntheticLength - it - 1] != originalText[originalLength - it - 1]
} ?: minLength
shift = syntheticLength - originalLength
}
private fun toOriginalFile(offset: Int): Int? = when {
offset <= typeParamsOffset -> offset
offset in (typeParamsOffset + 1)..completionOffset -> offset - typeParamsShift
offset >= originalLength - tailLength -> offset - shift - typeParamsShift
else -> null
}
private fun toSyntheticFile(offset: Int): Int? = when {
offset <= typeParamsOffset -> offset
offset in (typeParamsOffset + 1)..completionOffset -> offset + typeParamsShift
offset >= originalLength - tailLength -> offset + shift + typeParamsShift
else -> null
}
fun <TElement : PsiElement> toOriginalFile(element: TElement): TElement? {
if (element.containingFile != syntheticFile) return element
val offset = toOriginalFile(element.startOffset) ?: return null
return PsiTreeUtil.findElementOfClassAtOffset(originalFile, offset, element::class.java, true)
}
fun <TElement : PsiElement> toSyntheticFile(element: TElement): TElement? {
if (element.containingFile != originalFile) return element
val offset = toSyntheticFile(element.startOffset) ?: return null
return PsiTreeUtil.findElementOfClassAtOffset(syntheticFile, offset, element::class.java, true)
}
}
| apache-2.0 | 92a086cf05040c04e36d3cc016b400f9 | 40.638554 | 158 | 0.704861 | 5.015965 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.