repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
53 values
size
stringlengths
2
6
content
stringlengths
73
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
977
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
GunoH/intellij-community
plugins/kotlin/j2k/old/tests/testData/fileOrElement/nullability/LocalValReassignment.kt
13
768
import org.jetbrains.annotations.* internal class A { /* rare nullable, handle with caution */ fun nullableString(): String? { return if (Math.random() > 0.999) { "a string" } else null } fun takesNotNullString(s: String) { println(s.substring(1)) } fun aVoid() { var aString: String? if (nullableString() != null) { aString = nullableString() if (aString != null) { for (i in 0..9) { takesNotNullString(aString!!) // Bang-bang here aString = nullableString() } } else { aString = "aaa" } } else { aString = "bbbb" } } }
apache-2.0
46deda7bba6524df6bf02bbafe0f7021
23.03125
67
0.457031
4.571429
false
false
false
false
GunoH/intellij-community
plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalProjectOptionsProvider.kt
8
5316
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.terminal import com.intellij.execution.configuration.EnvironmentVariablesData import com.intellij.execution.wsl.WslPath import com.intellij.ide.impl.isTrusted import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ProjectRootManager import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.util.text.Strings import com.intellij.util.xmlb.annotations.Property import java.io.File import kotlin.reflect.KMutableProperty0 import kotlin.reflect.KProperty @State(name = "TerminalProjectNonSharedOptionsProvider", storages = [(Storage(StoragePathMacros.WORKSPACE_FILE))]) class TerminalProjectOptionsProvider(val project: Project) : PersistentStateComponent<TerminalProjectOptionsProvider.State> { private val state = State() override fun getState(): State { return state } override fun loadState(newState: State) { state.startingDirectory = newState.startingDirectory state.shellPath = newState.shellPath state.envDataOptions = newState.envDataOptions } fun getEnvData(): EnvironmentVariablesData { return state.envDataOptions.get() } fun setEnvData(envData: EnvironmentVariablesData) { state.envDataOptions.set(envData) } class State { var startingDirectory: String? = null var shellPath: String? = null @get:Property(surroundWithTag = false, flat = true) var envDataOptions = EnvironmentVariablesDataOptions() } var startingDirectory: String? by ValueWithDefault(state::startingDirectory) { defaultStartingDirectory } val defaultStartingDirectory: String? get() { var directory: String? = null for (customizer in LocalTerminalCustomizer.EP_NAME.extensions) { try { directory = customizer.getDefaultFolder(project) if (directory != null) { break } } catch (e: Exception) { LOG.error("Exception during getting default folder", e) } } if (directory == null) { directory = getDefaultWorkingDirectory() } return if (directory != null) FileUtil.toSystemDependentName(directory) else null } private fun getDefaultWorkingDirectory(): String? { val roots = ProjectRootManager.getInstance(project).contentRoots @Suppress("DEPRECATION") val dir = if (roots.size == 1 && roots[0] != null && roots[0].isDirectory) roots[0] else project.baseDir return dir?.canonicalPath } var shellPath: String get() { val workingDirectoryLazy : Lazy<String?> = lazy { startingDirectory } val shellPath = when { isProjectLevelShellPath(workingDirectoryLazy::value) && project.isTrusted() -> state.shellPath else -> TerminalOptionsProvider.instance.shellPath } if (shellPath.isNullOrBlank()) { return findDefaultShellPath(workingDirectoryLazy::value) } return shellPath } set(value) { val workingDirectoryLazy : Lazy<String?> = lazy { startingDirectory } val valueToStore = Strings.nullize(value, findDefaultShellPath(workingDirectoryLazy::value)) if (isProjectLevelShellPath((workingDirectoryLazy::value))) { state.shellPath = valueToStore } else { TerminalOptionsProvider.instance.shellPath = valueToStore } } private fun isProjectLevelShellPath(workingDirectory: () -> String?): Boolean { return SystemInfo.isWindows && findWslDistributionName(workingDirectory()) != null } fun defaultShellPath(): String = findDefaultShellPath { startingDirectory } private fun findDefaultShellPath(workingDirectory: () -> String?): String { if (SystemInfo.isWindows) { val wslDistributionName = findWslDistributionName(workingDirectory()) if (wslDistributionName != null) { return "wsl.exe --distribution $wslDistributionName" } } val shell = System.getenv("SHELL") if (shell != null && File(shell).canExecute()) { return shell } if (SystemInfo.isUnix) { val bashPath = "/bin/bash" if (File(bashPath).exists()) { return bashPath } return "/bin/sh" } return "powershell.exe" } private fun findWslDistributionName(directory: String?): String? { return if (directory == null) null else WslPath.parseWindowsUncPath(directory)?.distributionId } companion object { private val LOG = Logger.getInstance(TerminalProjectOptionsProvider::class.java) @JvmStatic fun getInstance(project: Project): TerminalProjectOptionsProvider { return project.getService(TerminalProjectOptionsProvider::class.java) } } } class ValueWithDefault<T : String?>(val prop: KMutableProperty0<T?>, val default: () -> T) { operator fun getValue(thisRef: Any?, property: KProperty<*>): T { val value : T? = prop.get() return if (value !== null) value else default() } operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { prop.set(if (value == default() || value.isNullOrEmpty()) null else value) } }
apache-2.0
904fbcb5b3736bec8b990eb3001dda02
33.973684
140
0.709556
4.586713
false
false
false
false
Lizhny/BigDataFortuneTelling
baseuilib/src/main/java/com/bdft/baseuilib/base/BaseTitleBarActivity.kt
1
4335
package com.bdft.baseuilib.base import android.graphics.Color import android.support.annotation.* import android.text.TextUtils import android.view.View import android.view.ViewGroup import com.bdft.baselibrary.`interface`.OnDoubleClickListener import com.bdft.baselibrary.base.BaseActivity import com.bdft.baseuilib.R import com.bdft.baseuilib.widget.common.TitleBar /** * ${拥有titlebar的activity基类} * Created by spark_lizhy on 2017/10/25. */ abstract class BaseTitleBarActivity : BaseActivity() { protected var titleBar: TitleBar? = null override fun setContentView(layoutResID: Int) { super.setContentView(layoutResID) initTitlebar() } override fun setContentView(view: View?) { super.setContentView(view) initTitlebar() } override fun setContentView(view: View?, params: ViewGroup.LayoutParams?) { super.setContentView(view, params) initTitlebar() } fun setTitleText(@StringRes resId: Int) { if (titleBar != null && resId != 0) { titleBar?.setTitle(resId) } } fun getTitleText() { titleBar?.titleView?.text.toString() } fun setTitleMode(@TitleBar.TitleBarMode mode: Int) { if (titleBar != null) { titleBar?.currentMode = mode } } fun setTitleText(text: String) { if (titleBar != null && !TextUtils.isEmpty(text)) { titleBar?.setTitle(text) } } fun setTitleLeftText(@StringRes resId: Int) { if (titleBar != null && resId != 0) { titleBar?.setLeftText(resId) } } fun setTitleLeftText(text: String) { if (titleBar != null && !TextUtils.isEmpty(text)) { titleBar?.setLeftText(text) } } fun setTitleRightText(@StringRes resId: Int) { if (titleBar != null && resId != 0) { titleBar?.setRightText(resId) } } fun setTitleRightText(text: String) { if (titleBar != null && !TextUtils.isEmpty(text)) { titleBar?.setRightText(text) } } fun setLeftTextColor(@ColorRes resId: Int) { if (titleBar != null && resId != 0) { titleBar?.setLeftTextColor(resId) } } fun setRightTextColor(@ColorRes resId: Int) { if (titleBar != null && resId != 0) { titleBar?.setRigTextColor(resId) } } fun setTitleTextColor(@ColorRes resId: Int) { if (titleBar != null && resId != 0) { titleBar?.setTitleTextColor(resId) } } fun setTitleLeftIcon(@DrawableRes resId: Int) { if (titleBar != null) { titleBar?.setLeftIcon(resId) } } fun setTitleRightIcon(@DrawableRes resId: Int) { if (titleBar != null) { titleBar?.setRightIcon(resId) } } fun setTitleBackground(@ColorRes resId: Int) { if (titleBar != null) { titleBar?.setTitleBarBackground(resId) } } fun onTitleRightLongClick() { } fun onTitleLeftLongClick() { } fun onTitleRightClick() { } fun onTitleLeftClick() { finish() } fun onTitleDoubleClick() { } fun onTitleSingleClick() { } private fun initTitlebar() { titleBar = findView(R.id.title_bar_view) if (titleBar != null) { titleBar?.setOnClickListener(object : OnDoubleClickListener() { override fun onSingleClick() { onTitleSingleClick() } override fun onDoubleClick(view: View) { onTitleDoubleClick() } }) titleBar?.onTitleBarClickListener = mTitleBarClickListener } } private var mTitleBarClickListener = object : TitleBar.OnTitleBarClickListener { override fun onLeftClick(v: View?, isLongClick: Boolean): Boolean { if (isLongClick) onTitleLeftLongClick() else onTitleLeftClick() return false } override fun onRightClick(v: View?, isLongClick: Boolean): Boolean { if (isLongClick) onTitleRightLongClick() else onTitleRightClick() return false } } }
apache-2.0
9c4b70afd272cb41f1a2bf5becf38e5f
24.00578
84
0.577803
4.562236
false
false
false
false
GunoH/intellij-community
plugins/kotlin/j2k/new/src/org/jetbrains/kotlin/nj2k/conversions/StaticsToCompanionExtractConversion.kt
2
2039
// 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.nj2k.conversions import org.jetbrains.kotlin.nj2k.NewJ2kConverterContext import org.jetbrains.kotlin.nj2k.RecursiveApplicableConversionBase import org.jetbrains.kotlin.nj2k.declarationList import org.jetbrains.kotlin.nj2k.getOrCreateCompanionObject import org.jetbrains.kotlin.nj2k.tree.* class StaticsToCompanionExtractConversion(context: NewJ2kConverterContext) : RecursiveApplicableConversionBase(context) { override fun applyToElement(element: JKTreeElement): JKTreeElement { if (element !is JKClass) return recurse(element) if (element.classKind == JKClass.ClassKind.COMPANION || element.classKind == JKClass.ClassKind.OBJECT) return element val statics = element.declarationList.filter { declaration -> declaration is JKOtherModifiersOwner && declaration.hasOtherModifier(OtherModifier.STATIC) || declaration is JKJavaStaticInitDeclaration } if (statics.isEmpty()) return recurse(element) val companion = element.getOrCreateCompanionObject() element.classBody.declarations -= statics companion.classBody.declarations += statics.map { declaration -> when (declaration) { is JKJavaStaticInitDeclaration -> declaration.toKtInitDeclaration() else -> declaration } }.onEach { declaration -> if (declaration is JKOtherModifiersOwner) { declaration.otherModifierElements -= declaration.elementByModifier(OtherModifier.STATIC)!! } context.externalCodeProcessor.getMember(declaration)?.let { it.isStatic = true } } return recurse(element) } private fun JKJavaStaticInitDeclaration.toKtInitDeclaration() = JKKtInitDeclaration(::block.detached()).withFormattingFrom(this) }
apache-2.0
bd8ff1e09c4f7fe7baaa3f5a0c0543f7
47.547619
158
0.713095
5.268734
false
false
false
false
smmribeiro/intellij-community
platform/collaboration-tools/src/com/intellij/collaboration/auth/OAuthCallbackHandlerBase.kt
1
1966
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.collaboration.auth import com.intellij.collaboration.auth.services.OAuthService import com.intellij.util.Url import io.netty.buffer.Unpooled import io.netty.channel.ChannelHandlerContext import io.netty.handler.codec.http.* import org.jetbrains.ide.RestService import org.jetbrains.io.response import org.jetbrains.io.send /** * The base class of the callback handler for authorization services */ abstract class OAuthCallbackHandlerBase : RestService() { protected val service: OAuthService<*> get() = oauthService() abstract fun oauthService(): OAuthService<*> override fun getServiceName(): String = service.name override fun execute(urlDecoder: QueryStringDecoder, request: FullHttpRequest, context: ChannelHandlerContext): String? { val isCodeAccepted = service.handleServerCallback(urlDecoder.path(), urlDecoder.parameters()) when (val handleResult = handleAcceptCode(isCodeAccepted)) { is AcceptCodeHandleResult.Page -> { response( "text/html", Unpooled.wrappedBuffer(handleResult.html.toByteArray(Charsets.UTF_8)) ).send(context.channel(), request) } is AcceptCodeHandleResult.Redirect -> sendRedirect(request, context, handleResult.url) } return null } protected abstract fun handleAcceptCode(isAccepted: Boolean): AcceptCodeHandleResult private fun sendRedirect(request: FullHttpRequest, context: ChannelHandlerContext, url: Url) { val headers = DefaultHttpHeaders().set(HttpHeaderNames.LOCATION, url.toExternalForm()) HttpResponseStatus.FOUND.send(context.channel(), request, null, headers) } protected sealed class AcceptCodeHandleResult { class Redirect(val url: Url) : AcceptCodeHandleResult() class Page(val html: String) : AcceptCodeHandleResult() } }
apache-2.0
a7fad151b67bd69f6f93ecfa955d7315
38.32
158
0.761953
4.529954
false
false
false
false
smmribeiro/intellij-community
platform/platform-impl/src/com/intellij/ide/util/TipsUsageManager.kt
6
7228
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.util import com.intellij.featureStatistics.FeatureDescriptor import com.intellij.featureStatistics.FeaturesRegistryListener import com.intellij.featureStatistics.ProductivityFeaturesRegistry import com.intellij.ide.TipsOfTheDayUsagesCollector import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.util.ResourceUtil import com.intellij.util.text.DateFormatUtil import org.jetbrains.annotations.ApiStatus import java.awt.EventQueue import kotlin.random.Random @ApiStatus.Internal @State(name = "ShownTips", storages = [Storage(value = "shownTips.xml", roamingType = RoamingType.DISABLED)]) internal class TipsUsageManager : PersistentStateComponent<TipsUsageManager.State> { companion object { @JvmStatic fun getInstance(): TipsUsageManager = service() } private val shownTips: MutableMap<String, Long> = mutableMapOf() private val utilityHolder = TipsUtilityHolder.readFromResourcesAndCreate() init { ApplicationManager.getApplication().messageBus.connect().subscribe(FeaturesRegistryListener.TOPIC, TipsUsageListener()) } override fun getState(): State = State(shownTips) override fun loadState(state: State) { shownTips.putAll(state.shownTips) } fun sortTips(tips: List<TipAndTrickBean>, experimentType: TipsUtilityExperiment): RecommendationDescription { val usedTips = mutableSetOf<TipAndTrickBean>() val unusedTips = mutableSetOf<TipAndTrickBean>() ProductivityFeaturesRegistry.getInstance()?.let { featuresRegistry -> for (featureId in featuresRegistry.featureIds) { val feature = featuresRegistry.getFeatureDescriptor(featureId) val tip = TipUIUtil.getTip(feature) ?: continue if (!tips.contains(tip)) continue if (System.currentTimeMillis() - feature.lastTimeUsed < DateFormatUtil.MONTH) { usedTips.add(tip) unusedTips.remove(tip) // some tips correspond to multiple features } else if (!usedTips.contains(tip)) { unusedTips.add(tip) } } } val otherTips = tips.toSet() - (usedTips + unusedTips) val resultTips = when (experimentType) { TipsUtilityExperiment.BY_TIP_UTILITY -> { val sortedByUtility = utilityHolder.sampleTips(unusedTips + usedTips) sortedByUtility + otherTips.shuffled() } TipsUtilityExperiment.BY_TIP_UTILITY_IGNORE_USED -> { val sortedByUtility = utilityHolder.sampleTips(unusedTips) sortedByUtility + otherTips.shuffled() + usedTips.shuffled() } TipsUtilityExperiment.RANDOM_IGNORE_USED -> { unusedTips.shuffled() + otherTips.shuffled() + usedTips.shuffled() } } return RecommendationDescription(experimentType.toString(), resultTips, utilityHolder.getMetadataVersion()) } fun fireTipShown(tip: TipAndTrickBean) { shownTips[tip.fileName] = System.currentTimeMillis() } fun filterShownTips(tips: List<TipAndTrickBean>): List<TipAndTrickBean> { val resultTips = tips.toMutableList() for (tipFile in shownTips.keys.shuffled()) { resultTips.find { it.fileName == tipFile }?.let { tip -> resultTips.remove(tip) resultTips.add(tip) } } if (wereTipsShownToday()) { shownTips.maxByOrNull { it.value }?.let { resultTips.find { tip -> tip.fileName == it.key }?.let { tip -> resultTips.remove(tip) resultTips.add(0, tip) } } } return resultTips } fun wereTipsShownToday(): Boolean = System.currentTimeMillis() - (shownTips.maxOfOrNull { it.value } ?: 0) < DateFormatUtil.DAY data class State(var shownTips: Map<String, Long> = emptyMap()) private class TipsUtilityHolder private constructor(private val tips2utility: Map<String, Double>) { companion object { private val LOG = logger<TipsUtilityHolder>() private const val TIPS_UTILITY_FILE = "tips_utility.csv" fun create(tipsUtility: Map<String, Double>): TipsUtilityHolder = TipsUtilityHolder(tipsUtility) fun readFromResourcesAndCreate(): TipsUtilityHolder = create(readTipsUtility()) private fun readTipsUtility() : Map<String, Double> { assert(!EventQueue.isDispatchThread() || ApplicationManager.getApplication().isUnitTestMode) val classLoader = TipsUtilityHolder::class.java.classLoader val lines = ResourceUtil.getResourceAsBytes(TIPS_UTILITY_FILE, classLoader)?.decodeToString()?.reader()?.readLines() if (lines == null) { LOG.error("Can't read resource file with tips utilities: $TIPS_UTILITY_FILE") return emptyMap() } return lines.associate { val values = it.split(",") Pair(values[0], values[1].toDoubleOrNull() ?: 0.0) } } } fun getMetadataVersion(): String = "0.1" fun sampleTips(tips: Iterable<TipAndTrickBean>): List<TipAndTrickBean> { val (knownTips, unknownTips) = tips.map { Pair(it, getTipUtility(it)) }.partition { it.second >= 0 } val result = mutableListOf<TipAndTrickBean>() result.sampleByUtility(knownTips) result.sampleUnknown(unknownTips) return result } private fun MutableList<TipAndTrickBean>.sampleByUtility(knownTips: List<Pair<TipAndTrickBean, Double>>) { val sortedTips = knownTips.sortedByDescending { it.second }.toMutableSet() var totalUtility = sortedTips.sumByDouble { it.second } for (i in 0 until sortedTips.size) { var cumulativeUtility = 0.0 if (totalUtility <= 0.0) { this.addAll(sortedTips.map { it.first }.shuffled()) break } val prob = Random.nextDouble(totalUtility) for (tip2utility in sortedTips) { val tipUtility = tip2utility.second cumulativeUtility += tipUtility if (prob <= cumulativeUtility) { this.add(tip2utility.first) totalUtility -= tipUtility sortedTips.remove(tip2utility) break } } } } private fun MutableList<TipAndTrickBean>.sampleUnknown(unknownTips: List<Pair<TipAndTrickBean, Double>>) { val unknownProb = unknownTips.size.toDouble() / (this.size + unknownTips.size) var currentIndex = 0 for (unknownTip in unknownTips.shuffled()) { while (currentIndex < this.size && Random.nextDouble() > unknownProb) { currentIndex++ } this.add(currentIndex, unknownTip.first) currentIndex++ } } private fun getTipUtility(tip: TipAndTrickBean): Double { return tips2utility.getOrDefault(tip.fileName, -1.0) } } private inner class TipsUsageListener : FeaturesRegistryListener { override fun featureUsed(feature: FeatureDescriptor) { TipUIUtil.getTip(feature)?.let { tip -> shownTips[tip.fileName]?.let { timestamp -> TipsOfTheDayUsagesCollector.triggerTipUsed(tip.fileName, System.currentTimeMillis() - timestamp) } } } } }
apache-2.0
fa3fde1a5802305ae6d5cdd50e170a1d
38.939227
158
0.693138
4.437078
false
false
false
false
testIT-LivingDoc/livingdoc2
livingdoc-reports/src/test/kotlin/org/livingdoc/reports/confluence/tree/elements/ConfluenceReportTest.kt
2
10228
package org.livingdoc.reports.confluence.tree.elements import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.livingdoc.repositories.model.TestDataDescription import org.livingdoc.repositories.model.decisiontable.DecisionTable import org.livingdoc.repositories.model.decisiontable.Field import org.livingdoc.repositories.model.decisiontable.Header import org.livingdoc.repositories.model.decisiontable.Row import org.livingdoc.repositories.model.scenario.Scenario import org.livingdoc.repositories.model.scenario.Step import org.livingdoc.results.Status import org.livingdoc.results.documents.DocumentResult import org.livingdoc.results.examples.decisiontables.DecisionTableResult import org.livingdoc.results.examples.decisiontables.FieldResult import org.livingdoc.results.examples.decisiontables.RowResult import org.livingdoc.results.examples.scenarios.ScenarioResult import org.livingdoc.results.examples.scenarios.StepResult internal class ConfluenceReportTest { @Test fun `decisionTableResult is rendered correctly`() { val headerA = Header("a") val headerB = Header("b") val headerAPlusB = Header("a + b = ?") val row1 = Row( mapOf( headerA to Field("2"), headerB to Field("3"), headerAPlusB to Field("6") ) ) val row2 = Row( mapOf( headerA to Field("5"), headerB to Field("6"), headerAPlusB to Field("11") ) ) val row3 = Row( mapOf( headerA to Field("2"), headerB to Field("1"), headerAPlusB to Field("") ) ) val decisionTable = DecisionTable( listOf(headerA, headerB, headerAPlusB), listOf(row1, row2, row3), TestDataDescription("Title", false, "descriptive text") ) val rowResult1 = RowResult.Builder().withRow(row1) .withFieldResult( headerA, FieldResult.Builder() .withValue("2") .withStatus(Status.Executed) .build() ) .withFieldResult( headerB, FieldResult.Builder() .withValue("3") .withStatus(Status.Disabled("Disabled test")) .build() ) .withFieldResult( headerAPlusB, FieldResult.Builder() .withValue("6") .withStatus(Status.Failed(mockk(relaxed = true))) .build() ) .withStatus(Status.Executed) val rowResult2 = RowResult.Builder().withRow(row2) .withFieldResult( headerA, FieldResult.Builder() .withValue("5") .withStatus(Status.Skipped) .build() ) .withFieldResult( headerB, FieldResult.Builder() .withValue("6") .withStatus(Status.Manual) .build() ) .withFieldResult( headerAPlusB, FieldResult.Builder() .withValue("11") .withStatus(Status.Exception(mockk(relaxed = true))) .build() ) .withStatus(Status.Executed) val rowResult3 = RowResult.Builder().withRow(row3) .withFieldResult( headerA, FieldResult.Builder() .withValue("2") .withStatus(Status.Executed) .build() ) .withFieldResult( headerB, FieldResult.Builder() .withValue("1") .withStatus(Status.Executed) .build() ) .withFieldResult( headerAPlusB, FieldResult.Builder() .withValue("") .withStatus(Status.ReportActualResult("3")) .build() ) .withStatus(Status.Executed) val decisionTableResult = DecisionTableResult.Builder().withDecisionTable(decisionTable) decisionTableResult .withRow(rowResult1.build()) .withRow(rowResult2.build()) .withRow(rowResult3.build()) .withStatus(Status.Failed(mockk(relaxed = true))) val documentResult = DocumentResult.Builder() .withDocumentClass(ConfluenceReportTest::class.java) .withStatus(Status.Executed) .withResult(decisionTableResult.build()) .withTags(emptyList()) .build() val renderResult = ConfluenceReport(documentResult).toString() assertThat(renderResult).isEqualToIgnoringWhitespace( """ <h2>Title</h2> <div> <p>descriptive text</p> </div> <table> <thead> <tr> <th>a</th> <th>b</th> <th>a + b = ?</th> </tr> </thead> <tbody> <tr> <td class="highlight-green">2</td> <td class="highlight-grey">3</td> <td class="highlight-red">6 <ac:structured-macro ac:name="warning"> <ac:rich-text-body> <pre></pre> </ac:rich-text-body> </ac:structured-macro> </td> </tr> <tr> <td class="highlight-grey">5</td> <td class="highlight-yellow">6</td> <td class="highlight-red">11 <ac:structured-macro ac:name="warning"> <ac:rich-text-body> <pre></pre> </ac:rich-text-body> </ac:structured-macro> </td> </tr> <tr> <td class="highlight-green">2</td> <td class="highlight-green">1</td> <td class="highlight-blue">3</td> </tr> </tbody> </table> """ ) } @Test fun `scenarioResult is rendered correctly`() { val stepResultA = StepResult.Builder().withValue("A").withStatus(Status.Executed).build() val stepResultB = StepResult.Builder().withValue("B").withStatus(Status.Manual).build() val stepResultC = StepResult.Builder().withValue("C").withStatus(Status.Skipped).build() val stepResultD = StepResult.Builder().withValue("D").withStatus(Status.Failed(mockk())).build() val stepResultE = StepResult.Builder().withValue("E").withStatus(Status.Exception(mockk())).build() val documentResult = DocumentResult.Builder() .withDocumentClass(ConfluenceReportTest::class.java) .withStatus(Status.Executed) .withResult( ScenarioResult.Builder() .withStep(stepResultA) .withStep(stepResultB) .withStep(stepResultC) .withStep(stepResultD) .withStep(stepResultE) .withStatus(Status.Executed) .withScenario( Scenario( listOf( Step("A"), Step("B"), Step("C"), Step("D"), Step("E") ), TestDataDescription("Title", false, "descriptive text") ) ) .build() ).withTags(emptyList()) .build() val renderResult = ConfluenceReport(documentResult).toString() assertThat(renderResult).isEqualToIgnoringWhitespace( """ <h2>Title</h2> <div> <p>descriptive text</p> </div> <ul> <li style="color: rgb(0, 128, 0);">A</li> <li style="color: rgb(255, 102, 0);">B</li> <li style="color: rgb(165, 173, 186);">C</li> <li style="color: rgb(255, 0, 0);">D</li> <li style="color: rgb(255, 0, 0);">E</li> </ul> """ ) } @Test fun `tags are rendered correctly`() { val documentResult = DocumentResult.Builder() .withStatus(Status.Executed) .withDocumentClass(ConfluenceReportTest::class.java) .withTags(listOf("slow", "api")) .build() val renderResult = ConfluenceReport(documentResult).toString() assertThat(renderResult).isEqualToIgnoringWhitespace( """ <h2> <ac:structured-macro ac:name="status" ac:schema-version="1"> <ac:parameter ac:name="colour">Blue</ac:parameter> <ac:parameter ac:name="title">slow</ac:parameter> </ac:structured-macro> <ac:structured-macro ac:name="status" ac:schema-version="1"> <ac:parameter ac:name="colour">Blue</ac:parameter> <ac:parameter ac:name="title">api</ac:parameter> </ac:structured-macro> </h2> """ ) } }
apache-2.0
83e635fc655e313dc2c4f1f49790af47
37.022305
107
0.470278
5.088557
false
false
false
false
SUPERCILEX/FirebaseUI-Android
internal/lint/src/test/java/com/firebaseui/lint/NonGlobalIdDetectorTest.kt
1
1819
package com.firebaseui.lint import com.android.tools.lint.checks.infrastructure.TestFiles.xml import com.firebaseui.lint.LintTestHelper.configuredLint import com.firebaseui.lint.NonGlobalIdDetector.Companion.NON_GLOBAL_ID import org.junit.Test class NonGlobalIdDetectorTest { @Test fun `Passes on valid view id`() { configuredLint() .files(xml("res/layout/layout.xml", """ |<RelativeLayout | xmlns:android="http://schemas.android.com/apk/res/android" | android:id="@+id/valid"/>""".trimMargin())) .issues(NON_GLOBAL_ID) .run() .expectClean() } @Test fun `Fails on invalid view id`() { configuredLint() .files(xml("res/layout/layout.xml", """ |<ScrollView | xmlns:android="http://schemas.android.com/apk/res/android" | android:id="@id/invalid"/>""".trimMargin())) .issues(NON_GLOBAL_ID) .run() .expect(""" |res/layout/layout.xml:3: Error: Use of non-global @id in layout file, consider using @+id instead for compatibility with aapt1. [NonGlobalIdInLayout] | android:id="@id/invalid"/> | ~~~~~~~~~~~~~~~~~~~~~~~~ |1 errors, 0 warnings""".trimMargin()) .expectFixDiffs(""" |Fix for res/layout/layout.xml line 2: Fix id: |@@ -3 +3 |- android:id="@id/invalid"/> |@@ -4 +3 |+ android:id="@+id/invalid"/> |""".trimMargin()) } }
apache-2.0
2869fd3e2c30783999d2eca03bd72214
41.302326
174
0.472787
4.688144
false
true
false
false
DuckDeck/AndroidDemo
app/src/main/java/stan/androiddemo/project/petal/HttpUtiles/OkHttpHelper.kt
1
1128
package stan.androiddemo.project.petal.HttpUtiles import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import stan.androiddemo.tool.Logger /** * Created by stanhu on 11/8/2017. */ class OkHttpHelper{ companion object { val progressBean = ProgressBean() val mProgressHandler:ProgressHandler? = null fun addLogClient(builder:OkHttpClient.Builder):OkHttpClient.Builder{ val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BASIC builder.addInterceptor(logging) return builder } fun addProgressClient(builder:OkHttpClient.Builder,listener:OnProgressResponseListener):OkHttpClient.Builder{ builder.addNetworkInterceptor { Logger.d("start intercept") val originalResponse = it.proceed(it.request()) return@addNetworkInterceptor originalResponse.newBuilder().body( ProgressResponseBody(originalResponse.body(),listener) ).build() } return builder } } }
mit
b2d552d6762ace05dfb39cfb0dd591fd
34.25
117
0.663121
5.475728
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/settings/segwit/EnableSegWitUpdate.kt
1
2304
/** * BreadWallet * * Created by Pablo Budelli <pablo.budelli@breadwallet.com> on 11/05/19. * Copyright (c) 2019 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.settings.segwit import com.breadwallet.ui.settings.segwit.EnableSegWit.E import com.breadwallet.ui.settings.segwit.EnableSegWit.F import com.breadwallet.ui.settings.segwit.EnableSegWit.M import com.spotify.mobius.Next import com.spotify.mobius.Next.dispatch import com.spotify.mobius.Next.next import com.spotify.mobius.Update object EnableSegWitUpdate : Update<M, E, F>, EnableSegWitUpdateSpec { override fun update( model: M, event: E ): Next<M, F> = patch(model, event) override fun onEnableClick(model: M): Next<M, F> = next(model.copy(state = M.State.CONFIRMATION)) override fun onContinueClicked(model: M): Next<M, F> = next( model.copy(state = M.State.DONE), setOf(F.EnableSegWit) ) override fun onCancelClicked(model: M): Next<M, F> = next(model.copy(state = M.State.ENABLE)) override fun onBackClicked(model: M): Next<M, F> = dispatch(setOf(F.GoBack)) override fun onDoneClicked(model: M): Next<M, F> = dispatch(setOf(F.GoToHome)) }
mit
8f408197dfec36441067c3d1686bc5a3
38.724138
80
0.723524
3.898477
false
false
false
false
breadwallet/breadwallet-android
app/src/main/java/com/breadwallet/ui/staking/StakingController.kt
1
14857
/** * BreadWallet * * Created by Drew Carlson <drew.carlson@breadwallet.com> on 10/30/20. * Copyright (c) 2020 breadwallet LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.breadwallet.ui.uistaking import android.content.res.ColorStateList import android.content.res.Resources import android.os.Bundle import android.view.View import androidx.core.os.bundleOf import androidx.core.view.isVisible import androidx.core.view.isInvisible import com.bluelinelabs.conductor.RouterTransaction import com.breadwallet.R import com.breadwallet.breadbox.formatCryptoForUi import com.breadwallet.databinding.ControllerConfirmTxDetailsBinding import com.breadwallet.databinding.ControllerStakingBinding import com.breadwallet.tools.animation.SlideDetector import com.breadwallet.ui.BaseController import com.breadwallet.ui.BaseMobiusController import com.breadwallet.ui.ViewEffect import com.breadwallet.ui.auth.AuthMode import com.breadwallet.ui.auth.AuthenticationController import com.breadwallet.ui.changehandlers.BottomSheetChangeHandler import com.breadwallet.ui.changehandlers.DialogChangeHandler import com.breadwallet.ui.flowbind.clicks import com.breadwallet.ui.flowbind.textChanges import com.breadwallet.ui.uistaking.Staking.E import com.breadwallet.ui.uistaking.Staking.F import com.breadwallet.ui.uistaking.Staking.M import com.breadwallet.ui.uistaking.Staking.M.ViewValidator.State.PENDING_STAKE import com.breadwallet.ui.uistaking.Staking.M.ViewValidator.State.PENDING_UNSTAKE import com.breadwallet.ui.uistaking.Staking.M.ViewValidator.State.STAKED import com.breadwallet.ui.web.WebController import com.platform.HTTPServer import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.merge import org.kodein.di.direct import org.kodein.di.erased.instance import java.math.BigDecimal import java.util.Locale interface ConfirmationListener { fun onConfirmed() fun onCancelled() } private const val CURRENCY_ID = "currency_id" class StakingController( bundle: Bundle? = null ) : BaseMobiusController<M, E, F>(bundle), ConfirmationListener, AuthenticationController.Listener { constructor( currencyId: String ) : this(bundleOf(CURRENCY_ID to currencyId)) init { overridePopHandler(BottomSheetChangeHandler()) overridePushHandler(BottomSheetChangeHandler()) } override val defaultModel: M = M.Loading() override val init = StakingInit override val update = StakingUpdate override val flowEffectHandler get() = createStakingHandler( context = direct.instance(), currencyId = arg(CURRENCY_ID), breadBox = direct.instance(), userManager = direct.instance() ) private val binding by viewBinding(ControllerStakingBinding::inflate) override fun onCreateView(view: View) { super.onCreateView(view) binding.layoutHeader.setOnTouchListener(SlideDetector(router, view)) } override fun bindView(modelFlow: Flow<M>): Flow<E> { return with(binding) { merge( buttonStake.clicks().map { E.OnStakeClicked }, buttonPaste.clicks().map { E.OnPasteClicked }, buttonClose.clicks().map { E.OnCloseClicked }, buttonCancel.clicks().map { E.OnCancelClicked }, buttonUnstake.clicks().map { E.OnUnstakeClicked }, buttonConfirm.clicks().map { E.OnStakeClicked }, buttonChangeValidator.clicks().map { E.OnChangeClicked }, inputAddress.textChanges().map { E.OnAddressChanged(it) }, buttonFaq.clicks().map { E.OnHelpClicked } ) } } override fun handleViewEffect(effect: ViewEffect) { when (effect) { is F.ConfirmTransaction -> { val controller = ConfirmationController( effect.currencyCode, effect.address, effect.balance, effect.fee ) router.pushController(RouterTransaction.with(controller)) } is F.Help -> { val supportBaseUrl = HTTPServer.getPlatformUrl(HTTPServer.URL_SUPPORT) val url = "$supportBaseUrl/article?slug=staking" router.pushController(RouterTransaction.with(WebController(url))) } is F.Close -> router.popCurrentController() } } override fun M.render() { val res = checkNotNull(resources) with(binding) { ifChanged(M::currencyCode) { labelTitle.text = res.getString( R.string.Staking_title, currencyCode.toUpperCase(Locale.ROOT) ) } when (this@render) { is M.Loading -> { loadingView.isVisible = true buttonStake.isVisible = false labelStatus.isVisible = false layoutChange.isVisible = false buttonPaste.isVisible = false layoutConfirmChange.isVisible = false inputLayoutAddress.isVisible = false } is M.SetValidator -> renderSetBaker(res) is M.ViewValidator -> renderViewBaker(res) } } } private fun M.SetValidator.renderSetBaker(res: Resources) { val theme = checkNotNull(activity).theme with(binding) { loadingView.isVisible = false labelAddress.isVisible = false inputAddress.isEnabled = true inputLayoutAddress.isVisible = true ifChanged(M.SetValidator::isCancellable) { layoutChange.isVisible = false buttonStake.isVisible = !isCancellable layoutConfirmChange.isVisible = isCancellable } ifChanged(M.SetValidator::address) { buttonPaste.isVisible = address.isBlank() if (address.isNullOrBlank() || (address.isNotBlank() && inputAddress.text.isNullOrBlank())) { inputAddress.setText(address) } } ifChanged(M.SetValidator::isAddressValid, M.SetValidator::canSubmitTransfer) { buttonConfirm.isEnabled = canSubmitTransfer inputLayoutAddress.apply { if (isAddressValid) { error = null helperText = if (canSubmitTransfer) { "Valid baker address!" } else null setHelperTextColor( ColorStateList.valueOf( res.getColor(com.breadwallet.R.color.green_text, theme) ) ) } else { error = "Invalid baker address" helperText = null setHelperTextColor(null) } } } ifChanged(M.SetValidator::transactionError) { labelStatus.isInvisible = transactionError == null when (transactionError) { is M.TransactionError.Unknown, M.TransactionError.TransferFailed -> { labelStatus.setText(com.breadwallet.R.string.Transaction_failed) } M.TransactionError.FeeEstimateFailed -> { labelStatus.setText(com.breadwallet.R.string.Send_noFeesError) } null -> { labelStatus.text = null } } } ifChanged(M.SetValidator::isAuthenticating) { handleIsAuthenticating(it, isFingerprintEnabled, res) } } } private fun M.ViewValidator.renderViewBaker(res: Resources) { val theme = checkNotNull(activity).theme with(binding) { ifChanged(M::address) { labelAddress.isVisible = true labelAddress.text = address } ifChanged(M.ViewValidator::state) { labelStatus.isVisible = true layoutChange.isVisible = true loadingView.isVisible = false buttonPaste.isVisible = false buttonStake.isVisible = false layoutConfirmChange.isVisible = false inputLayoutAddress.isVisible = false when (state) { PENDING_STAKE, PENDING_UNSTAKE -> { buttonUnstake.isEnabled = false buttonChangeValidator.isEnabled = false labelStatus.setText(com.breadwallet.R.string.Transaction_pending) labelStatus.setTextColor(res.getColor(com.breadwallet.R.color.ui_accent, theme)) } STAKED -> { buttonUnstake.isEnabled = true buttonChangeValidator.isEnabled = true labelStatus.setText(com.breadwallet.R.string.Staking_statusStaked) labelStatus.setTextColor(res.getColor(com.breadwallet.R.color.green_text, theme)) } } } ifChanged(M.ViewValidator::isAuthenticating) { handleIsAuthenticating(it, isFingerprintEnabled, res) } } } private fun handleIsAuthenticating( isAuthenticating: Boolean, isFingerprintAuthEnable: Boolean, res: Resources ) { val isAuthVisible = router.backstack.lastOrNull()?.controller is AuthenticationController if (isAuthenticating && !isAuthVisible) { val authenticationMode = if (isFingerprintAuthEnable) { AuthMode.USER_PREFERRED } else { AuthMode.PIN_REQUIRED } val controller = AuthenticationController( mode = authenticationMode, title = res.getString(R.string.VerifyPin_touchIdMessage), message = res.getString(R.string.VerifyPin_authorize) ) controller.targetController = this@StakingController router.pushController(RouterTransaction.with(controller)) } } override fun onConfirmed() { eventConsumer.accept(E.OnTransactionConfirmClicked) } override fun onCancelled() { eventConsumer.accept(E.OnTransactionCancelClicked) } override fun onAuthenticationSuccess() { eventConsumer.accept(E.OnAuthSuccess) } override fun onAuthenticationCancelled() { eventConsumer.accept(E.OnAuthCancelled) } class ConfirmationController(args: Bundle) : BaseController(args) { constructor( currencyCode: String, address: String?, balance: BigDecimal, feeEstimate: BigDecimal ) : this(bundleOf( "currencyCode" to currencyCode, "address" to address, "balance" to balance, "feeEstimate" to feeEstimate )) private val currencyCode: String = arg("currencyCode") private val address: String? = argOptional("address") private val balance: BigDecimal = arg("balance") private val feeEstimate: BigDecimal = arg("feeEstimate") init { overridePopHandler(DialogChangeHandler()) overridePushHandler(DialogChangeHandler()) } private val binding by viewBinding(ControllerConfirmTxDetailsBinding::inflate) override fun onAttach(view: View) { super.onAttach(view) with(binding) { toLabel.isVisible = false toAddress.isVisible = false amountLabel.isVisible = false amountValue.isVisible = false totalCostLabel.isVisible = false totalCostValue.isVisible = false hederaMemoLabel.isVisible = false hederaMemoValue.isVisible = false destinationTagLabel.isVisible = false destinationTagValue.isVisible = false processingTimeLabel.text = view.resources.getString( com.breadwallet.R.string.Confirmation_processingTime, view.resources.getString( com.breadwallet.R.string.FeeSelector_ethTime ) ) sendLabel.setText(when (address) { null -> com.breadwallet.R.string.Staking_unstake else -> com.breadwallet.R.string.Staking_stake }) sendValue.text = balance.formatCryptoForUi(currencyCode) networkFeeValue.text = feeEstimate.formatCryptoForUi(currencyCode) val listener = findListener<ConfirmationListener>() val cancel = View.OnClickListener { listener?.onCancelled() router.popController(this@ConfirmationController) } okBtn.setOnClickListener { listener?.onConfirmed() router.popController(this@ConfirmationController) } closeBtn.setOnClickListener(cancel) cancelBtn.setOnClickListener(cancel) } } override fun handleBack(): Boolean { findListener<ConfirmationListener>()?.onCancelled() return super.handleBack() } } }
mit
13e73485ed3f93552d3ad6c7c736165a
37.994751
109
0.603823
5.20021
false
false
false
false
JakeWharton/dex-method-list
diffuse/src/main/kotlin/com/jakewharton/diffuse/report/text/JarDiffTextReport.kt
1
1255
package com.jakewharton.diffuse.report.text import com.jakewharton.diffuse.ArchiveFile.Type import com.jakewharton.diffuse.diff.JarDiff import com.jakewharton.diffuse.diff.toDetailReport import com.jakewharton.diffuse.diff.toSummaryTable import com.jakewharton.diffuse.report.DiffReport internal class JarDiffTextReport(private val jarDiff: JarDiff) : DiffReport { override fun write(appendable: Appendable) { appendable.apply { append("OLD: ") appendln(jarDiff.oldJar.filename) append("NEW: ") appendln(jarDiff.newJar.filename) appendln() appendln(jarDiff.archive.toSummaryTable("JAR", Type.JAR_TYPES)) appendln() appendln(jarDiff.jars.toSummaryTable("CLASSES")) if (jarDiff.archive.changed) { appendln() appendln("=================") appendln("==== JAR ====") appendln("=================") appendln(jarDiff.archive.toDetailReport()) } if (jarDiff.jars.changed) { appendln() appendln("=====================") appendln("==== CLASSES ====") appendln("=====================") appendln(jarDiff.jars.toDetailReport()) } } } override fun toString() = buildString { write(this) } }
apache-2.0
fe327f501495c20bba5d70b1847443c0
30.375
77
0.616733
4.450355
false
false
false
false
luhaoaimama1/JavaZone
JavaTest_Zone/src/ktshare/third/NoNullTest.kt
1
614
package ktshare.third /** * 非空 3种那个都行 * 当然能用 懒加载属性 或者 延迟加载属性更好了 */ fun nullState0(var1: String?) { var1?.let { // 做逻辑 } } fun nullState1(var1: String?) { val sVar = var1 ?: return val intVar = var1 as? Int ?: return // 做逻辑 } fun nullState2(var1: String?) { if (var1 == null) { return } var1[1] } fun nullState3(var1: String?) { //android 好使 可能是高版本的问题 return是可以添加let等方法的 // val sideTask = var1 ?: return let { // println("abc") // } }
epl-1.0
4a100d7e2f1b433d5cb2ee867dfe017b
14.393939
45
0.559055
2.527363
false
false
false
false
spinnaker/kork
kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/update/release/release_plugins.kt
3
3616
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package com.netflix.spinnaker.kork.plugins.update.release import com.netflix.spinnaker.kork.api.plugins.remote.RemoteExtensionConfig import com.netflix.spinnaker.kork.plugins.update.internal.SpinnakerPluginInfo import io.mockk.mockk import java.time.Instant import java.util.Date val plugin1 = SpinnakerPluginInfo().apply { id = "com.netflix.plugin1" name = "plugin1" description = "A test plugin" provider = "netflix" releases = listOf( SpinnakerPluginInfo.SpinnakerPluginRelease(false).apply { requires = "orca>=1.0.0" version = "2.0.0" date = Date.from(Instant.now()) url = "front50.com/plugin.zip" }, SpinnakerPluginInfo.SpinnakerPluginRelease(true).apply { requires = "orca>=1.0.0" version = "3.0.0" date = Date.from(Instant.now()) url = "front50.com/plugin.zip" } ) } val plugin2 = SpinnakerPluginInfo().apply { id = "com.netflix.plugin2" name = "plugin2" description = "A test plugin" provider = "netflix" releases = listOf( SpinnakerPluginInfo.SpinnakerPluginRelease(false).apply { requires = "orca>=2.0.0" version = "3.0.0" date = Date.from(Instant.now()) url = "front50.com/plugin.zip" }, SpinnakerPluginInfo.SpinnakerPluginRelease(false).apply { requires = "orca>=1.0.0" version = "4.0.0" date = Date.from(Instant.now()) url = "front50.com/plugin.zip" }, SpinnakerPluginInfo.SpinnakerPluginRelease(true).apply { requires = "orca>=1.0.0" version = "5.0.0" date = Date.from(Instant.now()) url = "front50.com/plugin.zip" } ) } val plugin3 = SpinnakerPluginInfo().apply { id = "com.netflix.plugin3" name = "plugin3" description = "A test plugin" provider = "netflix" releases = listOf( SpinnakerPluginInfo.SpinnakerPluginRelease(false).apply { requires = "orca>=2.0.0" version = "7.0.0" date = Date.from(Instant.now()) url = "front50.com/plugin.zip" } ) } val pluginWithRemoteExtension = SpinnakerPluginInfo().apply { id = "com.netflix.plugin.remote" name = "remote" description = "A test plugin" provider = "netflix" releases = listOf( SpinnakerPluginInfo.SpinnakerPluginRelease( true, mutableListOf( RemoteExtensionConfig( "type", "netflix.remote.extension", RemoteExtensionConfig.RemoteExtensionTransportConfig( RemoteExtensionConfig.RemoteExtensionTransportConfig.Http( "https://example.com", mutableMapOf(), mutableMapOf(), mockk(relaxed = true) ) ), mutableMapOf() ) ) ).apply { requires = "orca>=2.0.0" version = "7.0.0" date = Date.from(Instant.now()) url = null } ) } val pluginNoReleases = SpinnakerPluginInfo().apply { id = "com.netflix.no.releases" name = "plugin2" description = "A test plugin" provider = "netflix" releases = emptyList() }
apache-2.0
f9e00683fb0fd319ec5c92102389811e
27.472441
77
0.649336
3.762747
false
false
false
false
metinkale38/prayer-times-android
features/times/src/main/java/com/metinkale/prayer/times/utils/BatteryOptimizations.kt
2
1430
/* * Copyright (c) 2013-2019 Metin Kale * * 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.metinkale.prayer.times.utils import android.content.Context import android.content.Intent import android.os.Build import android.os.PowerManager import android.provider.Settings fun isIgnoringBatteryOptimizations(context: Context): Boolean { val pwrm = context.applicationContext.getSystemService(Context.POWER_SERVICE) as PowerManager val name = context.applicationContext.packageName if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { return pwrm.isIgnoringBatteryOptimizations(name) } return true } fun checkBatteryOptimizations(context:Context) { if (!isIgnoringBatteryOptimizations(context) && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val intent = Intent(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS) context.startActivity(intent) } }
apache-2.0
e471ae0a502b54b678f9d40abf0f3dc3
35.692308
101
0.756643
4.169096
false
false
false
false
jonnyzzz/TeamCity.Node
agent/src/main/java/com/jonnyzzz/teamcity/plugins/node/agent/JsService.kt
1
5749
/* * Copyright 2013-2015 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.agent import jetbrains.buildServer.RunBuildException import jetbrains.buildServer.agent.runner.ProgramCommandLine import jetbrains.buildServer.agent.runner.BuildServiceAdapter import jetbrains.buildServer.util.FileUtil import com.jonnyzzz.teamcity.plugins.node.common.* import org.apache.log4j.Logger import com.jonnyzzz.teamcity.plugins.node.agent.processes.ScriptWrappingCommandLineGenerator import jetbrains.buildServer.agent.runner.SimpleProgramCommandLine import java.io.File import java.util.TreeMap import com.google.gson.Gson /** * Created by Eugene Petrenko (eugene.petrenko@gmail.com) * Date: 15.01.13 1:00 */ abstract class BaseService : BuildServiceAdapter() { private val disposables = arrayListOf<() -> Unit>() protected val LOG : Logger = log4j(this.javaClass) fun disposeLater(action : () -> Unit) { disposables.add(action) } override fun afterProcessFinished() { super.afterProcessFinished() disposables.forEach { it() } } protected fun execute(executable:String, arguments:List<String>) : ProgramCommandLine { val that = this return object:ScriptWrappingCommandLineGenerator<ProgramCommandLine>(runnerContext) { override fun execute(executable: String, args: List<String>): ProgramCommandLine = SimpleProgramCommandLine(build, executable, args) override fun disposeLater(action: () -> Unit) = that.disposeLater(action) }.generate(executable, arguments) } private inline fun generateTeamCityProperties(builder : MutableMap<String,String>.() -> Unit) : File { val file = io("Failed to create temp file") { agentTempDirectory.tempFile(TempFileName("teamcity", ".json")) } disposeLater { file.smartDelete() } val map = TreeMap<String, String>() map.builder() val text = Gson().toJson(map)!! io("Failed to create parameters file: $file") { writeUTF(file, text) } return file } fun generateSystemParametersJSON() : File = generateTeamCityProperties { putAll(buildParameters.systemProperties) } fun generateAllParametersJSON(): File = generateTeamCityProperties { putAll(configParameters) putAll(buildParameters.allParameters) } fun generateDefaultTeamCityParametersJSON(): List<String> = listOf( "--teamcity.properties.all=" + generateAllParametersJSON(), "--teamcity.properties=" + generateSystemParametersJSON()) } abstract class JsService() : BaseService() { protected val bean : NodeBean = NodeBean() override fun makeProgramCommandLine(): ProgramCommandLine { val mode = bean.findExecutionMode(runnerParameters) ?: throw RunBuildException("Execution mode was not specified") val arguments = arrayListOf<String>() //add [options section] arguments.addAll(fetchArguments(bean.commandLineParameterKey)) //add script file if (mode == ExecutionModes.File) { val filePath = runnerParameters[mode.parameter] if (filePath == null || filePath.isEmptyOrSpaces()) { throw RunBuildException("Script file path was not specified") } val file = checkoutDirectory.resolveEx(filePath) if (!file.isFile) { throw RunBuildException("Failed to find File at path: $file") } arguments.add(file.path) } else { if (mode == ExecutionModes.Script) { val scriptText = runnerParameters[mode.parameter] if (scriptText == null || scriptText.isEmptyOrSpaces()) { throw RuntimeException("Script was not defined or empty") } val tempScript = io("Failed to create temp file") { ( ///See issue #66 if (configParameters["teamcity.node.use.tempDirectory.for.generated.files"] != null) agentTempDirectory else workingDirectory ).tempFile(TempFileName(getToolName(), getGeneratedScriptExtImpl())) } disposeLater { tempScript.smartDelete() } io("Failed to write script to temp file") { FileUtil.writeFileAndReportErrors(tempScript, scriptText); } LOG.info("Generated script was saved to file: $tempScript") //so add generated script as commandline parameter arguments.add(tempScript.path) } else { throw RunBuildException("Unknown execution mode: $mode") } } //add script options arguments.addAll(fetchArguments(bean.scriptParameterKey)) val executable = getToolPath() ?: throw RunBuildException("Path to tool was not specified") return execute(executable, arguments) } protected abstract fun getToolPath() : String? protected abstract fun getToolName() : String protected abstract fun getGeneratedScriptExt() : String private fun getGeneratedScriptExtImpl() : String { var ext = getGeneratedScriptExt() while(ext.startsWith(".")) ext = ext.substring(1) return "." + ext } protected fun fetchArguments(runnerParametersKey : String) : Collection<String> { return runnerParameters[runnerParametersKey].fetchArguments() } }
apache-2.0
7a546f055022673ac712a6a64f1a98c5
34.054878
118
0.701687
4.613965
false
false
false
false
jonnyzzz/TeamCity.Node
common/src/main/java/com/jonnyzzz/teamcity/plugins/node/common/GruntBean.kt
1
1794
/* * Copyright 2013-2015 Eugene Petrenko * * 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.jonnyzzz.teamcity.plugins.node.common /** * Created by Eugene Petrenko (eugene.petrenko@gmail.com) * Date: 27.04.13 9:58 */ class GruntBean { val gruntConfigurationParameter : String = "grunt" val runTypeName: String = "jonnyzzz.grunt" val file: String = "jonnyzzz.grunt.file" val targets: String = "jonnyzzz.grunt.tasks" val commandLineParameterKey : String = "jonnyzzz.commandLine" val gruntMode : String = "jonnyzzz.grunt.mode" val gruntModeDefault : GruntExecutionMode = GruntExecutionMode.NPM val gruntModes : List<GruntExecutionMode> get() = arrayListOf(*GruntExecutionMode.values()) fun parseMode(text : String?) : GruntExecutionMode? = gruntModes.firstOrNull { text == it.value } ?: gruntModeDefault fun parseCommands(text: String?): Collection<String> { if (text == null) return listOf() else return text .lines() .map { it.trim() } .filterNot { it.isEmpty() } } } enum class GruntExecutionMode(val title : String, val value : String) { NPM("NPM package from project", "npm"), GLOBAL("System-wide grunt", "global"), }
apache-2.0
c5e34d4cff6eb77825a906d03a922217
31.618182
75
0.682274
3.849785
false
false
false
false
RP-Kit/RPKit
bukkit/rpk-travel-bukkit/src/main/kotlin/com/rpkit/travel/bukkit/database/table/RPKWarpTable.kt
1
6725
/* * Copyright 2022 Ren Binden * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rpkit.travel.bukkit.database.table import com.rpkit.core.database.Database import com.rpkit.core.database.Table import com.rpkit.core.location.RPKLocation import com.rpkit.travel.bukkit.RPKTravelBukkit import com.rpkit.travel.bukkit.database.create import com.rpkit.travel.bukkit.database.jooq.Tables.RPKIT_WARP import com.rpkit.travel.bukkit.warp.RPKWarpImpl import com.rpkit.warp.bukkit.warp.RPKWarp import com.rpkit.warp.bukkit.warp.RPKWarpName import java.util.concurrent.CompletableFuture import java.util.logging.Level class RPKWarpTable(private val database: Database, private val plugin: RPKTravelBukkit) : Table { private val cache = if (plugin.config.getBoolean("caching.rpkit_warp.name.enabled")) { database.cacheManager.createCache( "rpk-travel-bukkit.rpkit_warp.name", String::class.java, RPKWarp::class.java, plugin.config.getLong("caching.rpkit_warp.name.size") ) } else { null } fun insert(entity: RPKWarp): CompletableFuture<Void> { return CompletableFuture.runAsync { database.create .insertInto( RPKIT_WARP, RPKIT_WARP.NAME, RPKIT_WARP.WORLD, RPKIT_WARP.X, RPKIT_WARP.Y, RPKIT_WARP.Z, RPKIT_WARP.YAW, RPKIT_WARP.PITCH ) .values( entity.name.value, entity.location.world, entity.location.x, entity.location.y, entity.location.z, entity.location.yaw.toDouble(), entity.location.pitch.toDouble() ) .execute() cache?.set(entity.name.value, entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to insert warp", exception) throw exception } } fun update(entity: RPKWarp): CompletableFuture<Void> { return CompletableFuture.runAsync { database.create .update(RPKIT_WARP) .set(RPKIT_WARP.WORLD, entity.location.world) .set(RPKIT_WARP.X, entity.location.x) .set(RPKIT_WARP.Y, entity.location.y) .set(RPKIT_WARP.Z, entity.location.z) .set(RPKIT_WARP.YAW, entity.location.yaw.toDouble()) .set(RPKIT_WARP.PITCH, entity.location.pitch.toDouble()) .where(RPKIT_WARP.NAME.eq(entity.name.value)) .execute() cache?.set(entity.name.value, entity) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to update warp", exception) throw exception } } operator fun get(name: String): CompletableFuture<out RPKWarp?> { if (cache?.containsKey(name) == true) { return CompletableFuture.completedFuture(cache[name]) } else { return CompletableFuture.supplyAsync { val result = database.create .select( RPKIT_WARP.NAME, RPKIT_WARP.WORLD, RPKIT_WARP.X, RPKIT_WARP.Y, RPKIT_WARP.Z, RPKIT_WARP.YAW, RPKIT_WARP.PITCH ) .from(RPKIT_WARP) .where(RPKIT_WARP.NAME.eq(name)) .fetchOne() ?: return@supplyAsync null val warp = RPKWarpImpl( RPKWarpName(result.get(RPKIT_WARP.NAME)), RPKLocation( result.get(RPKIT_WARP.WORLD), result.get(RPKIT_WARP.X), result.get(RPKIT_WARP.Y), result.get(RPKIT_WARP.Z), result.get(RPKIT_WARP.YAW).toFloat(), result.get(RPKIT_WARP.PITCH).toFloat() ) ) cache?.set(name, warp) return@supplyAsync warp }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get warp", exception) throw exception } } } fun getAll(): CompletableFuture<out List<RPKWarp>> { return CompletableFuture.supplyAsync { val results = database.create .select( RPKIT_WARP.NAME, RPKIT_WARP.WORLD, RPKIT_WARP.X, RPKIT_WARP.Y, RPKIT_WARP.Z, RPKIT_WARP.YAW, RPKIT_WARP.PITCH ) .from(RPKIT_WARP) .fetch() return@supplyAsync results.mapNotNull { result -> RPKWarpImpl( RPKWarpName(result.get(RPKIT_WARP.NAME)), RPKLocation( result.get(RPKIT_WARP.WORLD), result.get(RPKIT_WARP.X), result.get(RPKIT_WARP.Y), result.get(RPKIT_WARP.Z), result.get(RPKIT_WARP.YAW).toFloat(), result.get(RPKIT_WARP.PITCH).toFloat() ) ) } }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to get all warps", exception) throw exception } } fun delete(entity: RPKWarp): CompletableFuture<Void> { return CompletableFuture.runAsync { database.create .deleteFrom(RPKIT_WARP) .where(RPKIT_WARP.NAME.eq(entity.name.value)) .execute() cache?.remove(entity.name.value) }.exceptionally { exception -> plugin.logger.log(Level.SEVERE, "Failed to delete warp", exception) throw exception } } }
apache-2.0
8f039383c6502917c6743fc17ccdf2bd
36.780899
97
0.528773
4.543919
false
false
false
false
pardom/navigator
navigator/src/main/kotlin/navigator/page/PageRoute.kt
1
982
package navigator.page import android.graphics.drawable.ColorDrawable import android.graphics.drawable.Drawable import navigator.Overlay import navigator.Route import navigator.ViewBuilder import navigator.route.AbsModalRoute import navigator.route.TransitionRoute class PageRoute<T>( private val builder: ViewBuilder, override val settings: Route.Settings = Route.Settings()) : AbsModalRoute<T>() { override val opaque: Boolean = true override val barrierDismissible: Boolean = false override val barrierDrawable: Drawable = ColorDrawable() override fun canTransitionTo(nextRoute: TransitionRoute<*>) = nextRoute is PageRoute override fun canTransitionFrom(nextRoute: TransitionRoute<*>) = nextRoute is PageRoute override fun createOverlayEntries(): Collection<Overlay.Entry> { return listOf( Overlay.Entry( builder, opaque ) ) } }
apache-2.0
81a22013a3a5d8e4c448bd93e5001ad6
27.882353
90
0.697556
5.010204
false
false
false
false
square/kotlinpoet
kotlinpoet/src/main/java/com/squareup/kotlinpoet/TypeAliasSpec.kt
1
5512
/* * Copyright (C) 2017 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.kotlinpoet import com.squareup.kotlinpoet.KModifier.ACTUAL import com.squareup.kotlinpoet.KModifier.INTERNAL import com.squareup.kotlinpoet.KModifier.PRIVATE import com.squareup.kotlinpoet.KModifier.PUBLIC import java.lang.reflect.Type import kotlin.reflect.KClass /** A generated typealias declaration */ public class TypeAliasSpec private constructor( builder: Builder, private val tagMap: TagMap = builder.buildTagMap(), ) : Taggable by tagMap { public val name: String = builder.name public val type: TypeName = builder.type public val modifiers: Set<KModifier> = builder.modifiers.toImmutableSet() public val typeVariables: List<TypeVariableName> = builder.typeVariables.toImmutableList() public val kdoc: CodeBlock = builder.kdoc.build() public val annotations: List<AnnotationSpec> = builder.annotations.toImmutableList() internal fun emit(codeWriter: CodeWriter) { codeWriter.emitKdoc(kdoc.ensureEndsWithNewLine()) codeWriter.emitAnnotations(annotations, false) codeWriter.emitModifiers(modifiers, setOf(PUBLIC)) codeWriter.emitCode("typealias %N", name) codeWriter.emitTypeVariables(typeVariables) codeWriter.emitCode(" = %T", type) codeWriter.emit("\n") } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (javaClass != other.javaClass) return false return toString() == other.toString() } override fun hashCode(): Int = toString().hashCode() override fun toString(): String = buildCodeString { emit(this) } @JvmOverloads public fun toBuilder(name: String = this.name, type: TypeName = this.type): Builder { val builder = Builder(name, type) builder.modifiers += modifiers builder.typeVariables += typeVariables builder.kdoc.add(kdoc) builder.annotations += annotations builder.tags += tagMap.tags return builder } public class Builder internal constructor( internal val name: String, internal val type: TypeName, ) : Taggable.Builder<Builder> { internal val kdoc = CodeBlock.builder() public val modifiers: MutableSet<KModifier> = mutableSetOf() public val typeVariables: MutableSet<TypeVariableName> = mutableSetOf() public val annotations: MutableList<AnnotationSpec> = mutableListOf() override val tags: MutableMap<KClass<*>, Any> = mutableMapOf() public fun addModifiers(vararg modifiers: KModifier): Builder = apply { modifiers.forEach(this::addModifier) } public fun addModifiers(modifiers: Iterable<KModifier>): Builder = apply { modifiers.forEach(this::addModifier) } private fun addModifier(modifier: KModifier) { this.modifiers.add(modifier) } public fun addTypeVariables(typeVariables: Iterable<TypeVariableName>): Builder = apply { this.typeVariables += typeVariables } public fun addTypeVariable(typeVariable: TypeVariableName): Builder = apply { typeVariables += typeVariable } public fun addKdoc(format: String, vararg args: Any): Builder = apply { kdoc.add(format, *args) } public fun addKdoc(block: CodeBlock): Builder = apply { kdoc.add(block) } public fun addAnnotations(annotationSpecs: Iterable<AnnotationSpec>): Builder = apply { this.annotations += annotationSpecs } public fun addAnnotation(annotationSpec: AnnotationSpec): Builder = apply { annotations += annotationSpec } public fun addAnnotation(annotation: ClassName): Builder = apply { annotations += AnnotationSpec.builder(annotation).build() } @DelicateKotlinPoetApi( message = "Java reflection APIs don't give complete information on Kotlin types. Consider " + "using the kotlinpoet-metadata APIs instead.", ) public fun addAnnotation(annotation: Class<*>): Builder = addAnnotation(annotation.asClassName()) public fun addAnnotation(annotation: KClass<*>): Builder = addAnnotation(annotation.asClassName()) public fun build(): TypeAliasSpec { for (it in modifiers) { require(it in ALLOWABLE_MODIFIERS) { "unexpected typealias modifier $it" } } return TypeAliasSpec(this) } private companion object { private val ALLOWABLE_MODIFIERS = setOf(PUBLIC, INTERNAL, PRIVATE, ACTUAL) } } public companion object { @JvmStatic public fun builder(name: String, type: TypeName): Builder = Builder(name, type) @DelicateKotlinPoetApi( message = "Java reflection APIs don't give complete information on Kotlin types. Consider " + "using the kotlinpoet-metadata APIs instead.", ) @JvmStatic public fun builder(name: String, type: Type): Builder = builder(name, type.asTypeName()) @JvmStatic public fun builder(name: String, type: KClass<*>): Builder = builder(name, type.asTypeName()) } }
apache-2.0
5f11a520556219f4594ea94461b06ef7
33.886076
99
0.713716
4.631933
false
false
false
false
Quireg/AnotherMovieApp
app/src/main/java/com/anothermovieapp/repository/WebserviceMovieDatabase.kt
1
1482
/* * Created by Arcturus Mengsk * 2021. */ package com.anothermovieapp.repository import com.anothermovieapp.BuildConfig import okhttp3.ResponseBody import retrofit2.http.GET import retrofit2.http.Path import retrofit2.http.Query interface WebserviceMovieDatabase { @GET("/3/movie/{id}/") suspend fun getMovie( @Path("id") id: String, @Query("api_key") key: String = BuildConfig.MOVIE_DATABASE_API_KEY ): ResponseBody @GET("/3/movie/{id}/videos") suspend fun getMovieTrailers( @Path("id") id: String, @Query("api_key") key: String = BuildConfig.MOVIE_DATABASE_API_KEY ): ResponseBody @GET("/3/movie/{id}/reviews/") suspend fun getMovieReviews( @Path("id") id: String, @Query("api_key") key: String = BuildConfig.MOVIE_DATABASE_API_KEY ): ResponseBody @GET("/3/movie/{id}/reviews") suspend fun getMovieReviewsForPage( @Path("id") id: String, @Query("page") page: Int, @Query("api_key") key: String = BuildConfig.MOVIE_DATABASE_API_KEY ): ResponseBody @GET("/3/movie/popular/") suspend fun getMoviesListPopular( @Query("page") page: Int, @Query("api_key") key: String = BuildConfig.MOVIE_DATABASE_API_KEY ): ResponseBody @GET("/3/movie/top_rated/") suspend fun getMoviesListTopRated( @Query("page") page: Int, @Query("api_key") key: String = BuildConfig.MOVIE_DATABASE_API_KEY ): ResponseBody }
mit
aaec409aecb4cb9e6740b9a04330dc48
27.519231
74
0.646424
3.742424
false
true
false
false
etesync/android
app/src/main/java/com/etesync/syncadapter/ui/importlocal/AccountResolver.kt
1
1826
package com.etesync.syncadapter.ui.importlocal import android.content.Context import android.content.pm.PackageManager import android.graphics.drawable.Drawable import androidx.core.content.ContextCompat import com.etesync.syncadapter.App import com.etesync.syncadapter.R import java.util.* internal class AccountResolver(private val context: Context) { private val cache: HashMap<String, AccountInfo> init { this.cache = LinkedHashMap() } fun resolve(accountName: String): AccountInfo { var accountName = accountName // Hardcoded swaps for known accounts: if (accountName == "com.google") { accountName = "com.google.android.googlequicksearchbox" } else if (accountName == App.addressBookAccountType) { accountName = App.accountType } else if (accountName == "at.bitfire.davdroid.address_book") { accountName = "at.bitfire.davdroid" } var ret: AccountInfo? = cache[accountName] if (ret == null) { try { val packageManager = context.packageManager val applicationInfo = packageManager.getApplicationInfo(accountName, 0) val name = if (applicationInfo != null) packageManager.getApplicationLabel(applicationInfo).toString() else accountName val icon = context.packageManager.getApplicationIcon(accountName) ret = AccountInfo(name, icon) } catch (e: PackageManager.NameNotFoundException) { ret = AccountInfo(accountName, ContextCompat.getDrawable(context, R.drawable.ic_account_dark)!!) } cache[accountName] = ret!! } return ret } class AccountInfo internal constructor(internal val name: String, internal val icon: Drawable) }
gpl-3.0
267aa32c96fe531c7d301beb86954d71
37.041667
135
0.667579
5.044199
false
false
false
false
LorittaBot/Loritta
common/src/jsMain/kotlin/net/perfectdreams/loritta/common/utils/image/JSImage.kt
1
1364
package net.perfectdreams.loritta.common.utils.image import net.perfectdreams.loritta.common.utils.image.Graphics import net.perfectdreams.loritta.common.utils.image.Image import nodecanvas.Buffer import nodecanvas.createCanvas import nodecanvas.toByteArray class JSImage(val canvas: Canvas) : Image { override val width: Int get() = canvas.width override val height: Int get() = canvas.height override fun getScaledInstance(width: Int, height: Int, scaleType: Image.ScaleType): Image { // Clonar imagem original val scaledImage = createCanvas(width, height) val ctx = scaledImage.getContext("2d") ctx.drawImage(this.canvas.getContext("2d").canvas, 0.0, 0.0, width.toDouble(), height.toDouble()) return JSImage(scaledImage) } override fun getSkewedInstance(x0: Float, y0: Float, x1: Float, y1: Float, x2: Float, y2: Float, x3: Float, y3: Float): Image { return JSImage( HackySkew(canvas) .setCorners( x0, y0, x1, y1, x2, y2, x3, y3 ) ) } override fun createGraphics(): Graphics { return JSGraphics(canvas.getContext("2d")) } override fun toByteArray(): ByteArray { val ctx = canvas.getContext("2d") val dataUrl = ctx.canvas.toDataURL("image/png") val dataBase64 = dataUrl.split("base64,").last() val buf = Buffer.from(dataBase64, "base64") return buf.toByteArray() } }
agpl-3.0
17a23ac903755086119e51af2a12b35a
27.4375
128
0.709677
3.164733
false
false
false
false
JustinMullin/drifter-kotlin
src/main/kotlin/xyz/jmullin/drifter/gdx/MultiTargetFrameBuffer.kt
1
4811
package xyz.jmullin.drifter.gdx import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.GL20 import com.badlogic.gdx.graphics.GL30 import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.graphics.glutils.GLOnlyTextureData import com.badlogic.gdx.utils.BufferUtils import com.badlogic.gdx.utils.Disposable import kotlin.jvm.JvmOverloads; class MultiTargetFrameBuffer(val width: Int, val height: Int, private val targets: List<String>) : Disposable { private var colorTextures = listOf<Texture>() private var framebufferHandle: Int = 0 init { build() } private fun createColorTexture(min: Texture.TextureFilter, mag: Texture.TextureFilter, internalformat: Int, format: Int, type: Int): Texture { val data = GLOnlyTextureData(width, height, 0, internalformat, format, type) val result = Texture(data) result.setFilter(min, mag) result.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat) return result } private fun createDepthTexture(): Texture { val data = GLOnlyTextureData(width, height, 0, GL30.GL_DEPTH_COMPONENT32F, GL30.GL_DEPTH_COMPONENT, GL30.GL_FLOAT) val result = Texture(data) result.setFilter(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest) result.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat) return result } private fun disposeColorTexture(colorTexture: Texture) { colorTexture.dispose() } private fun build() { val gl = Gdx.gl20 colorTextures = listOf() framebufferHandle = gl.glGenFramebuffer() gl.glBindFramebuffer(GL20.GL_FRAMEBUFFER, framebufferHandle) val textures = targets.map { createColorTexture(Texture.TextureFilter.Nearest, Texture.TextureFilter.Nearest, GL30.GL_RGB16F, GL30.GL_RGB, GL30.GL_FLOAT) } textures.forEach { colorTextures += it } textures.forEachIndexed { i, texture -> gl.glFramebufferTexture2D(GL20.GL_FRAMEBUFFER, GL30.GL_COLOR_ATTACHMENT0 + i, GL30.GL_TEXTURE_2D, texture.textureObjectHandle, 0) } val buffer = BufferUtils.newIntBuffer(targets.size) textures.forEachIndexed { i, _ -> buffer.put(GL30.GL_COLOR_ATTACHMENT0 + i) } buffer.position(0) Gdx.gl30.glDrawBuffers(targets.size, buffer) gl.glBindRenderbuffer(GL20.GL_RENDERBUFFER, 0) gl.glBindTexture(GL20.GL_TEXTURE_2D, 0) val result = gl.glCheckFramebufferStatus(GL20.GL_FRAMEBUFFER) gl.glBindFramebuffer(GL20.GL_FRAMEBUFFER, 0) if (result != GL20.GL_FRAMEBUFFER_COMPLETE) { for (colorTexture in colorTextures) disposeColorTexture(colorTexture) gl.glDeleteFramebuffer(framebufferHandle) if (result == GL20.GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT) throw IllegalStateException("frame buffer couldn't be constructed: incomplete attachment") if (result == GL20.GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS) throw IllegalStateException("frame buffer couldn't be constructed: incomplete dimensions") if (result == GL20.GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT) throw IllegalStateException("frame buffer couldn't be constructed: missing attachment") if (result == GL20.GL_FRAMEBUFFER_UNSUPPORTED) throw IllegalStateException("frame buffer couldn't be constructed: unsupported combination of formats") throw IllegalStateException("frame buffer couldn't be constructed: unknown error " + result) } } override fun dispose() { val gl = Gdx.gl20 for (textureAttachment in colorTextures) { disposeColorTexture(textureAttachment) } gl.glDeleteFramebuffer(framebufferHandle) } fun bind() { Gdx.gl20.glBindFramebuffer(GL20.GL_FRAMEBUFFER, framebufferHandle) } fun begin() { bind() setFrameBufferViewport() } private fun setFrameBufferViewport() { Gdx.gl20.glViewport(0, 0, colorTextures.first().width, colorTextures.first().height) } @JvmOverloads fun end(x: Int = 0, y: Int = 0, width: Int = Gdx.graphics.backBufferWidth, height: Int = Gdx.graphics.backBufferHeight) { unbind() Gdx.gl20.glViewport(x, y, width, height) } fun getColorBufferTextures() = colorTextures fun getColorBufferTexture(index: Int) = colorTextures[index] val depth: Int get() = colorTextures.first().depth fun unbind() { Gdx.gl20.glBindFramebuffer(GL20.GL_FRAMEBUFFER, 0) } }
mit
d1ab2053b1329beff3dc58caf97a6278
34.637037
139
0.662025
4.393607
false
false
false
false
TimePath/commons
src/main/kotlin/com/timepath/io/struct/StructField.kt
1
1064
package com.timepath.io.struct /** * Struct field marker. * Nested Object fields must either be statically accessible * via the nullary constructor, or pre-instantiated. * Arrays must also be instantiated. * * @author TimePath */ @Retention @Target(AnnotationTarget.FIELD) annotation public class StructField(public val index: Int = 0, /** * @return read with reverse byte order? */ public val reverse: Boolean = false, /** * @return bytes to skip after this field */ public val skip: Int = 0, /** * @return maximum length (mostly used for zstrings) */ public val limit: Int = 0, public val nullable: Boolean = false)
artistic-2.0
46a840ac0534f85859ac3cf1961e1657
41.56
100
0.427632
6.409639
false
false
false
false
Nagarajj/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/handler/PauseStageHandlerSpec.kt
1
3109
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.handler import com.natpryce.hamkrest.absent import com.natpryce.hamkrest.should.shouldMatch import com.netflix.spinnaker.orca.ExecutionStatus import com.netflix.spinnaker.orca.pipeline.model.Pipeline import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.q.* import com.netflix.spinnaker.spek.shouldEqual import com.nhaarman.mockito_kotlin.* import org.jetbrains.spek.api.dsl.context import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.subject.SubjectSpek object PauseStageHandlerSpec : SubjectSpek<PauseStageHandler>({ val queue: Queue = mock() val repository: ExecutionRepository = mock() subject { PauseStageHandler(queue, repository) } fun resetMocks() = reset(queue, repository) describe("when a stage is paused") { val pipeline = pipeline { application = "foo" stage { refId = "1" type = singleTaskStage.type } stage { refId = "2" requisiteStageRefIds = listOf("1") type = singleTaskStage.type } } val message = PauseStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stages.first().id) beforeGroup { whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline } afterGroup(::resetMocks) action("the handler receives a message") { subject.handle(message) } it("updates the stage state") { verify(repository).storeStage(check { it.getStatus() shouldEqual ExecutionStatus.PAUSED it.getEndTime() shouldMatch absent() }) } it("does not take any further action") { verifyZeroInteractions(queue) } } context("when a synthetic stage is paused") { val pipeline = pipeline { application = "foo" stage { refId = "1" type = stageWithSyntheticBefore.type stageWithSyntheticBefore.buildSyntheticStages(this) } } val message = PauseStage(Pipeline::class.java, pipeline.id, "foo", pipeline.stageByRef("1<1").id) beforeGroup { whenever(repository.retrievePipeline(message.executionId)) doReturn pipeline } action("the handler receives a message") { subject.handle(message) } afterGroup(::resetMocks) it("rolls up to the parent stage") { verify(queue).push(message.copy(stageId = pipeline.stageByRef("1").id)) verifyNoMoreInteractions(queue) } } })
apache-2.0
02a14f19b3691436821b34fe54b11114
28.330189
101
0.700547
4.312067
false
false
false
false
nt-ca-aqe/library-app
library-service/src/test/kotlin/utils/Books.kt
1
3849
package utils import library.service.business.books.domain.composites.Book import library.service.business.books.domain.types.Author import library.service.business.books.domain.types.Isbn13 import library.service.business.books.domain.types.Title object Books { private val STEPHEN_KING = Author("Stephen King") private val JRR_TOLKIEN = Author("J.R.R. Tolkien") private val ANDY_WEIR = Author("Andy Weir") private val GEORGE_RR_MARTIN = Author("George R.R. Martin") private val ROBERT_MARTIN = Author("Robert C. Martin") private val DEAB_WAMPLER = Author("Dean Wampler") val THE_LORD_OF_THE_RINGS_1 = Book( isbn = Isbn13("9780261102354"), title = Title("The Lord of the Rings 1. The Fellowship of the Ring"), authors = listOf(JRR_TOLKIEN), numberOfPages = 529 ) val THE_LORD_OF_THE_RINGS_2 = Book( isbn = Isbn13("9780261102361"), title = Title("The Lord of the Rings 2. The Two Towers"), authors = listOf(JRR_TOLKIEN), numberOfPages = 442 ) val THE_LORD_OF_THE_RINGS_3 = Book( isbn = Isbn13("9780261102378"), title = Title("The Lord of the Rings 3. The Return of the King"), authors = listOf(JRR_TOLKIEN), numberOfPages = 556 ) val THE_DARK_TOWER_I = Book( isbn = Isbn13("9781444723441"), title = Title("The Dark Tower I: The Gunslinger"), authors = listOf(STEPHEN_KING), numberOfPages = 304 ) val THE_DARK_TOWER_II = Book( isbn = Isbn13("9781444723458"), title = Title("The Dark Tower II: The Drawing Of The Three"), authors = listOf(STEPHEN_KING), numberOfPages = 496 ) val THE_DARK_TOWER_III = Book( isbn = Isbn13("9781444723465"), title = Title("The Dark Tower III: The Waste Lands"), authors = listOf(STEPHEN_KING), numberOfPages = 624 ) val THE_DARK_TOWER_IV = Book( isbn = Isbn13("9781444723472"), title = Title("The Dark Tower IV: Wizard and Glass"), authors = listOf(STEPHEN_KING), numberOfPages = 896 ) val THE_DARK_TOWER_V = Book( isbn = Isbn13("9781444723489"), title = Title("The Dark Tower V: Wolves of the Calla"), authors = listOf(STEPHEN_KING), numberOfPages = 816 ) val THE_DARK_TOWER_VI = Book( isbn = Isbn13("9781444723496"), title = Title("The Dark Tower VI: Song of Susannah"), authors = listOf(STEPHEN_KING), numberOfPages = 480 ) val THE_DARK_TOWER_VII = Book( isbn = Isbn13("9781444723502"), title = Title("The Dark Tower VII: The Dark Tower"), authors = listOf(STEPHEN_KING), numberOfPages = 736 ) val A_KNIGHT_OF_THE_SEVEN_KINGDOMS = Book( isbn = Isbn13("9780007507672"), title = Title("A Knight of the Seven Kingdoms"), authors = listOf(GEORGE_RR_MARTIN), numberOfPages = 355 ) val THE_MARTIAN = Book( isbn = Isbn13("9780091956141"), title = Title("The Martian"), authors = listOf(ANDY_WEIR), numberOfPages = 384 ) val CLEAN_CODE = Book( isbn = Isbn13("9780132350884"), title = Title("Clean Code: A Handbook of Agile Software Craftsmanship"), authors = listOf(ROBERT_MARTIN, DEAB_WAMPLER), numberOfPages = 462 ) val CLEAN_CODER = Book( isbn = Isbn13("9780137081073"), title = Title("Clean Coder: A Code of Conduct for Professional Programmers"), authors = listOf(ROBERT_MARTIN), numberOfPages = 256 ) }
apache-2.0
7c2b8c9077fb89f40e96c749cab5e755
35.320755
89
0.578592
3.669209
false
false
false
false
danrien/projectBlue
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/sync/GivenACustomStoragePreference/WhenLookingUpTheSyncDrive.kt
1
1924
package com.lasthopesoftware.bluewater.client.stored.library.sync.GivenACustomStoragePreference import com.lasthopesoftware.bluewater.client.browsing.library.access.FakeLibraryProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.stored.library.sync.SyncDirectoryLookup import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise import com.lasthopesoftware.storage.directories.FakePrivateDirectoryLookup import com.lasthopesoftware.storage.directories.FakePublicDirectoryLookup import org.assertj.core.api.AssertionsForClassTypes.assertThat import org.junit.BeforeClass import org.junit.Test import java.io.File class WhenLookingUpTheSyncDrive { @Test fun thenTheDriveIsTheOneWithTheMostSpace() { assertThat(file!!.path).isEqualTo("/stoarage2/my-second-card") } companion object { private var file: File? = null @BeforeClass @JvmStatic fun before() { val publicDrives = FakePublicDirectoryLookup() publicDrives.addDirectory("", 1) publicDrives.addDirectory("", 2) publicDrives.addDirectory("", 3) publicDrives.addDirectory("/storage/0/my-big-sd-card", 4) val fakePrivateDirectoryLookup = FakePrivateDirectoryLookup() fakePrivateDirectoryLookup.addDirectory("fake-private-path", 3) fakePrivateDirectoryLookup.addDirectory("/fake-private-path", 5) val fakeLibraryProvider = FakeLibraryProvider( Library() .setId(14) .setSyncedFileLocation(Library.SyncedFileLocation.CUSTOM) .setCustomSyncedFilesPath("/stoarage2/my-second-card") ) val syncDirectoryLookup = SyncDirectoryLookup( fakeLibraryProvider, publicDrives, fakePrivateDirectoryLookup, { f: File? -> 0 }) file = FuturePromise(syncDirectoryLookup.promiseSyncDirectory(LibraryId(14))).get() } } }
lgpl-3.0
7995ecb17e6d52f058a9d86c8942f89c
38.265306
95
0.804054
3.950719
false
false
false
false
PizzaGames/emulio
core/src/main/com/github/emulio/scrapers/tgdb/old/TheGamesDBScraperV1.kt
1
13845
package com.github.emulio.scrapers.tgdb.old import com.thoughtworks.xstream.XStream import com.thoughtworks.xstream.annotations.XStreamAlias import com.thoughtworks.xstream.annotations.XStreamAsAttribute import com.thoughtworks.xstream.annotations.XStreamConverter import com.thoughtworks.xstream.annotations.XStreamImplicit import com.thoughtworks.xstream.converters.extended.ToAttributedValueConverter import com.thoughtworks.xstream.io.xml.StaxDriver import mu.KotlinLogging import org.apache.commons.io.IOUtils import org.apache.http.client.methods.HttpGet import org.apache.http.impl.client.HttpClients import java.io.File import java.io.FileOutputStream import java.io.InputStream import java.net.URLEncoder import kotlin.system.measureTimeMillis /** * Documentation of api can be found in: http://wiki.thegamesdb.net/index.php?title=API_Introduction * * <b>Note:</b> * * Xstream is used here to parse all xmls, this is used due to easyness to use, but * the performance is a little compromized, maybe this can be changed to a better/ * more performatic parser (but xStream have a good performance, so, make sure you * have a good choice) */ @Deprecated("Use TheGamesDBScraperV2") object TheGamesDBScraperV1 { val logger = KotlinLogging.logger { } fun platformsList(): DataPlatformsList { logger.debug { "platformsList" } val xStream = getXStream() xStream.alias("Data", DataPlatformsList::class.java) xStream.alias("Platform", Platform::class.java) val url = "http://thegamesdb.net/api/GetPlatformsList.php" return performRequest(url, xStream) as DataPlatformsList } private fun performRequest(url: String, xStream: XStream) = HttpClients.createDefault().use { httpClient -> logger.debug { "performRequest: $url" } val httpGet = HttpGet(url) httpClient.execute(httpGet).use { response -> response.entity.content.use { stream -> xStream.fromXML(stream) } } } private fun getXStream() = XStream(StaxDriver()).apply { XStream.setupDefaultSecurity(this) allowTypes(arrayOf( DataGetGamesList::class.java, DataGetGame::class.java, DataArt::class.java, DataGetPlatform::class.java, DataPlatformGames::class.java, Game::class.java, AlternateTitle::class.java, Genres::class.java, Similar::class.java, DataPlatformsList::class.java, Platform::class.java, FanartImages::class.java, Fanart::class.java, Original::class.java, Boxart::class.java, Banner::class.java )) } fun platformGames(platform: String): DataPlatformGames { logger.debug { "platformGames" } val xStream = getXStream() xStream.alias("Data", DataPlatformGames::class.java) xStream.processAnnotations(DataPlatformGames::class.java) val url = "http://thegamesdb.net/api/PlatformGames.php?platform=${URLEncoder.encode(platform, "UTF-8")}" return performRequest(url, xStream) as DataPlatformGames } fun getPlatform(id: Int): DataGetPlatform { logger.debug { "getPlatform" } val xStream = getXStream() xStream.alias("Data", DataGetPlatform::class.java) xStream.alias("Platform", Platform::class.java) xStream.alias("Images", FanartImages::class.java) xStream.processAnnotations(FanartImages::class.java) xStream.processAnnotations(Fanart::class.java) xStream.processAnnotations(Original::class.java) xStream.processAnnotations(Boxart::class.java) xStream.processAnnotations(Banner::class.java) xStream.alias("fanart", Fanart::class.java) val url = "http://thegamesdb.net/api/GetPlatform.php?id=$id" return performRequest(url, xStream) as DataGetPlatform } fun getArt(id: Int): DataArt { logger.debug { "getArt" } val xStream = getXStream() xStream.alias("Data", DataArt::class.java) xStream.alias("Images", FanartImages::class.java) xStream.processAnnotations(Fanart::class.java) xStream.processAnnotations(Original::class.java) xStream.processAnnotations(Boxart::class.java) xStream.processAnnotations(Banner::class.java) xStream.processAnnotations(FanartImages::class.java) xStream.alias("fanart", Fanart::class.java) val url = "http://thegamesdb.net/api/GetArt.php?id=$id" return performRequest(url, xStream) as DataArt } fun getGame(id: Int? = null, name: String? = null, exactName: String? = null, platform: String? = null): DataGetGame { logger.debug { "getGame" } val xStream = getXStream() xStream.alias("Data", DataGetGame::class.java) xStream.processAnnotations(DataGetGame::class.java) xStream.alias("Platform", Platform::class.java) xStream.alias("Game", Game::class.java) xStream.alias("Images", FanartImages::class.java) xStream.processAnnotations(FanartImages::class.java) xStream.processAnnotations(Fanart::class.java) xStream.processAnnotations(Original::class.java) xStream.processAnnotations(Boxart::class.java) xStream.processAnnotations(Banner::class.java) xStream.alias("fanart", Fanart::class.java) check(id != null || name != null) { "A name or id must be provided" } val url = StringBuilder("http://thegamesdb.net/api/GetGame.php?") if (id != null) { url.append("id=$id&") } if (name != null) { url.append("name=$name&") } if (exactName != null) { url.append("exactname=$exactName&") } if (platform != null) { url.append("platform=$platform&") } url.setLength(url.length - 1) // always will end with & so we remove it here return performRequest(url.toString(), xStream) as DataGetGame } fun getGamesList(name: String? = null, genre: String? = null, platform: String? = null): DataGetGamesList { logger.debug { "getGamesList" } val xStream = getXStream() xStream.alias("Data", DataGetGamesList::class.java) xStream.processAnnotations(DataGetGamesList::class.java) xStream.alias("Platform", Platform::class.java) xStream.alias("Game", Game::class.java) xStream.processAnnotations(Genres::class.java) xStream.processAnnotations(Game::class.java) xStream.alias("Images", FanartImages::class.java) xStream.processAnnotations(Fanart::class.java) xStream.processAnnotations(Original::class.java) xStream.processAnnotations(Boxart::class.java) xStream.processAnnotations(Banner::class.java) xStream.processAnnotations(FanartImages::class.java) xStream.alias("fanart", Fanart::class.java) check(name != null || genre != null) { "A name or genre must be provided"} val url = StringBuilder("http://thegamesdb.net/api/GetGamesList.php?") if (name != null) { url.append("name=$name&") } if (genre != null) { url.append("genre=$genre&") } if (platform != null) { url.append("platform=$platform&") } url.setLength(url.length - 1) // always will end with & so we remove it here return performRequest(url.toString(), xStream) as DataGetGamesList } fun downloadImage(baseUrl: String, path: String, destiny: File) { downloadImage("$baseUrl$path", destiny) } fun downloadImage(url: String, destiny: File) { HttpClients.createDefault().use { httpClient -> val httpGet = HttpGet(url) httpClient.execute(httpGet).use { response -> response.entity.content.use { stream -> readStream(destiny, stream) } } } } private fun readStream(destiny: File, stream: InputStream?): Int { return FileOutputStream(destiny).use { fos -> IOUtils.copy(stream, fos) } } } // Sample api tests fun main(args: Array<String>) { println("; time: ${measureTimeMillis { print("platformsList: ${TheGamesDBScraperV1.platformsList()}") }}") println("; time: ${measureTimeMillis { print("platformGames: ${TheGamesDBScraperV1.platformGames("microsoft xbox 360")}") }}") println("; time: ${measureTimeMillis { print("getPlatform: ${TheGamesDBScraperV1.getPlatform(15)}") }}") println("; time: ${measureTimeMillis { print("getArt: ${TheGamesDBScraperV1.getArt(15)}") }}") println("; time: ${measureTimeMillis { print("getGame: ${TheGamesDBScraperV1.getGame(id=15)}") }}") println("; time: ${measureTimeMillis { print("getGamesList: ${TheGamesDBScraperV1.getGamesList(name="donkey")}") }}") TheGamesDBScraperV1.downloadImage("http://thegamesdb.net/banners/", "fanart/original/15-2.jpg", File("g:/15-2.jpg")) println("xStream time: ${measureTimeMillis { XStream(StaxDriver()) }}") } /** * Classes used to represent the data from: * http://thegamesdb.net/api/GetGamesList.php?name=x-men * * Official documentation: * http://wiki.thegamesdb.net/index.php/GetGamesList */ data class DataGetGamesList( val baseImgUrl: String?, @XStreamImplicit(itemFieldName = "Game") var games: List<Game> = listOf() ) /** * Classes used to represent the data from: * http://thegamesdb.net/api/GetGame.php?id=2 * * Official documentation: * http://wiki.thegamesdb.net/index.php/GetGame */ data class DataGetGame( val baseImgUrl: String?, @XStreamImplicit(itemFieldName = "Game") var games: List<Game> = listOf() ) /** * Classes used to represent the data from: *http://thegamesdb.net/api/GetArt.php?id=2 * * Official documentation: * http://wiki.thegamesdb.net/index.php/GetArt */ data class DataArt( val baseImgUrl: String?, var Images: FanartImages? ) /** * Classes used to represent the data from: * http://thegamesdb.net/api/GetPlatform.php?id=15 * * Official documentation: * http://wiki.thegamesdb.net/index.php/GetPlatform */ data class DataGetPlatform( val baseImgUrl: String?, var Platform: Platform? ) /** * Classes used to represent the data from: * http://thegamesdb.net/api/PlatformGames.php?platform=xpto * * Official documentation: * http://wiki.thegamesdb.net/index.php/PlatformGames */ data class DataPlatformGames( @XStreamImplicit(itemFieldName = "Game") var games: List<Game> = listOf() ) data class Game( val id: Int?, val GameTitle: String?, val ReleaseDate: String?, val AlternateTitles: AlternateTitle?, val thumb: String?, val Overview: String?, val ESRB: String?, @XStreamAlias("Co-op") val CoOp: String?, val Players: Int?, val Genres: Genres?, val Youtube: String?, val Publisher: String?, val Developer: String?, val Similar: Similar?, val Platform: String?, val PlatformId: Int?, val Rating: Float?, val Images: FanartImages? ) data class AlternateTitle( var title: String ) data class Genres( @XStreamImplicit(itemFieldName = "genre") var genres: List<String> = listOf() ) data class Similar( @XStreamImplicit(itemFieldName = "Game") var games: List<Game> = listOf() ) /** * Classes used to represent the data from: * http://thegamesdb.net/api/GetPlatformsList.php * * Official documentation: * http://wiki.thegamesdb.net/index.php/GetPlatformsList */ data class DataPlatformsList( val Platforms: List<Platform> = listOf(), val basePlatformUrl: String? ) data class Platform( val id: Int?, val name: String?, val alias: String?, val Platform: String?, val console: String?, val controller: String?, val overview: String?, val developer: String?, val manufacturer: String?, val cpu: String?, val memory: String?, val graphics: String?, val sound: String?, val display: String?, val media: String?, val maxcontrollers: Int?, val Rating: Float?, val Images: FanartImages? ) data class FanartImages( @XStreamImplicit(itemFieldName = "fanart") var games: List<Fanart> = listOf(), @XStreamImplicit(itemFieldName = "boxart") var boxart: List<Boxart>? = null, @XStreamImplicit(itemFieldName = "banner") var banner: List<Banner>? = null, var consoleart: String? = null, var controllerart: String? = null, var screenshot: Fanart? = null, var clearlogo: String? = null ) data class Fanart( val original: Original?, val thumb: String? ) @XStreamConverter(value= ToAttributedValueConverter::class, strings= ["value"]) data class Original( @XStreamAsAttribute var height: Int?, @XStreamAsAttribute var width: Int?, @XStreamAsAttribute var thumb: String?, @XStreamAsAttribute var side: String?, var value: String? ) @XStreamConverter(value= ToAttributedValueConverter::class, strings= ["value"]) data class Boxart( @XStreamAsAttribute var height: Int?, @XStreamAsAttribute var width: Int?, @XStreamAsAttribute var thumb: String?, @XStreamAsAttribute var side: String?, var value: String? ) @XStreamConverter(value= ToAttributedValueConverter::class, strings= ["value"]) data class Banner( @XStreamAsAttribute var height: Int?, @XStreamAsAttribute var width: Int?, @XStreamAsAttribute var thumb: String?, @XStreamAsAttribute var side: String?, var value: String? )
gpl-3.0
94bab12671accb9fa4d3bca80740d05c
31.885986
130
0.654966
3.914334
false
false
false
false
jitsi/jitsi-videobridge
jitsi-media-transform/src/main/kotlin/org/jitsi/nlj/transform/node/incoming/RemoteBandwidthEstimator.kt
1
5637
/* * Copyright @ 2018 - Present, 8x8 Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.nlj.transform.node.incoming import edu.umd.cs.findbugs.annotations.SuppressFBWarnings import org.jitsi.nlj.Event import org.jitsi.nlj.PacketInfo import org.jitsi.nlj.SetLocalSsrcEvent import org.jitsi.nlj.rtp.RtpExtensionType.ABS_SEND_TIME import org.jitsi.nlj.rtp.bandwidthestimation.BandwidthEstimator import org.jitsi.nlj.rtp.bandwidthestimation.GoogleCcEstimator import org.jitsi.nlj.stats.NodeStatsBlock import org.jitsi.nlj.transform.node.ObserverNode import org.jitsi.nlj.util.ReadOnlyStreamInformationStore import org.jitsi.nlj.util.bps import org.jitsi.nlj.util.bytes import org.jitsi.rtp.rtcp.RtcpHeaderBuilder import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbRembPacket import org.jitsi.rtp.rtcp.rtcpfb.payload_specific_fb.RtcpFbRembPacketBuilder import org.jitsi.rtp.rtp.RtpPacket import org.jitsi.rtp.rtp.header_extensions.AbsSendTimeHeaderExtension import org.jitsi.utils.LRUCache import org.jitsi.utils.MediaType import org.jitsi.utils.logging.DiagnosticContext import org.jitsi.utils.logging2.Logger import org.jitsi.utils.logging2.createChildLogger import org.jitsi.utils.observableWhenChanged import java.time.Clock import java.time.Duration import java.util.Collections /** * Estimates the available bandwidth for the incoming stream using the abs-send-time extension. */ class RemoteBandwidthEstimator( private val streamInformationStore: ReadOnlyStreamInformationStore, parentLogger: Logger, diagnosticContext: DiagnosticContext = DiagnosticContext(), private val clock: Clock = Clock.systemUTC() ) : ObserverNode("Remote Bandwidth Estimator") { private val logger = createChildLogger(parentLogger) /** * The remote bandwidth estimation is enabled when REMB support is signaled, but TCC is not signaled. */ private var enabled: Boolean by observableWhenChanged(false) { _, _, newValue -> logger.debug { "Setting enabled=$newValue." } } private var astExtId: Int? = null /** * We use the full [GoogleCcEstimator] here, but we don't notify it of packet loss, effectively using only the * delay-based part. */ private val bwe: BandwidthEstimator by lazy { GoogleCcEstimator(diagnosticContext, logger) } private val ssrcs: MutableSet<Long> = Collections.synchronizedSet(LRUCache.lruSet(MAX_SSRCS, true /* accessOrder */)) private var numRembsCreated = 0 private var numPacketsWithoutAbsSendTime = 0 private var localSsrc = 0L init { streamInformationStore.onRtpExtensionMapping(ABS_SEND_TIME) { astExtId = it logger.debug { "Setting abs-send-time extension ID to $astExtId" } } streamInformationStore.onRtpPayloadTypesChanged { enabled = streamInformationStore.supportsRemb && !streamInformationStore.supportsTcc } } companion object { private const val MAX_SSRCS: Int = 8 } override fun handleEvent(event: Event) { if (event is SetLocalSsrcEvent && event.mediaType == MediaType.VIDEO) { localSsrc = event.ssrc } } override fun trace(f: () -> Unit) = f.invoke() @SuppressFBWarnings("RV_RETURN_VALUE_IGNORED_NO_SIDE_EFFECT", "False positive") override fun observe(packetInfo: PacketInfo) { if (!enabled) return astExtId?.let { val rtpPacket = packetInfo.packetAs<RtpPacket>() rtpPacket.getHeaderExtension(it)?.let { ext -> val now = clock.instant() bwe.processPacketArrival( now, AbsSendTimeHeaderExtension.getTime(ext), packetInfo.receivedTime, rtpPacket.sequenceNumber, rtpPacket.length.bytes ) /* With receiver-side bwe we need to treat each received packet as separate feedback */ bwe.feedbackComplete(now) ssrcs.add(rtpPacket.ssrc) } } ?: numPacketsWithoutAbsSendTime++ } override fun getNodeStats(): NodeStatsBlock = super.getNodeStats().apply { addString("ast_ext_id", astExtId.toString()) addBoolean("enabled", enabled) addNumber("num_rembs_created", numRembsCreated) addNumber("num_packets_without_ast", numPacketsWithoutAbsSendTime) } fun createRemb(): RtcpFbRembPacket? { // REMB based BWE is not configured. if (!enabled || astExtId == null) return null val currentBw = bwe.getCurrentBw(clock.instant()) // The estimator does not yet have a valid value. if (currentBw < 0.bps) return null numRembsCreated++ return RtcpFbRembPacketBuilder( rtcpHeader = RtcpHeaderBuilder(senderSsrc = localSsrc), brBps = currentBw.bps.toLong(), ssrcs = ssrcs.toList() ).build() } fun onRttUpdate(newRttMs: Double) { bwe.onRttUpdate(clock.instant(), Duration.ofNanos((newRttMs * 1000_000).toLong())) } }
apache-2.0
dc8f498cc9111a1ab384f34dd1aaaafe
38.145833
114
0.695051
4.216156
false
false
false
false
koesie10/AdventOfCode-Solutions-Kotlin
2015/src/main/kotlin/com/koenv/adventofcode/Day3.kt
1
1719
package com.koenv.adventofcode object Day3 { public fun getTotalVisitedHouses(input: String): Int { var currentPosition = Coordinate(0, 0) val visitedHouses = arrayListOf(currentPosition) input.forEach { currentPosition += getCoordinateDelta(it) visitedHouses.add(currentPosition) } return visitedHouses.distinct().size } public fun getTotalVisitedHousesWithRoboSanta(input: String): Int { var santaCurrentPosition = Coordinate(0, 0) var roboSantaCurrentPosition = santaCurrentPosition val visitedHouses = arrayListOf(santaCurrentPosition) input.forEachIndexed { i, it -> if (i % 2 == 0) { santaCurrentPosition += getCoordinateDelta(it) visitedHouses.add(santaCurrentPosition) } else { roboSantaCurrentPosition += getCoordinateDelta(it) visitedHouses.add(roboSantaCurrentPosition) } } return visitedHouses.distinct().size } private fun getCoordinateDelta(input: Char): Coordinate { when (input) { '>' -> { return Coordinate(1, 0) } '<' -> { return Coordinate(-1, 0) } '^' -> { return Coordinate(0, -1) } 'v' -> { return Coordinate(0, 1) } } throw IllegalArgumentException("Invalid input: $input") } data class Coordinate(val x: Int, val y: Int) { public operator fun plus(other: Coordinate): Coordinate { return Coordinate(x + other.x, y + other.y) } } }
mit
1b0bee58adf383e9c8804ea248845b7f
28.655172
71
0.554974
4.897436
false
false
false
false
nisrulz/android-examples
AutoInitLibrary/awesomelib/src/main/java/github/nisrulz/example/awesomelib/AwesomeLibInitProvider.kt
1
1943
package github.nisrulz.example.awesomelib import android.content.ContentProvider import android.content.ContentValues import android.content.Context import android.content.pm.ProviderInfo import android.database.Cursor import android.net.Uri class AwesomeLibInitProvider : ContentProvider() { override fun attachInfo(context: Context, providerInfo: ProviderInfo) { if (providerInfo == null) { throw NullPointerException("YourLibraryInitProvider ProviderInfo cannot be null.") } // So if the authorities equal the library internal ones, the developer forgot to set his applicationId val libAuthorityString = "github.nisrulz.example.awesomelib.awesomelibinitprovider" check(libAuthorityString != providerInfo.authority) { ("Incorrect provider authority[" + libAuthorityString + "]" + " in manifest. " + "Most likely due to a " + "missing applicationId variable in application\'s build.gradle.") } super.attachInfo(context, providerInfo) } override fun onCreate(): Boolean { // get the context (Application context) val context = context // initialize AwesomeLib here AwesomeLib.initLibrary() return false } override fun getType(uri: Uri): String? { return null } override fun query( uri: Uri, projection: Array<String>?, selection: String?, selectionArgs: Array<String>?, sortOrder: String? ): Cursor? { return null } override fun insert(uri: Uri, values: ContentValues?): Uri? { return null } override fun update( uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<String>? ): Int { return 0 } override fun delete(uri: Uri, selection: String?, selectionArgs: Array<String>?): Int { return 0 } }
apache-2.0
9d8e875aabd056e62c3185f0bb4a27c3
31.4
111
0.649511
4.845387
false
false
false
false
Shopify/mobile-buy-sdk-android
MobileBuy/buy3/src/main/java/com/shopify/buy3/CardClient.kt
1
4569
/* * The MIT License (MIT) * * Copyright (c) 2015 Shopify Inc. * * 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.shopify.buy3 import android.os.Handler import com.shopify.buy3.internal.RealCreditCardVaultCall import okhttp3.Call import okhttp3.HttpUrl import okhttp3.OkHttpClient import java.util.concurrent.TimeUnit private val DEFAULT_HTTP_CONNECTION_TIME_OUT_MS = TimeUnit.SECONDS.toMillis(10) private val DEFAULT_HTTP_READ_WRITE_TIME_OUT_MS = TimeUnit.SECONDS.toMillis(20) /** * [CardVaultResult] card vault result handler. */ typealias CardVaultResultCallback = (result: CardVaultResult) -> Unit /** * Factory for network calls to the card server * * Should be shared and reused for all calls to the card server. */ class CardClient(internal val httpCallFactory: Call.Factory = defaultOkHttpClient()) { /** * Creates a call to vault credit card on the server * * Credit cards cannot be sent to the checkout API directly. They must be sent to the card vault which in response will return an token. * This token should be used for completion checkout with credit card. * * @param creditCard [CreditCard] credit card info * @param vaultServerUrl endpoint of card vault returned in [Storefront.PaymentSettings.getCardVaultUrl] * @return [CreditCardVaultCall] */ fun vault(creditCard: CreditCard, vaultServerUrl: String): CreditCardVaultCall { return RealCreditCardVaultCall(creditCard, HttpUrl.parse(vaultServerUrl), httpCallFactory) } } private fun defaultOkHttpClient(): OkHttpClient { return OkHttpClient.Builder() .connectTimeout(DEFAULT_HTTP_CONNECTION_TIME_OUT_MS, TimeUnit.MILLISECONDS) .readTimeout(DEFAULT_HTTP_READ_WRITE_TIME_OUT_MS, TimeUnit.MILLISECONDS) .writeTimeout(DEFAULT_HTTP_READ_WRITE_TIME_OUT_MS, TimeUnit.MILLISECONDS) .build() } /** * Abstraction for call to the vaulting card server. * * Credit cards cannot be sent to the checkout API directly. They must be sent to the card vault which in response will return an token. * * This token should be used for completion checkout with credit card. */ interface CreditCardVaultCall { /** * Checks if this call has been canceled. */ val isCanceled: Boolean /** * Cancels this call if possible. */ fun cancel() /** * Creates a new, identical call to this one, which can be enqueued even if this call has already been executed or canceled. * * @return [CreditCardVaultCall] cloned call */ fun clone(): CreditCardVaultCall /** * Schedules the call to be executed at some point in the future. * * @param callback [CardVaultResultCallback] to handle the response or a failure * @param callbackHandler optional handler provided callback will be running on the thread to which it is attached to * @return [CreditCardVaultCall] scheduled for execution * @throws IllegalStateException when the call has already been executed */ fun enqueue(callbackHandler: Handler? = null, callback: CardVaultResultCallback): CreditCardVaultCall } /** * Represents result of the [CreditCardVaultCall] execution */ sealed class CardVaultResult { /** * Success result with a returned credit card token. */ class Success(val token: String) : CardVaultResult() /** * Failure result with exception caused an error. */ class Failure(val exception: Exception) : CardVaultResult() }
mit
c35643fd1314bbfcb740dea36182a6ba
36.154472
140
0.725542
4.414493
false
false
false
false
Ribesg/Pure
src/main/kotlin/fr/ribesg/minecraft/pure/util/ReflectionUtils.kt
1
2259
package fr.ribesg.minecraft.pure.util import org.objenesis.ObjenesisStd import java.lang.reflect.Field import java.lang.reflect.Modifier /** * @author Ribesg */ object ReflectionUtils { /** * Creates a new instance of the provided class without calling any * constructor. * * @param clazz the class * @param <T> the type * * @return an instance of the provided class */ @Suppress("unchecked") @JvmStatic fun <T> newInstance(clazz: Class<T>): T = ObjenesisStd().newInstance(clazz) /** * Sets the provided field to the provided value in the provided instance * of the provided class. * * @param clazz the class * @param obj the object * @param fieldName the name of the field * @param value the new value of the field * * @throws ReflectiveOperationException if anything goes wrong */ @Throws(ReflectiveOperationException::class) @JvmStatic fun set(clazz: Class<*>, obj: Any?, fieldName: String, value: Any?) { val field = clazz.getDeclaredField(fieldName) field.isAccessible = true if (Modifier.isFinal(field.modifiers)) { // Field is final, work around it val modifiersField = Field::class.java.getDeclaredField("modifiers") modifiersField.isAccessible = true modifiersField.setInt(field, field.modifiers and Modifier.FINAL.inv()) } field.set(obj, value) } /** * Gets the value of the provided field from the provided instance of the * provided class. * * @param clazz the class of the object * @param obj the object * @param fieldName the name of the field * @param fieldClass the class of the field * @param <T> the type of the field * * @return the field's value * * @throws ReflectiveOperationException if anything goes wrong */ @Throws(ReflectiveOperationException::class) @JvmStatic fun<T> get(clazz: Class<*>, obj: Any?, fieldName: String, fieldClass: Class<T>): T { val field = clazz.getDeclaredField(fieldName) field.isAccessible = true return fieldClass.cast(field.get(obj)) } }
gpl-3.0
88cb01ded37dc82039a0ae2bc5b16651
29.12
88
0.63081
4.386408
false
false
false
false
wenhaiz/ListenAll
app/src/main/java/com/wenhaiz/himusic/module/playhistory/PlayHistoryFragment.kt
1
5092
package com.wenhaiz.himusic.module.playhistory import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageButton import android.widget.LinearLayout import android.widget.TextView import butterknife.BindView import butterknife.ButterKnife import butterknife.OnClick import butterknife.Unbinder import com.wenhaiz.himusic.R import com.wenhaiz.himusic.data.bean.PlayHistory import com.wenhaiz.himusic.data.bean.Song import com.wenhaiz.himusic.ext.showToast import com.wenhaiz.himusic.module.main.MainActivity import com.wenhaiz.himusic.utils.removeFragment import com.wenhaiz.himusic.widget.SongOpsDialog class PlayHistoryFragment : Fragment(), PlayHistoryContract.View { @BindView(R.id.action_bar_title) lateinit var mTvTitle: TextView @BindView(R.id.play_history_list) lateinit var mHistoryList: RecyclerView private lateinit var mUnbinder: Unbinder private lateinit var mPresenter: PlayHistoryContract.Presenter private lateinit var mPlayHistoryAdapter: PlayHistoryAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) PlayHistoryPresenter(this) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val contentView = inflater.inflate(R.layout.fragment_play_history, container, false) mUnbinder = ButterKnife.bind(this, contentView) initView() return contentView } override fun initView() { mTvTitle.text = getString(R.string.main_recent_play) mPlayHistoryAdapter = PlayHistoryAdapter(ArrayList()) mHistoryList.layoutManager = LinearLayoutManager(context) mHistoryList.adapter = mPlayHistoryAdapter mPresenter.loadPlayHistory(context!!) } @OnClick(R.id.action_bar_back, R.id.play_history_shuffle_all) fun onClick(view: View) { when (view.id) { R.id.action_bar_back -> { removeFragment(fragmentManager!!, this) } R.id.play_history_shuffle_all -> { if (mPlayHistoryAdapter.playHistoryList.isEmpty()) { context!!.showToast(R.string.no_songs_to_play) } else { val songList = ArrayList<Song>() mPlayHistoryAdapter.playHistoryList.mapTo(songList) { it.song } (activity as MainActivity).playService.shuffleAll(songList) } } } } override fun setPresenter(presenter: PlayHistoryContract.Presenter) { mPresenter = presenter } override fun getViewContext(): Context { return context!! } override fun onPlayHistoryLoad(playHistory: List<PlayHistory>) { mPlayHistoryAdapter.setData(playHistory) } override fun onNoPlayHistory() { context!!.showToast(R.string.no_play_history) } override fun onLoading() { } override fun onFailure(msg: String) { context!!.showToast(msg) } inner class PlayHistoryAdapter(var playHistoryList: List<PlayHistory>) : RecyclerView.Adapter<PlayHistoryAdapter.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemView = LayoutInflater.from(context).inflate(R.layout.item_play_history, parent, false) return ViewHolder(itemView) } override fun getItemCount(): Int = playHistoryList.size override fun onBindViewHolder(holder: ViewHolder, position: Int) { val playHistory = playHistoryList[position] holder.songName.text = playHistory.songName holder.playTimes.text = playHistory.playTimes.toString() val songInfoStr = "${playHistory.artistName} · ${playHistory.albumName}" holder.songInfo.text = songInfoStr holder.operation.setOnClickListener { val dialog = SongOpsDialog(context!!, playHistory.song, activity!!) dialog.show() } holder.item.setOnClickListener { (activity as MainActivity).playService.playNewSong(playHistory.song) } } fun setData(historyList: List<PlayHistory>) { playHistoryList = historyList notifyDataSetChanged() } inner class ViewHolder(item: View) : RecyclerView.ViewHolder(item) { val item: LinearLayout = item.findViewById(R.id.play_history_item) var songName: TextView = item.findViewById(R.id.play_history_song_name) var songInfo: TextView = item.findViewById(R.id.play_history_song_info) var playTimes: TextView = item.findViewById(R.id.play_history_times) var operation: ImageButton = item.findViewById(R.id.play_history_ops) } } }
apache-2.0
cf226d6e6e81d28d6ecee5923863d4c9
36.167883
132
0.684148
4.582358
false
false
false
false
cuebyte/rendition
src/main/kotlin/moe/cuebyte/rendition/query/data/InsertData.kt
1
1714
package moe.cuebyte.rendition.query.data import moe.cuebyte.rendition.Model import moe.cuebyte.rendition.util.IdGenerator internal class InsertData(model: Model, input: Map<String, Any>) : InputData(model, input) { override fun idInit(input: Map<String, Any>) { val pk = model.pk if (pk.automated) { tId = IdGenerator.next() return } if (input[pk.name] == null || input[pk.name] == "") { throw Exception("Id has not defined.") } if (!model.pk.checkType(input[pk.name]!!)) { throw Exception("Id type was error.") } tId = input[pk.name].toString() } override fun indicesInit(input: Map<String, Any>) { for (idx in model.stringIndices.values) { input[idx.name] ?: throw Exception("Index-${idx.name} shall be defined.") if (input[idx.name]!! !is String) { throw Exception("${idx.name} should be String.") } tStrIndices.put(idx, input[idx.name] as String) } for (idx in model.numberIndices.values) { input[idx.name] ?: throw Exception("Index-${idx.name} shall be defined.") if (!idx.checkType(input[idx.name]!!)) { throw Exception("${idx.name} type error.") } tNumIndices.put(idx, (input[idx.name] as Number).toDouble()) } } override fun dataInit(input: Map<String, Any>) { for ((name, col) in model.columns) { if (name !in input.keys) { tBody.put(name, col.default.toString()) } else if (!col.checkType(input[name]!!)) { throw Exception("$name type error.") } else { tBody.put(name, input[name].toString()) } } if (model.pk.automated) { tBody.put(model.pk.name, tId) } } }
lgpl-3.0
cbea51d79cd93b0b2affde9e633758e6
28.067797
92
0.60035
3.48374
false
false
false
false
inorichi/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsLibraryController.kt
1
16741
package eu.kanade.tachiyomi.ui.setting import android.app.Dialog import android.os.Bundle import android.view.LayoutInflater import androidx.core.content.ContextCompat import androidx.core.text.buildSpannedString import androidx.preference.PreferenceScreen import com.google.android.material.dialog.MaterialAlertDialogBuilder import eu.kanade.tachiyomi.R import eu.kanade.tachiyomi.data.database.DatabaseHelper import eu.kanade.tachiyomi.data.database.models.Category import eu.kanade.tachiyomi.data.library.LibraryUpdateJob import eu.kanade.tachiyomi.data.preference.DEVICE_CHARGING import eu.kanade.tachiyomi.data.preference.DEVICE_ONLY_ON_WIFI import eu.kanade.tachiyomi.data.preference.MANGA_FULLY_READ import eu.kanade.tachiyomi.data.preference.MANGA_ONGOING import eu.kanade.tachiyomi.data.preference.PreferencesHelper import eu.kanade.tachiyomi.data.track.TrackManager import eu.kanade.tachiyomi.databinding.PrefLibraryColumnsBinding import eu.kanade.tachiyomi.ui.base.controller.DialogController import eu.kanade.tachiyomi.ui.base.controller.withFadeTransaction import eu.kanade.tachiyomi.ui.category.CategoryController import eu.kanade.tachiyomi.util.preference.bindTo import eu.kanade.tachiyomi.util.preference.defaultValue import eu.kanade.tachiyomi.util.preference.entriesRes import eu.kanade.tachiyomi.util.preference.intListPreference import eu.kanade.tachiyomi.util.preference.multiSelectListPreference import eu.kanade.tachiyomi.util.preference.onChange import eu.kanade.tachiyomi.util.preference.onClick import eu.kanade.tachiyomi.util.preference.preference import eu.kanade.tachiyomi.util.preference.preferenceCategory import eu.kanade.tachiyomi.util.preference.summaryRes import eu.kanade.tachiyomi.util.preference.switchPreference import eu.kanade.tachiyomi.util.preference.titleRes import eu.kanade.tachiyomi.util.system.isTablet import eu.kanade.tachiyomi.widget.materialdialogs.QuadStateTextView import eu.kanade.tachiyomi.widget.materialdialogs.setQuadStateMultiChoiceItems import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import uy.kohesive.injekt.Injekt import uy.kohesive.injekt.api.get import uy.kohesive.injekt.injectLazy import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys class SettingsLibraryController : SettingsController() { private val db: DatabaseHelper = Injekt.get() private val trackManager: TrackManager by injectLazy() override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply { titleRes = R.string.pref_category_library val dbCategories = db.getCategories().executeAsBlocking() val categories = listOf(Category.createDefault(context)) + dbCategories preferenceCategory { titleRes = R.string.pref_category_display preference { key = "pref_library_columns" titleRes = R.string.pref_library_columns onClick { LibraryColumnsDialog().showDialog(router) } fun getColumnValue(value: Int): String { return if (value == 0) { context.getString(R.string.label_default) } else { value.toString() } } preferences.portraitColumns().asFlow().combine(preferences.landscapeColumns().asFlow()) { portraitCols, landscapeCols -> Pair(portraitCols, landscapeCols) } .onEach { (portraitCols, landscapeCols) -> val portrait = getColumnValue(portraitCols) val landscape = getColumnValue(landscapeCols) summary = "${context.getString(R.string.portrait)}: $portrait, " + "${context.getString(R.string.landscape)}: $landscape" } .launchIn(viewScope) } if (!context.isTablet()) { switchPreference { key = Keys.jumpToChapters titleRes = R.string.pref_jump_to_chapters defaultValue = false } } } preferenceCategory { titleRes = R.string.categories preference { key = "pref_action_edit_categories" titleRes = R.string.action_edit_categories val catCount = dbCategories.size summary = context.resources.getQuantityString(R.plurals.num_categories, catCount, catCount) onClick { router.pushController(CategoryController().withFadeTransaction()) } } intListPreference { key = Keys.defaultCategory titleRes = R.string.default_category entries = arrayOf(context.getString(R.string.default_category_summary)) + categories.map { it.name }.toTypedArray() entryValues = arrayOf("-1") + categories.map { it.id.toString() }.toTypedArray() defaultValue = "-1" val selectedCategory = categories.find { it.id == preferences.defaultCategory() } summary = selectedCategory?.name ?: context.getString(R.string.default_category_summary) onChange { newValue -> summary = categories.find { it.id == (newValue as String).toInt() }?.name ?: context.getString(R.string.default_category_summary) true } } switchPreference { bindTo(preferences.categorizedDisplaySettings()) titleRes = R.string.categorized_display_settings } } preferenceCategory { titleRes = R.string.pref_category_library_update intListPreference { bindTo(preferences.libraryUpdateInterval()) titleRes = R.string.pref_library_update_interval entriesRes = arrayOf( R.string.update_never, R.string.update_12hour, R.string.update_24hour, R.string.update_48hour, R.string.update_72hour, R.string.update_weekly ) entryValues = arrayOf("0", "12", "24", "48", "72", "168") summary = "%s" onChange { newValue -> val interval = (newValue as String).toInt() LibraryUpdateJob.setupTask(context, interval) true } } multiSelectListPreference { bindTo(preferences.libraryUpdateDeviceRestriction()) titleRes = R.string.pref_library_update_restriction entriesRes = arrayOf(R.string.connected_to_wifi, R.string.charging) entryValues = arrayOf(DEVICE_ONLY_ON_WIFI, DEVICE_CHARGING) visibleIf(preferences.libraryUpdateInterval()) { it > 0 } onChange { // Post to event looper to allow the preference to be updated. ContextCompat.getMainExecutor(context).execute { LibraryUpdateJob.setupTask(context) } true } fun updateSummary() { val restrictions = preferences.libraryUpdateDeviceRestriction().get() .sorted() .map { when (it) { DEVICE_ONLY_ON_WIFI -> context.getString(R.string.connected_to_wifi) DEVICE_CHARGING -> context.getString(R.string.charging) else -> it } } val restrictionsText = if (restrictions.isEmpty()) { context.getString(R.string.none) } else { restrictions.joinToString() } summary = context.getString(R.string.restrictions, restrictionsText) } preferences.libraryUpdateDeviceRestriction().asFlow() .onEach { updateSummary() } .launchIn(viewScope) } multiSelectListPreference { bindTo(preferences.libraryUpdateMangaRestriction()) titleRes = R.string.pref_library_update_manga_restriction entriesRes = arrayOf(R.string.pref_update_only_completely_read, R.string.pref_update_only_non_completed) entryValues = arrayOf(MANGA_FULLY_READ, MANGA_ONGOING) fun updateSummary() { val restrictions = preferences.libraryUpdateMangaRestriction().get() .sorted() .map { when (it) { MANGA_ONGOING -> context.getString(R.string.pref_update_only_non_completed) MANGA_FULLY_READ -> context.getString(R.string.pref_update_only_completely_read) else -> it } } val restrictionsText = if (restrictions.isEmpty()) { context.getString(R.string.none) } else { restrictions.joinToString() } summary = context.getString(R.string.only_update_restrictions, restrictionsText) } preferences.libraryUpdateMangaRestriction().asFlow() .onEach { updateSummary() } .launchIn(viewScope) } preference { bindTo(preferences.libraryUpdateCategories()) titleRes = R.string.categories onClick { LibraryGlobalUpdateCategoriesDialog().showDialog(router) } fun updateSummary() { val includedCategories = preferences.libraryUpdateCategories().get() .mapNotNull { id -> categories.find { it.id == id.toInt() } } .sortedBy { it.order } val excludedCategories = preferences.libraryUpdateCategoriesExclude().get() .mapNotNull { id -> categories.find { it.id == id.toInt() } } .sortedBy { it.order } val includedItemsText = if (includedCategories.isEmpty()) { context.getString(R.string.none) } else { if (includedCategories.size == categories.size) context.getString(R.string.all) else includedCategories.joinToString { it.name } } val excludedItemsText = if (excludedCategories.isEmpty()) { context.getString(R.string.none) } else { if (excludedCategories.size == categories.size) context.getString(R.string.all) else excludedCategories.joinToString { it.name } } summary = buildSpannedString { append(context.getString(R.string.include, includedItemsText)) appendLine() append(context.getString(R.string.exclude, excludedItemsText)) } } preferences.libraryUpdateCategories().asFlow() .onEach { updateSummary() } .launchIn(viewScope) preferences.libraryUpdateCategoriesExclude().asFlow() .onEach { updateSummary() } .launchIn(viewScope) } switchPreference { key = Keys.autoUpdateMetadata titleRes = R.string.pref_library_update_refresh_metadata summaryRes = R.string.pref_library_update_refresh_metadata_summary defaultValue = false } if (trackManager.hasLoggedServices()) { switchPreference { key = Keys.autoUpdateTrackers titleRes = R.string.pref_library_update_refresh_trackers summaryRes = R.string.pref_library_update_refresh_trackers_summary defaultValue = false } } } } class LibraryColumnsDialog : DialogController() { private val preferences: PreferencesHelper = Injekt.get() private var portrait = preferences.portraitColumns().get() private var landscape = preferences.landscapeColumns().get() override fun onCreateDialog(savedViewState: Bundle?): Dialog { val binding = PrefLibraryColumnsBinding.inflate(LayoutInflater.from(activity!!)) onViewCreated(binding) return MaterialAlertDialogBuilder(activity!!) .setTitle(R.string.pref_library_columns) .setView(binding.root) .setPositiveButton(android.R.string.ok) { _, _ -> preferences.portraitColumns().set(portrait) preferences.landscapeColumns().set(landscape) } .setNegativeButton(android.R.string.cancel, null) .create() } fun onViewCreated(binding: PrefLibraryColumnsBinding) { with(binding.portraitColumns) { displayedValues = arrayOf(context.getString(R.string.label_default)) + IntRange(1, 10).map(Int::toString) value = portrait setOnValueChangedListener { _, _, newValue -> portrait = newValue } } with(binding.landscapeColumns) { displayedValues = arrayOf(context.getString(R.string.label_default)) + IntRange(1, 10).map(Int::toString) value = landscape setOnValueChangedListener { _, _, newValue -> landscape = newValue } } } } class LibraryGlobalUpdateCategoriesDialog : DialogController() { private val preferences: PreferencesHelper = Injekt.get() private val db: DatabaseHelper = Injekt.get() override fun onCreateDialog(savedViewState: Bundle?): Dialog { val dbCategories = db.getCategories().executeAsBlocking() val categories = listOf(Category.createDefault(activity!!)) + dbCategories val items = categories.map { it.name } var selected = categories .map { when (it.id.toString()) { in preferences.libraryUpdateCategories().get() -> QuadStateTextView.State.CHECKED.ordinal in preferences.libraryUpdateCategoriesExclude().get() -> QuadStateTextView.State.INVERSED.ordinal else -> QuadStateTextView.State.UNCHECKED.ordinal } } .toIntArray() return MaterialAlertDialogBuilder(activity!!) .setTitle(R.string.categories) .setQuadStateMultiChoiceItems( message = R.string.pref_library_update_categories_details, items = items, initialSelected = selected ) { selections -> selected = selections } .setPositiveButton(android.R.string.ok) { _, _ -> val included = selected .mapIndexed { index, value -> if (value == QuadStateTextView.State.CHECKED.ordinal) index else null } .filterNotNull() .map { categories[it].id.toString() } .toSet() val excluded = selected .mapIndexed { index, value -> if (value == QuadStateTextView.State.INVERSED.ordinal) index else null } .filterNotNull() .map { categories[it].id.toString() } .toSet() preferences.libraryUpdateCategories().set(included) preferences.libraryUpdateCategoriesExclude().set(excluded) } .setNegativeButton(android.R.string.cancel, null) .create() } } }
apache-2.0
bdb8ff57e6820b8a94cc1c911dacc703
43.405836
172
0.562929
5.567343
false
false
false
false
sephiroth74/Material-BottomNavigation
bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/TabletLayout.kt
1
4616
package it.sephiroth.android.library.bottomnavigation import android.annotation.SuppressLint import android.content.Context import android.view.MotionEvent import android.view.View import android.widget.LinearLayout import android.widget.Toast import it.sephiroth.android.library.bottonnavigation.R import timber.log.Timber /** * Created by crugnola on 4/4/16. * MaterialBottomNavigation */ class TabletLayout(context: Context) : ItemsLayoutContainer(context) { private val itemHeight: Int private val itemPaddingTop: Int private var hasFrame: Boolean = false private var selectedIndex: Int = 0 private var menu: MenuParser.Menu? = null init { val res = resources selectedIndex = 0 itemHeight = res.getDimensionPixelSize(R.dimen.bbn_tablet_item_height) itemPaddingTop = res.getDimensionPixelSize(R.dimen.bbn_tablet_layout_padding_top) } override fun removeAll() { removeAllViews() selectedIndex = 0 menu = null } override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) { if (!hasFrame || childCount == 0) { return } var top = itemPaddingTop for (i in 0 until childCount) { val child = getChildAt(i) val params = child.layoutParams setChildFrame(child, 0, top, params.width, params.height) top += child.height } } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) hasFrame = true if (null != menu) { populateInternal(menu!!) menu = null } } private fun setChildFrame(child: View, left: Int, top: Int, width: Int, height: Int) { Timber.v("setChildFrame: $left, $top, $width, $height") child.layout(left, top, left + width, top + height) } override fun setSelectedIndex(index: Int, animate: Boolean) { Timber.v("setSelectedIndex: $index") if (selectedIndex == index) { return } val oldSelectedIndex = this.selectedIndex this.selectedIndex = index if (!hasFrame || childCount == 0) { return } val current = getChildAt(oldSelectedIndex) as BottomNavigationTabletItemView? val child = getChildAt(index) as BottomNavigationTabletItemView? current?.setExpanded(false, 0, animate) child?.setExpanded(true, 0, animate) } override fun setItemEnabled(index: Int, enabled: Boolean) { Timber.v("setItemEnabled($index, $enabled)") val child = getChildAt(index) as BottomNavigationItemViewAbstract? child?.let { it.isEnabled = enabled it.postInvalidate() requestLayout() } } override fun getSelectedIndex(): Int { return selectedIndex } override fun populate(menu: MenuParser.Menu) { Timber.v("populate: $menu") if (hasFrame) { populateInternal(menu) } else { this.menu = menu } } @SuppressLint("ClickableViewAccessibility") private fun populateInternal(menu: MenuParser.Menu) { Timber.v("populateInternal") val parent = parent as BottomNavigation for (i in 0 until menu.itemsCount) { val item = menu.getItemAt(i) Timber.v("item: $item") val params = LinearLayout.LayoutParams(width, itemHeight) val view = BottomNavigationTabletItemView(parent, i == selectedIndex, menu) view.item = item view.layoutParams = params view.isClickable = true view.setTypeface(parent.typeface) val finalI = i view.setOnTouchListener { v, event -> val action = event.actionMasked if (action == MotionEvent.ACTION_DOWN) { itemClickListener?.onItemDown(this@TabletLayout, v, true, event.x, event.y) } else if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) { itemClickListener?.onItemDown(this@TabletLayout, v, false, event.x, event.y) } false } view.setOnClickListener { v -> itemClickListener?.onItemClick(this@TabletLayout, v, finalI, true) } view.setOnLongClickListener { Toast.makeText(context, item.title, Toast.LENGTH_SHORT).show() true } addView(view) } } }
mit
3be5fdd3f20a42e1af7ed908f53fba43
30.834483
100
0.601603
4.602193
false
false
false
false
icarumbas/bagel
core/src/ru/icarumbas/bagel/utils/B2dCategoryBits.kt
1
376
package ru.icarumbas.bagel.utils const val GROUND_BIT: Short = 2 const val PLATFORM_BIT: Short = 4 const val PLAYER_BIT: Short = 8 const val PLAYER_FEET_BIT: Short = 16 const val KEY_OPEN_BIT: Short = 32 const val BREAKABLE_BIT: Short = 64 const val AI_BIT: Short = 256 const val WEAPON_BIT: Short = 512 const val STATIC_BIT: Short = 1024 const val SHARP_BIT: Short = 2048
apache-2.0
5899d5028c5df882ab770ba2e2fb664a
25.857143
37
0.734043
3.107438
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UITextView_Cursor.kt
1
8011
package com.yy.codex.uikit import android.content.ClipboardManager import android.content.Context import com.yy.codex.foundation.lets /** * Created by cuiminghui on 2017/2/8. */ internal fun UITextView.showCursorView() { cursorView.hidden = false cursorView.setBackgroundColor(tintColor) resetCursorLayout() setupCursorAnimation() } private fun UITextView.setupCursorAnimation() { cursorOptID = System.currentTimeMillis() removeCursorAnimation() runCursorAnimation(true) } private fun UITextView.runCursorAnimation(show: Boolean) { val currentID = cursorOptID if (show) { cursorViewAnimation = UIViewAnimator.linear(0.15, Runnable { cursorView.alpha = 1.0f }, Runnable { postDelayed({ if (currentID != cursorOptID) { return@postDelayed } runCursorAnimation(false) }, 500) }) } else { cursorViewAnimation = UIViewAnimator.linear(0.15, Runnable { cursorView.alpha = 0.0f }, Runnable { postDelayed({ if (currentID != cursorOptID) { return@postDelayed } runCursorAnimation(true) }, 500) }) } } internal fun UITextView.hideCursorView() { removeCursorAnimation() cursorView.hidden = true } internal fun UITextView.removeCursorAnimation() { cursorViewAnimation?.let(UIViewAnimation::cancel) } internal fun UITextView.operateCursor(sender: UILongPressGestureRecognizer) { if (isFirstResponder()) { if (selection != null) { operateSelection(sender) return } val location = sender.location(label) moveCursor(location.setY(location.y)) } } internal fun UITextView.operateCursor(sender: UITapGestureRecognizer) { if (isFirstResponder()) { if (selection != null) { operateSelection(sender) return } val location = sender.location(label) moveCursor(location.setY(location.y)) } } private fun UITextView.moveCursor(pt: CGPoint) { label.textPosition(CGPoint(pt.x, pt.y))?.let { input.editor?.setSelection(it) resetCursorLayout() } } internal fun UITextView.showPositionMenu() { val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager var menuItems: MutableList<UIMenuItem> = mutableListOf() if (input.editor?.length() ?: 0 > 0) { menuItems.add(UIMenuItem("选择", this, "onChoose")) menuItems.add(UIMenuItem("全选", this, "onChooseAll")) } if (manager.hasPrimaryClip() && manager.primaryClip.itemCount > 0) { menuItems.add(UIMenuItem("粘贴", this, "onPaste")) } if (menuItems.count() == 0) { return } UIMenuController.sharedMenuController.menuItems = menuItems UIMenuController.sharedMenuController.setTargetWithRect(CGRect(0.0, 0.0, 0.0, 0.0), cursorView, this) UIMenuController.sharedMenuController.setMenuVisible(true, true) } internal fun UITextView.resetSelection() { if (selection == null) { label.selectText(null) showCursorView() UIMenuController.sharedMenuController.setMenuVisible(false, true) return } selection?.let { hideCursorView() label.selectText(it) showSelectionMenu() input.editor?.setSelection(it.location, it.location + it.length) } } internal fun UITextView.showSelectionMenu() { if (selectionOperatingLeft || selectionOperatingRight) { return } lets(label.selectorLeftHandleView, label.selectorRightHandleView) { selectorLeftHandleView, selectorRightHandleView -> val manager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager var menuItems: MutableList<UIMenuItem> = mutableListOf() menuItems.add(UIMenuItem("剪切", this, "onCrop")) menuItems.add(UIMenuItem("拷贝", this, "onCopy")) if (manager.hasPrimaryClip() && manager.primaryClip.itemCount > 0) { menuItems.add(UIMenuItem("粘贴", this, "onPaste")) } UIMenuController.sharedMenuController.menuItems = menuItems UIMenuController.sharedMenuController.setTargetWithRect(CGRect(0.0, 10.0, selectorRightHandleView.frame.x + 10.0 - selectorLeftHandleView.frame.x, 0.0), selectorLeftHandleView, this) postDelayed({ UIMenuController.sharedMenuController.setMenuVisible(true, true) }, 300) } } internal fun UITextView.operateSelection(sender: UILongPressGestureRecognizer) { lets(label.selectorLeftHandleView, label.selectorRightHandleView) { selectorLeftHandleView, selectorRightHandleView -> var touchPoint = sender.location(label) if (sender.state == UIGestureRecognizerState.Began) { selectionOperatingLeft = false selectionOperatingRight = false if (UIViewHelpers.pointInside(selectorLeftHandleView, label.convertPoint(touchPoint, selectorLeftHandleView), CGPoint(22.0, 22.0))) { selectionOperatingLeft = true UIMenuController.sharedMenuController.setMenuVisible(false, true) } else if (UIViewHelpers.pointInside(selectorRightHandleView, label.convertPoint(touchPoint, selectorRightHandleView), CGPoint(22.0, 22.0))) { selectionOperatingRight = true UIMenuController.sharedMenuController.setMenuVisible(false, true) } else { selection = null moveCursor(sender.location(label)) } } else if (sender.state == UIGestureRecognizerState.Changed) { if (selectionOperatingLeft) { moveSelectionLeft(touchPoint.x, touchPoint.y) } else if (selectionOperatingRight) { moveSelectionRight(touchPoint.x, touchPoint.y) } } else if (sender.state == UIGestureRecognizerState.Ended) { if (selectionOperatingLeft) { moveSelectionLeft(touchPoint.x, touchPoint.y) selectionOperatingLeft = false showSelectionMenu() } else if (selectionOperatingRight) { moveSelectionRight(touchPoint.x, touchPoint.y) selectionOperatingRight = false showSelectionMenu() } } } } private fun UITextView.moveSelectionLeft(x: Double, y: Double) { label.textPosition(CGPoint(x, y))?.let { val newPosition = it selection?.let { if (it.location + it.length - newPosition <= 0) { selection = NSRange(it.location + it.length - 1, 1) } else { selection = NSRange(newPosition, it.location + it.length - newPosition) } } } } private fun UITextView.moveSelectionRight(x: Double, y: Double) { label.textPosition(CGPoint(x, y))?.let { val newPosition = it selection?.let { if (newPosition <= it.location) { selection = NSRange(it.location, 1) } else { selection = NSRange(it.location, newPosition - it.location) } } } } internal fun UITextView.operateSelection(sender: UITapGestureRecognizer) { lets(label.selectorLeftHandleView, label.selectorRightHandleView) { selectorLeftHandleView, selectorRightHandleView -> var touchPoint = sender.location(label) if (UIViewHelpers.pointInside(selectorLeftHandleView, label.convertPoint(touchPoint, selectorLeftHandleView), CGPoint(22.0, 22.0)) || UIViewHelpers.pointInside(selectorRightHandleView, label.convertPoint(touchPoint, selectorRightHandleView), CGPoint(22.0, 22.0))) { } else { selection = null moveCursor(sender.location(label)) } } }
gpl-3.0
565f14850f20a4a6198c4a6fa73411fa
34.502222
190
0.637411
4.393289
false
false
false
false
Shynixn/BlockBall
blockball-core/src/main/java/com/github/shynixn/blockball/core/logic/business/commandmenu/AreaProtectionPage.kt
1
5807
package com.github.shynixn.blockball.core.logic.business.commandmenu import com.github.shynixn.blockball.api.business.enumeration.* import com.github.shynixn.blockball.api.persistence.entity.Arena import com.github.shynixn.blockball.api.persistence.entity.ChatBuilder import com.github.shynixn.blockball.core.logic.persistence.entity.ChatBuilderEntity import com.github.shynixn.blockball.core.logic.persistence.entity.PositionEntity /** * Created by Shynixn 2018. * <p> * Version 1.2 * <p> * MIT License * <p> * Copyright (c) 2018 by Shynixn * <p> * 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: * <p> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p> * 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. */ class AreaProtectionPage : Page(AreaProtectionPage.ID, MiscSettingsPage.ID) { companion object { /** Id of the page. */ const val ID = 26 } /** * Returns the key of the command when this page should be executed. * * @return key */ override fun getCommandKey(): MenuPageKey { return MenuPageKey.AREAPROTECTION } /** * Executes actions for this page. * * @param cache cache */ override fun <P> execute(player: P, command: MenuCommand, cache: Array<Any?>, args: Array<String>): MenuCommandResult { val arena = cache[0] as Arena if (command == MenuCommand.AREAPROTECTION_TOGGLE_ENTITYFORCEFIELD) { arena.meta.protectionMeta.entityProtectionEnabled = !arena.meta.protectionMeta.entityProtectionEnabled } else if (command == MenuCommand.AREAPROTECTION_TOGGLE_PLAYERJOINFORCEFIELD) { arena.meta.protectionMeta.rejoinProtectionEnabled = !arena.meta.protectionMeta.rejoinProtectionEnabled } else if (command == MenuCommand.AREAPROTECTION_SET_ENTITYFORCEFIELD && args.size >= 5 && args[2].toDoubleOrNull() != null && args[3].toDoubleOrNull() != null && args[4].toDoubleOrNull() != null ) { arena.meta.protectionMeta.entityProtection = PositionEntity(args[2].toDouble(), args[3].toDouble(), args[4].toDouble()) } else if (command == MenuCommand.AREAPROTECTION_SET_PLAYERJOINFORCEFIELD && args.size >= 5 && args[2].toDoubleOrNull() != null && args[3].toDoubleOrNull() != null && args[4].toDoubleOrNull() != null ) { arena.meta.protectionMeta.rejoinProtection = PositionEntity(args[2].toDouble(), args[3].toDouble(), args[4].toDouble()) } return super.execute(player, command, cache, args) } /** * Builds this page for the player. * * @return page */ override fun buildPage(cache: Array<Any?>): ChatBuilder? { val arena = cache[0] as Arena val meta = arena.meta.protectionMeta return ChatBuilderEntity() .component("- Animal and Monster protection enabled: " + meta.entityProtectionEnabled).builder() .component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.AREAPROTECTION_TOGGLE_ENTITYFORCEFIELD.command) .setHoverText("Toggles allowing animals and monsters to run inside of the arena.") .builder().nextLine() .component("- Animal and Monster protection velocity: " + meta.entityProtection).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.AREAPROTECTION_SET_ENTITYFORCEFIELD.command) .setHoverText( "Changes the velocity being applied to animals and monsters when they try to enter the arena." + "\nEnter 3 values when using this command.\n/blockball aprot enprot <x> <y> <z>" ) .builder().nextLine() .component("- Join protection enabled: " + meta.rejoinProtectionEnabled).builder() .component(MenuClickableItem.TOGGLE.text).setColor(MenuClickableItem.TOGGLE.color) .setClickAction(ChatClickAction.RUN_COMMAND, MenuCommand.AREAPROTECTION_TOGGLE_PLAYERJOINFORCEFIELD.command) .setHoverText("Toggles the protection to move players outside of the arena.") .builder().nextLine() .component("- Join protection velocity: " + meta.rejoinProtection).builder() .component(MenuClickableItem.EDIT.text).setColor(MenuClickableItem.EDIT.color) .setClickAction(ChatClickAction.SUGGEST_COMMAND, MenuCommand.AREAPROTECTION_SET_PLAYERJOINFORCEFIELD.command) .setHoverText( "Changes the velocity being applied to players when they try to enter the arena." + "\nEnter 3 values when using this command.\n/blockball aprot plprot <x> <y> <z>" ) .builder().nextLine() } }
apache-2.0
84c6a50a750d4207a0ca91ed484326d3
51.8
131
0.689685
4.456639
false
false
false
false
mmorihiro/larger-circle
core/src/mmorihiro/matchland/controller/appwarp/WarpController.kt
2
8580
package mmorihiro.matchland.controller.appwarp import com.badlogic.gdx.Gdx import com.badlogic.gdx.graphics.Texture import com.badlogic.gdx.math.MathUtils import com.badlogic.gdx.scenes.scene2d.ui.Image import com.shephertz.app42.gaming.multiplayer.client.WarpClient import com.shephertz.app42.gaming.multiplayer.client.command.WarpResponseResultCode.* import com.shephertz.app42.gaming.multiplayer.client.events.LiveRoomInfoEvent import com.squareup.moshi.Types import de.tomgrill.gdxdialogs.core.GDXDialogsSystem import de.tomgrill.gdxdialogs.core.dialogs.GDXButtonDialog import ktx.actors.plus import ktx.assets.asset import mmorihiro.matchland.controller.* import mmorihiro.matchland.model.ConfigModel import mmorihiro.matchland.model.ItemType import mmorihiro.matchland.model.MessageType import mmorihiro.matchland.view.ConnectEvent import mmorihiro.matchland.view.MyImage import mmorihiro.matchland.view.Puzzle import mmorihiro.matchland.view.View import java.lang.reflect.Type class WarpController(private val onStart: () -> Unit, private val onHome: () -> Unit, private val top: View) : Controller { val warpClient: WarpClient by lazy { ClientHolder.client } var roomID = "" var canceled = false var createdRoom = false private val dialogs = GDXDialogsSystem.install() private var errorDialogShown = false override val view = WarpPuzzleView( onTouchDown = { view, x, y -> touchAction(view, x, y) view.connectEvent?.let { sendMessage(MessageType.CONNECT, x, y) view.connectEvent = it.copy( enemy = (view as WarpPuzzleView).enemyConnected) } }, onTouchDragged = { view, x, y -> onTouchDragged(view, x, y, { sendMessage(MessageType.CONNECT, x, y) }, { bx, by -> sendMessage(MessageType.NotConnect, bx.toInt(), by.toInt()) }) }, onTouchUp = { view -> val warpView = view as WarpPuzzleView if (warpView.connectEvent == null) return@WarpPuzzleView val connectEvent = warpView.connectEvent!! onTouchUp(view, { event -> sendMessage(MessageType.TouchUp) if (view.isEnemyTouchUp) { view.enemyConnected = listOf() iconReaction(view, event.enemy, false) iconReaction(view, event.connectedItems, true) addNewItems(view, event) sendNewItems(view, event) view.isEnemyTouchUp = false changeBarValue(view) } else { view.isPlayerTouchUp = true view.connectEvent = connectEvent } }, { sendMessage(MessageType.NotEnough) }) }, onFinish = { disconnect() }, onHome = onHome, top = top) init { ClientHolder.addListeners(this) warpClient.connectWithUserName("${view.playerType.name}@${MathUtils.random(1000)}") } fun startGame(event: LiveRoomInfoEvent, users: List<String>) = view.run { Gdx.input.inputProcessor = null onStart() StageChangeEffect().resumeEffect(top) enemyType = users.first { it != playerType.name }.let { typeName -> ItemType.values().first { it.name == typeName.split("@").first() } } this + backGround this + itemLayer val adapter = ConfigModel.moshi.adapter(IconList::class.java) val list = adapter.fromJson(event.properties["iconList"].toString())!!.list val type0 = event.properties["type0"].toString().let { colorName -> ItemType.values().first { it.name == colorName } } val type1 = if (type0 == enemyType) playerType else enemyType tiles = (0 until colSize).map { yIndex -> (0 until rowSize).map { xIndex -> val itemType = when (yIndex) { 0 -> type0 colSize - 1 -> type1 else -> ItemType.WATER } MyImage(Image(asset<Texture>("tile.png")), itemType.position).apply { x = 19 + xIndex * tileSize y = yIndex * tileSize + bottom color = itemType.color } } } items = list.mapIndexed { yIndex, it -> it.mapIndexed { xIndex, type -> itemLoader.load( listOf(type0, type1, ItemType.WATER)[type].position) .apply { val tile = tiles[yIndex][xIndex] setPosition(tile.x + padding, tile.y + padding) } }.toMutableList() }.toMutableList() tiles.forEach { it.forEach { itemLayer + it } } items.forEach { it.forEach { itemLayer + it } } this + cover Gdx.input.inputProcessor = this } private fun sendMessage(type: MessageType, x: Int = -1, y: Int = -1) { val adapter = ConfigModel.moshi.adapter(Point::class.java) val json = if (x >= 0 && y >= 0) adapter.toJson(Point(x, y)) else "" warpClient.sendUpdatePeers("${ConfigModel.config.itemType.name}@${type.name}@$json" .toByteArray()) } private fun sendNewItems(view: Puzzle, event: ConnectEvent) { val items = (event.enemy + event.connectedItems).map { val position = view.items[it.second][it.first].type val type = ItemType.values().first { it.position == position } NewItem(type, it.first, it.second) } val type: Type = Types.newParameterizedType(List::class.java, NewItem::class.java) val adapter = ConfigModel.moshi.adapter<List<NewItem>>(type) val str = adapter.toJson(items) warpClient.sendUpdatePeers("${ConfigModel.config.itemType .name}@${MessageType.NewItem.name}@$str".toByteArray()) } internal fun onLobbyError(where: String?, result: Byte) { if (errorDialogShown) return else errorDialogShown = true disconnect() val (resultCode, resultText) = when (result) { AUTH_ERROR -> "AUTH_ERROR" to "The session id sent in the request was incorrect. This can happen if the client connects without initializing with the correct keys." RESOURCE_MOVED -> "RESOURCE_MOVED" to "The resource for which the request was intended to has moved to a state where it can’t process the request. For example, if a client sends a chat or updatePeers message and the connected user is not present in any room." UNKNOWN_ERROR -> "UNKNOWN_ERROR" to "This is an unexpected error. Retrying the request is recommended if this happens." BAD_REQUEST -> "BAD_REQUEST" to "This occurs if the parameters passed to the request are invalid. For example if null or empty string is passed in the roomId parameter of a joinRoom request." CONNECTION_ERROR -> "CONNECTION_ERROR" to "This occurs if the underlying TCP connection with AppWarp cloud service got broken. The client will need to reconnect to the service and retry the operation." SUCCESS_RECOVERED -> "SUCCESS_RECOVERED" to "This occurs if when successfully recover a session." CONNECTION_ERROR_RECOVERABLE -> "CONNECTION_ERROR_RECOVERABLE" to "This occurs if the underlying TCP connection with AppWarp cloud service got broken but same session can be recovered. The client will need call RecoverConnection() to resume same session." USER_PAUSED_ERROR -> "USER_PAUSED_ERROR" to "" AUTO_RECOVERING -> "AUTO_RECOVERING" to "" else -> "Unknown error " + result to "" } val bDialog = dialogs.newDialog(GDXButtonDialog::class.java) bDialog.setTitle("Error") bDialog.setMessage("Failed to connect to server($where): $resultCode\n$resultText") bDialog.addButton("OK") bDialog.setClickListener { errorDialogShown = false Gdx.app.postRunnable { onHome() StageChangeEffect().resumeEffect(top) } } bDialog.build().show() } fun disconnect() { if (roomID.isNotEmpty()) { warpClient.unsubscribeRoom(roomID) warpClient.leaveRoom(roomID) warpClient.deleteRoom(roomID) warpClient.disconnect() } } }
apache-2.0
f3ac55c9c5ae1c18384ca7aad8af53f1
45.367568
271
0.611448
4.467708
false
false
false
false
dataloom/conductor-client
src/main/kotlin/com/openlattice/hazelcast/serializers/BulkLinkedDataLambdasStreamSerializer.kt
1
3914
package com.openlattice.hazelcast.serializers import com.dataloom.mappers.ObjectMappers import com.esotericsoftware.kryo.Kryo import com.esotericsoftware.kryo.Serializer import com.esotericsoftware.kryo.io.Input import com.esotericsoftware.kryo.io.Output import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.readValue import com.openlattice.conductor.rpc.BulkLinkedDataLambdas import org.slf4j.LoggerFactory import org.springframework.stereotype.Component import java.io.IOException import java.util.UUID @Component class BulkLinkedDataLambdasStreamSerializer( private val mapper: ObjectMapper = ObjectMappers.getSmileMapper() ) : Serializer<BulkLinkedDataLambdas>() { companion object { private val logger = LoggerFactory.getLogger(BulkLinkedDataLambdasStreamSerializer::class.java) } private fun writeUUID(output: Output, id: UUID) { output.writeLong(id.leastSignificantBits) output.writeLong(id.mostSignificantBits) } private fun readUUID(input: Input): UUID { val lsb = input.readLong() val msb = input.readLong() return UUID(msb, lsb) } override fun write(kryo: Kryo, output: Output, data: BulkLinkedDataLambdas) { writeUUID(output, data.entityTypeId) try { output.writeInt(data.entitiesByLinkingId.size) data.entitiesByLinkingId.forEach { (linkingId, entitiesOfLinkingId) -> writeUUID(output, linkingId) output.writeInt(entitiesOfLinkingId.size) entitiesOfLinkingId.forEach { (entitySetId, entitiesOfEntitySetId) -> writeUUID(output, entitySetId) output.writeInt(entitiesOfEntitySetId.size) entitiesOfEntitySetId.forEach { (originId, entityData) -> writeUUID(output, originId) val bytes = mapper.writeValueAsBytes(entityData) output.writeInt(bytes.size) output.writeBytes(bytes) } } } } catch (e: JsonProcessingException) { logger.debug("Unable to serialize linking entities with linking ids: {}", data.entitiesByLinkingId.keys) } } override fun read(kryo: Kryo, input: Input, type: Class<BulkLinkedDataLambdas>): BulkLinkedDataLambdas { val entityTypeId = readUUID(input) val linkingIdsSize = input.readInt() val entitiesByLinkingId = HashMap<UUID, Map<UUID, Map<UUID, Map<UUID, Set<Any>>>>>(linkingIdsSize) for (i in 1..linkingIdsSize) { val linkingId = readUUID(input) val entitySetsSize = input.readInt() val entitiesByEntitySetId = HashMap<UUID, Map<UUID, Map<UUID, Set<Any>>>>(entitySetsSize) for (j in 1..entitySetsSize) { val entitySetId = readUUID(input) val originIdsSize = input.readInt() val entitiesByOriginId = HashMap<UUID, Map<UUID, Set<Any>>>(originIdsSize) for (k in 1..originIdsSize) { val originId = readUUID(input) val numBytes = input.readInt() try { val entityData = mapper.readValue<Map<UUID, Set<Any>>>(input.readBytes(numBytes)) entitiesByOriginId[originId] = entityData } catch (e: IOException) { logger.debug("Unable to deserialize entities for linking id: {}", linkingId) } } entitiesByEntitySetId[entitySetId] = entitiesByOriginId } entitiesByLinkingId[linkingId] = entitiesByEntitySetId } return BulkLinkedDataLambdas(entityTypeId, entitiesByLinkingId) } }
gpl-3.0
456093e6cefc26413ea7a4a74aa49334
38.938776
116
0.639244
4.75
false
false
false
false
pnemonic78/RemoveDuplicates
duplicates-android/app/src/main/java/com/github/duplicates/message/MessageItem.kt
1
2877
/* * Copyright 2016, Moshe Waisberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.duplicates.message import android.provider.Telephony import com.github.duplicates.DuplicateItem import com.github.duplicates.DuplicateItemType /** * Duplicate message item. * * @author moshe.w */ class MessageItem : DuplicateItem(DuplicateItemType.MESSAGE) { var address: String? = null var body: String? = null set(value) { var body = value if (body != null) { body = body.replace("\\s+".toRegex(), " ") } field = body } var dateReceived: Long = 0 var dateSent: Long = 0 var errorCode: Int = 0 var isLocked: Boolean = false var person: Int = 0 var protocol: Int = 0 var isRead: Boolean = false var isSeen: Boolean = false var status = STATUS_NONE var subject: String? = null var threadId: Long = 0 var type = MESSAGE_TYPE_ALL override fun contains(s: CharSequence): Boolean { return (address?.contains(s, true) ?: false) || (body?.contains(s, true) ?: false) || (subject?.contains(s, true) ?: false) } companion object { /** * Message type: all messages. */ const val MESSAGE_TYPE_ALL = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_ALL /** * Message type: inbox. */ const val MESSAGE_TYPE_INBOX = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_INBOX /** * Message type: sent messages. */ const val MESSAGE_TYPE_SENT = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_SENT /** * Message type: drafts. */ const val MESSAGE_TYPE_DRAFT = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_DRAFT /** * Message type: outbox. */ const val MESSAGE_TYPE_OUTBOX = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_OUTBOX /** * Message type: failed outgoing message. */ const val MESSAGE_TYPE_FAILED = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_FAILED /** * Message type: queued to send later. */ const val MESSAGE_TYPE_QUEUED = Telephony.TextBasedSmsColumns.MESSAGE_TYPE_QUEUED const val STATUS_NONE = Telephony.TextBasedSmsColumns.STATUS_NONE } }
apache-2.0
5596190a8c439c2bc51f26483cd7183d
28.96875
89
0.62878
4.28763
false
false
false
false
pacien/tincapp
app/src/main/java/org/pacien/tincapp/commands/Command.kt
1
1575
/* * Tinc App, an Android binding and user interface for the tinc mesh VPN daemon * Copyright (C) 2017-2020 Pacien TRAN-GIRARD * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.pacien.tincapp.commands import java.util.* /** * @author pacien */ internal class Command(private val cmd: String) { private data class Option(val key: String, val value: String?) { fun toCommandLineOption(): String = if (value != null) "--$key=$value" else "--$key" } private val opts: MutableList<Option> = LinkedList() private val args: MutableList<String> = LinkedList() fun withOption(key: String, value: String? = null): Command { this.opts.add(Option(key, value)) return this } fun withArguments(vararg args: String): Command { this.args.addAll(listOf(*args)) return this } fun asList(): List<String> = listOf(cmd) + opts.map { it.toCommandLineOption() } + args fun asArray(): Array<String> = this.asList().toTypedArray() }
gpl-3.0
561566fd8ad910410d9106026232761d
33.23913
89
0.709841
3.888889
false
false
false
false
lewinskimaciej/planner
app/src/main/java/com/atc/planner/data/repository/places_repository/PlacesRepositoryImpl.kt
1
5788
package com.atc.planner.data.repository.places_repository import com.atc.planner.R import com.atc.planner.commons.CityProvider import com.atc.planner.commons.StringProvider import com.atc.planner.data.model.local.Beacon import com.atc.planner.data.model.local.Place import com.atc.planner.data.remote_service.DirectionsRemoteService import com.atc.planner.data.repository.places_repository.data_source.firebase_database.FirebaseDatabaseDataSource import com.atc.planner.extension.asLatLng import com.atc.planner.extension.asLocation import com.github.ajalt.timberkt.d import com.github.ajalt.timberkt.e import com.google.android.gms.maps.model.LatLng import io.reactivex.Single import javax.inject.Inject import javax.inject.Singleton @Singleton class PlacesRepositoryImpl @Inject constructor(private val firebaseDatabaseDataSource: FirebaseDatabaseDataSource, private val directionsRemoteService: DirectionsRemoteService, private val cityProvider: CityProvider, private val stringProvider: StringProvider) : PlacesRepository { private var places: List<Place> = listOf() private var beaconsNearby: List<Beacon> = listOf() override fun getLocallySavedPlacesNearby(): List<Place> = places override fun getPlacesNearby(latLng: LatLng, filterDetails: SightsFilterDetails?): Single<List<Place>> { val city = cityProvider.getCity(latLng) return if (city != null) { firebaseDatabaseDataSource.getPlaces(city, filterDetails) .doOnSuccess { places = it } } else { Single.error(NoSuchElementException("City for these coordinates was not found")) } } override fun getPlaceByAreaId(areaId: String?): Single<Place> = firebaseDatabaseDataSource.getPlaceByAreaId(areaId) override fun getBeaconsNearby(latLng: LatLng): Single<List<Beacon>> { if (beaconsNearby.isNotEmpty()) { return Single.just(beaconsNearby) } val city = cityProvider.getCity(latLng) return if (city != null) { firebaseDatabaseDataSource.getBeaconsNearby(city) .doOnSuccess { beaconsNearby = it } .doOnError(::e) } else { Single.error(NoSuchElementException("City for these coordinates was not found")) } } override fun getDirections(source: LatLng, dest: LatLng) = directionsRemoteService.getDirections("${source.latitude},${source.longitude}", "${dest.latitude},${dest.longitude}", stringProvider.getString(R.string.places_api_key)) override fun getRoute(currentLocation: LatLng, filterDetails: SightsFilterDetails?): Single<ArrayList<Place?>> = Single.create { emitter -> d { "getRoute" } val placesToChooseFrom = ArrayList(places) val chosenPlaces: ArrayList<Place?> = arrayListOf() var closestPlace: Place? = null var closestPlaceDistance = Float.MAX_VALUE for (index in places.indices) { val distance = currentLocation.asLocation().distanceTo(places[index].location.asLatLng().asLocation()) if (distance < closestPlaceDistance) { closestPlace = places[index] closestPlaceDistance = distance } } chosenPlaces.add(closestPlace) placesToChooseFrom.remove(closestPlace) var lastBestPlace = closestPlace for (count in 0..10) { val tempPlace = lastBestPlace?.getHighestRatedClosePlace(filterDetails, placesToChooseFrom) lastBestPlace = tempPlace if (tempPlace != null) { chosenPlaces.add(tempPlace) placesToChooseFrom.remove(tempPlace) } } emitter.onSuccess(chosenPlaces) } private fun Place.getHighestRatedClosePlace(filterDetails: SightsFilterDetails?, placesToChooseFrom: ArrayList<Place>): Place? { var highestRatedPlace: Place? = null // point of origin var highestRatedPlaceWeight = 0f for (place in placesToChooseFrom) { val placeWeight = place.attractiveness(this.location.asLatLng(), filterDetails, placesToChooseFrom) if (placeWeight > highestRatedPlaceWeight) { highestRatedPlace = place highestRatedPlaceWeight = placeWeight } } return highestRatedPlace } private fun Place.attractiveness(currentLocation: LatLng, filterDetails: SightsFilterDetails?, placesToChooseFrom: ArrayList<Place>): Float { val maxDistance = placesToChooseFrom.maximumDistanceFrom(this) val distance = this.location.asLatLng().asLocation().distanceTo(currentLocation.asLocation()) var attractiveness: Float = (maxDistance - distance) / 10 attractiveness += this.rating * 3 if (filterDetails?.hasSouvenirs == true) { attractiveness += 5 } if (filterDetails?.childrenFriendly == true) { attractiveness += 5 } return attractiveness } private fun List<Place>?.maximumDistanceFrom(place: Place): Float { var highestDistance = 0f if (this != null) { for (index in this.indices) { val distance = place.location?.asLatLng().asLocation().distanceTo(this[index].location?.asLatLng().asLocation()) if (distance > highestDistance) { highestDistance = distance } } } return highestDistance } }
mit
a07c85d5dd20245d957ab2e9314a3b7f
39.194444
145
0.642709
4.783471
false
false
false
false
carlphilipp/stock-tracker-android
src/fr/cph/stock/android/activity/LoginActivity.kt
1
5468
/** * Copyright 2017 Carl-Philipp Harmant * * * 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 fr.cph.stock.android.activity import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.app.Activity import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.view.View import android.widget.CheckBox import android.widget.EditText import android.widget.TextView import fr.cph.stock.android.Constants.LOGIN import fr.cph.stock.android.Constants.PASSWORD import fr.cph.stock.android.Constants.PORTFOLIO import fr.cph.stock.android.Constants.PREFS_NAME import fr.cph.stock.android.Constants.RED import fr.cph.stock.android.R import fr.cph.stock.android.domain.Portfolio import fr.cph.stock.android.domain.UrlType import fr.cph.stock.android.task.MainTask import fr.cph.stock.android.web.Md5 import org.json.JSONObject /** * Activity which displays a login screen to the user. */ class LoginActivity : Activity(), StockTrackerActivity { private lateinit var login: String private lateinit var password: String // UI references. private lateinit var loginView: EditText private lateinit var passwordView: EditText private lateinit var checkBox: CheckBox private lateinit var loginFormView: View private lateinit var loginStatusView: View private lateinit var loginStatusMessageView: TextView private lateinit var errorView: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.login_activity) loginView = findViewById(R.id.email) errorView = findViewById(R.id.login_error) passwordView = findViewById(R.id.password) checkBox = findViewById(R.id.checkbox) loginFormView = findViewById(R.id.login_form) loginStatusView = findViewById(R.id.login_status) loginStatusMessageView = findViewById(R.id.login_status_message) findViewById<View>(R.id.sign_in_button).setOnClickListener { _ -> attemptLogin() } } private fun attemptLogin() { // Reset errors. loginView.error = null passwordView.error = null // Store values at the time of the login attempt. login = loginView.text.toString() password = passwordView.text.toString() var cancel = false var focusView: View? = null // Check for a valid password. if (TextUtils.isEmpty(password)) { passwordView.error = getString(R.string.error_field_required) focusView = passwordView cancel = true } // Check for a valid email address. if (TextUtils.isEmpty(login)) { loginView.error = getString(R.string.error_field_required) focusView = loginView cancel = true } if (cancel) { focusView!!.requestFocus() } else { loginStatusMessageView.setText(R.string.login_progress_signing_in) showProgress(true, null) val params = hashMapOf(LOGIN to login, PASSWORD to Md5(password).hexInString) MainTask(this, UrlType.AUTH, params).execute() } } override fun update(portfolio: Portfolio) { finish() if (checkBox.isChecked) { saveCredentials() } val intent = Intent(this, MainActivity::class.java) intent.putExtra(PORTFOLIO, portfolio) startActivity(intent) } override fun displayError(json: JSONObject) { showProgress(false, json.optString("error")) } private fun showProgress(show: Boolean, errorMessage: String?) { val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime) loginStatusView.visibility = View.VISIBLE loginStatusView.animate().setDuration(shortAnimTime.toLong()).alpha((if (show) 1 else 0).toFloat()).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { loginStatusView.visibility = if (show) View.VISIBLE else View.GONE } }) loginFormView.visibility = View.VISIBLE loginFormView.animate().setDuration(shortAnimTime.toLong()).alpha((if (show) 0 else 1).toFloat()).setListener(object : AnimatorListenerAdapter() { override fun onAnimationEnd(animation: Animator) { loginFormView.visibility = if (show) View.GONE else View.VISIBLE } }) if (!show) { errorView.text = errorMessage errorView.setTextColor(RED) } } private fun saveCredentials() { val settings = getSharedPreferences(PREFS_NAME, 0) settings.edit().putString(LOGIN, login).apply() settings.edit().putString(PASSWORD, Md5(password).hexInString).apply() } override fun logOut() { // no-op } }
apache-2.0
d7cd921e8d7721dd60d3c98533784792
33.828025
156
0.682699
4.537759
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/utils/ContentResolverUtil.kt
1
4253
/* * Copyright (c) 2020 David Allison <davidallisongithub@gmail.com> * * 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 com.ichi2.utils import android.content.ContentResolver import android.database.sqlite.SQLiteException import android.net.Uri import android.provider.MediaStore import android.webkit.MimeTypeMap import androidx.annotation.CheckResult import timber.log.Timber import java.io.File import java.lang.Exception import java.lang.IllegalStateException import java.util.* object ContentResolverUtil { /** Obtains the filename from the url. Throws if all methods return exception */ @CheckResult fun getFileName(contentResolver: ContentResolver, uri: Uri): String { try { val filename = getFilenameViaDisplayName(contentResolver, uri) if (filename != null) { return filename } } catch (e: Exception) { Timber.w(e, "getFilenameViaDisplayName") } // let this one throw val filename = getFilenameViaMimeType(contentResolver, uri) if (filename != null) { return filename } throw IllegalStateException("Unable to obtain valid filename from uri: $uri") } @CheckResult private fun getFilenameViaMimeType(contentResolver: ContentResolver, uri: Uri): String? { // value: "png" when testing var extension: String? = null // Check uri format to avoid null if (uri.scheme != null && uri.scheme == ContentResolver.SCHEME_CONTENT) { // If scheme is a content val mime = MimeTypeMap.getSingleton() extension = mime.getExtensionFromMimeType(contentResolver.getType(uri)) } else { // If scheme is a File // This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters. if (uri.path != null) { extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(File(uri.path as String)).toString().lowercase(Locale.ROOT)) } } return if (extension == null) { null } else "image.$extension" } @CheckResult private fun getFilenameViaDisplayName(contentResolver: ContentResolver, uri: Uri): String? { // 7748: android.database.sqlite.SQLiteException: no such column: _display_name (code 1 SQLITE_ERROR[1]): ... try { contentResolver.query(uri, null, null, null, null).use { c -> if (c == null) { return null } c.moveToNext() val mediaIndex = c.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME) if (mediaIndex != -1) { return c.getString(mediaIndex) } // use `_data` column label directly, MediaStore.MediaColumns.DATA is deprecated in API29+ but // the recommended MediaStore.MediaColumns.RELATIVE_PATH does not appear to be available // content uri contains only id and _data columns in samsung clipboard and not media columns // gboard contains media columns and works with MediaStore.MediaColumns.DISPLAY_NAME val dataIndex = c.getColumnIndexOrThrow("_data") val fileUri = Uri.parse(c.getString(dataIndex)) return fileUri.lastPathSegment } } catch (e: SQLiteException) { Timber.w(e, "getFilenameViaDisplayName ContentResolver query failed.") } return null } }
gpl-3.0
c8eb4e4abbdbcdbe86a1adf5cabd7ec3
41.53
176
0.646838
4.800226
false
false
false
false
Aidanvii7/Toolbox
delegates-observable-rxjava/src/main/java/com/aidanvii/toolbox/delegates/observable/rxjava/RxDistinctUntilChangedDecorator.kt
1
1947
package com.aidanvii.toolbox.delegates.observable.rxjava import com.aidanvii.toolbox.delegates.observable.Functions import io.reactivex.Observable import kotlin.reflect.KProperty /** * Returns an [RxObservableProperty] that will only forward items downstream * when a new item is set that is different from the previous item. * @param ST the base type of the source observable ([RxObservableProperty.SourceTransformer]). * @param TT the type on which this [RxObservableProperty] operates. */ fun <ST, TT> RxObservableProperty<ST, TT>.distinctUntilChanged() = RxDistinctUntilChangedDecorator(this, Functions.areEqual) /** * Returns an [RxObservableProperty] that will only forward items downstream * when a new item is set that is different from the previous item. * @param areEqual a function that receives the previous item and the current item and is * expected to return true if the two are equal, thus skipping the current value. * @param ST the base type of the source observable ([RxObservableProperty.SourceTransformer]). * @param TT the type on which this [RxObservableProperty] operates. */ fun <ST, TT> RxObservableProperty<ST, TT>.distinctUntilChanged( areEqual: (oldValue: TT, newValue: TT) -> Boolean ) = RxDistinctUntilChangedDecorator(this, areEqual) class RxDistinctUntilChangedDecorator<ST, TT>( private val decorated: RxObservableProperty<ST, TT>, private val areEqual: ((oldValue: TT, newValue: TT) -> Boolean) ) : RxObservableProperty<ST, TT> by decorated { override val observable: Observable<RxObservableProperty.ValueContainer<TT>> get() = decorated.observable.filter { it.run { oldValue == null || !areEqual(oldValue, newValue) } } operator fun provideDelegate(thisRef: Any?, property: KProperty<*>): RxDistinctUntilChangedDecorator<ST, TT> { onProvideDelegate(thisRef, property) subscribe(observable) return this } }
apache-2.0
754bece194f575632d3411517011a724
45.380952
124
0.748331
4.559719
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/multimediacard/fields/TextField.kt
1
2624
/**************************************************************************************** * Copyright (c) 2013 Bibek Shrestha <bibekshrestha@gmail.com> * * Copyright (c) 2013 Zaur Molotnikov <qutorial@gmail.com> * * Copyright (c) 2013 Nicolas Raoul <nicolas.raoul@gmail.com> * * Copyright (c) 2013 Flavio Lerda <flerda@gmail.com> * * * * 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 com.ichi2.anki.multimediacard.fields import com.ichi2.libanki.Collection /** * Text Field implementation. */ class TextField : FieldBase(), IField { private var mText = "" private var mName: String? = null override val type: EFieldType = EFieldType.TEXT override val isModified: Boolean get() = thisModified override var imagePath: String? = null override var audioPath: String? = null override var text: String? get() = mText set(value) { mText = value!! setThisModified() } override var hasTemporaryMedia: Boolean = false override var name: String? get() = mName set(value) { mName = value } override val formattedValue: String? get() = text override fun setFormattedString(col: Collection, value: String) { mText = value } companion object { private const val serialVersionUID = -6508967905716947525L } }
gpl-3.0
bef5b729b13aecace100ee5860ec88ea
39.369231
90
0.488948
5.258517
false
false
false
false
rock3r/detekt
detekt-rules/src/test/resources/cases/CollapsibleIfsNegative.kt
1
748
package cases @Suppress("unused", "ConstantConditionIf", "SimplifyBooleanWithConstants", "RedundantSemicolon") fun collapsibleIfsNegative() { if (true) { } else if (1 == 1) { if (true) { } } if (true) { if (1 == 1) { } } else { } if (true) { if (1 == 1) { } } else if (false) { } else { } if (true) { if (1 == 1); println() } if (true) { if (1 == 1) { } else { } } if (true) { if (1 == 1) { } else if (2 == 2) { } } if (true) { if (1 == 1) { } println() } if (true) { println() if (1 == 1) { } } }
apache-2.0
73ec9c2b4bc6c8d58dcc975ad5debe7d
12.851852
96
0.34492
3.415525
false
false
false
false
pdvrieze/ProcessManager
java-common/src/javaMain/kotlin/net/devrieze/util/MonitoringCollectionAdapter.kt
1
3543
/* * 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 3 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 net.devrieze.util internal class MonitoringCollectionAdapter<V>(private val delegate: MutableCollection<V>) : MonitorableCollection<V> { private var _listeners: MutableSet<CollectionChangeListener<V>>? = null private val listeners: MutableSet<CollectionChangeListener<V>> get() = _listeners ?: hashSetOf<CollectionChangeListener<V>>().also { _listeners = it } override fun addCollectionChangeListener(listener: CollectionChangeListener<V>) { listeners.add(listener) } override fun removeCollectionChangeListener(listener: CollectionChangeListener<V>) { _listeners?.remove(listener) } private inline fun fireEvent(trigger: CollectionChangeListener<V>.()->Unit) { @Suppress("RemoveExplicitTypeArguments") val error = _listeners?.fold<CollectionChangeListener<V>,MultiException?>(null) { e: MultiException?, listener -> try { listener.trigger() e } catch (f: Exception) { MultiException.add(e,f) } } MultiException.throwIfError(error) } private fun fireAddEvent(element: V) { fireEvent { elementAdded(element) } } private fun fireClearEvent() { fireEvent { collectionCleared() } } private fun fireRemoveEvent(element: V) { fireEvent { elementRemoved(element) } } override fun add(element: V): Boolean { return delegate.add(element).also { if (it) fireAddEvent(element) } } override fun addAll(elements: Collection<V>): Boolean { var result = false for (elem in elements) { result = result or add(elem) } return result } override fun clear() { delegate.clear() fireClearEvent() } override fun contains(element: V): Boolean = delegate.contains(element) override fun containsAll(elements: Collection<V>): Boolean = delegate.containsAll(elements) override fun equals(other: Any?): Boolean { return delegate == other } override fun hashCode(): Int { return delegate.hashCode() } override fun isEmpty(): Boolean { return delegate.isEmpty() } override fun iterator(): MutableIterator<V> { return monitoringIterator(listeners, delegate.iterator()) } override fun remove(element: V): Boolean { return delegate.remove(element).also { if (it) fireRemoveEvent(element) } } override fun removeAll(elements: Collection<V>): Boolean { return elements.fold(false) { changed, element -> changed or remove(element) } } override fun retainAll(elements: Collection<V>): Boolean { return delegate.removeAll { it in elements } } override val size: Int get() = delegate.size }
lgpl-3.0
8a08e2c17540320335239bda7bb0a387
29.033898
121
0.656788
4.71771
false
false
false
false
pdvrieze/ProcessManager
TestSupport/src/main/kotlin/nl/adaptivity/process/MemTransactionedHandleMap.kt
1
4175
/* * Copyright (c) 2016. * * This file is part of ProcessManager. * * ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 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 nl.adaptivity.process import net.devrieze.util.* import java.sql.SQLException /** * Created by pdvrieze on 09/12/15. */ open class MemTransactionedHandleMap<T : Any, TR : StubTransaction>(private val assigner: Assigner<T, TR>) : MemHandleMap<T>(handleAssigner = { t: T, h: Handle<T> -> assigner(t, h) }), MutableTransactionedHandleMap<T, TR> { @JvmOverloads constructor( handleAssigner: (TR, T, Handle<T>) -> T? = { transaction, value, handle -> HANDLE_AWARE_ASSIGNER(transaction, value, handle) } ) : this(Assigner(handleAssigner)) class Assigner<T, TR : StubTransaction>(private val base: (TR, T, Handle<T>) -> T?) { lateinit var transaction: TR operator fun invoke(t: T, h: Handle<T>): T? { return base(transaction, t, h) } } interface TestTransactionFactory<TR : StubTransaction> { fun newTransaction(): TR } private class IteratorWrapper<T>(private val delegate: Iterator<T>, private val readOnly: Boolean) : MutableAutoCloseableIterator<T> { override fun remove() { if (readOnly) throw UnsupportedOperationException("The iterator is read-only") } override fun next(): T { return delegate.next() } override fun hasNext(): Boolean { return delegate.hasNext() } override fun close() { // Do nothing } } @Throws(SQLException::class) override fun <W : T> put(transaction: TR, value: W): Handle<W> { assigner.transaction = transaction return put(value) } @Throws(SQLException::class) override fun get(transaction: TR, handle: Handle<T>): T? { return get(handle) } @Throws(SQLException::class) override fun castOrGet(transaction: TR, handle: Handle<T>): T? { return get(handle) } @Throws(SQLException::class) override fun set(transaction: TR, handle: Handle<T>, value: T): T? { assigner.transaction = transaction return set(handle, value) } override fun iterable(transaction: TR): MutableIterable<T> { assigner.transaction = transaction return this } override fun iterator(transaction: TR, readOnly: Boolean): MutableIterator<T> { assigner.transaction = transaction return IteratorWrapper(iterator(), readOnly) } @Throws(SQLException::class) override fun containsAll(transaction: TR, c: Collection<*>) = c.all { it != null && contains(it) } @Throws(SQLException::class) override fun containsElement(transaction: TR, element: Any): Boolean { return contains(element) } @Throws(SQLException::class) override fun contains(transaction: TR, handle: Handle<T>): Boolean { return contains(handle) } @Throws(SQLException::class) override fun remove(transaction: TR, handle: Handle<T>): Boolean { assigner.transaction = transaction return remove(handle) } override fun invalidateCache(handle: Handle<T>) { /* No-op */ } override fun invalidateCache() { /* No-op */ } @Throws(SQLException::class) override fun clear(transaction: TR) { assigner.transaction = transaction clear() } override fun withTransaction(transaction: TR): MutableHandleMap<T> { assigner.transaction = transaction return MutableHandleMapForwarder(transaction, this) } }
lgpl-3.0
a702fc89ba01b947280e5a19d96a9474
29.698529
118
0.649341
4.286448
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/test/java/org/wordpress/android/fluxc/wc/product/WCProductStoreTest.kt
1
26229
package org.wordpress.android.fluxc.wc.product import com.google.gson.JsonObject import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import com.yarolegovich.wellsql.WellSql import kotlinx.coroutines.flow.first import kotlinx.coroutines.runBlocking import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.SingleStoreWellSqlConfigForTests import org.wordpress.android.fluxc.generated.WCProductActionBuilder import org.wordpress.android.fluxc.model.AccountModel import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.WCProductCategoryModel import org.wordpress.android.fluxc.model.WCProductModel import org.wordpress.android.fluxc.model.WCProductReviewModel import org.wordpress.android.fluxc.model.WCProductVariationModel import org.wordpress.android.fluxc.network.BaseRequest.GenericErrorType.NETWORK_ERROR import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooError import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooErrorType.GENERIC_ERROR import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.BatchProductVariationsUpdateApiResponse import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.CoreProductStockStatus import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.ProductRestClient import org.wordpress.android.fluxc.network.rest.wpcom.wc.product.ProductVariationApiResponse import org.wordpress.android.fluxc.persistence.ProductSqlUtils import org.wordpress.android.fluxc.persistence.WellSqlConfig import org.wordpress.android.fluxc.store.WCProductStore import org.wordpress.android.fluxc.store.WCProductStore.BatchUpdateVariationsPayload import org.wordpress.android.fluxc.store.WCProductStore.FetchSingleProductReviewPayload import org.wordpress.android.fluxc.store.WCProductStore.ProductFilterOption import org.wordpress.android.fluxc.store.WCProductStore.RemoteAddProductPayload import org.wordpress.android.fluxc.store.WCProductStore.RemoteProductReviewPayload import org.wordpress.android.fluxc.store.WCProductStore.RemoteUpdateProductPayload import org.wordpress.android.fluxc.store.WCProductStore.RemoteUpdateVariationPayload import org.wordpress.android.fluxc.store.WCProductStore.UpdateVariationPayload import org.wordpress.android.fluxc.test import org.wordpress.android.fluxc.tools.initCoroutineEngine import org.wordpress.android.fluxc.wc.utils.SiteTestUtils import kotlin.random.Random import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertTrue @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner::class) class WCProductStoreTest { private val productRestClient: ProductRestClient = mock() private val productStore = WCProductStore( Dispatcher(), productRestClient, addonsDao = mock(), logger = mock(), coroutineEngine = initCoroutineEngine() ) @Before fun setUp() { val appContext = RuntimeEnvironment.application.applicationContext val config = SingleStoreWellSqlConfigForTests( appContext, listOf( WCProductModel::class.java, WCProductVariationModel::class.java, WCProductCategoryModel::class.java, WCProductReviewModel::class.java, SiteModel::class.java, AccountModel::class.java ), WellSqlConfig.ADDON_WOOCOMMERCE ) WellSql.init(config) config.reset() } @Test fun testSimpleInsertionAndRetrieval() { val productModel = ProductTestUtils.generateSampleProduct(42) val site = SiteModel().apply { id = productModel.localSiteId } ProductSqlUtils.insertOrUpdateProduct(productModel) val storedProduct = productStore.getProductByRemoteId(site, productModel.remoteProductId) assertEquals(42, storedProduct?.remoteProductId) assertEquals(productModel, storedProduct) } @Test fun testGetProductsBySiteAndProductIds() { val productIds = listOf<Long>(30, 31, 2) val product1 = ProductTestUtils.generateSampleProduct(30) val product2 = ProductTestUtils.generateSampleProduct(31) val product3 = ProductTestUtils.generateSampleProduct(42) ProductSqlUtils.insertOrUpdateProduct(product1) ProductSqlUtils.insertOrUpdateProduct(product2) ProductSqlUtils.insertOrUpdateProduct(product3) val site = SiteModel().apply { id = product1.localSiteId } val products = productStore.getProductsByRemoteIds(site, productIds) assertEquals(2, products.size) // insert products with the same productId but for a different site val differentSiteProduct1 = ProductTestUtils.generateSampleProduct(10, siteId = 10) val differentSiteProduct2 = ProductTestUtils.generateSampleProduct(11, siteId = 10) val differentSiteProduct3 = ProductTestUtils.generateSampleProduct(2, siteId = 10) ProductSqlUtils.insertOrUpdateProduct(differentSiteProduct1) ProductSqlUtils.insertOrUpdateProduct(differentSiteProduct2) ProductSqlUtils.insertOrUpdateProduct(differentSiteProduct3) // verify that the products for the first site is still 2 assertEquals(2, productStore.getProductsByRemoteIds(site, productIds).size) // verify that the products for the second site is 3 val site2 = SiteModel().apply { id = differentSiteProduct1.localSiteId } val differentSiteProducts = productStore.getProductsByRemoteIds(site2, listOf(10, 11, 2)) assertEquals(3, differentSiteProducts.size) assertEquals(differentSiteProduct1.remoteProductId, differentSiteProducts[0].remoteProductId) assertEquals(differentSiteProduct2.remoteProductId, differentSiteProducts[1].remoteProductId) assertEquals(differentSiteProduct3.remoteProductId, differentSiteProducts[2].remoteProductId) } @Test fun testUpdateProduct() { val productModel = ProductTestUtils.generateSampleProduct(42).apply { name = "test product" description = "test description" } val site = SiteModel().apply { id = productModel.localSiteId } ProductSqlUtils.insertOrUpdateProduct(productModel) // Simulate incoming action with updated product model val payload = RemoteUpdateProductPayload(site, productModel.apply { description = "Updated description" }) productStore.onAction(WCProductActionBuilder.newUpdatedProductAction(payload)) with(productStore.getProductByRemoteId(site, productModel.remoteProductId)) { // The version of the product model in the database should have the updated description assertEquals(productModel.description, this?.description) // Other fields should not be altered by the update assertEquals(productModel.name, this?.name) } } @Test fun testUpdateVariation() = runBlocking { val variationModel = ProductTestUtils.generateSampleVariation(42, 24).apply { description = "test description" } val site = SiteModel().apply { id = variationModel.localSiteId } whenever(productRestClient.updateVariation(site, null, variationModel)) .thenReturn(RemoteUpdateVariationPayload(site, variationModel)) productStore.updateVariation(UpdateVariationPayload(site, variationModel)) with(productStore.getVariationByRemoteId( site, variationModel.remoteProductId, variationModel.remoteVariationId )) { // The version of the product model in the database should have the updated description assertEquals(variationModel.description, this?.description) // Other fields should not be altered by the update assertEquals(variationModel.status, this?.status) } } @Test fun testVerifySkuExistsLocally() { val sku = "woo-cap" val productModel = ProductTestUtils.generateSampleProduct(42).apply { name = "test product" description = "test description" this.sku = sku } val site = SiteModel().apply { id = productModel.localSiteId } ProductSqlUtils.insertOrUpdateProduct(productModel) // verify if product with sku: woo-cap exists in local cache val skuAvailable = ProductSqlUtils.getProductExistsBySku(site, sku) assertTrue(skuAvailable) // verify if product with non existent sku returns false assertFalse(ProductSqlUtils.getProductExistsBySku(site, "woooo")) } @Test fun testGetProductsByFilterOptions() { val filterOptions = mapOf<ProductFilterOption, String>( ProductFilterOption.TYPE to "simple", ProductFilterOption.STOCK_STATUS to "instock", ProductFilterOption.STATUS to "publish", ProductFilterOption.CATEGORY to "1337" ) val product1 = ProductTestUtils.generateSampleProduct(3) val product2 = ProductTestUtils.generateSampleProduct( 31, type = "variable", status = "draft" ) val product3 = ProductTestUtils.generateSampleProduct( 42, stockStatus = "onbackorder", status = "pending" ) val product4 = ProductTestUtils.generateSampleProduct( 43, categories = "[{\"id\":1337,\"name\":\"Clothing\",\"slug\":\"clothing\"}]") ProductSqlUtils.insertOrUpdateProduct(product1) ProductSqlUtils.insertOrUpdateProduct(product2) ProductSqlUtils.insertOrUpdateProduct(product3) ProductSqlUtils.insertOrUpdateProduct(product4) val site = SiteModel().apply { id = product1.localSiteId } val products = productStore.getProductsByFilterOptions(site, filterOptions) assertEquals(1, products.size) // insert products with the same product options but for a different site val differentSiteProduct1 = ProductTestUtils.generateSampleProduct(10, siteId = 10) val differentSiteProduct2 = ProductTestUtils.generateSampleProduct( 11, siteId = 10, type = "variable", status = "draft" ) val differentSiteProduct3 = ProductTestUtils.generateSampleProduct( 12, siteId = 10, stockStatus = "onbackorder", status = "pending" ) val differentSiteProduct4 = ProductTestUtils.generateSampleProduct( 13, siteId = 10, categories = "[{\"id\":1337,\"name\":\"Clothing\",\"slug\":\"clothing\"}]") ProductSqlUtils.insertOrUpdateProduct(differentSiteProduct1) ProductSqlUtils.insertOrUpdateProduct(differentSiteProduct2) ProductSqlUtils.insertOrUpdateProduct(differentSiteProduct3) ProductSqlUtils.insertOrUpdateProduct(differentSiteProduct4) // verify that the products for the first site is still 1 assertEquals(1, productStore.getProductsByFilterOptions(site, filterOptions).size) // verify that the products for the second site is 3 val site2 = SiteModel().apply { id = differentSiteProduct1.localSiteId } val filterOptions2 = mapOf(ProductFilterOption.STATUS to "draft") val differentSiteProducts = productStore.getProductsByFilterOptions(site2, filterOptions2) assertEquals(1, differentSiteProducts.size) assertEquals(differentSiteProduct2.status, differentSiteProducts[0].status) val filterOptions3 = mapOf(ProductFilterOption.STOCK_STATUS to "onbackorder") val differentProductFilters = productStore.getProductsByFilterOptions(site2, filterOptions3) assertEquals(1, differentProductFilters.size) assertEquals(differentSiteProduct3.stockStatus, differentProductFilters[0].stockStatus) val filterByCategory = mapOf(ProductFilterOption.CATEGORY to "1337") val productsFilteredByCategory = productStore.getProductsByFilterOptions(site2, filterByCategory) assertEquals(1, productsFilteredByCategory.size) assertTrue(productsFilteredByCategory[0].categories.contains("1337")) } @Test fun `test AddProduct Action triggered correctly`() { // given val productModel = ProductTestUtils.generateSampleProduct(remoteId = 0).apply { name = "test new product" description = "test new description" } val site = SiteModel().apply { id = productModel.localSiteId } // when ProductSqlUtils.insertOrUpdateProduct(productModel) val payload = RemoteAddProductPayload(site, productModel) productStore.onAction(WCProductActionBuilder.newAddedProductAction(payload)) // then with(productStore.getProductByRemoteId(site, productModel.remoteProductId)) { assertNotNull(this) assertEquals(productModel.description, this.description) assertEquals(productModel.name, this.name) } } @Test fun `test that product insert emits a flow event`() = test { // given val productModel = ProductTestUtils.generateSampleProduct(remoteId = 0).apply { name = "test new product" description = "test new description" } val productList = ProductTestUtils.generateProductList() ProductSqlUtils.insertOrUpdateProducts(productList) val site = SiteModel().apply { id = productModel.localSiteId } var observedProducts = productStore.observeProducts(site).first() assertThat(observedProducts).isEqualTo(productList) // when ProductSqlUtils.insertOrUpdateProduct(productModel) observedProducts = productStore.observeProducts(site).first() // then assertThat(observedProducts).isEqualTo(productList + productModel) } @Test fun `test that variation insert emits a flow event`() = test { // given val variation = ProductTestUtils.generateSampleVariation( remoteId = 0, variationId = 1 ).apply { description = "test new description" } val site = SiteModel().apply { id = variation.localSiteId } val variations = ProductTestUtils.generateSampleVariations( number = 5, productId = variation.remoteProductId, siteId = site.id ) ProductSqlUtils.insertOrUpdateProductVariations(variations) var observedVariations = productStore.observeVariations(site, variation.remoteProductId) .first() assertThat(observedVariations).isEqualTo(variations) // when ProductSqlUtils.insertOrUpdateProductVariation(variation) observedVariations = productStore.observeVariations(site, variation.remoteProductId).first() // then assertThat(observedVariations).isEqualTo(variations + variation) } @Test fun `given product review exists, when fetch product review, then local database updated`() = runBlocking { val site = SiteTestUtils.insertTestAccountAndSiteIntoDb() val productModel = ProductTestUtils.generateSampleProduct(remoteId = 1).apply { localSiteId = site.id } ProductSqlUtils.insertOrUpdateProduct(productModel) val reviewModel = ProductTestUtils.generateSampleProductReview( productModel.remoteProductId, 123L, site.id ) whenever(productRestClient.fetchProductReviewById(site, reviewModel.remoteProductReviewId)) .thenReturn(RemoteProductReviewPayload(site, reviewModel)) productStore.fetchSingleProductReview(FetchSingleProductReviewPayload(site, reviewModel.remoteProductReviewId)) assertThat(productStore.getProductReviewByRemoteId(site.id, reviewModel.remoteProductReviewId)).isNotNull Unit } @Test fun `batch variations update should return positive result on successful backend request`() = runBlocking { // given val product = ProductTestUtils.generateSampleProduct(Random.nextLong()) val site = SiteModel().apply { id = product.localSiteId } val variations = ProductTestUtils.generateSampleVariations( number = 64, productId = product.remoteProductId, siteId = site.id ) // when val variationsIds = variations.map { it.remoteVariationId } val variationsUpdatePayload = BatchUpdateVariationsPayload.Builder( site, product.remoteProductId, variationsIds ).build() val response = BatchProductVariationsUpdateApiResponse().apply { updatedVariations = emptyList() } whenever( productRestClient.batchUpdateVariations( any(), any(), any(), any() ) ) doReturn WooPayload(response) val result = productStore.batchUpdateVariations(variationsUpdatePayload) // then assertThat(result.isError).isFalse assertThat(result.model).isNotNull Unit } @Test fun `batch variations update should return negative result on failed backend request`() = runBlocking { // given val product = ProductTestUtils.generateSampleProduct(Random.nextLong()) val site = SiteModel().apply { id = product.localSiteId } val variations = ProductTestUtils.generateSampleVariations( number = 64, productId = product.remoteProductId, siteId = site.id ) // when val variationsIds = variations.map { it.remoteVariationId } val variationsUpdatePayload = BatchUpdateVariationsPayload.Builder(site, product.remoteProductId, variationsIds) .build() val errorResponse = WooError(GENERIC_ERROR, NETWORK_ERROR, "🔴") whenever( productRestClient.batchUpdateVariations( any(), any(), any(), any() ) ) doReturn WooPayload(errorResponse) val result = productStore.batchUpdateVariations(variationsUpdatePayload) // then assertThat(result.isError).isTrue Unit } @Test fun `batch variations update should update variations locally after successful backend request`() = runBlocking { // given val product = ProductTestUtils.generateSampleProduct(Random.nextLong()) ProductSqlUtils.insertOrUpdateProduct(product) val site = SiteTestUtils.insertTestAccountAndSiteIntoDb() val variations = ProductTestUtils.generateSampleVariations( number = 64, productId = product.remoteProductId, siteId = site.id ) ProductSqlUtils.insertOrUpdateProductVariations(variations) // when val variationsIds = variations.map { it.remoteVariationId } val newRegularPrice = "1.234 💰" val newSalePrice = "0.234 💰" val variationsUpdatePayload = BatchUpdateVariationsPayload.Builder(site, product.remoteProductId, variationsIds) .regularPrice(newRegularPrice) .salePrice(newSalePrice) .build() val variationsReturnedFromBackend = variations.map { ProductVariationApiResponse().apply { id = it.remoteVariationId regular_price = newRegularPrice sale_price = newSalePrice } } val response = BatchProductVariationsUpdateApiResponse().apply { updatedVariations = variationsReturnedFromBackend } whenever( productRestClient.batchUpdateVariations( any(), any(), any(), any() ) ) doReturn WooPayload(response) val result = productStore.batchUpdateVariations(variationsUpdatePayload) // then assertThat(result.isError).isFalse assertThat(result.model).isNotNull with(ProductSqlUtils.getVariationsForProduct(site, product.remoteProductId)) { forEach { variation -> assertThat(variation.regularPrice).isEqualTo(newRegularPrice) assertThat(variation.salePrice).isEqualTo(newSalePrice) } } Unit } @Test fun `batch variations update should not update variations locally after failed backend request`() = runBlocking { // given val product = ProductTestUtils.generateSampleProduct(Random.nextLong()) ProductSqlUtils.insertOrUpdateProduct(product) val site = SiteTestUtils.insertTestAccountAndSiteIntoDb() val variations = ProductTestUtils.generateSampleVariations( number = 64, productId = product.remoteProductId, siteId = site.id ) ProductSqlUtils.insertOrUpdateProductVariations(variations) // when val variationsIds = variations.map { it.remoteVariationId } val newRegularPrice = "1.234 💰" val newSalePrice = "0.234 💰" val variationsUpdatePayload = BatchUpdateVariationsPayload.Builder(site, product.remoteProductId, variationsIds) .regularPrice(newRegularPrice) .salePrice(newSalePrice) .build() val errorResponse = WooError(GENERIC_ERROR, NETWORK_ERROR, "🔴") whenever( productRestClient.batchUpdateVariations( any(), any(), any(), any() ) ) doReturn WooPayload(errorResponse) val result = productStore.batchUpdateVariations(variationsUpdatePayload) // then assertThat(result.isError).isTrue with(ProductSqlUtils.getVariationsForProduct(site, product.remoteProductId)) { forEach { variation -> assertThat(variation.regularPrice).isNotEqualTo(newRegularPrice) assertThat(variation.salePrice).isNotEqualTo(newSalePrice) } } Unit } @Test fun `BatchUpdateVariationsPayload_Builder should produce correct variations modifications map`() { // given val product = ProductTestUtils.generateSampleProduct(Random.nextLong()) val site = SiteModel().apply { id = 23 } val variations = ProductTestUtils.generateSampleVariations( number = 64, productId = product.remoteProductId, siteId = site.id ) val builder = BatchUpdateVariationsPayload.Builder( site, product.remoteProductId, variations.map { it.remoteVariationId } ) val modifiedRegularPrice = "11234.234" val modifiedSalePrice = "123,2.4" val modifiedStartOfSale = "tomorrow" val modifiedEndOfSale = "next week" val modifiedStockQuantity = 1234 val modifiedStockStatus = CoreProductStockStatus.IN_STOCK val modifiedWeight = "1234 kg" val modifiedWidth = "5" val modifiedHeight = "10" val modifiedLength = "15" val modifiedShippingClassId = "1234" val modifiedShippingClassSlug = "DHL" // when builder.regularPrice(modifiedRegularPrice) .salePrice(modifiedSalePrice) .startOfSale(modifiedStartOfSale) .endOfSale(modifiedEndOfSale) .stockQuantity(modifiedStockQuantity) .stockStatus(modifiedStockStatus) .weight(modifiedWeight) .dimensions(length = modifiedLength, width = modifiedWidth, height = modifiedHeight) .shippingClassId(modifiedShippingClassId) .shippingClassSlug(modifiedShippingClassSlug) val payload = builder.build() // then with(payload.modifiedProperties) { assertThat(get("regular_price")).isEqualTo(modifiedRegularPrice) assertThat(get("sale_price")).isEqualTo(modifiedSalePrice) assertThat(get("date_on_sale_from")).isEqualTo(modifiedStartOfSale) assertThat(get("date_on_sale_to")).isEqualTo(modifiedEndOfSale) assertThat(get("stock_quantity")).isEqualTo(modifiedStockQuantity) assertThat(get("stock_status")).isEqualTo(modifiedStockStatus) assertThat(get("weight")).isEqualTo(modifiedWeight) with(get("dimensions") as JsonObject) { assertThat(get("length").asString).isEqualTo(modifiedLength) assertThat(get("height").asString).isEqualTo(modifiedHeight) assertThat(get("width").asString).isEqualTo(modifiedWidth) } assertThat(get("shipping_class_id")).isEqualTo(modifiedShippingClassId) assertThat(get("shipping_class")).isEqualTo(modifiedShippingClassSlug) } } }
gpl-2.0
995d75f2e858cd3021e619fe11ef3bdd
43.350254
119
0.667659
5.462901
false
true
false
false
Team-Antimatter-Mod/AntiMatterMod
src/main/java/antimattermod/core/Fluid/tank/RenderTileTank.kt
1
4062
package antimattermod.core.Fluid.tank import net.minecraft.client.renderer.Tessellator import net.minecraft.client.renderer.texture.TextureMap import net.minecraft.client.renderer.tileentity.TileEntitySpecialRenderer import net.minecraft.tileentity.TileEntity import net.minecraft.util.IIcon import org.lwjgl.opengl.GL11 import org.lwjgl.opengl.GL12 /** * @author kojin15. */ class RenderTileTank : TileEntitySpecialRenderer() { override fun renderTileEntityAt(tile: TileEntity?, x: Double, y: Double, z: Double, ff: Float) { renderFluid(tile as TileBasicTank, x, y, z) } fun renderFluid(tile: TileBasicTank, x: Double, y: Double, z: Double) { val tessellator: Tessellator = Tessellator.instance val fluidIcon: IIcon? = tile.getFluidIcon() val tankMinX = x + 0.126 val tankMaxX = x + 0.874 val tankMinZ = z + 0.126 val tankMaxZ = z + 0.874 if (fluidIcon != null) { GL11.glPushMatrix() GL11.glEnable(GL12.GL_RESCALE_NORMAL) GL11.glEnable(GL11.GL_BLEND) GL11.glBlendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA) GL11.glColor4f(2.0f, 2.0f, 2.0f, 0.75f) val minU: Double = fluidIcon.minU.toDouble() val maxU: Double = fluidIcon.maxU.toDouble() val minV: Double = fluidIcon.minV.toDouble() val maxV: Double = fluidIcon.maxV.toDouble() val c = 0.98 / tile.maxCapacity val high = (c * (tile.productTank.fluidAmount)) + 0.01 val iconU = maxU - minU val iconC = iconU / tile.maxCapacity val iconHighU = (iconC * (tile.productTank.fluidAmount)) + minU val tankMaxV = (((maxV - minV) / 10) * 8 ) + minV bindTexture(TextureMap.locationBlocksTexture) tessellator.startDrawingQuads() tessellator.addVertexWithUV(tankMinX, y + high, tankMinZ, minU, minV) tessellator.addVertexWithUV(tankMinX, y + high, tankMaxZ, minU, maxV) tessellator.addVertexWithUV(tankMaxX, y + high, tankMaxZ, maxU, maxV) tessellator.addVertexWithUV(tankMaxX, y + high, tankMinZ, maxU, minV) tessellator.draw() tessellator.startDrawingQuads() tessellator.addVertexWithUV(tankMinX, y + 0.01, tankMinZ, minU, minV) tessellator.addVertexWithUV(tankMinX, y + 0.01, tankMaxZ, minU, tankMaxV) tessellator.addVertexWithUV(tankMinX, y + high, tankMaxZ, iconHighU, tankMaxV) tessellator.addVertexWithUV(tankMinX, y + high, tankMinZ, iconHighU, minV) tessellator.draw() tessellator.startDrawingQuads() tessellator.addVertexWithUV(tankMaxX, y + high, tankMinZ, iconHighU, minV) tessellator.addVertexWithUV(tankMaxX, y + high, tankMaxZ, iconHighU, tankMaxV) tessellator.addVertexWithUV(tankMaxX, y + 0.01, tankMaxZ, minU, tankMaxV) tessellator.addVertexWithUV(tankMaxX, y + 0.01, tankMinZ, minU, minV) tessellator.draw() tessellator.startDrawingQuads() tessellator.addVertexWithUV(tankMinX, y + high, tankMinZ, iconHighU, minV) tessellator.addVertexWithUV(tankMaxX, y + high, tankMinZ, iconHighU, tankMaxV) tessellator.addVertexWithUV(tankMaxX, y + 0.01, tankMinZ, minU, tankMaxV) tessellator.addVertexWithUV(tankMinX, y + 0.01, tankMinZ, minU, minV) tessellator.draw() tessellator.startDrawingQuads() tessellator.addVertexWithUV(tankMinX, y + 0.01, tankMaxZ, minU, minV) tessellator.addVertexWithUV(tankMaxX, y + 0.01, tankMaxZ, minU, tankMaxV) tessellator.addVertexWithUV(tankMaxX, y + high, tankMaxZ, iconHighU, tankMaxV) tessellator.addVertexWithUV(tankMinX, y + high, tankMaxZ, iconHighU, minV) tessellator.draw() GL11.glDisable(GL12.GL_RESCALE_NORMAL) GL11.glDisable(GL11.GL_BLEND) GL11.glPopMatrix() } } }
gpl-3.0
b2b66862ea40a802d64dc13170edda13
42.223404
100
0.646233
3.792717
false
false
false
false
V2Ray-Android/Actinium
app/src/main/kotlin/com/v2ray/actinium/extension/NetworkFormatter.kt
1
904
package com.v2ray.actinium.extension const val threshold = 1000 const val divisor = 1024F fun Long.toSpeedString() = toTrafficString() + "/s" fun Long.toTrafficString(): String { if (this < threshold) return "$this Bytes" val kib = this / divisor if (kib < threshold) return "${kib.toShortString()} KiB" val mib = kib / divisor if (mib < threshold) return "${mib.toShortString()} MiB" val gib = mib / divisor if (gib < threshold) return "${gib.toShortString()} GiB" val tib = gib / divisor if (tib < threshold) return "${tib.toShortString()} TiB" val pib = tib / divisor if (pib < threshold) return "${pib.toShortString()} PiB" return "∞" } private fun Float.toShortString(): String { val s = toString() if (s.length <= 4) return s return s.substring(0, 4).removeSuffix(".") }
gpl-3.0
ed309b0eb4184cc2f2a2b0c88e10796e
21.575
51
0.600887
3.608
false
false
false
false
hartwigmedical/hmftools
teal/src/main/kotlin/com/hartwig/hmftools/teal/breakend/BreakEndSupportCounter.kt
1
13611
package com.hartwig.hmftools.teal.breakend import com.hartwig.hmftools.common.genome.chromosome.HumanChromosome import com.hartwig.hmftools.common.genome.refgenome.RefGenomeCoordinates import com.hartwig.hmftools.common.genome.refgenome.RefGenomeVersion import com.hartwig.hmftools.common.samtools.CigarUtils import com.hartwig.hmftools.common.samtools.CigarUtils.* import com.hartwig.hmftools.teal.ReadGroup import com.hartwig.hmftools.teal.TealUtils import com.hartwig.hmftools.teal.util.TelomereMatcher import htsjdk.samtools.SAMRecord import org.apache.logging.log4j.LogManager import kotlin.math.* private const val MAX_DISTANCE_FROM_BREAKEND = 500 // split positions within 5 bases are count as the same private const val SPLIT_POSITION_TOLERANCE = 5 // find all the disordant pairs given // a list of candidate telomeric break ends // class BreakEndSupportCounter(refGenomeVersion: RefGenomeVersion, telomereMatchThreshold: Double) { private val mLogger = LogManager.getLogger(javaClass) private val mTelomereMatchThreshold = telomereMatchThreshold private val mMinTelomereMatchLength = 12 private val mRefGenomeCoordinates = when (refGenomeVersion) { RefGenomeVersion.V37 -> RefGenomeCoordinates.COORDS_37 RefGenomeVersion.V38 -> RefGenomeCoordinates.COORDS_38 } private fun matchesTelomere(seq: String, gRich: Boolean): Boolean { return TelomereMatcher.matchesTelomere(seq, mTelomereMatchThreshold, mMinTelomereMatchLength, gRich) } // after we found all the candidate break ends, we want to process // the reads again and see if any discordant pairs support the split fun countBreakEndSupports(breakEnds: List<TelomericBreakEnd>, readGroups: Collection<ReadGroup>) : List<TelomericBreakEndSupport> { val breakEndSupports = breakEnds.map({ o -> TelomericBreakEndSupport(o) }) for (rg in readGroups) { for (breakEnd: TelomericBreakEndSupport in breakEndSupports) { breakEndFragment(rg, breakEnd.key)?.apply({breakEnd.fragments.add(this)}) } } // now we work out fragment length for (breakEnd: TelomericBreakEndSupport in breakEndSupports) { populateLongestTelomereSegment(breakEnd) populateLongestSplitReadAlign(breakEnd) populateDistanceFromTelomere(breakEnd) } return breakEndSupports } fun breakEndFragment(rg: ReadGroup, breakEnd: TelomericBreakEnd) : Fragment? { val alignedRead = findAlignedRead(rg, breakEnd) // we exclude duplicate reads if (alignedRead == null || alignedRead.duplicateReadFlag) { return null } val pairedRead = if (alignedRead.firstOfPairFlag) rg.secondOfPair else rg.firstOfPair if (pairedRead == null) { // shouldn't be here really, so we just do not classify this fragment return null } val alignedReadType = classifyAlignedRead(breakEnd, alignedRead) val pairedReadType = classifyPairedRead(breakEnd, pairedRead = pairedRead, alignedRead = alignedRead) if (alignedReadType != null) { mLogger.debug("breakend(${breakEnd}) readId(${rg.name}) aligned read type($alignedReadType) paired read type($pairedReadType)") // add it to the break end return Fragment(rg, alignedReadType = alignedReadType, pairedReadType = pairedReadType, alignedRead = alignedRead, pairedRead = pairedRead) } return null } // find the read that is aligned to the break point fun findAlignedRead(rg: ReadGroup, breakEnd: TelomericBreakEnd) : SAMRecord? { var alignedRead: SAMRecord? = null // first we find out which one is aligned close to the break point and which one // is the other read for (r in rg.allReads) { if (r.readUnmappedFlag) { continue } if (breakEnd.isRightTelomeric()) { if (r.alignmentEnd <= breakEnd.position && r.alignmentEnd > breakEnd.position - MAX_DISTANCE_FROM_BREAKEND && r.referenceName == breakEnd.chromosome) { // this is aligned read, but also compared to what we already found // chose the one that is further to the right if (alignedRead == null || r.alignmentEnd > alignedRead.alignmentEnd) { alignedRead = r } } } else { // to support a new left telomere, we want to find a reverse reads to // be on the higher side of the break position, and the other // read to be fully telomeric if (r.alignmentStart >= breakEnd.position && r.alignmentStart < breakEnd.position + MAX_DISTANCE_FROM_BREAKEND && r.referenceName == breakEnd.chromosome) { // this is aligned read, but also compared to what we already found // chose the one that is further to the left if (alignedRead == null || r.alignmentStart < alignedRead.alignmentStart) { alignedRead = r } } } } // if the aligned read that we found is not facing the breakend and // does not cross it, then it is not interesting if (alignedRead != null) { if (breakEnd.isRightTelomeric() && alignedRead.readNegativeStrandFlag && alignedRead.alignmentEnd < breakEnd.position) { // for right telomere // reverse read faces away from breakend return null } if (!breakEnd.isRightTelomeric() && !alignedRead.readNegativeStrandFlag && alignedRead.alignmentStart > breakEnd.position) { // for left telomere // forward read faces away from breakend return null } } return alignedRead } fun classifyAlignedRead(breakEnd: TelomericBreakEnd, alignedRead: SAMRecord) : Fragment.AlignedReadType? { // check if aligned read is a split read var clipBases: String? = null if (breakEnd.isRightTelomeric() && abs(alignedRead.alignmentEnd - breakEnd.position) <= SPLIT_POSITION_TOLERANCE) { clipBases = CigarUtils.rightSoftClipBases(alignedRead) } else if (!breakEnd.isRightTelomeric() && abs(alignedRead.alignmentStart - breakEnd.position) <= SPLIT_POSITION_TOLERANCE) { clipBases = CigarUtils.leftSoftClipBases(alignedRead) } if (clipBases != null) { // now depending on whether the clipped bases are telomeric or not we assign types return if (matchesTelomere(clipBases, breakEnd.isGTelomeric())) { Fragment.AlignedReadType.SPLIT_READ_TELOMERIC } else { Fragment.AlignedReadType.SPLIT_READ_NOT_TELOMERIC } } // if this read spans across the break end, then we designate it as non split if ((alignedRead.alignmentStart + SPLIT_POSITION_TOLERANCE) < breakEnd.position && (alignedRead.alignmentEnd - + SPLIT_POSITION_TOLERANCE) > breakEnd.position) { return Fragment.AlignedReadType.NOT_SPLIT_READ } // discordant pair. This usually means that the other if (breakEnd.isRightTelomeric() && alignedRead.alignmentEnd < breakEnd.position && !alignedRead.readNegativeStrandFlag || !breakEnd.isRightTelomeric() && alignedRead.alignmentStart > breakEnd.position && alignedRead.readNegativeStrandFlag) { return Fragment.AlignedReadType.DISCORDANT_PAIR } return null } // We want to check the read group against the break end see if this supports // any of the following scenarios: // for right C telomere fun classifyPairedRead(breakEnd: TelomericBreakEnd, pairedRead: SAMRecord, alignedRead: SAMRecord) : Fragment.PairedReadType { // if the aligned read is not facing breakend then the pair read is not // interesting if (breakEnd.isRightTelomeric() == alignedRead.readNegativeStrandFlag) { return Fragment.PairedReadType.NOT_DISCORDANT } // now we need to make sure the other read sequence is represented properly // the negative strand flag is set based on where the paired read is aligned to in the ref // genome. However that alignment is not interesting for this purpose. We want to make sure the // paired read is represented such that it is pointing in the other direction of the aligned read. val pairReadString = if (alignedRead.readNegativeStrandFlag == pairedRead.readNegativeStrandFlag) TealUtils.reverseComplementSequence(pairedRead.readString) else pairedRead.readString // now we have filter down to the case where the aligned read is // aligned close to the correct side of the break point // we want to decide whether the read that is supposedly on the // other side of the break point is telomeric or not return if (matchesTelomere(pairReadString, breakEnd.isGTelomeric())) { Fragment.PairedReadType.DISCORDANT_PAIR_TELOMERIC } else { Fragment.PairedReadType.DISCORDANT_PAIR_NOT_TELOMERIC } // now we want to work out if this fragment contradict or support this break point /* TeloConfig.TE_LOGGER.info( "record({}) -v strand({}) breakend({}) cigar({}) leftClip({}) rightClip({}) aligned({})", r, r.readNegativeStrandFlag, tbe, r.cigarString, leftClipBases, rightClipBases, alignedBases )*/ } private fun populateLongestTelomereSegment(breakEnd: TelomericBreakEndSupport) { // for all the reads, find the longest segment that matches our threshold val sequences = ArrayList<String>() for (frag in breakEnd.fragments) { // check the split reads val clipBases = if (breakEnd.type.isRightTelomeric()) { rightSoftClipBases(frag.alignedRead) } else { leftSoftClipBases(frag.alignedRead) } if (clipBases != null) { sequences.add(clipBases) } if (frag.pairedReadType != Fragment.PairedReadType.NOT_DISCORDANT) { sequences.add(frag.pairedRead.readString) } } val telomereSegments = ArrayList<String>() // now we got all the sequences, we find the longest telomere match for (s in sequences) { val telomereMatch : TelomereMatcher.TelomereMatch? = if (breakEnd.type.isGTelomeric()) { TelomereMatcher.findGTelomereSegment(s, mTelomereMatchThreshold) } else { TelomereMatcher.findCTelomereSegment(s, mTelomereMatchThreshold) } if (telomereMatch != null) { telomereSegments.add(telomereMatch.matchedSequence) } } // now find the longest one breakEnd.longestTelomereSegment = telomereSegments.maxByOrNull({ s -> s.length }) } private fun populateLongestSplitReadAlign(breakEnd: TelomericBreakEndSupport) { // for all the reads, find the longest segment that matches our threshold for (frag in breakEnd.fragments) { // check the split reads if (frag.alignedReadType == Fragment.AlignedReadType.SPLIT_READ_TELOMERIC || frag.alignedReadType == Fragment.AlignedReadType.SPLIT_READ_NOT_TELOMERIC) { val splitRead = frag.alignedRead val alignedLength = splitRead.readLength - leftSoftClipLength(splitRead) - rightSoftClipLength(splitRead) breakEnd.longestSplitReadAlignLength = max(breakEnd.longestSplitReadAlignLength, alignedLength) } } } // we find the distance of the breakpoint to break end private fun populateDistanceFromTelomere(breakEnd: TelomericBreakEndSupport) { // find which ref genome to use var chromosomeLength: Int? = null try { chromosomeLength = mRefGenomeCoordinates.lengths()[HumanChromosome.fromString(breakEnd.chromosome)] } catch (_: IllegalArgumentException) { } if (chromosomeLength == null) { mLogger.debug("cannot find chromosome length for chromosome: {}", breakEnd.chromosome) return } val distance = min(breakEnd.position, chromosomeLength - breakEnd.position) breakEnd.distanceToTelomere = distance } }
gpl-3.0
b8fdb9f3c2852310ec03b9e879ad825f
38.56686
163
0.611858
4.669297
false
false
false
false
SpineEventEngine/core-java
buildSrc/src/main/kotlin/io/spine/internal/dependency/Jackson.kt
2
2541
/* * Copyright 2022, TeamDev. All rights reserved. * * 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 * * Redistribution and use in source and/or binary forms, with or without * modification, must retain the above copyright notice and the following * disclaimer. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package io.spine.internal.dependency @Suppress("unused") object Jackson { const val version = "2.13.4" private const val databindVersion = "2.13.4.2" private const val coreGroup = "com.fasterxml.jackson.core" private const val dataformatGroup = "com.fasterxml.jackson.dataformat" private const val moduleGroup = "com.fasterxml.jackson.module" // https://github.com/FasterXML/jackson-core const val core = "$coreGroup:jackson-core:${version}" // https://github.com/FasterXML/jackson-databind const val databind = "$coreGroup:jackson-databind:${databindVersion}" // https://github.com/FasterXML/jackson-annotations const val annotations = "$coreGroup:jackson-annotations:${version}" // https://github.com/FasterXML/jackson-dataformat-xml/releases const val dataformatXml = "$dataformatGroup:jackson-dataformat-xml:${version}" // https://github.com/FasterXML/jackson-dataformats-text/releases const val dataformatYaml = "$dataformatGroup:jackson-dataformat-yaml:${version}" // https://github.com/FasterXML/jackson-module-kotlin/releases const val moduleKotlin = "$moduleGroup:jackson-module-kotlin:${version}" // https://github.com/FasterXML/jackson-bom const val bom = "com.fasterxml.jackson:jackson-bom:${version}" }
apache-2.0
735000749a14e894be4c5c931b7b4545
45.2
84
0.743802
4.158756
false
false
false
false
arturbosch/detekt
detekt-rules-coroutines/src/test/kotlin/io/gitlab/arturbosch/detekt/rules/coroutines/SuspendFunWithFlowReturnTypeSpec.kt
1
10522
package io.gitlab.arturbosch.detekt.rules.coroutines import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.rules.setupKotlinEnvironment import io.gitlab.arturbosch.detekt.test.compileAndLintWithContext import org.assertj.core.api.Assertions.assertThat import org.jetbrains.kotlin.cli.jvm.compiler.KotlinCoreEnvironment import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object SuspendFunWithFlowReturnTypeSpec : Spek({ setupKotlinEnvironment() val env: KotlinCoreEnvironment by memoized() val subject by memoized { SuspendFunWithFlowReturnType(Config.empty) } describe("SuspendFunWithFlowReturn") { it("reports when top-level suspend function has explicit Flow return type") { val code = """ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.yield suspend fun flowValues(): Flow<Long> { yield() return flowOf(1L, 2L, 3L) } suspend fun stateFlowValues(): StateFlow<Long> { yield() return MutableStateFlow(value = 1L) } suspend fun mutableStateFlowValues(): MutableStateFlow<Long> { yield() return MutableStateFlow(value = 1L) } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(3) } it("reports when top-level suspend function has explicit Flow return type and star import used") { val code = """ import kotlinx.coroutines.flow.* import kotlinx.coroutines.yield suspend fun flowValues(): Flow<Long> { yield() return flowOf(1L, 2L, 3L) } suspend fun stateFlowValues(): StateFlow<Long> { yield() return MutableStateFlow(value = 1L) } suspend fun mutableStateFlowValues(): MutableStateFlow<Long> { yield() return MutableStateFlow(value = 1L) } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(3) } it("reports when top-level suspend function has explicit FQN Flow return type") { val code = """ import kotlinx.coroutines.yield suspend fun flowValues(): kotlinx.coroutines.flow.Flow<Long> { yield() return kotlinx.coroutines.flow.flowOf(1L, 2L, 3L) } suspend fun stateFlowValues(): kotlinx.coroutines.flow.StateFlow<Long> { yield() return kotlinx.coroutines.flow.MutableStateFlow(value = 1L) } suspend fun mutableStateFlowValues(): kotlinx.coroutines.flow.MutableStateFlow<Long> { yield() return kotlinx.coroutines.flow.MutableStateFlow(value = 1L) } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(3) } it("reports when top-level suspend function has implicit Flow return type") { val code = """ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.MutableStateFlow suspend fun flowValues() = flowOf(1L, 2L, 3L) suspend fun mutableStateFlowValues() = MutableStateFlow(value = 1L) """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2) } it("reports when interface suspend function has explicit Flow return type") { val code = """ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow interface ValuesRepository { suspend fun flowValues(): Flow<Long> suspend fun stateFlowValues(): StateFlow<Long> suspend fun mutableStateFlowValues(): MutableStateFlow<Long> } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(3) } it("reports when class suspend function has explicit Flow return type") { val code = """ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.yield class ValuesRepository { suspend fun flowValues(): Flow<Long> { yield() return flowOf(1L, 2L, 3L) } suspend fun stateFlowValues(): StateFlow<Long> { yield() return MutableStateFlow(value = 1L) } suspend fun mutableStateFlowValues(): MutableStateFlow<Long> { yield() return MutableStateFlow(value = 1L) } } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(3) } it("reports when class suspend function has implicit Flow return type") { val code = """ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.MutableStateFlow class ValuesRepository { suspend fun flowValues() = flowOf(1L, 2L, 3L) suspend fun mutableStateFlowValues() = MutableStateFlow(value = 1L) } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2) } it("reports when suspend extension function has explicit Flow return type") { val code = """ import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.yield suspend fun Long.flowValues(): Flow<Long> { yield() return (0..this).asFlow() } suspend fun Long.stateFlowValues(): StateFlow<Long> { yield() return MutableStateFlow(value = this) } suspend fun Long.mutableStateFlowValues(): MutableStateFlow<Long> { yield() return MutableStateFlow(value = this) } """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(3) } it("reports when suspend extension function has implicit Flow return type") { val code = """ import kotlinx.coroutines.flow.asFlow import kotlinx.coroutines.flow.MutableStateFlow suspend fun Long.flowValues() = (0..this).asFlow() suspend fun Long.mutableStateFlowValues() = MutableStateFlow(value = this) """ assertThat(subject.compileAndLintWithContext(env, code)).hasSize(2) } it("does not report when suspend lambda has Flow return type") { val code = """ import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow fun doSomething1(block: suspend () -> Flow<Long>) { TODO() } fun doSomething2(block: suspend () -> StateFlow<Long>) { TODO() } fun doSomething3(block: suspend () -> MutableStateFlow<Long>) { TODO() } """ assertThat(subject.compileAndLintWithContext(env, code)).isEmpty() } it("does not report when suspend functions have non-Flow return types") { val code = """ import kotlinx.coroutines.delay suspend fun delayValue(value: Long): Long { delay(1_000L) return value } suspend fun delayValue2(value: Long) = value.apply { delay(1_000L) } suspend fun Long.delayValue(): Long { delay(1_000L) return this } suspend fun Long.delayValue2() = this.apply { delay(1_000L) } interface ValueRepository { suspend fun getValue(): Long } class ValueRepository2 { suspend fun getValue(): Long { delay(1_000L) return 5L } } class ValueRepository3 { suspend fun getValue() = 5L.apply { delay(1_000L) } } """ assertThat(subject.compileAndLintWithContext(env, code)).isEmpty() } it("does not report when non-suspend functions have Flow return types") { val code = """ import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow fun flowValues(): Flow<Long> { return flowOf(1L, 2L, 3L) } fun stateFlowValues(): StateFlow<Long> { return MutableStateFlow(value = 1L) } fun mutableStateFlowValues(): MutableStateFlow<Long> { return MutableStateFlow(value = 1L) } """ assertThat(subject.compileAndLintWithContext(env, code)).isEmpty() } } })
apache-2.0
87a34f599e4653e7533c2f79bd7460a4
37.683824
106
0.531743
5.784497
false
false
false
false
arturbosch/detekt
detekt-core/src/test/kotlin/io/gitlab/arturbosch/detekt/core/AnalyzerSpec.kt
1
4507
package io.gitlab.arturbosch.detekt.core import io.github.detekt.test.utils.compileForTest import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.RuleSet import io.gitlab.arturbosch.detekt.api.RuleSetProvider import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.test.yamlConfig import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.jetbrains.kotlin.psi.KtFile import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.concurrent.CompletionException class AnalyzerSpec : Spek({ describe("exceptions during analyze()") { it("throw error explicitly when config has wrong value type in config") { val testFile = path.resolve("Test.kt") val settings = createProcessingSettings(testFile, yamlConfig("configs/config-value-type-wrong.yml")) val analyzer = Analyzer(settings, listOf(StyleRuleSetProvider()), emptyList()) assertThatThrownBy { settings.use { analyzer.run(listOf(compileForTest(testFile))) } }.isInstanceOf(IllegalStateException::class.java) } it("throw error explicitly in parallel when config has wrong value in config") { val testFile = path.resolve("Test.kt") val settings = createProcessingSettings( inputPath = testFile, config = yamlConfig("configs/config-value-type-wrong.yml"), spec = createNullLoggingSpec { execution { parallelParsing = true parallelAnalysis = true } } ) val analyzer = Analyzer(settings, listOf(StyleRuleSetProvider()), emptyList()) assertThatThrownBy { settings.use { analyzer.run(listOf(compileForTest(testFile))) } } .isInstanceOf(CompletionException::class.java) .hasCauseInstanceOf(IllegalStateException::class.java) } } describe("analyze successfully when config has correct value type in config") { it("no findings") { val testFile = path.resolve("Test.kt") val settings = createProcessingSettings(testFile, yamlConfig("configs/config-value-type-correct.yml")) val analyzer = Analyzer(settings, listOf(StyleRuleSetProvider()), emptyList()) assertThat(settings.use { analyzer.run(listOf(compileForTest(testFile))) }).isEmpty() } it("with findings") { val testFile = path.resolve("Test.kt") val settings = createProcessingSettings(testFile, yamlConfig("configs/config-value-type-correct.yml")) val analyzer = Analyzer(settings, listOf(StyleRuleSetProvider(18)), emptyList()) assertThat(settings.use { analyzer.run(listOf(compileForTest(testFile))) }).hasSize(1) } it("with findings but ignored") { val testFile = path.resolve("Test.kt") val settings = createProcessingSettings( testFile, yamlConfig("configs/config-value-type-correct-ignore-annotated.yml") ) val analyzer = Analyzer(settings, listOf(StyleRuleSetProvider(18)), emptyList()) assertThat(settings.use { analyzer.run(listOf(compileForTest(testFile))) }).isEmpty() } } }) private class StyleRuleSetProvider(private val threshold: Int? = null) : RuleSetProvider { override val ruleSetId: String = "style" override fun instance(config: Config) = RuleSet(ruleSetId, listOf(MaxLineLength(config, threshold))) } private class MaxLineLength(config: Config, threshold: Int?) : Rule(config) { override val issue = Issue(this::class.java.simpleName, Severity.Style, "", Debt.FIVE_MINS) private val lengthThreshold: Int = threshold ?: valueOrDefault("maxLineLength", 100) override fun visitKtFile(file: KtFile) { super.visitKtFile(file) for (line in file.text.lineSequence()) { if (line.length > lengthThreshold) { report(CodeSmell(issue, Entity.atPackageOrFirstDecl(file), issue.description)) } } } }
apache-2.0
aa722c0270c14353d2695597dc136d79
43.623762
114
0.670734
4.789586
false
true
false
false
nemerosa/ontrack
ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/metrics/NotificationsMetricsExtensions.kt
1
1810
package net.nemerosa.ontrack.extension.notifications.metrics import io.micrometer.core.instrument.MeterRegistry import net.nemerosa.ontrack.extension.notifications.channels.NotificationResult import net.nemerosa.ontrack.extension.notifications.dispatching.NotificationDispatchingResult import net.nemerosa.ontrack.extension.notifications.model.Notification import net.nemerosa.ontrack.extension.notifications.subscriptions.EventSubscription import net.nemerosa.ontrack.model.events.Event import net.nemerosa.ontrack.model.metrics.increment fun MeterRegistry.incrementForEvent( name: String, event: Event, ) = increment( name, *getTags(event) ) fun MeterRegistry.incrementForDispatching( name: String, event: Event, subscription: EventSubscription, result: NotificationDispatchingResult? = null, ) = increment( name, *getTags(event, subscription, result) ) fun MeterRegistry.incrementForProcessing( name: String, notification: Notification, result: NotificationResult? = null, ) = if (result != null) { increment( name, "event" to notification.event.eventType.id, "channel" to notification.channel, "result" to result.type.name, ) } else { increment( name, "event" to notification.event.eventType.id, "channel" to notification.channel, ) } fun getTags( event: Event, subscription: EventSubscription, result: NotificationDispatchingResult?, ): Array<Pair<String, String>> = arrayOf( "event" to event.eventType.id, "channel" to subscription.channel, ) + if (result != null) { arrayOf("result" to result.name) } else { emptyArray() } private fun getTags(event: Event): Array<Pair<String, String>> = arrayOf( "event" to event.eventType.id )
mit
03946697e924cfb263b0edd87fa0e828
27.28125
93
0.724309
4.141876
false
false
false
false
americanexpress/bucketlist
examples/src/main/kotlin/io/aexp/bucketlist/examples/concurrentprs/ExportConcurrentPrData.kt
1
12548
package io.aexp.bucketlist.examples.concurrentprs import com.google.common.collect.HashMultiset import com.google.common.collect.Multiset import com.opencsv.CSVWriter import io.aexp.bucketlist.BucketListClient import io.aexp.bucketlist.data.PullRequest import io.aexp.bucketlist.data.PullRequestActivity import io.aexp.bucketlist.data.PullRequestState import io.aexp.bucketlist.examples.getBitBucketClient import org.slf4j.Logger import org.slf4j.LoggerFactory import rx.Observable import rx.observables.GroupedObservable import java.io.FileWriter import java.nio.file.Path import java.nio.file.Paths import java.time.LocalDate import java.time.LocalDateTime import java.time.LocalTime import java.time.ZoneId import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import java.util.ArrayList /** * This example downloads all the activity on all the PRs in the selected repository and attempts to determine * the maximum number of PRs that each user could have had open during that time. * * We wanted to get a sense of how many PRs our team typically has open, and even more importantly, how many PRs each * person has open at any given time. We wanted to look at about a week's worth of activity to prevent too much noise * from being generated, so we started by breaking down the most recent week by hour and calculating how many * PRs could have been open by author. * * This should allow us to see how many PRs our team as a whole has open, but also how many PRs each person has * at a given time. * * Usage: * - make a properties file containing 'username', 'password', and 'url' info for your Bitbucket-Server instance * - invoke with <path to props file> <project key> <repo slug> <output file> <start date> <end date> * - dates should be in the format YYYY-MM-DD */ object ExportConcurrentPrData { val logger: Logger = LoggerFactory.getLogger(javaClass) @JvmStatic fun main(args: Array<String>) { if (args.size != 6) { System.err!!.println("Must have 6 arguments: <config file> <project key> <repo slug> <output file> <start date> <end date>") System.exit(1) } val configPath = Paths.get(args[0]) val client = getBitBucketClient(configPath) val projectKey = args[1] val repoSlug = args[2] val outputCsvPath = Paths.get(args[3]) val startDate = ZonedDateTime.of(LocalDateTime.of(LocalDate.parse(args[4]), LocalTime.MIDNIGHT), ZoneId.of("UTC")) val endDate = ZonedDateTime.of(LocalDateTime.of(LocalDate.parse(args[5]), LocalTime.MIDNIGHT), ZoneId.of("UTC")) if (startDate.isAfter(endDate)) { System.err!!.println("Start date must be before end date") System.exit(1); } val prsByAuthor = getPrsByAuthor(client, projectKey, repoSlug, startDate, endDate) val authorStats = prsByAuthor.flatMap({ authorWithPrs -> authorWithPrs.collect({ -> AuthorStats(authorWithPrs.key) }, { authorHolder, prSummary -> val truncatedOpenTime = prSummary.openDate.truncatedTo(ChronoUnit.HOURS) val truncatedCloseTime = prSummary.closeDate.truncatedTo(ChronoUnit.HOURS) logger.info("Adding PR opened by ${authorHolder.author} at $truncatedOpenTime") authorHolder.openedPrs.add(truncatedOpenTime) logger.info("Adding PR closed by ${authorHolder.author} at $truncatedCloseTime") authorHolder.closedPrs.add(truncatedCloseTime) }) }) .toSortedList({ authors1, authors2 -> authors1.author.compareTo(authors2.author) }) .toBlocking() .first() printBetterCsv(outputCsvPath, authorStats, startDate, endDate) logger.info("Done writing CSV") System.exit(0) } /** * Get a collection of PRs with their respective open and close activities, grouped by the person who created the PR */ private fun getPrsByAuthor(client: BucketListClient, projectKey: String, repoSlug: String, startDate: ZonedDateTime, endDate: ZonedDateTime) : Observable<GroupedObservable<String, PrSummary>> { return client.getPrs(projectKey, repoSlug, PullRequestState.ALL) .flatMap({ prPages -> Observable.from(prPages.values) }) .filter({ pr -> // Don't bother getting activity for any PRs that were created after the end date // Don't bother getting activity for any PRs that are closed, where the last update was before the start date. pr.createdAt.isBefore(endDate) && !(pr.closed && pr.updatedAt.isBefore(startDate)) }) .flatMap({ pr -> client.getPrActivity(projectKey, repoSlug, pr.id) .flatMap({ activityPage -> Observable.from(activityPage.values) }) .filter({ activity -> // We only care about activity that opens or closes the PR, filter everything else out activity.action.equals("OPENED") || activity.action.equals("MERGED") || activity.action.equals("DECLINED") }) .toSortedList({ activity1, activity2 -> activity1.createdAt.compareTo(activity2.createdAt) }) .map({ activities -> PrSummary(pr, activities) }) }) .groupBy({ pr -> pr.pr.author.user.name }) } private class AuthorStats(val author: String, val openedPrs: Multiset<ZonedDateTime> = HashMultiset.create<ZonedDateTime>(), val closedPrs: Multiset<ZonedDateTime> = HashMultiset.create<ZonedDateTime>(), val totalPrs: Multiset<ZonedDateTime> = HashMultiset.create<ZonedDateTime>()) /** * Container class to hold a PR and its activities. Also supplies a few convenience methods for getting * statistics relevant to the timeline of the PR */ private class PrSummary(val pr: PullRequest, val activities: List<PullRequestActivity>) { val openDate: ZonedDateTime get() = pr.createdAt val closeDate: ZonedDateTime // We assume that the last event of the PR is either a merge or a decline. Theoretically you can take // more action after that, but this combined with out filter should be enough to capture most cases. // Note, PRs that are still open will not have a close event, so it will look like closeDate == openDate get() = activities.last().createdAt } /** * Given a collection of data, where each author has a multiset of times where they had some number of PRs * open, print that to a CSV file * * Each user will have a column of integrers that correspond to the maximum number of PRs that they could * have had open during that time period. * * For example, if user1 starts out at time t with 2 PRs open and, over the duration that it takes to get to time * t2, opens 3 more PRs, then we should print a 5 in the t column for that user. However, it might also be * true that user1 merged 1 PR during that time, so time t2 would have an initial value of 4. */ private fun printBetterCsv(outputCsvPath: Path, authorStats: List<AuthorStats>, startDate: ZonedDateTime, endDate: ZonedDateTime) { val times = getTimesBetween(startDate, endDate) // totalAuthorStats is actually the same list as the authorStats argument, except that the totalPrs // multiset has been filled out, based on the openPrs and closedPrs sets. It isn't necessary to keep // the extra instance, but I think it makes it clearer that it's been operated on. val totalAuthorStats = calculateTotalPrs(times, authorStats) val outputCsvFile = outputCsvPath.toFile() CSVWriter(FileWriter(outputCsvFile)).use { writer -> // Header row val authors = ArrayList<String>(listOf("Time")) for (author in totalAuthorStats) { authors.add(author.author) } writer.writeNext(authors.toArray(arrayOfNulls<String>(0))) // For every time that we're interested in, look at each author and get the count of times that we've // added something into their PR set. for (time in times) { logger.info("Looking for PRs on $time") val row = ArrayList<String>(listOf(time.toString())) for (authorStat in totalAuthorStats) { row.add(authorStat.totalPrs.count(time).toString()) } logger.info("Writing row for day $time") writer.writeNext(row.toArray(arrayOfNulls<String>(0))) } } } /** * We think that the most valuable piece of data from this set is the total number of PRs that could have been * open during a time slot. We calculate that by adding the number of PRs that a user had open at the start * of the time slot to the number of PRs that they opened during the time slot. However, it's also possible * that they closed some number of PRs during that time slot, so the following slot should be the maximum * described above, minus the number of PRs that the user closed. */ private fun calculateTotalPrs(times: List<ZonedDateTime>, authorStats: List<AuthorStats>) : List<AuthorStats> { // Write the first time period as a base case. All the future time slots will rely on the first one // being filled out val firstTime = times[0] for (authorStat in authorStats) { // Note, our first time slot only takes into account the number of PRs that are opened during that time. // This could mean that the user already has some PRs open. We think that we can ignore those for now, // but we'll have to provide a little extra safety later to make sure we don't set a count of < 0. val openedPrs = authorStat.openedPrs.count(firstTime) authorStat.totalPrs.setCount(firstTime, openedPrs) } // Now that we have a base case, look at the rest of the time slots and calculate the total value based // on the previous total value, along with opens and closes. // Note that we ignore the first element, because that had to be manually set above for (i in times.subList(1, times.count()).indices) { for (authorStat in authorStats) { // This is a bit weird, but we're actually trying to set the count at the next timeslot, given // the count at the current timeslot, so we have to shift our indices to match what we're looking for. // Hence, the previous time is the current index and the current time is the i + 1 index. We made sure // not to go out of bounds on the list by sublisting in the outer for loop. val currentTime = times[i + 1] val previousTime = times[i] val previouslyOpenCount = authorStat.totalPrs.count(previousTime) val previouslyClosedCount = authorStat.closedPrs.count(previousTime) val currentOpenCount = getOpenPrsForNextTime(currentTime, previouslyOpenCount, previouslyClosedCount, authorStat.openedPrs) authorStat.totalPrs.setCount(currentTime, if (currentOpenCount < 0) 0 else currentOpenCount) } } return authorStats } /** * Collect a list of times that we want to use as inputs to calculate the number of PRs at. */ private fun getTimesBetween(startDate: ZonedDateTime, endDate: ZonedDateTime) : List<ZonedDateTime> { val times = ArrayList<ZonedDateTime>() var time = startDate while (time.isBefore(endDate)) { times.add(time) time = time.plusHours(1) } return times } /** * Calculation to get the current row of a CSV, based on the previous row. */ private fun getOpenPrsForNextTime(time: ZonedDateTime, previouslyOpenCount: Int, previouslyClosedCount: Int, openedPrs: Multiset<ZonedDateTime>) : Int { return previouslyOpenCount + openedPrs.count(time) - previouslyClosedCount } }
apache-2.0
d83025d2913302bedd870bd7ed1b0950
50.85124
148
0.652614
4.508803
false
false
false
false
cbeust/kobalt
modules/kobalt-plugin-api/src/main/kotlin/com/beust/kobalt/BuildScript.kt
2
4986
package com.beust.kobalt import com.beust.kobalt.api.IClasspathDependency import com.beust.kobalt.api.Kobalt import com.beust.kobalt.api.annotation.Directive import com.beust.kobalt.internal.KobaltSettings import com.beust.kobalt.internal.PluginInfo import com.beust.kobalt.maven.DependencyManager import com.beust.kobalt.maven.dependency.FileDependency import com.beust.kobalt.misc.KobaltLogger import org.eclipse.aether.repository.Proxy import java.io.File import java.net.InetSocketAddress var BUILD_SCRIPT_CONFIG : BuildScriptConfig? = null class BuildScriptConfig { /** The list of repos used to locate plug-ins. */ @Directive fun repos(vararg r: String) = newRepos(*r) /** The list of plug-ins to use for this build file. */ @Directive fun plugins(vararg pl: String) = newPlugins(*pl) /** The build file classpath. */ @Directive fun buildFileClasspath(vararg bfc: String) = newBuildFileClasspath(*bfc) /** Options passed to Kobalt */ @Directive fun kobaltOptions(vararg options: String) = Kobalt.addKobaltOptions(options) /** Where to find additional build files */ @Directive fun buildSourceDirs(vararg dirs: String) = Kobalt.addBuildSourceDirs(dirs) // The following settings modify the compiler used to compile the build file, which regular users should // probably never need to do. Projects should use kotlinCompiler { compilerVersion } to configure the // Kotin compiler for their source files. var kobaltCompilerVersion : String? = null var kobaltCompilerRepo: String? = null var kobaltCompilerFlags: String? = null } @Directive fun homeDir(vararg dirs: String) : String = SystemProperties.homeDir + File.separator + dirs.toMutableList().joinToString(File.separator) @Directive fun file(file: String) : String = FileDependency.PREFIX_FILE + file fun plugins(vararg dependency : IClasspathDependency) { dependency.forEach { Plugins.addDynamicPlugin(it) } } fun plugins(vararg dependencies : String) { KobaltLogger.logger.warn("Build.kt", "Invoking plugins() directly is deprecated, use the buildScript{} directive") newPlugins(*dependencies) } @Directive fun newPlugins(vararg dependencies : String) { val factory = Kobalt.INJECTOR.getInstance(DependencyManager::class.java) dependencies.forEach { Plugins.addDynamicPlugin(factory.create(it)) } } data class ProxyConfig(val host: String = "", val port: Int = 0, val type: String = "", val nonProxyHosts: String = "") { fun toProxy() = java.net.Proxy(java.net.Proxy.Type.HTTP, InetSocketAddress(host, port)) fun toAetherProxy() = Proxy(type, host, port) // TODO make support for proxy auth } data class HostConfig(var url: String = "", var name: String = HostConfig.createRepoName(url), var username: String? = null, var password: String? = null) { companion object { /** * For repos specified in the build file (repos()) that don't have an associated unique name, * create such a name from the URL. This is a requirement from Maven Resolver, and failing to do * this leads to very weird resolution errors. */ private fun createRepoName(url: String) = url.replace("/", "_").replace("\\", "_").replace(":", "_") } fun hasAuth() : Boolean { return (! username.isNullOrBlank()) && (! password.isNullOrBlank()) } override fun toString() : String { return url + if (username != null) { "username: $username, password: ***" } else { "" } } } fun repos(vararg repos : String) { KobaltLogger.logger.warn("Build.kt", "Invoking repos() directly is deprecated, use the buildScript{} directive") newRepos(*repos) } fun newRepos(vararg repos: String) { repos.forEach { Kobalt.addRepo(HostConfig(it)) } } fun buildFileClasspath(vararg deps: String) { KobaltLogger.logger.warn("Build.kt", "Invoking buildFileClasspath() directly is deprecated, use the buildScript{} directive") newBuildFileClasspath(*deps) } fun newBuildFileClasspath(vararg deps: String) { //FIXME newBuildFileClasspath called twice deps.forEach { Kobalt.addBuildFileClasspath(it) } } @Directive fun authRepos(vararg repos : HostConfig) { repos.forEach { Kobalt.addRepo(it) } } @Directive fun authRepo(init: HostConfig.() -> Unit) = HostConfig(name = "").apply { init() } @Directive fun glob(g: String) : IFileSpec.GlobSpec = IFileSpec.GlobSpec(g) /** * The location of the local Maven repository. */ @Directive fun localMaven() : String { val pluginInfo = Kobalt.INJECTOR.getInstance(PluginInfo::class.java) val initial = Kobalt.INJECTOR.getInstance(KobaltSettings::class.java).localMavenRepo val result = pluginInfo.localMavenRepoPathInterceptors.fold(initial) { current, interceptor -> File(interceptor.repoPath(current.absolutePath)) } return result.toURI().toString() }
apache-2.0
7ac9d3fa2bb8867032336ac0e6793b79
33.386207
121
0.703771
4.161937
false
true
false
false
equeim/tremotesf-android
torrentfile/src/test/kotlin/org/equeim/tremotesf/torrentfile/NodeUtils.kt
1
2672
package org.equeim.tremotesf.torrentfile import org.junit.Assert.assertArrayEquals import org.junit.Assert.assertEquals import org.junit.Assert.assertNotEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertNotSame import org.junit.Assert.assertSame fun assertNodesAreSimilar(expected: TorrentFilesTree.Node, actual: TorrentFilesTree.Node?) { assertNotNull(actual) assertEquals(expected::class, actual!!::class) assertArrayEquals(expected.path, actual.path) assertEquals(expected.item, actual.item) if (expected is TorrentFilesTree.DirectoryNode && actual is TorrentFilesTree.DirectoryNode) { assertNodesAreSimilar(expected.children, actual.children) } } fun assertNodesAreSimilar(expected: List<TorrentFilesTree.Node>, actual: List<TorrentFilesTree.Node>) { expected.asSequence().zip(actual.asSequence()).forEach { (expectedFile, actualFile) -> assertNodesAreSimilar(expectedFile, actualFile) } } fun expectedFileItem(fileId: Int, nodePath: IntArray): TorrentFilesTree.Item { return TorrentFilesTree.Item(fileId, fileId.toString(), 666, 7, TorrentFilesTree.Item.WantedState.Wanted, TorrentFilesTree.Item.Priority.Normal, nodePath) } fun expectedDirectoryItem(nodePath: IntArray): TorrentFilesTree.Item { return TorrentFilesTree.Item(name = "42${nodePath.contentToString()}", nodePath = nodePath) } fun TorrentFilesTree.Node.getAllNodes(): Sequence<TorrentFilesTree.Node> { return if (this is TorrentFilesTree.DirectoryNode) { sequenceOf(this) + children.asSequence() } else { sequenceOf(this) } } class NodesThatMustChangeHelper(val nodes: List<TorrentFilesTree.Node>) { constructor(nodes: Sequence<TorrentFilesTree.Node>) : this(nodes.toList()) constructor(vararg nodes: TorrentFilesTree.Node) : this(nodes.toList()) private val oldItems = nodes.map { it.item } fun assertThatItemsChanged(additionalChecks: (TorrentFilesTree.Item) -> Unit = {}) = nodes.asSequence().zip(oldItems.asSequence()).forEach { (node, oldItem) -> assertNotSame(oldItem, node.item) assertNotEquals(oldItem, node.item) additionalChecks(node.item) } } class NodesThatMustNotChangeHelper(val nodes: List<TorrentFilesTree.Node>) { constructor(nodes: Sequence<TorrentFilesTree.Node>) : this(nodes.toList()) constructor(vararg nodes: TorrentFilesTree.Node) : this(nodes.toList()) private val oldItems = nodes.map { it.item } fun assertThatItemsAreNotChanged() = nodes.asSequence().zip(oldItems.asSequence()).forEach { (node, oldItem) -> assertSame(oldItem, node.item) assertEquals(oldItem, node.item) } }
gpl-3.0
e648a3bfbd8762349b410920bcb2b0f4
40.107692
163
0.750749
4.373159
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/view/Text.kt
1
15882
package com.soywiz.korge.view import com.soywiz.korge.debug.* import com.soywiz.korge.html.* import com.soywiz.korge.render.* import com.soywiz.korge.view.internal.InternalViewAutoscaling import com.soywiz.korge.view.ktree.* import com.soywiz.korim.bitmap.* import com.soywiz.korim.color.* import com.soywiz.korim.font.* import com.soywiz.korim.text.* import com.soywiz.korio.async.* import com.soywiz.korio.file.* import com.soywiz.korio.resources.* import com.soywiz.korio.serialization.xml.* import com.soywiz.korma.geom.* import com.soywiz.korui.* /* // Example: val font = BitmapFont(DefaultTtfFont, 64.0) var offset = 0.degrees addUpdater { offset += 10.degrees } text2("Hello World!", color = Colors.RED, font = font, renderer = CreateStringTextRenderer { text, n, c, c1, g, advance -> transform.identity() val sin = sin(offset + (n * 360 / text.length).degrees) transform.rotate(15.degrees) transform.translate(0.0, sin * 16) transform.scale(1.0, 1.0 + sin * 0.1) put(c) advance(advance) }).position(100, 100) */ inline fun Container.text( text: String, textSize: Double = Text.DEFAULT_TEXT_SIZE, color: RGBA = Colors.WHITE, font: Resourceable<out Font> = DefaultTtfFont, alignment: TextAlignment = TextAlignment.TOP_LEFT, renderer: TextRenderer<String> = DefaultStringTextRenderer, autoScaling: Boolean = Text.DEFAULT_AUTO_SCALING, block: @ViewDslMarker Text.() -> Unit = {} ): Text = Text(text, textSize, color, font, alignment, renderer, autoScaling).addTo(this, block) open class Text( text: String, textSize: Double = DEFAULT_TEXT_SIZE, color: RGBA = Colors.WHITE, font: Resourceable<out Font> = DefaultTtfFont, alignment: TextAlignment = TextAlignment.TOP_LEFT, renderer: TextRenderer<String> = DefaultStringTextRenderer, autoScaling: Boolean = DEFAULT_AUTO_SCALING ) : Container(), ViewLeaf, IText { companion object { val DEFAULT_TEXT_SIZE = 16.0 val DEFAULT_AUTO_SCALING = true } var smoothing: Boolean = true object Serializer : KTreeSerializerExt<Text>("Text", Text::class, { Text("Text") }, { add(Text::text, "Text") add(Text::fontSource) add(Text::textSize, DEFAULT_TEXT_SIZE) add(Text::autoScaling, DEFAULT_AUTO_SCALING) add(Text::verticalAlign, { VerticalAlign(it) }, { it.toString() }) add(Text::horizontalAlign, { HorizontalAlign(it) }, { it.toString() }) //view.fontSource = xml.str("fontSource", "") }) { override suspend fun ktreeToViewTree(xml: Xml, currentVfs: VfsFile): Text { return super.ktreeToViewTree(xml, currentVfs).also { view -> if ((view.fontSource ?: "").isNotBlank()) { try { view.forceLoadFontSource(currentVfs, view.fontSource) } catch (e: Throwable) { e.printStackTrace() } } } } } private var cachedVersion = -1 private var cachedVersionRenderer = -1 private var version = 0 var lineCount: Int = 0; private set override var text: String = text; set(value) { if (field != value) { field = value; updateLineCount() version++ } } private fun updateLineCount() { lineCount = text.count { it == '\n' } + 1 } init { updateLineCount() } var color: RGBA = color; set(value) { if (field != value) { field = value; version++ } } var font: Resourceable<out Font> = font; set(value) { if (field != value) { field = value; version++ } } var textSize: Double = textSize; set(value) { if (field != value) { field = value; version++ } } var fontSize: Double get() = textSize set(value) { textSize = value } var renderer: TextRenderer<String> = renderer; set(value) { if (field != value) { field = value; version++ } } var alignment: TextAlignment = alignment; set(value) { if (field != value) { field = value; version++ } } var horizontalAlign: HorizontalAlign get() = alignment.horizontal set(value) = run { alignment = alignment.withHorizontal(value) } var verticalAlign: VerticalAlign get() = alignment.vertical set(value) = run { alignment = alignment.withVertical(value) } private lateinit var textToBitmapResult: TextToBitmapResult private val container = container() private val bitmapFontActions = Text2TextRendererActions() private var fontLoaded: Boolean = false var autoScaling = autoScaling var fontSource: String? = null set(value) { field = value fontLoaded = false } // @TODO: Use, font: Resourceable<out Font> suspend fun forceLoadFontSource(currentVfs: VfsFile, sourceFile: String?) { fontSource = sourceFile fontLoaded = true if (sourceFile != null) { font = currentVfs["$sourceFile"].readFont() } } private val _textBounds = Rectangle(0, 0, 2048, 2048) var autoSize = true private var boundsVersion = -1 val textBounds: Rectangle get() { getLocalBounds(_textBounds) return _textBounds } fun setFormat(face: Resourceable<out Font>? = this.font, size: Int = this.size, color: RGBA = this.color, align: TextAlignment = this.alignment) { this.font = face ?: DefaultTtfFont this.textSize = size.toDouble() this.color = color this.alignment = align } fun setFormat(format: Html.Format) { setFormat(format.computedFace, format.computedSize, format.computedColor, format.computedAlign) } fun setTextBounds(rect: Rectangle) { if (this._textBounds == rect && !autoSize) return this._textBounds.copyFrom(rect) autoSize = false boundsVersion++ version++ } fun unsetTextBounds() { if (autoSize) return autoSize = true boundsVersion++ version++ } override fun getLocalBoundsInternal(out: Rectangle) { _renderInternal(null) out.copyFrom(_textBounds) } private val tempMatrix = Matrix() //var newTvaRenderer = true var newTvaRenderer = false override fun renderInternal(ctx: RenderContext) { _renderInternal(ctx) while (imagesToRemove.isNotEmpty()) { ctx.agBitmapTextureManager.removeBitmap(imagesToRemove.removeLast()) } //val tva: TexturedVertexArray? = null if (tva != null) { tempMatrix.copyFrom(globalMatrix) tempMatrix.pretranslate(container.x, container.y) ctx.useBatcher { batch -> batch.setStateFast((font as BitmapFont).baseBmp, smoothing, renderBlendMode.factors, null) batch.drawVertices(tva!!, tempMatrix) } } else { super.renderInternal(ctx) } } var cachedVersionGlyphMetrics = -1 private var _textMetricsResult: TextMetricsResult? = null fun getGlyphMetrics(): TextMetricsResult { if (cachedVersionGlyphMetrics != version) { cachedVersionGlyphMetrics = version _textMetricsResult = font.getOrNull()?.measureTextGlyphs(fontSize, text, renderer) } return _textMetricsResult ?: error("Must ensure font is resolved before calling getGlyphMetrics") } private val tempBmpEntry = Text2TextRendererActions.Entry() private val fontMetrics = FontMetrics() private val textMetrics = TextMetrics() private var lastAutoScaling: Boolean? = null private var lastSmoothing: Boolean? = null private var lastNativeRendering: Boolean? = null private var tva: TexturedVertexArray? = null private val identityMat = Matrix() fun _renderInternal(ctx: RenderContext?) { if (ctx != null) { val fontSource = fontSource if (!fontLoaded && fontSource != null) { fontLoaded = true launchImmediately(ctx.coroutineContext) { forceLoadFontSource(ctx.views!!.currentVfs, fontSource) } } } container.colorMul = color val font = this.font.getOrNull() if (autoSize && font is Font && boundsVersion != version) { boundsVersion = version val metrics = font.getTextBounds(textSize, text, out = textMetrics, renderer = renderer) _textBounds.copyFrom(metrics.bounds) _textBounds.height = font.getFontMetrics(textSize, metrics = fontMetrics).lineHeight * lineCount _textBounds.x = -alignment.horizontal.getOffsetX(_textBounds.width) + metrics.left _textBounds.y = alignment.vertical.getOffsetY(_textBounds.height, -metrics.ascent) } when (font) { null -> Unit is BitmapFont -> { val rversion = renderer.version if (lastSmoothing != smoothing || cachedVersion != version || cachedVersionRenderer != rversion) { lastSmoothing = smoothing cachedVersionRenderer = rversion cachedVersion = version _staticImage = null bitmapFontActions.x = 0.0 bitmapFontActions.y = 0.0 bitmapFontActions.mreset() bitmapFontActions.verticalAlign = verticalAlign bitmapFontActions.horizontalAlign = horizontalAlign renderer.invoke(bitmapFontActions, text, textSize, font) while (container.numChildren < bitmapFontActions.size) { container.image(Bitmaps.transparent) } while (container.numChildren > bitmapFontActions.size) { container[container.numChildren - 1].removeFromParent() } //println(font.glyphs['H'.toInt()]) //println(font.glyphs['a'.toInt()]) //println(font.glyphs['g'.toInt()]) val textWidth = bitmapFontActions.x val dx = -textWidth * horizontalAlign.ratio if (newTvaRenderer) { this.tva = TexturedVertexArray.forQuads(bitmapFontActions.size) } for (n in 0 until bitmapFontActions.size) { val entry = bitmapFontActions.read(n, tempBmpEntry) if (newTvaRenderer) { tva?.quad(n * 4, entry.x + dx, entry.y, entry.tex.width * entry.sx, entry.tex.height * entry.sy, identityMat, entry.tex, renderColorMul, renderColorAdd) } else { val it = (container[n] as Image) it.anchor(0, 0) it.smoothing = smoothing it.bitmap = entry.tex it.x = entry.x + dx it.y = entry.y it.scaleX = entry.sx it.scaleY = entry.sy it.rotation = entry.rot } } setContainerPosition(0.0, 0.0, font.base) } } else -> { val onRenderResult = autoscaling.onRender(autoScaling, this.globalMatrix) val lastAutoScalingResult = lastAutoScaling != autoScaling if (onRenderResult || lastAutoScalingResult || lastSmoothing != smoothing || lastNativeRendering != useNativeRendering) { version++ //println("UPDATED VERSION[$this] lastAutoScaling=$lastAutoScaling, autoScaling=$autoScaling, onRenderResult=$onRenderResult, lastAutoScalingResult=$lastAutoScalingResult") lastNativeRendering = useNativeRendering lastAutoScaling = autoScaling lastSmoothing = smoothing } if (cachedVersion != version) { cachedVersion = version val realTextSize = textSize * autoscaling.renderedAtScaleXY //println("realTextSize=$realTextSize") textToBitmapResult = when { text.isNotEmpty() -> { font.renderTextToBitmap( realTextSize, text, paint = Colors.WHITE, fill = true, renderer = renderer, //background = Colors.RED, nativeRendering = useNativeRendering, drawBorder = true ) } else -> { TextToBitmapResult(Bitmaps.transparent.bmp, FontMetrics(), TextMetrics(), emptyList()) } } //println("RENDER TEXT: '$text'") val met = textToBitmapResult.metrics val x = -horizontalAlign.getOffsetX(met.width) + met.left val y = verticalAlign.getOffsetY(met.lineHeight, -(met.ascent)) if (_staticImage == null) { container.removeChildren() _staticImage = container.image(textToBitmapResult.bmp) } else { imagesToRemove.add(_staticImage!!.bitmap.bmpBase) _staticImage!!.bitmap = textToBitmapResult.bmp.slice() } val mscale = 1.0 / autoscaling.renderedAtScaleXY _staticImage!!.scale(mscale, mscale) setContainerPosition(x * mscale, y * mscale, font.getFontMetrics(fontSize, fontMetrics).baseline) } _staticImage?.smoothing = smoothing } } } var useNativeRendering: Boolean = true private val autoscaling = InternalViewAutoscaling() private fun setContainerPosition(x: Double, y: Double, baseline: Double) { if (autoSize) { setRealContainerPosition(x, y) } else { //staticImage?.position(x + alignment.horizontal.getOffsetX(textBounds.width), y + alignment.vertical.getOffsetY(textBounds.height, font.getFontMetrics(fontSize).baseline)) setRealContainerPosition(x + alignment.horizontal.getOffsetX(_textBounds.width), y - alignment.vertical.getOffsetY(_textBounds.height, baseline)) } } private fun setRealContainerPosition(x: Double, y: Double) { container.position(x, y) } private val imagesToRemove = arrayListOf<Bitmap>() internal var _staticImage: Image? = null val staticImage: Image? get() { _renderInternal(null) return _staticImage } override fun buildDebugComponent(views: Views, container: UiContainer) { container.uiCollapsibleSection("Text") { uiEditableValue(::text) uiEditableValue(::textSize, min= 1.0, max = 300.0) uiEditableValue(::autoScaling) uiEditableValue(::verticalAlign, values = { listOf(VerticalAlign.TOP, VerticalAlign.MIDDLE, VerticalAlign.BASELINE, VerticalAlign.BOTTOM) }) uiEditableValue(::horizontalAlign, values = { listOf(HorizontalAlign.LEFT, HorizontalAlign.CENTER, HorizontalAlign.RIGHT, HorizontalAlign.JUSTIFY) }) uiEditableValue(::fontSource, UiTextEditableValue.Kind.FILE(views.currentVfs) { it.extensionLC == "ttf" || it.extensionLC == "fnt" }) } super.buildDebugComponent(views, container) } } fun <T : Text> T.autoSize(value: Boolean): T { this.autoSize = value return this }
apache-2.0
60d806a9cc90abfd212f535a05a55706
39.827763
192
0.587395
4.686338
false
false
false
false
bozaro/git-as-svn
src/test/kotlin/svnserver/server/DepthTest.kt
1
31466
/* * This file is part of git-as-svn. It is subject to the license terms * in the LICENSE file found in the top-level directory of this distribution * and at http://www.gnu.org/licenses/gpl-2.0.html. No part of git-as-svn, * including this file, may be copied, modified, propagated, or distributed * except according to the terms contained in the LICENSE file. */ package svnserver.server import org.testng.Assert import org.testng.annotations.Listeners import org.testng.annotations.Test import org.tmatesoft.svn.core.SVNDepth import org.tmatesoft.svn.core.SVNPropertyValue import org.tmatesoft.svn.core.io.ISVNReporter import org.tmatesoft.svn.core.io.ISVNReporterBaton import svnserver.SvnTestHelper import svnserver.replay.ReportSVNEditor import svnserver.tester.SvnTester import svnserver.tester.SvnTesterDataProvider import svnserver.tester.SvnTesterExternalListener import svnserver.tester.SvnTesterFactory /** * @author Marat Radchenko <marat@slonopotamus.org> */ @Listeners(SvnTesterExternalListener::class) class DepthTest { @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun interruptedUpdate(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision check( server, "", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, false) reporter.setPath("a/b/c", null, revision, SVNDepth.INFINITY, true) reporter.finishReport() }, """ - open-root: r0 / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid a - change-dir-prop: svn:entry:committed-date a - change-dir-prop: svn:entry:committed-rev a - change-dir-prop: svn:entry:last-author a - change-dir-prop: svn:entry:uuid a - open-dir: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c - open-dir: r0 a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end """ ) } } private fun create(factory: SvnTesterFactory): SvnTester { val tester = factory.create() val repo = tester.openSvnRepository() val editor = repo.getCommitEditor("", null) editor.openRoot(-1) editor.changeDirProperty("svn:ignore", SVNPropertyValue.create("sample.txt")) editor.addFile("/.gitattributes", null, -1) SvnTestHelper.sendDeltaAndClose(editor, "/.gitattributes", null, "\n") editor.addFile("/.gitignore", null, -1) SvnTestHelper.sendDeltaAndClose(editor, "/.gitignore", null, "/sample.txt\n") editor.addDir("/a", null, -1) editor.addDir("/a/b", null, -1) editor.addFile("/a/b/e", null, -1) SvnTestHelper.sendDeltaAndClose(editor, "/a/b/e", null, "e body") editor.addDir("/a/b/c", null, -1) editor.addFile("/a/b/c/d", null, -1) SvnTestHelper.sendDeltaAndClose(editor, "/a/b/c/d", null, "d body") editor.closeDir() editor.closeDir() editor.closeDir() editor.closeDir() editor.closeEdit() return tester } private fun check(server: SvnTester, path: String, depth: SVNDepth?, reporterBaton: ISVNReporterBaton, expected: String) { val repo = server.openSvnRepository() val editor = ReportSVNEditor() repo.update(repo.latestRevision, path, depth, false, reporterBaton, editor) Assert.assertEquals(editor.toString(), expected) } @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun empty(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision // svn checkout --depth empty check( server, "", SVNDepth.EMPTY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, true) reporter.finishReport() }, """ - open-root: r0 / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid / - change-dir-prop: svn:ignore """ ) // svn update check( server, "", SVNDepth.EMPTY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, """ - open-root: r0 / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid """ ) // svn update --set-depth infinity check( server, "", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, """ - open-root: r0 .gitattributes - add-file .gitattributes - apply-text-delta: null .gitattributes - change-file-prop: svn:entry:committed-date .gitattributes - change-file-prop: svn:entry:committed-rev .gitattributes - change-file-prop: svn:entry:last-author .gitattributes - change-file-prop: svn:entry:uuid .gitattributes - close-file: 68b329da9893e34099c7d8ad5cb9c940 .gitattributes - delta-chunk .gitattributes - delta-end .gitignore - add-file .gitignore - apply-text-delta: null .gitignore - change-file-prop: svn:entry:committed-date .gitignore - change-file-prop: svn:entry:committed-rev .gitignore - change-file-prop: svn:entry:last-author .gitignore - change-file-prop: svn:entry:uuid .gitignore - close-file: 57457451fdf67806102d334f30c062f3 .gitignore - delta-chunk .gitignore - delta-end / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid a - add-dir a - change-dir-prop: svn:entry:committed-date a - change-dir-prop: svn:entry:committed-rev a - change-dir-prop: svn:entry:last-author a - change-dir-prop: svn:entry:uuid a/b - add-dir a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end a/b/e - add-file a/b/e - apply-text-delta: null a/b/e - change-file-prop: svn:entry:committed-date a/b/e - change-file-prop: svn:entry:committed-rev a/b/e - change-file-prop: svn:entry:last-author a/b/e - change-file-prop: svn:entry:uuid a/b/e - close-file: babc2f91dac8ef35815e635d89196696 a/b/e - delta-chunk a/b/e - delta-end """ ) } } @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun emptySubdir(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision // svn checkout --depth empty check( server, "a/b", SVNDepth.EMPTY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, true) reporter.finishReport() }, """ - open-root: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 """ ) // svn update check(server, "a/b", SVNDepth.EMPTY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, " - open-root: r0\n") // svn update --set-depth infinity check( server, "a/b", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, """ - open-root: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end a/b/e - add-file a/b/e - apply-text-delta: null a/b/e - change-file-prop: svn:entry:committed-date a/b/e - change-file-prop: svn:entry:committed-rev a/b/e - change-file-prop: svn:entry:last-author a/b/e - change-file-prop: svn:entry:uuid a/b/e - close-file: babc2f91dac8ef35815e635d89196696 a/b/e - delta-chunk a/b/e - delta-end """ ) } } @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun emptySubdir2(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision // svn checkout --depth empty check( server, "a/b/c", SVNDepth.EMPTY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, true) reporter.finishReport() }, """ - open-root: r0 a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c - open-dir: r0 """ ) // svn update check(server, "a/b/c", SVNDepth.EMPTY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, " - open-root: r0\n") // svn update --set-depth infinity check( server, "a/b/c", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, """ - open-root: r0 a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c - open-dir: r0 a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end """ ) } } @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun infinity(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision // svn checkout --depth infinity a check( server, "", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, true) reporter.finishReport() }, """ - open-root: r0 .gitattributes - add-file .gitattributes - apply-text-delta: null .gitattributes - change-file-prop: svn:entry:committed-date .gitattributes - change-file-prop: svn:entry:committed-rev .gitattributes - change-file-prop: svn:entry:last-author .gitattributes - change-file-prop: svn:entry:uuid .gitattributes - close-file: 68b329da9893e34099c7d8ad5cb9c940 .gitattributes - delta-chunk .gitattributes - delta-end .gitignore - add-file .gitignore - apply-text-delta: null .gitignore - change-file-prop: svn:entry:committed-date .gitignore - change-file-prop: svn:entry:committed-rev .gitignore - change-file-prop: svn:entry:last-author .gitignore - change-file-prop: svn:entry:uuid .gitignore - close-file: 57457451fdf67806102d334f30c062f3 .gitignore - delta-chunk .gitignore - delta-end / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid / - change-dir-prop: svn:ignore a - add-dir a - change-dir-prop: svn:entry:committed-date a - change-dir-prop: svn:entry:committed-rev a - change-dir-prop: svn:entry:last-author a - change-dir-prop: svn:entry:uuid a/b - add-dir a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end a/b/e - add-file a/b/e - apply-text-delta: null a/b/e - change-file-prop: svn:entry:committed-date a/b/e - change-file-prop: svn:entry:committed-rev a/b/e - change-file-prop: svn:entry:last-author a/b/e - change-file-prop: svn:entry:uuid a/b/e - close-file: babc2f91dac8ef35815e635d89196696 a/b/e - delta-chunk a/b/e - delta-end """ ) // svn update check( server, "", SVNDepth.UNKNOWN, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, false) reporter.finishReport() }, """ - open-root: r0 / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid """ ) } } @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun infinitySubdir(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision // svn checkout --depth infinity a check( server, "a", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, true) reporter.finishReport() }, """ - open-root: r0 a - change-dir-prop: svn:entry:committed-date a - change-dir-prop: svn:entry:committed-rev a - change-dir-prop: svn:entry:last-author a - change-dir-prop: svn:entry:uuid a - open-dir: r0 a/b - add-dir a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end a/b/e - add-file a/b/e - apply-text-delta: null a/b/e - change-file-prop: svn:entry:committed-date a/b/e - change-file-prop: svn:entry:committed-rev a/b/e - change-file-prop: svn:entry:last-author a/b/e - change-file-prop: svn:entry:uuid a/b/e - close-file: babc2f91dac8ef35815e635d89196696 a/b/e - delta-chunk a/b/e - delta-end """ ) // svn update check(server, "a", SVNDepth.UNKNOWN, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, false) reporter.finishReport() }, " - open-root: r0\n") } } @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun files(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision // svn checkout --depth infinity a check( server, "a/b", SVNDepth.FILES, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, true) reporter.finishReport() }, """ - open-root: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/e - add-file a/b/e - apply-text-delta: null a/b/e - change-file-prop: svn:entry:committed-date a/b/e - change-file-prop: svn:entry:committed-rev a/b/e - change-file-prop: svn:entry:last-author a/b/e - change-file-prop: svn:entry:uuid a/b/e - close-file: babc2f91dac8ef35815e635d89196696 a/b/e - delta-chunk a/b/e - delta-end """ ) // svn update check(server, "a/b", SVNDepth.UNKNOWN, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.FILES, false) reporter.finishReport() }, " - open-root: r0\n") // svn update --set-depth infinity check( server, "a/b", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.FILES, false) reporter.finishReport() }, """ - open-root: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end """ ) } } @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun immediates(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision // svn checkout --depth immediates a/b check( server, "a/b", SVNDepth.IMMEDIATES, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, true) reporter.finishReport() }, """ - open-root: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/e - add-file a/b/e - apply-text-delta: null a/b/e - change-file-prop: svn:entry:committed-date a/b/e - change-file-prop: svn:entry:committed-rev a/b/e - change-file-prop: svn:entry:last-author a/b/e - change-file-prop: svn:entry:uuid a/b/e - close-file: babc2f91dac8ef35815e635d89196696 a/b/e - delta-chunk a/b/e - delta-end """ ) // svn update check(server, "a/b", SVNDepth.UNKNOWN, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.IMMEDIATES, false) reporter.finishReport() }, " - open-root: r0\n") // svn update --set-depth infinity check( server, "a/b", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.IMMEDIATES, false) reporter.finishReport() }, """ - open-root: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c - open-dir: r0 a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end """ ) } } @Test(dataProvider = "all", dataProviderClass = SvnTesterDataProvider::class) fun complex(factory: SvnTesterFactory) { create(factory).use { server -> val revision = server.openSvnRepository().latestRevision // svn checkout --depth infinity check( server, "", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, true) reporter.finishReport() }, """ - open-root: r0 .gitattributes - add-file .gitattributes - apply-text-delta: null .gitattributes - change-file-prop: svn:entry:committed-date .gitattributes - change-file-prop: svn:entry:committed-rev .gitattributes - change-file-prop: svn:entry:last-author .gitattributes - change-file-prop: svn:entry:uuid .gitattributes - close-file: 68b329da9893e34099c7d8ad5cb9c940 .gitattributes - delta-chunk .gitattributes - delta-end .gitignore - add-file .gitignore - apply-text-delta: null .gitignore - change-file-prop: svn:entry:committed-date .gitignore - change-file-prop: svn:entry:committed-rev .gitignore - change-file-prop: svn:entry:last-author .gitignore - change-file-prop: svn:entry:uuid .gitignore - close-file: 57457451fdf67806102d334f30c062f3 .gitignore - delta-chunk .gitignore - delta-end / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid / - change-dir-prop: svn:ignore a - add-dir a - change-dir-prop: svn:entry:committed-date a - change-dir-prop: svn:entry:committed-rev a - change-dir-prop: svn:entry:last-author a - change-dir-prop: svn:entry:uuid a/b - add-dir a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end a/b/e - add-file a/b/e - apply-text-delta: null a/b/e - change-file-prop: svn:entry:committed-date a/b/e - change-file-prop: svn:entry:committed-rev a/b/e - change-file-prop: svn:entry:last-author a/b/e - change-file-prop: svn:entry:uuid a/b/e - close-file: babc2f91dac8ef35815e635d89196696 a/b/e - delta-chunk a/b/e - delta-end """ ) // svn update --set-depth files a/b check(server, "a/b", SVNDepth.FILES, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.FILES, false) reporter.finishReport() }, " - open-root: r0\n") // svn update --set-depth infinity check( server, "", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, false) reporter.setPath("a/b", null, revision, SVNDepth.FILES, false) reporter.finishReport() }, """ - open-root: r0 / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid a - change-dir-prop: svn:entry:committed-date a - change-dir-prop: svn:entry:committed-rev a - change-dir-prop: svn:entry:last-author a - change-dir-prop: svn:entry:uuid a - open-dir: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end """ ) // svn update --set-depth empty a/b check(server, "a/b", SVNDepth.EMPTY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, " - open-root: r0\n") // svn update --set-depth infinity check( server, "", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, false) reporter.setPath("a/b", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, """ - open-root: r0 / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid a - change-dir-prop: svn:entry:committed-date a - change-dir-prop: svn:entry:committed-rev a - change-dir-prop: svn:entry:last-author a - change-dir-prop: svn:entry:uuid a - open-dir: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/c - add-dir a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end a/b/e - add-file a/b/e - apply-text-delta: null a/b/e - change-file-prop: svn:entry:committed-date a/b/e - change-file-prop: svn:entry:committed-rev a/b/e - change-file-prop: svn:entry:last-author a/b/e - change-file-prop: svn:entry:uuid a/b/e - close-file: babc2f91dac8ef35815e635d89196696 a/b/e - delta-chunk a/b/e - delta-end """ ) // svn update --set-depth immediates a/b check(server, "a/b", SVNDepth.IMMEDIATES, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.IMMEDIATES, false) reporter.finishReport() }, " - open-root: r0\n") // svn update --set-depth infinity check( server, "", SVNDepth.INFINITY, { reporter: ISVNReporter -> reporter.setPath("", null, revision, SVNDepth.INFINITY, false) reporter.setPath("a/b", null, revision, SVNDepth.IMMEDIATES, false) reporter.setPath("a/b/c", null, revision, SVNDepth.EMPTY, false) reporter.finishReport() }, """ - open-root: r0 / - change-dir-prop: svn:entry:committed-date / - change-dir-prop: svn:entry:committed-rev / - change-dir-prop: svn:entry:last-author / - change-dir-prop: svn:entry:uuid a - change-dir-prop: svn:entry:committed-date a - change-dir-prop: svn:entry:committed-rev a - change-dir-prop: svn:entry:last-author a - change-dir-prop: svn:entry:uuid a - open-dir: r0 a/b - change-dir-prop: svn:entry:committed-date a/b - change-dir-prop: svn:entry:committed-rev a/b - change-dir-prop: svn:entry:last-author a/b - change-dir-prop: svn:entry:uuid a/b - open-dir: r0 a/b/c - change-dir-prop: svn:entry:committed-date a/b/c - change-dir-prop: svn:entry:committed-rev a/b/c - change-dir-prop: svn:entry:last-author a/b/c - change-dir-prop: svn:entry:uuid a/b/c - open-dir: r0 a/b/c/d - add-file a/b/c/d - apply-text-delta: null a/b/c/d - change-file-prop: svn:entry:committed-date a/b/c/d - change-file-prop: svn:entry:committed-rev a/b/c/d - change-file-prop: svn:entry:last-author a/b/c/d - change-file-prop: svn:entry:uuid a/b/c/d - close-file: e08b5cff98d6e3f8a892fc999622d441 a/b/c/d - delta-chunk a/b/c/d - delta-end """ ) } } }
gpl-2.0
a5a0e0c1557593a10189d69632979108
38.629723
126
0.652005
2.979453
false
true
false
false
yukuku/androidbible
Alkitab/src/main/java/yuku/alkitab/base/verses/VersesAttributes.kt
1
1055
package yuku.alkitab.base.verses import yuku.alkitab.base.util.Highlights class VersesAttributes( val bookmarkCountMap_: IntArray, val noteCountMap_: IntArray, val highlightInfoMap_: Array<Highlights.Info?>, val progressMarkBitsMap_: IntArray, val hasMapsMap_: BooleanArray ) { companion object { private val EMPTY = VersesAttributes( bookmarkCountMap_ = IntArray(0), noteCountMap_ = IntArray(0), highlightInfoMap_ = emptyArray(), progressMarkBitsMap_ = IntArray(0), hasMapsMap_ = BooleanArray(0) ) fun createEmpty(verseCount: Int) = if (verseCount == 0) { EMPTY } else { VersesAttributes( bookmarkCountMap_ = IntArray(verseCount), noteCountMap_ = IntArray(verseCount), highlightInfoMap_ = arrayOfNulls(verseCount), progressMarkBitsMap_ = IntArray(verseCount), hasMapsMap_ = BooleanArray(verseCount) ) } } }
apache-2.0
76fe64fb8a88e1c1bbe8c2c076bde3c8
30.969697
65
0.599052
4.606987
false
false
false
false
Andr3Carvalh0/mGBA
app/src/main/java/io/mgba/data/FileManager.kt
1
2504
package io.mgba.data import io.mgba.utilities.Constants.PLATFORM_GBA import io.mgba.utilities.Constants.PLATFORM_GBC import java.io.File import io.mgba.utilities.device.PreferencesManager.GAMES_DIRECTORY import io.mgba.utilities.device.PreferencesManager.get /** * Handles the fetching/filtering of the supported files for the selected dir. */ object FileManager { private val TAG = "FileService" private val GBC_FILES_SUPPORTED: List<String> = listOf("gba", "gb") private val GBA_FILES_SUPPORTED: List<String> = listOf("gbc") private var directory: File = File(get(GAMES_DIRECTORY, "")) val gameList: List<File> = if (!directory.exists()) emptyList() else fetchGames() var path: String get() = directory.absolutePath set(directory) { FileManager.directory = File(directory) } /** * Based on the files of the directory, discard the ones we dont need. * If the file is a directory or the extension isnt in the FILES_SUPPORTED list, that file * isnt valid. * @param files the files of the directory * @return files that contain gba, gb, gbc extension and arent folders */ private fun filter(files: Array<File>): List<File> { return files.toList() .filter { f -> !f.isDirectory && (GBA_FILES_SUPPORTED.contains(getFileExtension(f)) || GBC_FILES_SUPPORTED.contains(getFileExtension(f))) } .toList() } private fun fetchGames(): List<File> = filter(directory.listFiles()) fun getPlatform(file: File): Int { if(GBC_FILES_SUPPORTED.contains(getFileExtension(file))){ return PLATFORM_GBC } return PLATFORM_GBA } /** * Gets the file extension. * For example. For the file 'a.bc' this method will return 'bc' * @param file The file to extract a extension * @return the file's extension */ fun getFileExtension(file: File): String { val name = file.name return if (!name.contains(".")) name.substring(name.length - 3) else name .substring(file.name.lastIndexOf(".")) .substring(1) .toLowerCase() } /** * Gets the filename without the extension * @param file * @return */ fun getFileWithoutExtension(file: File): String { val tmp = file.path.split("/".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() return tmp[tmp.size - 1].substring(0, tmp[tmp.size - 1].lastIndexOf(".")) } }
mpl-2.0
29394e9485f39a0f04c35e48536f51e4
32.837838
153
0.644968
4.111658
false
false
false
false
jitsi/jicofo
jicofo/src/test/kotlin/org/jitsi/jicofo/conference/source/EndpointSourceSetTest.kt
1
6648
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2021-Present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.jicofo.conference.source import io.kotest.core.spec.IsolationMode import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe import io.kotest.matchers.types.shouldBeInstanceOf import org.jitsi.utils.MediaType.AUDIO import org.jitsi.utils.MediaType.VIDEO import org.jitsi.xmpp.extensions.colibri.SourcePacketExtension import org.jitsi.xmpp.extensions.jingle.RtpDescriptionPacketExtension import org.jitsi.xmpp.extensions.jingle.SourceGroupPacketExtension import org.json.simple.JSONArray import org.json.simple.JSONObject import org.json.simple.parser.JSONParser @Suppress("NAME_SHADOWING") class EndpointSourceSetTest : ShouldSpec() { override fun isolationMode() = IsolationMode.InstancePerLeaf init { context("From XML") { // Assume serializing works correctly -- it's tested below. val contents = sourceSet.toJingle(jid1) val parsed = EndpointSourceSet.fromJingle(contents) // Use the provided ownerJid, not the one encoded in XML. parsed shouldBe sourceSet } context("To XML") { val contents = sourceSet.toJingle() contents.size shouldBe 2 val videoContent = contents.find { it.name == "video" }!! val videoRtpDesc = videoContent.getFirstChildOfType(RtpDescriptionPacketExtension::class.java)!! val videoSources = videoRtpDesc.getChildExtensionsOfType(SourcePacketExtension::class.java) .map { Source(VIDEO, it) }.toSet() videoSources shouldBe sourceSet.sources.filter { it.mediaType == VIDEO }.toSet() val sourceGroupPacketExtensions = videoRtpDesc.getChildExtensionsOfType(SourceGroupPacketExtension::class.java) sourceGroupPacketExtensions.map { SsrcGroup.fromPacketExtension(it) }.toSet() shouldBe sourceSet.ssrcGroups val audioContent = contents.find { it.name == "audio" }!! val audioRtpDesc = audioContent.getFirstChildOfType(RtpDescriptionPacketExtension::class.java)!! val audioSources = audioRtpDesc.getChildExtensionsOfType(SourcePacketExtension::class.java) .map { Source(AUDIO, it) }.toSet() audioSources shouldBe sourceSet.sources.filter { it.mediaType == AUDIO }.toSet() } context("Strip simulcast") { val s8 = Source(8, VIDEO) context("Without RTX") { EndpointSourceSet( setOf(s1, s2, s3, s7, s8), setOf(sim) ).stripSimulcast shouldBe EndpointSourceSet(setOf(s1, s7, s8)) } context("With multiple SIM groups") { EndpointSourceSet( sourceSet.sources + s8, setOf( sim, SsrcGroup(SsrcGroupSemantics.Sim, listOf(4, 5, 6)) ) ).stripSimulcast shouldBe EndpointSourceSet(setOf(s1, s4, s7, s8)) } context("With RTX") { EndpointSourceSet( sourceSet.sources + s8, sourceSet.ssrcGroups ).stripSimulcast shouldBe EndpointSourceSet( setOf(s1, s4, s7, s8), setOf(fid1) ) } context("Compact JSON") { // See the documentation of [EndpointSourceSet.compactJson] for the expected JSON format. val json = JSONParser().parse(sourceSet.compactJson) json.shouldBeInstanceOf<JSONArray>() val videoSourceList = json[0] videoSourceList.shouldBeInstanceOf<JSONArray>() videoSourceList.map { (it as JSONObject).toMap() }.toSet() shouldBe setOf( mapOf("s" to 1L), mapOf("s" to 2L), mapOf("s" to 3L), mapOf("s" to 4L), mapOf("s" to 5L), mapOf("s" to 6L) ) val videoSsrcGroups = json[1] videoSsrcGroups.shouldBeInstanceOf<JSONArray>() videoSsrcGroups.map { (it as JSONArray).toList() }.toSet() shouldBe setOf( listOf("s", 1, 2, 3), listOf("f", 1, 4), listOf("f", 2, 5), listOf("f", 3, 6) ) val audioSourceList = json[2] audioSourceList.shouldBeInstanceOf<JSONArray>() audioSourceList.map { (it as JSONObject).toMap() }.toSet() shouldBe setOf( mapOf("s" to 7L) ) // No audio source groups encoded. json.size shouldBe 3 } } } } const val jid1 = "jid1" const val jid2 = "jid2" val s1 = Source(1, VIDEO) val s2 = Source(2, VIDEO) val s3 = Source(3, VIDEO) val s4 = Source(4, VIDEO) val s5 = Source(5, VIDEO) val s6 = Source(6, VIDEO) val s7 = Source(7, AUDIO) val sim = SsrcGroup(SsrcGroupSemantics.Sim, listOf(1, 2, 3)) val fid1 = SsrcGroup(SsrcGroupSemantics.Fid, listOf(1, 4)) val fid2 = SsrcGroup(SsrcGroupSemantics.Fid, listOf(2, 5)) val fid3 = SsrcGroup(SsrcGroupSemantics.Fid, listOf(3, 6)) val sourceSet = EndpointSourceSet( setOf(s1, s2, s3, s4, s5, s6, s7), setOf(sim, fid1, fid2, fid3) ) val e2s1 = Source(11, VIDEO) val e2s2 = Source(12, VIDEO) val e2s3 = Source(13, VIDEO) val e2s4 = Source(14, VIDEO) val e2s5 = Source(15, VIDEO) val e2s6 = Source(16, VIDEO) val e2s7 = Source(17, AUDIO) val e2sim = SsrcGroup(SsrcGroupSemantics.Sim, listOf(11, 12, 13)) val e2fid1 = SsrcGroup(SsrcGroupSemantics.Fid, listOf(11, 14)) val e2fid2 = SsrcGroup(SsrcGroupSemantics.Fid, listOf(12, 15)) val e2fid3 = SsrcGroup(SsrcGroupSemantics.Fid, listOf(13, 16)) val e2sourceSet = EndpointSourceSet( setOf(e2s1, e2s2, e2s3, e2s4, e2s5, e2s6, e2s7), setOf(e2sim, e2fid1, e2fid2, e2fid3) )
apache-2.0
7b16a6ce45b305244dcae87ec9dc10db
39.785276
108
0.612515
4.1602
false
false
false
false
JavaProphet/JASM
src/main/java/com/protryon/jasm/JarFile.kt
1
2417
package com.protryon.jasm import java.io.* import java.net.URL import java.util.LinkedHashMap import java.util.Scanner import java.util.jar.JarOutputStream import java.util.zip.ZipEntry import java.util.zip.ZipInputStream class JarFile @Throws(IOException::class) constructor(val source: URL) { val resources = LinkedHashMap<String, ByteArray>() val mainClass: String? get() { if (!resources.containsKey("META-INF/MANIFEST.MF")) return null val input = Scanner(String(resources["META-INF/MANIFEST.MF"]!!)) while (input.hasNextLine()) { val line = input.nextLine().trim { it <= ' ' } if (line.startsWith("Main-Class:")) { input.close() return line.substring(11).trim { it <= ' ' } } } input.close() return null } @Throws(IOException::class) constructor(f: File) : this(f.toURI().toURL()) init { read(this.source.openStream()) } // public ReflectionClassLoader getReflector() { // ReflectionClassLoader rcl = new ReflectionClassLoader(); // rcl.setPreloadCache(false); // rcl.loadJarFile(this); // rcl.flushToMemory(); // return rcl; // } override fun toString(): String { return source.toString() } @Throws(IOException::class) fun read(`in`: InputStream) { val jarIn = ZipInputStream(`in`)// not jar, so we can read manifest directly var entry: ZipEntry? this.resources.clear() while (true) { entry = jarIn.nextEntry if (entry == null) { break } val out = ByteArrayOutputStream() val buf = ByteArray(1024) var i = 1 while (i > 0) { i = jarIn.read(buf, 0, i) if (i > 0) { out.write(buf, 0, i) } } this.resources[entry.name] = out.toByteArray() } jarIn.close() } @Throws(IOException::class) fun write(out: OutputStream) { val jarOut = JarOutputStream(out) for (s in resources.keys) { jarOut.putNextEntry(ZipEntry(s)) jarOut.write(resources[s]) jarOut.closeEntry() } jarOut.close() } }
gpl-3.0
d70e006786ef71c06a456afbca273654
27.77381
84
0.532478
4.300712
false
false
false
false
rmnn/compiler
src/main/kotlin/ru/dageev/compiler/parser/provider/TypeProvider.kt
1
1029
package ru.dageev.compiler.parser.provider import ru.dageev.compiler.domain.type.ClassType import ru.dageev.compiler.domain.type.PrimitiveType import ru.dageev.compiler.domain.type.Type import ru.dageev.compiler.grammar.ElaginParser import ru.dageev.compiler.parser.CompilationException /** * Created by dageev * on 15-May-16. */ class TypeProvider(val availableClasses: List<ClassType>) { fun getType(typeContext: ElaginParser.TypeContext?): Type { return if (typeContext == null) { PrimitiveType.VOID } else { getByName(typeContext.text) } } private fun getByName(text: String): Type { return if (primitiveType(text)) { PrimitiveType.getByName(text) } else { availableClasses.find { it.getTypeName() == text } ?: throw CompilationException("Class $text not exists") } } private fun primitiveType(text: String): Boolean { return PrimitiveType.values().any { it.getTypeName() == text } } }
apache-2.0
77e83c50a19a453ba6ca1bd7f88e4ba1
27.583333
118
0.670554
4.234568
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/model/analyzer/PurchaseFinished.kt
1
1869
/* * Twittnuker - Twitter client for Android * * Copyright (C) 2013-2017 vanita5 <mail@vanit.as> * * This program incorporates a modified version of Twidere. * Copyright (C) 2012-2017 Mariotaku Lee <mariotaku.lee@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package de.vanita5.twittnuker.model.analyzer import android.content.Intent import de.vanita5.twittnuker.activity.premium.AbsExtraFeaturePurchaseActivity.Companion.EXTRA_PURCHASE_RESULT import de.vanita5.twittnuker.model.premium.PurchaseResult import de.vanita5.twittnuker.util.Analyzer data class PurchaseFinished(val productName: String) : Analyzer.Event { override val name: String = "PurchaseFinished" override var accountType: String? = null var price: Double = Double.NaN var currency: String? = null companion object { const val NAME_EXTRA_FEATURES = "Enhanced Features" fun create(data: Intent): PurchaseFinished { val purchaseResult: PurchaseResult = data.getParcelableExtra(EXTRA_PURCHASE_RESULT) val result = PurchaseFinished(purchaseResult.feature) result.price = purchaseResult.price result.currency = purchaseResult.currency return result } } }
gpl-3.0
8c812e2a267e6617da3760cfba34ce87
37.958333
109
0.729267
4.267123
false
false
false
false
stripe/stripe-android
payments-core/src/test/java/com/stripe/android/model/parsers/SourceCardDataJsonParserTest.kt
1
1764
package com.stripe.android.model.parsers import com.google.common.truth.Truth.assertThat import com.stripe.android.model.CardBrand import com.stripe.android.model.CardFunding import com.stripe.android.model.SourceFixtures import com.stripe.android.model.SourceTypeModel import com.stripe.android.model.TokenizationMethod import kotlin.test.Test class SourceCardDataJsonParserTest { @Test fun `should parse correctly`() { assertThat(CARD_DATA) .isEqualTo( SourceTypeModel.Card( brand = CardBrand.Visa, funding = CardFunding.Credit, last4 = "4242", expiryMonth = 12, expiryYear = 2050, country = "US", addressLine1Check = "unchecked", addressZipCheck = "unchecked", cvcCheck = "unchecked", dynamicLast4 = "4242", threeDSecureStatus = SourceTypeModel.Card.ThreeDSecureStatus.Optional, tokenizationMethod = TokenizationMethod.ApplePay ) ) } @Test fun `should implement equals correctly`() { assertThat(PARSER.parse(SourceFixtures.SOURCE_CARD_DATA_WITH_APPLE_PAY_JSON)) .isEqualTo(CARD_DATA) } @Test fun `should implement hashCode correctly`() { assertThat( PARSER.parse(SourceFixtures.SOURCE_CARD_DATA_WITH_APPLE_PAY_JSON).hashCode() ).isEqualTo(CARD_DATA.hashCode()) } private companion object { private val PARSER = SourceCardDataJsonParser() private val CARD_DATA = PARSER.parse(SourceFixtures.SOURCE_CARD_DATA_WITH_APPLE_PAY_JSON) } }
mit
836f93f9b9f46f66bd8407691fd8e33d
33.588235
90
0.60771
4.666667
false
true
false
false
stripe/stripe-android
stripecardscan/src/main/java/com/stripe/android/stripecardscan/cardscan/CardScanFragment.kt
1
12303
package com.stripe.android.stripecardscan.cardscan import android.annotation.SuppressLint import android.content.res.Resources import android.graphics.Bitmap import android.graphics.PointF import android.os.Bundle import android.util.Size import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.core.os.bundleOf import androidx.core.view.updateMargins import androidx.fragment.app.setFragmentResult import com.stripe.android.camera.CameraPreviewImage import com.stripe.android.camera.framework.Stats import com.stripe.android.camera.scanui.ScanErrorListener import com.stripe.android.camera.scanui.SimpleScanStateful import com.stripe.android.camera.scanui.ViewFinderBackground import com.stripe.android.camera.scanui.util.asRect import com.stripe.android.camera.scanui.util.startAnimation import com.stripe.android.stripecardscan.R import com.stripe.android.stripecardscan.cardscan.exception.InvalidStripePublishableKeyException import com.stripe.android.stripecardscan.cardscan.exception.UnknownScanException import com.stripe.android.stripecardscan.cardscan.result.MainLoopAggregator import com.stripe.android.stripecardscan.cardscan.result.MainLoopState import com.stripe.android.stripecardscan.databinding.FragmentCardscanBinding import com.stripe.android.stripecardscan.framework.api.dto.ScanStatistics import com.stripe.android.stripecardscan.framework.api.uploadScanStatsOCR import com.stripe.android.stripecardscan.framework.util.AppDetails import com.stripe.android.stripecardscan.framework.util.Device import com.stripe.android.stripecardscan.framework.util.ScanConfig import com.stripe.android.stripecardscan.payment.card.ScannedCard import com.stripe.android.stripecardscan.scanui.CancellationReason import com.stripe.android.stripecardscan.scanui.ScanFragment import com.stripe.android.stripecardscan.scanui.util.getColorByRes import com.stripe.android.stripecardscan.scanui.util.getFloatResource import com.stripe.android.stripecardscan.scanui.util.setVisible import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.launch import java.util.concurrent.atomic.AtomicBoolean import kotlin.math.min import kotlin.math.roundToInt private val MINIMUM_RESOLUTION = Size(1067, 600) // minimum size of OCR const val CARD_SCAN_FRAGMENT_REQUEST_KEY = "CardScanRequestKey" const val CARD_SCAN_FRAGMENT_BUNDLE_KEY = "CardScanBundleKey" const val CARD_SCAN_FRAGMENT_PARAMS_KEY = "CardScanParamsKey" class CardScanFragment : ScanFragment(), SimpleScanStateful<CardScanState> { override val minimumAnalysisResolution = MINIMUM_RESOLUTION private lateinit var viewBinding: FragmentCardscanBinding override val instructionsText: TextView by lazy { viewBinding.instructions } override val previewFrame: ViewGroup by lazy { viewBinding.cameraView.previewFrame } private val viewFinderWindow: View by lazy { viewBinding.cameraView.viewFinderWindowView } private val viewFinderBorder: ImageView by lazy { viewBinding.cameraView.viewFinderBorderView } private val viewFinderBackground: ViewFinderBackground by lazy { viewBinding.cameraView.viewFinderBackgroundView } private val params: CardScanSheetParams by lazy { arguments?.getParcelable(CARD_SCAN_FRAGMENT_PARAMS_KEY) ?: CardScanSheetParams("") } private val hasPreviousValidResult = AtomicBoolean(false) override var scanState: CardScanState? = CardScanState.NotFound override var scanStatePrevious: CardScanState? = null override val scanErrorListener: ScanErrorListener = ScanErrorListener() /** * The listener which handles results from the scan. */ override val resultListener: CardScanResultListener = object : CardScanResultListener { override fun cardScanComplete(card: ScannedCard) { setFragmentResult( CARD_SCAN_FRAGMENT_REQUEST_KEY, bundleOf( CARD_SCAN_FRAGMENT_BUNDLE_KEY to CardScanSheetResult.Completed( ScannedCard( pan = card.pan ) ) ) ) closeScanner() } override fun userCanceled(reason: CancellationReason) { setFragmentResult( CARD_SCAN_FRAGMENT_REQUEST_KEY, bundleOf( CARD_SCAN_FRAGMENT_BUNDLE_KEY to CardScanSheetResult.Canceled(reason) ) ) } override fun failed(cause: Throwable?) { setFragmentResult( CARD_SCAN_FRAGMENT_REQUEST_KEY, bundleOf( CARD_SCAN_FRAGMENT_BUNDLE_KEY to CardScanSheetResult.Failed( cause ?: UnknownScanException() ) ) ) } } /** * The flow used to scan an item. */ private val scanFlow: CardScanFlow by lazy { object : CardScanFlow(scanErrorListener) { /** * A final result was received from the aggregator. Set the result from this activity. */ override suspend fun onResult( result: MainLoopAggregator.FinalResult ) { launch(Dispatchers.Main) { changeScanState(CardScanState.Correct) activity?.let { cameraAdapter.unbindFromLifecycle(it) } resultListener.cardScanComplete(ScannedCard(result.pan)) scanStat.trackResult("scan_complete") closeScanner() }.let { } } /** * An interim result was received from the result aggregator. */ override suspend fun onInterimResult( result: MainLoopAggregator.InterimResult ) = launch(Dispatchers.Main) { if ( result.state is MainLoopState.OcrFound && !hasPreviousValidResult.getAndSet(true) ) { scanStat.trackResult("ocr_pan_observed") } when (result.state) { is MainLoopState.Initial -> changeScanState(CardScanState.NotFound) is MainLoopState.OcrFound -> changeScanState(CardScanState.Found) is MainLoopState.Finished -> changeScanState(CardScanState.Correct) } }.let { } override suspend fun onReset() = launch(Dispatchers.Main) { changeScanState(CardScanState.NotFound) }.let { } } } @SuppressLint("ClickableViewAccessibility") override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { viewBinding = FragmentCardscanBinding.inflate(inflater, container, false) setupViewFinderConstraints() viewBinding.closeButton.setOnClickListener { userClosedScanner() } viewBinding.torchButton.setOnClickListener { toggleFlashlight() } viewBinding.swapCameraButton.setOnClickListener { toggleCamera() } viewFinderBorder.setOnTouchListener { _, e -> setFocus( PointF( e.x + viewFinderWindow.left, e.y + viewFinderWindow.top ) ) true } displayState(requireNotNull(scanState), scanStatePrevious) return viewBinding.root } override fun onStart() { super.onStart() if (!ensureValidParams()) { return } } override fun onResume() { super.onResume() scanState = CardScanState.NotFound } override fun onDestroy() { scanFlow.cancelFlow() super.onDestroy() } /** * Set up viewFinderWindowView and viewFinderBorderView centered with predefined margins */ private fun setupViewFinderConstraints() { val screenSize = Resources.getSystem().displayMetrics.let { Size(it.widthPixels, it.heightPixels) } val viewFinderMargin = ( min(screenSize.width, screenSize.height) * (context?.getFloatResource(R.dimen.stripeViewFinderMargin) ?: 0F) ).roundToInt() listOf(viewFinderWindow, viewFinderBorder).forEach { view -> (view.layoutParams as ViewGroup.MarginLayoutParams) .updateMargins( viewFinderMargin, viewFinderMargin, viewFinderMargin, viewFinderMargin ) } viewFinderBackground.setViewFinderRect(viewFinderWindow.asRect()) } override fun onFlashSupported(supported: Boolean) { viewBinding.torchButton.setVisible(supported) } override fun onSupportsMultipleCameras(supported: Boolean) { viewBinding.swapCameraButton.setVisible(supported) } /** * Prepare to start the camera. Once the camera is ready, [onCameraReady] must be called. */ override fun prepareCamera(onCameraReady: () -> Unit) { previewFrame.post { viewFinderBackground .setViewFinderRect(viewFinderWindow.asRect()) onCameraReady() } } /** * Once the camera stream is available, start processing images. */ override suspend fun onCameraStreamAvailable(cameraStream: Flow<CameraPreviewImage<Bitmap>>) { context?.let { scanFlow.startFlow( context = it, imageStream = cameraStream, viewFinder = viewFinderWindow.asRect(), lifecycleOwner = this, coroutineScope = this, parameters = null ) } } /** * Called when the flashlight state has changed. */ override fun onFlashlightStateChanged(flashlightOn: Boolean) {} private fun ensureValidParams() = when { params.stripePublishableKey.isEmpty() -> { scanFailure(InvalidStripePublishableKeyException("Missing publishable key")) false } else -> true } override fun displayState(newState: CardScanState, previousState: CardScanState?) { when (newState) { is CardScanState.NotFound, CardScanState.Found -> { context?.let { viewFinderBackground .setBackgroundColor( it.getColorByRes(R.color.stripeNotFoundBackground) ) } viewFinderWindow .setBackgroundResource(R.drawable.stripe_card_background_not_found) viewFinderBorder .startAnimation(R.drawable.stripe_paymentsheet_card_border_not_found) } is CardScanState.Correct -> { context?.let { viewFinderBackground .setBackgroundColor( it.getColorByRes(R.color.stripeCorrectBackground) ) } viewFinderWindow .setBackgroundResource(R.drawable.stripe_card_background_correct) viewFinderBorder.startAnimation(R.drawable.stripe_card_border_correct) } } } override fun closeScanner() { uploadScanStatsOCR( stripePublishableKey = params.stripePublishableKey, instanceId = Stats.instanceId, scanId = Stats.scanId, device = Device.fromContext(context), appDetails = AppDetails.fromContext(context), scanStatistics = ScanStatistics.fromStats(), scanConfig = ScanConfig(0) ) scanFlow.resetFlow() super.closeScanner() } }
mit
8671b37a305bf353e0e4f9388d4964af
35.185294
98
0.627408
5.314471
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/focus/ComposeViewKeyEventInteropTest.kt
3
5897
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.focus import android.view.KeyEvent as AndroidKeyEvent import android.view.KeyEvent.ACTION_DOWN as KeyDown import androidx.activity.compose.setContent import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.text.BasicText import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.input.key.Key.Companion.Back import androidx.compose.ui.input.key.Key.Companion.DirectionRight import androidx.compose.ui.input.key.nativeKeyCode import androidx.compose.ui.test.TestActivity import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.MediumTest import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @MediumTest @RunWith(AndroidJUnit4::class) @OptIn(ExperimentalComposeUiApi::class) class ComposeViewKeyEventInteropTest { @get:Rule val rule = createAndroidComposeRule<TestActivity>() @Test fun composeView_doesNotConsumesKeyEvent_ifTheContentIsNotFocusable() { // Arrange. rule.activityRule.scenario.onActivity { activity -> activity.setContent { BasicText("text") } } // Act. val keyEvent = AndroidKeyEvent(KeyDown, DirectionRight.nativeKeyCode) rule.activity.dispatchKeyEvent(keyEvent) // Assert. assertThat(rule.activity.receivedKeyEvent).isEqualTo(keyEvent) } @Test fun composeView_doesNotConsumesKeyEvent_ifFocusIsNotMoved() { // Arrange. val focusRequester = FocusRequester() rule.activityRule.scenario.onActivity { activity -> activity.setContent { BasicText( text = "text", modifier = Modifier .focusRequester(focusRequester) .focusable() ) } } rule.runOnIdle { focusRequester.requestFocus() } // Act. val keyEvent = AndroidKeyEvent(KeyDown, DirectionRight.nativeKeyCode) rule.activity.dispatchKeyEvent(keyEvent) // Assert. assertThat(rule.activity.receivedKeyEvent).isEqualTo(keyEvent) } @Test @OptIn(ExperimentalComposeUiApi::class) fun composeView_consumesKeyEvent_ifFocusIsMoved() { // Arrange. val (item1, item2) = FocusRequester.createRefs() rule.activityRule.scenario.onActivity { activity -> activity.setContent { Row { BasicText( text = "Item 1", modifier = Modifier .focusRequester(item1) .focusProperties { right = item2 } .focusable() ) BasicText( text = "Item 2", modifier = Modifier .focusRequester(item2) .focusable() ) } } } rule.runOnIdle { item1.requestFocus() } // Act. val keyEvent = AndroidKeyEvent(KeyDown, DirectionRight.nativeKeyCode) rule.activity.dispatchKeyEvent(keyEvent) // Assert. assertThat(rule.activity.receivedKeyEvent).isNull() } @Test fun composeView_doesNotConsumeBackKeyEvent_ifFocusMovesToRoot() { // Arrange. val (item1, item2) = FocusRequester.createRefs() rule.activityRule.scenario.onActivity { activity -> activity.setContent { BasicText( text = "Item 1", modifier = Modifier .focusRequester(item1) .focusProperties { down = item2 } .focusable() ) } } rule.runOnIdle { item1.requestFocus() } // Act. val keyEvent = AndroidKeyEvent(KeyDown, Back.nativeKeyCode) rule.activity.dispatchKeyEvent(keyEvent) // Assert. assertThat(rule.activity.receivedKeyEvent).isEqualTo(keyEvent) } @Test fun composeView_consumesBackKeyEvent_ifFocusMovesToNonRoot() { // Arrange. val (item1, item2) = FocusRequester.createRefs() rule.activityRule.scenario.onActivity { activity -> activity.setContent { Box(Modifier.focusable()) { BasicText( text = "Item 1", modifier = Modifier .focusRequester(item1) .focusProperties { down = item2 } .focusable() ) } } } rule.runOnIdle { item1.requestFocus() } // Act. val keyEvent = AndroidKeyEvent(KeyDown, Back.nativeKeyCode) rule.activity.dispatchKeyEvent(keyEvent) // Assert. assertThat(rule.activity.receivedKeyEvent).isNull() } }
apache-2.0
94bbd7d43cc2d5cf57f1f2d2e7f0f88f
33.086705
77
0.602679
5.15923
false
true
false
false
AndroidX/androidx
glance/glance/src/test/kotlin/androidx/glance/layout/PaddingTest.kt
3
9696
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.glance.layout import android.content.res.Resources import android.util.DisplayMetrics import androidx.compose.ui.unit.dp import androidx.glance.GlanceModifier import androidx.glance.findModifier import com.google.common.truth.Truth.assertThat import org.mockito.kotlin.doReturn import org.mockito.kotlin.mock import org.junit.Test class PaddingTest { private val mockDisplayMetrics = DisplayMetrics().also { it.density = density } private val mockResources = mock<Resources>() { on { displayMetrics } doReturn mockDisplayMetrics on { getDimension(dimensionRes1) } doReturn dimension1InDp * density on { getDimension(dimensionRes2) } doReturn dimension2InDp * density } @Test fun buildPadding() { val modifiers = GlanceModifier.padding( start = 1.dp, top = 2.dp, end = 3.dp, bottom = 4.dp ) // Find the padding modifier... val paddingModifier = checkNotNull(modifiers.findModifier<PaddingModifier>()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(1.dp), top = PaddingDimension(2.dp), end = PaddingDimension(3.dp), bottom = PaddingDimension(4.dp), ) ) } @Test fun buildVerticalHorizontalPadding() { val modifiers = GlanceModifier.padding(vertical = 2.dp, horizontal = 4.dp) val paddingModifier = checkNotNull(modifiers.findModifier<PaddingModifier>()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(4.dp), top = PaddingDimension(2.dp), end = PaddingDimension(4.dp), bottom = PaddingDimension(2.dp), ) ) } @Test fun buildAllPadding() { val modifiers = GlanceModifier.padding(all = 5.dp) val paddingModifier = checkNotNull(modifiers.findModifier<PaddingModifier>()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(5.dp), top = PaddingDimension(5.dp), end = PaddingDimension(5.dp), bottom = PaddingDimension(5.dp), ) ) } @Test fun buildAbsolutePadding() { val modifiers = GlanceModifier.absolutePadding( left = 1.dp, top = 2.dp, right = 3.dp, bottom = 4.dp, ) val paddingModifier = checkNotNull(modifiers.findModifier<PaddingModifier>()) assertThat(paddingModifier).isEqualTo( PaddingModifier( left = PaddingDimension(1.dp), top = PaddingDimension(2.dp), right = PaddingDimension(3.dp), bottom = PaddingDimension(4.dp), ) ) } @Test fun extractPadding_shouldReturnNull() { val modifiers = GlanceModifier.then(object : GlanceModifier.Element {}) assertThat(modifiers.collectPadding()).isNull() assertThat(modifiers.collectPaddingInDp(mockResources)).isNull() } @Test fun mergePadding_noOrientation() { val modifiers = GlanceModifier.padding(horizontal = 15.dp).padding(vertical = dimensionRes1) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(15.dp), end = PaddingDimension(15.dp), top = PaddingDimension(dimensionRes1), bottom = PaddingDimension(dimensionRes1), ) ) val paddingInDp = checkNotNull(modifiers.collectPaddingInDp(mockResources)) assertThat(paddingInDp).isEqualTo( PaddingInDp( start = 15.dp, end = 15.dp, top = dimension1InDp.dp, bottom = dimension1InDp.dp, ) ) } @Test fun mergePadding_resetWithAll() { val modifiers = GlanceModifier.padding(horizontal = 12.dp).padding(all = dimensionRes2) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(dp = 12.dp, resourceIds = listOf(dimensionRes2)), end = PaddingDimension(dp = 12.dp, resourceIds = listOf(dimensionRes2)), top = PaddingDimension(dimensionRes2), bottom = PaddingDimension(dimensionRes2), ) ) val paddingInDp = checkNotNull(modifiers.collectPaddingInDp(mockResources)) assertThat(paddingInDp).isEqualTo( PaddingInDp( start = (12 + dimension2InDp).dp, end = (12 + dimension2InDp).dp, top = dimension2InDp.dp, bottom = dimension2InDp.dp, ) ) } @Test fun mergePadding_withRelativeOrientation() { val modifiers = GlanceModifier.padding(start = 15.dp, end = 12.dp, top = 20.dp) .padding(end = dimensionRes1) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(15.dp), end = PaddingDimension(dp = 12.dp, resourceIds = listOf(dimensionRes1)), top = PaddingDimension(20.dp), ) ) } @Test fun mergePadding_withAbsoluteOrientation() { val modifiers = GlanceModifier.absolutePadding(left = 15.dp, right = 12.dp) .absolutePadding(left = dimensionRes1, bottom = dimensionRes2) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( left = PaddingDimension(dp = 15.dp, resourceIds = listOf(dimensionRes1)), right = PaddingDimension(12.dp), bottom = PaddingDimension(dimensionRes2), ) ) } @Test fun mergePadding_setOrientationToRelative() { val modifiers = GlanceModifier.absolutePadding(left = 10.dp, right = 10.dp) .padding(start = dimensionRes1, end = dimensionRes2) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( start = PaddingDimension(dimensionRes1), end = PaddingDimension(dimensionRes2), left = PaddingDimension(10.dp), right = PaddingDimension(10.dp), ) ) } @Test fun mergePadding_setOrientationToAbsolute() { val modifiers = GlanceModifier.padding(start = dimensionRes1, end = dimensionRes2) .absolutePadding(left = 10.dp, right = 12.dp) val paddingModifier = checkNotNull(modifiers.collectPadding()) assertThat(paddingModifier).isEqualTo( PaddingModifier( left = PaddingDimension(10.dp), right = PaddingDimension(12.dp), start = PaddingDimension(dimensionRes1), end = PaddingDimension(dimensionRes2),) ) } @Test fun toRelative() { val paddingInDp = PaddingInDp( left = 1.dp, right = 2.dp, start = 10.dp, end = 20.dp, top = 50.dp, bottom = 100.dp, ) assertThat(paddingInDp.toRelative(isRtl = true)).isEqualTo( PaddingInDp( start = 12.dp, end = 21.dp, top = 50.dp, bottom = 100.dp, ) ) assertThat(paddingInDp.toRelative(isRtl = false)).isEqualTo( PaddingInDp( start = 11.dp, end = 22.dp, top = 50.dp, bottom = 100.dp, ) ) } @Test fun toAbsolute() { val paddingInDp = PaddingInDp( left = 1.dp, right = 2.dp, start = 10.dp, end = 20.dp, top = 50.dp, bottom = 100.dp, ) assertThat(paddingInDp.toAbsolute(isRtl = true)).isEqualTo( PaddingInDp( left = 21.dp, right = 12.dp, top = 50.dp, bottom = 100.dp, ) ) assertThat(paddingInDp.toAbsolute(isRtl = false)).isEqualTo( PaddingInDp( left = 11.dp, right = 22.dp, top = 50.dp, bottom = 100.dp, ) ) } private companion object { const val dimensionRes1 = 123 const val dimensionRes2 = 321 const val density = 2f const val dimension1InDp = 100f const val dimension2InDp = 200f } }
apache-2.0
eaaaeb1bdf14abdbb69e955259ad39b1
30.176849
100
0.575289
4.693127
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/ide/utils/checkMatch/Constructor.kt
3
4800
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.utils.checkMatch import org.rust.lang.core.psi.RsEnumItem import org.rust.lang.core.psi.RsEnumVariant import org.rust.lang.core.psi.RsStructItem import org.rust.lang.core.psi.ext.RsFieldsOwner import org.rust.lang.core.psi.ext.fieldTypes import org.rust.lang.core.psi.ext.size import org.rust.lang.core.psi.ext.variants import org.rust.lang.core.types.infer.substitute import org.rust.lang.core.types.ty.* import org.rust.lang.utils.evaluation.ConstExpr.Value sealed class Constructor { /** The constructor of all patterns that don't vary by constructor, e.g. struct patterns and fixed-length arrays */ object Single : Constructor() { override fun coveredByRange(from: Value<*>, to: Value<*>, included: Boolean): Boolean = true } /** Enum variants */ data class Variant(val variant: RsEnumVariant) : Constructor() /** Literal values */ data class ConstantValue(val value: Value<*>) : Constructor() { override fun coveredByRange(from: Value<*>, to: Value<*>, included: Boolean): Boolean = if (included) { value >= from && value <= to } else { value >= from && value < to } } /** Ranges of literal values (`2..=5` and `2..5`) */ data class ConstantRange(val start: Value<*>, val end: Value<*>, val includeEnd: Boolean = false) : Constructor() { override fun coveredByRange(from: Value<*>, to: Value<*>, included: Boolean): Boolean = if (includeEnd) { ((end < to) || (included && to == end)) && (start >= from) } else { ((end < to) || (!included && to == end)) && (start >= from) } } /** Array patterns of length n */ data class Slice(val size: Int) : Constructor() fun arity(type: Ty): Int = when (type) { is TyTuple -> type.types.size is TySlice, is TyArray -> when (this) { is Slice -> size is ConstantValue -> 0 else -> throw CheckMatchException("Incompatible constructor") } is TyReference -> 1 is TyAdt -> when { type.item is RsStructItem -> type.item.size type.item is RsEnumItem && this is Variant -> variant.size else -> throw CheckMatchException("Incompatible constructor") } else -> 0 } open fun coveredByRange(from: Value<*>, to: Value<*>, included: Boolean): Boolean = false fun subTypes(type: Ty): List<Ty> = when (type) { is TyTuple -> type.types is TySlice, is TyArray -> when (this) { is Slice -> (0 until this.size).map { type } is ConstantValue -> emptyList() else -> throw CheckMatchException("Incompatible constructor") } is TyReference -> listOf(type.referenced) is TyAdt -> when { this is Single && type.item is RsFieldsOwner -> { type.item.fieldTypes.map { it.substitute(type.typeParameterValues) } } this is Variant -> { variant.fieldTypes.map { it.substitute(type.typeParameterValues) } } else -> emptyList() } else -> emptyList() } companion object { private fun allConstructorsLazy(ty: Ty): Sequence<Constructor> = when { ty is TyBool -> sequenceOf(true, false).map { ConstantValue(Value.Bool(it)) } ty is TyAdt && ty.item is RsEnumItem -> ty.item.variants.asSequence().map { Variant(it) } // TODO: TyInteger, TyChar (see `all_constructors` at `https://github.com/rust-lang/rust/blob/master/src/librustc_mir/hair/pattern/_match.rs`) ty is TyArray && ty.size != null -> TODO() ty is TyArray || ty is TySlice -> TODO() else -> sequenceOf(Single) } fun isInhabited(ty: Ty): Boolean = allConstructorsLazy(ty).any() fun allConstructors(ty: Ty): List<Constructor> = allConstructorsLazy(ty).toList() } } private operator fun Value<*>.compareTo(other: Value<*>): Int { return when { this is Value.Bool && other is Value.Bool -> value.compareTo(other.value) this is Value.Integer && other is Value.Integer -> value.compareTo(other.value) this is Value.Float && other is Value.Float -> value.compareTo(other.value) this is Value.Str && other is Value.Str -> value.compareTo(other.value) this is Value.Char && other is Value.Char -> value.compareTo(other.value) else -> throw CheckMatchException("Comparison of incompatible types: $javaClass and ${other.javaClass}") } }
mit
3110cc6b088e20996ac14d4b3dfdc85a
36.209302
158
0.600417
4.18483
false
false
false
false
androidx/androidx
testutils/testutils-common/src/test/java/androidx/testutils/ParameterizedHelperTest.kt
3
4513
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.testutils import com.google.common.truth.Truth.assertThat import org.junit.Test class ParameterizedHelperTest { @Test fun testIncrement() { val number = listOf(RadixDigit(2, 0), RadixDigit(3, 0)) assertThat(::increment.invoke(number, 1)).isEqualTo( listOf(RadixDigit(2, 0), RadixDigit(3, 1)) ) assertThat(::increment.invoke(number, 2)).isEqualTo( listOf(RadixDigit(2, 0), RadixDigit(3, 2)) ) assertThat(::increment.invoke(number, 3)).isEqualTo( listOf(RadixDigit(2, 1), RadixDigit(3, 0)) ) assertThat(::increment.invoke(number, 4)).isEqualTo( listOf(RadixDigit(2, 1), RadixDigit(3, 1)) ) assertThat(::increment.invoke(number, 5)).isEqualTo( listOf(RadixDigit(2, 1), RadixDigit(3, 2)) ) assertThat(::increment.invoke(number, 6)).isEqualTo( listOf(RadixDigit(2, 0), RadixDigit(3, 0)) ) assertThat(::increment.invoke(number, 7)).isEqualTo( listOf(RadixDigit(2, 0), RadixDigit(3, 1)) ) } @Test fun testProduct() { assertThat(listOf<Int>().product()).isEqualTo(1) assertThat(listOf(0).product()).isEqualTo(0) assertThat(listOf(2).product()).isEqualTo(2) assertThat(listOf(2, 3).product()).isEqualTo(6) } @Test fun testEnumerations() { assertThat(generateAllEnumerations()).isEmpty() // Comparing List of Arrays doesn't work(https://github.com/google/truth/issues/928), so // we're mapping it to List of Lists assertThat( generateAllEnumerations(listOf(false)).map { it.toList() }).isEqualTo( listOf( listOf<Any>(false) ) ) assertThat( generateAllEnumerations(listOf(false, true)).map { it.toList() }).isEqualTo( listOf( listOf<Any>(false), listOf<Any>(true) ) ) assertThat(generateAllEnumerations(listOf(false, true), listOf())).isEmpty() assertThat( generateAllEnumerations( listOf(false, true), listOf(false, true) ).map { it.toList() } ).isEqualTo( listOf( listOf(false, false), listOf(false, true), listOf(true, false), listOf(true, true) ) ) assertThat( generateAllEnumerations( listOf(false, true), (0..2).toList(), listOf("low", "hi") ).map { it.toList() } ).isEqualTo( listOf( listOf(false, 0, "low"), listOf(false, 0, "hi"), listOf(false, 1, "low"), listOf(false, 1, "hi"), listOf(false, 2, "low"), listOf(false, 2, "hi"), listOf(true, 0, "low"), listOf(true, 0, "hi"), listOf(true, 1, "low"), listOf(true, 1, "hi"), listOf(true, 2, "low"), listOf(true, 2, "hi") ) ) } // `::f.invoke(0, 3)` is equivalent to `f(f(f(0)))` private fun <T> ((T) -> T).invoke(argument: T, repeat: Int): T { var result = argument for (i in 0 until repeat) { result = this(result) } return result } @Test fun testInvoke() { val addOne = { i: Int -> i + 1 } assertThat(addOne.invoke(42, 0)).isEqualTo(42) assertThat(addOne.invoke(42, 1)).isEqualTo(addOne(42)) assertThat(addOne.invoke(42, 2)).isEqualTo(addOne(addOne(42))) val appendA = { str: String -> str + "a" } assertThat(appendA.invoke("a", 2)).isEqualTo(appendA(appendA("a"))) } }
apache-2.0
a8e304a2eab7282ec5bc78bdf550f614
32.679104
96
0.542876
4.033065
false
true
false
false
jrgonzalezg/OpenLibraryApp
app/src/main/kotlin/com/github/jrgonzalezg/openlibrary/features/books/data/api/OpenLibraryService.kt
1
1360
/* * Copyright (C) 2017 Juan Ramón González González (https://github.com/jrgonzalezg) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.jrgonzalezg.openlibrary.features.books.data.api import com.github.jrgonzalezg.openlibrary.features.books.domain.BookSummary import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Path object Endpoints { const val BOOK_QUERY = "{key}.json" const val BOOK_SUMMARIES_QUERY = "/query.json?type=/type/edition&authors=/authors/OL2162284A&title=&covers=" } interface OpenLibraryService { @GET(Endpoints.BOOK_QUERY) @Headers("Accept: application/json") fun getBook(@Path("key") key: String): Call<BookResponse> @GET(Endpoints.BOOK_SUMMARIES_QUERY) @Headers("Accept: application/json") fun getBookSummaries(): Call<List<BookSummary>> }
apache-2.0
8d49ae5855311e3be7b3856eab879a2a
34.710526
110
0.761238
3.790503
false
false
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui/src/org/jetbrains/kotlin/ui/commands/findReferences/querySpecifications.kt
1
2905
package org.jetbrains.kotlin.ui.commands.findReferences import org.eclipse.jdt.core.search.IJavaSearchConstants import org.eclipse.jdt.ui.search.PatternQuerySpecification import org.eclipse.jdt.core.search.IJavaSearchScope import org.jetbrains.kotlin.psi.KtElement import org.eclipse.jdt.core.IJavaElement import org.eclipse.core.runtime.IPath import org.eclipse.jdt.ui.search.ElementQuerySpecification import org.eclipse.core.resources.ResourcesPlugin import org.eclipse.core.resources.IFile import org.jetbrains.kotlin.descriptors.SourceElement interface KotlinAndJavaSearchable { val sourceElements: List<SourceElement> } interface KotlinScoped { val searchScope: List<IFile> } class KotlinJavaQuerySpecification( override val sourceElements: List<SourceElement>, limitTo: Int, searchScope: IJavaSearchScope, description: String) : KotlinDummyQuerySpecification(searchScope, description, limitTo), KotlinAndJavaSearchable class KotlinScopedQuerySpecification( override val sourceElements: List<SourceElement>, override val searchScope: List<IFile>, limitTo: Int, description: String) : KotlinDummyQuerySpecification(EmptyJavaSearchScope, description, limitTo), KotlinAndJavaSearchable, KotlinScoped class KotlinOnlyQuerySpecification( val kotlinElement: KtElement, override val searchScope: List<IFile>, limitTo: Int, description: String) : KotlinDummyQuerySpecification(EmptyJavaSearchScope, description, limitTo), KotlinScoped // After passing this query specification to java, it will try to find some usages and to ensure that nothing will found // before KotlinQueryParticipant here is using dummy element '------------' abstract class KotlinDummyQuerySpecification( searchScope: IJavaSearchScope, description: String, limitTo: Int = IJavaSearchConstants.REFERENCES) : PatternQuerySpecification( "Kotlin Find References", IJavaSearchConstants.CLASS, true, limitTo, searchScope, description) object EmptyJavaSearchScope : IJavaSearchScope { override fun setIncludesClasspaths(includesClasspaths: Boolean) { } override fun setIncludesBinaries(includesBinaries: Boolean) { } override fun enclosingProjectsAndJars(): Array<out IPath> { val base = ResourcesPlugin.getWorkspace().getRoot().getLocation() return ResourcesPlugin.getWorkspace().getRoot().getProjects() .map { it.getLocation().makeRelativeTo(base) } .toTypedArray() } override fun includesBinaries(): Boolean = false override fun includesClasspaths(): Boolean = false override fun encloses(resourcePath: String?): Boolean = false override fun encloses(element: IJavaElement?): Boolean = false }
apache-2.0
b1b238cef0050b0c26959193b742f181
37.746667
120
0.733907
4.982847
false
false
false
false
mocovenwitch/heykotlin
app/src/main/java/com/mocoven/heykotlin/playground/Singleton.kt
1
230
package com.mocoven.heykotlin.playground object Singleton { private var value: String? = null fun hereYouGo(value: String) { this.value = value } val isEmpty: Boolean get() = value?.length == 0 }
mit
e9ee16081cbbae9af440be6dcfa566ba
18.25
40
0.630435
3.833333
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/modules/forums/topic/TopicPresenter.kt
2
4443
package ru.fantlab.android.ui.modules.forums.topic import android.view.View import io.reactivex.Single import io.reactivex.functions.Consumer import ru.fantlab.android.data.dao.model.ForumTopic import ru.fantlab.android.data.dao.response.ForumTopicResponse import ru.fantlab.android.provider.rest.DataManager import ru.fantlab.android.provider.rest.TopicMessagesSortOption import ru.fantlab.android.provider.rest.getTopicMessagesPath import ru.fantlab.android.provider.storage.DbProvider import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter class TopicPresenter : BasePresenter<TopicMvp.View>(), TopicMvp.Presenter { private var page: Int = 1 private var topicId: Int = 0 private var lastPage: Int = Integer.MAX_VALUE private var previousTotal: Int = 0 private var order = TopicMessagesSortOption.BY_NEW override fun onCallApi(page: Int, parameter: Int?): Boolean { topicId = parameter!! if (page == 1) { lastPage = Integer.MAX_VALUE sendToView { it.getLoadMore().reset() } } setCurrentPage(page) if (page > lastPage || lastPage == 0) { sendToView { it.hideProgress() } return false } getMessages(false) return true } override fun getMessages(force: Boolean) { makeRestCall( getTopicsInternal(force).toObservable(), Consumer { (pinned, messages, lastPage) -> sendToView { this.lastPage = lastPage it.getLoadMore().setTotalPagesCount(lastPage) it.onSetPinnedMessage(pinned) it.onNotifyAdapter(messages, page) } } ) } override fun refreshMessages(lastMessageId: String, isNewMessage: Boolean) { makeRestCall( getLastMessages().toObservable(), Consumer { messages -> sendToView { val newMessages = messages.filter { message -> message.id > lastMessageId } as ArrayList<ForumTopic.Message> if (isNewMessage && newMessages.size > 1) it.onAddToAdapter(newMessages, isNewMessage) else if (!isNewMessage && newMessages.isNotEmpty()) it.onAddToAdapter(newMessages, isNewMessage) else it.hideProgress() } } ) } private fun getTopicsInternal(force: Boolean) = getTopicsFromServer() .onErrorResumeNext { throwable -> if (!force) { getMessagesFromDb() } else { throw throwable } } private fun getTopicsFromServer(): Single<Triple<ForumTopic.PinnedMessage?, ArrayList<ForumTopic.Message>, Int>> = DataManager.getTopicMessages(topicId, page, order, 20) .map { getMessages(it) } private fun getMessagesFromDb(): Single<Triple<ForumTopic.PinnedMessage?, ArrayList<ForumTopic.Message>, Int>> = DbProvider.mainDatabase .responseDao() .get(getTopicMessagesPath(topicId, page, order, 20)) .map { it.response } .map { ForumTopicResponse.Deserializer().deserialize(it) } .map { getMessages(it) } private fun getLastMessages(): Single<ArrayList<ForumTopic.Message>> = DataManager.getTopicMessages(topicId, 1, TopicMessagesSortOption.BY_NEW, 10) .map { it.messages.items } private fun getMessages(response: ForumTopicResponse): Triple<ForumTopic.PinnedMessage?, ArrayList<ForumTopic.Message>, Int> = Triple(response.pinnedMessage, response.messages.items, response.messages.last) fun onDeleteMessage(messageId: Int) { makeRestCall( DataManager.deleteTopicMessage(messageId).toObservable(), Consumer { _ -> sendToView { it.onMessageDeleted(messageId) } } ) } override fun onDeleteDraftMessage(topicId: Int) { makeRestCall( DataManager.deleteTopicDraft(topicId).toObservable(), Consumer { sendToView { it.onMessageDraftDeleted() it.hideProgress() } } ) } override fun onConfirmDraftMessage(topicId: Int, lastMessageId: String) { makeRestCall( DataManager.confirmTopicDraft(topicId).toObservable(), Consumer { sendToView { it.onMessageDraftDeleted() } refreshMessages(lastMessageId, false) } ) } override fun getCurrentPage(): Int = page override fun getPreviousTotal(): Int = previousTotal override fun setCurrentPage(page: Int) { this.page = page } override fun setPreviousTotal(previousTotal: Int) { this.previousTotal = previousTotal } override fun onItemClick(position: Int, v: View?, item: ForumTopic.Message) { sendToView { it.onItemClicked(item) } } override fun onItemLongClick(position: Int, v: View?, item: ForumTopic.Message) { sendToView { it.onItemLongClicked(position, v, item) } } }
gpl-3.0
ca3833b8fdeced20b4bf2b50362e65b8
30.076923
207
0.724736
3.765254
false
false
false
false
kenrube/Fantlab-client
app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/ContextMenuViewHolder.kt
2
1180
package ru.fantlab.android.ui.adapter.viewholder import android.graphics.Typeface import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.context_row_item.view.* import ru.fantlab.android.R import ru.fantlab.android.data.dao.model.ContextMenus import ru.fantlab.android.ui.widgets.recyclerview.BaseRecyclerAdapter import ru.fantlab.android.ui.widgets.recyclerview.BaseViewHolder class ContextMenuViewHolder(itemView: View, adapter: BaseRecyclerAdapter<ContextMenus.MenuItem, ContextMenuViewHolder>) : BaseViewHolder<ContextMenus.MenuItem>(itemView, adapter) { override fun bind(item: ContextMenus.MenuItem) { if (item.icon != null) { itemView.icon.setImageResource(item.icon) itemView.icon.visibility = View.VISIBLE } else itemView.icon.visibility = View.GONE if (item.selected) itemView.title.text = "✓ ${item.title}" else itemView.title.text = item.title } companion object { fun newInstance( viewGroup: ViewGroup, adapter: BaseRecyclerAdapter<ContextMenus.MenuItem, ContextMenuViewHolder> ): ContextMenuViewHolder = ContextMenuViewHolder(getView(viewGroup, R.layout.context_row_item), adapter) } }
gpl-3.0
c1097f0f89659519b0a9a3e1af38aa0a
33.676471
119
0.795416
3.900662
false
false
false
false
tasomaniac/OpenLinkWith
app/src/main/java/com/tasomaniac/openwith/settings/ClipboardSettings.kt
1
2164
package com.tasomaniac.openwith.settings import android.content.ClipboardManager import androidx.core.view.doOnLayout import androidx.preference.PreferenceCategory import com.tasomaniac.openwith.R import com.tasomaniac.openwith.data.Analytics import com.tasomaniac.openwith.extensions.findFirstUrl import com.tasomaniac.openwith.redirect.RedirectFixActivity import javax.inject.Inject class ClipboardSettings @Inject constructor( fragment: SettingsFragment, private val clipboardManager: ClipboardManager, private val analytics: Analytics ) : Settings(fragment) { private var preferenceCategory: PreferenceCategory? = null override fun resume() { fragment.requireView().doOnLayout { updateClipboard() } } private fun updateClipboard() { val clipUrl = clipUrl() if (clipUrl == null && isAdded()) { remove() } if (clipUrl != null) { if (!isAdded()) { addClipboardPreference() analytics.sendEvent("Clipboard", "Added", "New") } updateClipUrl(clipUrl) } } private fun updateClipUrl(clipUrl: String) { findPreference(R.string.pref_key_clipboard).apply { setOnPreferenceClickListener { context.startActivity(RedirectFixActivity.createIntent(activity, clipUrl)) analytics.sendEvent("Clipboard", "Clicked", "Clicked") true } summary = clipUrl } } private fun clipUrl(): String? { return try { clipboardManager.primaryClip?.getItemAt(0)?.coerceToText(context)?.toString()?.findFirstUrl() } catch (ignored: Exception) { return null } } private fun addClipboardPreference() { addPreferencesFromResource(R.xml.pref_clipboard) preferenceCategory = findPreference(R.string.pref_key_category_clipboard) as PreferenceCategory } private fun remove() { removePreference(preferenceCategory!!) preferenceCategory = null } private fun isAdded() = preferenceCategory != null }
apache-2.0
46e627cb8dfba3e79b6e7c3927305f3c
28.643836
105
0.649723
5.079812
false
false
false
false
CoderLine/alphaTab
src.kotlin/alphaTab/alphaTab/src/androidMain/kotlin/alphaTab/platform/android/AndroidThreadScoreRenderer.kt
1
5643
package alphaTab.platform.android import alphaTab.* import alphaTab.collections.DoubleList import alphaTab.core.ecmaScript.Error import alphaTab.model.Score import alphaTab.rendering.IScoreRenderer import alphaTab.rendering.RenderFinishedEventArgs import alphaTab.rendering.ScoreRenderer import alphaTab.rendering.utils.BoundsLookup import java.util.concurrent.BlockingQueue import java.util.concurrent.LinkedBlockingQueue import java.util.concurrent.Semaphore import java.util.concurrent.TimeUnit import kotlin.contracts.ExperimentalContracts @ExperimentalContracts @ExperimentalUnsignedTypes internal class AndroidThreadScoreRenderer : IScoreRenderer, Runnable { private val _uiInvoke: ( action: (() -> Unit) ) -> Unit private val _workerThread: Thread private val _workerQueue: BlockingQueue<() -> Unit> private val _threadStartedEvent: Semaphore private var _isCancelled = false public lateinit var renderer: ScoreRenderer private var _width: Double = 0.0 public constructor(settings: Settings, uiInvoke: ( action: (() -> Unit) ) -> Unit) { _uiInvoke = uiInvoke _threadStartedEvent = Semaphore(1) _threadStartedEvent.acquire() _workerQueue = LinkedBlockingQueue() _workerThread = Thread(this) _workerThread.name = "alphaTabRenderThread" _workerThread.isDaemon = true _workerThread.start() _threadStartedEvent.acquire() _workerQueue.add { initialize(settings) } } override fun run() { _threadStartedEvent.release() try { do { val item = _workerQueue.poll(500, TimeUnit.MILLISECONDS) if (!_isCancelled && item != null) { item() } } while (!_isCancelled) } catch (e: InterruptedException) { // finished } } private fun initialize(settings: Settings) { renderer = ScoreRenderer(settings) renderer.partialRenderFinished.on { _uiInvoke { onPartialRenderFinished(it) } } renderer.partialLayoutFinished.on { _uiInvoke { onPartialLayoutFinished(it) } } renderer.renderFinished.on { _uiInvoke { onRenderFinished(it) } } renderer.postRenderFinished.on { _uiInvoke { onPostFinished(renderer.boundsLookup) } } renderer.preRender.on { _uiInvoke { onPreRender(it) } } renderer.error.on { _uiInvoke { onError(it) } } } private fun onPostFinished(boundsLookup: BoundsLookup?) { this.boundsLookup = boundsLookup onPostRenderFinished() } override var boundsLookup: BoundsLookup? = null override var width: Double get() = _width set(value) { _width = value if (checkAccess()) { renderer.width = value } else { _workerQueue.add { renderer.width = value } } } override fun render() { if (checkAccess()) { renderer.render() } else { _workerQueue.add { render() } } } override fun renderResult(resultId:String) { if (checkAccess()) { renderer.renderResult(resultId) } else { _workerQueue.add { renderResult(resultId) } } } override fun resizeRender() { if (checkAccess()) { renderer.resizeRender() } else { _workerQueue.add { resizeRender() } } } override fun renderScore(score: Score?, trackIndexes: DoubleList?) { if (checkAccess()) { renderer.renderScore(score, trackIndexes) } else { _workerQueue.add { renderScore( score, trackIndexes ) } } } override fun updateSettings(settings: Settings) { if (checkAccess()) { renderer.updateSettings(settings) } else { _workerQueue.add { updateSettings(settings) } } } private fun checkAccess(): Boolean { return Thread.currentThread().id == _workerThread.id } override fun destroy() { _isCancelled = true _workerThread.interrupt() _workerThread.join() } override val preRender: IEventEmitterOfT<Boolean> = EventEmitterOfT() private fun onPreRender(isResize: Boolean) { (preRender as EventEmitterOfT).trigger(isResize) } override val renderFinished: IEventEmitterOfT<RenderFinishedEventArgs> = EventEmitterOfT() private fun onRenderFinished(args: RenderFinishedEventArgs) { (renderFinished as EventEmitterOfT).trigger(args) } override val partialRenderFinished: IEventEmitterOfT<RenderFinishedEventArgs> = EventEmitterOfT() private fun onPartialRenderFinished(args: RenderFinishedEventArgs) { (partialRenderFinished as EventEmitterOfT).trigger(args) } override val partialLayoutFinished: IEventEmitterOfT<RenderFinishedEventArgs> = EventEmitterOfT() private fun onPartialLayoutFinished(args: RenderFinishedEventArgs) { (partialLayoutFinished as EventEmitterOfT).trigger(args) } override val postRenderFinished: IEventEmitter = EventEmitter() private fun onPostRenderFinished() { (postRenderFinished as EventEmitter).trigger() } override val error: IEventEmitterOfT<Error> = EventEmitterOfT() private fun onError(e: Error) { (error as EventEmitterOfT).trigger(e) } }
mpl-2.0
ab384bb1d36b2759babe578933be6e43
29.33871
94
0.625377
4.698585
false
false
false
false
elect86/jAssimp
src/test/kotlin/assimp/utils.kt
2
3296
package assimp import glm_.glm import glm_.mat2x2.Mat2 import glm_.mat3x3.Mat3 import glm_.mat4x4.Mat4 import glm_.mat4x4.Mat4d import glm_.quat.Quat import glm_.quat.QuatD import glm_.vec1.Vec1 import glm_.vec1.Vec1d import glm_.vec2.Vec2 import glm_.vec2.Vec2d import glm_.vec3.Vec3 import glm_.vec3.Vec3d import glm_.vec4.Vec4 import glm_.vec4.Vec4d import io.kotest.matchers.shouldBe // from glm test infix fun Float.shouldEqual(f: Float) = shouldEqual(f, glm.εf) fun Float.shouldEqual(f: Float, epsilon: Float) = glm.equal(this, f, epsilon) shouldBe true infix fun Double.shouldEqual(d: Double) = shouldEqual(d, glm.ε) fun Double.shouldEqual(d: Double, epsilon: Double) = glm.equal(this, d, epsilon) shouldBe true infix fun Quat.shouldEqual(q: Quat) = shouldEqual(q, glm.εf) fun Quat.shouldEqual(q: Quat, epsilon: Float) = allEqual(q, epsilon) shouldBe true infix fun QuatD.shouldEqual(q: QuatD) = shouldEqual(q, glm.ε) fun QuatD.shouldEqual(q: QuatD, epsilon: Double) = allEqual(q, epsilon) shouldBe true infix fun Vec1.shouldEqual(v: Vec1) = shouldEqual(v, glm.εf) fun Vec1.shouldEqual(v: Vec1, epsilon: Float) = glm.equal(x, v.x, epsilon) shouldBe true infix fun Vec1d.shouldEqual(v: Vec1d) = shouldEqual(v, glm.ε) fun Vec1d.shouldEqual(v: Vec1d, epsilon: Double) = glm.equal(x, v.x, epsilon) shouldBe true infix fun Vec2.shouldEqual(v: Vec2) = shouldEqual(v, glm.εf) fun Vec2.shouldEqual(v: Vec2, epsilon: Float) = allEqual(v, epsilon) shouldBe true infix fun Vec2d.shouldEqual(v: Vec2d) = shouldEqual(v, glm.ε) fun Vec2d.shouldEqual(v: Vec2d, epsilon: Double) = allEqual(v, epsilon) shouldBe true infix fun Vec3.shouldEqual(v: Vec3) = shouldEqual(v, glm.εf) fun Vec3.shouldEqual(v: Vec3, epsilon: Float) = allEqual(v, epsilon) shouldBe true infix fun Vec3d.shouldEqual(v: Vec3d) = shouldEqual(v, glm.ε) fun Vec3d.shouldEqual(v: Vec3d, epsilon: Double) = allEqual(v, epsilon) shouldBe true infix fun Vec4.shouldEqual(v: Vec4) = shouldEqual(v, glm.εf) fun Vec4.shouldEqual(v: Vec4, epsilon: Float) = allEqual(v, epsilon) shouldBe true infix fun Vec4d.shouldEqual(v: Vec4d) = shouldEqual(v, glm.ε) fun Vec4d.shouldEqual(v: Vec4d, epsilon: Double) = allEqual(v, epsilon) shouldBe true infix fun Mat2.shouldEqual(v: Mat2) = shouldEqual(v, glm.εf) fun Mat2.shouldEqual(v: Mat2, epsilon: Float) = allEqual(v, epsilon) shouldBe true infix fun Mat3.shouldEqual(v: Mat3) = shouldEqual(v, glm.εf) fun Mat3.shouldEqual(v: Mat3, epsilon: Float) = allEqual(v, epsilon) shouldBe true infix fun Mat4.shouldEqual(v: Mat4) = shouldEqual(v, glm.εf) fun Mat4.shouldEqual(v: Mat4, epsilon: Float) = allEqual(v, epsilon) shouldBe true infix fun Mat4d.shouldEqual(v: Mat4d) = shouldEqual(v, glm.ε) fun Mat4d.shouldEqual(v: Mat4d, epsilon: Double) = allEqual(v, epsilon) shouldBe true fun FloatArray.shouldEqual2(x: Float, y: Float) = shouldEqual2(x, y, glm.εf) fun FloatArray.shouldEqual2(x: Float, y: Float, epsilon: Float) { get(0).shouldEqual(x, epsilon) get(1).shouldEqual(y, epsilon) } fun FloatArray.shouldEqual3(x: Float, y: Float, z: Float) = shouldEqual3(x, y, z, glm.εf) fun FloatArray.shouldEqual3(x: Float, y: Float, z: Float, epsilon: Float) { get(0).shouldEqual(x, epsilon) get(1).shouldEqual(y, epsilon) get(2).shouldEqual(z, epsilon) }
mit
66e67def22f0947fe58baee7d98b35a9
39.481481
94
0.741916
2.799317
false
false
false
false
da1z/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/util/psiTreeUtil.kt
2
1942
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.psi.util import com.intellij.openapi.progress.ProgressManager import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.parents import com.intellij.util.withPrevious import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil.DECLARATION_SCOPE_PASSED /** * @receiver element to start from * @return sequence of context elements */ fun PsiElement.contexts(): Sequence<PsiElement> = generateSequence(this) { ProgressManager.checkCanceled() it.context } @JvmOverloads fun PsiElement.treeWalkUp(processor: PsiScopeProcessor, state: ResolveState = ResolveState.initial(), place: PsiElement = this): Boolean { for ((scope, lastParent) in contexts().withPrevious()) { if (!scope.processDeclarations(processor, state, lastParent, place)) return false processor.handleEvent(DECLARATION_SCOPE_PASSED, scope) } return true } inline fun <reified T : PsiElement> PsiElement.skipParentsOfType() = skipParentsOfType(true, T::class.java) fun PsiElement.skipParentsOfType(strict: Boolean = false, vararg types: Class<*>): Pair<PsiElement, PsiElement?>? { val seq = parents().withPrevious().drop(if (strict) 1 else 0) return seq.firstOrNull { (parent, _) -> parent.javaClass !in types } }
apache-2.0
dcfede11473bb64c5f95ad644f89c841
37.078431
138
0.762616
4.194384
false
false
false
false
paslavsky/music-sync-manager
msm-server/src/main/kotlin/net/paslavsky/msm/setting/description/XmlProperty.kt
1
2931
package net.paslavsky.msm.setting.description import javax.xml.bind.annotation.XmlAccessType import javax.xml.bind.annotation.XmlType import javax.xml.bind.annotation.XmlAccessorType import javax.xml.bind.annotation.XmlElement import javax.xml.bind.annotation.XmlAttribute import java.util.ArrayList import org.apache.commons.lang3.builder.ReflectionToStringBuilder import org.apache.commons.lang3.builder.EqualsBuilder import org.apache.commons.lang3.builder.HashCodeBuilder import net.paslavsky.msm.setting.PropertyValidator /** * <p>Class for Property complex type. * <p/> * <p>The following schema fragment specifies the expected content contained within this class. * <p/> * <pre> * &lt;complexType name="Property"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="validator" type="{http://www.w3.org/2001/XMLSchema}string" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="name" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="type" use="required" type="{http://paslavsky.net/property-description/1.0}PropertyType" /> * &lt;attribute name="validate" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="scope" type="{http://paslavsky.net/property-description/1.0}PropertyScope" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * @author Andrey Paslavsky * @version 1.0 */ XmlAccessorType(XmlAccessType.FIELD) XmlType(name = "Property", namespace = "http://paslavsky.net/property-description/1.0", propOrder = arrayOf("validators")) public class XmlProperty { XmlAttribute(name = "name", required = true) public var name: String = "" XmlAttribute(name = "type", required = true) public var `type`: PropertyType = PropertyType.string XmlAttribute(name = "scope") public var scope: PropertyScope = PropertyScope.application XmlAttribute(name = "validate") public var validate: String? = null XmlElement(name = "validator", namespace = "http://paslavsky.net/property-description/1.0") public var validators: MutableCollection<Class<out PropertyValidator>> = ArrayList() override fun toString(): String = ReflectionToStringBuilder(this).toString(); override fun hashCode(): Int = HashCodeBuilder().append(name)!!.append(`type`)!!.toHashCode() override fun equals(other: Any?): Boolean { when { other identityEquals(null) -> return false other identityEquals(this) -> return true other is XmlProperty -> return EqualsBuilder(). append(name, other.name)!!. append(`type`, other.`type`)!!. append(scope, other.scope)!!. isEquals() else -> return false } } }
apache-2.0
e2d6a99e2cbdbee060283ab80125957d
42.117647
125
0.684408
3.887268
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/queue/commands/CommandReadStatus.kt
1
1381
package info.nightscout.androidaps.queue.commands import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.shared.logging.LTag import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.LocalAlertUtils import info.nightscout.androidaps.utils.T import javax.inject.Inject class CommandReadStatus( injector: HasAndroidInjector, val reason: String, callback: Callback? ) : Command(injector, CommandType.READSTATUS, callback) { @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var localAlertUtils: LocalAlertUtils override fun execute() { activePlugin.activePump.getPumpStatus(reason) localAlertUtils.notifyPumpStatusRead() aapsLogger.debug(LTag.PUMPQUEUE, "CommandReadStatus executed. Reason: $reason") val pump = activePlugin.activePump val result = PumpEnactResult(injector).success(false) val lastConnection = pump.lastDataTime() if (lastConnection > System.currentTimeMillis() - T.mins(1).msecs()) result.success(true) callback?.result(result)?.run() } override fun status(): String = rh.gs(R.string.read_status, reason) override fun log(): String = "READSTATUS $reason" }
agpl-3.0
bbdbc7f308ba6a3b81a7d8f48baf4075
37.388889
97
0.763215
4.542763
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/plugins/general/smsCommunicator/SmsCommunicatorFragment.kt
1
3540
package info.nightscout.androidaps.plugins.general.smsCommunicator import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import dagger.android.support.DaggerFragment import info.nightscout.androidaps.databinding.SmscommunicatorFragmentBinding import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.general.smsCommunicator.events.EventSmsCommunicatorUpdateGui import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.FabricPrivacy import info.nightscout.androidaps.utils.HtmlHelper import io.reactivex.rxjava3.kotlin.plusAssign import info.nightscout.androidaps.utils.rx.AapsSchedulers import io.reactivex.rxjava3.disposables.CompositeDisposable import java.util.* import javax.inject.Inject import kotlin.math.max class SmsCommunicatorFragment : DaggerFragment() { @Inject lateinit var aapsSchedulers: AapsSchedulers @Inject lateinit var fabricPrivacy: FabricPrivacy @Inject lateinit var rxBus: RxBus @Inject lateinit var smsCommunicatorPlugin: SmsCommunicatorPlugin @Inject lateinit var dateUtil: DateUtil private val disposable = CompositeDisposable() private var _binding: SmscommunicatorFragmentBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { _binding = SmscommunicatorFragmentBinding.inflate(inflater, container, false) return binding.root } @Synchronized override fun onResume() { super.onResume() disposable += rxBus .toObservable(EventSmsCommunicatorUpdateGui::class.java) .observeOn(aapsSchedulers.main) .subscribe({ updateGui() }, fabricPrivacy::logException) updateGui() } @Synchronized override fun onPause() { super.onPause() disposable.clear() } override fun onDestroyView() { super.onDestroyView() _binding = null } fun updateGui() { if (_binding == null) return class CustomComparator : Comparator<Sms> { override fun compare(object1: Sms, object2: Sms): Int { return (object1.date - object2.date).toInt() } } Collections.sort(smsCommunicatorPlugin.messages, CustomComparator()) val messagesToShow = 40 val start = max(0, smsCommunicatorPlugin.messages.size - messagesToShow) var logText = "" for (x in start until smsCommunicatorPlugin.messages.size) { val sms = smsCommunicatorPlugin.messages[x] when { sms.ignored -> { logText += dateUtil.timeString(sms.date) + " &lt;&lt;&lt; " + "░ " + sms.phoneNumber + " <b>" + sms.text + "</b><br>" } sms.received -> { logText += dateUtil.timeString(sms.date) + " &lt;&lt;&lt; " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>" } sms.sent -> { logText += dateUtil.timeString(sms.date) + " &gt;&gt;&gt; " + (if (sms.processed) "● " else "○ ") + sms.phoneNumber + " <b>" + sms.text + "</b><br>" } } } binding.log.text = HtmlHelper.fromHtml(logText) } }
agpl-3.0
baf427d338eaa95fef593617069f82f2
36.168421
168
0.654391
4.644737
false
false
false
false
abigpotostew/easypolitics
ui/src/main/kotlin/bz/stew/bracken/ui/common/bill/govtrack/GovTrackMajorAction.kt
1
1226
package bz.stew.bracken.ui.common.bill.govtrack import bz.stew.bracken.ui.extension.html.jsDate import bz.stew.bracken.ui.common.bill.MajorAction import kotlin.js.Date /** * Created by stew on 2/13/17. */ private val dateRegex: Regex = Regex( "datetime\\.datetime\\((\\d{4}),\\s{0,1}(\\d{1,2}),\\s{0,1}(\\d{1,2})") class GovTrackMajorAction(date: String, private val id: Int = -1, private val description: String = "none", private val xml: String = "none") : MajorAction { private val date = resolveDate(date) private fun resolveDate(dateString: String): Date { val matches = dateRegex.findAll(dateString) var matchGroups: List<String> = matches.iterator().next().groupValues val year = matchGroups[1].toInt() val month = matchGroups[2].toInt() - 1 val day = matchGroups[3].toInt() //val hour = matchGroups[4].toInt() return jsDate(year, month, day) } override fun id(): Int { return id } override fun description(): String { return description } override fun raw(): String { return xml } override fun date(): Date { return date } }
apache-2.0
264b5d003fead2c419674d1ab00cf98c
26.266667
77
0.60522
3.749235
false
false
false
false
SnakeEys/MessagePlus
app/src/main/java/info/fox/messup/contacts/TabContactFragment.kt
1
1378
package info.fox.messup.contacts import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.support.v4.widget.SwipeRefreshLayout import android.support.v7.widget.DividerItemDecoration import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import info.fox.messup.R /** * Created by snake * on 17/6/9. */ class TabContactFragment : Fragment(){ companion object { fun newInstance(): TabContactFragment { val instance = TabContactFragment() return instance } } override fun onAttach(context: Context?) { super.onAttach(context) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.tab_contact, container, false) as SwipeRefreshLayout view.isEnabled = false val recycler = view.findViewById(R.id.rv_content) as RecyclerView recycler.layoutManager = LinearLayoutManager(context) recycler.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) val adapter = ContactAdapter(activity) recycler.adapter = adapter return view } }
mit
36dee39f0549a33a240869088ab2f293
28.340426
116
0.733672
4.639731
false
false
false
false
ingokegel/intellij-community
build/tasks/src/org/jetbrains/intellij/build/io/zip.kt
1
4938
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.intellij.build.io import org.jetbrains.intellij.build.tasks.PackageIndexBuilder import java.nio.channels.FileChannel import java.nio.file.* import java.util.* import java.util.zip.Deflater private val W_OVERWRITE = EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE) enum class AddDirEntriesMode { NONE, RESOURCE_ONLY, ALL } // symlinks not supported but can be easily implemented - see CollectingVisitor.visitFile fun zip(targetFile: Path, dirs: Map<Path, String>, compress: Boolean, addDirEntriesMode: AddDirEntriesMode = AddDirEntriesMode.NONE, overwrite: Boolean = false, compressionLevel: Int = Deflater.DEFAULT_COMPRESSION, fileFilter: ((name: String) -> Boolean)? = null) { // note - dirs contain duplicated directories (you cannot simply add directory entry on visit - uniqueness must be preserved) // anyway, directory entry are not added Files.createDirectories(targetFile.parent) ZipFileWriter(channel = FileChannel.open(targetFile, if (overwrite) W_OVERWRITE else W_CREATE_NEW), deflater = if (compress) Deflater(compressionLevel, true) else null).use { val fileAdded: ((String) -> Boolean)? val dirNameSetToAdd: Set<String> if (addDirEntriesMode != AddDirEntriesMode.NONE) { dirNameSetToAdd = LinkedHashSet() fileAdded = { name -> if (addDirEntriesMode == AddDirEntriesMode.ALL || (addDirEntriesMode == AddDirEntriesMode.RESOURCE_ONLY && !name.endsWith(".class") && !name.endsWith( "/package.html") && name != "META-INF/MANIFEST.MF")) { var slashIndex = name.lastIndexOf('/') if (slashIndex != -1) { while (dirNameSetToAdd.add(name.substring(0, slashIndex))) { slashIndex = name.lastIndexOf('/', slashIndex - 2) if (slashIndex == -1) { break } } } } true } } else { fileAdded = fileFilter?.let { { name -> it(name) } } dirNameSetToAdd = emptySet() } val archiver = ZipArchiver(it, fileAdded) for ((dir, prefix) in dirs.entries) { val normalizedDir = dir.toAbsolutePath().normalize() archiver.setRootDir(normalizedDir, prefix) compressDir(normalizedDir, archiver, excludes = null) } if (dirNameSetToAdd.isNotEmpty()) { addDirForResourceFiles(it, dirNameSetToAdd) } } } private fun addDirForResourceFiles(out: ZipFileWriter, dirNameSetToAdd: Set<String>) { for (dir in dirNameSetToAdd) { out.dir(dir) } } class ZipArchiver(private val zipCreator: ZipFileWriter, val fileAdded: ((String) -> Boolean)? = null) : AutoCloseable { private var localPrefixLength = -1 private var archivePrefix = "" // rootDir must be absolute and normalized fun setRootDir(rootDir: Path, prefix: String = "") { archivePrefix = when { prefix.isNotEmpty() && !prefix.endsWith('/') -> "$prefix/" prefix == "/" -> "" else -> prefix } localPrefixLength = rootDir.toString().length + 1 } fun addFile(file: Path) { val name = archivePrefix + file.toString().substring(localPrefixLength).replace('\\', '/') if (fileAdded == null || fileAdded.invoke(name)) { zipCreator.file(name, file) } } override fun close() { zipCreator.close() } } fun compressDir(startDir: Path, archiver: ZipArchiver, excludes: List<PathMatcher>? = emptyList()) { val dirCandidates = ArrayDeque<Path>() dirCandidates.add(startDir) val tempList = ArrayList<Path>() while (true) { val dir = dirCandidates.pollFirst() ?: break tempList.clear() val dirStream = try { Files.newDirectoryStream(dir) } catch (e: NoSuchFileException) { continue } dirStream.use { if (excludes == null) { tempList.addAll(it) } else { l@ for (child in it) { val relative = startDir.relativize(child) for (exclude in excludes) { if (exclude.matches(relative)) { continue@l } } tempList.add(child) } } } tempList.sort() for (file in tempList) { if (Files.isDirectory(file)) { dirCandidates.add(file) } else { archiver.addFile(file) } } } } internal fun copyZipRaw(sourceFile: Path, packageIndexBuilder: PackageIndexBuilder, zipCreator: ZipFileWriter, filter: (entryName: String) -> Boolean = { true }) { readZipFile(sourceFile) { name, entry -> if (filter(name)) { packageIndexBuilder.addFile(name) zipCreator.uncompressedData(name, entry.getByteBuffer()) } } }
apache-2.0
a40625bd71016dd58d40683f7dc49428
31.071429
127
0.63224
4.22774
false
false
false
false
mdaniel/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/editor/tables/ui/presentation/HorizontalBarPresentation.kt
2
11443
// 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.intellij.plugins.markdown.editor.tables.ui.presentation import com.intellij.codeInsight.hint.HintManager import com.intellij.codeInsight.hint.HintManagerImpl import com.intellij.codeInsight.hints.fireUpdateEvent import com.intellij.codeInsight.hints.presentation.BasePresentation import com.intellij.codeInsight.hints.presentation.InlayPresentation import com.intellij.codeInsight.hints.presentation.PresentationFactory import com.intellij.openapi.actionSystem.ActionGroup import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.application.ModalityState import com.intellij.openapi.application.invokeLater import com.intellij.openapi.command.executeCommand import com.intellij.openapi.editor.Document import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.colors.EditorFontType import com.intellij.openapi.editor.markup.TextAttributes import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiDocumentManager import com.intellij.psi.util.siblings import com.intellij.refactoring.suggested.startOffset import com.intellij.ui.LightweightHint import com.intellij.util.ui.GraphicsUtil import org.intellij.plugins.markdown.editor.tables.TableFormattingUtils.isSoftWrapping import org.intellij.plugins.markdown.editor.tables.TableModificationUtils.selectColumn import org.intellij.plugins.markdown.editor.tables.actions.TableActionKeys import org.intellij.plugins.markdown.editor.tables.ui.presentation.GraphicsUtils.clearOvalOverEditor import org.intellij.plugins.markdown.lang.MarkdownTokenTypes import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTable import org.intellij.plugins.markdown.lang.psi.impl.MarkdownTableRow import org.intellij.plugins.markdown.lang.psi.util.hasType import java.awt.* import java.awt.event.MouseEvent import java.lang.ref.WeakReference import javax.swing.SwingUtilities internal class HorizontalBarPresentation(private val editor: Editor, private val table: MarkdownTable): BasePresentation() { private data class BoundsState( val width: Int, val height: Int, val barsModel: List<Rectangle> ) private var lastSelectedIndex: Int? = null private var boundsState = emptyBoundsState init { val document = editor.document PsiDocumentManager.getInstance(table.project).performForCommittedDocument(document) { invokeLater(ModalityState.stateForComponent(editor.contentComponent)) { if (!isInvalid && !table.isSoftWrapping(editor)) { val calculated = calculateCurrentBoundsState(document) boundsState = calculated fireSizeChanged(Dimension(0, 0), Dimension(calculated.width, calculated.height)) } } } } private val barsModel get() = boundsState.barsModel private val isInvalid get() = !table.isValid || editor.isDisposed override val width get() = boundsState.width override val height get() = boundsState.height override fun paint(graphics: Graphics2D, attributes: TextAttributes) { if (isInvalid) { return } GraphicsUtil.setupAntialiasing(graphics) GraphicsUtil.setupRoundedBorderAntialiasing(graphics) paintBars(graphics) } override fun toString() = "HorizontalBarPresentation" override fun mouseClicked(event: MouseEvent, translated: Point) { when { SwingUtilities.isLeftMouseButton(event) && event.clickCount.mod(2) == 0 -> handleMouseLeftDoubleClick(event, translated) SwingUtilities.isLeftMouseButton(event) -> handleMouseLeftClick(event, translated) } } override fun mouseMoved(event: MouseEvent, translated: Point) { val index = determineColumnIndex(translated) updateSelectedIndexIfNeeded(index) } override fun mouseExited() { updateSelectedIndexIfNeeded(null) } private fun calculateCurrentBoundsState(document: Document): BoundsState { if (isInvalid) { return emptyBoundsState } //val document = obtainCommittedDocument(table) ?: return emptyBoundsState val fontsMetrics = obtainFontMetrics(editor) val width = calculateRowWidth(fontsMetrics, document) val barsModel = buildBarsModel(fontsMetrics, document) return BoundsState(width, barHeight, barsModel) } private fun calculateRowWidth(fontMetrics: FontMetrics, document: Document): Int { if (isInvalid) { return 0 } val header = table.headerRow ?: return 0 return fontMetrics.stringWidth(document.getText(header.textRange)) } private fun updateSelectedIndexIfNeeded(index: Int?) { if (lastSelectedIndex != index) { lastSelectedIndex = index // Force full re-render by lying about previous dimensions fireUpdateEvent(Dimension(0, 0)) } } private fun buildBarsModel(fontMetrics: FontMetrics, document: Document): List<Rectangle> { val header = requireNotNull(table.headerRow) val positions = calculatePositions(header, document, fontMetrics) val sectors = buildSectors(positions) return sectors.map { (offset, width) -> Rectangle(offset - barHeight / 2, 0, width + barHeight, barHeight) } } private fun calculatePositions(header: MarkdownTableRow, document: Document, fontMetrics: FontMetrics): List<Int> { require(barHeight % 2 == 0) { "barHeight value should be even" } val separators = header.firstChild.siblings(forward = true, withSelf = true) .filter { it.hasType(MarkdownTokenTypes.TABLE_SEPARATOR) } .map { it.startOffset } val separatorWidth = fontMetrics.charWidth('|') val firstOffset = separators.firstOrNull() ?: return emptyList() val result = ArrayList<Int>() var position = editor.offsetToXY(firstOffset).x + separatorWidth / 2 var lastOffset = firstOffset result.add(position) for (offset in separators.drop(1)) { val length = fontMetrics.stringWidth(document.getText(TextRange(lastOffset, offset))) position += length result.add(position) lastOffset = offset } return result } private fun buildSectors(positions: List<Int>): List<Pair<Int, Int>> { return positions.windowed(2).map { (left, right) -> left to (right - left) }.toList() } private fun determineColumnIndex(point: Point): Int? { return barsModel.indexOfFirst { it.contains(point) }.takeUnless { it < 0 } } private fun calculateToolbarPosition(componentHeight: Int, columnIndex: Int): Point { val position = editor.offsetToXY(table.startOffset) // Position hint relative to the editor val editorParent = editor.contentComponent.topLevelAncestor.locationOnScreen val editorPosition = editor.contentComponent.locationOnScreen position.translate(editorPosition.x - editorParent.x, editorPosition.y - editorParent.y) // Translate hint right above the bar position.translate(leftPadding, -editor.lineHeight) position.translate(0, -componentHeight) val rect = barsModel[columnIndex] val bottomPadding = 2 position.translate(rect.x, -rect.y - barHeight * 2 - bottomPadding) return position } private fun showToolbar(columnIndex: Int) { val actionToolbar = TableActionKeys.createActionToolbar( columnActionGroup, isHorizontal = true, editor, createDataProvider(table, columnIndex) ) val hint = LightweightHint(actionToolbar.component) hint.setForceShowAsPopup(true) val targetPoint = calculateToolbarPosition(hint.component.preferredSize.height, columnIndex) val hintManager = HintManagerImpl.getInstanceImpl() hintManager.hideAllHints() val flags = HintManager.HIDE_BY_ANY_KEY or HintManager.HIDE_BY_SCROLLING or HintManager.HIDE_BY_CARET_MOVE or HintManager.HIDE_BY_TEXT_CHANGE hintManager.showEditorHint(hint, editor, targetPoint, flags, 0, false) } private fun handleMouseLeftDoubleClick(event: MouseEvent, translated: Point) { val columnIndex = determineColumnIndex(translated) ?: return invokeLater { executeCommand { table.selectColumn(editor, columnIndex, withHeader = true, withSeparator = true, withBorders = true) } } } private fun handleMouseLeftClick(event: MouseEvent, translated: Point) { val columnIndex = determineColumnIndex(translated) ?: return showToolbar(columnIndex) } private fun actuallyPaintBars(graphics: Graphics2D, rect: Rectangle, hover: Boolean, accent: Boolean) { val paintCount = when { accent -> 2 else -> 1 } repeat(paintCount) { graphics.color = when { hover -> TableInlayProperties.barHoverColor else -> TableInlayProperties.barColor } graphics.fillRoundRect(rect.x, 0, rect.width, barHeight, barHeight, barHeight) graphics.clearOvalOverEditor(rect.x, 0, barHeight, barHeight) graphics.clearOvalOverEditor(rect.x + rect.width - barHeight, 0, barHeight, barHeight) } } private fun paintBars(graphics: Graphics2D) { val currentBarsModel = barsModel // First pass: paint each bar without circles for ((index, rect) in currentBarsModel.withIndex()) { val mouseIsOver = lastSelectedIndex == index actuallyPaintBars(graphics, rect, hover = mouseIsOver, accent = false) } // Second pass: paint each circle to fill up gaps repeat(2) { paintCircles(currentBarsModel) { x, _, _ -> graphics.color = TableInlayProperties.barColor graphics.fillOval(x, 0, barHeight, barHeight) } } } private fun paintCircles(rects: List<Rectangle>, width: Int = barHeight, block: (Int, Rectangle, Int) -> Unit) { if (rects.isNotEmpty()) { for ((index, rect) in rects.withIndex()) { block(rect.x, rect, index) } rects.last().let { block(it.x + it.width - width, it, -1) } } } companion object { private val columnActionGroup get() = ActionManager.getInstance().getAction("Markdown.TableColumnActions") as ActionGroup private val emptyBoundsState = BoundsState(0, 0, emptyList()) // Should be even const val barHeight = TableInlayProperties.barSize const val leftPadding = VerticalBarPresentation.barWidth + TableInlayProperties.leftRightPadding * 2 private fun wrapPresentation(factory: PresentationFactory, editor: Editor, presentation: InlayPresentation): InlayPresentation { return factory.inset( PresentationWithCustomCursor(editor, presentation), left = leftPadding, top = TableInlayProperties.topDownPadding, down = TableInlayProperties.topDownPadding ) } fun create(factory: PresentationFactory, editor: Editor, table: MarkdownTable): InlayPresentation { return wrapPresentation(factory, editor, HorizontalBarPresentation(editor, table)) } private fun obtainFontMetrics(editor: Editor): FontMetrics { val font = editor.colorsScheme.getFont(EditorFontType.PLAIN) return editor.contentComponent.getFontMetrics(font) } private fun createDataProvider(table: MarkdownTable, columnIndex: Int): DataProvider { val tableReference = WeakReference(table) return DataProvider { when { TableActionKeys.COLUMN_INDEX.`is`(it) -> columnIndex TableActionKeys.ELEMENT.`is`(it) -> tableReference else -> null } } } } }
apache-2.0
4bbe7605e153c21700d45d1231e5fe6d
38.732639
158
0.740191
4.457733
false
false
false
false
spinnaker/orca
orca-keel/src/test/kotlin/com/netflix/spinnaker/orca/keel/ImportDeliveryConfigTaskTests.kt
2
17032
/* * Copyright 2019 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.keel import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.convertValue import com.netflix.spinnaker.kork.web.exceptions.InvalidRequestException import com.netflix.spinnaker.orca.KeelService import com.netflix.spinnaker.orca.api.pipeline.TaskResult import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.api.pipeline.models.ExecutionType import com.netflix.spinnaker.orca.api.pipeline.models.Trigger import com.netflix.spinnaker.orca.config.KeelConfiguration import com.netflix.spinnaker.orca.igor.ScmService import com.netflix.spinnaker.orca.keel.model.DeliveryConfig import com.netflix.spinnaker.orca.keel.task.ImportDeliveryConfigTask import com.netflix.spinnaker.orca.keel.task.ImportDeliveryConfigTask.Companion.UNAUTHORIZED_SCM_ACCESS_MESSAGE import com.netflix.spinnaker.orca.keel.task.ImportDeliveryConfigTask.SpringHttpError import com.netflix.spinnaker.orca.pipeline.model.DefaultTrigger import com.netflix.spinnaker.orca.pipeline.model.GitTrigger import com.netflix.spinnaker.orca.pipeline.model.PipelineExecutionImpl import com.netflix.spinnaker.orca.pipeline.model.StageExecutionImpl import dev.minutest.junit.JUnit5Minutests import dev.minutest.rootContext import io.mockk.every import io.mockk.mockk import io.mockk.slot import io.mockk.verify import org.springframework.http.HttpStatus.BAD_REQUEST import org.springframework.http.HttpStatus.FORBIDDEN import retrofit.RetrofitError import retrofit.client.Response import retrofit.converter.JacksonConverter import retrofit.mime.TypedInput import strikt.api.expectThat import strikt.api.expectThrows import strikt.assertions.contains import strikt.assertions.isA import strikt.assertions.isEqualTo import strikt.assertions.isNotEqualTo import strikt.assertions.isNotNull import java.time.Instant import java.time.temporal.ChronoUnit internal class ImportDeliveryConfigTaskTests : JUnit5Minutests { data class ManifestLocation( val repoType: String, val projectKey: String, val repositorySlug: String, val directory: String, val manifest: String, val ref: String ) data class Fixture( val trigger: Trigger, val manifestLocation: ManifestLocation = ManifestLocation( repoType = "stash", projectKey = "SPKR", repositorySlug = "keeldemo", directory = ".", manifest = "spinnaker.yml", ref = "refs/heads/master" ) ) { companion object { val objectMapper: ObjectMapper = KeelConfiguration().keelObjectMapper() } val manifest = mapOf( "name" to "keeldemo-manifest", "application" to "keeldemo", "artifacts" to emptySet<Map<String, Any?>>(), "environments" to emptySet<Map<String, Any?>>() ) val scmService: ScmService = mockk(relaxUnitFun = true) { every { getDeliveryConfigManifest(any(), any(), any(), any(), any(), any()) } returns manifest } val keelService: KeelService = mockk(relaxUnitFun = true) { every { publishDeliveryConfig(any()) } returns Response("http://keel", 200, "", emptyList(), null) } val subject = ImportDeliveryConfigTask(keelService, scmService, objectMapper) fun execute(context: Map<String, Any?>) = subject.execute( StageExecutionImpl( PipelineExecutionImpl(ExecutionType.PIPELINE, "keeldemo").also { it.trigger = trigger }, ExecutionType.PIPELINE.toString(), context ) ) val parsingError = SpringHttpError( status = BAD_REQUEST.value(), error = BAD_REQUEST.reasonPhrase, message = "Parsing error", details = mapOf( "message" to "Parsing error", "path" to listOf( mapOf( "type" to "SomeClass", "field" to "someField" ) ), "pathExpression" to ".someField" ), // Jackson writes this as ms-since-epoch, so we need to strip off the nanoseconds, since we'll // be round-tripping it through Jackson before testing for equality. timestamp = Instant.now().truncatedTo(ChronoUnit.MILLIS) ) val accessDeniedError = SpringHttpError( status = FORBIDDEN.value(), error = FORBIDDEN.reasonPhrase, message = "Access denied", // Jackson writes this as ms-since-epoch, so we need to strip off the nanoseconds, since we'll // be round-tripping it through Jackson before testing for equality. timestamp = Instant.now().truncatedTo(ChronoUnit.MILLIS) ) } private fun ManifestLocation.toMap() = Fixture.objectMapper.convertValue<Map<String, Any?>>(this).toMutableMap() private val objectMapper = Fixture.objectMapper fun tests() = rootContext<Fixture> { context("basic behavior") { fixture { Fixture( DefaultTrigger("manual") ) } test("successfully retrieves manifest from SCM and publishes to keel") { val result = execute(manifestLocation.toMap()) expectThat(result.status).isEqualTo(SUCCEEDED) verify(exactly = 1) { scmService.getDeliveryConfigManifest( manifestLocation.repoType, manifestLocation.projectKey, manifestLocation.repositorySlug, manifestLocation.directory, manifestLocation.manifest, manifestLocation.ref ) } verify(exactly = 1) { keelService.publishDeliveryConfig(manifest) } } } context("with manual trigger") { fixture { Fixture( DefaultTrigger("manual") ) } context("with required stage context missing") { test("throws an exception") { expectThrows<InvalidRequestException> { execute(manifestLocation.toMap().also { it.remove("repoType") }) } } } context("with optional stage context missing") { test("uses defaults to fill in the blanks") { val result = execute( manifestLocation.toMap().also { it.remove("directory") it.remove("manifest") it.remove("ref") } ) expectThat(result.status).isEqualTo(SUCCEEDED) verify(exactly = 1) { scmService.getDeliveryConfigManifest( manifestLocation.repoType, manifestLocation.projectKey, manifestLocation.repositorySlug, null, "spinnaker.yml", "refs/heads/master" ) } } } } context("with git trigger") { fixture { Fixture( GitTrigger( source = "stash", project = "other", slug = "other", branch = "master", hash = "bea43e7033e19327183416f23fe2ee1b64c25f4a", action = "n/a" ) ) } context("with fully-populated stage context") { test("disregards trigger and uses context information to retrieve manifest from SCM") { val result = execute(manifestLocation.toMap()) expectThat(result.status).isEqualTo(SUCCEEDED) verify(exactly = 1) { scmService.getDeliveryConfigManifest( manifestLocation.repoType, manifestLocation.projectKey, manifestLocation.repositorySlug, manifestLocation.directory, manifestLocation.manifest, manifestLocation.ref ) } } } context("with some missing information in stage context") { test("uses trigger information to fill in the blanks") { val result = execute( manifestLocation.toMap().also { it.remove("projectKey") it.remove("repositorySlug") it.remove("ref") } ) expectThat(result.status).isEqualTo(SUCCEEDED) verify(exactly = 1) { scmService.getDeliveryConfigManifest( manifestLocation.repoType, (trigger as GitTrigger).project, trigger.slug, manifestLocation.directory, manifestLocation.manifest, trigger.hash ) } } } context("with no information in stage context") { test("uses trigger information and defaults to fill in the blanks") { val result = execute(mutableMapOf()) expectThat(result.status).isEqualTo(SUCCEEDED) verify(exactly = 1) { scmService.getDeliveryConfigManifest( (trigger as GitTrigger).source, trigger.project, trigger.slug, null, "spinnaker.yml", trigger.hash ) } } } } context("with detailed git info in payload field") { val trigger = objectMapper.readValue(javaClass.getResource("/trigger.json"), Trigger::class.java) fixture { Fixture( trigger ) } context("parsing git metadata") { test("parses correctly") { execute(mutableMapOf()) val submittedConfig = slot<DeliveryConfig>() verify(exactly = 1) { keelService.publishDeliveryConfig(capture(submittedConfig)) } val m: Any = submittedConfig.captured.getOrDefault("metadata", emptyMap<String, Any?>())!! val metadata: Map<String, Any?> = objectMapper.convertValue(m) expectThat(metadata["gitMetadata"]).isNotEqualTo(null) } } } context("additional error handling behavior") { fixture { Fixture( DefaultTrigger("manual") ) } context("manifest is not found") { modifyFixture { with(scmService) { every { getDeliveryConfigManifest( manifestLocation.repoType, manifestLocation.projectKey, manifestLocation.repositorySlug, manifestLocation.directory, manifestLocation.manifest, manifestLocation.ref ) } throws RetrofitError.httpError( "http://igor", Response("http://igor", 404, "", emptyList(), null), null, null ) } } test("task fails if manifest not found") { val result = execute(manifestLocation.toMap()) expectThat(result.status).isEqualTo(ExecutionStatus.TERMINAL) } } context("unauthorized access to manifest") { modifyFixture { with(scmService) { every { getDeliveryConfigManifest( manifestLocation.repoType, manifestLocation.projectKey, manifestLocation.repositorySlug, manifestLocation.directory, manifestLocation.manifest, manifestLocation.ref ) } throws RetrofitError.httpError( "http://igor", Response("http://igor", 401, "", emptyList(), null), null, null ) } } test("task fails with a helpful error message") { val result = execute(manifestLocation.toMap()) expectThat(result.status).isEqualTo(ExecutionStatus.TERMINAL) expectThat(result.context["error"]).isEqualTo(mapOf("message" to UNAUTHORIZED_SCM_ACCESS_MESSAGE)) } } context("keel access denied error") { modifyFixture { with(scmService) { every { getDeliveryConfigManifest( manifestLocation.repoType, manifestLocation.projectKey, manifestLocation.repositorySlug, manifestLocation.directory, manifestLocation.manifest, manifestLocation.ref ) } throws RetrofitError.httpError( "http://keel", Response( "http://keel", 403, "", emptyList(), JacksonConverter(objectMapper).toBody(accessDeniedError) as TypedInput ), null, null ) } } test("task fails and includes the error details returned by keel") { val result = execute(manifestLocation.toMap()) expectThat(result.status).isEqualTo(ExecutionStatus.TERMINAL) expectThat(result.context["error"]).isA<SpringHttpError>().isEqualTo(accessDeniedError) } } context("delivery config parsing error") { modifyFixture { with(scmService) { every { getDeliveryConfigManifest( manifestLocation.repoType, manifestLocation.projectKey, manifestLocation.repositorySlug, manifestLocation.directory, manifestLocation.manifest, manifestLocation.ref ) } throws RetrofitError.httpError( "http://keel", Response( "http://keel", 400, "", emptyList(), JacksonConverter(objectMapper).toBody(parsingError) as TypedInput ), null, null ) } } test("task fails and includes the error details returned by keel") { val result = execute(manifestLocation.toMap()) expectThat(result.status).isEqualTo(ExecutionStatus.TERMINAL) expectThat(result.context["error"]).isA<SpringHttpError>().isEqualTo(parsingError) } } context("retryable failure to call downstream services") { modifyFixture { with(scmService) { every { getDeliveryConfigManifest( manifestLocation.repoType, manifestLocation.projectKey, manifestLocation.repositorySlug, manifestLocation.directory, manifestLocation.manifest, manifestLocation.ref ) } throws RetrofitError.httpError( "http://igor", Response("http://igor", 503, "", emptyList(), null), null, null ) } } test("task retries if max retries not reached") { var result: TaskResult for (attempt in 1 until ImportDeliveryConfigTask.MAX_RETRIES) { result = execute(manifestLocation.toMap().also { it["attempt"] = attempt }) expectThat(result.status).isEqualTo(ExecutionStatus.RUNNING) expectThat(result.context["attempt"]).isEqualTo(attempt + 1) } } test("task fails if max retries reached") { val result = execute(manifestLocation.toMap().also { it["attempt"] = ImportDeliveryConfigTask.MAX_RETRIES }) expectThat(result.status).isEqualTo(ExecutionStatus.TERMINAL) } test("task result context includes the error from the last attempt") { var result: TaskResult? = null for (attempt in 1..ImportDeliveryConfigTask.MAX_RETRIES) { result = execute(manifestLocation.toMap().also { it["attempt"] = attempt }) } expectThat(result!!.context["errorFromLastAttempt"]).isNotNull() expectThat(result!!.context["error"] as String).contains(result!!.context["errorFromLastAttempt"] as String) } } } context("malformed input") { fixture { Fixture( trigger = DefaultTrigger("manual"), manifestLocation = ManifestLocation( repoType = "stash", projectKey = "SPKR", repositorySlug = "keeldemo", directory = ".", manifest = "", ref = "refs/heads/master" ) ) } test("successfully retrieves manifest from SCM and publishes to keel") { val result = execute(manifestLocation.toMap()) expectThat(result.status) isEqualTo SUCCEEDED verify(exactly = 1) { scmService.getDeliveryConfigManifest(any(), any(), any(), any(), "spinnaker.yml", any()) } } } } }
apache-2.0
5fe74217b3b41e59d8619e93f82fd2d1
33.132265
118
0.606505
4.899885
false
true
false
false
square/picasso
picasso-compose/src/main/java/com/squareup/picasso3/compose/PicassoPainter.kt
1
3477
/* * Copyright (C) 2022 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.squareup.picasso3.compose import android.graphics.drawable.Drawable import androidx.compose.runtime.Composable import androidx.compose.runtime.RememberObserver import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.geometry.Size import androidx.compose.ui.graphics.ColorFilter import androidx.compose.ui.graphics.DefaultAlpha import androidx.compose.ui.graphics.drawscope.DrawScope import androidx.compose.ui.graphics.painter.Painter import com.google.accompanist.drawablepainter.DrawablePainter import com.squareup.picasso3.DrawableTarget import com.squareup.picasso3.Picasso import com.squareup.picasso3.Picasso.LoadedFrom import com.squareup.picasso3.RequestCreator @Composable fun Picasso.rememberPainter( key: Any? = null, onError: ((Exception) -> Unit)? = null, request: (Picasso) -> RequestCreator, ): Painter { return remember(key) { PicassoPainter(this, request, onError) } } internal class PicassoPainter( private val picasso: Picasso, private val request: (Picasso) -> RequestCreator, private val onError: ((Exception) -> Unit)? = null ) : Painter(), RememberObserver, DrawableTarget { private var painter: Painter by mutableStateOf(EmptyPainter) private var alpha: Float by mutableStateOf(DefaultAlpha) private var colorFilter: ColorFilter? by mutableStateOf(null) override val intrinsicSize: Size get() = painter.intrinsicSize override fun applyAlpha(alpha: Float): Boolean { this.alpha = alpha return true } override fun applyColorFilter(colorFilter: ColorFilter?): Boolean { this.colorFilter = colorFilter return true } override fun DrawScope.onDraw() { with(painter) { draw(size, alpha, colorFilter) } } override fun onRemembered() { request.invoke(picasso).into(this) } override fun onAbandoned() { (painter as? RememberObserver)?.onAbandoned() painter = EmptyPainter picasso.cancelRequest(this) } override fun onForgotten() { (painter as? RememberObserver)?.onForgotten() painter = EmptyPainter picasso.cancelRequest(this) } override fun onPrepareLoad(placeHolderDrawable: Drawable?) { placeHolderDrawable?.let(::setPainter) } override fun onDrawableLoaded(drawable: Drawable, from: LoadedFrom) { setPainter(drawable) } override fun onDrawableFailed(e: Exception, errorDrawable: Drawable?) { onError?.invoke(e) errorDrawable?.let(::setPainter) } private fun setPainter(drawable: Drawable) { (painter as? RememberObserver)?.onForgotten() painter = DrawablePainter(drawable).apply(DrawablePainter::onRemembered) } } private object EmptyPainter : Painter() { override val intrinsicSize = Size.Zero override fun DrawScope.onDraw() = Unit }
apache-2.0
3b4f29a6effc7336d84912eb03215ba3
30.044643
76
0.756687
4.250611
false
false
false
false
GunoH/intellij-community
plugins/git4idea/src/git4idea/update/GitUpdateOptionsPanel.kt
9
1503
/* * Copyright 2000-2009 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 git4idea.update import com.intellij.openapi.ui.DialogPanel import com.intellij.ui.dsl.builder.bind import com.intellij.ui.dsl.builder.panel import com.intellij.util.ui.JBUI import git4idea.config.GitVcsSettings import git4idea.config.UpdateMethod internal class GitUpdateOptionsPanel(private val settings: GitVcsSettings) { val panel = createPanel() private fun createPanel(): DialogPanel = panel { buttonsGroup { getUpdateMethods().forEach { method -> row { radioButton(method.presentation, method) } } }.bind({ settings.updateMethod }, { settings.updateMethod = it }) }.withBorder(JBUI.Borders.empty(8, 8, 2, 8)) fun isModified(): Boolean = panel.isModified() fun applyTo() = panel.apply() fun updateFrom() = panel.reset() } internal fun getUpdateMethods(): List<UpdateMethod> = listOf(UpdateMethod.MERGE, UpdateMethod.REBASE)
apache-2.0
63c9a14ac0f86afc1f60ac0e8e2041ef
32.4
101
0.7332
4.151934
false
false
false
false
GunoH/intellij-community
plugins/full-line/src/org/jetbrains/completion/full/line/services/managers/MavenModelsManager.kt
2
2349
package org.jetbrains.completion.full.line.services.managers import com.intellij.lang.Language import com.intellij.openapi.components.service import com.intellij.openapi.util.registry.Registry import com.intellij.util.download.DownloadableFileService import com.intellij.util.io.HttpRequests import org.jetbrains.completion.full.line.local.MavenMetadata import org.jetbrains.completion.full.line.local.ModelSchema import org.jetbrains.completion.full.line.local.decodeFromXml import java.io.File class MavenModelsManager(private val root: File) : ModelsManager { private val cached: HashMap<String, ModelSchema> = HashMap() override fun getLatest(language: Language, force: Boolean): ModelSchema { return if (force || !cached.containsKey(language.id)) { val metadata = HttpRequests.request("${mavenHost(language)}/maven-metadata.xml").connect { r -> val content = r.reader.readText() decodeFromXml<MavenMetadata>(content) } val latest = if (Registry.`is`("full.line.local.models.beta")) { metadata.versioning.release } else { metadata.versioning.latest } HttpRequests.request("${mavenHost(language)}/$latest/model.xml").connect { r -> val content = r.reader.readText() decodeFromXml<ModelSchema>(content) }.also { cached[language.id] = it } } else { cached.getValue(language.id) } } override fun download(language: Language, force: Boolean): ModelSchema { val model = if (force || !cached.containsKey(language.id)) { getLatest(language, force) } else { cached.getValue(language.id) } val downloadableService = service<DownloadableFileService>() downloadableService.createDownloader( listOf(model.binary.path, model.bpe.path, model.config.path).map { downloadableService.createFileDescription("${mavenHost(language)}/${model.version}/${it}", it) }, "${language.displayName} model" ).download(root.resolve(model.uid())) return model } override fun update(language: Language, force: Boolean) = download(language, force) private fun mavenHost(language: Language): String { return "https://packages.jetbrains.team/maven/p/ccrm/flcc-local-models" + "/org/jetbrains/completion/full/line/local-model-${language.id.toLowerCase()}" } }
apache-2.0
86bf5c9da7b49ec6613439c60b01885f
35.703125
102
0.710089
4.128295
false
true
false
false
eyneill777/SpacePirates
core/src/rustyice/graphics/Camera.kt
1
1778
package rustyice.graphics import com.badlogic.gdx.math.MathUtils import rustyice.game.Actor /** * @author gabek */ class Camera { var target: Actor? var isTracking: Boolean var relativeRotation: Boolean var x: Float = 0f var y: Float = 0f private var _rotation: Float = 0f var targetX: Float = 0f var targetY: Float = 0f var targetRot: Float = 0f var width: Float = 0f var height: Float = 0f var halfRenderSize: Float = 0f var rotation: Float get() = _rotation set(value) { targetRot = value } constructor() { target = null isTracking = false relativeRotation = false } constructor(width: Float, height: Float): this(){ this.width = width this.height = height } fun setSize(width: Float, height: Float){ this.width = width this.height = height } fun update(delta: Float) { val target = target if (isTracking && target != null) { if (relativeRotation) { _rotation = target.rotation + targetRot } else { _rotation = targetRot } x += MathUtils.clamp(target.x - x, -.5f, .5f) y += MathUtils.clamp(target.y - y, -.5f, .5f) } else { _rotation = targetRot x = targetX y = targetY } } fun apply(ortho: com.badlogic.gdx.graphics.Camera) { ortho.position.x = this.x ortho.position.y = this.y ortho.viewportWidth = width ortho.viewportHeight = height ortho.up.set(MathUtils.cosDeg(this._rotation + 90), MathUtils.sinDeg(this._rotation + 90), 0f) ortho.direction.set(0f, 0f, -1f) } }
mit
9f5bd2516721a1a3c4c8abae55598b4a
23.356164
102
0.554556
3.873638
false
false
false
false
marius-m/wt4
components/src/main/java/lt/markmerkk/timecounter/WorkGoalReporterDay.kt
1
2657
package lt.markmerkk.timecounter import lt.markmerkk.entities.DateRange import org.joda.time.DateTime import org.joda.time.Duration class WorkGoalReporterDay( private val reporter: WorkGoalReporter, ) : WorkGoalReporter.ReporterDecorator { override fun reportLogged(durationLogged: Duration): String { return reporter.reportLogged(durationLogged) } override fun reportLoggedOngoing(durationLogged: Duration, durationOngoing: Duration): String { return reporter.reportLoggedWithOngoing(durationLogged, durationOngoing) } override fun reportPace( now: DateTime, displayDateRange: DateRange, durationWorked: Duration, ): String { return reporter.reportPaceDay(now, displayDateRange, durationWorked) } override fun reportShouldComplete( now: DateTime, displayDateRange: DateRange, durationWorked: Duration ): String { return reporter.reportDayShouldComplete(now, displayDateRange, durationWorked) } override fun reportGoal(dtTarget: DateTime, durationWorked: Duration): String { return reporter.reportDayGoalDuration(dtTarget, durationWorked) } override fun reportSchedule(dtTarget: DateTime): String { return reporter.reportDaySchedule(dtTarget) } override fun reportSummary( now: DateTime, displayDateRange: DateRange, durationWorkedDay: Duration, durationLogged: Duration, durationOngoing: Duration, ): String { val durationWorked = durationLogged .plus(durationOngoing) val reportTotal = if (durationOngoing == Duration.ZERO) { reportLogged(durationLogged) } else { reportLoggedOngoing( durationLogged = durationLogged, durationOngoing = durationOngoing, ) } val reportPace = reportPace(now, displayDateRange, durationWorked) val reportShouldComplete = reportShouldComplete(now, displayDateRange, durationWorked) val reportGoal = reportGoal( displayDateRange.selectDate.toDateTimeAtStartOfDay(), durationWorked, ) val reportSchedule = reportSchedule( displayDateRange.selectDate.toDateTimeAtStartOfDay(), ) val reports = listOf( "${reportTotal}\n", reportPace, reportShouldComplete, reportGoal, reportSchedule, ) val reportsAsString = reports .filter { it.isNotEmpty() } .joinToString(separator = "\n") return reportsAsString } }
apache-2.0
c167d611f414f88625cac94c3f274c27
32.225
99
0.662401
5.159223
false
false
false
false