content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
/*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.options
import com.eclipsesource.json.Json
import com.eclipsesource.json.JsonArray
import com.eclipsesource.json.JsonObject
import javafx.scene.input.DataFormat
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyCodeCombination
import javafx.scene.input.KeyCombination
import uk.co.nickthecoder.paratask.Tool
import uk.co.nickthecoder.paratask.JsonHelper
import java.io.Externalizable
import java.io.ObjectInput
import java.io.ObjectOutput
interface Option : Externalizable, Comparable<Option> {
var code: String
var aliases: MutableList<String>
var label: String
var isRow: Boolean
var isMultiple: Boolean
var refresh: Boolean
var newTab: Boolean
var prompt: Boolean
var shortcut: KeyCodeCombination?
fun run(tool: Tool, row: Any): Any?
fun runNonRow(tool: Tool): Any?
fun runMultiple(tool: Tool, rows: List<Any>): Any?
fun copy(): Option
fun toJson(): JsonObject {
val joption = JsonObject()
when (this) {
is GroovyOption -> {
joption.set("type", "groovy")
joption.set("script", script)
}
is TaskOption -> {
joption.set("type", "task")
joption.set("task", task.creationString())
}
else -> {
throw RuntimeException("Unknown Option : $javaClass")
}
}
with(joption) {
set("code", code)
set("label", label)
set("isRow", isRow)
set("isMultiple", isMultiple)
set("prompt", prompt)
set("newTab", newTab)
set("refresh", refresh)
shortcut?.let {
set("keyCode", it.code.toString())
saveModifier(joption, "shift", it.shift)
saveModifier(joption, "control", it.control)
saveModifier(joption, "alt", it.alt)
}
}
if (aliases.size > 0) {
val jaliases = JsonArray()
aliases.forEach { alias ->
jaliases.add(alias)
}
joption.add("aliases", jaliases)
}
if (this is TaskOption) {
val jparameters = JsonHelper.parametersAsJsonArray(task)
joption.add("parameters", jparameters)
}
return joption
}
override fun readExternal(input: ObjectInput) {
val jsonString = input.readObject() as String
val jsonObject = Json.parse(jsonString) as JsonObject
val option = fromJson(jsonObject)
code = option.code
aliases = option.aliases
label = option.label
isRow = option.isRow
isMultiple = option.isMultiple
refresh = option.refresh
newTab = option.newTab
prompt = option.prompt
shortcut = option.shortcut
if (this is TaskOption && option is TaskOption) {
task = option.task
}
if (this is GroovyOption && option is GroovyOption) {
script = option.script
}
}
override fun writeExternal(out: ObjectOutput) {
val jsonString = toJson().toString()
out.writeObject(jsonString)
}
companion object {
val dataFormat = DataFormat("application/x-java-paratask-option-list")
private fun saveModifier(joption: JsonObject, name: String, mod: KeyCombination.ModifierValue) {
if (mod != KeyCombination.ModifierValue.UP) {
joption.set(name, mod.toString())
}
}
fun fromJson(joption: JsonObject): Option {
val type = joption.getString("type", "groovy")
val option: Option
when (type) {
"groovy" -> {
option = GroovyOption(joption.getString("script", ""))
}
"task" -> {
option = TaskOption(joption.getString("task", ""))
}
else -> {
throw RuntimeException("Unknown option type : " + type)
}
}
with(option) {
code = joption.getString("code", "?")
label = joption.getString("label", "")
isRow = joption.getBoolean("isRow", false)
isMultiple = joption.getBoolean("isMultiple", false)
newTab = joption.getBoolean("newTab", false)
prompt = joption.getBoolean("prompt", false)
refresh = joption.getBoolean("refresh", false)
}
val keyCodeS = joption.getString("keyCode", "")
if (keyCodeS == "") {
option.shortcut = null
} else {
val keyCode = KeyCode.valueOf(keyCodeS)
val shiftS = joption.getString("shift", "UP")
val controlS = joption.getString("control", "UP")
val altS = joption.getString("alt", "UP")
val shift = KeyCombination.ModifierValue.valueOf(shiftS)
val control = KeyCombination.ModifierValue.valueOf(controlS)
val alt = KeyCombination.ModifierValue.valueOf(altS)
option.shortcut = KeyCodeCombination(keyCode, shift, control, alt, KeyCombination.ModifierValue.UP, KeyCombination.ModifierValue.UP)
}
val jaliases = joption.get("aliases")
jaliases?.let {
option.aliases = jaliases.asArray().map { it.asString() }.toMutableList()
}
// Load parameter values/expressions for TaskOption
if (option is TaskOption) {
val jparameters = joption.get("parameters").asArray()
JsonHelper.read(jparameters, option.task)
}
return option
}
}
override fun compareTo(other: Option): Int {
return this.label.compareTo(other.label)
}
}
| paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/options/Option.kt | 2425089850 |
package com.github.pgutkowski.kgraphql
import com.github.pgutkowski.kgraphql.schema.introspection.NotIntrospected
import kotlin.reflect.KClass
@NotIntrospected
class Context(private val map: Map<Any, Any>) {
operator fun <T : Any> get(kClass: KClass<T>): T? {
val value = map[kClass]
return if(kClass.isInstance(value)) value as T else null
}
inline fun <reified T : Any> get() : T? = get(T::class)
} | src/main/kotlin/com/github/pgutkowski/kgraphql/Context.kt | 3796653299 |
/*
* Copyright (C) 2017 Andrzej Ressel ([email protected])
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.jereksel.libresubstratum.activities.main
import com.jereksel.libresubstratum.data.InstalledTheme
import com.jereksel.libresubstratum.domain.IKeyFinder
import com.jereksel.libresubstratum.domain.IPackageManager
import com.jereksel.libresubstratum.domain.OverlayService
import com.jereksel.libresubstratum.presenters.PresenterTestUtils.initLiveData
import com.jereksel.libresubstratum.presenters.PresenterTestUtils.initRxJava
import com.jereksel.libresubstratum.utils.FutureUtils.toFuture
import com.nhaarman.mockito_kotlin.times
import com.nhaarman.mockito_kotlin.verify
import com.nhaarman.mockito_kotlin.whenever
import io.kotlintest.mock.mock
import io.kotlintest.specs.FunSpec
import kotlinx.coroutines.experimental.runBlocking
import org.assertj.core.api.Assertions.assertThat
import org.mockito.ArgumentMatchers.anyString
import org.mockito.Mock
import org.mockito.MockitoAnnotations
class MainViewViewModelTest: FunSpec() {
@Mock
lateinit var packageManager: IPackageManager
@Mock
lateinit var overlayService: OverlayService
@Mock
lateinit var keyFinder: IKeyFinder
lateinit var mainViewViewModel: MainViewViewModel
override fun beforeEach() {
MockitoAnnotations.initMocks(this)
mainViewViewModel = MainViewViewModel(packageManager, overlayService, keyFinder, mock())
initRxJava()
initLiveData()
}
init {
test("init doesn't call getInstalledThemes the second time") {
whenever(packageManager.getInstalledThemes()).thenReturn(listOf())
mainViewViewModel.init()
mainViewViewModel.init()
runBlocking {
mainViewViewModel.job.join()
}
verify(packageManager, times(1)).getInstalledThemes()
}
test("Values from PackageManager is passed to ObservableList") {
whenever(packageManager.getInstalledThemes()).thenReturn(listOf(
InstalledTheme("app1", "Theme 1", "", false, ""),
InstalledTheme("app2", "Theme 2", "", false, ""),
InstalledTheme("app3", "Theme 3", "", false, "")
))
whenever(packageManager.getHeroImage(anyString())).thenReturn(null.toFuture())
mainViewViewModel.init()
runBlocking {
mainViewViewModel.job.join()
}
assertThat(mainViewViewModel.getAppsObservable()).containsExactly(
MainViewModel("app1", "Theme 1", keyAvailable = false, heroImage = null),
MainViewModel("app2", "Theme 2", keyAvailable = false, heroImage = null),
MainViewModel("app3", "Theme 3", keyAvailable = false, heroImage = null)
)
}
test("When permissions are required they are passed to permissions live event") {
whenever(overlayService.requiredPermissions()).thenReturn(listOf("permission1", "permission2"))
runBlocking {
mainViewViewModel.tickChecks()
}
assertThat(mainViewViewModel.getPermissions().value).containsOnly(
"permission1", "permission2"
)
}
test("When permissions are not required and there is other message available it is shown") {
val message = "Dialog message"
whenever(overlayService.requiredPermissions()).thenReturn(listOf())
whenever(overlayService.additionalSteps()).thenReturn(message.toFuture())
runBlocking {
mainViewViewModel.tickChecks()
}
assertThat(mainViewViewModel.getPermissions().value).isNullOrEmpty()
assertThat(mainViewViewModel.getDialogContent().value).isEqualTo(message)
}
test("When permissions are not required and there are no messages nothing is passed") {
whenever(overlayService.requiredPermissions()).thenReturn(listOf())
whenever(overlayService.additionalSteps()).thenReturn(null.toFuture())
runBlocking {
mainViewViewModel.tickChecks()
}
assertThat(mainViewViewModel.getPermissions().value).isNullOrEmpty()
assertThat(mainViewViewModel.getDialogContent().value).isNullOrEmpty()
}
test("Reset removed apps and redownloads them") {
whenever(packageManager.getInstalledThemes()).thenReturn(listOf(
InstalledTheme("app1", "Theme 1", "", false, ""),
InstalledTheme("app2", "Theme 2", "", false, "")
))
whenever(packageManager.getHeroImage(anyString())).thenReturn(null.toFuture())
mainViewViewModel.init()
runBlocking {
mainViewViewModel.job.join()
}
assertThat(mainViewViewModel.getAppsObservable()).containsExactly(
MainViewModel("app1", "Theme 1", keyAvailable = false, heroImage = null),
MainViewModel("app2", "Theme 2", keyAvailable = false, heroImage = null)
)
whenever(packageManager.getInstalledThemes()).thenReturn(listOf(
InstalledTheme("app1", "Theme 1", "", false, ""),
InstalledTheme("app2", "Theme 2", "", false, ""),
InstalledTheme("app3", "Theme 3", "", false, "")
))
mainViewViewModel.reset()
//FIXME: Too flaky
// assertThat(mainViewViewModel.getSwipeToRefreshObservable().get()).isTrue()
runBlocking {
mainViewViewModel.job.join()
}
assertThat(mainViewViewModel.getAppsObservable()).containsExactly(
MainViewModel("app1", "Theme 1", keyAvailable = false, heroImage = null),
MainViewModel("app2", "Theme 2", keyAvailable = false, heroImage = null),
MainViewModel("app3", "Theme 3", keyAvailable = false, heroImage = null)
)
assertThat(mainViewViewModel.getSwipeToRefreshObservable().get()).isFalse()
}
}
}
| app/src/test/kotlin/com/jereksel/libresubstratum/activities/main/MainViewViewModelTest.kt | 3917045136 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.exceptions
import android.content.Context
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import kotlinx.android.synthetic.main.fragment_exceptions_domains.*
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import org.mozilla.focus.R
import org.mozilla.focus.settings.BaseSettingsFragment
import org.mozilla.focus.telemetry.TelemetryWrapper
class ExceptionsRemoveFragment : ExceptionsListFragment() {
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
inflater?.inflate(R.menu.menu_autocomplete_remove, menu)
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean = when (item?.itemId) {
R.id.remove -> {
removeSelectedDomains(activity!!.applicationContext)
true
}
else -> super.onOptionsItemSelected(item)
}
private fun removeSelectedDomains(context: Context) {
val domains = (exceptionList.adapter as DomainListAdapter).selection()
TelemetryWrapper.removeExceptionDomains(domains.size)
if (domains.isNotEmpty()) {
launch(Main) {
async {
ExceptionDomains.remove(context, domains)
}.await()
fragmentManager!!.popBackStack()
}
}
}
override fun isSelectionMode() = true
override fun onResume() {
super.onResume()
val updater = activity as BaseSettingsFragment.ActionBarUpdater
updater.updateTitle(R.string.preference_autocomplete_title_remove)
updater.updateIcon(R.drawable.ic_back)
}
}
| app/src/main/java/org/mozilla/focus/exceptions/ExceptionsRemoveFragment.kt | 2311093717 |
/*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
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.thomas.needham.neurophidea.designer.editor.nnet
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.vfs.VirtualFile
import com.thomas.needham.neurophidea.actions.InitialisationAction
import org.neuroph.core.NeuralNetwork
import java.io.*
/**
* Created by Thomas Needham on 09/06/2016.
*/
class NnetLoader {
val file: VirtualFile?
constructor(file: VirtualFile?) {
this.file = file
}
fun LoadNetwork(): NeuralNetwork? {
try {
val f = File(file?.path)
val fis: FileInputStream? = f.inputStream()
val ois: ObjectInputStream? = ObjectInputStream(fis)
return ois?.readObject() as NeuralNetwork?
} catch (ioe: IOException) {
ioe.printStackTrace(System.err)
Messages.showErrorDialog(InitialisationAction.project, "Error Loading Network From File", "Error")
} catch (fnfe: FileNotFoundException) {
fnfe.printStackTrace(System.err)
Messages.showErrorDialog(InitialisationAction.project, "No network found in file: ${file?.path}", "Error")
}
return null
}
} | neuroph-plugin/src/com/thomas/needham/neurophidea/designer/editor/nnet/NnetLoader.kt | 2808269769 |
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package org.jetbrains.kotlin.cli.utilities
import org.jetbrains.kotlin.cli.bc.SHORT_MODULE_NAME_ARG
import org.jetbrains.kotlin.konan.file.File
import org.jetbrains.kotlin.konan.target.PlatformManager
import org.jetbrains.kotlin.konan.util.KonanHomeProvider
import org.jetbrains.kotlin.native.interop.gen.jvm.InternalInteropOptions
import org.jetbrains.kotlin.native.interop.gen.jvm.interop
import org.jetbrains.kotlin.native.interop.tool.*
// TODO: this function should eventually be eliminated from 'utilities'.
// The interaction of interop and the compiler should be streamlined.
/**
* @return null if there is no need in compiler invocation.
* Otherwise returns array of compiler args.
*/
fun invokeInterop(flavor: String, args: Array<String>): Array<String>? {
val arguments = if (flavor == "native") CInteropArguments() else JSInteropArguments()
arguments.argParser.parse(args)
val outputFileName = arguments.output
val noDefaultLibs = arguments.nodefaultlibs || arguments.nodefaultlibsDeprecated
val noEndorsedLibs = arguments.noendorsedlibs
val purgeUserLibs = arguments.purgeUserLibs
val nopack = arguments.nopack
val temporaryFilesDir = arguments.tempDir
val moduleName = (arguments as? CInteropArguments)?.moduleName
val shortModuleName = (arguments as? CInteropArguments)?.shortModuleName
val buildDir = File("$outputFileName-build")
val generatedDir = File(buildDir, "kotlin")
val nativesDir = File(buildDir,"natives")
val manifest = File(buildDir, "manifest.properties")
val cstubsName ="cstubs"
val libraries = arguments.library
val repos = arguments.repo
val targetRequest = if (arguments is CInteropArguments) arguments.target
else (arguments as JSInteropArguments).target
val target = PlatformManager(KonanHomeProvider.determineKonanHome()).targetManager(targetRequest).target
val cinteropArgsToCompiler = interop(flavor, args,
InternalInteropOptions(generatedDir.absolutePath,
nativesDir.absolutePath,manifest.path,
cstubsName.takeIf { flavor == "native" }
)
) ?: return null // There is no need in compiler invocation if we're generating only metadata.
val nativeStubs =
if (flavor == "wasm")
arrayOf("-include-binary", File(nativesDir, "js_stubs.js").path)
else
arrayOf("-native-library", File(nativesDir, "$cstubsName.bc").path)
return arrayOf(
generatedDir.path,
"-produce", "library",
"-o", outputFileName,
"-target", target.visibleName,
"-manifest", manifest.path,
"-Xtemporary-files-dir=$temporaryFilesDir") +
nativeStubs +
cinteropArgsToCompiler +
libraries.flatMap { listOf("-library", it) } +
repos.flatMap { listOf("-repo", it) } +
(if (noDefaultLibs) arrayOf("-$NODEFAULTLIBS") else emptyArray()) +
(if (noEndorsedLibs) arrayOf("-$NOENDORSEDLIBS") else emptyArray()) +
(if (purgeUserLibs) arrayOf("-$PURGE_USER_LIBS") else emptyArray()) +
(if (nopack) arrayOf("-$NOPACK") else emptyArray()) +
moduleName?.let { arrayOf("-module-name", it) }.orEmpty() +
shortModuleName?.let { arrayOf("$SHORT_MODULE_NAME_ARG=$it") }.orEmpty() +
arguments.kotlincOption
}
| utilities/cli-runner/src/main/kotlin/org/jetbrains/kotlin/cli/utilities/InteropCompiler.kt | 2717983641 |
package net.nemerosa.ontrack.extension.indicators.portfolio
import net.nemerosa.ontrack.extension.indicators.acl.IndicatorPortfolioManagement
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategory
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategoryListener
import net.nemerosa.ontrack.extension.indicators.model.IndicatorCategoryService
import net.nemerosa.ontrack.model.labels.Label
import net.nemerosa.ontrack.model.labels.LabelManagementService
import net.nemerosa.ontrack.model.labels.ProjectLabelManagementService
import net.nemerosa.ontrack.model.security.SecurityService
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.StructureService
import net.nemerosa.ontrack.model.support.StorageService
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
@Service
@Transactional
class IndicatorPortfolioServiceImpl(
private val structureService: StructureService,
private val securityService: SecurityService,
private val storageService: StorageService,
private val labelManagementService: LabelManagementService,
private val projectLabelManagementService: ProjectLabelManagementService,
private val indicatorCategoryService: IndicatorCategoryService
) : IndicatorPortfolioService, IndicatorCategoryListener {
init {
indicatorCategoryService.registerCategoryListener(this)
}
override fun onCategoryDeleted(category: IndicatorCategory) {
findAll().forEach { portfolio ->
if (category.id in portfolio.categories) {
val newCategories = portfolio.categories - category.id
updatePortfolio(
portfolio.id,
PortfolioUpdateForm(
categories = newCategories
)
)
}
}
}
override fun createPortfolio(id: String, name: String): IndicatorPortfolio {
securityService.checkGlobalFunction(IndicatorPortfolioManagement::class.java)
val existing = findPortfolioById(id)
if (existing != null) {
throw IndicatorPortfolioIdAlreadyExistingException(id)
} else {
val portfolio = IndicatorPortfolio(
id = id,
name = name,
label = null,
categories = emptyList()
)
storageService.store(STORE, id, portfolio)
return portfolio
}
}
override fun updatePortfolio(id: String, input: PortfolioUpdateForm): IndicatorPortfolio {
securityService.checkGlobalFunction(IndicatorPortfolioManagement::class.java)
val existing = findPortfolioById(id) ?: throw IndicatorPortfolioNotFoundException(id)
val name = if (!input.name.isNullOrBlank()) {
input.name
} else {
existing.name
}
val label = input.label ?: existing.label
val categories = input.categories ?: existing.categories
val newRecord = IndicatorPortfolio(
id = id,
name = name,
label = label,
categories = categories
)
storageService.store(STORE, id, newRecord)
return newRecord
}
override fun deletePortfolio(id: String) {
securityService.checkGlobalFunction(IndicatorPortfolioManagement::class.java)
storageService.delete(STORE, id)
}
override fun getPortfolioLabel(portfolio: IndicatorPortfolio): Label? =
portfolio.label?.let {
labelManagementService.findLabelById(it)
}
override fun getPortfolioProjects(portfolio: IndicatorPortfolio): List<Project> =
getPortfolioLabel(portfolio)?.let { label ->
projectLabelManagementService.getProjectsForLabel(label)
}?.map {
structureService.getProject(it)
} ?: emptyList()
override fun findPortfolioById(id: String): IndicatorPortfolio? {
return storageService.retrieve(STORE, id, IndicatorPortfolio::class.java).orElse(null)
}
override fun findAll(): List<IndicatorPortfolio> {
return storageService.getKeys(STORE).mapNotNull { key ->
storageService.retrieve(STORE, key, IndicatorPortfolio::class.java).orElse(null)
}.sortedBy { it.name }
}
override fun getPortfolioOfPortfolios(): IndicatorPortfolioOfPortfolios {
// Checks we have access to the projects
structureService.projectList
return storageService.retrieve(STORE_PORTFOLIO_OF_PORTFOLIOS, PORTFOLIO_OF_PORTFOLIOS, IndicatorPortfolioOfPortfolios::class.java)
.orElse(IndicatorPortfolioOfPortfolios(
categories = emptyList()
))
}
override fun savePortfolioOfPortfolios(input: PortfolioGlobalIndicators): IndicatorPortfolioOfPortfolios {
val portfolio = IndicatorPortfolioOfPortfolios(
input.categories.filter {
indicatorCategoryService.findCategoryById(it) != null
}
)
storageService.store(STORE_PORTFOLIO_OF_PORTFOLIOS, PORTFOLIO_OF_PORTFOLIOS, portfolio)
return portfolio
}
override fun findPortfolioByProject(project: Project): List<IndicatorPortfolio> {
// Gets the labels for this project
val labels = projectLabelManagementService.getLabelsForProject(project).map { it.id }.toSet()
// Gets all portfolios and filter on label
return if (labels.isEmpty()) {
emptyList()
} else {
findAll().filter { portfolio ->
portfolio.label != null && portfolio.label in labels
}
}
}
companion object {
private val STORE = IndicatorPortfolio::class.java.name
@Deprecated("Use views")
private val STORE_PORTFOLIO_OF_PORTFOLIOS = IndicatorPortfolioOfPortfolios::class.java.name
@Deprecated("Use views")
private const val PORTFOLIO_OF_PORTFOLIOS = "0"
}
} | ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/portfolio/IndicatorPortfolioServiceImpl.kt | 599540328 |
package net.nemerosa.ontrack.extension.general.validation
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.extension.general.GeneralExtensionFeature
import net.nemerosa.ontrack.json.getInt
import net.nemerosa.ontrack.json.getRequiredEnum
import net.nemerosa.ontrack.json.parse
import net.nemerosa.ontrack.json.toJson
import net.nemerosa.ontrack.model.form.Form
import net.nemerosa.ontrack.model.form.selection
import net.nemerosa.ontrack.model.structure.AbstractValidationDataType
import net.nemerosa.ontrack.model.structure.NumericValidationDataType
import net.nemerosa.ontrack.model.structure.ValidationRunStatusID
import org.springframework.stereotype.Component
import net.nemerosa.ontrack.model.form.Int as IntField
/**
* Validation data based on the critical / high / medium / low numbers.
*/
@Component
class CHMLValidationDataType(
extensionFeature: GeneralExtensionFeature,
) : AbstractValidationDataType<CHMLValidationDataTypeConfig, CHMLValidationDataTypeData>(
extensionFeature
), NumericValidationDataType<CHMLValidationDataTypeConfig, CHMLValidationDataTypeData> {
override val displayName = "Critical / high / medium / low"
override fun configToJson(config: CHMLValidationDataTypeConfig) = config.toJson()!!
override fun configFromJson(node: JsonNode?): CHMLValidationDataTypeConfig? = node?.parse()
override fun getConfigForm(config: CHMLValidationDataTypeConfig?): Form =
Form.create()
.with(
selection<CHML>("failedLevel", CHML::displayName)
.label("Failed if")
.value(config?.failedLevel?.level)
)
.with(
IntField.of("failedValue")
.label("greater or equal than")
.min(0)
.value(config?.failedLevel?.value ?: 0)
)
.with(
selection<CHML>("warningLevel", CHML::displayName)
.label("Warning if")
.value(config?.warningLevel?.level)
)
.with(
IntField.of("warningValue")
.label("greater or equal than")
.min(0)
.value(config?.warningLevel?.value ?: 0)
)
override fun configToFormJson(config: CHMLValidationDataTypeConfig?) =
config?.let {
mapOf(
"failedLevel" to it.failedLevel.level,
"failedValue" to it.failedLevel.value,
"warningLevel" to it.warningLevel.level,
"warningValue" to it.warningLevel.value
).toJson()
}
override fun fromConfigForm(node: JsonNode?) =
node?.let {
CHMLValidationDataTypeConfig(
warningLevel = CHMLLevel(
node.getRequiredEnum("warningLevel"),
node.getInt("warningValue") ?: 0
),
failedLevel = CHMLLevel(
node.getRequiredEnum("failedLevel"),
node.getInt("failedValue") ?: 0
)
)
}
override fun toJson(data: CHMLValidationDataTypeData) = data.toJson()!!
override fun fromJson(node: JsonNode): CHMLValidationDataTypeData = node.parse()
override fun getForm(data: CHMLValidationDataTypeData?): Form =
Form.create()
.with(
CHML.values().map {
IntField.of(it.name)
.label(it.displayName)
.optional()
.min(0)
.value(data?.levels?.get(it) ?: 0)
}
)
override fun fromForm(node: JsonNode?): CHMLValidationDataTypeData? =
node?.let {
CHMLValidationDataTypeData(
CHML.values().associate {
it to (node.getInt(it.name) ?: 0)
}
)
}
override fun computeStatus(
config: CHMLValidationDataTypeConfig?,
data: CHMLValidationDataTypeData,
): ValidationRunStatusID? {
if (config != null) {
if (config.failedLevel.value > 0) {
if ((data.levels[config.failedLevel.level] ?: 0) >= config.failedLevel.value) {
return ValidationRunStatusID.STATUS_FAILED
}
}
if (config.warningLevel.value > 0) {
if ((data.levels[config.warningLevel.level] ?: 0) >= config.warningLevel.value) {
return ValidationRunStatusID.STATUS_WARNING
}
}
return ValidationRunStatusID.STATUS_PASSED
} else {
return null
}
}
override fun validateData(config: CHMLValidationDataTypeConfig?, data: CHMLValidationDataTypeData?) =
validateNotNull(data) {
CHML.values().forEach {
val value = levels[it]
if (value != null) {
validate(value >= 0, "Value for ${it} must be >= 0")
}
}
}
override fun getMetrics(data: CHMLValidationDataTypeData): Map<String, *>? {
return mapOf(
"critical" to (data.levels[CHML.CRITICAL] ?: 0),
"high" to (data.levels[CHML.HIGH] ?: 0),
"medium" to (data.levels[CHML.MEDIUM] ?: 0),
"low" to (data.levels[CHML.LOW] ?: 0)
)
}
override fun getNumericMetrics(data: CHMLValidationDataTypeData): Map<String, Double> {
return mapOf(
"critical" to (data.levels[CHML.CRITICAL] ?: 0).toDouble(),
"high" to (data.levels[CHML.HIGH] ?: 0).toDouble(),
"medium" to (data.levels[CHML.MEDIUM] ?: 0).toDouble(),
"low" to (data.levels[CHML.LOW] ?: 0).toDouble()
)
}
}
data class CHMLValidationDataTypeData(
val levels: Map<CHML, Int>,
)
data class CHMLValidationDataTypeConfig(
val warningLevel: CHMLLevel,
val failedLevel: CHMLLevel,
)
data class CHMLLevel(
val level: CHML,
val value: Int,
) {
init {
if (value < 0) throw IllegalArgumentException("Value must be >= 0")
}
}
enum class CHML(val displayName: String) {
CRITICAL("Critical"),
HIGH("High"),
MEDIUM("Medium"),
LOW("Low")
}
| ontrack-extension-general/src/main/java/net/nemerosa/ontrack/extension/general/validation/CHMLValidationDataType.kt | 3350730293 |
package com.jraska.github.client.users.model
import androidx.annotation.Keep
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
@Keep
internal class GitHubUserRepo {
@SerializedName("id")
@Expose
var id: Int? = null
@SerializedName("name")
@Expose
var name: String? = null
@SerializedName("owner")
@Expose
var owner: GitHubUser? = null
@SerializedName("html_url")
@Expose
var description: String? = null
@SerializedName("stargazers_count")
@Expose
var stargazersCount: Int? = null
@SerializedName("forks")
@Expose
var forks: Int? = null
}
| feature/users/src/main/java/com/jraska/github/client/users/model/GitHubUserRepo.kt | 1140396081 |
/*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.upnp.internal.server
import net.mm2d.upnp.Http
import net.mm2d.upnp.SsdpMessage
import net.mm2d.upnp.log.Logger
import java.io.IOException
import java.net.InetAddress
import java.net.URL
internal val DEFAULT_SSDP_MESSAGE_FILTER: (SsdpMessage) -> Boolean = { true }
/**
* A normal URL is described in the Location of SsdpMessage,
* and it is checked whether there is a mismatch between the description address and the packet source address.
*
* @receiver SsdpMessage to check
* @param sourceAddress source address
* @return true: if there is an invalid Location, such as a mismatch with the sender. false: otherwise
*/
internal fun SsdpMessage.hasInvalidLocation(sourceAddress: InetAddress): Boolean =
(!hasValidLocation(sourceAddress)).also {
if (it) Logger.w { "Location: $location is invalid from $sourceAddress" }
}
private fun SsdpMessage.hasValidLocation(sourceAddress: InetAddress): Boolean {
val location = location ?: return false
if (!Http.isHttpUrl(location)) return false
try {
return sourceAddress == InetAddress.getByName(URL(location).host)
} catch (ignored: IOException) {
}
return false
}
internal fun SsdpMessage.isNotUpnp(): Boolean {
if (getHeader("X-TelepathyAddress.sony.com") != null) {
// Sony telepathy service(urn:schemas-sony-com:service:X_Telepathy:1) send ssdp packet,
// but its location address refuses connection. Since this is not correct as UPnP, ignore it.
Logger.v("ignore sony telepathy service")
return true
}
return false
}
| mmupnp/src/main/java/net/mm2d/upnp/internal/server/SsdpMessageValidator.kt | 123103691 |
package com.google.firebase.quickstart.auth.kotlin
import android.content.Intent
import android.os.Bundle
import com.google.android.material.snackbar.Snackbar
import android.util.Log
import android.view.View
import com.google.android.gms.auth.api.signin.GoogleSignIn
import com.google.android.gms.auth.api.signin.GoogleSignInClient
import com.google.android.gms.auth.api.signin.GoogleSignInOptions
import com.google.android.gms.common.api.ApiException
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.google.firebase.auth.GoogleAuthProvider
import com.google.firebase.auth.ktx.auth
import com.google.firebase.ktx.Firebase
import com.google.firebase.quickstart.auth.R
import com.google.firebase.quickstart.auth.databinding.ActivityGoogleBinding
/**
* Demonstrate Firebase Authentication using a Google ID Token.
*/
class GoogleSignInActivity : BaseActivity(), View.OnClickListener {
// [START declare_auth]
private lateinit var auth: FirebaseAuth
// [END declare_auth]
private lateinit var binding: ActivityGoogleBinding
private lateinit var googleSignInClient: GoogleSignInClient
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityGoogleBinding.inflate(layoutInflater)
setContentView(binding.root)
setProgressBar(binding.progressBar)
// Button listeners
binding.signInButton.setOnClickListener(this)
binding.signOutButton.setOnClickListener(this)
binding.disconnectButton.setOnClickListener(this)
// [START config_signin]
// Configure Google Sign In
val gso = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.default_web_client_id))
.requestEmail()
.build()
// [END config_signin]
googleSignInClient = GoogleSignIn.getClient(this, gso)
// [START initialize_auth]
// Initialize Firebase Auth
auth = Firebase.auth
// [END initialize_auth]
}
// [START on_start_check_user]
override fun onStart() {
super.onStart()
// Check if user is signed in (non-null) and update UI accordingly.
val currentUser = auth.currentUser
updateUI(currentUser)
}
// [END on_start_check_user]
// [START onactivityresult]
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
val task = GoogleSignIn.getSignedInAccountFromIntent(data)
try {
// Google Sign In was successful, authenticate with Firebase
val account = task.getResult(ApiException::class.java)!!
Log.d(TAG, "firebaseAuthWithGoogle:" + account.id)
firebaseAuthWithGoogle(account.idToken!!)
} catch (e: ApiException) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e)
// [START_EXCLUDE]
updateUI(null)
// [END_EXCLUDE]
}
}
}
// [END onactivityresult]
// [START auth_with_google]
private fun firebaseAuthWithGoogle(idToken: String) {
// [START_EXCLUDE silent]
showProgressBar()
// [END_EXCLUDE]
val credential = GoogleAuthProvider.getCredential(idToken, null)
auth.signInWithCredential(credential)
.addOnCompleteListener(this) { task ->
if (task.isSuccessful) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success")
val user = auth.currentUser
updateUI(user)
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.exception)
// [START_EXCLUDE]
val view = binding.mainLayout
// [END_EXCLUDE]
Snackbar.make(view, "Authentication Failed.", Snackbar.LENGTH_SHORT).show()
updateUI(null)
}
// [START_EXCLUDE]
hideProgressBar()
// [END_EXCLUDE]
}
}
// [END auth_with_google]
// [START signin]
private fun signIn() {
val signInIntent = googleSignInClient.signInIntent
startActivityForResult(signInIntent, RC_SIGN_IN)
}
// [END signin]
private fun signOut() {
// Firebase sign out
auth.signOut()
// Google sign out
googleSignInClient.signOut().addOnCompleteListener(this) {
updateUI(null)
}
}
private fun revokeAccess() {
// Firebase sign out
auth.signOut()
// Google revoke access
googleSignInClient.revokeAccess().addOnCompleteListener(this) {
updateUI(null)
}
}
private fun updateUI(user: FirebaseUser?) {
hideProgressBar()
if (user != null) {
binding.status.text = getString(R.string.google_status_fmt, user.email)
binding.detail.text = getString(R.string.firebase_status_fmt, user.uid)
binding.signInButton.visibility = View.GONE
binding.signOutAndDisconnect.visibility = View.VISIBLE
} else {
binding.status.setText(R.string.signed_out)
binding.detail.text = null
binding.signInButton.visibility = View.VISIBLE
binding.signOutAndDisconnect.visibility = View.GONE
}
}
override fun onClick(v: View) {
when (v.id) {
R.id.signInButton -> signIn()
R.id.signOutButton -> signOut()
R.id.disconnectButton -> revokeAccess()
}
}
companion object {
private const val TAG = "GoogleActivity"
private const val RC_SIGN_IN = 9001
}
}
| auth/app/src/main/java/com/google/firebase/quickstart/auth/kotlin/GoogleSignInActivity.kt | 2445940772 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.materialstudies.reply.ui.email
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.GridLayoutManager
import com.materialstudies.reply.data.EmailStore
import com.materialstudies.reply.databinding.FragmentEmailBinding
import kotlin.LazyThreadSafetyMode.NONE
private const val MAX_GRID_SPANS = 3
/**
* A [Fragment] which displays a single, full email.
*/
class EmailFragment : Fragment() {
private val args: EmailFragmentArgs by navArgs()
private val emailId: Long by lazy(NONE) { args.emailId }
private lateinit var binding: FragmentEmailBinding
private val attachmentAdapter = EmailAttachmentGridAdapter(MAX_GRID_SPANS)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// TODO: Set up MaterialContainerTransform transition as sharedElementEnterTransition.
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentEmailBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.navigationIcon.setOnClickListener {
findNavController().navigateUp()
}
val email = EmailStore.get(emailId)
if (email == null) {
showError()
return
}
binding.run {
this.email = email
// Set up the staggered/masonry grid recycler
attachmentRecyclerView.layoutManager = GridLayoutManager(
requireContext(),
MAX_GRID_SPANS
).apply {
spanSizeLookup = attachmentAdapter.variableSpanSizeLookup
}
attachmentRecyclerView.adapter = attachmentAdapter
attachmentAdapter.submitList(email.attachments)
}
}
private fun showError() {
// Do nothing
}
} | app/src/main/java/com/materialstudies/reply/ui/email/EmailFragment.kt | 625847329 |
//
// (C) Copyright 2018-2019 Martin E. Nordberg III
// Apache 2.0 License
//
package o.katydid.css.stylesheets
//---------------------------------------------------------------------------------------------------------------------
/**
* A rule of any type (at-rule or style rule) in a style sheet, or the style sheet itself.
*/
interface KatydidCssRule {
/** The parent rule containing this rule. */
val parent: KatydidCompositeCssRule
////
/** Makes a copy of this rule, placing the copy as a child of [parentOfCopy]. */
fun copy(parentOfCopy: KatydidCompositeCssRule): KatydidCssRule
/** Converts this rule to CSS. */
fun toCssString(indent: Int = 0): String
}
//---------------------------------------------------------------------------------------------------------------------
| Katydid-CSS-JS/src/main/kotlin/o/katydid/css/stylesheets/KatydidCssRule.kt | 1200415135 |
package app.cash.sqldelight.tests
import app.cash.sqldelight.gradle.SqlDelightCompilationUnitImpl
import app.cash.sqldelight.gradle.SqlDelightDatabasePropertiesImpl
import app.cash.sqldelight.gradle.SqlDelightSourceFolderImpl
import app.cash.sqldelight.withTemporaryFixture
import com.google.common.truth.Truth.assertThat
import org.junit.Test
import java.io.File
class CompilationUnitTests {
@Test
fun `JVM kotlin`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'org.jetbrains.kotlin.jvm'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).hasSize(1)
val database = properties.databases[0]
assertThat(database.className).isEqualTo("CommonDb")
assertThat(database.packageName).isEqualTo("com.sample")
assertThat(database.compilationUnits).containsExactly(
SqlDelightCompilationUnitImpl(
name = "main",
sourceFolders = listOf(SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false)),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb"),
),
)
}
}
}
@Test
fun `JVM kotlin with multiple databases`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'org.jetbrains.kotlin.jvm'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|
| OtherDb {
| packageName = "com.sample.otherdb"
| sourceFolders = ["sqldelight", "otherdb"]
| treatNullAsUnknownForEquality = true
| }
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).containsExactly(
SqlDelightDatabasePropertiesImpl(
className = "CommonDb",
packageName = "com.sample",
compilationUnits = listOf(
SqlDelightCompilationUnitImpl(
name = "main",
sourceFolders = listOf(SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false)),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb"),
),
),
dependencies = emptyList(),
rootDirectory = fixtureRoot,
),
SqlDelightDatabasePropertiesImpl(
className = "OtherDb",
packageName = "com.sample.otherdb",
compilationUnits = listOf(
SqlDelightCompilationUnitImpl(
name = "main",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/otherdb"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/OtherDb"),
),
),
dependencies = emptyList(),
rootDirectory = fixtureRoot,
treatNullAsUnknownForEquality = true,
),
)
}
}
}
@Test
fun `Multiplatform project with multiple targets`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'org.jetbrains.kotlin.multiplatform'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|}
|
|kotlin {
| targetFromPreset(presets.jvm, 'jvm')
| targetFromPreset(presets.js, 'js')
| targetFromPreset(presets.iosArm32, 'iosArm32')
| targetFromPreset(presets.iosArm64, 'iosArm64')
| targetFromPreset(presets.iosX64, 'iosX64')
| targetFromPreset(presets.macosX64, 'macosX64')
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).hasSize(1)
val database = properties.databases[0]
assertThat(database.className).isEqualTo("CommonDb")
assertThat(database.packageName).isEqualTo("com.sample")
assertThat(database.compilationUnits).containsExactly(
SqlDelightCompilationUnitImpl(
name = "commonMain",
sourceFolders = listOf(SqlDelightSourceFolderImpl(File(fixtureRoot, "src/commonMain/sqldelight"), false)),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb"),
),
)
}
}
}
@Test
fun `Multiplatform project with android and ios targets`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'org.jetbrains.kotlin.multiplatform'
|apply plugin: 'com.android.application'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|}
|
|android {
| compileSdk libs.versions.compileSdk.get() as int
|
| buildTypes {
| release {}
| sqldelight {}
| }
|
| flavorDimensions "api", "mode"
|
| productFlavors {
| demo {
| applicationIdSuffix ".demo"
| dimension "mode"
| }
| full {
| applicationIdSuffix ".full"
| dimension "mode"
| }
| minApi21 {
| dimension "api"
| }
| minApi23 {
| dimension "api"
| }
| }
|}
|
|kotlin {
| targetFromPreset(presets.iosX64, 'iosX64')
| targetFromPreset(presets.android, 'androidLib')
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).hasSize(1)
val database = properties.databases[0]
assertThat(database.className).isEqualTo("CommonDb")
assertThat(database.packageName).isEqualTo("com.sample")
assertThat(database.compilationUnits).containsExactly(
SqlDelightCompilationUnitImpl(
name = "commonMain",
sourceFolders = listOf(SqlDelightSourceFolderImpl(File(fixtureRoot, "src/commonMain/sqldelight"), false)),
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb"),
),
)
}
}
}
@Test
fun `android project with multiple flavors`() {
withTemporaryFixture {
gradleFile(
"""
|buildscript {
| apply from: "${"$"}{projectDir.absolutePath}/../buildscript.gradle"
|}
|
|apply plugin: 'com.android.application'
|apply plugin: 'org.jetbrains.kotlin.android'
|apply plugin: 'app.cash.sqldelight'
|
|repositories {
| maven {
| url "file://${"$"}{rootDir}/../../../../build/localMaven"
| }
|}
|
|sqldelight {
| CommonDb {
| packageName = "com.sample"
| }
|}
|
|android {
| compileSdk libs.versions.compileSdk.get() as int
|
| buildTypes {
| release {}
| sqldelight {}
| }
|
| flavorDimensions "api", "mode"
|
| productFlavors {
| demo {
| applicationIdSuffix ".demo"
| dimension "mode"
| }
| full {
| applicationIdSuffix ".full"
| dimension "mode"
| }
| minApi21 {
| dimension "api"
| }
| minApi23 {
| dimension "api"
| }
| }
|}
""".trimMargin(),
)
properties().let { properties ->
assertThat(properties.databases).hasSize(1)
val database = properties.databases[0]
assertThat(database.className).isEqualTo("CommonDb")
assertThat(database.packageName).isEqualTo("com.sample")
assertThat(database.compilationUnits).containsExactly(
SqlDelightCompilationUnitImpl(
name = "minApi23DemoDebug",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23DemoDebug/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23DemoDebug"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23DemoRelease",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23DemoRelease/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23DemoRelease"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23DemoSqldelight",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23DemoSqldelight/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/sqldelight/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23DemoSqldelight"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23FullDebug",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23FullDebug/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23FullDebug"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23FullRelease",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23FullRelease/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23FullRelease"),
),
SqlDelightCompilationUnitImpl(
name = "minApi23FullSqldelight",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi23FullSqldelight/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/sqldelight/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi23FullSqldelight"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21DemoDebug",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21DemoDebug/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21DemoDebug"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21DemoRelease",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21DemoRelease/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21DemoRelease"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21DemoSqldelight",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Demo/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21DemoSqldelight/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/sqldelight/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21DemoSqldelight"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21FullDebug",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/debug/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21FullDebug/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21FullDebug"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21FullRelease",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21FullRelease/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/release/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21FullRelease"),
),
SqlDelightCompilationUnitImpl(
name = "minApi21FullSqldelight",
sourceFolders = listOf(
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/main/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21Full/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/minApi21FullSqldelight/sqldelight"), false),
SqlDelightSourceFolderImpl(File(fixtureRoot, "src/sqldelight/sqldelight"), false),
).sortedBy { it.folder.absolutePath },
outputDirectoryFile = File(fixtureRoot, "build/generated/sqldelight/code/CommonDb/minApi21FullSqldelight"),
),
)
}
}
}
}
| sqldelight-gradle-plugin/src/test/kotlin/app/cash/sqldelight/tests/CompilationUnitTests.kt | 2434945352 |
/****************************************************************************************
* Copyright (c) 2015 Timothy Rae <[email protected]> *
* *
* This program is free software; you can redistribute it and/or modify it under *
* the terms of the GNU General Public License as published by the Free Software *
* Foundation; either version 3 of the License, or (at your option) any later *
* version. *
* *
* This program is distributed in the hope that it will be useful, but WITHOUT ANY *
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A *
* PARTICULAR PURPOSE. See the GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License along with *
* this program. If not, see <http://www.gnu.org/licenses/>. *
****************************************************************************************/
package com.ichi2.anki.exception
import com.ichi2.utils.KotlinCleanup
import java.lang.Exception
@KotlinCleanup("Combine constructors")
class StorageAccessException : Exception {
constructor(msg: String?, e: Throwable?) : super(msg, e) {}
constructor(msg: String?) : super(msg) {}
}
| AnkiDroid/src/main/java/com/ichi2/anki/exception/StorageAccessException.kt | 2588895116 |
package com.tamsiree.rxui.view
import android.content.Context
import android.os.Handler
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.animation.AnimationUtils
import android.widget.FrameLayout
import android.widget.ImageView
import com.tamsiree.rxui.R
/**
* @author tamsiree
* 自动左右平滑移动的ImageView
*/
class RxAutoImageView : FrameLayout {
private var mImageView: ImageView? = null
var resId = 0
constructor(context: Context?) : super(context!!)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
//导入布局
initView(context, attrs)
}
private fun initView(context: Context, attrs: AttributeSet?) {
LayoutInflater.from(context).inflate(R.layout.layout_auto_imageview, this)
mImageView = findViewById(R.id.img_backgroud)
//获得这个控件对应的属性。
val a = getContext().obtainStyledAttributes(attrs, R.styleable.RxAutoImageView)
resId = try {
//获得属性值
a.getResourceId(R.styleable.RxAutoImageView_ImageSrc, 0)
} finally {
//回收这个对象
a.recycle()
}
if (resId != 0) {
mImageView?.setImageResource(resId)
}
Handler().postDelayed({
val animation = AnimationUtils.loadAnimation(context, R.anim.translate_anim)
mImageView?.startAnimation(animation)
}, 200)
}
} | RxUI/src/main/java/com/tamsiree/rxui/view/RxAutoImageView.kt | 2633729724 |
/*
* Copyright 2017 RedRoma, 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 tech.aroma.thrift.functions
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.notNullValue
import org.junit.Assert.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import tech.aroma.thrift.LengthOfTime
import tech.aroma.thrift.TimeUnit
import tech.aroma.thrift.TimeUnit.DAYS
import tech.aroma.thrift.TimeUnit.HOURS
import tech.aroma.thrift.TimeUnit.MILLIS
import tech.aroma.thrift.TimeUnit.MINUTES
import tech.aroma.thrift.TimeUnit.SECONDS
import tech.aroma.thrift.TimeUnit.WEEKS
import tech.sirwellington.alchemy.generator.AlchemyGenerator.Get.one
import tech.sirwellington.alchemy.generator.NumberGenerators
import tech.sirwellington.alchemy.generator.NumberGenerators.Companion.integers
import tech.sirwellington.alchemy.generator.TimeGenerators.Companion.anytime
import tech.sirwellington.alchemy.generator.TimeGenerators.Companion.futureInstants
import tech.sirwellington.alchemy.generator.TimeGenerators.Companion.pastInstants
import tech.sirwellington.alchemy.test.junit.runners.AlchemyTestRunner
import tech.sirwellington.alchemy.test.junit.runners.DontRepeat
import tech.sirwellington.alchemy.test.junit.runners.Repeat
import java.time.Instant
import java.time.temporal.ChronoUnit
import java.util.Arrays
/**
* @author SirWellington
*/
@Repeat(500)
@RunWith(AlchemyTestRunner::class)
class TimeFunctionsTest
{
private lateinit var timeUnit: TimeUnit
private var timeValue: Long = 0
private lateinit var lengthOfTime: LengthOfTime
private var expectedInSeconds: Long = 0
private var anyTimestamp: Long = 0
private var pastTimestamp: Long = 0
private var futureTimestamp: Long = 0
@Before
fun setUp()
{
val units = Arrays.asList(SECONDS, MINUTES, DAYS)
timeUnit = anyOf(units)!!
timeValue = one(NumberGenerators.integers(1, 100)).toLong()
lengthOfTime = LengthOfTime(timeUnit, timeValue)
val duration = TimeFunctions.lengthOfTimeToDuration().apply(lengthOfTime)
expectedInSeconds = duration.seconds
anyTimestamp = one(anytime()).toEpochMilli()
pastTimestamp = one(pastInstants()).toEpochMilli()
futureTimestamp = one(futureInstants()).toEpochMilli()
}
@DontRepeat
@Test(expected = IllegalAccessException::class)
@Throws(IllegalAccessException::class, InstantiationException::class)
fun testCannotInstantiate()
{
TimeFunctions::class.java.newInstance()
}
@Test
fun testTimeUnitToChronoUnit()
{
val expected = toChronoUnit(timeUnit)
val chronoUnit = TimeFunctions.TIME_UNIT_TO_CHRONO_UNIT.apply(timeUnit)
assertThat(chronoUnit, notNullValue())
assertThat(chronoUnit, equalTo(expected))
}
@Test
fun testLengthOfTimeToDuration()
{
val chronoUnit = toChronoUnit(timeUnit)
val duration = TimeFunctions.LENGTH_OF_TIME_TO_DURATION.apply(lengthOfTime)
val expectedDuration = chronoUnit.duration.multipliedBy(timeValue)
assertThat(duration, equalTo(expectedDuration))
}
@Test
fun testToSeconds()
{
val seconds = TimeFunctions.toSeconds(lengthOfTime!!)
assertThat(seconds, equalTo(expectedInSeconds))
}
private fun toChronoUnit(timeUnit: TimeUnit): ChronoUnit
{
when (timeUnit)
{
MILLIS -> return ChronoUnit.MILLIS
SECONDS -> return ChronoUnit.SECONDS
MINUTES -> return ChronoUnit.MINUTES
HOURS -> return ChronoUnit.HOURS
DAYS -> return ChronoUnit.DAYS
WEEKS -> return ChronoUnit.WEEKS
else -> throw UnsupportedOperationException("Unexpected Time Unit Type: " + timeUnit)
}
}
@Test
fun testToInstant()
{
val result = TimeFunctions.toInstant(anyTimestamp)
assertThat(result, equalTo(Instant.ofEpochMilli(anyTimestamp)))
assertThat(result.toEpochMilli(), equalTo(anyTimestamp))
}
@Test
fun testIsInThePast()
{
assertThat(TimeFunctions.isInThePast(pastTimestamp), equalTo(true))
assertThat(TimeFunctions.isInThePast(futureTimestamp), equalTo(false))
}
@Test
fun testIsInTheFuture()
{
assertThat(TimeFunctions.isInTheFuture(futureTimestamp), equalTo(true))
assertThat(TimeFunctions.isInTheFuture(pastTimestamp), equalTo(false))
}
private fun <T> anyOf(list: List<T>): T?
{
if (list.isEmpty())
{
return null
}
val index = one(integers(0, list.size - 1))
return list[index]
}
}
| src/test/java/tech/aroma/thrift/functions/TimeFunctionsTest.kt | 28497830 |
package me.xbh.lib.core.cxx
import me.xbh.lib.core.ICrypt
/**
* <p>
* 描述:RSA加密本地接口
* </p>
* 创建日期:2017年11月02日.
* @author [email protected]
* @version 1.0
*/
internal open class RsaImpl : ICrypt {
override fun getKey(obj: Any?): String = getPublicKey(obj as Int)
override fun encrypt(plain: String, key: String): String = encryptByPublicKey(plain, key)
override fun decrypt(cipher: String, key: String): String = decryptByPublicKey(cipher, key)
external fun getPublicKey(int: Int): String
external fun encryptByPublicKey(plain: String, key: String): String
external fun decryptByPublicKey(cipher: String, key: String): String
} | CryptLibrary/src/main/kotlin/me/xbh/lib/core/cxx/RsaImpl.kt | 2241508708 |
package ws.osiris.awsdeploy
import com.amazonaws.services.lambda.model.InvocationType
import com.amazonaws.services.lambda.model.InvokeRequest
import com.google.gson.Gson
import org.slf4j.LoggerFactory
import ws.osiris.aws.ApiFactory
import ws.osiris.awsdeploy.cloudformation.DeployResult
import ws.osiris.awsdeploy.cloudformation.Templates
import ws.osiris.awsdeploy.cloudformation.apiId
import ws.osiris.awsdeploy.cloudformation.apiName
import ws.osiris.awsdeploy.cloudformation.deployStack
import ws.osiris.core.Api
import java.awt.Desktop
import java.io.BufferedReader
import java.io.FileReader
import java.io.IOException
import java.io.InputStream
import java.net.URI
import java.net.URLClassLoader
import java.nio.ByteBuffer
import java.nio.file.FileVisitResult
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.nio.file.SimpleFileVisitor
import java.nio.file.attribute.BasicFileAttributes
import java.security.MessageDigest
import java.time.Duration
import java.util.stream.Collectors
private val log = LoggerFactory.getLogger("ws.osiris.awsdeploy")
/**
* Implemented for each build system to hook into the project configuration.
*
* The configuration allows the code and CloudFormation template to be generated and the project to be deployed.
*/
interface DeployableProject {
/** The project name; must be specified by the user in the Maven or Gradle project. */
val name: String
/** The project version; Maven requires a version but it's optional in Gradle. */
val version: String?
/** The root of the build directory. */
val buildDir: Path
/** The directory where jar files are built. */
val zipBuildDir: Path
/** The root of the main source directory; normally `src/main`. */
val sourceDir: Path
/** The root package of the application; used when generating the CloudFormation template. */
val rootPackage: String
/** The name of the environment into which the code is being deployed; used in resource and bucket names. */
val environmentName: String?
/** The directory containing the static files; null if the API doesn't serve static files. */
val staticFilesDirectory: String?
/** The name of the AWS profile; if not specified the default chain is used to find the profile and region. */
val awsProfile: String?
/** The name of the CloudFormation stack; if not specified a name is generated from the app and environment names. */
val stackName: String?
/** The jar files on the runtime classpath. */
val runtimeClasspath: List<Path>
/** The jar containing the project classes and resources. */
val projectJar: Path
private val cloudFormationSourceDir: Path get() = sourceDir.resolve("cloudformation")
private val rootTemplate: Path get() = cloudFormationSourceDir.resolve("root.template")
private val generatedCorePackage: String get() = "$rootPackage.core.generated"
private val lambdaClassName: String get() = "$generatedCorePackage.GeneratedLambda"
private val cloudFormationGeneratedDir: Path get() = buildDir.resolve("cloudformation")
private val apiFactoryClassName: String get() = "$generatedCorePackage.GeneratedApiFactory"
private val zipFile: Path get() = zipBuildDir.resolve(zipName)
private val zipName: String get() = if (version == null) {
"$name-dist.zip"
} else {
"$name-$version-dist.zip"
}
private fun profile(): AwsProfile {
val awsProfile = this.awsProfile
return if (awsProfile == null) {
val profile = AwsProfile.default()
log.info("Using default AWS profile, region = {}", profile.region)
profile
} else {
val profile = AwsProfile.named(awsProfile)
log.info("Using AWS profile named '{}', region = {}", awsProfile, profile.region)
profile
}
}
/**
* Returns a factory that can build the API, the components and the application configuration.
*/
fun createApiFactory(parentClassLoader: ClassLoader): ApiFactory<*> {
log.debug("runtime classpath: {}", runtimeClasspath)
log.debug("project jar: {}", projectJar)
val classpathJars = runtimeClasspath.map { it.toUri().toURL() } + projectJar.toUri().toURL()
val classLoader = URLClassLoader(classpathJars.toTypedArray(), parentClassLoader)
val apiFactoryClass = Class.forName(apiFactoryClassName, true, classLoader)
return apiFactoryClass.newInstance() as ApiFactory<*>
}
fun generateCloudFormation() {
val apiFactory = createApiFactory(javaClass.classLoader)
val api = apiFactory.api
val appConfig = apiFactory.config
val appName = appConfig.applicationName
val profile = profile()
val codeBucket = appConfig.codeBucket ?: codeBucketName(appName, environmentName, profile.accountId)
val (codeHash, jarKey) = zipS3Key(appName)
// Parse the parameters from root.template and pass them to the lambda as env vars
// This allows the handler code to reference any resources defined in root.template
val templateParams = generatedTemplateParameters(rootTemplate, appName)
val staticHash = staticFilesInfo(api, staticFilesDirectory)?.hash
deleteContents(cloudFormationGeneratedDir)
Files.createDirectories(cloudFormationGeneratedDir)
val templates = Templates.create(
api,
appConfig,
templateParams,
lambdaClassName,
codeHash,
staticHash,
codeBucket,
jarKey,
environmentName,
profile.accountId
)
for (file in templates.files) {
file.write(cloudFormationGeneratedDir)
}
// copy all templates from the template src dir to the generated template dir with filtering
if (!Files.exists(cloudFormationSourceDir)) return
Files.list(cloudFormationSourceDir)
.filter { it.fileName.toString().endsWith(".template") }
.forEach { file ->
val templateText = BufferedReader(FileReader(file.toFile())).use { it.readText() }
val generatedFile = templateText
.replace("\${codeS3Bucket}", codeBucket)
.replace("\${codeS3Key}", jarKey)
.replace("\${environmentName}", environmentName ?: "null")
val generatedFilePath = cloudFormationGeneratedDir.resolve(file.fileName)
log.debug("Copying template from ${file.toAbsolutePath()} to ${generatedFilePath.toAbsolutePath()}")
Files.write(generatedFilePath, generatedFile.toByteArray(Charsets.UTF_8))
}
}
/**
* Recursively deletes all files and subdirectories of a directory, leaving the directory empty.
*/
private fun deleteContents(dir: Path) {
if (!Files.exists(dir)) return
Files.walkFileTree(dir, object : SimpleFileVisitor<Path>() {
override fun visitFile(file: Path, attrs: BasicFileAttributes): FileVisitResult {
Files.delete(file)
return FileVisitResult.CONTINUE
}
override fun postVisitDirectory(dir: Path, exc: IOException?): FileVisitResult {
Files.delete(dir)
return FileVisitResult.CONTINUE
}
})
}
private data class ZipKey(val hash: String, val name: String)
private fun zipS3Key(apiName: String): ZipKey {
val zipPath = zipBuildDir.resolve(zipName)
val md5Hash = md5Hash(zipPath)
return ZipKey(md5Hash, "$apiName.$md5Hash.jar")
}
private fun md5Hash(vararg files: Path): String {
val messageDigest = MessageDigest.getInstance("md5")
val buffer = ByteArray(1024 * 1024)
tailrec fun readChunk(stream: InputStream) {
val bytesRead = stream.read(buffer)
if (bytesRead == -1) {
return
} else {
messageDigest.update(buffer, 0, bytesRead)
readChunk(stream)
}
}
for (file in files) {
Files.newInputStream(file).buffered(1024 * 1024).use { readChunk(it) }
}
val digest = messageDigest.digest()
return digest.joinToString("") { String.format("%02x", it) }
}
private fun templateUrl(templateName: String, codeBucket: String, region: String): String =
"https://$codeBucket.s3.$region.amazonaws.com/$templateName"
private fun generatedTemplateParameters(rootTemplatePath: Path, apiName: String): Set<String> {
val templateBytes = Files.readAllBytes(rootTemplatePath)
val templateYaml = String(templateBytes, Charsets.UTF_8)
return generatedTemplateParameters(templateYaml, apiName)
}
@Suppress("UNCHECKED_CAST")
fun deploy(): Map<String, String> {
if (!Files.exists(zipFile)) throw DeployException("Cannot find $zipName")
val apiFactory = createApiFactory(javaClass.classLoader)
val appConfig = apiFactory.config
val api = apiFactory.api
val appName = appConfig.applicationName
val profile = profile()
val codeBucket = appConfig.codeBucket
?: createBucket(profile, codeBucketName(appName, environmentName, profile.accountId))
val (_, jarKey) = zipS3Key(appName)
log.info("Uploading function code '$zipFile' to $codeBucket with key $jarKey")
uploadFile(profile, zipFile, codeBucket, jarKey)
log.info("Upload of function code complete")
uploadTemplates(profile, codeBucket)
if (!Files.exists(rootTemplate)) throw IllegalStateException("core/src/main/cloudformation/root.template is missing")
val deploymentTemplateUrl = templateUrl(rootTemplate.fileName.toString(), codeBucket, profile.region)
val apiName = apiName(appConfig.applicationName, environmentName)
val localStackName = this.stackName
val stackName = if (localStackName == null) {
val stackEnvSuffix = if (environmentName == null) "" else "-$environmentName"
"${appConfig.applicationName}$stackEnvSuffix"
} else {
localStackName
}
val deployResult = deployStack(profile, stackName, apiName, deploymentTemplateUrl)
val staticBucket = appConfig.staticFilesBucket
?: staticFilesBucketName(appName, environmentName, profile.accountId)
uploadStaticFiles(profile, api, staticBucket, staticFilesDirectory)
val apiId = deployResult.apiId
val stackCreated = deployResult.stackCreated
val deployedStages = deployStages(profile, apiId, apiName, appConfig.stages, stackCreated)
val stageUrls = deployedStages.associateWith { stageUrl(apiId, it, profile.region) }
for ((stage, url) in stageUrls) log.info("Deployed to stage '$stage' at $url")
sendKeepAlive(deployResult, appConfig.keepAliveCount, appConfig.keepAliveSleep, profile)
return stageUrls
}
/**
* Opens a path from a stage in the system default browser.
*/
fun openBrowser(stage: String, path: String) {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
val apiFactory = createApiFactory(javaClass.classLoader)
val apiName = apiName(apiFactory.config.applicationName, environmentName)
val urlBase = stageUrl(apiName, stage, profile())
val url = urlBase + path.removePrefix("/")
log.debug("Opening path {} of stage {} of API {} in the default browser: {}", path, stage, apiName, url)
Desktop.getDesktop().browse(URI(url))
} else {
log.warn("Opening a browser is not supported")
}
}
// --------------------------------------------------------------------------------------------------
private fun uploadStaticFiles(profile: AwsProfile, api: Api<*>, bucket: String, staticFilesDirectory: String?) {
val staticFilesInfo = staticFilesInfo(api, staticFilesDirectory) ?: return
val staticFilesDir = staticFilesDirectory?.let { Paths.get(it) } ?: sourceDir.resolve("static")
for (file in staticFilesInfo.files) {
uploadFile(profile, file, bucket, staticFilesDir, bucketDir = staticFilesInfo.hash)
}
}
private fun uploadTemplates(profile: AwsProfile, codeBucket: String) {
if (!Files.exists(cloudFormationGeneratedDir)) return
Files.list(cloudFormationGeneratedDir)
.filter { it.fileName.toString().endsWith(".template") }
.forEach { uploadFile(profile, it, codeBucket) }
}
private fun staticFilesInfo(api: Api<*>, staticFilesDirectory: String?): StaticFilesInfo? {
if (!api.staticFiles) {
return null
}
val staticFilesDir = staticFilesDirectory?.let { Paths.get(it) } ?: sourceDir.resolve("static")
val staticFiles = Files.walk(staticFilesDir, Int.MAX_VALUE)
.filter { !Files.isDirectory(it) }
.collect(Collectors.toList())
val hash = md5Hash(*staticFiles.toTypedArray())
return StaticFilesInfo(staticFiles, hash)
}
private fun sendKeepAlive(deployResult: DeployResult, instanceCount: Int, sleepTimeMs: Duration, profile: AwsProfile) {
if (deployResult.keepAliveLambdaArn == null) return
log.info("Invoking keep-alive lambda {}", deployResult.keepAliveLambdaArn)
val payloadMap = mapOf(
"functionArn" to deployResult.lambdaVersionArn,
"instanceCount" to instanceCount,
"sleepTimeMs" to sleepTimeMs.toMillis()
)
log.debug("Keep-alive payload: {}", payloadMap)
val payloadJson = Gson().toJson(payloadMap)
profile.lambdaClient.invoke(InvokeRequest().apply {
functionName = deployResult.keepAliveLambdaArn
invocationType = InvocationType.Event.name
payload = ByteBuffer.wrap(payloadJson.toByteArray())
})
}
}
/**
* The static files and the hash of all of them together.
*
* The hash is used to derive the name of the folder in the static files bucket that the files are deployed to.
* Each different set of files must be uploaded to a different location to that different stages can use
* different sets of files. Using the hash to name a subdirectory of the static files bucket has two advantages:
*
* * The template generation code and deployment code can both derive the same location
* * A new set of files is only created when any of them change and the hash changes
*/
private class StaticFilesInfo(val files: List<Path>, val hash: String)
internal fun stageUrl(apiId: String, stageName: String, region: String) =
"https://$apiId.execute-api.$region.amazonaws.com/$stageName/"
internal fun stageUrl(apiName: String, stage: String, profile: AwsProfile): String {
val apiId = apiId(apiName, profile)
return stageUrl(apiId, stage, profile.region)
}
| aws-deploy/src/main/kotlin/ws/osiris/awsdeploy/DeployableProject.kt | 3362571155 |
package com.sapuseven.untis.models.untis.params
import com.sapuseven.untis.models.untis.UntisAuth
import com.sapuseven.untis.models.untis.UntisDate
import kotlinx.serialization.Serializable
@Serializable
data class AbsenceParams(
val startDate: UntisDate,
val endDate: UntisDate,
val includeExcused: Boolean,
val includeUnExcused: Boolean,
val auth: UntisAuth
) : BaseParams()
| app/src/main/java/com/sapuseven/untis/models/untis/params/AbsenceParams.kt | 3974718438 |
package com.stripe.android.stripecardscan.framework.util
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class AppDetailsTest {
private val testContext = InstrumentationRegistry.getInstrumentation().context
@Test
fun appDetails_full() {
val appDetails = AppDetails.fromContext(testContext)
assertEquals(
"com.stripe.android.stripecardscan.test",
appDetails.appPackageName
)
assertEquals("", appDetails.applicationId)
assertEquals(
"com.stripe.android.stripecardscan",
appDetails.libraryPackageName
)
assertTrue(
appDetails.sdkVersion.startsWith("1."),
"${appDetails.sdkVersion} does not start with \"2.\""
)
assertEquals(-1, appDetails.sdkVersionCode)
assertTrue(appDetails.sdkFlavor.isNotEmpty())
}
}
| stripecardscan/src/androidTest/java/com/stripe/android/stripecardscan/framework/util/AppDetailsTest.kt | 3298267219 |
package com.bl_lia.kirakiratter.domain.repository
import com.bl_lia.kirakiratter.domain.entity.Account
import com.bl_lia.kirakiratter.domain.entity.Relationship
import com.bl_lia.kirakiratter.domain.entity.Status
import io.reactivex.Single
interface AccountRepository {
fun statuses(id: Int): Single<List<Status>>
fun moreStatuses(id: Int, maxId: String? = null, sinceId: Int? = null): Single<List<Status>>
fun relationship(id: Int): Single<Relationship>
fun follow(id: Int): Single<Relationship>
fun unfollow(id: Int): Single<Relationship>
fun verifyCredentials(): Single<Account>
fun account(id: Int): Single<Account>
} | app/src/main/kotlin/com/bl_lia/kirakiratter/domain/repository/AccountRepository.kt | 953361691 |
package com.stripe.android.model.parsers
import com.stripe.android.core.model.StripeJsonUtils
import com.stripe.android.core.model.parsers.ModelJsonParser
import com.stripe.android.model.Card
import com.stripe.android.model.CardFunding
import com.stripe.android.model.SourceTypeModel
import com.stripe.android.model.TokenizationMethod
import org.json.JSONObject
internal class SourceCardDataJsonParser : ModelJsonParser<SourceTypeModel.Card> {
override fun parse(json: JSONObject): SourceTypeModel.Card {
return SourceTypeModel.Card(
addressLine1Check = StripeJsonUtils.optString(json, FIELD_ADDRESS_LINE1_CHECK),
addressZipCheck = StripeJsonUtils.optString(json, FIELD_ADDRESS_ZIP_CHECK),
brand = Card.getCardBrand(StripeJsonUtils.optString(json, FIELD_BRAND)),
country = StripeJsonUtils.optString(json, FIELD_COUNTRY),
cvcCheck = StripeJsonUtils.optString(json, FIELD_CVC_CHECK),
dynamicLast4 = StripeJsonUtils.optString(json, FIELD_DYNAMIC_LAST4),
expiryMonth = StripeJsonUtils.optInteger(json, FIELD_EXP_MONTH),
expiryYear = StripeJsonUtils.optInteger(json, FIELD_EXP_YEAR),
funding = CardFunding.fromCode(StripeJsonUtils.optString(json, FIELD_FUNDING)),
last4 = StripeJsonUtils.optString(json, FIELD_LAST4),
threeDSecureStatus = SourceTypeModel.Card.ThreeDSecureStatus.fromCode(
StripeJsonUtils.optString(json, FIELD_THREE_D_SECURE)
),
tokenizationMethod = TokenizationMethod.fromCode(
StripeJsonUtils.optString(json, FIELD_TOKENIZATION_METHOD)
)
)
}
internal companion object {
private const val FIELD_ADDRESS_LINE1_CHECK = "address_line1_check"
private const val FIELD_ADDRESS_ZIP_CHECK = "address_zip_check"
private const val FIELD_BRAND = "brand"
private const val FIELD_COUNTRY = "country"
private const val FIELD_CVC_CHECK = "cvc_check"
private const val FIELD_DYNAMIC_LAST4 = "dynamic_last4"
private const val FIELD_EXP_MONTH = "exp_month"
private const val FIELD_EXP_YEAR = "exp_year"
private const val FIELD_FUNDING = "funding"
private const val FIELD_LAST4 = "last4"
private const val FIELD_THREE_D_SECURE = "three_d_secure"
private const val FIELD_TOKENIZATION_METHOD = "tokenization_method"
}
}
| payments-core/src/main/java/com/stripe/android/model/parsers/SourceCardDataJsonParser.kt | 3973939902 |
package nl.endran.demotime.test
import android.support.design.widget.Snackbar
import android.view.View
fun View.showSnackbarOnClick(message : String) {
setOnClickListener {
Snackbar.make(it, message, Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
}
| Sources/DemoTime/app/src/main/java/nl/endran/demotime/test/e.kt | 2139694884 |
package com.stripe.android.financialconnections.analytics
import android.app.Application
import androidx.test.core.app.ApplicationProvider
import com.stripe.android.core.networking.AnalyticsRequestExecutor
import com.stripe.android.core.networking.AnalyticsRequestFactory
import com.stripe.android.financialconnections.ApiKeyFixtures
import com.stripe.android.financialconnections.FinancialConnectionsSheet
import com.stripe.android.financialconnections.launcher.FinancialConnectionsSheetActivityResult
import com.stripe.android.financialconnections.model.FinancialConnectionsAccountList
import com.stripe.android.financialconnections.model.FinancialConnectionsSession
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.kotlin.argWhere
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.robolectric.RobolectricTestRunner
@ExperimentalCoroutinesApi
@RunWith(RobolectricTestRunner::class)
class DefaultConnectionsEventReportTest {
private val testDispatcher = UnconfinedTestDispatcher()
private val application = ApplicationProvider.getApplicationContext<Application>()
private val analyticsRequestExecutor = mock<AnalyticsRequestExecutor>()
private val analyticsRequestFactory = AnalyticsRequestFactory(
packageManager = application.packageManager,
packageName = application.packageName.orEmpty(),
packageInfo = application.packageManager.getPackageInfo(application.packageName, 0),
publishableKeyProvider = { ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY }
)
private val eventReporter = DefaultFinancialConnectionsEventReporter(
analyticsRequestExecutor,
analyticsRequestFactory,
testDispatcher
)
private val configuration = FinancialConnectionsSheet.Configuration(
ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET,
ApiKeyFixtures.DEFAULT_PUBLISHABLE_KEY
)
private val financialConnectionsSession = FinancialConnectionsSession(
clientSecret = "las_1234567890",
id = ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET,
accountsNew = FinancialConnectionsAccountList(
data = emptyList(),
hasMore = false,
url = "url",
count = 0
),
livemode = true
)
@Test
fun `onPresented() should fire analytics request with expected event value`() {
eventReporter.onPresented(configuration)
verify(analyticsRequestExecutor).executeAsync(
argWhere { req ->
req.params["event"] == "stripe_android.connections.sheet.presented" &&
req.params["las_client_secret"] == ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET
}
)
}
@Test
fun `onResult() should fire analytics request with expected event value for success`() {
eventReporter.onResult(
configuration,
FinancialConnectionsSheetActivityResult.Completed(
financialConnectionsSession = financialConnectionsSession
)
)
verify(analyticsRequestExecutor).executeAsync(
argWhere { req ->
req.params["event"] == "stripe_android.connections.sheet.closed" &&
req.params["session_result"] == "completed" &&
req.params["las_client_secret"] == ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET
}
)
}
@Test
fun `onResult() should fire analytics request with expected event value for cancelled`() {
eventReporter.onResult(configuration, FinancialConnectionsSheetActivityResult.Canceled)
verify(analyticsRequestExecutor).executeAsync(
argWhere { req ->
req.params["event"] == "stripe_android.connections.sheet.closed" &&
req.params["session_result"] == "cancelled" &&
req.params["las_client_secret"] == ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET
}
)
}
@Test
fun `onResult() should fire analytics request with expected event value for failure`() {
eventReporter.onResult(configuration, FinancialConnectionsSheetActivityResult.Failed(Exception()))
verify(analyticsRequestExecutor).executeAsync(
argWhere { req ->
req.params["event"] == "stripe_android.connections.sheet.failed" &&
req.params["session_result"] == "failure" &&
req.params["las_client_secret"] == ApiKeyFixtures.DEFAULT_FINANCIAL_CONNECTIONS_SESSION_SECRET
}
)
}
}
| financial-connections/src/test/java/com/stripe/android/financialconnections/analytics/DefaultConnectionsEventReportTest.kt | 1552228990 |
/*
* Copyright 2017 Paulo Fernando
*
* 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 site.paulo.localchat.ui.dashboard.chat
import androidx.recyclerview.widget.SortedList
import site.paulo.localchat.data.model.firebase.Chat
import site.paulo.localchat.data.model.firebase.ChatMessage
import site.paulo.localchat.ui.base.BaseMvpPresenter
import site.paulo.localchat.ui.base.MvpView
object ChatContract {
interface View : MvpView {
fun showChat(chat: Chat)
fun showChatsEmpty()
fun showError()
fun messageReceived(chatMessage: ChatMessage, chatId: String)
fun updateLastMessage(chatMessage: ChatMessage, chatId: String)
fun notifyUser(chatMessage: ChatMessage, chatId: String)
}
abstract class Presenter : BaseMvpPresenter<View>() {
abstract fun loadChatRooms(userId: String)
abstract fun loadChatRoom(chatId: String)
/** Listen to new chats the current user is added */
abstract fun listenNewChatRooms(chatId: String) //TODO remove chatId param when get user information before open the dashboard
abstract fun loadProfilePicture(chatList: List<Chat>)
}
}
| app/src/main/kotlin/site/paulo/localchat/ui/dashboard/chat/ChatContract.kt | 207080226 |
package com.stripe.android.core.networking
import androidx.annotation.RestrictTo
import com.stripe.android.core.exception.InvalidRequestException
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Factory to create [StripeConnection], which encapsulates an [HttpURLConnection], triggers the
* request and parses the response with different body type as [StripeResponse].
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
interface ConnectionFactory {
/**
* Creates an [StripeConnection] which attempts to parse the http response body as a [String].
*/
@Throws(IOException::class, InvalidRequestException::class)
fun create(request: StripeRequest): StripeConnection<String>
/**
* Creates an [StripeConnection] which attempts to parse the http response body as a [File].
*/
@Throws(IOException::class, InvalidRequestException::class)
fun createForFile(request: StripeRequest, outputFile: File): StripeConnection<File>
object Default : ConnectionFactory {
@Throws(IOException::class, InvalidRequestException::class)
@JvmSynthetic
override fun create(request: StripeRequest): StripeConnection<String> {
return StripeConnection.Default(openConnectionAndApplyFields(request))
}
override fun createForFile(
request: StripeRequest,
outputFile: File
): StripeConnection<File> {
return StripeConnection.FileConnection(
openConnectionAndApplyFields(request),
outputFile
)
}
private fun openConnectionAndApplyFields(request: StripeRequest): HttpURLConnection {
return (URL(request.url).openConnection() as HttpURLConnection).apply {
connectTimeout = CONNECT_TIMEOUT
readTimeout = READ_TIMEOUT
useCaches = request.shouldCache
requestMethod = request.method.code
request.headers.forEach { (key, value) ->
setRequestProperty(key, value)
}
if (StripeRequest.Method.POST == request.method) {
doOutput = true
request.postHeaders?.forEach { (key, value) ->
setRequestProperty(key, value)
}
outputStream.use { output -> request.writePostBody(output) }
}
}
}
}
private companion object {
private val CONNECT_TIMEOUT = TimeUnit.SECONDS.toMillis(30).toInt()
private val READ_TIMEOUT = TimeUnit.SECONDS.toMillis(80).toInt()
}
}
| stripe-core/src/main/java/com/stripe/android/core/networking/ConnectionFactory.kt | 2825155019 |
package com.stripe.android.model
import androidx.annotation.RestrictTo
import com.stripe.android.core.model.StripeJsonUtils
import com.stripe.android.core.model.StripeModel
import com.stripe.android.model.PaymentIntent.CaptureMethod
import com.stripe.android.model.PaymentIntent.ConfirmationMethod
import com.stripe.android.model.parsers.PaymentIntentJsonParser
import kotlinx.parcelize.Parcelize
import org.json.JSONObject
import java.util.regex.Pattern
/**
* A [PaymentIntent] tracks the process of collecting a payment from your customer.
*
* - [Payment Intents Overview](https://stripe.com/docs/payments/payment-intents)
* - [PaymentIntents API Reference](https://stripe.com/docs/api/payment_intents)
*/
@Parcelize
data class PaymentIntent internal constructor(
/**
* Unique identifier for the object.
*/
override val id: String?,
/**
* The list of payment method types (e.g. card) that this [PaymentIntent] is allowed to
* use.
*/
override val paymentMethodTypes: List<String>,
/**
* Amount intended to be collected by this [PaymentIntent]. A positive integer
* representing how much to charge in the smallest currency unit (e.g., 100 cents to charge
* $1.00 or 100 to charge ¥100, a zero-decimal currency). The minimum amount is $0.50 US or
* equivalent in charge currency. The amount value supports up to eight digits (e.g., a value
* of 99999999 for a USD charge of $999,999.99).
*/
val amount: Long?,
/**
* Populated when `status` is `canceled`, this is the time at which the [PaymentIntent]
* was canceled. Measured in seconds since the Unix epoch. If unavailable, will return 0.
*/
val canceledAt: Long = 0L,
/**
* Reason for cancellation of this [PaymentIntent].
*/
val cancellationReason: CancellationReason? = null,
/**
* Controls when the funds will be captured from the customer’s account.
* See [CaptureMethod].
*/
val captureMethod: CaptureMethod = CaptureMethod.Automatic,
/**
* The client secret of this [PaymentIntent]. Used for client-side retrieval using a
* publishable key.
*
* The client secret can be used to complete a payment from your frontend.
* It should not be stored, logged, embedded in URLs, or exposed to anyone other than the
* customer. Make sure that you have TLS enabled on any page that includes the client
* secret.
*/
override val clientSecret: String?,
/**
* One of automatic (default) or manual. See [ConfirmationMethod].
*
* When [confirmationMethod] is `automatic`, a [PaymentIntent] can be confirmed
* using a publishable key. After `next_action`s are handled, no additional
* confirmation is required to complete the payment.
*
* When [confirmationMethod] is `manual`, all payment attempts must be made
* using a secret key. The [PaymentIntent] returns to the
* [RequiresConfirmation][StripeIntent.Status.RequiresConfirmation]
* state after handling `next_action`s, and requires your server to initiate each
* payment attempt with an explicit confirmation.
*/
val confirmationMethod: ConfirmationMethod = ConfirmationMethod.Automatic,
/**
* Country code of the user.
*/
@get:RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
val countryCode: String?,
/**
* Time at which the object was created. Measured in seconds since the Unix epoch.
*/
override val created: Long,
/**
* Three-letter ISO currency code, in lowercase. Must be a supported currency.
*/
val currency: String?,
/**
* An arbitrary string attached to the object. Often useful for displaying to users.
*/
override val description: String? = null,
/**
* Has the value `true` if the object exists in live mode or the value
* `false` if the object exists in test mode.
*/
override val isLiveMode: Boolean,
override val paymentMethod: PaymentMethod? = null,
/**
* ID of the payment method (a PaymentMethod, Card, BankAccount, or saved Source object)
* to attach to this [PaymentIntent].
*/
override val paymentMethodId: String? = null,
/**
* Email address that the receipt for the resulting payment will be sent to.
*/
val receiptEmail: String? = null,
/**
* Status of this [PaymentIntent].
*/
override val status: StripeIntent.Status? = null,
val setupFutureUsage: StripeIntent.Usage? = null,
/**
* The payment error encountered in the previous [PaymentIntent] confirmation.
*/
val lastPaymentError: Error? = null,
/**
* Shipping information for this [PaymentIntent].
*/
val shipping: Shipping? = null,
/**
* Payment types that have not been activated in livemode, but have been activated in testmode.
*/
override val unactivatedPaymentMethods: List<String>,
/**
* Payment types that are accepted when paying with Link.
*/
override val linkFundingSources: List<String> = emptyList(),
override val nextActionData: StripeIntent.NextActionData? = null,
private val paymentMethodOptionsJsonString: String? = null
) : StripeIntent {
fun getPaymentMethodOptions() = paymentMethodOptionsJsonString?.let {
StripeJsonUtils.jsonObjectToMap(JSONObject(it))
} ?: emptyMap()
override val nextActionType: StripeIntent.NextActionType?
get() = when (nextActionData) {
is StripeIntent.NextActionData.SdkData -> {
StripeIntent.NextActionType.UseStripeSdk
}
is StripeIntent.NextActionData.RedirectToUrl -> {
StripeIntent.NextActionType.RedirectToUrl
}
is StripeIntent.NextActionData.DisplayOxxoDetails -> {
StripeIntent.NextActionType.DisplayOxxoDetails
}
is StripeIntent.NextActionData.VerifyWithMicrodeposits -> {
StripeIntent.NextActionType.VerifyWithMicrodeposits
}
is StripeIntent.NextActionData.UpiAwaitNotification -> {
StripeIntent.NextActionType.UpiAwaitNotification
}
is StripeIntent.NextActionData.AlipayRedirect,
is StripeIntent.NextActionData.BlikAuthorize,
is StripeIntent.NextActionData.WeChatPayRedirect,
null -> {
null
}
}
override val isConfirmed: Boolean
get() = setOf(
StripeIntent.Status.Processing,
StripeIntent.Status.RequiresCapture,
StripeIntent.Status.Succeeded
).contains(status)
override val lastErrorMessage: String?
get() = lastPaymentError?.message
override fun requiresAction(): Boolean {
return status === StripeIntent.Status.RequiresAction
}
override fun requiresConfirmation(): Boolean {
return status === StripeIntent.Status.RequiresConfirmation
}
/**
* SetupFutureUsage is considered to be set if it is on or off session.
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
private fun isTopLevelSetupFutureUsageSet() =
when (setupFutureUsage) {
StripeIntent.Usage.OnSession -> true
StripeIntent.Usage.OffSession -> true
StripeIntent.Usage.OneTime -> false
null -> false
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
fun isLpmLevelSetupFutureUsageSet(code: PaymentMethodCode): Boolean {
return isTopLevelSetupFutureUsageSet() || paymentMethodOptionsJsonString?.let {
JSONObject(paymentMethodOptionsJsonString)
.optJSONObject(code)
?.optString("setup_future_usage")?.let {
true
} ?: false
} ?: false
}
/**
* The payment error encountered in the previous [PaymentIntent] confirmation.
*
* See [last_payment_error](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-last_payment_error).
*/
@Parcelize
data class Error internal constructor(
/**
* For card errors, the ID of the failed charge.
*/
val charge: String?,
/**
* For some errors that could be handled programmatically, a short string indicating the
* [error code](https://stripe.com/docs/error-codes) reported.
*/
val code: String?,
/**
* For card errors resulting from a card issuer decline, a short string indicating the
* [card issuer’s reason for the decline](https://stripe.com/docs/declines#issuer-declines)
* if they provide one.
*/
val declineCode: String?,
/**
* A URL to more information about the
* [error code](https://stripe.com/docs/error-codes) reported.
*/
val docUrl: String?,
/**
* A human-readable message providing more details about the error. For card errors,
* these messages can be shown to your users.
*/
val message: String?,
/**
* If the error is parameter-specific, the parameter related to the error.
* For example, you can use this to display a message near the correct form field.
*/
val param: String?,
/**
* The PaymentMethod object for errors returned on a request involving a PaymentMethod.
*/
val paymentMethod: PaymentMethod?,
/**
* The type of error returned.
*/
val type: Type?
) : StripeModel {
enum class Type(val code: String) {
ApiConnectionError("api_connection_error"),
ApiError("api_error"),
AuthenticationError("authentication_error"),
CardError("card_error"),
IdempotencyError("idempotency_error"),
InvalidRequestError("invalid_request_error"),
RateLimitError("rate_limit_error");
internal companion object {
fun fromCode(typeCode: String?) = values().firstOrNull { it.code == typeCode }
}
}
internal companion object {
internal const val CODE_AUTHENTICATION_ERROR = "payment_intent_authentication_failure"
}
}
/**
* Shipping information for this [PaymentIntent].
*
* See [shipping](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping)
*/
@Parcelize
data class Shipping(
/**
* Shipping address.
*
* See [shipping.address](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-address)
*/
val address: Address,
/**
* The delivery service that shipped a physical product, such as Fedex, UPS, USPS, etc.
*
* See [shipping.carrier](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-carrier)
*/
val carrier: String? = null,
/**
* Recipient name.
*
* See [shipping.name](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-name)
*/
val name: String? = null,
/**
* Recipient phone (including extension).
*
* See [shipping.phone](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-phone)
*/
val phone: String? = null,
/**
* The tracking number for a physical product, obtained from the delivery service.
* If multiple tracking numbers were generated for this purchase, please separate them
* with commas.
*
* See [shipping.tracking_number](https://stripe.com/docs/api/payment_intents/object#payment_intent_object-shipping-tracking_number)
*/
val trackingNumber: String? = null
) : StripeModel
internal data class ClientSecret(internal val value: String) {
internal val paymentIntentId: String =
value.split("_secret".toRegex())
.dropLastWhile { it.isEmpty() }.toTypedArray()[0]
init {
require(isMatch(value)) {
"Invalid Payment Intent client secret: $value"
}
}
internal companion object {
private val PATTERN = Pattern.compile("^pi_[^_]+_secret_[^_]+$")
fun isMatch(value: String) = PATTERN.matcher(value).matches()
}
}
/**
* Reason for cancellation of this [PaymentIntent], either user-provided (duplicate, fraudulent,
* requested_by_customer, or abandoned) or generated by Stripe internally (failed_invoice,
* void_invoice, or automatic).
*/
enum class CancellationReason(private val code: String) {
Duplicate("duplicate"),
Fraudulent("fraudulent"),
RequestedByCustomer("requested_by_customer"),
Abandoned("abandoned"),
FailedInvoice("failed_invoice"),
VoidInvoice("void_invoice"),
Automatic("automatic");
internal companion object {
fun fromCode(code: String?) = values().firstOrNull { it.code == code }
}
}
/**
* Controls when the funds will be captured from the customer’s account.
*/
enum class CaptureMethod(private val code: String) {
/**
* (Default) Stripe automatically captures funds when the customer authorizes the payment.
*/
Automatic("automatic"),
/**
* Place a hold on the funds when the customer authorizes the payment, but don’t capture
* the funds until later. (Not all payment methods support this.)
*/
Manual("manual");
internal companion object {
fun fromCode(code: String?) = values().firstOrNull { it.code == code } ?: Automatic
}
}
enum class ConfirmationMethod(private val code: String) {
/**
* (Default) PaymentIntent can be confirmed using a publishable key. After `next_action`s
* are handled, no additional confirmation is required to complete the payment.
*/
Automatic("automatic"),
/**
* All payment attempts must be made using a secret key. The PaymentIntent returns to the
* `requires_confirmation` state after handling `next_action`s, and requires your server to
* initiate each payment attempt with an explicit confirmation.
*/
Manual("manual");
internal companion object {
fun fromCode(code: String?) = values().firstOrNull { it.code == code } ?: Automatic
}
}
companion object {
@JvmStatic
fun fromJson(jsonObject: JSONObject?): PaymentIntent? {
return jsonObject?.let {
PaymentIntentJsonParser().parse(it)
}
}
}
}
| payments-core/src/main/java/com/stripe/android/model/PaymentIntent.kt | 1823956511 |
/*
* Copyright 2019 Peter Kenji Yamanaka
*
* 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.pyamsoft.padlock.purge
import com.pyamsoft.padlock.api.PurgeInteractor
import com.pyamsoft.pydroid.core.cache.Cache
import dagger.Binds
import dagger.Module
import javax.inject.Named
@Module
abstract class PurgeSingletonModule {
@Binds
internal abstract fun providePurgeInteractor(impl: PurgeInteractorImpl): PurgeInteractor
@Binds
@Named("cache_purge")
internal abstract fun providePurgeCache(impl: PurgeInteractorImpl): Cache
@Binds
@Named("interactor_purge")
internal abstract fun providePurgeInteractorDb(impl: PurgeInteractorDb): PurgeInteractor
}
| padlock-purge/src/main/java/com/pyamsoft/padlock/purge/PurgeSingletonModule.kt | 3687677319 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import org.rust.ide.inspections.fixes.AddRemainingArmsFix
import org.rust.ide.utils.checkMatch.Pattern
import org.rust.ide.utils.checkMatch.checkExhaustive
import org.rust.lang.core.psi.RsMatchBody
import org.rust.lang.core.psi.RsMatchExpr
open class AddRemainingArmsIntention : RsElementBaseIntentionAction<AddRemainingArmsIntention.Context>() {
override fun getText(): String = AddRemainingArmsFix.NAME
override fun getFamilyName(): String = text
override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? {
val matchExpr = when (val parent = element.context) {
is RsMatchExpr -> parent
is RsMatchBody -> parent.context as? RsMatchExpr
else -> null
} ?: return null
val textRange = matchExpr.match.textRange
val caretOffset = editor.caretModel.offset
// `RsNonExhaustiveMatchInspection` register its quick fixes only for `match` keyword.
// At the same time, platform shows these quick fixes even when caret is located just after the keyword,
// i.e. `match/*caret*/`.
// So disable this intention for such range not to provide two the same actions to a user
if (caretOffset >= textRange.startOffset && caretOffset <= textRange.endOffset) return null
val patterns = matchExpr.checkExhaustive() ?: return null
return Context(matchExpr, patterns)
}
override fun invoke(project: Project, editor: Editor, ctx: Context) {
val (matchExpr, patterns) = ctx
createQuickFix(matchExpr, patterns).invoke(project, matchExpr.containingFile, matchExpr, matchExpr)
}
protected open fun createQuickFix(matchExpr: RsMatchExpr, patterns: List<Pattern>): AddRemainingArmsFix {
return AddRemainingArmsFix(matchExpr, patterns)
}
data class Context(val matchExpr: RsMatchExpr, val patterns: List<Pattern>)
}
| src/main/kotlin/org/rust/ide/intentions/AddRemainingArmsIntention.kt | 1961302661 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.codeInsight.editorActions.moveLeftRight.MoveElementLeftRightHandler
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.arrayElements
import org.rust.lang.core.psi.ext.getGenericParameters
class RsMoveLeftRightHandler : MoveElementLeftRightHandler() {
override fun getMovableSubElements(element: PsiElement): Array<PsiElement> {
val subElements = when (element) {
is RsArrayExpr -> element.arrayElements.orEmpty()
is RsFormatMacroArgument -> element.formatMacroArgList
is RsLifetimeParamBounds -> element.lifetimeList
is RsMetaItemArgs -> element.metaItemList + element.litExprList
is RsTraitType -> element.polyboundList
is RsTupleExpr -> element.exprList
is RsTupleType -> element.typeReferenceList
is RsTupleFields -> element.tupleFieldDeclList
is RsTypeParamBounds -> element.polyboundList
is RsTypeParameterList -> element.getGenericParameters()
is RsUseGroup -> element.useSpeckList
is RsValueArgumentList -> element.exprList
is RsValueParameterList -> element.valueParameterList
is RsVecMacroArgument -> if (element.semicolon == null) element.exprList else emptyList()
is RsWhereClause -> element.wherePredList
else -> return PsiElement.EMPTY_ARRAY
}
return subElements.toTypedArray()
}
}
| src/main/kotlin/org/rust/ide/actions/RsMoveLeftRightHandler.kt | 305607177 |
package org.tsdes.spring.frontend.restwsamqp.zuulws
import org.springframework.context.annotation.Configuration
import org.springframework.messaging.simp.config.MessageBrokerRegistry
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker
import org.springframework.web.socket.config.annotation.StompEndpointRegistry
@Configuration
@EnableWebSocketMessageBroker
class WebSocketConfig : AbstractWebSocketMessageBrokerConfigurer() {
override fun configureMessageBroker(config: MessageBrokerRegistry) {
config.enableSimpleBroker("/topic")
config.setApplicationDestinationPrefixes("/ws-api")
}
override fun registerStompEndpoints(registry: StompEndpointRegistry) {
registry.addEndpoint("/websocket-endpoint").withSockJS()
}
} | old/old_rest-ws-amqp/zuul-ws/src/main/kotlin/org/tsdes/spring/frontend/restwsamqp/zuulws/WebSocketConfig.kt | 1424429656 |
package com.habitrpg.android.habitica.ui.views.dialogs
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.fromHtml
import com.habitrpg.android.habitica.models.notifications.ChallengeWonData
import com.habitrpg.android.habitica.ui.helpers.DataBindingUtils
class WonChallengeDialog(context: Context) : HabiticaAlertDialog(context) {
fun configure(data: ChallengeWonData?) {
val imageView = additionalContentView?.findViewById<ImageView>(R.id.achievement_view)
DataBindingUtils.loadImage(imageView, "achievement-karaoke-2x")
if (data?.name != null) {
additionalContentView?.findViewById<TextView>(R.id.description_view)?.text = context.getString(R.string.won_achievement_description, data.name).fromHtml()
}
if ((data?.prize ?: 0) > 0) {
addButton(context.getString(R.string.claim_x_gems, data?.prize), true)
additionalContentView?.findViewById<ImageView>(R.id.achievement_confetti_left)?.visibility = View.GONE
additionalContentView?.findViewById<ImageView>(R.id.achievement_confetti_right)?.visibility = View.GONE
} else {
addButton(R.string.hurray, true)
additionalContentView?.findViewById<ImageView>(R.id.achievement_confetti_view)?.visibility = View.GONE
}
}
init {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as? LayoutInflater
val view = inflater?.inflate(R.layout.dialog_won_challenge, null)
setTitle(R.string.you_won_challenge)
setAdditionalContentView(view)
}
}
| Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/dialogs/WonChallengeDialog.kt | 2963550945 |
package com.devbrackets.android.recyclerext.adapter.delegate
interface DelegateApi<T> {
/**
* Retrieves the item associated with the `position`
*
* @param position The position to get the item for
* @return The item in the `position`
*/
fun getItem(position: Int): T
fun getItemViewType(adapterPosition: Int): Int
} | library/src/main/kotlin/com/devbrackets/android/recyclerext/adapter/delegate/DelegateApi.kt | 1435753351 |
package org.tsdes.advanced.exercises.cardgame.cards
import org.tsdes.advanced.exercises.cardgame.cards.dto.CardDto
import org.tsdes.advanced.exercises.cardgame.cards.dto.CollectionDto
import org.tsdes.advanced.exercises.cardgame.cards.dto.Rarity.*
object CardCollection{
fun get() : CollectionDto{
val dto = CollectionDto()
dto.prices.run {
put(BRONZE, 100)
put(SILVER, 500)
put(GOLD, 1_000)
put(PINK_DIAMOND, 100_000)
}
dto.prices.forEach { dto.millValues[it.key] = it.value / 4 }
dto.rarityProbabilities.run {
put(SILVER, 0.10)
put(GOLD, 0.01)
put(PINK_DIAMOND, 0.001)
put(BRONZE, 1 - get(SILVER)!! - get(GOLD)!! - get(PINK_DIAMOND)!!)
}
addCards(dto)
return dto
}
private fun addCards(dto: CollectionDto){
dto.cards.run {
add(CardDto("c000", "Green Mold", "lore ipsum", BRONZE, "035-monster.svg"))
add(CardDto("c001", "Opera Singer", "lore ipsum", BRONZE, "056-monster.svg"))
add(CardDto("c002", "Not Stitch", "lore ipsum", BRONZE, "070-monster.svg"))
add(CardDto("c003", "Assault Hamster", "lore ipsum", BRONZE, "100-monster.svg"))
add(CardDto("c004", "WTF?!?", "lore ipsum", BRONZE, "075-monster.svg"))
add(CardDto("c005", "Stupid Lump", "lore ipsum", BRONZE, "055-monster.svg"))
add(CardDto("c006", "Sad Farter", "lore ipsum", BRONZE, "063-monster.svg"))
add(CardDto("c007", "Smelly Tainter", "lore ipsum", BRONZE, "050-monster.svg"))
add(CardDto("c008", "Hårboll", "lore ipsum", BRONZE, "019-monster.svg"))
add(CardDto("c009", "Blue Horned", "lore ipsum", BRONZE, "006-monster.svg"))
add(CardDto("c010", "Børje McTrumf", "lore ipsum", SILVER, "081-monster.svg"))
add(CardDto("c011", "Exa Nopass", "lore ipsum", SILVER, "057-monster.svg"))
add(CardDto("c012", "Dick Tracy", "lore ipsum", SILVER, "028-monster.svg"))
add(CardDto("c013", "Marius Mario", "lore ipsum", SILVER, "032-monster.svg"))
add(CardDto("c014", "Patrick Stew", "lore ipsum", SILVER, "002-monster.svg"))
add(CardDto("c015", "Fluffy The Hugger of Death", "lore ipsum", GOLD, "036-monster.svg"))
add(CardDto("c016", "Gary The Wise", "lore ipsum", GOLD, "064-monster.svg"))
add(CardDto("c017", "Grump-Grump The Grumpy One", "lore ipsum", GOLD, "044-monster.svg"))
add(CardDto("c018", "Bert-ho-met The Polite Guy", "lore ipsum", GOLD, "041-monster.svg"))
add(CardDto("c019", "Bengt The Destroyer", "lore ipsum", PINK_DIAMOND, "051-monster.svg"))
}
assert(dto.cards.size == dto.cards.map { it.cardId }.toSet().size)
assert(dto.cards.size == dto.cards.map { it.name }.toSet().size)
assert(dto.cards.size == dto.cards.map { it.imageId }.toSet().size)
}
} | advanced/exercise-solutions/card-game/part-08/cards/src/main/kotlin/org/tsdes/advanced/exercises/cardgame/cards/CardCollection.kt | 2997149750 |
package org.open.openstore.file.internal.querys
import com.google.gson.JsonObject
/**
* 文件查询的分页器
*/
interface FilePager {
/**
* 当前页号
*/
fun current():Long
/**
* 页大小
*/
val size:Long
/**
* 数据总数,
*/
fun total():Long
/**
* 下一页
*/
fun next():FilePager
/**
* 上一页
*/
fun pre():FilePager
/**
* 第一页
*/
fun first():FilePager
/**
* 最后一页
*/
fun last():FilePager
/**
* 跳转到指定页
*/
fun jumpTo(pageNum:Long): FilePager
/**
* 获取分页内,指定索引的数据[0<i<size-1]
*/
operator fun get(i:Int): JsonObject
/**
* 获取本页内所有数据
*/
fun allData():Array<JsonObject>
} | src/main/kotlin/org/open/openstore/file/internal/querys/FilePager.kt | 4202863351 |
/*
* 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.appwidget
import android.Manifest
import android.appwidget.AppWidgetHostView
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.view.View
import android.view.ViewGroup
import android.view.ViewTreeObserver
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.core.view.children
import androidx.glance.session.GlanceSessionManager
import androidx.test.core.app.ActivityScenario
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.rules.ActivityScenarioRule
import androidx.test.filters.SdkSuppress
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.uiautomator.UiDevice
import androidx.work.WorkManager
import androidx.work.testing.WorkManagerTestInitHelper
import com.google.common.truth.Truth.assertThat
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import kotlin.test.assertIs
import kotlin.test.fail
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.junit.rules.RuleChain
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
@SdkSuppress(minSdkVersion = 29)
class AppWidgetHostRule(
private var mPortraitSize: DpSize = DpSize(200.dp, 300.dp),
private var mLandscapeSize: DpSize = DpSize(300.dp, 200.dp),
private var useSessionManager: Boolean = false,
) : TestRule {
val portraitSize: DpSize
get() = mPortraitSize
val landscapeSize: DpSize
get() = mLandscapeSize
private val mInstrumentation = InstrumentationRegistry.getInstrumentation()
private val mUiAutomation = mInstrumentation.uiAutomation
private val mActivityRule: ActivityScenarioRule<AppWidgetHostTestActivity> =
ActivityScenarioRule(AppWidgetHostTestActivity::class.java)
private val mUiDevice = UiDevice.getInstance(mInstrumentation)
// Ensure the screen starts in portrait and restore the orientation on leaving
private val mOrientationRule = TestRule { base, _ ->
object : Statement() {
override fun evaluate() {
mUiDevice.freezeRotation()
mUiDevice.setOrientationNatural()
base.evaluate()
mUiDevice.unfreezeRotation()
}
}
}
private val mInnerRules = RuleChain.outerRule(mActivityRule).around(mOrientationRule)
private var mHostStarted = false
private var mMaybeHostView: TestAppWidgetHostView? = null
private var mAppWidgetId = 0
private val mScenario: ActivityScenario<AppWidgetHostTestActivity>
get() = mActivityRule.scenario
private val mContext = ApplicationProvider.getApplicationContext<Context>()
val mHostView: TestAppWidgetHostView
get() = checkNotNull(mMaybeHostView) { "No app widget installed on the host" }
val appWidgetId: Int get() = mAppWidgetId
val device: UiDevice get() = mUiDevice
override fun apply(base: Statement, description: Description) = object : Statement() {
override fun evaluate() {
WorkManagerTestInitHelper.initializeTestWorkManager(mContext)
TestGlanceAppWidget.sessionManager =
if (useSessionManager) GlanceSessionManager else null
mInnerRules.apply(base, description).evaluate()
stopHost()
}
private fun stopHost() {
if (mHostStarted) {
mUiAutomation.dropShellPermissionIdentity()
}
WorkManager.getInstance(mContext).cancelAllWork()
}
}
/** Start the host and bind the app widget. */
fun startHost() {
mUiAutomation.adoptShellPermissionIdentity(Manifest.permission.BIND_APPWIDGET)
mHostStarted = true
mActivityRule.scenario.onActivity { activity ->
mMaybeHostView = activity.bindAppWidget(mPortraitSize, mLandscapeSize)
}
val hostView = checkNotNull(mMaybeHostView) { "Host view wasn't successfully started" }
runAndWaitForChildren {
mAppWidgetId = hostView.appWidgetId
hostView.waitForRemoteViews()
}
}
/**
* Run the [block] (usually some sort of app widget update) and wait for new RemoteViews to be
* applied.
*
* This should not be called from the main thread, i.e. in [onHostView] or [onHostActivity].
*/
suspend fun runAndWaitForUpdate(block: suspend () -> Unit) {
val hostView = checkNotNull(mMaybeHostView) { "Host view wasn't successfully started" }
hostView.resetRemoteViewsLatch()
withContext(Dispatchers.Main) { block() }
// Do not wait on the main thread so that the UI handlers can run.
runAndWaitForChildren {
hostView.waitForRemoteViews()
}
}
/**
* Set TestGlanceAppWidgetReceiver to ignore broadcasts, run [block], and then reset
* TestGlanceAppWidgetReceiver.
*/
fun ignoreBroadcasts(block: () -> Unit) {
TestGlanceAppWidgetReceiver.ignoreBroadcasts = true
try {
block()
} finally {
TestGlanceAppWidgetReceiver.ignoreBroadcasts = false
}
}
fun removeAppWidget() {
mActivityRule.scenario.onActivity { activity ->
val hostView = checkNotNull(mMaybeHostView) { "No app widget to remove" }
activity.deleteAppWidget(hostView)
}
}
fun onHostActivity(block: (AppWidgetHostTestActivity) -> Unit) {
mScenario.onActivity(block)
}
fun onHostView(block: (AppWidgetHostView) -> Unit) {
onHostActivity { block(mHostView) }
}
/**
* The top-level view is always boxed into a FrameLayout.
*
* This will retrieve the actual top-level view, skipping the boxing for the root view, and
* possibly the one to get the exact size.
*/
inline fun <reified T : View> onUnboxedHostView(crossinline block: (T) -> Unit) {
onHostActivity {
val boxingView = assertIs<ViewGroup>(mHostView.getChildAt(0))
block(boxingView.children.single().getTargetView())
}
}
/** Change the orientation to landscape.*/
fun setLandscapeOrientation() {
var activity: AppWidgetHostTestActivity? = null
onHostActivity {
it.resetConfigurationChangedLatch()
it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
activity = it
}
checkNotNull(activity).apply {
waitForConfigurationChange()
assertThat(lastConfiguration.orientation).isEqualTo(Configuration.ORIENTATION_LANDSCAPE)
}
}
/** Change the orientation to portrait.*/
fun setPortraitOrientation() {
var activity: AppWidgetHostTestActivity? = null
onHostActivity {
it.resetConfigurationChangedLatch()
it.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
activity = it
}
checkNotNull(activity).apply {
waitForConfigurationChange()
assertThat(lastConfiguration.orientation).isEqualTo(Configuration.ORIENTATION_PORTRAIT)
}
}
/**
* Set the sizes for portrait and landscape for the host view.
*
* If specified, the options bundle for the AppWidget is updated and the code waits for the
* new RemoteViews from the provider.
*
* @param portraitSize Size of the view in portrait mode.
* @param landscapeSize Size of the view in landscape. If null, the portrait and landscape sizes
* will be set to be such that portrait is narrower than tall and the landscape wider than
* tall.
* @param updateRemoteViews If the host is already started and this is true, the provider will
* be called to get a new set of RemoteViews for the new sizes.
*/
fun setSizes(
portraitSize: DpSize,
landscapeSize: DpSize? = null,
updateRemoteViews: Boolean = true
) {
val (portrait, landscape) = if (landscapeSize != null) {
portraitSize to landscapeSize
} else {
if (portraitSize.width < portraitSize.height) {
portraitSize to DpSize(portraitSize.height, portraitSize.width)
} else {
DpSize(portraitSize.height, portraitSize.width) to portraitSize
}
}
mLandscapeSize = landscape
mPortraitSize = portrait
if (!mHostStarted) return
val hostView = mMaybeHostView
if (hostView != null) {
mScenario.onActivity {
hostView.setSizes(portrait, landscape)
}
if (updateRemoteViews) {
runAndWaitForChildren {
hostView.resetRemoteViewsLatch()
AppWidgetManager.getInstance(mContext).updateAppWidgetOptions(
mAppWidgetId,
optionsBundleOf(listOf(portrait, landscape))
)
hostView.waitForRemoteViews()
}
}
}
}
fun runAndObserveUntilDraw(
condition: String = "Expected condition to be met within 5 seconds",
run: () -> Unit = {},
test: () -> Boolean
) {
val hostView = mHostView
val latch = CountDownLatch(1)
val onDrawListener = ViewTreeObserver.OnDrawListener {
if (hostView.childCount > 0 && test()) latch.countDown()
}
mActivityRule.scenario.onActivity {
hostView.viewTreeObserver.addOnDrawListener(onDrawListener)
}
run()
try {
if (test()) return
val interval = 200L
for (timeout in 0..5000L step interval) {
val countedDown = latch.await(interval, TimeUnit.MILLISECONDS)
if (countedDown || test()) return
}
fail(condition)
} finally {
latch.countDown() // make sure it's released in all conditions
mActivityRule.scenario.onActivity {
hostView.viewTreeObserver.removeOnDrawListener(onDrawListener)
}
}
}
private fun runAndWaitForChildren(action: () -> Unit) {
runAndObserveUntilDraw("Expected new children on HostView within 5 seconds", action) {
mHostView.childCount > 0
}
}
}
| glance/glance-appwidget/src/androidAndroidTest/kotlin/androidx/glance/appwidget/AppWidgetHostRule.kt | 1141893569 |
package charlie.laplacian.plugin.essential
//import charlie.laplacian.decoder.essential.FFmpegDecoderFactory
import charlie.laplacian.decoder.DecoderRegistry
import charlie.laplacian.decoder.essential.FFmpegDecoder
import charlie.laplacian.output.OutputMethodRegistry
import charlie.laplacian.output.essential.JavaSoundOutputMethod
import charlie.laplacian.source.SourceRegistry
import charlie.laplacian.source.essential.FileSource
import ro.fortsoft.pf4j.Plugin
import ro.fortsoft.pf4j.PluginWrapper
class EssentialDesktop(wrapper: PluginWrapper?) : Plugin(wrapper) {
companion object {
val VERSION = 1
val AUTHOR = "Charlie Jiang"
}
private val decoder = FFmpegDecoder()
private val outputMethod = JavaSoundOutputMethod()
private val fileSource = FileSource()
override fun start() {
DecoderRegistry.registerDecoderFactory(decoder)
FFmpegDecoder.init()
OutputMethodRegistry.registerOutputMethod(outputMethod)
SourceRegistry.registerSource(fileSource)
}
override fun stop() {
DecoderRegistry.unregisterDecoderFactory(decoder)
OutputMethodRegistry.unregisterOutputMethod(outputMethod)
SourceRegistry.unregisterSource(fileSource)
}
} | Laplacian.Essential.Desktop/src/main/kotlin/charlie/laplacian/plugin/essential/EssentialDesktop.kt | 1037894605 |
/*
Escalero - An Android dice program.
Copyright (C) 2016-2021 Karl Schreiner, [email protected]
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.androidheads.vienna.escalero
import android.app.Activity
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Paint
import android.os.Bundle
import android.text.Editable
import android.view.View
import android.widget.*
import androidx.core.content.ContextCompat
class Preferences : Activity() {
private lateinit var prefs: SharedPreferences
internal var dice = 0 // 0 : result entry, 1 : dice
private var isPlayOnline = true
private var isPlayerColumn = false
private var isDiceBoard = true
private var diceSize = 2 // 1 small, 2 medium, 3 large
private var icons = 1
private lateinit var cbLogging: CheckBox
private lateinit var cbMainDialog: CheckBox
private lateinit var diceIcon1: ImageView
private lateinit var diceIcon2: ImageView
private lateinit var diceIcon3: ImageView
private lateinit var col1: TextView
private lateinit var col2: TextView
private lateinit var col3: TextView
private lateinit var bon: TextView
private lateinit var multiplier: TextView
private lateinit var unit: TextView
private lateinit var bonusServed: TextView
private lateinit var bonusServedGrande: TextView
private lateinit var cbSummation: CheckBox
private lateinit var cbNewGame: CheckBox
private lateinit var cbSounds: CheckBox
private lateinit var cbFlipScreen: CheckBox
private lateinit var cbAdvertising: CheckBox
private lateinit var rbDiceManuel: RadioButton
private lateinit var rbDiceAutomatic: RadioButton
private lateinit var rbSizeSmall: RadioButton
private lateinit var rbSizeMedium: RadioButton
private lateinit var rbSizeLarge: RadioButton
private lateinit var rbAccountingPlayer: RadioButton
private lateinit var rbAccountingColumns: RadioButton
private lateinit var rbDimension3D: RadioButton
private lateinit var rbDimension2D: RadioButton
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.prefs)
cbLogging = findViewById<View>(R.id.cbLogging) as CheckBox
cbMainDialog = findViewById<View>(R.id.cbMainDialog) as CheckBox
diceIcon1 = findViewById<View>(R.id.dice_icon_1) as ImageView
diceIcon2 = findViewById<View>(R.id.dice_icon_2) as ImageView
diceIcon3 = findViewById<View>(R.id.dice_icon_3) as ImageView
col1 = findViewById<View>(R.id.col1) as TextView
col2 = findViewById<View>(R.id.col2) as TextView
col3 = findViewById<View>(R.id.col3) as TextView
bon = findViewById<View>(R.id.bon) as TextView
multiplier = findViewById<View>(R.id.multiplier) as TextView
unit = findViewById<View>(R.id.unit) as TextView
bonusServed = findViewById<View>(R.id.bonusServed) as TextView
bonusServedGrande = findViewById<View>(R.id.bonusServedGrande) as TextView
cbSummation = findViewById<View>(R.id.cbSummation) as CheckBox
cbNewGame = findViewById<View>(R.id.cbNewGame) as CheckBox
cbSounds = findViewById<View>(R.id.cbSounds) as CheckBox
cbFlipScreen = findViewById<View>(R.id.cbFlipScreen) as CheckBox
cbAdvertising = findViewById<View>(R.id.cbAdvertising) as CheckBox
rbDiceManuel = findViewById<View>(R.id.rbDiceManuel) as RadioButton
rbDiceAutomatic = findViewById<View>(R.id.rbDiceAutomatic) as RadioButton
rbSizeSmall = findViewById<View>(R.id.rbSizeSmall) as RadioButton
rbSizeMedium = findViewById<View>(R.id.rbSizeMedium) as RadioButton
rbSizeLarge = findViewById<View>(R.id.rbSizeLarge) as RadioButton
rbAccountingPlayer = findViewById<View>(R.id.rbAccountingPlayer) as RadioButton
rbAccountingColumns = findViewById<View>(R.id.rbAccountingColumns) as RadioButton
rbDimension3D = findViewById<View>(R.id.rbDimension3D) as RadioButton
rbDimension2D = findViewById<View>(R.id.rbDimension2D) as RadioButton
prefs = getSharedPreferences("prefs", 0)
isPlayOnline = prefs.getBoolean("playOnline", true)
cbLogging!!.isChecked = prefs.getBoolean("logging", false)
cbMainDialog!!.isChecked = prefs.getBoolean("mainDialog", true)
dice = prefs.getInt("dice", 1)
isDiceBoard = prefs.getBoolean("isDiceBoard", true)
diceSize = prefs.getInt("diceSize", 2)
icons = prefs.getInt("icons", 1)
if (prefs.getInt("icons", 1) == 1)
diceIcon1.setImageBitmap(getHoldBitmap(R.drawable._1_4, true))
if (prefs.getInt("icons", 1) == 2)
diceIcon2.setImageBitmap(getHoldBitmap(R.drawable._2_4, true))
if (prefs.getInt("icons", 1) == 3)
diceIcon3.setImageBitmap(getHoldBitmap(R.drawable._3_4, true))
col1.setText(String.format("%d", prefs.getInt("pointsCol1", 1)))
col2.setText(String.format("%d", prefs.getInt("pointsCol2", 2)))
col3.setText(String.format("%d", prefs.getInt("pointsCol3", 4)))
bon.setText(String.format("%d", prefs.getInt("pointsBon", 3)))
multiplier.setText(String.format("%d", prefs.getInt("multiplier", 1)))
unit.setText(prefs.getString("unit", resources.getString(R.string.points)))
bonusServed.setText(String.format("%d", prefs.getInt("bonusServed", 5)))
bonusServedGrande.setText(String.format("%d", prefs.getInt("bonusServedGrande", 30)))
isPlayerColumn = prefs.getBoolean("isPlayerColumn", true)
cbSummation!!.isChecked = prefs.getBoolean("isSummation", false)
cbSounds!!.isChecked = prefs.getBoolean("sounds", true)
cbFlipScreen!!.isChecked = prefs.getBoolean("computeFlipScreen", false)
cbAdvertising!!.isChecked = prefs.getBoolean("advertising", true)
cbNewGame!!.isChecked = false
if (isPlayOnline)
cbNewGame.visibility = CheckBox.INVISIBLE
if (dice == 0)
rbDiceManuel.isChecked = true
if (dice == 1)
rbDiceAutomatic.isChecked = true
if (diceSize == 1)
rbSizeSmall.isChecked = true
if (diceSize == 2)
rbSizeMedium.isChecked = true
if (diceSize == 3)
rbSizeLarge.isChecked = true
if (isPlayerColumn)
rbAccountingPlayer.isChecked = true
else
rbAccountingColumns.isChecked = true
if (isDiceBoard)
rbDimension3D.isChecked = true
else
rbDimension2D.isChecked = true
var msg = getString(R.string.player)
msg = msg.replace("0", "")
msg = msg.replace(" ", "")
rbAccountingPlayer.text = Editable.Factory.getInstance().newEditable(msg)
if (isPlayOnline) {
col1.isClickable = false
col1.isFocusable = false
col2.isClickable = false
col2.isFocusable = false
col3.isClickable = false
col3.isFocusable = false
bon.isClickable = false
bon.isFocusable = false
multiplier.isClickable = false
multiplier.isFocusable = false
unit.isClickable = false
unit.isFocusable = false
bonusServed.isClickable = false
bonusServed.isFocusable = false
bonusServedGrande.isClickable = false
bonusServedGrande.isFocusable = false
}
//karl
cbMainDialog.visibility = View.INVISIBLE
cbAdvertising.visibility = View.INVISIBLE
}
fun onRadioButtonClicked(view: View) {
val checked = view as RadioButton
if (rbDiceManuel == checked) {
dice = 0
if (isPlayOnline) {
dice = 1
rbDiceManuel.isChecked = false
rbDiceAutomatic.isChecked = true
Toast.makeText(applicationContext, getString(R.string.disabledOnline), Toast.LENGTH_SHORT).show()
}
}
if (rbDiceAutomatic == checked) { dice = 1 }
if (rbAccountingPlayer == checked) { isPlayerColumn = true }
if (rbAccountingColumns == checked) { isPlayerColumn = false }
if (rbDimension3D == checked) { isDiceBoard = true }
if (rbDimension2D == checked) { isDiceBoard = false }
if (rbSizeSmall == checked) { diceSize = 1 }
if (rbSizeMedium == checked) { diceSize = 2 }
if (rbSizeLarge == checked) { diceSize = 3 }
}
fun myClickHandler(view: View) {
val returnIntent: Intent
when (view.id) {
R.id.btnOk -> {
setPrefs()
returnIntent = Intent()
setResult(RESULT_OK, returnIntent)
finish()
}
R.id.dice_icon_1 -> {
icons = 1
diceIcon1.setImageBitmap(getHoldBitmap(R.drawable._1_4, true))
diceIcon2.setImageBitmap(getHoldBitmap(R.drawable._2_4, false))
diceIcon3.setImageBitmap(getHoldBitmap(R.drawable._3_4, false))
}
R.id.dice_icon_2 -> {
icons = 2
diceIcon2.setImageBitmap(getHoldBitmap(R.drawable._2_4, true))
diceIcon1.setImageBitmap(getHoldBitmap(R.drawable._1_4, false))
diceIcon3.setImageBitmap(getHoldBitmap(R.drawable._3_4, false))
}
R.id.dice_icon_3 -> {
icons = 3
diceIcon3.setImageBitmap(getHoldBitmap(R.drawable._3_4, true))
diceIcon1.setImageBitmap(getHoldBitmap(R.drawable._1_4, false))
diceIcon2.setImageBitmap(getHoldBitmap(R.drawable._2_4, false))
}
}
}
private fun getHoldBitmap(imageId: Int, isDrawRect: Boolean): Bitmap {
// hold BORDER
val bm = BitmapFactory.decodeResource(this.resources, imageId).copy(Bitmap.Config.ARGB_8888, true)
val canvas = Canvas()
canvas.setBitmap(bm)
val paint = Paint()
val stroke = canvas.width / 6
paint.strokeWidth = stroke.toFloat()
paint.color = ContextCompat.getColor(this, R.color.colorHold)
paint.style = Paint.Style.STROKE
val width = canvas.width.toFloat()
val height = canvas.height.toFloat()
if (isDrawRect)
canvas.drawRect(0f, 0f, width, height, paint)
return bm
}
private fun setPrefs() {
val ed = prefs.edit()
ed.putInt("dice", dice)
ed.putBoolean("isDiceBoard", isDiceBoard)
ed.putInt("diceSize", diceSize)
ed.putInt("icons", icons)
ed.putBoolean("isPlayerColumn", isPlayerColumn)
if (!col1.text.isNullOrEmpty())
ed.putInt("pointsCol1", Integer.parseInt(col1.text.toString()))
if (!col2.text.isNullOrEmpty())
ed.putInt("pointsCol2", Integer.parseInt(col2.text.toString()))
if (!col3.text.isNullOrEmpty())
ed.putInt("pointsCol3", Integer.parseInt(col3.text.toString()))
if (!bon.text.isNullOrEmpty())
ed.putInt("pointsBon", Integer.parseInt(bon.text.toString()))
if (!multiplier.text.isNullOrEmpty())
ed.putInt("multiplier", Integer.parseInt(multiplier.text.toString()))
if (unit.text != null)
ed.putString("unit", unit.text.toString())
if (!bonusServed.text.isNullOrEmpty())
ed.putInt("bonusServed", Integer.parseInt(bonusServed.text.toString()))
if (!bonusServedGrande.text.isNullOrEmpty())
ed.putInt("bonusServedGrande", Integer.parseInt(bonusServedGrande.text.toString()))
if (cbSummation != null)
ed.putBoolean("isSummation", cbSummation!!.isChecked)
if (cbSounds != null)
ed.putBoolean("sounds", cbSounds!!.isChecked)
if (cbFlipScreen != null) {
if (isPlayOnline)
ed.putBoolean("computeFlipScreen", false)
else
ed.putBoolean("computeFlipScreen", cbFlipScreen!!.isChecked)
}
if (cbLogging != null)
ed.putBoolean("logging", cbLogging!!.isChecked)
ed.putBoolean("mainDialog", false)
ed.putBoolean("advertising", true)
if (cbNewGame != null)
ed.putBoolean("cbNewGame", cbNewGame!!.isChecked)
ed.apply()
var col1 = prefs.getInt("pointsCol1", 1)
var col2 = prefs.getInt("pointsCol2", 2)
var col3 = prefs.getInt("pointsCol3", 4)
for (i in 0..1) {
if (col1 > col2) {
val tmp = col2
col2 = col1
col1 = tmp
}
if (col2 > col3) {
val tmp = col3
col3 = col2
col2 = tmp
}
}
ed.putInt("pointsCol1", col1)
ed.putInt("pointsCol2", col2)
ed.putInt("pointsCol3", col3)
ed.apply()
}
companion object {
const val TAG = "Preferences"
}
}
| app/src/main/java/com/androidheads/vienna/escalero/Preferences.kt | 3440585480 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// VERSION: v0_103
// GENERATED CODE - DO NOT MODIFY BY HAND
package androidx.compose.material3.tokens
internal enum class ShapeKeyTokens {
CornerExtraLarge,
CornerExtraLargeTop,
CornerExtraSmall,
CornerExtraSmallTop,
CornerFull,
CornerLarge,
CornerLargeEnd,
CornerLargeTop,
CornerMedium,
CornerNone,
CornerSmall,
} | compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/tokens/ShapeKeyTokens.kt | 3457050710 |
package de.holisticon.ranked.service.elo
import de.holisticon.ranked.properties.createProperties
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.data.Offset
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.junit.runners.Parameterized.Parameters
class EloCalculationServiceSpec {
private val service = EloCalculationService(factor = 20, maxDifference = 400)
companion object {
val MAX_MEAN = 0.9090909f
val MIN_MEAN = 0.09090909f
val PROBABILITY_MAX = 1f
}
@Test
fun ` understand float math first`() {
assertThat(MAX_MEAN + MIN_MEAN).isEqualTo(PROBABILITY_MAX)
}
@Test
fun `calculate equal mean`() {
val mean = service.mean(1000, 1000)
assertThat(mean).isEqualTo(PROBABILITY_MAX.div(2))
}
@Test
fun `calculate equal null mean`() {
val mean = service.mean(0, 0)
assertThat(mean).isEqualTo(PROBABILITY_MAX.div(2))
}
@Test
fun `calculate max mean`() {
val mean = service.mean(800, 400)
assertThat(mean).isEqualTo(MAX_MEAN)
}
@Test
fun `calculate max mean beyond threshold`() {
val mean = service.mean(1400, 400)
assertThat(mean).isEqualTo(MAX_MEAN)
}
@Test
fun `calculate min mean`() {
val mean = service.mean(400, 800)
assertThat(mean).isEqualTo(MIN_MEAN)
}
@Test
fun `calculate min mean below threshold`() {
val mean = service.mean(100, 800)
assertThat(mean).isEqualTo(MIN_MEAN)
}
@Test
fun `two means should result in probability of 1`() {
val elo1 = 1431
val elo2 = 1671
val mean1 = service.mean(elo1, elo2)
val mean2 = service.mean(elo2, elo1)
assertThat(mean1 + mean2).isEqualTo(PROBABILITY_MAX)
}
@Test
fun `calculate new elo`() {
val elo = Pair(1431, 1671)
val newElo = service.calculateElo(elo)
// winner should receive elo points
assertThat(newElo.first).isGreaterThan(elo.first)
// looser should loose elo points
assertThat(newElo.second).isLessThan(elo.second)
// elo is ranking, it only distributed elo points
assertThat(newElo.first - elo.first).isEqualTo(elo.second - newElo.second)
}
@Test
fun `calculate new elo by equal game`() {
val elo = Pair(1431, 1431)
val newElo = service.calculateElo(elo)
// winner should receive elo points
assertThat(newElo.first).isGreaterThan(elo.first)
// looser should loose elo points
assertThat(newElo.second).isLessThan(elo.second)
// by equal ranking, the probability to win is 50% (mean = 0.5f)
// and eloFactor is 20, so the elo receipt/loss is 0,5 * 20 = 10 points
val expected = (PROBABILITY_MAX.div(2) * service.factor).toInt()
assertThat(newElo.first - elo.first).isEqualTo(expected)
assertThat(elo.second - newElo.second).isEqualTo(expected)
}
@Test
fun `calculate zero touching elo`() {
val elo = Pair(0, 7)
val newElo = service.calculateElo(elo)
// winner should usually receive 10 elo points, but the looser only has 7
assertThat(newElo.first).isEqualTo(elo.second)
// looser should loose elo points
assertThat(newElo.second).isEqualTo(0)
}
@Test
fun `calculate team elo`() {
// winner has team elo of (300 + 700) / 2 = 1000 / 2 = 500
val winner = Pair(300, 700)
// looser has team elo of (400 + 600) / 2 = 1000 / 2 = 500
val looser = Pair(400, 600)
// equal team elo => 10 point per team (got, lost)
val result = service.calculateTeamElo(winner, looser)
// every winner won 5 points
assertThat(result.first.first).isEqualTo(winner.first + 5)
assertThat(result.first.second).isEqualTo(winner.second + 5)
// every looser lost 5 points
assertThat(result.second.first).isEqualTo(looser.first - 5)
assertThat(result.second.second).isEqualTo(looser.second - 5)
// elo is pure distribution, no elo points get into the system or from the system
assertThat(winner.first + winner.second + looser.first + looser.second)
.isEqualTo(result.first.first + result.first.second + result.second.first + result.second.second)
}
@Test
fun `single elo 1000-1000`() {
assertThat(service.calculateElo(Pair(1000,1000))).isEqualTo(Pair(1010,990))
}
@Test
fun `single elo 1100-1000`() {
assertThat(service.calculateElo(Pair(1100,1000))).isEqualTo(Pair(1107,993))
}
}
@RunWith(Parameterized::class)
class MeanSpec(
val own: Int,
val enemy: Int,
val expectedMean : Float
) {
companion object {
@JvmStatic
@Parameters(name="{index} {0}-{1} expected:{2}")
fun data() : Collection<Array<Any>> {
return listOf(
arrayOf(1000,1000, 0.5f),
arrayOf(1100,1000, 0.64f),
arrayOf(1200,1000, 0.76f),
arrayOf(1300,1000, 0.85f),
arrayOf(1400,1000, 0.91f),
arrayOf(1500,1000, 0.91f) // max difference limit
)
}
}
@Test
fun `evaluate mean factor`() {
assertThat(EloCalculationService(factor = 20, maxDifference = 400).mean(own, enemy)).isEqualTo(expectedMean, Offset.offset(.001f))
}
}
| backend/services/elo/src/test/kotlin/EloCalculationServiceSpec.kt | 4049711215 |
package com.baeldung.kotlin.arrow
import arrow.core.Either
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.NotANumber
import com.baeldung.kotlin.arrow.FunctionalErrorHandlingWithEither.ComputeProblem.OddNumber
import org.junit.Assert
import org.junit.Test
class FunctionalErrorHandlingWithEitherTest {
val operator = FunctionalErrorHandlingWithEither()
@Test
fun givenInvalidInput_whenComputeInvoked_NotANumberIsPresent(){
val computeWithEither = operator.computeWithEither("bar")
Assert.assertTrue(computeWithEither.isLeft())
when(computeWithEither){
is Either.Left -> when(computeWithEither.a){
NotANumber -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenOddNumberInput_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("121")
Assert.assertTrue(computeWithEither.isLeft())
when(computeWithEither){
is Either.Left -> when(computeWithEither.a){
OddNumber -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenEvenNumberWithoutSquare_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("100")
Assert.assertTrue(computeWithEither.isRight())
when(computeWithEither){
is Either.Right -> when(computeWithEither.b){
false -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
@Test
fun givenEvenNumberWithSquare_whenComputeInvoked_OddNumberIsPresent(){
val computeWithEither = operator.computeWithEither("98")
Assert.assertTrue(computeWithEither.isRight())
when(computeWithEither){
is Either.Right -> when(computeWithEither.b){
true -> "Ok."
else -> Assert.fail()
}
else -> Assert.fail()
}
}
} | projects/tutorials-master/tutorials-master/kotlin-libraries/src/test/kotlin/com/baeldung/kotlin/arrow/FunctionalErrorHandlingWithEitherTest.kt | 2826135862 |
package com.percolate.sdk.dto
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.annotation.JsonInclude
import com.openpojo.reflection.PojoClass
import com.openpojo.reflection.filters.FilterClassName
import com.openpojo.reflection.filters.FilterEnum
import com.openpojo.reflection.filters.FilterSyntheticClasses
import com.openpojo.validation.ValidatorBuilder
import com.openpojo.validation.affirm.Affirm
import com.openpojo.validation.rule.impl.NoNestedClassRule
import com.openpojo.validation.rule.impl.NoStaticExceptFinalRule
import com.openpojo.validation.rule.impl.SerializableMustHaveSerialVersionUIDRule
import com.openpojo.validation.test.Tester
import com.openpojo.validation.test.impl.GetterTester
import com.openpojo.validation.test.impl.SetterTester
import com.openpojo.validation.utils.ValidationHelper
import org.junit.Test
/**
* This test class uses OpenPojo to test all of our DTO classes dynamically.
* Docs available here: https://github.com/oshoukry/openpojo
*/
class DtosTest {
@Test
fun testAllDtos() {
val validator = ValidatorBuilder.create().with(SetterTester()) // Test all setter methods
.with(GetterTester()) // Test all getter methods
.with(OpenPojoToStringTester()) // Test for custom toString() method
.with(OpenPojoHasExpectedAnnotationsTester()) // Ensure all DTOs have any required annotations
.with(NoNestedClassRule()) // Pojo's should stay simple, don't allow nested classes.
.with(NoStaticExceptFinalRule()) // Static fields must be final.
.with(SerializableMustHaveSerialVersionUIDRule()) // Serializable classes must have serialVersionUID.
.build()
validator.validate("com.percolate.sdk.dto",
FilterClassName(".*(?<!Test)$"), //Filter classes that end with "Test"
FilterClassName(".*(?<!Tester)$"), //Filter classes that end with "Tester"
FilterSyntheticClasses(), //Filter any synthetic classes
FilterEnum() //Skip enums (needed because of `NoNestedClassRule` rule)
)
}
/**
* This class implements OpenPojo's `Tester` interface.
* It runs `toString()` for each class passed into it to make sure
* our custom `toString()` method format is detected.
*/
internal inner class OpenPojoToStringTester : Tester {
override fun run(pojoClass: PojoClass) {
val classInstance = ValidationHelper.getBasicInstance(pojoClass)
val fullClassName = classInstance.javaClass.canonicalName
val simpleClassName = classInstance.javaClass.simpleName
val toString = classInstance.toString()
val startsAsExpected = toString.startsWith(simpleClassName + "[")
Affirm.affirmTrue("No toString() found in " + fullClassName, startsAsExpected)
}
}
/**
* This class implements OpenPojo's `Tester` interface.
* It makes sure that all DTOs are annotated with 2 annotations that we require on
* all objects: @JsonIgnoreProperties and @JsonInclude.
*/
internal inner class OpenPojoHasExpectedAnnotationsTester : Tester {
override fun run(pojoClass: PojoClass) {
val classInstance = ValidationHelper.getBasicInstance(pojoClass)
val fullClassName = classInstance.javaClass.canonicalName
val hasJsonIgnorePropertiesAnnotation = classInstance.javaClass.isAnnotationPresent(JsonIgnoreProperties::class.java)
val hasJsonIncludeAnnotation = classInstance.javaClass.isAnnotationPresent(JsonInclude::class.java)
Affirm.affirmTrue("Expected annotation @JsonIgnoreProperties not found on " + fullClassName, hasJsonIgnorePropertiesAnnotation);
Affirm.affirmTrue("Expected annotation @JsonInclude not found on " + fullClassName, hasJsonIncludeAnnotation);
}
}
}
| core/src/test/java/com/percolate/sdk/dto/DtosTest.kt | 2598618197 |
/*
* 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 com.intellij.debugger.streams.trace.dsl
/**
* @author Vitaliy.Bibaev
*/
interface VariableDeclaration : Statement {
val variable: Variable
val isMutable: Boolean
}
| src/main/java/com/intellij/debugger/streams/trace/dsl/VariableDeclaration.kt | 615094416 |
fun main(args : Array<String>) {
for (i in 1..100) {
when {
i%3 == 0 -> {print("Fizz"); continue;}
i%5 == 0 -> {print("Buzz"); continue;}
(i%3 != 0 && i%5 != 0) -> {print(i); continue;}
else -> println()
}
}
}
fun foo() : Unit <selection>{
println() {
println()
pr<caret>intln()
println()
}
println(array(1, 2, 3))
println()
}</selection> | kotlin-eclipse-ui-test/testData/wordSelection/selectEnclosing/StatementsWithWindowsDelimiter/7.kt | 4251351511 |
package org.edx.mobile.view
import android.content.Context
import android.os.Bundle
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentTransaction
import com.google.inject.Inject
import kotlinx.android.synthetic.main.fragment_payments_banner.*
import org.edx.mobile.R
import org.edx.mobile.base.BaseFragment
import org.edx.mobile.core.IEdxEnvironment
import org.edx.mobile.databinding.FragmentPaymentsBannerBinding
import org.edx.mobile.model.api.CourseUpgradeResponse
import org.edx.mobile.model.api.EnrolledCoursesResponse
import org.edx.mobile.model.course.CourseComponent
class PaymentsBannerFragment : BaseFragment() {
@Inject
var environment: IEdxEnvironment? = null
companion object {
private const val EXTRA_SHOW_INFO_BUTTON = "show_info_button"
private fun newInstance(courseData: EnrolledCoursesResponse,
courseUnit: CourseComponent?,
courseUpgradeData: CourseUpgradeResponse,
showInfoButton: Boolean): Fragment {
val fragment = PaymentsBannerFragment()
val bundle = Bundle()
bundle.putSerializable(Router.EXTRA_COURSE_DATA, courseData)
bundle.putSerializable(Router.EXTRA_COURSE_UNIT, courseUnit)
bundle.putParcelable(Router.EXTRA_COURSE_UPGRADE_DATA, courseUpgradeData)
bundle.putBoolean(EXTRA_SHOW_INFO_BUTTON, showInfoButton)
fragment.arguments = bundle
return fragment
}
fun loadPaymentsBannerFragment(containerId: Int,
courseData: EnrolledCoursesResponse,
courseUnit: CourseComponent?,
courseUpgradeData: CourseUpgradeResponse, showInfoButton: Boolean,
childFragmentManager: FragmentManager, animate: Boolean) {
val frag: Fragment? = childFragmentManager.findFragmentByTag("payment_banner_frag")
if (frag != null) {
// Payment banner already exists
return
}
val fragment: Fragment = newInstance(courseData, courseUnit, courseUpgradeData, showInfoButton)
// This activity will only ever hold this lone fragment, so we
// can afford to retain the instance during activity recreation
fragment.retainInstance = true
val fragmentTransaction: FragmentTransaction = childFragmentManager.beginTransaction()
if (animate) {
fragmentTransaction.setCustomAnimations(R.anim.slide_up, android.R.anim.fade_out)
}
fragmentTransaction.replace(containerId, fragment, "payment_banner_frag")
fragmentTransaction.disallowAddToBackStack()
fragmentTransaction.commitAllowingStateLoss()
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val binding: FragmentPaymentsBannerBinding =
DataBindingUtil.inflate(inflater, R.layout.fragment_payments_banner, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
populateCourseUpgradeBanner(view.context)
}
private fun populateCourseUpgradeBanner(context: Context) {
val courseUpgradeData: CourseUpgradeResponse =
arguments?.getParcelable(Router.EXTRA_COURSE_UPGRADE_DATA) as CourseUpgradeResponse
val courseData: EnrolledCoursesResponse =
arguments?.getSerializable(Router.EXTRA_COURSE_DATA) as EnrolledCoursesResponse
val showInfoButton: Boolean = arguments?.getBoolean(EXTRA_SHOW_INFO_BUTTON) ?: false
upgrade_to_verified_footer.visibility = View.VISIBLE
if (showInfoButton) {
info.visibility = View.VISIBLE
info.setOnClickListener {
environment?.router?.showPaymentsInfoActivity(context, courseData, courseUpgradeData)
}
} else {
info.visibility = View.GONE
}
if (!TextUtils.isEmpty(courseUpgradeData.price)) {
tv_upgrade_price.text = courseUpgradeData.price
} else {
tv_upgrade_price.visibility = View.GONE
}
val courseUnit: CourseComponent? = arguments?.getSerializable(Router.EXTRA_COURSE_UNIT) as CourseComponent?
courseUpgradeData.basketUrl?.let { basketUrl ->
ll_upgrade_button.setOnClickListener {
environment?.router?.showCourseUpgradeWebViewActivity(
context, basketUrl, courseData, courseUnit)
}
}
}
}
| OpenEdXMobile/src/main/java/org/edx/mobile/view/PaymentsBannerFragment.kt | 2299346335 |
package com.wealthfront.magellan.navigation
import com.wealthfront.magellan.Direction
import com.wealthfront.magellan.core.Navigable
import com.wealthfront.magellan.lifecycle.LifecycleAware
import com.wealthfront.magellan.transitions.MagellanTransition
import java.util.Deque
public interface LinearNavigator : Navigator, LifecycleAware {
public fun goTo(navigable: Navigable, overrideMagellanTransition: MagellanTransition? = null)
public fun replace(navigable: Navigable, overrideMagellanTransition: MagellanTransition? = null)
public fun navigate(
direction: Direction,
backStackOperation: (Deque<NavigationEvent>) -> MagellanTransition
)
}
| magellan-library/src/main/java/com/wealthfront/magellan/navigation/LinearNavigator.kt | 2824570298 |
/*
* 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 2.1 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with Foobar. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.android.darwin
import android.accounts.Account
import android.accounts.AccountManager
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.os.Build
import android.support.annotation.WorkerThread
import android.util.Log
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import nl.adaptivity.android.coroutines.CoroutineActivity
import nl.adaptivity.android.coroutines.getAuthToken
import java.io.IOException
import java.net.*
/**
* A class making it easier to make authenticated requests to darwin.
*
*/
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
internal class AuthenticatedWebClientV14(override val account: Account, override val authBase: URI?) : AuthenticatedWebClient {
private var token: String? = null
private val cookieManager: CookieManager by lazy<CookieManager> {
CookieManager(MyCookieStore(), CookiePolicy.ACCEPT_ORIGINAL_SERVER).also {
CookieHandler.setDefault(it)
}
}
@WorkerThread
@Throws(IOException::class)
override fun execute(context: Context, request: AuthenticatedWebClient.WebRequest): HttpURLConnection? {
return execute(context, request, false)
}
suspend fun execute(activity: Activity, request: AuthenticatedWebClient.WebRequest): HttpURLConnection? {
val am = AccountManager.get(activity)
@Suppress("DEPRECATION")
val token = am.getAuthToken(activity, account, AuthenticatedWebClient.ACCOUNT_TOKEN_TYPE)
if (token!=null) {
val cookieUri = request.uri
val cookieStore = cookieManager.cookieStore
for(repeat in 0..1) {
val cookie = HttpCookie(AuthenticatedWebClient.DARWIN_AUTH_COOKIE, token)
if ("https" == request.uri.scheme.toLowerCase()) {
cookie.secure = true
}
removeConflictingCookies(cookieStore, cookie)
cookieStore.add(cookieUri, cookie)
request.setHeader(AuthenticatedWebClient.DARWIN_AUTH_COOKIE, token)
val connection = request.connection
when {
connection.responseCode == HttpURLConnection.HTTP_UNAUTHORIZED && repeat==0 -> {
try {
connection.errorStream.use { errorStream ->
errorStream.skip(Int.MAX_VALUE.toLong())
}
} finally {
connection.disconnect()
}
Log.d(TAG, "execute: Invalidating auth token")
am.invalidateAuthToken(AuthenticatedWebClient.ACCOUNT_TYPE, token)
}
else -> return connection
}
}
}
return null
}
override fun <A> A.execute(
request: AuthenticatedWebClient.WebRequest,
currentlyInRetry: Boolean,
onError: RequestFailure,
onSuccess: RequestSuccess
): Job where A : Activity, A : CoroutineScope {
return launch {
val connection = execute(this@execute, request)
when {
connection==null -> onError(null)
connection.responseCode in 200..399 -> try { onSuccess(connection) } finally { connection.disconnect() }
else -> try { onError(connection) } finally { connection.disconnect() }
}
}
}
@WorkerThread
@Throws(IOException::class)
private fun execute(context: Context, request: AuthenticatedWebClient.WebRequest, currentlyInRetry: Boolean): HttpURLConnection? {
Log.d(TAG, "execute() called with: request = [$request], currentlyInRetry = [$currentlyInRetry]")
val accountManager = AccountManager.get(context)
token = getAuthToken(context, accountManager)
if (token == null) {
return null
}
val cookieUri = request.uri
// cookieUri = cookieUri.resolve("/");
val cookie = HttpCookie(AuthenticatedWebClient.DARWIN_AUTH_COOKIE, token)
// cookie.setDomain(cookieUri.getHost());
// cookie.setVersion(1);
// cookie.setPath("/");
if ("https" == request.uri.scheme.toLowerCase()) {
cookie.secure = true
}
val cookieStore = cookieManager.cookieStore
removeConflictingCookies(cookieStore, cookie)
cookieStore.add(cookieUri, cookie)
request.setHeader(AuthenticatedWebClient.DARWIN_AUTH_COOKIE, token!!)
val connection = request.connection
try {
if (connection.responseCode == HttpURLConnection.HTTP_UNAUTHORIZED) {
connection.errorStream.use { errorStream ->
errorStream.skip(Int.MAX_VALUE.toLong())
}
Log.d(TAG, "execute: Invalidating auth token")
accountManager.invalidateAuthToken(AuthenticatedWebClient.ACCOUNT_TYPE, token)
if (!currentlyInRetry) { // Do not repeat retry
return execute(context, request, true)
}
}
return connection
} catch (e: Throwable) { // Catch exception as there would be no way for a caller to disconnect
connection.disconnect()
throw e
}
}
private fun removeConflictingCookies(cookieStore: CookieStore, refCookie: HttpCookie) {
val toRemove = cookieStore.cookies.filter { it.name == refCookie.name }
for (c in toRemove) {
for (url in cookieStore.urIs) {
cookieStore.remove(url, c)
}
}
}
@WorkerThread
private fun getAuthToken(context: Context, accountManager: AccountManager): String? {
if (token != null) return token
return AuthenticatedWebClientFactory.getAuthToken(accountManager, context, this.authBase, this.account)
}
companion object {
private val TAG = AuthenticatedWebClientV14::class.java.name
}
} | src/main/java/nl/adaptivity/android/darwin/AuthenticatedWebClientV14.kt | 1923180832 |
package org.ccci.gto.android.common.api.okhttp3.interceptor
import android.content.Context
import android.content.SharedPreferences
import androidx.annotation.CallSuper
import androidx.annotation.VisibleForTesting
import java.io.IOException
import okhttp3.Interceptor
import okhttp3.Interceptor.Chain
import okhttp3.Request
import okhttp3.Response
import org.ccci.gto.android.common.api.Session
import org.ccci.gto.android.common.api.okhttp3.EstablishSessionApiException
import org.ccci.gto.android.common.api.okhttp3.InvalidSessionApiException
private const val DEFAULT_RETURN_INVALID_SESSION_RESPONSES = false
abstract class SessionInterceptor<S : Session> @JvmOverloads protected constructor(
context: Context,
private val returnInvalidSessionResponses: Boolean = DEFAULT_RETURN_INVALID_SESSION_RESPONSES,
prefFile: String? = null
) : Interceptor {
protected val context: Context = context.applicationContext
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal val prefFileName = prefFile?.also { require(it.isNotEmpty()) { "prefFile cannot be an empty string" } }
?: generateSequence<Class<*>>(javaClass) { it.superclass }
.mapNotNull { it.simpleName.takeUnless { it.isEmpty() } }
.first()
protected val prefs by lazy { this.context.getSharedPreferences(prefFileName, Context.MODE_PRIVATE) }
protected val lockSession = Any()
@JvmField
@Deprecated("Since v3.10.0, use lockSession property instead", ReplaceWith("lockSession"))
protected val mLockSession = lockSession
@JvmField
@Deprecated("Since v3.10.0, use context property instead", ReplaceWith("context"))
protected val mContext = this.context
@Deprecated("Since v3.10.0, use named parameters for the constructor instead.")
protected constructor(context: Context, prefFile: String?) :
this(context, DEFAULT_RETURN_INVALID_SESSION_RESPONSES, prefFile)
@Throws(IOException::class)
override fun intercept(chain: Chain): Response {
val session = synchronized(lockSession) {
// load a valid session
loadSession()?.takeIf { it.isValid }
// otherwise try establishing a session
?: try {
establishSession()?.takeIf { it.isValid }?.also { saveSession(it) }
} catch (e: IOException) {
throw EstablishSessionApiException(e)
}
} ?: throw InvalidSessionApiException()
return processResponse(chain.proceed(attachSession(chain.request(), session)), session)
}
protected abstract fun attachSession(request: Request, session: S): Request
@CallSuper
@Throws(IOException::class)
protected open fun processResponse(response: Response, session: S): Response {
if (isSessionInvalid(response)) {
// reset the session if this is still the same session
synchronized(lockSession) {
loadSession()?.takeIf { it == session }?.apply { deleteSession(this) }
}
if (!returnInvalidSessionResponses) throw InvalidSessionApiException()
}
return response
}
@Throws(IOException::class)
open fun isSessionInvalid(response: Response) = false
private fun loadSession() = synchronized(lockSession) { loadSession(prefs) }?.takeIf { it.isValid }
protected abstract fun loadSession(prefs: SharedPreferences): S?
@Throws(IOException::class)
protected open fun establishSession(): S? = null
private fun saveSession(session: Session) {
val changes = prefs.edit().apply { session.save(this) }
synchronized(lockSession) { changes.apply() }
}
private fun deleteSession(session: Session) {
val changes = prefs.edit().apply { session.delete(this) }
synchronized(lockSession) { changes.apply() }
}
}
| gto-support-api-okhttp3/src/main/java/org/ccci/gto/android/common/api/okhttp3/interceptor/SessionInterceptor.kt | 3979337016 |
/*
* Copyright (c) 2017. tangzx([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.tang.intellij.lua.stubs
import com.intellij.lang.ASTNode
import com.intellij.psi.stubs.IndexSink
import com.intellij.psi.stubs.StubElement
import com.intellij.psi.stubs.StubInputStream
import com.intellij.psi.stubs.StubOutputStream
import com.intellij.util.io.StringRef
import com.tang.intellij.lua.psi.LuaLocalFuncDef
import com.tang.intellij.lua.psi.LuaParamInfo
import com.tang.intellij.lua.psi.impl.LuaLocalFuncDefImpl
import com.tang.intellij.lua.psi.overloads
import com.tang.intellij.lua.psi.tyParams
import com.tang.intellij.lua.ty.IFunSignature
import com.tang.intellij.lua.ty.ITy
import com.tang.intellij.lua.ty.TyParameter
class LuaLocalFuncDefElementType
: LuaStubElementType<LuaLocalFuncDefStub, LuaLocalFuncDef>("LOCAL_FUNC_DEF") {
override fun serialize(stub: LuaLocalFuncDefStub, stream: StubOutputStream) {
stream.writeName(stub.name)
stream.writeTyNullable(stub.returnDocTy)
stream.writeTyNullable(stub.varargTy)
stream.writeParamInfoArray(stub.params)
stream.writeTyParams(stub.tyParams)
stream.writeSignatures(stub.overloads)
}
override fun shouldCreateStub(node: ASTNode): Boolean {
val psi = node.psi as LuaLocalFuncDef
return createStubIfParentIsStub(node) && psi.name != null
}
override fun createStub(def: LuaLocalFuncDef, parentStub: StubElement<*>?): LuaLocalFuncDefStub {
val retDocTy = def.comment?.tagReturn?.type
val params = def.params
val tyParams = def.tyParams
val overloads = def.overloads
return LuaLocalFuncDefStub(def.name!!,
retDocTy,
def.varargType,
params,
tyParams,
overloads,
parentStub,
this)
}
override fun deserialize(stream: StubInputStream, parentStub: StubElement<*>?): LuaLocalFuncDefStub {
val name = stream.readName()
val retDocTy = stream.readTyNullable()
val varargTy = stream.readTyNullable()
val params = stream.readParamInfoArray()
val tyParams = stream.readTyParams()
val overloads = stream.readSignatures()
return LuaLocalFuncDefStub(StringRef.toString(name),
retDocTy,
varargTy,
params,
tyParams,
overloads,
parentStub,
this)
}
override fun indexStub(stub: LuaLocalFuncDefStub, sink: IndexSink) {
}
override fun createPsi(stub: LuaLocalFuncDefStub): LuaLocalFuncDef {
return LuaLocalFuncDefImpl(stub, this)
}
}
class LuaLocalFuncDefStub(
val name: String,
override val returnDocTy: ITy?,
override val varargTy: ITy?,
override val params: Array<LuaParamInfo>,
override val tyParams: Array<TyParameter>,
override val overloads: Array<IFunSignature>,
parent: StubElement<*>?,
type: LuaStubElementType<*, *>
) : LuaStubBase<LuaLocalFuncDef>(parent, type), LuaFuncBodyOwnerStub<LuaLocalFuncDef> | src/main/java/com/tang/intellij/lua/stubs/LuaLocalFuncDefStub.kt | 26951546 |
/*
* Copyright 2017 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.topeka.activity
import android.support.test.InstrumentationRegistry
import android.support.test.espresso.Espresso.onData
import android.support.test.espresso.Espresso.onView
import android.support.test.espresso.action.ViewActions.click
import android.support.test.espresso.action.ViewActions.closeSoftKeyboard
import android.support.test.espresso.action.ViewActions.typeText
import android.support.test.espresso.assertion.ViewAssertions.matches
import android.support.test.espresso.matcher.ViewMatchers.assertThat
import android.support.test.espresso.matcher.ViewMatchers.isChecked
import android.support.test.espresso.matcher.ViewMatchers.isClickable
import android.support.test.espresso.matcher.ViewMatchers.isDisplayed
import android.support.test.espresso.matcher.ViewMatchers.isEnabled
import android.support.test.espresso.matcher.ViewMatchers.isFocusable
import android.support.test.espresso.matcher.ViewMatchers.withId
import android.support.test.espresso.matcher.ViewMatchers.withText
import android.support.test.filters.LargeTest
import android.support.test.rule.ActivityTestRule
import android.support.test.runner.AndroidJUnit4
import android.view.View
import com.google.samples.apps.topeka.R
import com.google.samples.apps.topeka.helper.isSignedIn
import com.google.samples.apps.topeka.helper.signOut
import com.google.samples.apps.topeka.model.Avatar
import com.google.samples.apps.topeka.model.TEST_AVATAR
import com.google.samples.apps.topeka.model.TEST_FIRST_NAME
import com.google.samples.apps.topeka.model.TEST_LAST_INITIAL
import org.hamcrest.Matcher
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.equalTo
import org.hamcrest.Matchers.isEmptyOrNullString
import org.hamcrest.Matchers.not
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@LargeTest
class SignInActivityTest {
@Suppress("unused") // actually used by Espresso
val activityRule @Rule get() = object :
ActivityTestRule<SignInActivity>(SignInActivity::class.java) {
override fun beforeActivityLaunched() {
InstrumentationRegistry.getTargetContext().signOut()
}
}
@Before fun clearPreferences() {
InstrumentationRegistry.getTargetContext().signOut()
}
@Test fun checkFab_initiallyNotDisplayed() {
onView(withId(R.id.done)).check(matches(not(isDisplayed())))
}
@Test fun signIn_withoutFirstNameFailed() {
inputData(null, TEST_LAST_INITIAL, TEST_AVATAR)
onDoneView().check(matches(not(isDisplayed())))
}
@Test fun signIn_withoutLastInitialFailed() {
inputData(TEST_FIRST_NAME, null, TEST_AVATAR)
onDoneView().check(matches(not(isDisplayed())))
}
@Test fun signIn_withoutAvatarFailed() {
inputData(TEST_FIRST_NAME, TEST_LAST_INITIAL, null)
onDoneView().check(matches(not(isDisplayed())))
}
@Test fun signIn_withAllPlayerPreferencesSuccessfully() {
inputData(TEST_FIRST_NAME, TEST_LAST_INITIAL, TEST_AVATAR)
onDoneView().check(matches(isDisplayed()))
}
@Test fun signIn_performSignIn() {
inputData(TEST_FIRST_NAME, TEST_LAST_INITIAL, TEST_AVATAR)
onDoneView().perform(click())
assertThat(InstrumentationRegistry.getTargetContext().isSignedIn(), `is`(true))
}
private fun onDoneView() = onView(withId(R.id.done))
@Test fun signIn_withLongLastName() {
typeAndHideKeyboard(R.id.last_initial, TEST_FIRST_NAME)
val expectedValue = TEST_FIRST_NAME[0].toString()
onView(withId(R.id.last_initial)).check(matches(withText(expectedValue)))
}
private fun inputData(firstName: String?, lastInitial: String?, avatar: Avatar?) {
if (firstName != null) typeAndHideKeyboard(R.id.first_name, firstName)
if (lastInitial != null) typeAndHideKeyboard(R.id.last_initial, lastInitial)
if (avatar != null) clickAvatar(avatar)
}
private fun typeAndHideKeyboard(targetViewId: Int, text: String) {
onView(withId(targetViewId)).perform(typeText(text), closeSoftKeyboard())
}
private fun clickAvatar(avatar: Avatar) {
onData(equalTo(avatar))
.inAdapterView(withId(R.id.avatars))
.perform(click())
}
@Test fun firstName_isInitiallyEmpty() = editTextIsEmpty(R.id.first_name)
@Test fun lastInitial_isInitiallyEmpty() = editTextIsEmpty(R.id.last_initial)
private fun editTextIsEmpty(id: Int) {
onView(withId(id)).check(matches(withText(isEmptyOrNullString())))
}
@Test fun avatar_allDisplayed() = checkOnAvatar(isDisplayed())
@Test fun avatar_isEnabled() = checkOnAvatar(isEnabled())
@Test fun avatar_notFocusable() = checkOnAvatar(not(isFocusable()))
@Test fun avatar_notClickable() = checkOnAvatar(not(isClickable()))
@Test fun avatar_noneChecked() = checkOnAvatar(not(isChecked()))
private fun checkOnAvatar(matcher: Matcher<View>) {
(0 until Avatar.values().size).forEach {
onData(equalTo(Avatar.values()[it]))
.inAdapterView(withId(R.id.avatars))
.check(matches(matcher))
}
}
}
| app/src/androidTest/java/com/google/samples/apps/topeka/activity/SignInActivityTest.kt | 483742252 |
package ru.fantlab.android.ui.modules.translator.overview
import android.os.Bundle
import android.view.View
import io.reactivex.Single
import io.reactivex.functions.Consumer
import ru.fantlab.android.data.dao.model.Nomination
import ru.fantlab.android.data.dao.model.Translator
import ru.fantlab.android.data.dao.response.TranslatorResponse
import ru.fantlab.android.helper.BundleConstant
import ru.fantlab.android.provider.rest.DataManager
import ru.fantlab.android.provider.rest.getTranslatorInformationPath
import ru.fantlab.android.provider.storage.DbProvider
import ru.fantlab.android.ui.base.mvp.presenter.BasePresenter
class TranslatorOverviewPresenter : BasePresenter<TranslatorOverviewMvp.View>(), TranslatorOverviewMvp.Presenter {
override fun onFragmentCreated(bundle: Bundle) {
val translatorId = bundle.getInt(BundleConstant.EXTRA)
makeRestCall(
retrieveTranslatorInfoInternal(translatorId).toObservable(),
Consumer { (translator, awards) ->
sendToView { it.onTranslatorInformationRetrieved(translator, awards) }
}
)
}
override fun onItemClick(position: Int, v: View?, item: Nomination) {
sendToView { it.onItemClicked(item) }
}
override fun onItemLongClick(position: Int, v: View?, item: Nomination) {
}
private fun retrieveTranslatorInfoInternal(translatorId: Int) =
retrieveTranslatorInfoFromServer(translatorId)
.onErrorResumeNext { retrieveTranslatorInfoFromDb(translatorId) }
private fun retrieveTranslatorInfoFromServer(translatorId: Int): Single<Pair<Translator, ArrayList<Translator.TranslationAward>>> =
DataManager.getTranslatorInformation(translatorId, showBio = true, showAwards = true)
.map { getTranslator(it) }
private fun retrieveTranslatorInfoFromDb(translatorId: Int): Single<Pair<Translator, ArrayList<Translator.TranslationAward>>> =
DbProvider.mainDatabase
.responseDao()
.get(getTranslatorInformationPath(translatorId, showBio = true, showAwards = true))
.map { it.response }
.map { TranslatorResponse.Deserializer().deserialize(it) }
.map { getTranslator(it) }
private fun getTranslator(response: TranslatorResponse): Pair<Translator, ArrayList<Translator.TranslationAward>> =
Pair(response.translator, response.awards)
} | app/src/main/kotlin/ru/fantlab/android/ui/modules/translator/overview/TranslatorOverviewPresenter.kt | 542930609 |
package com.commonsense.android.kotlin.base.scheduling
import com.commonsense.android.kotlin.base.extensions.collections.*
import org.junit.*
import org.junit.jupiter.api.Test
/**
* Created by Kasper Tvede on 09-07-2017.
*/
class MutableExtensionsTests {
@Test
fun testReplace() {
val list = mutableListOf("1", "2")
list.replace("3", 1)
Assert.assertEquals(list[1], "3")
}
} | base/src/test/kotlin/com/commonsense/android/kotlin/base/scheduling/MutableExtensionsTests.kt | 4078325100 |
package ca.sfu.cs.porter
/**
* Created by Geoff on 4/3/2016.
*/
fun main(args: Array<String>){
Porter().port(args);
}
class Porter{
fun port(args : Array<String>){
//multiple return values, probably my #1 feature for java (considering JEP 286)
val parser = CommandLineInterpreter()
val testTarget = parser.parse(args);
val generator = JunitDriverSourceGenerator();
val resultPath = generator.generateSource(testTarget);
println("porter finished generating code in $resultPath")
}
}
| porter/src/ca/sfu/cs/porter/Porter.kt | 4275754461 |
/**
* The MIT License (MIT)
*
* Copyright (c) 2019 vk.com
*
* 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.
*/
// *********************************************************************
// THIS FILE IS AUTO GENERATED!
// DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING.
// *********************************************************************
package com.vk.sdk.api.groups.dto
import com.google.gson.annotations.SerializedName
import com.vk.dto.common.id.UserId
import kotlin.Int
import kotlin.collections.List
/**
* @param count - Communities number
* @param items
*/
data class GroupsGroupsArray(
@SerializedName("count")
val count: Int,
@SerializedName("items")
val items: List<UserId>
)
| api/src/main/java/com/vk/sdk/api/groups/dto/GroupsGroupsArray.kt | 1885232621 |
package com.eden.orchid.wiki.pages
import com.eden.orchid.api.options.annotations.Description
import com.eden.orchid.api.render.RenderService
import com.eden.orchid.api.theme.pages.OrchidPage
import com.eden.orchid.api.theme.pages.OrchidReference
import com.eden.orchid.wiki.model.WikiSection
@Description(value = "An offline PDF with your wiki contents.", name = "Wiki Book")
class WikiBookPage(
reference: OrchidReference,
val section: WikiSection
) : OrchidPage(
WikiBookResource(reference, section),
RenderService.RenderMode.BINARY,
"wikiBook",
"${section.sectionTitle} Book"
)
| plugins/OrchidWiki/src/main/kotlin/com/eden/orchid/wiki/pages/WikiBookPage.kt | 2365174524 |
/**
* Z PL/SQL Analyzer
* Copyright (C) 2015-2022 Felipe Zorzo
* mailto:felipe AT felipezorzo DOT com DOT br
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.plsqlopen.api.sql
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.sonar.plugins.plsqlopen.api.DmlGrammar
import org.sonar.plugins.plsqlopen.api.RuleTest
import com.felipebz.flr.tests.Assertions.assertThat
class WhereClauseTest : RuleTest() {
@BeforeEach
fun init() {
setRootRule(DmlGrammar.WHERE_CLAUSE)
}
@Test
fun matchesSimpleWhere() {
assertThat(p).matches("where 1 = 1")
}
@Test
fun matchesColumnComparation() {
assertThat(p).matches("where tab.col = tab2.col2")
}
@Test
fun matchesMultipleColumnComparation() {
assertThat(p).matches("where tab.col = tab2.col2 and tab.col = tab2.col2")
}
@Test
fun matchesComparationWithSubquery() {
assertThat(p).matches("where tab.col = (select 1 from dual)")
}
@Test
fun matchesOuterJoin() {
assertThat(p).matches("where tab.col(+) = tab2.col2")
}
@Test
fun matchesTupleInSelect() {
assertThat(p).matches("where (foo, bar, baz) in (select 1, 2, 3 from dual)")
}
@Test
fun matchesTupleInValues() {
assertThat(p).matches("where (foo, bar) in ((1, 2), (2, 3))")
}
@Test
fun matchesExists() {
assertThat(p).matches("where exists (select 1 from dual)")
}
@Test
fun matchesNotExists() {
assertThat(p).matches("where not exists (select 1 from dual)")
}
@Test
fun matchesAny() {
assertThat(p).matches("where data = any (select 1,2,3 from dual)")
}
}
| zpa-core/src/test/kotlin/org/sonar/plugins/plsqlopen/api/sql/WhereClauseTest.kt | 4196841862 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.ambient.crossdevice.discovery
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Parcelable
import android.util.Log
import androidx.activity.result.ActivityResultCaller
import androidx.annotation.RequiresApi
import com.google.ambient.crossdevice.Participant
import com.google.ambient.crossdevice.ParticipantImpl
import com.google.android.gms.dtdi.Dtdi as GmsDtdi
import com.google.android.gms.dtdi.analytics.CorrelationData
import com.google.android.gms.dtdi.core.AnalyticsInfo
import com.google.android.gms.dtdi.core.DtdiClient
import com.google.android.gms.dtdi.core.SelectedDevice
/** Entry point for discovering devices. */
@RequiresApi(Build.VERSION_CODES.O)
interface Discovery {
/**
* Gets the participant from an incoming [Intent]. Used to begin the process of accepting a remote
* connection with a [Participant]. Returns null if the [Intent] is not valid for getting a
* [Participant].
*/
fun getParticipantFromIntent(intent: Intent): Participant?
/**
* Registers a callback for discovery.
*
* @param caller The calling activity or fragment.
* @param callback The callback to be called when devices are selected by a user.
* @return The launcher to use to show a device picker UI to the user.
*/
fun registerForResult(
caller: ActivityResultCaller,
callback: OnDevicePickerResultListener,
): DevicePickerLauncher
/** Interface to receive the result from the device picker, for use with [registerForResult]. */
fun interface OnDevicePickerResultListener {
/**
* Called when the user has selected the devices to connect to, and the receiving component has
* been successfully started.
*/
fun onDevicePickerResult(participants: Collection<Participant>)
}
companion object {
internal const val ORIGIN_DEVICE = "com.google.android.gms.dtdi.extra.ORIGIN_DEVICE"
internal const val ANALYTICS_INFO = "com.google.android.gms.dtdi.extra.ANALYTICS_INFO"
/** Creates an instance of [Discovery]. */
@JvmStatic
fun create(context: Context): Discovery = DiscoveryImpl(context, GmsDtdi.getClient(context))
}
}
private const val TAG = "CrossDeviceDiscovery"
/**
* Not intended for external usage. Please use [Discovery.create].
*
* @hide
*/
// TODO: Move Impl classes into internal packages with visibility/strict deps.
@RequiresApi(Build.VERSION_CODES.O)
class DiscoveryImpl(private val context: Context, private val dtdiClient: DtdiClient) : Discovery {
@SuppressWarnings("GmsCoreFirstPartyApiChecker")
override fun getParticipantFromIntent(intent: Intent): Participant? {
val device =
intent.getParcelable<SelectedDevice>(Discovery.ORIGIN_DEVICE)
?: run {
Log.w(TAG, "Unable to get participant token from intent")
return null
}
val analyticsInfo =
intent.getParcelable<AnalyticsInfo>(Discovery.ANALYTICS_INFO)
?: run {
Log.w(TAG, "Unable to get analytics info from intent")
return null
}
return ParticipantImpl(
device.displayName,
device.token,
CorrelationData.createFromAnalyticsInfo(analyticsInfo),
dtdiClient,
)
}
private inline fun <reified T : Parcelable> Intent.getParcelable(key: String): T? {
// TODO: Use the non-deprecated Bundle.getParcelable(String, Class) instead on T or
// above when b/232589966 is fixed.
@Suppress("DEPRECATION") return extras?.getParcelable(key)
}
override fun registerForResult(
caller: ActivityResultCaller,
callback: Discovery.OnDevicePickerResultListener,
): DevicePickerLauncher {
return DevicePickerLauncherImpl(
context = context,
launcher =
caller.registerForActivityResult(DevicePickerResultContract(dtdiClient)) {
callback.onDevicePickerResult(it)
}
)
}
}
| crossdevice/src/main/kotlin/com/google/ambient/crossdevice/discovery/Discovery.kt | 973074421 |
package org.jetbrains.kotlinx.jupyter.test
import kotlinx.coroutines.runBlocking
import org.junit.jupiter.api.Test
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.io.File
import kotlin.script.experimental.api.ResultWithDiagnostics
import kotlin.script.experimental.dependencies.ExternalDependenciesResolver
import kotlin.script.experimental.dependencies.maven.MavenDependenciesResolver
import kotlin.test.assertTrue
class ResolverTests {
private val log: Logger by lazy { LoggerFactory.getLogger("resolver") }
private fun ExternalDependenciesResolver.doResolve(artifact: String): List<File> {
testRepositories.forEach { addRepository(it) }
assertTrue(acceptsArtifact(artifact))
val result = runBlocking { resolve(artifact) }
assertTrue(result is ResultWithDiagnostics.Success)
return result.value
}
@Test
fun resolveSparkMlLibTest() {
val files = MavenDependenciesResolver().doResolve("org.apache.spark:spark-mllib_2.11:2.4.4")
log.debug("Downloaded files: ${files.count()}")
files.forEach {
log.debug(it.toString())
}
}
}
| src/test/kotlin/org/jetbrains/kotlinx/jupyter/test/ResolverTests.kt | 3808645575 |
package com.eden.orchid.groovydoc
import com.eden.orchid.sourcedoc.SourceDocModule
import com.eden.orchid.strikt.nothingElseRendered
import com.eden.orchid.strikt.pageWasRendered
import com.eden.orchid.testhelpers.OrchidIntegrationTest
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import strikt.api.expectThat
@DisplayName("Tests page-rendering behavior of Groovydoc generator")
class GroovydocGeneratorTest : OrchidIntegrationTest(GroovydocModule(), SourceDocModule()) {
@Test
@DisplayName("Groovy files are parsed, and pages are generated for each class and package.")
fun test01() {
configObject(
"groovydoc",
"""
|{
| "sourceDirs": [
| "mockGroovy",
| "./../../OrchidJavadoc/src/mockJava",
| ]
|}
|""".trimMargin()
)
expectThat(execute())
// Module readme
.pageWasRendered("/groovydoc/index.html") { }
// Groovy sources
.pageWasRendered("/groovydoc/com/eden/orchid/mock/groovyannotation/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/groovyclass/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/groovyenumclass/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/groovyexceptionclass/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/groovyinterface/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/groovytrait/index.html") { }
// Java sources
.pageWasRendered("/groovydoc/com/eden/orchid/mock/javaannotation/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/javaclass/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/javaenumclass/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/javaexceptionclass/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/javainterface/index.html") { }
.pageWasRendered("/groovydoc/com/eden/orchid/mock/index.html") { }
// other
.pageWasRendered("/assets/css/orchidSourceDoc.css")
.pageWasRendered("/favicon.ico")
.nothingElseRendered()
}
}
| plugins/OrchidGroovydoc/src/test/kotlin/com/eden/orchid/groovydoc/GroovydocGeneratorTest.kt | 2274107180 |
package moe.feng.nhentai.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
class Picture {
@Expose @SerializedName("h") var height: Int = 0
@Expose @SerializedName("w") var width: Int = 0
private @Expose @SerializedName("t") var type: String = "j"
val isJpg: Boolean get() = type == "j"
val isPng: Boolean get() = type == "p"
val fileType: String get() = if (isJpg) "jpg" else "png"
fun setIsJpg() {
type = "j"
}
fun setIsPng() {
type = "p"
}
} | app/src/main/kotlin/moe/feng/nhentai/model/Picture.kt | 3960828528 |
package sqlbuilder.impl.mappers
import sqlbuilder.mapping.BiMapper
import sqlbuilder.mapping.ToObjectMappingParameters
import sqlbuilder.mapping.ToSQLMappingParameters
import java.sql.Types
/**
* @author Laurent Van der Linden.
*/
class DoubleMapper : BiMapper {
override fun toObject(params: ToObjectMappingParameters): Double? {
val value = params.resultSet.getDouble(params.index)
return if (params.resultSet.wasNull()) {
null
} else {
value
}
}
override fun toSQL(params: ToSQLMappingParameters) {
if (params.value != null) {
params.preparedStatement.setDouble(params.index, params.value as Double)
} else {
params.preparedStatement.setNull(params.index, Types.DECIMAL)
}
}
override fun handles(targetType: Class<*>): Boolean {
return targetType == Double::class.java || targetType == java.lang.Double::class.java
}
} | src/main/kotlin/sqlbuilder/impl/mappers/DoubleMapper.kt | 2850124752 |
/*
* Copyright (C) 2017 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.ast.plugin
import uk.co.reecedunn.intellij.plugin.xpath.ast.full.text.FTMatchOption
/**
* A BaseX 6.1 `FTFuzzyOption` node in the XQuery AST.
*/
interface PluginFTFuzzyOption : FTMatchOption | src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/ast/plugin/PluginFTFuzzyOption.kt | 3408067561 |
package com.slelyuk.android.circleavatarview
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Bitmap.Config
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Paint.Style.FILL
import android.graphics.PorterDuff.Mode.SRC_IN
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.drawable.Drawable
import android.support.v4.content.ContextCompat
import android.support.v7.widget.AppCompatImageView
import android.util.AttributeSet
import com.slelyuk.android.circleavatarview.R.color
import com.slelyuk.android.circleavatarview.R.dimen
import com.slelyuk.android.circleavatarview.R.styleable
/**
* Circle image view that could use defined name's abbreviation as a placeholder.
*/
class CircleAvatarView : AppCompatImageView {
internal var circleRadius = 0f
internal var circleCenterXValue = 0f
internal var circleCenterYValue = 0f
private var borderColor = 0
private var borderWidth = 0
private var viewSize = 0
private val borderPaint = Paint()
private val mainPaint = Paint()
private var circleDrawable: Drawable? = null
private val circleRect = Rect()
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs,
defStyleAttr) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
val defaultBorderColor = ContextCompat.getColor(context, color.default_border_color)
val defaultBorderWidth = context.resources.getDimensionPixelSize(dimen.default_border_width)
val arr = obtainStyledAttributes(attrs, styleable.CircleAvatarView)
try {
borderColor = arr.getColor(styleable.CircleAvatarView_av_border_color, defaultBorderColor)
borderWidth = arr.getDimensionPixelSize(styleable.CircleAvatarView_av_border_width,
defaultBorderWidth)
} finally {
arr.recycle()
}
borderPaint.let {
it.isAntiAlias = true
it.style = FILL
//it.color = borderColor
}
mainPaint.let {
it.isAntiAlias = true
it.xfermode = PorterDuffXfermode(SRC_IN)
}
}
public override fun onDraw(canvas: Canvas) {
updateViewParams(canvas)
if (viewSize == 0) {
return
}
val bitmap = cutIntoCircle(drawableToBitmap(circleDrawable)) ?: return
//Draw Border
canvas.let {
//val radius = circleRadius + borderWidth
it.translate(circleCenterXValue, circleCenterYValue)
//it.drawCircle(radius, radius, radius, borderPaint)
it.drawBitmap(bitmap, 0f, 0f, null)
}
}
private fun drawableToBitmap(drawable: Drawable?): Bitmap? {
if (viewSize == 0) {
return null
}
val bitmap = Bitmap.createBitmap(viewSize, viewSize, Config.ARGB_8888)
val canvas = Canvas(bitmap)
drawable?.let {
it.setBounds(0, 0, viewSize, viewSize)
it.draw(canvas)
}
return bitmap
}
private fun cutIntoCircle(bitmap: Bitmap?): Bitmap? {
if (viewSize == 0) {
return null
}
val output = Bitmap.createBitmap(viewSize, viewSize, Config.ARGB_8888)
val canvas = Canvas(output)
canvas.let {
val radiusWithBorder = (circleRadius + borderWidth)
//it.drawARGB(0, 0, 0, 0)
it.drawCircle(radiusWithBorder, radiusWithBorder, circleRadius, borderPaint)
it.drawBitmap(bitmap, circleRect, circleRect, mainPaint)
}
return output
}
private fun updateViewParams(canvas: Canvas) {
val viewHeight = canvas.height
val viewWidth = canvas.width
viewSize = Math.min(viewWidth, viewHeight)
circleCenterXValue = (viewWidth - viewSize) / 2f
circleCenterYValue = (viewHeight - viewSize) / 2f
circleRadius = (viewSize - borderWidth * 2) / 2f
circleRect.set(Rect(0, 0, viewSize, viewSize))
borderWidth = Math.min(viewSize / 3, borderWidth)
if (viewSize != 0) {
circleDrawable = this.drawable
}
}
override fun drawableStateChanged() {
super.drawableStateChanged()
invalidate()
}
} | circle-avatar/src/main/kotlin/com/slelyuk/android/circleavatarview/CircleAvatarView.kt | 936787123 |
/*
* Copyright (C) 2019 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xquery.completion.property
import com.intellij.psi.PsiElement
import com.intellij.util.ProcessingContext
import uk.co.reecedunn.intellij.plugin.core.completion.CompletionProperty
import uk.co.reecedunn.intellij.plugin.intellij.lang.Version
import uk.co.reecedunn.intellij.plugin.intellij.lang.XPathSpec
import uk.co.reecedunn.intellij.plugin.intellij.lang.XQuerySpec
import uk.co.reecedunn.intellij.plugin.xpath.completion.property.XPathCompletionProperty
object XPathVersion : CompletionProperty {
override fun computeProperty(element: PsiElement, context: ProcessingContext) {
if (context[XPathCompletionProperty.XPATH_VERSION] == null) {
XQueryVersion.computeProperty(element, context)
val xquery = context[XQueryCompletionProperty.XQUERY_VERSION]
context.put(XPathCompletionProperty.XPATH_VERSION, get(xquery))
}
}
fun get(element: PsiElement): Version = get(XQueryVersion.get(element))
private fun get(xqueryVersion: Version): Version = when (xqueryVersion) {
XQuerySpec.REC_1_0_20070123 -> XPathSpec.REC_2_0_20070123
XQuerySpec.REC_1_0_20101214 -> XPathSpec.REC_2_0_20101214
XQuerySpec.WD_1_0_20030502 -> XPathSpec.WD_2_0_20030502
XQuerySpec.REC_3_0_20140408 -> XPathSpec.REC_3_0_20140408
XQuerySpec.CR_3_1_20151217 -> XPathSpec.CR_3_1_20151217
XQuerySpec.REC_3_1_20170321 -> XPathSpec.REC_3_1_20170321
XQuerySpec.ED_4_0_20210113 -> XPathSpec.ED_4_0_20210113
XQuerySpec.MARKLOGIC_0_9 -> XPathSpec.WD_2_0_20030502
XQuerySpec.MARKLOGIC_1_0 -> XPathSpec.REC_3_0_20140408
else -> XPathSpec.REC_3_1_20170321
}
}
| src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/completion/property/XPathVersion.kt | 3150800019 |
package org.stepik.android.remote.step_source
import io.reactivex.Single
import io.reactivex.functions.Function
import org.stepik.android.data.step_source.source.StepSourceRemoteDataSource
import org.stepik.android.model.StepSource
import org.stepik.android.remote.step_source.model.StepSourceRequest
import org.stepik.android.remote.step_source.model.StepSourceResponse
import org.stepik.android.remote.step_source.service.StepSourceService
import javax.inject.Inject
class StepSourceRemoteDataSourceImpl
@Inject
constructor(
private val stepSourceService: StepSourceService
) : StepSourceRemoteDataSource {
private val responseMapper =
Function<StepSourceResponse, StepSource> { it.stepSources.first() }
override fun getStepSource(stepId: Long): Single<StepSource> =
stepSourceService
.getStepSources(longArrayOf(stepId))
.map(responseMapper)
override fun saveStepSource(stepSource: StepSource): Single<StepSource> =
stepSourceService
.saveStepSource(stepSource.id, StepSourceRequest(stepSource))
.map(responseMapper)
} | app/src/main/java/org/stepik/android/remote/step_source/StepSourceRemoteDataSourceImpl.kt | 4285131073 |
package org.livingdoc.converters.collection
import org.livingdoc.api.conversion.ConversionException
internal object Tokenizer {
fun tokenizeToStringList(value: String, delimiter: String = ",") = value.split(delimiter).map { it.trim() }
fun tokenizeToMap(value: String, pairDelimiter: String = ";", valueDelimiter: String = ","): Map<String, String> {
val pairs = tokenizeToStringList(value, pairDelimiter)
return pairs.map { pairString ->
val split = tokenizeToStringList(pairString, valueDelimiter)
if (split.size != 2) throw ConversionException("'$pairString' is not a valid Pair")
split[0] to split[1]
}.toMap()
}
}
| livingdoc-converters/src/main/kotlin/org/livingdoc/converters/collection/Tokenizer.kt | 436354679 |
/*
* Copyright (c) 2017 Stefan Neubert
*
* 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 net.kejira.wifabs.ui.fabric.edit
import javafx.collections.ObservableList
import javafx.geometry.Insets
import javafx.geometry.Orientation
import javafx.scene.control.Button
import javafx.scene.control.TextField
import javafx.scene.input.KeyCode
import javafx.scene.layout.FlowPane
import org.controlsfx.control.textfield.TextFields
class FabricEditMultiAttributeBox(private val name_list: ObservableList<String>) : FlowPane(Orientation.HORIZONTAL) {
private val list = hashSetOf<String>()
init {
style =
"-fx-background-color: linear-gradient(to bottom, derive(-fx-text-box-border, -10%), -fx-text-box-border), linear-gradient(from 0px 0px to 0px 5px, derive(-fx-control-inner-background, -9%), -fx-control-inner-background);" +
"-fx-background-insets: 0, 1;" +
"-fx-background-radius: 3, 2;"
padding = Insets(5.0)
minHeight = 35.0
hgap = 5.0
vgap = 5.0
this.setOnMouseReleased { mouse_event ->
if (mouse_event.button == javafx.scene.input.MouseButton.PRIMARY) {
createTextField()
}
}
}
private fun add(attribute: String) {
var text = attribute.trim().capitalize()
if (text.isNotEmpty()) {
if (text.length > 35) {
text = text.substring(0, 35)
}
if (!list.contains(text)) {
createButton(text)
list.add(text)
}
}
}
fun get(): Set<String> = list.toSet()
fun set(attributes: Set<String>) {
this.list.clear()
this.children.clear()
attributes.forEach {
createButton(it)
list.add(it)
}
}
private fun remove(attribute: String) {
list.remove(attribute)
}
private fun createButton(text: String) {
val button = Button(text)
button.setOnMouseClicked {
remove(button.text)
this.children.remove(button)
}
this.children.add(button)
}
private fun createTextField() {
val text_field = FabricEditAttributeTextField()
/* enter */
text_field.setOnKeyPressed { ke ->
if (ke.code == KeyCode.ESCAPE) {
text_field.createButton = false
super.requestFocus()
} else if (ke.code == KeyCode.ENTER) {
super.requestFocus()
}
}
/* focus lost */
text_field.focusedProperty().addListener { _, _, new ->
if (!new) {
this.children.remove(text_field)
if (text_field.createButton) add(text_field.text)
}
}
/* auto completion */
val autoCompletion = TextFields.bindAutoCompletion(text_field, name_list)
autoCompletion.setOnAutoCompleted { super.requestFocus() }
this.children.add(text_field)
text_field.requestFocus()
}
}
class FabricEditAttributeTextField : TextField() {
@JvmField var createButton = true
init {
maxWidth = 85.0
}
} | src/main/kotlin/net/kejira/wifabs/ui/fabric/edit/FabricEditMultiAttributeBox.kt | 3818739849 |
package com.vmenon.mpo.downloads.domain
interface DownloadsService {
suspend fun queueDownload(downloadRequest: DownloadRequest): DownloadModel
suspend fun getAllQueued(): List<QueuedDownloadModel>
suspend fun getCompletedDownloadByQueueId(queueId: Long): CompletedDownloadModel
suspend fun delete(id: Long)
suspend fun retryDownload(download: DownloadModel): DownloadModel
} | downloads_domain/src/main/java/com/vmenon/mpo/downloads/domain/DownloadsService.kt | 2145425008 |
package org.walleth.enhancedlist
import android.animation.ObjectAnimator
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.SearchView
import androidx.core.animation.doOnEnd
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.ItemTouchHelper.LEFT
import androidx.recyclerview.widget.ItemTouchHelper.RIGHT
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
import kotlinx.android.synthetic.main.activity_list.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.koin.android.ext.android.inject
import org.ligi.kaxt.startActivityFromURL
import org.walleth.R
import org.walleth.base_activities.BaseSubActivity
import org.walleth.chains.getFaucetURL
import org.walleth.chains.hasFaucetWithAddressSupport
import org.walleth.data.AppDatabase
import org.walleth.data.addresses.CurrentAddressProvider
import org.walleth.data.chaininfo.ChainInfo
import org.walleth.util.question
import timber.log.Timber
interface Deletable {
var deleted: Boolean
}
interface ListItem : Deletable {
val name: String
}
@SuppressLint("Registered")
abstract class BaseEnhancedListActivity<T : ListItem> : BaseSubActivity() {
abstract val enhancedList: EnhancedListInterface<T>
abstract val adapter: EnhancedListAdapter<T>
private var currentSnack: Snackbar? = null
internal var searchTerm = ""
fun T.changeDeleteState(state: Boolean) {
val changedEntity = apply { deleted = state }
lifecycleScope.launch(Dispatchers.Main) {
withContext(Dispatchers.Default) {
enhancedList.upsert(changedEntity)
if (state) {
currentSnack = Snackbar.make(coordinator, "Deleted " + changedEntity.name, Snackbar.LENGTH_INDEFINITE)
.setAction(getString(R.string.undo)) { changeDeleteState(false) }
.apply { show() }
}
refreshAdapter()
invalidateOptionsMenu()
}
}
}
internal fun View.deleteWithAnimation(t: T) {
ObjectAnimator.ofFloat(this, "translationX", this.width.toFloat()).apply {
duration = 333
start()
doOnEnd {
t.changeDeleteState(true)
handler.postDelayed({
translationX = 0f
}, 333)
}
}
}
fun AppCompatImageView.prepareFaucetButton(chainInfo: ChainInfo?,
currentAddressProvider: CurrentAddressProvider,
postAction: () -> Unit = {}) {
visibility = if (chainInfo?.faucets?.isNotEmpty() == true) {
setImageResource(if (chainInfo.hasFaucetWithAddressSupport()) R.drawable.ic_flash_on_black_24dp else R.drawable.ic_redeem_black_24dp)
View.VISIBLE
} else {
View.INVISIBLE
}
setOnClickListener {
chainInfo?.getFaucetURL(currentAddressProvider.getCurrentNeverNull())?.let { url ->
context.startActivityFromURL(url)
postAction.invoke()
}
}
}
internal fun MenuItem.filterToggle(updater: (value: Boolean) -> Unit) = true.also {
isChecked = !isChecked
updater(isChecked)
refreshAdapter()
}
val appDatabase: AppDatabase by inject()
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val anySoftDeletedExists = adapter.list.any { it.deleted }
menu.findItem(R.id.menu_undelete).isVisible = anySoftDeletedExists
menu.findItem(R.id.menu_delete_forever).isVisible = anySoftDeletedExists
return super.onPrepareOptionsMenu(menu)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.menu_enhanced_list, menu)
val searchItem = menu.findItem(R.id.action_search)
val searchView = searchItem.actionView as SearchView
Timber.i("setting search term $searchTerm")
searchItem.setOnActionExpandListener(object : MenuItem.OnActionExpandListener {
override fun onMenuItemActionExpand(p0: MenuItem?) = true
override fun onMenuItemActionCollapse(p0: MenuItem?) = true.also {
searchTerm = ""
}
})
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextChange(newSearchTerm: String) = true.also {
searchTerm = newSearchTerm
Timber.i("setting search term 2 $newSearchTerm")
refreshAdapter()
}
override fun onQueryTextSubmit(query: String?) = false
})
searchView.setQuery(searchTerm, true)
return super.onCreateOptionsMenu(menu)
}
fun checkForSearchTerm(vararg terms: String) = terms.any { it.toLowerCase().contains(searchTerm, ignoreCase = true) }
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.menu_undelete -> true.also {
lifecycleScope.launch(Dispatchers.Main) {
currentSnack?.dismiss()
enhancedList.undeleteAll()
refreshAdapter()
}
}
R.id.menu_delete_forever -> true.also {
question(configurator = {
setIcon(R.drawable.ic_warning_orange_24dp)
setTitle(R.string.are_you_sure)
setMessage(R.string.permanent_delete_question)
}, action = {
currentSnack?.dismiss()
lifecycleScope.launch {
enhancedList.deleteAllSoftDeleted()
refreshAdapter()
}
})
}
else -> super.onOptionsItemSelected(item)
}
internal fun refreshAdapter() = lifecycleScope.launch(Dispatchers.Main) {
adapter.filter(enhancedList.getAll(),
filter = { enhancedList.filter(it) },
onChange = { invalidateOptionsMenu() },
areEqual = { t1, t2 -> enhancedList.compare(t1, t2) })
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_list)
recycler_view.layoutManager = LinearLayoutManager(this)
recycler_view.adapter = adapter
val simpleItemTouchCallback = object : ItemTouchHelper.SimpleCallback(0, LEFT or RIGHT) {
override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, target: RecyclerView.ViewHolder) = false
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) {
adapter.displayList[viewHolder.adapterPosition].changeDeleteState(true)
}
}
val itemTouchHelper = ItemTouchHelper(simpleItemTouchCallback)
itemTouchHelper.attachToRecyclerView(recycler_view)
}
override fun onResume() {
super.onResume()
refreshAdapter()
}
} | app/src/main/java/org/walleth/enhancedlist/BaseEnhancedListActivity.kt | 92852926 |
package com.vmenon.mpo.search.domain
data class ShowSearchResultEpisodeModel(
val name: String,
val description: String?,
val published: Long,
val type: String,
val downloadUrl: String,
val length: Long?,
val artworkUrl: String?
) | search_domain/src/main/java/com/vmenon/mpo/search/domain/ShowSearchResultEpisodeModel.kt | 3565484090 |
import net.minecraft.init.Items
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.math.BlockPos
import net.minecraftforge.fluids.FluidRegistry
import net.minecraftforge.fluids.FluidStack
import net.shadowfacts.shadowmc.nbt.dsl.compound
import net.shadowfacts.shadowmc.nbt.dsl.list
/**
* @author shadowfacts
*/
fun main(args: Array<String>) {
val tag = test()
println("done")
}
fun test(): NBTTagCompound {
return compound {
// "a" to ItemStack(Items.DIAMOND, 3)
"b" to false
// "c" to FluidStack(FluidRegistry.LAVA, 1000)
"d" to compound {
"ca" to "test"
"cb" to BlockPos(1, 2, 3)
}
"e" to list {
this += compound {
"da" to "test 1"
"db" to false
"dc" to list {
this += 1
this += 2
this += 3
}
}
this += compound {
"da" to "test 2"
"db" to true
"dc" to list {
this += 4
this += 5
this += 6
}
}
}
}
} | src/test/kotlin/test/nbt/dsl/NBTDSLTest.kt | 3805913667 |
package com.auth0.android.request.internal
import com.auth0.android.result.UserIdentity
import com.auth0.android.result.UserProfile
import com.auth0.android.util.UserIdentityMatcher
import com.auth0.android.util.UserProfileMatcher
import com.google.gson.JsonParseException
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.*
import org.hamcrest.collection.IsMapWithSize
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import java.io.StringReader
import java.text.SimpleDateFormat
import java.util.*
public class UserProfileGsonTest : GsonBaseTest() {
@Before
public fun setUp() {
gson = GsonProvider.gson
}
@Test
@Throws(Exception::class)
public fun shouldFailWithInvalidJson() {
Assert.assertThrows(JsonParseException::class.java) {
pojoFrom(json(INVALID), UserProfile::class.java)
}
}
@Test
@Throws(Exception::class)
public fun shouldFailWithEmptyJson() {
Assert.assertThrows(JsonParseException::class.java) {
pojoFrom(json(EMPTY_OBJECT), UserProfile::class.java)
}
}
@Test
@Throws(Exception::class)
public fun shouldHandleNullBooleans() {
val userProfile = pojoFrom(
StringReader(
"""{"email_verified": null}"""
), UserProfile::class.java
)
assertThat(userProfile, `is`(notNullValue()))
}
@Test
@Throws(Exception::class)
public fun shouldNotRequireUserId() {
val userProfile = pojoFrom(
StringReader(
"""{
"picture": "https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png",
"name": "info @ auth0",
"nickname": "a0",
"identities": [
{
"user_id": "1234567890",
"provider": "auth0",
"connection": "Username-Password-Authentication",
"isSocial": false
}
],
"created_at": "2014-07-06T18:33:49.005Z"
}"""
), UserProfile::class.java
)
assertThat(userProfile, `is`(notNullValue()))
}
@Test
@Throws(Exception::class)
public fun shouldNotRequireName() {
val userProfile = pojoFrom(
StringReader(
"""{
"picture": "https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png",
"nickname": "a0",
"user_id": "auth0|1234567890",
"identities": [
{
"user_id": "1234567890",
"provider": "auth0",
"connection": "Username-Password-Authentication",
"isSocial": false
}
],
"created_at": "2014-07-06T18:33:49.005Z"
}"""
), UserProfile::class.java
)
assertThat(userProfile, `is`(notNullValue()))
}
@Test
@Throws(Exception::class)
public fun shouldNotRequireNickname() {
val userProfile = pojoFrom(
StringReader(
"""{
"picture": "https://secure.gravatar.com/avatar/cfacbe113a96fdfc85134534771d88b4?s=480&r=pg&d=https%3A%2F%2Fssl.gstatic.com%2Fs2%2Fprofiles%2Fimages%2Fsilhouette80.png",
"name": "info @ auth0",
"user_id": "auth0|1234567890",
"identities": [
{
"user_id": "1234567890",
"provider": "auth0",
"connection": "Username-Password-Authentication",
"isSocial": false
}
],
"created_at": "2014-07-06T18:33:49.005Z"
}"""
), UserProfile::class.java
)
assertThat(userProfile, `is`(notNullValue()))
}
@Test
@Throws(Exception::class)
public fun shouldNotRequirePicture() {
val userProfile = pojoFrom(
StringReader(
"""{
"name": "info @ auth0",
"nickname": "a0",
"user_id": "auth0|1234567890",
"identities": [
{
"user_id": "1234567890",
"provider": "auth0",
"connection": "Username-Password-Authentication",
"isSocial": false
}
],
"created_at": "2014-07-06T18:33:49.005Z"
}"""
), UserProfile::class.java
)
assertThat(userProfile, `is`(notNullValue()))
}
@Test
@Throws(Exception::class)
public fun shouldReturnOAuthProfile() {
val profile = pojoFrom(json(PROFILE_OAUTH), UserProfile::class.java)
assertThat(
profile.getId(),
`is`("google-oauth2|9883254263433883220")
)
assertThat(profile.name, `is`(nullValue()))
assertThat(profile.nickname, `is`(nullValue()))
assertThat(profile.pictureURL, `is`(nullValue()))
assertThat(
profile.getIdentities(), `is`(
emptyCollectionOf(
UserIdentity::class.java
)
)
)
assertThat(profile.getUserMetadata(), IsMapWithSize.anEmptyMap())
assertThat(profile.getAppMetadata(), IsMapWithSize.anEmptyMap())
assertThat(profile.getExtraInfo(), IsMapWithSize.aMapWithSize(1))
assertThat(
profile.getExtraInfo(),
hasEntry("sub", "google-oauth2|9883254263433883220" as Any)
)
}
@Test
@Throws(Exception::class)
public fun shouldReturnProfileWithOnlyRequiredValues() {
val profile = pojoFrom(json(PROFILE_BASIC), UserProfile::class.java)
assertThat(
profile,
UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME)
)
assertThat(profile.getIdentities(), hasSize(1))
assertThat(
profile.getIdentities(),
hasItem(
UserIdentityMatcher.isUserIdentity(
"1234567890",
"auth0",
"Username-Password-Authentication"
)
)
)
assertThat(profile.getUserMetadata(), IsMapWithSize.anEmptyMap())
assertThat(profile.getAppMetadata(), IsMapWithSize.anEmptyMap())
assertThat(profile.getExtraInfo(), IsMapWithSize.anEmptyMap())
}
@Test
@Throws(Exception::class)
public fun shouldReturnNormalizedProfile() {
val profile = pojoFrom(json(PROFILE), UserProfile::class.java)
assertThat(
profile,
UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME)
)
assertThat(profile.getIdentities(), hasSize(1))
assertThat(
profile.getIdentities(),
hasItem(
UserIdentityMatcher.isUserIdentity(
"1234567890",
"auth0",
"Username-Password-Authentication"
)
)
)
assertThat(profile.getUserMetadata(), IsMapWithSize.anEmptyMap())
assertThat(profile.getAppMetadata(), IsMapWithSize.anEmptyMap())
assertThat(profile.getExtraInfo(), notNullValue())
}
@Test
@Throws(Exception::class)
public fun shouldReturnProfileWithOptionalFields() {
val profile = pojoFrom(json(PROFILE_FULL), UserProfile::class.java)
assertThat(
profile,
UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME)
)
assertThat(profile.email, equalTo("[email protected]"))
assertThat(profile.givenName, equalTo("John"))
assertThat(profile.familyName, equalTo("Foobar"))
assertThat(profile.isEmailVerified, `is`(false))
assertThat(
profile.createdAt,
equalTo(
getUTCDate(2014, 6, 6, 18, 33, 49, 5)
)
)
}
@Test
@Throws(Exception::class)
public fun shouldCreateProfileFromISO8601CreatedAt() {
val profileUtc = pojoFrom(
StringReader("""{ "created_at": "2022-04-29T07:09:23.000Z" }"""),
UserProfile::class.java
)
val profileLocal = pojoFrom(
StringReader("""{ "created_at": "2022-04-29T10:09:23.000+0300" }"""),
UserProfile::class.java
)
val dateUtc = getUTCDate(2022, 3, 29, 7, 9, 23, 0);
assertThat(profileUtc.createdAt, equalTo(dateUtc))
assertThat(profileLocal.createdAt, equalTo(dateUtc))
}
@Test
@Throws(Exception::class)
public fun shouldReturnProfileWithMultipleIdentities() {
val profile = pojoFrom(json(PROFILE_FULL), UserProfile::class.java)
assertThat(
profile,
UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME)
)
assertThat(
profile.getIdentities(),
hasItem(
UserIdentityMatcher.isUserIdentity(
"1234567890",
"auth0",
"Username-Password-Authentication"
)
)
)
assertThat(
profile.getIdentities(),
hasItem(
UserIdentityMatcher.isUserIdentity(
"999997950999976",
"facebook",
"facebook"
)
)
)
}
@Test
@Throws(Exception::class)
public fun shouldReturnProfileWithExtraInfo() {
val profile = pojoFrom(json(PROFILE_FULL), UserProfile::class.java)
assertThat(
profile,
UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME)
)
assertThat(
profile.getExtraInfo(),
hasEntry("multifactor", listOf("google-authenticator"))
)
assertThat(
profile.getExtraInfo(),
not(
anyOf(
hasKey("user_id"),
hasKey("name"),
hasKey("nickname"),
hasKey("picture"),
hasKey("email"),
hasKey("created_at")
)
)
)
}
@Test
@Throws(Exception::class)
public fun shouldReturnProfileWithMetadata() {
val profile = pojoFrom(json(PROFILE_FULL), UserProfile::class.java)
assertThat(
profile,
UserProfileMatcher.isNormalizedProfile(ID, NAME, NICKNAME)
)
assertThat(
profile.getUserMetadata(),
hasEntry("first_name", "Info" as Any)
)
assertThat(
profile.getUserMetadata(),
hasEntry("last_name", "Auth0" as Any)
)
assertThat(
profile.getUserMetadata(),
hasEntry("first_name", "Info" as Any)
)
assertThat(
profile.getAppMetadata(),
hasEntry("role", "admin" as Any)
)
assertThat(profile.getAppMetadata(), hasEntry("tier", 2.0 as Any))
assertThat(
profile.getAppMetadata(),
hasEntry("blocked", false as Any)
)
}
private fun getUTCDate(year: Int, month: Int, day: Int, hr: Int, min: Int, sec: Int, ms: Int): Date {
val cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"))
cal[Calendar.YEAR] = year
cal[Calendar.MONTH] = month
cal[Calendar.DAY_OF_MONTH] = day
cal[Calendar.HOUR_OF_DAY] = hr
cal[Calendar.MINUTE] = min
cal[Calendar.SECOND] = sec
cal[Calendar.MILLISECOND] = ms
return cal.time
}
private companion object {
private const val NICKNAME = "a0"
private const val NAME = "info @ auth0"
private const val ID = "auth0|1234567890"
private const val PROFILE_OAUTH = "src/test/resources/profile_oauth.json"
private const val PROFILE_FULL = "src/test/resources/profile_full.json"
private const val PROFILE_BASIC = "src/test/resources/profile_basic.json"
private const val PROFILE = "src/test/resources/profile.json"
}
} | auth0/src/test/java/com/auth0/android/request/internal/UserProfileGsonTest.kt | 2925250292 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix.replaceWith
import com.intellij.openapi.diagnostic.ControlFlowException
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.idea.FrontendInternals
import org.jetbrains.kotlin.idea.base.projectStructure.compositeAnalysis.findAnalyzerServices
import org.jetbrains.kotlin.idea.caches.resolve.analyzeInContext
import org.jetbrains.kotlin.idea.caches.resolve.resolveImportReference
import org.jetbrains.kotlin.idea.codeInliner.CodeToInline
import org.jetbrains.kotlin.idea.codeInliner.CodeToInlineBuilder
import org.jetbrains.kotlin.idea.core.unwrapIfFakeOverride
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.resolve.ResolutionFacade
import org.jetbrains.kotlin.idea.resolve.frontendService
import org.jetbrains.kotlin.idea.resolve.languageVersionSettings
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.FqNameUnsafe
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.psi.KtExpression
import org.jetbrains.kotlin.psi.KtNameReferenceExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtUserType
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
import org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport
import org.jetbrains.kotlin.resolve.scopes.*
import org.jetbrains.kotlin.resolve.scopes.utils.chainImportingScopes
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
data class ReplaceWithData(val pattern: String, val imports: List<String>, val replaceInWholeProject: Boolean)
@OptIn(FrontendInternals::class)
object ReplaceWithAnnotationAnalyzer {
fun analyzeCallableReplacement(
replaceWith: ReplaceWithData,
symbolDescriptor: CallableDescriptor,
resolutionFacade: ResolutionFacade,
reformat: Boolean
): CodeToInline? {
val originalDescriptor = symbolDescriptor.unwrapIfFakeOverride().original
return analyzeOriginal(replaceWith, originalDescriptor, resolutionFacade, reformat)
}
private fun analyzeOriginal(
replaceWith: ReplaceWithData,
symbolDescriptor: CallableDescriptor,
resolutionFacade: ResolutionFacade,
reformat: Boolean
): CodeToInline? {
val psiFactory = KtPsiFactory(resolutionFacade.project)
val expression = psiFactory.createExpressionIfPossible(replaceWith.pattern) ?: return null
val module = resolutionFacade.moduleDescriptor
val scope = buildScope(resolutionFacade, replaceWith, symbolDescriptor) ?: return null
val expressionTypingServices = resolutionFacade.getFrontendService(module, ExpressionTypingServices::class.java)
fun analyzeExpression(ignore: KtExpression) = expression.analyzeInContext(
scope,
expressionTypingServices = expressionTypingServices
)
return CodeToInlineBuilder(symbolDescriptor, resolutionFacade, originalDeclaration = null).prepareCodeToInline(
expression,
emptyList(),
::analyzeExpression,
reformat,
)
}
fun analyzeClassifierReplacement(
replaceWith: ReplaceWithData,
symbolDescriptor: ClassifierDescriptorWithTypeParameters,
resolutionFacade: ResolutionFacade
): KtUserType? {
val psiFactory = KtPsiFactory(resolutionFacade.project)
val typeReference = try {
psiFactory.createType(replaceWith.pattern)
} catch (e: Exception) {
if (e is ControlFlowException) throw e
return null
}
if (typeReference.typeElement !is KtUserType) return null
val scope = buildScope(resolutionFacade, replaceWith, symbolDescriptor) ?: return null
val typeResolver = resolutionFacade.getFrontendService(TypeResolver::class.java)
val bindingTrace = BindingTraceContext()
typeResolver.resolvePossiblyBareType(TypeResolutionContext(scope, bindingTrace, false, true, false), typeReference)
val typesToQualify = ArrayList<Pair<KtNameReferenceExpression, FqName>>()
typeReference.forEachDescendantOfType<KtNameReferenceExpression> { expression ->
val parentType = expression.parent as? KtUserType ?: return@forEachDescendantOfType
if (parentType.qualifier != null) return@forEachDescendantOfType
val targetClass = bindingTrace.bindingContext[BindingContext.REFERENCE_TARGET, expression] as? ClassDescriptor
?: return@forEachDescendantOfType
val fqName = targetClass.fqNameUnsafe
if (fqName.isSafe) {
typesToQualify.add(expression to fqName.toSafe())
}
}
for ((nameExpression, fqName) in typesToQualify) {
nameExpression.mainReference.bindToFqName(fqName, KtSimpleNameReference.ShorteningMode.NO_SHORTENING)
}
return typeReference.typeElement as KtUserType
}
private fun buildScope(
resolutionFacade: ResolutionFacade,
replaceWith: ReplaceWithData,
symbolDescriptor: DeclarationDescriptor
): LexicalScope? {
val module = resolutionFacade.moduleDescriptor
val explicitImportsScope = buildExplicitImportsScope(importFqNames(replaceWith), resolutionFacade, module)
val languageVersionSettings = resolutionFacade.languageVersionSettings
val defaultImportsScopes = buildDefaultImportsScopes(resolutionFacade, module, languageVersionSettings)
return getResolutionScope(
symbolDescriptor, symbolDescriptor, listOf(explicitImportsScope), defaultImportsScopes, languageVersionSettings
)
}
private fun buildDefaultImportsScopes(
resolutionFacade: ResolutionFacade,
module: ModuleDescriptor,
languageVersionSettings: LanguageVersionSettings
): List<ImportingScope> {
val allDefaultImports =
resolutionFacade.frontendService<TargetPlatform>().findAnalyzerServices(resolutionFacade.project)
.getDefaultImports(languageVersionSettings, includeLowPriorityImports = true)
val (allUnderImports, aliasImports) = allDefaultImports.partition { it.isAllUnder }
// this solution doesn't support aliased default imports with a different alias
// TODO: Create import directives from ImportPath, create ImportResolver, create LazyResolverScope, see FileScopeProviderImpl
return listOf(buildExplicitImportsScope(aliasImports.map { it.fqName }, resolutionFacade, module)) +
allUnderImports.map { module.getPackage(it.fqName).memberScope.memberScopeAsImportingScope() }.asReversed()
}
private fun buildExplicitImportsScope(
importFqNames: List<FqName>,
resolutionFacade: ResolutionFacade,
module: ModuleDescriptor
): ExplicitImportsScope {
val importedSymbols = importFqNames.flatMap { resolutionFacade.resolveImportReference(module, it) }
return ExplicitImportsScope(importedSymbols)
}
private fun importFqNames(annotation: ReplaceWithData): List<FqName> {
val result = ArrayList<FqName>()
for (fqName in annotation.imports) {
if (!FqNameUnsafe.isValid(fqName)) continue
result += FqNameUnsafe(fqName).takeIf { it.isSafe }?.toSafe() ?: continue
}
return result
}
private fun getResolutionScope(
descriptor: DeclarationDescriptor,
ownerDescriptor: DeclarationDescriptor,
explicitScopes: Collection<ExplicitImportsScope>,
additionalScopes: Collection<ImportingScope>,
languageVersionSettings: LanguageVersionSettings
): LexicalScope? {
return when (descriptor) {
is PackageFragmentDescriptor -> {
val moduleDescriptor = descriptor.containingDeclaration
getResolutionScope(
moduleDescriptor.getPackage(descriptor.fqName),
ownerDescriptor,
explicitScopes,
additionalScopes,
languageVersionSettings
)
}
is PackageViewDescriptor -> {
val memberAsImportingScope = descriptor.memberScope.memberScopeAsImportingScope()
LexicalScope.Base(
chainImportingScopes(explicitScopes + listOf(memberAsImportingScope) + additionalScopes)!!,
ownerDescriptor
)
}
is ClassDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
ClassResolutionScopesSupport(
descriptor,
LockBasedStorageManager.NO_LOCKS,
languageVersionSettings
) { outerScope }.scopeForMemberDeclarationResolution()
}
is TypeAliasDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
LexicalScopeImpl(
outerScope,
descriptor,
false,
null,
emptyList(),
LexicalScopeKind.TYPE_ALIAS_HEADER,
LocalRedeclarationChecker.DO_NOTHING
) {
for (typeParameter in descriptor.declaredTypeParameters) {
addClassifierDescriptor(typeParameter)
}
}
}
is FunctionDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
FunctionDescriptorUtil.getFunctionInnerScope(outerScope, descriptor, LocalRedeclarationChecker.DO_NOTHING)
}
is PropertyDescriptor -> {
val outerScope = getResolutionScope(
descriptor.containingDeclaration, ownerDescriptor, explicitScopes, additionalScopes, languageVersionSettings
) ?: return null
val propertyHeader = ScopeUtils.makeScopeForPropertyHeader(outerScope, descriptor)
LexicalScopeImpl(
propertyHeader,
descriptor,
false,
descriptor.extensionReceiverParameter,
descriptor.contextReceiverParameters,
LexicalScopeKind.PROPERTY_ACCESSOR_BODY
)
}
else -> return null // something local, should not work with ReplaceWith
}
}
}
| plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/replaceWith/ReplaceWithAnnotationAnalyzer.kt | 2766721897 |
package com.bajdcc.LALR1.interpret.os.user.routine.file
import com.bajdcc.LALR1.interpret.os.IOSCodePage
import com.bajdcc.util.ResourceLoader
/**
* 【用户态】读文件
*
* @author bajdcc
*/
class URFileLoad : IOSCodePage {
override val name: String
get() = "/usr/p/<"
override val code: String
get() = ResourceLoader.load(javaClass)
}
| src/main/kotlin/com/bajdcc/LALR1/interpret/os/user/routine/file/URFileLoad.kt | 4050233435 |
/*
* Copyright 2020 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.storage
import arcs.core.crdt.CrdtCount
import arcs.core.crdt.CrdtCount.Operation.Increment
import arcs.core.crdt.CrdtCount.Operation.MultiIncrement
import arcs.core.crdt.VersionMap
import arcs.core.data.CountType
import arcs.core.storage.ProxyMessage.ModelUpdate
import arcs.core.storage.ProxyMessage.Operations
import arcs.core.storage.driver.RamDisk
import arcs.core.storage.driver.RamDiskDriverProvider
import arcs.core.storage.keys.RamDiskStorageKey
import arcs.core.storage.testutil.getTestHelper
import arcs.core.storage.testutil.testDriverFactory
import arcs.core.storage.testutil.testWriteBackProvider
import com.google.common.truth.Truth.assertThat
import kotlin.random.Random
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.joinAll
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
/** Tests behaviors of the combination of [DirectStore] and [RamDisk]. */
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(JUnit4::class)
class DirectStoreConcurrencyTest {
private val storageKey: StorageKey = RamDiskStorageKey("unique")
@Before
fun setup() = runBlockingTest {
DefaultDriverFactory.update(RamDiskDriverProvider())
RamDisk.clear()
}
@Test
fun stores_sequenceOfModelAndOperationUpdates_asModels() = runBlockingTest {
val activeStore = createStore(storageKey)
val count = CrdtCount()
count.applyOperation(MultiIncrement(actor = "me", VersionMap("me" to 1), delta = 42))
// Launch three separate coroutines to emulate some concurrency.
val jobs = mutableListOf<Job>()
jobs += launch {
activeStore.onProxyMessage(ModelUpdate(count.data, id = 1))
println("Sent 1")
}
jobs += launch {
activeStore.onProxyMessage(
Operations(listOf(Increment("me", VersionMap("me" to 2))), id = 1)
)
println("Sent 2")
}
jobs += launch {
activeStore.onProxyMessage(
Operations(listOf(Increment("them", VersionMap("them" to 1))), id = 1)
)
println("Sent 3")
}
println("Jobs length: ${jobs.size}")
jobs.joinAll()
println("Joined")
activeStore.idle()
val driverTestHelper = activeStore.driver.getTestHelper()
assertThat(driverTestHelper.getData()).isEqualTo(activeStore.getLocalData())
assertThat(driverTestHelper.getVersion()).isEqualTo(3)
println("Done")
}
@Test
fun stores_operationUpdates_fromMultipleSources() = runBlockingTest {
val activeStore1 = createStore(storageKey)
val activeStore2 = createStore(storageKey)
val count1 = CrdtCount()
count1.applyOperation(MultiIncrement("me", VersionMap("me" to 1), delta = 42))
val count2 = CrdtCount()
count2.applyOperation(MultiIncrement("them", VersionMap("them" to 1), delta = 23))
// These three opearations cannot occur concurrently (if they did, versions wouldn't line up
// correctly on an actor-by-actor basis, and thus - CRDT would be unable to apply changes.
coroutineScope {
async { activeStore1.onProxyMessage(ModelUpdate(count1.data, 1)) }
async { activeStore2.onProxyMessage(ModelUpdate(count2.data, 1)) }
async {
delay(Random.nextLong(1500))
activeStore1.onProxyMessage(
Operations(
listOf(
Increment("me", VersionMap("me" to 2)),
Increment("other", VersionMap("other" to 1))
),
id = 1
)
)
}
}
// These two operations can occur concurrently, since their modifications come from only one
// actor at a time, and their actors' versions are correct.
coroutineScope {
async(start = CoroutineStart.UNDISPATCHED) {
// Random sleep/delay, to make the ordering of execution random.
delay(Random.nextLong(1500))
activeStore2.onProxyMessage(
Operations(
listOf(
Increment("them", VersionMap("them" to 2))
),
id = 1
)
)
}
async(start = CoroutineStart.UNDISPATCHED) {
// Random sleep/delay, to make the ordering of execution random.
delay(Random.nextLong(1500))
activeStore1.onProxyMessage(
Operations(
listOf(
MultiIncrement("me", VersionMap("me" to 3), delta = 74)
),
id = 1
)
)
}
}
activeStore1.idle()
activeStore2.idle()
val driverTestHelper = activeStore1.driver.getTestHelper()
assertThat(driverTestHelper.getData()).isEqualTo(activeStore1.getLocalData())
assertThat(driverTestHelper.getData()).isEqualTo(activeStore2.getLocalData())
assertThat(driverTestHelper.getVersion()).isEqualTo(5)
}
@Test
@Suppress("UNCHECKED_CAST")
fun store_operationUpdates_fromMultipleSources_withTimingDelays() = runBlockingTest {
val activeStore1 = createStore(storageKey)
val activeStore2 = createStore(storageKey)
activeStore1.onProxyMessage(Operations(listOf(Increment("me", VersionMap("me" to 1))), 1))
delay(100)
val concurrentJobA = launch {
delay(Random.nextLong(5))
activeStore1.onProxyMessage(
Operations(listOf(Increment("them", VersionMap("them" to 1))), 1)
)
}
val concurrentJobB = launch {
delay(Random.nextLong(5))
activeStore2.onProxyMessage(
Operations(listOf(Increment("other", VersionMap("other" to 1))), 1)
)
}
listOf(concurrentJobA, concurrentJobB).joinAll()
delay(100)
activeStore2.onProxyMessage(Operations(listOf(Increment("other", VersionMap("other" to 2))), 1))
activeStore1.idle()
activeStore2.idle()
val driverTestHelper = activeStore1.driver.getTestHelper()
assertThat(driverTestHelper.getData()).isEqualTo(activeStore1.getLocalData())
assertThat(driverTestHelper.getData()).isEqualTo(activeStore2.getLocalData())
assertThat(driverTestHelper.getVersion()).isEqualTo(4)
assertThat(activeStore1.localModel.consumerView).isEqualTo(4)
assertThat(activeStore2.localModel.consumerView).isEqualTo(4)
}
companion object {
private suspend fun CoroutineScope.createStore(
storageKey: StorageKey
): DirectStore<CrdtCount.Data, CrdtCount.Operation, Int> {
return DirectStore.create(
StoreOptions(
storageKey,
type = CountType()
),
this,
testDriverFactory,
::testWriteBackProvider,
null
)
}
}
}
| javatests/arcs/core/storage/DirectStoreConcurrencyTest.kt | 4096397578 |
package me.elsiff.morefish.shop
import me.elsiff.egui.GuiOpener
import me.elsiff.morefish.configuration.Config
import me.elsiff.morefish.configuration.ConfigurationSectionAccessor
import me.elsiff.morefish.fishing.Fish
import me.elsiff.morefish.hooker.VaultHooker
import me.elsiff.morefish.item.FishItemStackConverter
import me.elsiff.morefish.util.OneTickScheduler
import net.milkbowl.vault.economy.Economy
import org.bukkit.entity.Player
import kotlin.math.floor
/**
* Created by elsiff on 2019-01-03.
*/
class FishShop(
private val guiOpener: GuiOpener,
private val oneTickScheduler: OneTickScheduler,
private val converter: FishItemStackConverter,
private val vault: VaultHooker
) {
private val economy: Economy
get() {
check(vault.hasHooked) { "Vault must be hooked for fish shop feature" }
check(vault.hasEconomy()) { "Vault doesn't have economy plugin" }
check(vault.economy.isEnabled) { "Economy must be enabled" }
return vault.economy
}
private val shopConfig: ConfigurationSectionAccessor
get() = Config.standard["fish-shop"]
val enabled: Boolean
get() = shopConfig.boolean("enable")
private val priceMultiplier: Double
get() = shopConfig.double("multiplier")
private val roundDecimalPoints: Boolean
get () = shopConfig.boolean("round-decimal-points")
fun sell(player: Player, fish: Fish) {
val price = priceOf(fish)
economy.depositPlayer(player, price)
}
fun sell(player: Player, fish: Collection<Fish>) {
val price = fish.map(this::priceOf).sum()
economy.depositPlayer(player, price)
}
fun priceOf(fish: Fish): Double {
val rarityPrice = fish.type.rarity.additionalPrice
val price = (priceMultiplier * fish.length) + rarityPrice
return if (roundDecimalPoints) {
floor(price)
} else {
price
}
}
fun openGuiTo(player: Player) {
val gui = FishShopGui(this, converter, oneTickScheduler, player)
guiOpener.open(player, gui)
}
} | src/main/kotlin/me/elsiff/morefish/shop/FishShop.kt | 3237481019 |
package bz.stew.bracken.ui.extension.kotlin.collections
/**
* Created by stew on 2/10/17.
*/
fun <K, V> Map<K, Set<V>>.flattenValueSets(): List<V> {
val out : List<V> = mutableListOf()
for (set in this.values) {
out.plus(set)
}
return out
}
fun <L> Collection<L>.flatten(): Collection<L> {
val out: List<L> = mutableListOf()
for (set in this) {
out.plus(set)
}
return out
} | ui/src/main/kotlin/bz/stew/bracken/ui/extension/kotlin/collections/Collections.kt | 3870690509 |
package failchat.gui
import failchat.emoticon.GlobalEmoticonUpdater
import failchat.github.ReleaseChecker
import failchat.kodein
import failchat.platform.windows.WindowsCtConfigurator
import failchat.skin.Skin
import failchat.util.executeWithCatch
import javafx.application.Application
import javafx.application.Platform
import javafx.scene.control.Alert
import javafx.scene.control.Alert.AlertType
import javafx.scene.control.ButtonBar.ButtonData
import javafx.scene.control.ButtonBar.ButtonData.OK_DONE
import javafx.scene.control.ButtonType
import javafx.stage.Stage
import mu.KotlinLogging
import org.apache.commons.configuration2.Configuration
import org.kodein.di.instance
import java.nio.file.Path
import java.time.Duration
import java.time.Instant
import java.util.concurrent.ScheduledExecutorService
class GuiLauncher : Application() {
companion object {
private val logger = KotlinLogging.logger {}
}
override fun start(primaryStage: Stage) {
val startTime = Instant.now()
val config = kodein.instance<Configuration>()
val isWindows = com.sun.jna.Platform.isWindows()
val settings = SettingsFrame(
this,
primaryStage,
config,
kodein.instance<List<Skin>>(),
kodein.instance<Path>("failchatEmoticonsDirectory"),
isWindows,
lazy { kodein.instance<GuiEventHandler>() },
lazy { kodein.instance<GlobalEmoticonUpdater>() }
)
settings.show()
val showTime = Instant.now()
logger.debug { "Settings frame showed in ${Duration.between(startTime, showTime).toMillis()} ms" }
val ctConfigurator: ClickTransparencyConfigurator? = if (isWindows) {
WindowsCtConfigurator(config)
} else {
null
}
Platform.runLater {
val chat = ChatFrame(
this,
kodein.instance<Configuration>(),
kodein.instance<List<Skin>>(),
lazy { kodein.instance<GuiEventHandler>() },
ctConfigurator
)
val backgroundExecutor = kodein.instance<ScheduledExecutorService>("background")
backgroundExecutor.executeWithCatch {
val eventHandler = kodein.instance<GuiEventHandler>()
if (eventHandler is FullGuiEventHandler) {
eventHandler.guiFrames.set(GuiFrames(settings, chat))
}
}
// init web engine (fixes flickering)
chat.clearWebContent()
showUpdateNotificationOnNewRelease()
}
logger.info("GUI loaded")
}
private fun showUpdateNotificationOnNewRelease() {
kodein.instance<ReleaseChecker>().checkNewRelease { release ->
Platform.runLater {
val notification = Alert(AlertType.CONFIRMATION).apply {
title = "Update notification"
headerText = null
graphic = null
contentText = "New release available: ${release.version}"
}
val stage = notification.dialogPane.scene.window as Stage
stage.icons.setAll(Images.appIcon)
val changelogButton = ButtonType("Download", OK_DONE)
val closeButton = ButtonType("Close", ButtonData.CANCEL_CLOSE)
notification.buttonTypes.setAll(changelogButton, closeButton)
val result = notification.showAndWait().get()
if (result === changelogButton) {
hostServices.showDocument(release.releasePageUrl)
}
}
}
}
}
| src/main/kotlin/failchat/gui/GuiLauncher.kt | 1451525102 |
package com.bajdcc.LALR1.semantic.test
import com.bajdcc.LALR1.semantic.Semantic
import com.bajdcc.LALR1.syntax.handler.SyntaxException
import com.bajdcc.util.lexer.error.RegexException
import com.bajdcc.util.lexer.token.OperatorType
import com.bajdcc.util.lexer.token.TokenType
object TestSemantic {
@JvmStatic
fun main(args: Array<String>) {
// System.out.println("Z -> `a`<,> | B | [`a` `b` Z B]");
try {
// Scanner scanner = new Scanner(System.in);
// String expr = "( i )";
val expr = "((i))+i*i+i/(i-i)"
val semantic = Semantic(expr)
semantic.addTerminal("PLUS", TokenType.OPERATOR, OperatorType.PLUS)
semantic.addTerminal("MINUS", TokenType.OPERATOR,
OperatorType.MINUS)
semantic.addTerminal("TIMES", TokenType.OPERATOR,
OperatorType.TIMES)
semantic.addTerminal("DIVIDE", TokenType.OPERATOR,
OperatorType.DIVIDE)
semantic.addTerminal("LPA", TokenType.OPERATOR, OperatorType.LPARAN)
semantic.addTerminal("RPA", TokenType.OPERATOR, OperatorType.RPARAN)
semantic.addTerminal("SYMBOL", TokenType.ID, "i")
semantic.addNonTerminal("Z")
semantic.addNonTerminal("E")
semantic.addNonTerminal("T")
semantic.addNonTerminal("F")
// syntax.infer("E -> T `PLUS`<+> E | T `MINUS`<-> E | T");
// syntax.infer("T -> F `TIMES`<*> T | F `DIVIDE`</> T | F");
// syntax.infer("F -> `LPA`<(> E `RPA`<)> | `SYMBOL`<i>");
semantic.infer("Z -> E")
semantic.infer("E -> T")
semantic.infer("E -> E @PLUS<+> T")
semantic.infer("E -> E @MINUS<-> T")
semantic.infer("T -> F")
semantic.infer("T -> T @TIMES<*> F")
semantic.infer("T -> T @DIVIDE</> F")
semantic.infer("F -> @SYMBOL<i>")
semantic.infer("F -> @LPA<(> E @RPA<)>")
semantic.initialize("Z")
println(semantic.toString())
println(semantic.ngaString)
println(semantic.npaString)
println(semantic.inst)
println(semantic.trackerError)
println(semantic.tokenList)
// scanner.close();
} catch (e: RegexException) {
System.err.println(e.position.toString() + "," + e.message)
e.printStackTrace()
} catch (e: SyntaxException) {
System.err.println(e.position.toString() + "," + e.message + " "
+ e.info)
e.printStackTrace()
}
}
}
| src/main/kotlin/com/bajdcc/LALR1/semantic/test/TestSemantic.kt | 2439103818 |
/*
* Copyright (c) 2017. All Rights Reserved. Michal Jankowski orbitemobile.pl
*/
package pl.orbitemobile.wspolnoty.data.remote.download
import org.jsoup.Connection
import org.jsoup.Jsoup
class DownloadManagerImpl private constructor() : DownloadManager {
private val USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36"
private val TIMEOUT = 10000
override fun getResponse(url: String): Connection.Response {
return Jsoup.connect(url)
.userAgent(USER_AGENT)
.timeout(TIMEOUT)
.ignoreContentType(true)
.execute()
}
companion object {
val instance = DownloadManagerImpl()
}
}
| app/src/main/java/pl/orbitemobile/wspolnoty/data/remote/download/DownloadManagerImpl.kt | 636599963 |
/*
* Skybot, a multipurpose discord bot
* Copyright (C) 2017 Duncan "duncte123" Sterken & Ramid "ramidzkh" Khan & Maurice R S "Sanduhr32"
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package ml.duncte123.skybot.commands.music
import me.duncte123.botcommons.messaging.MessageUtils
import ml.duncte123.skybot.objects.command.CommandContext
import ml.duncte123.skybot.objects.command.MusicCommand
class ShuffleCommand : MusicCommand() {
init {
this.name = "shuffle"
this.help = "Shuffles the current queue"
}
override fun run(ctx: CommandContext) {
val event = ctx.event
val scheduler = ctx.audioUtils.getMusicManager(event.guild).scheduler
if (scheduler.queue.isEmpty()) {
MessageUtils.sendMsg(ctx, "There are no songs to shuffle")
return
}
scheduler.shuffle()
MessageUtils.sendMsg(ctx, "The queue has been shuffled!")
}
}
| src/main/kotlin/ml/duncte123/skybot/commands/music/ShuffleCommand.kt | 247213097 |
package iii_conventions
import util.TODO
import iii_conventions.TimeInterval.*
fun todoTask29(): Nothing = TODO(
"""
Task 29.
Implement a kind of date arithmetic. Support adding years, weeks and days to a date.
Use classes MyDate and TimeInterval.
Use a utility function MyDate.addTimeIntervals.
Uncomment the commented line and make it compile.
(1). Add an extension function 'plus()' to MyDate, taking a TimeInterval as an argument.
(2). Support adding several time intervals to a date. Add an extra class.
If you have any problems, see the iii_conventions/_29_Tips.kt file.
""",
references = { date: MyDate, timeInterval: TimeInterval ->
date.addTimeIntervals(timeInterval, 1)
})
fun task29_1(today: MyDate): MyDate {
// todoTask29()
return today + YEAR + WEEK
}
fun task29_2(today: MyDate): MyDate {
// todoTask29()
return today + YEAR * 2 + WEEK * 3 + DAY * 5
}
| src/iii_conventions/_29_OperatorsOverloading.kt | 3993150118 |
package org.hexworks.zircon.example
import com.badlogic.gdx.ApplicationAdapter
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import com.badlogic.gdx.graphics.OrthographicCamera
import com.badlogic.gdx.utils.viewport.ExtendViewport
import org.hexworks.zircon.api.CP437TilesetResources
import org.hexworks.zircon.api.DrawSurfaces
import org.hexworks.zircon.api.LibgdxApplications
import org.hexworks.zircon.api.application.AppConfig
import org.hexworks.zircon.api.builder.graphics.LayerBuilder
import org.hexworks.zircon.api.color.ANSITileColor
import org.hexworks.zircon.api.data.Position
import org.hexworks.zircon.api.data.Size
import org.hexworks.zircon.api.data.Tile
import org.hexworks.zircon.api.graphics.Layer
import org.hexworks.zircon.api.graphics.StyleSet
import org.hexworks.zircon.api.grid.TileGrid
import org.hexworks.zircon.internal.RunTimeStats
import org.hexworks.zircon.internal.data.GridPosition
import org.hexworks.zircon.internal.grid.InternalTileGrid
import org.hexworks.zircon.internal.grid.ThreadSafeTileGrid
import org.hexworks.zircon.internal.renderer.LibgdxRenderer
import java.util.*
private val size = Size.create(80, 40)
private val tileset = CP437TilesetResources.wanderlust16x16()
private const val screenWidth = 1920f
private const val screenHeight = 1080f
class LibgdxTest(
config: AppConfig
) : ApplicationAdapter() {
private val camera = OrthographicCamera()
private val viewport = ExtendViewport(screenWidth, screenHeight, camera)
private val tileGrid: InternalTileGrid = ThreadSafeTileGrid(config)
private val renderer = LibgdxRenderer(grid = tileGrid)
private val random = Random()
private val terminalWidth = size.width
private val terminalHeight = size.height
private val layerCount = 1
private val layerWidth = 15
private val layerHeight = 15
private val layerSize = Size.create(layerWidth, layerHeight)
private val filler = Tile.defaultTile().withCharacter('x')
private var layers: List<Layer> = (0..layerCount).map {
val imageLayer = DrawSurfaces.tileGraphicsBuilder()
.withSize(layerSize)
.withTileset(tileset)
.build()
layerSize.fetchPositions().forEach {
imageLayer.draw(filler, it)
}
val layer = LayerBuilder.newBuilder()
.withOffset(
Position.create(
x = random.nextInt(terminalWidth - layerWidth),
y = random.nextInt(terminalHeight - layerHeight)
)
)
.withTileGraphics(imageLayer)
.build()
tileGrid.addLayer(layer)
layer
}
private val chars = listOf('a', 'b')
private val styles = listOf(
StyleSet.newBuilder().apply {
foregroundColor = ANSITileColor.RED
backgroundColor = ANSITileColor.GREEN
}.build(),
StyleSet.newBuilder().apply {
foregroundColor = ANSITileColor.MAGENTA
backgroundColor = ANSITileColor.YELLOW
}.build()
)
private var currIdx = 0
private var loopCount = 0
override fun create() {
camera.setToOrtho(false, viewport.screenWidth.toFloat(), viewport.screenHeight.toFloat())
viewport.update(screenWidth.toInt(), screenHeight.toInt())
viewport.apply()
println(camera.viewportHeight)
LibgdxApplications.startTileGrid(
AppConfig.newBuilder()
.withDefaultTileset(tileset)
.withSize(Size.create(terminalWidth, terminalHeight))
.build()
)
renderer.create()
}
override fun render() {
RunTimeStats.addTimedStatFor("debug.render.time") {
val tile = Tile.newBuilder()
.withCharacter(chars[currIdx])
.withStyleSet(styles[currIdx])
.build()
fillGrid(tileGrid, tile)
layers.forEach {
it.asInternalLayer().moveTo(
Position.create(
x = random.nextInt(terminalWidth - layerWidth),
y = random.nextInt(terminalHeight - layerHeight)
)
)
}
currIdx = if (currIdx == 0) 1 else 0
loopCount++
renderer.render()
camera.update()
}
}
override fun resize(width: Int, height: Int) {
viewport.update(width, height)
camera.update()
}
override fun dispose() {
renderer.close()
}
}
object GdxLauncher {
@JvmStatic
fun main(arg: Array<String>) {
val cfg = LwjglApplicationConfiguration()
cfg.title = "LibGDX Test"
cfg.height = size.height * tileset.height
cfg.width = size.width * tileset.width
LwjglApplication(LibgdxTest(AppConfig.defaultConfiguration()), cfg)
}
}
private fun fillGrid(tileGrid: TileGrid, tile: Tile) {
(0..tileGrid.size.height).forEach { y ->
(0..tileGrid.size.width).forEach { x ->
tileGrid.draw(tile, GridPosition(x, y))
}
}
}
| zircon.jvm.libgdx/src/test/kotlin/org/hexworks/zircon/example/LibgdxTest.kt | 2044912836 |
package org.hexworks.zircon.internal.uievent
import org.hexworks.zircon.api.uievent.*
/**
* Callback interface for [ComponentEvent]s which can typically be implemented
* by long-lived objects. See [ComponentEventType]. This class is part of the internal
* API so don't call any of these methods, it is the library's job to do so.
*/
interface ComponentEventAdapter {
/**
* Focus was given to the component. Note that if focus was programmatically
* given there is no originating [UIEvent].
*/
fun focusGiven(): UIEventResponse = Pass
/**
* Focus was taken away from the component. Note that if focus was programmatically
* taken there is no originating [UIEvent].
*/
fun focusTaken(): UIEventResponse = Pass
/**
* The component was activated (mouse click or spacebar press typically).
*/
fun activated(): UIEventResponse = Pass
/**
* The component was deactivated (mouse release or spacebar release typically).
*/
fun deactivated(): UIEventResponse = Pass
}
| zircon.core/src/commonMain/kotlin/org/hexworks/zircon/internal/uievent/ComponentEventAdapter.kt | 3321792901 |
/*
* Copyright 2019-present Facebook, 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.facebook.buck.multitenant.service
import com.facebook.buck.core.model.UnconfiguredBuildTarget
import com.facebook.buck.core.model.targetgraph.raw.RawTargetNode
import java.nio.file.Path
import java.util.*
typealias Commit = String
internal typealias BuildTargetId = Int
/**
* The values in the array must be sorted in ascending order or else [equals_BuildTargetSet] and
* [hashCode_BuildTargetSet] will not work properly.
*/
internal typealias BuildTargetSet = IntArray
/**
* This is a RawTargetNode paired with its deps as determined by configuring the RawTargetNode with
* the empty configuration.
*/
data class RawBuildRule(val targetNode: RawTargetNode, val deps: Set<UnconfiguredBuildTarget>)
/**
* @param[deps] must be sorted in ascending order!!!
*/
internal data class InternalRawBuildRule(val targetNode: RawTargetNode, val deps: BuildTargetSet) {
/*
* Because RawTargetNodeAndDeps contains an IntArray field, which does not play well with
* `.equals()` (or `hashCode()`, for that matter), we have to do a bit of work to implement
* these methods properly when the default implementations for a data class are not appropriate.
*/
override fun equals(other: Any?): Boolean {
if (other !is InternalRawBuildRule) {
return false
}
return targetNode == other.targetNode && equals_BuildTargetSet(deps, other.deps)
}
override fun hashCode(): Int {
return 31 * Objects.hash(targetNode) + hashCode_BuildTargetSet(deps)
}
}
private fun equals_BuildTargetSet(set1: BuildTargetSet, set2: BuildTargetSet): Boolean {
return set1.contentEquals(set2)
}
private fun hashCode_BuildTargetSet(set: BuildTargetSet): Int {
return set.contentHashCode()
}
/**
* By construction, the name for each rule in rules should be distinct across all of the rules in
* the set.
*/
data class BuildPackage(val buildFileDirectory: Path, val rules: Set<RawBuildRule>)
internal data class InternalBuildPackage(val buildFileDirectory: Path, val rules: Set<InternalRawBuildRule>)
/**
* By construction, the Path for each BuildPackage should be distinct across all of the
* collections of build packages.
*/
data class Changes(val addedBuildPackages: List<BuildPackage>,
val modifiedBuildPackages: List<BuildPackage>,
val removedBuildPackages: List<Path>)
internal data class InternalChanges(val addedBuildPackages: List<InternalBuildPackage>,
val modifiedBuildPackages: List<InternalBuildPackage>,
val removedBuildPackages: List<Path>)
| src/com/facebook/buck/multitenant/service/Types.kt | 2868787647 |
package com.android.mdl.app.transfer
import com.android.identity.IdentityCredentialStore.CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256
import com.android.identity.PresentationSession
class SessionSetup(
private val credentialStore: CredentialStore
) {
fun createSession(): PresentationSession {
val store = credentialStore.createIdentityCredentialStore()
return store.createPresentationSession(
CIPHERSUITE_ECDHE_HKDF_ECDSA_WITH_AES_256_GCM_SHA256
)
}
} | appholder/src/main/java/com/android/mdl/app/transfer/SessionSetup.kt | 2587237096 |
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, you can obtain one at http://mozilla.org/MPL/2.0/.
* ------------------------------------------------------------------*/
package com.kotlinnlp.simplednn.simplemath.ndarray
import java.io.Serializable
/**
* The shape of an bi-dimensional NDArray containing its dimensions (first and second).
*/
data class Shape(val dim1: Int, val dim2: Int = 1) : Serializable {
companion object {
/**
* Private val used to serialize the class (needed by Serializable).
*/
@Suppress("unused")
private const val serialVersionUID: Long = 1L
}
/**
* The inverse [Shape] of this.
*/
val inverse: Shape get() = Shape(this.dim2, this.dim1)
/**
* @param other any object
*
* @return a Boolean indicating if this [Shape] is equal to the given [other] object
*/
override fun equals(other: Any?): Boolean {
return (other is Shape && other.dim1 == this.dim1 && other.dim2 == this.dim2)
}
/**
* @return the hash code representation of this [Shape]
*/
override fun hashCode(): Int {
var hash = 7
hash = 83 * hash + this.dim1
hash = 83 * hash + this.dim2
return hash
}
}
| src/main/kotlin/com/kotlinnlp/simplednn/simplemath/ndarray/Shape.kt | 3331646460 |
package com.saladevs.rxsse
data class ServerSentEvent(val lastId: String,
val retry: Long,
val event: String,
val data: String)
| src/main/kotlin/com/saladevs/rxsse/ServerSentEvent.kt | 932841761 |
// PROBLEM: none
class My {
val x: <caret>Int = 1
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/redundantExplicitType/member.kt | 3185307622 |
// 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 training.learn.lesson.general.assistance
import com.intellij.CommonBundle
import com.intellij.history.integration.ui.actions.LocalHistoryGroup
import com.intellij.history.integration.ui.actions.ShowHistoryAction
import com.intellij.icons.AllIcons
import com.intellij.idea.ActionsBundle
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.actionSystem.IdeActions
import com.intellij.openapi.actionSystem.impl.ActionMenu
import com.intellij.openapi.actionSystem.impl.ActionMenuItem
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.application.invokeLater
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.EditorModificationUtil
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.editor.ex.EditorEx
import com.intellij.openapi.editor.ex.EditorGutterComponentEx
import com.intellij.openapi.editor.impl.EditorComponentImpl
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.progress.runBackgroundableTask
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.ui.popup.Balloon
import com.intellij.openapi.util.io.FileUtil
import com.intellij.ui.components.JBLoadingPanel
import com.intellij.ui.components.JBLoadingPanelListener
import com.intellij.ui.table.JBTable
import com.intellij.ui.tabs.impl.SingleHeightTabs
import com.intellij.util.DocumentUtil
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.ui.UIUtil
import org.assertj.swing.core.MouseButton
import org.assertj.swing.data.TableCell
import org.assertj.swing.fixture.JTableFixture
import org.jetbrains.annotations.Nls
import training.FeaturesTrainerIcons
import training.dsl.*
import training.dsl.LessonUtil.restoreIfModifiedOrMoved
import training.learn.LearnBundle
import training.learn.LessonsBundle
import training.learn.course.KLesson
import training.learn.course.LessonProperties
import training.learn.course.LessonType
import training.learn.lesson.LessonManager
import training.ui.LearningUiHighlightingManager
import training.ui.LearningUiHighlightingManager.HighlightingOptions
import training.ui.LearningUiUtil
import training.util.LessonEndInfo
import java.awt.Component
import java.awt.Point
import java.awt.Rectangle
import java.util.concurrent.CompletableFuture
import javax.swing.JFrame
class LocalHistoryLesson : KLesson("CodeAssistance.LocalHistory", LessonsBundle.message("local.history.lesson.name")) {
override val languageId = "yaml"
override val lessonType = LessonType.SCRATCH
override val properties = LessonProperties(availableSince = "212.5284")
private val lineToDelete = 14
private val revisionInd = 2
private val sample = parseLessonSample("""
cat:
name: Pelmen
gender: male
breed: sphinx
fur_type: hairless
fur_pattern: solid
fur_colors: [ white ]
tail_length: long
eyes_colors: [ green ]
favourite_things:
- three plaids
- pile of clothes
- castle of boxes
- toys scattered all over the place
behavior:
- play:
condition: boring
actions:
- bring one of the favourite toys to the human
- run all over the house
- eat:
condition: want to eat
actions:
- shout to the whole house
- sharpen claws by the sofa
- wake up a human in the middle of the night""".trimIndent())
private val textToDelete = """
| - play:
| condition: boring
| actions:
| - bring one of the favourite toys to the human
| - run all over the house
""".trimMargin()
private val textAfterDelete = """
| behavior:
|
| - eat:
""".trimMargin()
private val textToAppend = """
| - sleep:
| condition: want to sleep
| action:
| - bury himself in a human's blanket
| - bury himself in a favourite plaid
""".trimMargin()
override val lessonContent: LessonContext.() -> Unit = {
prepareSample(sample)
caret(textToDelete, select = true)
prepareRuntimeTask(ModalityState.NON_MODAL) {
FileDocumentManager.getInstance().saveDocument(editor.document)
}
val localHistoryActionText = ActionsBundle.groupText("LocalHistory").dropMnemonic()
task {
text(LessonsBundle.message("local.history.remove.code",
strong(localHistoryActionText),
action(IdeActions.ACTION_EDITOR_BACKSPACE)))
stateCheck {
editor.document.charsSequence.contains(textAfterDelete)
}
restoreIfModifiedOrMoved()
test { invokeActionViaShortcut("DELETE") }
}
setEditorHint(LessonsBundle.message("local.history.editor.hint"))
waitBeforeContinue(500)
prepareRuntimeTask {
if (!TaskTestContext.inTestMode) {
val userDecision = Messages.showOkCancelDialog(
LessonsBundle.message("local.history.dialog.message"),
LessonsBundle.message("recent.files.dialog.title"),
CommonBundle.message("button.ok"),
LearnBundle.message("learn.stop.lesson"),
FeaturesTrainerIcons.PluginIcon
)
if (userDecision != Messages.OK) {
LessonManager.instance.stopLesson()
}
}
}
modifyFile()
lateinit var invokeMenuTaskId: TaskContext.TaskId
task {
invokeMenuTaskId = taskId
text(LessonsBundle.message("local.history.imagine.restore", strong(ActionsBundle.message("action.\$Undo.text"))))
text(LessonsBundle.message("local.history.invoke.context.menu", strong(localHistoryActionText)))
triggerAndBorderHighlight().component { ui: EditorComponentImpl -> ui.editor == editor }
triggerAndFullHighlight().component { ui: ActionMenu ->
isClassEqual(ui.anAction, LocalHistoryGroup::class.java)
}
test {
ideFrame { robot().rightClick(editor.component) }
}
}
task("LocalHistory.ShowHistory") {
val showHistoryActionText = ActionsBundle.actionText(it).dropMnemonic()
text(LessonsBundle.message("local.history.show.history", strong(localHistoryActionText), strong(showHistoryActionText)))
triggerAndFullHighlight { clearPreviousHighlights = false }.component { ui: ActionMenuItem ->
isClassEqual(ui.anAction, ShowHistoryAction::class.java)
}
trigger(it)
restoreByUi()
test {
ideFrame {
jMenuItem { item: ActionMenu -> isClassEqual(item.anAction, LocalHistoryGroup::class.java) }.click()
jMenuItem { item: ActionMenuItem -> isClassEqual(item.anAction, ShowHistoryAction::class.java) }.click()
}
}
}
var revisionsTable: JBTable? = null
task {
triggerAndBorderHighlight().componentPart { ui: JBTable ->
if (checkInsideLocalHistoryFrame(ui)) {
revisionsTable = ui
ui.getCellRect(revisionInd, 0, false)
}
else null
}
}
lateinit var selectRevisionTaskId: TaskContext.TaskId
task {
selectRevisionTaskId = taskId
text(LessonsBundle.message("local.history.select.revision", strong(localHistoryActionText), strong(localHistoryActionText)))
val step = CompletableFuture<Boolean>()
addStep(step)
triggerUI { clearPreviousHighlights = false }.component l@{ ui: JBLoadingPanel ->
if (!checkInsideLocalHistoryFrame(ui)) return@l false
ui.addListener(object : JBLoadingPanelListener {
override fun onLoadingStart() {
// do nothing
}
override fun onLoadingFinish() {
val revisions = revisionsTable ?: return
if (revisions.selectionModel.selectedIndices.let { it.size == 1 && it[0] == revisionInd }) {
ui.removeListener(this)
step.complete(true)
}
}
})
true
}
restoreByUi(invokeMenuTaskId, delayMillis = defaultRestoreDelay)
test {
ideFrame {
Thread.sleep(1000)
val table = revisionsTable ?: error("revisionsTable is not initialized")
JTableFixture(robot(), table).click(TableCell.row(revisionInd).column(0), MouseButton.LEFT_BUTTON)
}
}
}
task {
triggerAndBorderHighlight().componentPart { ui: EditorGutterComponentEx -> findDiffGutterRect(ui) }
}
task {
text(LessonsBundle.message("local.history.restore.code", icon(AllIcons.Diff.ArrowRight)))
text(LessonsBundle.message("local.history.restore.code.balloon"),
LearningBalloonConfig(Balloon.Position.below, 0, cornerToPointerDistance = 50))
stateCheck {
editor.document.charsSequence.contains(textToDelete)
}
restoreByUi(invokeMenuTaskId)
restoreState(selectRevisionTaskId) l@{
val revisions = revisionsTable ?: return@l false
revisions.selectionModel.selectedIndices.let { it.size != 1 || it[0] != revisionInd }
}
test {
ideFrame {
val gutterComponent = previous.ui as? EditorGutterComponentEx ?: error("Failed to find gutter component")
val gutterRect = findDiffGutterRect(gutterComponent) ?: error("Failed to find required gutter")
robot().click(gutterComponent, Point(gutterRect.x + gutterRect.width / 2, gutterRect.y + gutterRect.height / 2))
}
}
}
task {
before { LearningUiHighlightingManager.clearHighlights() }
text(LessonsBundle.message("local.history.close.window", action("EditorEscape")))
stateCheck {
val focusedEditor = focusOwner as? EditorComponentImpl
// check that it is editor from main IDE frame
focusedEditor != null && UIUtil.getParentOfType(SingleHeightTabs::class.java, focusedEditor) != null
}
test {
invokeActionViaShortcut("ESCAPE")
// sometimes some small popup appears at mouse position so the first Escape may close just that popup
invokeActionViaShortcut("ESCAPE")
}
}
setEditorHint(null)
text(LessonsBundle.message("local.history.congratulations"))
}
override fun onLessonEnd(project: Project, lessonEndInfo: LessonEndInfo) {
if (!lessonEndInfo.lessonPassed) return
ApplicationManager.getApplication().executeOnPooledThread {
val editorComponent = LearningUiUtil.findComponentOrNull(project, EditorComponentImpl::class.java) { editor ->
UIUtil.getParentOfType(SingleHeightTabs::class.java, editor) != null
} ?: error("Failed to find editor component")
invokeLater {
val lines = textToDelete.lines()
val rightColumn = lines.maxOf { it.length }
LearningUiHighlightingManager.highlightPartOfComponent(editorComponent, HighlightingOptions(highlightInside = false)) {
val editor = editorComponent.editor
val textToFind = lines[0].trim()
val offset = editor.document.charsSequence.indexOf(textToFind)
if (offset == -1) error("Failed to find '$textToFind' in the editor")
val leftPosition = editor.offsetToLogicalPosition(offset)
val leftPoint = editor.logicalPositionToXY(leftPosition)
val rightPoint = editor.logicalPositionToXY(LogicalPosition(leftPosition.line, rightColumn))
Rectangle(leftPoint.x - 3, leftPoint.y, rightPoint.x - leftPoint.x + 6, editor.lineHeight * lines.size)
}
}
}
}
private fun isClassEqual(value: Any, expectedClass: Class<*>): Boolean {
return value.javaClass.name == expectedClass.name
}
private fun findDiffGutterRect(ui: EditorGutterComponentEx): Rectangle? {
val editor = CommonDataKeys.EDITOR.getData(ui as DataProvider) ?: return null
val offset = editor.document.charsSequence.indexOf(textToDelete)
return if (offset != -1) {
val lineIndex = editor.document.getLineNumber(offset)
invokeAndWaitIfNeeded {
val y = editor.visualLineToY(lineIndex)
Rectangle(ui.width - ui.whitespaceSeparatorOffset, y, ui.width - 26, editor.lineHeight)
}
}
else null
}
private fun TaskRuntimeContext.checkInsideLocalHistoryFrame(component: Component): Boolean {
val frame = UIUtil.getParentOfType(JFrame::class.java, component)
return frame?.title == FileUtil.toSystemDependentName(virtualFile.path)
}
// If message is null it will remove the existing hint and allow file modification
private fun LessonContext.setEditorHint(@Nls message: String?) {
prepareRuntimeTask {
EditorModificationUtil.setReadOnlyHint(editor, message)
(editor as EditorEx).isViewer = message != null
}
}
private fun LessonContext.modifyFile() {
task {
addFutureStep {
val editor = this.editor
runBackgroundableTask(LessonsBundle.message("local.history.file.modification.progress"), project, cancellable = false) {
val document = editor.document
invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) }
removeLineWithAnimation(editor)
invokeAndWaitIfNeeded { FileDocumentManager.getInstance().saveDocument(document) }
Thread.sleep(50)
insertStringWithAnimation(editor, textToAppend, editor.document.textLength)
taskInvokeLater {
editor.caretModel.moveToOffset(document.textLength)
FileDocumentManager.getInstance().saveDocument(document)
completeStep()
}
}
}
}
}
@RequiresBackgroundThread
private fun removeLineWithAnimation(editor: Editor) {
val document = editor.document
val startOffset = document.getLineStartOffset(lineToDelete)
val endOffset = document.getLineEndOffset(lineToDelete)
for (ind in endOffset downTo startOffset) {
invokeAndWaitIfNeeded {
DocumentUtil.writeInRunUndoTransparentAction {
editor.caretModel.moveToOffset(ind)
document.deleteString(ind - 1, ind)
}
}
Thread.sleep(10)
}
}
@RequiresBackgroundThread
private fun insertStringWithAnimation(editor: Editor, text: String, offset: Int) {
val document = editor.document
for (ind in text.indices) {
invokeAndWaitIfNeeded {
DocumentUtil.writeInRunUndoTransparentAction {
document.insertString(offset + ind, text[ind].toString())
editor.caretModel.moveToOffset(offset + ind)
}
}
Thread.sleep(10)
}
}
override val suitableTips = listOf("local_history")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("local.history.help.link"),
LessonUtil.getHelpLink("local-history.html")),
)
} | plugins/ide-features-trainer/src/training/learn/lesson/general/assistance/LocalHistoryLesson.kt | 189584702 |
package rs.emulate.legacy.title.font
import rs.emulate.legacy.IndexedFileSystem
import rs.emulate.legacy.archive.Archive
import rs.emulate.legacy.graphics.GraphicsDecoder
import rs.emulate.legacy.graphics.ImageFormat
/**
* A [GraphicsDecoder] for [Font]s.
*
* @param graphics The [Archive] containing the font.
* @param name The name of the [Font] to decode.
*/
class FontDecoder(graphics: Archive, name: String) : GraphicsDecoder(graphics, name) {
/**
* Decodes the [Font].
*/
fun decode(): Font {
index.readerIndex(data.readUnsignedShort() + 4)
val offset = index.readUnsignedByte()
if (offset > 0) {
index.readerIndex(3 * (offset - 1))
}
val glyphs = Array(GLYPHS_PER_FONT) { decodeGlyph() }
return Font(name, glyphs)
}
/**
* Decodes a single [Glyph].
*/
private fun decodeGlyph(): Glyph {
var horizontalOffset = index.readUnsignedByte()
val verticalOffset = index.readUnsignedByte()
val width = index.readUnsignedShort()
val height = index.readUnsignedShort()
val format = ImageFormat.valueOf(index.readUnsignedByte().toInt())
val raster = decodeRaster(width, height, format)
var spacing = width + SPACING
var left = 0
var right = 0
for (y in height / 7 until height) {
left += raster[y * width].toInt()
right += raster[(y + 1) * width - 1].toInt()
}
if (left <= height / 7) {
spacing--
horizontalOffset = 0
}
if (right <= height / 7) {
spacing--
}
return Glyph(format, raster, height, width, horizontalOffset.toInt(), verticalOffset.toInt(), spacing)
}
/**
* Decodes the raster of a single [Glyph].
*/
private fun decodeRaster(width: Int, height: Int, format: ImageFormat): ByteArray {
val count = width * height
val raster = ByteArray(count)
when (format) {
ImageFormat.COLUMN_ORDERED -> data.readBytes(raster)
ImageFormat.ROW_ORDERED -> for (x in 0 until width) {
for (y in 0 until height) {
raster[x + y * width] = data.readByte()
}
}
}
return raster
}
companion object {
/**
* The amount of Glyphs in a font.
*/
private const val GLYPHS_PER_FONT = 256
/**
* The default spacing offset.
*/
private const val SPACING = 2
/**
* The file id of the title archive.
*/
private const val TITLE_FILE_ID = 1
/**
* Creates a new FontDecoder for the Font with the specified name, using the specified [IndexedFileSystem].
*/
fun create(fs: IndexedFileSystem, name: String): FontDecoder {
return FontDecoder(fs.getArchive(0, TITLE_FILE_ID), name)
}
}
}
| legacy/src/main/kotlin/rs/emulate/legacy/title/font/FontDecoder.kt | 630161229 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.nowinandroid.core.ui
import androidx.compose.foundation.background
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalInspectionMode
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.onClick
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import coil.compose.AsyncImage
import com.google.samples.apps.nowinandroid.core.designsystem.R as DesignsystemR
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaTopicTag
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
import com.google.samples.apps.nowinandroid.core.model.data.Author
import com.google.samples.apps.nowinandroid.core.model.data.NewsResource
import com.google.samples.apps.nowinandroid.core.model.data.Topic
import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import java.util.Locale
import kotlinx.datetime.Instant
import kotlinx.datetime.toJavaInstant
/**
* [NewsResource] card used on the following screens: For You, Saved
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NewsResourceCardExpanded(
newsResource: NewsResource,
isBookmarked: Boolean,
onToggleBookmark: () -> Unit,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
val clickActionLabel = stringResource(R.string.card_tap_action)
Card(
onClick = onClick,
shape = RoundedCornerShape(16.dp),
colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface),
// Use custom label for accessibility services to communicate button's action to user.
// Pass null for action to only override the label and not the actual action.
modifier = modifier.semantics {
onClick(label = clickActionLabel, action = null)
}
) {
Column {
if (!newsResource.headerImageUrl.isNullOrEmpty()) {
Row {
NewsResourceHeaderImage(newsResource.headerImageUrl)
}
}
Box(
modifier = Modifier.padding(16.dp)
) {
Column {
Row {
NewsResourceAuthors(newsResource.authors)
}
Spacer(modifier = Modifier.height(12.dp))
Row {
NewsResourceTitle(
newsResource.title,
modifier = Modifier.fillMaxWidth((.8f))
)
Spacer(modifier = Modifier.weight(1f))
BookmarkButton(isBookmarked, onToggleBookmark)
}
Spacer(modifier = Modifier.height(12.dp))
NewsResourceDate(newsResource.publishDate)
Spacer(modifier = Modifier.height(12.dp))
NewsResourceShortDescription(newsResource.content)
Spacer(modifier = Modifier.height(12.dp))
NewsResourceTopics(newsResource.topics)
}
}
}
}
}
@Composable
fun NewsResourceHeaderImage(
headerImageUrl: String?
) {
AsyncImage(
placeholder = if (LocalInspectionMode.current) {
painterResource(DesignsystemR.drawable.ic_placeholder_default)
} else {
// TODO b/228077205, show specific loading image visual
null
},
modifier = Modifier
.fillMaxWidth()
.height(180.dp),
contentScale = ContentScale.Crop,
model = headerImageUrl,
// TODO b/226661685: Investigate using alt text of image to populate content description
contentDescription = null // decorative image
)
}
@Composable
fun NewsResourceAuthors(
authors: List<Author>
) {
if (authors.isNotEmpty()) {
// display all authors
val authorNameFormatted =
authors.joinToString(separator = ", ") { author -> author.name }
.uppercase(Locale.getDefault())
val authorImageUrl = authors[0].imageUrl
val authorImageModifier = Modifier
.clip(CircleShape)
.size(24.dp)
Row(verticalAlignment = Alignment.CenterVertically) {
if (authorImageUrl.isNotEmpty()) {
AsyncImage(
modifier = authorImageModifier,
contentScale = ContentScale.Crop,
model = authorImageUrl,
contentDescription = null // decorative image
)
} else {
Icon(
modifier = authorImageModifier
.background(MaterialTheme.colorScheme.surface)
.padding(4.dp),
imageVector = NiaIcons.Person,
contentDescription = null // decorative image
)
}
Spacer(modifier = Modifier.width(8.dp))
Text(authorNameFormatted, style = MaterialTheme.typography.labelSmall)
}
}
}
@Composable
fun NewsResourceTitle(
newsResourceTitle: String,
modifier: Modifier = Modifier
) {
Text(newsResourceTitle, style = MaterialTheme.typography.headlineSmall, modifier = modifier)
}
@Composable
fun BookmarkButton(
isBookmarked: Boolean,
onClick: () -> Unit,
modifier: Modifier = Modifier
) {
NiaToggleButton(
checked = isBookmarked,
onCheckedChange = { onClick() },
modifier = modifier,
icon = {
Icon(
painter = painterResource(NiaIcons.BookmarkBorder),
contentDescription = stringResource(R.string.bookmark)
)
},
checkedIcon = {
Icon(
painter = painterResource(NiaIcons.Bookmark),
contentDescription = stringResource(R.string.unbookmark)
)
}
)
}
@Composable
private fun dateFormatted(publishDate: Instant): String {
var zoneId by remember { mutableStateOf(ZoneId.systemDefault()) }
val context = LocalContext.current
DisposableEffect(context) {
val receiver = TimeZoneBroadcastReceiver(
onTimeZoneChanged = { zoneId = ZoneId.systemDefault() }
)
receiver.register(context)
onDispose {
receiver.unregister(context)
}
}
return DateTimeFormatter.ofPattern("MMM d, yyyy")
.withZone(zoneId).format(publishDate.toJavaInstant())
}
@Composable
fun NewsResourceDate(
publishDate: Instant
) {
Text(dateFormatted(publishDate), style = MaterialTheme.typography.labelSmall)
}
@Composable
fun NewsResourceLink(
newsResource: NewsResource
) {
TODO()
}
@Composable
fun NewsResourceShortDescription(
newsResourceShortDescription: String
) {
Text(newsResourceShortDescription, style = MaterialTheme.typography.bodyLarge)
}
@Composable
fun NewsResourceTopics(
topics: List<Topic>,
modifier: Modifier = Modifier
) {
// Store the ID of the Topic which has its "following" menu expanded, if any.
// To avoid UI confusion, only one topic can have an expanded menu at a time.
var expandedTopicId by remember { mutableStateOf<String?>(null) }
Row(
modifier = modifier.horizontalScroll(rememberScrollState()), // causes narrow chips
horizontalArrangement = Arrangement.spacedBy(4.dp),
) {
for (topic in topics) {
NiaTopicTag(
expanded = expandedTopicId == topic.id,
followed = true, // ToDo: Check if topic is followed
onDropMenuToggle = { show ->
expandedTopicId = if (show) topic.id else null
},
onFollowClick = { }, // ToDo
onUnfollowClick = { }, // ToDo
onBrowseClick = { }, // ToDo
text = { Text(text = topic.name.uppercase(Locale.getDefault())) }
)
}
}
}
@Preview("Bookmark Button")
@Composable
fun BookmarkButtonPreview() {
NiaTheme {
Surface {
BookmarkButton(isBookmarked = false, onClick = { })
}
}
}
@Preview("Bookmark Button Bookmarked")
@Composable
fun BookmarkButtonBookmarkedPreview() {
NiaTheme {
Surface {
BookmarkButton(isBookmarked = true, onClick = { })
}
}
}
@Preview("NewsResourceCardExpanded")
@Composable
fun ExpandedNewsResourcePreview() {
NiaTheme {
Surface {
NewsResourceCardExpanded(
newsResource = previewNewsResources[0],
isBookmarked = true,
onToggleBookmark = {},
onClick = {}
)
}
}
}
| core/ui/src/main/java/com/google/samples/apps/nowinandroid/core/ui/NewsResourceCard.kt | 3580198033 |
/*
* The MIT License (MIT)
* Copyright (c) 2016 DataRank, 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.simplymeasured.elasticsearch.plugins.tempest.balancer
import com.simplymeasured.elasticsearch.plugins.tempest.balancer.IndexSizingGroup.*
import org.eclipse.collections.api.RichIterable
import org.eclipse.collections.api.list.MutableList
import org.eclipse.collections.api.map.MapIterable
import org.eclipse.collections.impl.factory.Lists
import org.eclipse.collections.impl.factory.Maps
import org.eclipse.collections.impl.list.mutable.CompositeFastList
import org.eclipse.collections.impl.list.mutable.FastList
import org.eclipse.collections.impl.tuple.Tuples.pair
import org.eclipse.collections.impl.utility.LazyIterate
import org.elasticsearch.cluster.metadata.IndexMetaData
import org.elasticsearch.cluster.metadata.MetaData
import org.elasticsearch.cluster.routing.ShardRouting
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation
import org.elasticsearch.common.component.AbstractComponent
import org.elasticsearch.common.inject.Inject
import org.elasticsearch.common.settings.Settings
import org.elasticsearch.index.shard.ShardId
import org.joda.time.DateTime
/**
* Shard Size Calculator and Estimator used for preemptive balancing
*
* Users define index groups by writing regexes that match index names. When the balancer asks for a shard's size
* this class will either report the actual size of the shard or an estimate for how big the shard will get in the near
* future.
*
* The estimation step only occurs if the index in question is young and if it belongs to a group with indexes that are
* not young. Also, if the actual size of a shard is ever larger than the actual size, the estimation is ignored.
*
* Estimates come in two flavors, homogeneous and non-homogeneous. Homogeneous estimation occurs when the new index and
* all non-young indexes in a group have the same number of shards. In this case the estimated size of a shard is the
* average of all like-id shards in the group. For non-homogeneous groups, the average of all shards in the group is
* used.
*
* Note, any indexes not matching a pattern are placed into a "default" group
*/
class ShardSizeCalculator
@Inject constructor(
settings: Settings,
private val indexGroupPartitioner: IndexGroupPartitioner)
: AbstractComponent(settings) {
// should follow settings for tempest.balancer.modelAgeMinutes
var modelAgeInMinutes = 60*12
fun buildShardSizeInfo(allocation: RoutingAllocation) : MapIterable<ShardId, ShardSizeInfo> {
val shards = LazyIterate.concatenate(
allocation.routingNodes().flatMap { it },
allocation.routingNodes().unassigned())
val indexSizingGroupMap = buildIndexGroupMap(allocation.metaData())
return shards
.groupBy { it.shardId() }
.toMap()
.keyValuesView()
.collect { pair(it.one, it.two.collect { buildShardSizingInfo(allocation, it, indexSizingGroupMap) })}
.toMap({ it.one }, { it.two.maxBy { it.estimatedSize } })
}
private fun buildShardSizingInfo(allocation: RoutingAllocation, it: ShardRouting, indexSizingGroupMap: MapIterable<String, IndexSizingGroup>): ShardSizeInfo {
return ShardSizeInfo(
actualSize = allocation.clusterInfo().getShardSize(it) ?: 0,
estimatedSize = estimateShardSize(allocation, indexSizingGroupMap[it.index]!!, it))
}
private fun buildIndexGroupMap(metaData: MetaData): MapIterable<String, IndexSizingGroup> {
val modelTimestampThreshold = DateTime().minusMinutes(modelAgeInMinutes)
val indexGroups = indexGroupPartitioner.partition(metaData)
val indexSizingGroups = FastList.newWithNValues(indexGroups.size(), {IndexSizingGroup()})
return Maps.mutable.empty<String, IndexSizingGroup>().apply {
metaData.forEach { indexMetaData ->
val indexGroup = indexGroups
.indexOfFirst { it.contains(indexMetaData) }
.let { indexSizingGroups[it] }
when {
modelTimestampThreshold.isAfter(indexMetaData.creationDate) -> indexGroup.addModel(indexMetaData)
else -> indexGroup.addYoungIndex(indexMetaData)
}
this.put(indexMetaData.index, indexGroup)
}
}
}
private fun estimateShardSize(
routingAllocation: RoutingAllocation,
indexSizingGroup: IndexSizingGroup,
shardRouting: ShardRouting) : Long {
return arrayOf(routingAllocation.clusterInfo().getShardSize(shardRouting) ?: 0,
shardRouting.expectedShardSize,
calculateEstimatedShardSize(
routingAllocation,
indexSizingGroup,
shardRouting)).max()
?: 0L
}
private fun calculateEstimatedShardSize(
routingAllocation: RoutingAllocation,
indexSizingGroup: IndexSizingGroup,
shardRouting: ShardRouting): Long {
when {
indexSizingGroup.modelIndexes.anySatisfy { it.index == shardRouting.index() } ->
// for older indexes we can usually trust the actual shard size but not when the shard is being initialized
// from a dead node. In those cases we need to "guess" the size by looking at started replicas with the
// same shard id on that index
return Math.max(routingAllocation.clusterInfo().getShardSize(shardRouting) ?: 0,
routingAllocation.findLargestReplicaSize(shardRouting))
!indexSizingGroup.hasModelIndexes() ->
// it's possible for a newly created index to have no models (or for older versions of the index to be
// nuked). In these cases the best guess we have is the actual shard size
return routingAllocation.clusterInfo().getShardSize(shardRouting) ?: 0
indexSizingGroup.isHomogeneous() ->
// this is an ideal case where we see that the new (young) index and one or more model (old) indexes
// look alike. So we want to use the older indexes as a "guess" to the new size. Note that we do an
// average just in case multiple models exists (rare but useful)
return indexSizingGroup.modelIndexes
.map { routingAllocation.findLargestShardSizeById(it.index, shardRouting.id) }
.average()
.toLong()
else ->
// this is a less ideal case where we see a new index with no good model to fall back on. We can still
// make an educated guess on the shard size by averaging the size of the shards in the models
return indexSizingGroup.modelIndexes
.flatMap { routingAllocation.routingTable().index(it.index).shards.values() }
.map { routingAllocation.findLargestShardSizeById(it.value.shardId().index, it.value.shardId.id) }
.average()
.toLong()
}
}
fun youngIndexes(metaData: MetaData) : RichIterable<String> =
buildIndexGroupMap(metaData)
.valuesView()
.toSet()
.flatCollect { it.youngIndexes }
.collect { it.index }
}
// considers both primaries and replicas in order to worst case scenario for shard size estimation
fun RoutingAllocation.findLargestShardSizeById(index: String, id: Int) : Long =
routingTable()
.index(index)
.shard(id)
.map { clusterInfo().getShardSize(it) ?: 0 }
.max() ?: 0
fun RoutingAllocation.findLargestReplicaSize(shardRouting: ShardRouting): Long =
findLargestShardSizeById(shardRouting.index(), shardRouting.id)
class IndexSizingGroup {
val modelIndexes: MutableList<IndexMetaData> = Lists.mutable.empty<IndexMetaData>()
val youngIndexes: MutableList<IndexMetaData> = Lists.mutable.empty<IndexMetaData>()
fun addModel(indexMetadata: IndexMetaData) {
modelIndexes.add(indexMetadata)
}
fun addYoungIndex(indexMetadata: IndexMetaData) {
youngIndexes.add(indexMetadata)
}
fun hasModelIndexes(): Boolean {
return modelIndexes.isNotEmpty()
}
fun isHomogeneous(): Boolean {
val allIndexes = allIndexes()
if (allIndexes.isEmpty) { return false; }
val value = allIndexes.first.numberOfShards
return allIndexes.all { it.numberOfShards == value }
}
fun allIndexes(): CompositeFastList<IndexMetaData> {
val allIndexes = CompositeFastList<IndexMetaData>()
allIndexes.addComposited(modelIndexes)
allIndexes.addComposited(youngIndexes)
return allIndexes
}
data class ShardSizeInfo(val actualSize: Long, val estimatedSize: Long)
} | src/main/java/com/simplymeasured/elasticsearch/plugins/tempest/balancer/ShardSizeCalculator.kt | 2467034806 |
package cf.reol.stingy.act.recycler.viewholder
import android.content.Context
import android.util.SparseArray
import android.view.View
import android.widget.TextView
import android.widget.Toast
import cf.reol.stingy.R
import cf.reol.stingy.act.recycler.item.MemoItem
import kotlinx.android.synthetic.main.rv_item_memo.*
/**
* Created by reol on 2017/8/30.
*/
class MemoViewHolder(itemView: View?, private val mContext: Context) : BaseViewHolder<MemoItem>(itemView) {
private val title: TextView = itemView!!.findViewById(R.id.rv_memo_title)
private val status: TextView = itemView!!.findViewById(R.id.rv_memo_status)
override fun bindViewData(data: MemoItem, position: Int) {
title.text = data.title
status.text = data.status
itemView.setOnClickListener{Toast.makeText(mContext,data.description,Toast.LENGTH_SHORT).show()}
}
} | app/src/main/java/cf/reol/stingy/act/recycler/viewholder/MemoViewHolder.kt | 3737307642 |
package io.ipoli.android.friends.usecase
import io.ipoli.android.achievement.Achievement
import io.ipoli.android.challenge.entity.Challenge
import io.ipoli.android.challenge.entity.SharingPreference
import io.ipoli.android.challenge.persistence.ChallengeRepository
import io.ipoli.android.common.UseCase
import io.ipoli.android.common.datetime.days
import io.ipoli.android.common.datetime.daysBetween
import io.ipoli.android.common.datetime.minutes
import io.ipoli.android.friends.feed.data.Post
import io.ipoli.android.friends.feed.persistence.ImageRepository
import io.ipoli.android.friends.feed.persistence.PostRepository
import io.ipoli.android.habit.data.Habit
import io.ipoli.android.player.data.Player
import io.ipoli.android.player.persistence.PlayerRepository
import io.ipoli.android.quest.Quest
import org.threeten.bp.LocalDate
/**
* Created by Venelin Valkov <[email protected]>
* on 07/16/2018.
*/
open class SavePostsUseCase(
private val postRepository: PostRepository,
private val playerRepository: PlayerRepository,
private val challengeRepository: ChallengeRepository,
private val imageRepository: ImageRepository
) : UseCase<SavePostsUseCase.Params, Unit> {
override fun execute(parameters: Params) {
val player = parameters.player ?: playerRepository.find()!!
if (!player.isLoggedIn()) {
return
}
val isAutoPostingEnabled = player.preferences.isAutoPostingEnabled
when (parameters) {
is Params.LevelUp -> {
if (isAutoPostingEnabled && parameters.newLevel % 5 == 0) {
postRepository.save(
Post(
playerId = player.id,
playerAvatar = player.avatar,
playerDisplayName = player.displayName ?: "Unknown Hero",
playerUsername = player.username!!,
playerLevel = parameters.newLevel,
data = Post.Data.LevelUp(parameters.newLevel),
description = null,
reactions = emptyList(),
comments = emptyList(),
status = Post.Status.APPROVED,
isFromCurrentPlayer = true
)
)
}
}
is Params.DailyChallengeComplete -> {
val stats = player.statistics
if (isAutoPostingEnabled && stats.dailyChallengeCompleteStreak.count > 1 && stats.dailyChallengeCompleteStreak.count % 5 == 0L) {
savePost(
player = player,
data = Post.Data.DailyChallengeCompleted(
streak = stats.dailyChallengeCompleteStreak.count.toInt(),
bestStreak = stats.dailyChallengeBestStreak.toInt()
)
)
}
}
is Params.AchievementUnlocked -> {
if (isAutoPostingEnabled && parameters.achievement.level > 1) {
savePost(
player = player,
data = Post.Data.AchievementUnlocked(parameters.achievement)
)
}
}
is Params.QuestComplete -> {
val quest = parameters.quest
savePost(
player = player,
data = if (quest.hasPomodoroTimer) {
Post.Data.QuestWithPomodoroShared(
quest.id,
quest.name,
quest.totalPomodoros!!
)
} else {
Post.Data.QuestShared(
quest.id,
quest.name,
if (quest.hasTimer) quest.actualDuration.asMinutes else 0.minutes
)
},
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
is Params.QuestFromChallengeComplete -> {
val q = parameters.quest
val challenge = parameters.challenge
savePost(
player = player,
data = if (q.hasPomodoroTimer) {
Post.Data.QuestWithPomodoroFromChallengeCompleted(
questId = q.id,
challengeId = challenge.id,
questName = q.name,
challengeName = challenge.name,
pomodoroCount = q.totalPomodoros!!
)
} else {
Post.Data.QuestFromChallengeCompleted(
questId = q.id,
challengeId = challenge.id,
questName = q.name,
challengeName = challenge.name,
durationTracked = if (q.hasTimer) q.actualDuration.asMinutes else 0.minutes
)
},
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
is Params.ChallengeShared -> {
val challenge = parameters.challenge
challengeRepository.save(challenge.copy(sharingPreference = SharingPreference.FRIENDS))
savePost(
player = player,
data = Post.Data.ChallengeShared(challenge.id, challenge.name),
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
is Params.ChallengeComplete -> {
val c = parameters.challenge
savePost(
player = player,
data = Post.Data.ChallengeCompleted(
c.id,
c.name,
c.startDate.daysBetween(c.completedAtDate!!).days
),
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
is Params.HabitCompleted -> {
val habit = parameters.habit
val challenge = parameters.challenge
savePost(
player = player,
data = Post.Data.HabitCompleted(
habitId = habit.id,
habitName = habit.name,
habitDate = LocalDate.now(),
challengeId = challenge?.id,
challengeName = challenge?.name,
isGood = habit.isGood,
streak = habit.streak.current,
bestStreak = habit.streak.best
),
imageUrl = saveImageIfAdded(parameters.imageData),
description = parameters.description
)
}
}
}
private fun saveImageIfAdded(imageData: ByteArray?) =
imageData?.let {
imageRepository.savePostImage(it)
}
private fun savePost(
player: Player,
data: Post.Data,
imageUrl: String? = null,
description: String? = null
) {
postRepository.save(
Post(
playerId = player.id,
playerAvatar = player.avatar,
playerDisplayName = player.displayName ?: "Unknown Hero",
playerUsername = player.username!!,
playerLevel = player.level,
data = data,
imageUrl = imageUrl,
description = description,
reactions = emptyList(),
comments = emptyList(),
status = imageUrl?.let { Post.Status.PENDING } ?: Post.Status.APPROVED,
isFromCurrentPlayer = true
)
)
}
sealed class Params {
abstract val player: Player?
data class LevelUp(val newLevel: Int, override val player: Player?) : Params()
data class DailyChallengeComplete(override val player: Player? = null) : Params()
data class AchievementUnlocked(val achievement: Achievement, override val player: Player?) :
Params()
data class QuestComplete(
val quest: Quest,
val description: String?,
val imageData: ByteArray?,
override val player: Player?
) : Params()
data class QuestFromChallengeComplete(
val quest: Quest,
val challenge: Challenge,
val description: String?,
val imageData: ByteArray?,
override val player: Player?
) : Params()
data class ChallengeShared(
val challenge: Challenge,
val description: String?,
val imageData: ByteArray?,
override val player: Player?
) : Params()
data class HabitCompleted(
val habit: Habit,
val challenge: Challenge?,
val description: String?,
val imageData: ByteArray?,
override val player: Player?
) : Params()
data class ChallengeComplete(
val challenge: Challenge,
val description: String?,
val imageData: ByteArray?,
override val player: Player? = null
) : Params()
}
} | app/src/main/java/io/ipoli/android/friends/usecase/SavePostsUseCase.kt | 3808459946 |
package com.eden.orchid.writersblocks.tags
import com.eden.orchid.impl.generators.HomepageGenerator
import com.eden.orchid.strikt.htmlBodyMatches
import com.eden.orchid.strikt.pageWasRendered
import com.eden.orchid.testhelpers.OrchidIntegrationTest
import com.eden.orchid.testhelpers.withGenerator
import com.eden.orchid.writersblocks.WritersBlocksModule
import kotlinx.html.div
import kotlinx.html.iframe
import kotlinx.html.style
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import strikt.api.expectThat
class YouTubeTagTest : OrchidIntegrationTest(
withGenerator<HomepageGenerator>(),
WritersBlocksModule()
) {
@Test
@DisplayName("Test basic YouTube tag as video embed")
fun test01() {
resource(
"homepage.md",
"""
|---
|---
|{% youtube id='IvUU8joBb1Q' %}
""".trimMargin()
)
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
iframe {
src = "https://www.youtube.com/embed/IvUU8joBb1Q"
width = "560"
height = "315"
attributes["frameborder"] = "0"
attributes["allow"] = "accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
attributes["allowfullscreen"] = ""
}
}
}
}
@Test
@DisplayName("Test YouTube tag as video embed")
fun test02() {
resource(
"homepage.md",
"""
|---
|---
|{% youtube id='IvUU8joBb1Q' aspectRatio='16:9' allow=['encrypted-media'] %}
""".trimMargin()
)
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
div {
style = "position:relative;padding-top:56.25%;"
iframe {
style = "position:absolute;top:0;left:0;width:100%;height:100%;"
src = "https://www.youtube.com/embed/IvUU8joBb1Q"
attributes["frameborder"] = "0"
attributes["allow"] = "encrypted-media"
attributes["allowfullscreen"] = ""
}
}
}
}
}
@Test
@DisplayName("Test YouTube tag as video embed")
fun test03() {
resource(
"homepage.md",
"""
|---
|---
|{% youtube id='IvUU8joBb1Q' aspectRatio='4:3' allow=['encrypted-media', 'gyroscope', 'picture-in-picture'] start='1:06' %}
""".trimMargin()
)
expectThat(execute())
.pageWasRendered("/index.html") {
htmlBodyMatches {
div {
style = "position:relative;padding-top:75.00%;"
iframe {
style = "position:absolute;top:0;left:0;width:100%;height:100%;"
src = "https://www.youtube.com/embed/IvUU8joBb1Q?start=66"
attributes["frameborder"] = "0"
attributes["allow"] = "encrypted-media; gyroscope; picture-in-picture"
attributes["allowfullscreen"] = ""
}
}
}
}
}
}
| languageExtensions/OrchidWritersBlocks/src/test/kotlin/com/eden/orchid/writersblocks/tags/YouTubeTagTest.kt | 2241956904 |
package net.tlalka.imager.view
import net.tlalka.imager.data.GeoImage
class ReportFacade(private val reports: List<ReportApi>) : ReportApi {
constructor(vararg reports: ReportApi) : this(reports.asList())
override fun header(header: String) {
reports.forEach { it.header(header) }
}
override fun write(image: GeoImage) {
reports.forEach { it.write(image) }
}
override fun footer() {
reports.forEach { it.footer() }
}
}
| src/main/kotlin/net/tlalka/imager/view/ReportFacade.kt | 1832956579 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.editorconfig.language.psi.base
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.icons.AllIcons
import com.intellij.ide.projectView.PresentationData
import com.intellij.lang.ASTNode
import org.editorconfig.language.filetype.EditorConfigFileConstants.ROOT_KEY
import org.editorconfig.language.filetype.EditorConfigFileConstants.ROOT_VALUE
import org.editorconfig.language.psi.EditorConfigRootDeclaration
import org.editorconfig.language.util.EditorConfigPsiTreeUtil.containsErrors
import org.editorconfig.language.util.EditorConfigTextMatchingUtil.textMatchesToIgnoreCase
abstract class EditorConfigRootDeclarationBase(node: ASTNode) : ASTWrapperPsiElement(node), EditorConfigRootDeclaration {
final override fun isValidRootDeclaration(): Boolean {
if (containsErrors(this)) return false
if (!textMatchesToIgnoreCase(rootDeclarationKey, ROOT_KEY)) return false
val value = rootDeclarationValueList.singleOrNull() ?: return false
return textMatchesToIgnoreCase(value, ROOT_VALUE)
}
private val declarationSite: String
get() {
return containingFile.virtualFile?.presentableName ?: return ""
}
final override fun getPresentation() = PresentationData(text, declarationSite, AllIcons.Nodes.HomeFolder, null)
final override fun getName(): String = rootDeclarationKey.text
}
| plugins/editorconfig/src/org/editorconfig/language/psi/base/EditorConfigRootDeclarationBase.kt | 2862625112 |
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.webSymbols.patterns
import com.intellij.util.containers.Stack
import com.intellij.webSymbols.*
import com.intellij.webSymbols.completion.WebSymbolCodeCompletionItem
import com.intellij.webSymbols.patterns.impl.*
import com.intellij.webSymbols.query.WebSymbolsCodeCompletionQueryParams
import com.intellij.webSymbols.query.WebSymbolsNameMatchQueryParams
abstract class WebSymbolsPattern {
internal abstract fun getStaticPrefixes(): Sequence<String>
internal open fun isStaticAndRequired(): Boolean = true
internal fun match(owner: WebSymbol?,
scope: Stack<WebSymbolsScope>,
name: String,
params: WebSymbolsNameMatchQueryParams): List<MatchResult> =
match(owner, scope, null, MatchParameters(name, params), 0, name.length)
.map { it.removeEmptySegments() }
internal fun getCompletionResults(owner: WebSymbol?,
scope: Stack<WebSymbolsScope>,
name: String,
params: WebSymbolsCodeCompletionQueryParams): List<WebSymbolCodeCompletionItem> =
getCompletionResults(owner, Stack(scope), null,
CompletionParameters(name, params), 0, name.length).items
internal abstract fun match(owner: WebSymbol?,
scopeStack: Stack<WebSymbolsScope>,
itemsProvider: WebSymbolsPatternItemsProvider?,
params: MatchParameters, start: Int, end: Int): List<MatchResult>
internal abstract fun getCompletionResults(owner: WebSymbol?,
scopeStack: Stack<WebSymbolsScope>,
itemsProvider: WebSymbolsPatternItemsProvider?,
params: CompletionParameters, start: Int, end: Int): CompletionResults
} | platform/webSymbols/src/com/intellij/webSymbols/patterns/WebSymbolsPattern.kt | 3494532561 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.