repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
rspieldenner/nebula-dependency-base-plugin | src/main/kotlin/com/netflix/nebula/dependencybase/internal/Recommendation.kt | 2 | 889 | /*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.nebula.dependencybase.internal
data class Recommendation(override val configuration: String, override val coordinate: String, val version: String, val source: String): Reason {
override fun getReason(): String {
return "recommend $version via $source"
}
}
| apache-2.0 |
pnemonic78/RemoveDuplicates | duplicates-android/app/src/main/java/com/github/duplicates/alarm/SamsungAlarmProvider.kt | 1 | 5808 | /*
* Copyright 2016, Moshe Waisberg
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.duplicates.alarm
import android.content.Context
import android.database.Cursor
import android.net.Uri
import android.provider.BaseColumns._ID
import com.github.duplicates.DaysOfWeek
import com.github.duplicates.DuplicateProvider
/**
* Provide duplicate messages for Samsung devices.
*
* @author moshe.w
*/
class SamsungAlarmProvider(context: Context) : DuplicateProvider<AlarmItem>(context) {
override fun getContentUri(): Uri? {
return Uri.parse("content://com.samsung.sec.android.clockpackage/alarm")
}
override fun getCursorProjection(): Array<String> {
return PROJECTION
}
override fun createItem(cursor: Cursor): AlarmItem {
return AlarmItem()
}
override fun populateItem(cursor: Cursor, item: AlarmItem) {
item.id = cursor.getLong(INDEX_ID)
item.activate = cursor.getInt(INDEX_ACTIVE)
item.soundTone = cursor.getInt(INDEX_ALARMSOUND)
item.alarmTime = cursor.getInt(INDEX_ALARMTIME)
item.soundTone = cursor.getInt(INDEX_ALARMTONE)
item.soundUri = cursor.getString(INDEX_ALARMURI)
item.alertTime = cursor.getLong(INDEX_ALERTTIME)
item.createTime = cursor.getLong(INDEX_CREATETIME)
item.isDailyBriefing = cursor.getInt(INDEX_DAILYBRIEF) != 0
item.name = empty(cursor, INDEX_NAME)
item.notificationType = cursor.getInt(INDEX_NOTITYPE)
item.repeat = toDaysOfWeek(cursor.getInt(INDEX_REPEATTYPE))
item.isSubdueActivate = cursor.getInt(INDEX_SBDACTIVE) != 0
item.subdueDuration = cursor.getInt(INDEX_SBDDURATION)
item.subdueTone = cursor.getInt(INDEX_SBDTONE)
item.subdueUri = cursor.getInt(INDEX_SBDURI)
item.isSnoozeActivate = cursor.getInt(INDEX_SNZACTIVE) != 0
item.snoozeDoneCount = cursor.getInt(INDEX_SNZCOUNT)
item.snoozeDuration = cursor.getInt(INDEX_SNZDURATION)
item.snoozeRepeat = cursor.getInt(INDEX_SNZREPEAT)
item.volume = cursor.getInt(INDEX_VOLUME)
}
override fun getReadPermissions(): Array<String> {
return PERMISSIONS_READ
}
override fun getDeletePermissions(): Array<String> {
return PERMISSIONS_WRITE
}
protected fun toDaysOfWeek(repeat: Int): DaysOfWeek? {
if (repeat and REPEAT_WEEKLY != REPEAT_WEEKLY) {
return null
}
val daysOfWeek = DaysOfWeek(0)
daysOfWeek.set(0, repeat and DAY_SUNDAY == DAY_SUNDAY)
daysOfWeek.set(1, repeat and DAY_MONDAY == DAY_MONDAY)
daysOfWeek.set(2, repeat and DAY_TUESDAY == DAY_TUESDAY)
daysOfWeek.set(3, repeat and DAY_WEDNESDAY == DAY_WEDNESDAY)
daysOfWeek.set(4, repeat and DAY_THURSDAY == DAY_THURSDAY)
daysOfWeek.set(5, repeat and DAY_FRIDAY == DAY_FRIDAY)
daysOfWeek.set(6, repeat and DAY_SATURDAY == DAY_SATURDAY)
return daysOfWeek
}
companion object {
const val PACKAGE = "com.sec.android.app.clockpackage"
private val PERMISSIONS_READ =
arrayOf("com.sec.android.app.clockpackage.permission.READ_ALARM")
private val PERMISSIONS_WRITE =
arrayOf("com.sec.android.app.clockpackage.permission.WRITE_ALARM")
private val PROJECTION = arrayOf(
_ID,
"active",
"createtime",
"alerttime",
"alarmtime",
"repeattype",
"notitype",
"snzactive",
"snzduration",
"snzrepeat",
"snzcount",
"dailybrief",
"sbdactive",
"sbdduration",
"sbdtone",
"alarmsound",
"alarmtone",
"volume",
"sbduri",
"alarmuri",
"name"
)
private const val INDEX_ID = 0
private const val INDEX_ACTIVE = 1
private const val INDEX_CREATETIME = 2
private const val INDEX_ALERTTIME = 3
private const val INDEX_ALARMTIME = 4
private const val INDEX_REPEATTYPE = 5
private const val INDEX_NOTITYPE = 6
private const val INDEX_SNZACTIVE = 7
private const val INDEX_SNZDURATION = 8
private const val INDEX_SNZREPEAT = 9
private const val INDEX_SNZCOUNT = 10
private const val INDEX_DAILYBRIEF = 11
private const val INDEX_SBDACTIVE = 12
private const val INDEX_SBDDURATION = 13
private const val INDEX_SBDTONE = 14
private const val INDEX_ALARMSOUND = 15
private const val INDEX_ALARMTONE = 16
private const val INDEX_VOLUME = 17
private const val INDEX_SBDURI = 18
private const val INDEX_ALARMURI = 19
private const val INDEX_NAME = 20
private const val REPEAT_WEEKLY = 0x00000005
private const val REPEAT_TOMORROW = 0x00000001
private const val DAY_SUNDAY = 0x10000000
private const val DAY_MONDAY = 0x01000000
private const val DAY_TUESDAY = 0x00100000
private const val DAY_WEDNESDAY = 0x00010000
private const val DAY_THURSDAY = 0x00001000
private const val DAY_FRIDAY = 0x00000100
private const val DAY_SATURDAY = 0x10000010
}
}
| apache-2.0 |
http4k/http4k | http4k-security/oauth/src/main/kotlin/org/http4k/security/oauth/server/TokenRequest.kt | 1 | 485 | package org.http4k.security.oauth.server
import org.http4k.core.Uri
import org.http4k.security.oauth.core.RefreshToken
import org.http4k.security.oauth.server.accesstoken.GrantType
data class TokenRequest(
val grantType: GrantType,
val clientId: ClientId?,
val clientSecret: String?,
val code: String?,
val redirectUri: Uri?,
val scopes: List<String>,
val clientAssertionType: Uri?,
val clientAssertion: String?,
val refreshToken: RefreshToken?
)
| apache-2.0 |
GrandPanda/kommands | src/main/kotlin/com/darichey/discord/kommands/limiters/PermissionsLimiter.kt | 1 | 570 | package com.darichey.discord.kommands.limiters
import com.darichey.discord.kommands.CommandFunction
import com.darichey.discord.kommands.Limiter
import sx.blah.discord.handle.obj.Permissions
import java.util.*
/**
* A [Limiter] limiting the use of a command to certain [Permissions].
* Will pass a command executed by a user with **ANY** of the given permissions. (Not with all)
*/
class PermissionsLimiter(permissions: EnumSet<Permissions>, onFail: CommandFunction = {}):
Limiter({ author.getPermissionsForGuild(guild).any { permissions.contains(it) } }, onFail) | gpl-3.0 |
square/duktape-android | zipline/src/engineTest/kotlin/app/cash/zipline/QuickJsInterruptTest.kt | 1 | 3366 | /*
* Copyright (C) 2021 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.cash.zipline
import kotlin.test.AfterTest
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
class QuickJsInterruptTest {
private val quickJs = QuickJs.create()
@BeforeTest fun setUp() {
quickJs.evaluate("""
|var fib = function(a) {
| if (a < 2) return 1;
| return fib(a - 1) + fib(a - 2);
|}
""".trimMargin())
// Set a huge max stack because of the heavy recursion of fib().
quickJs.maxStackSize *= 5
}
@AfterTest fun tearDown() {
quickJs.close()
}
@Test fun interruptedAfterEnoughComputations() {
val counter = InterruptCounter()
quickJs.interruptHandler = counter
// Discovered experimentally, fib(17) does enough computations trigger exactly 1 interruption.
// This program completes in ~1 ms on a 2.4 GHz Intel i9 MacBook Pro.
val result = quickJs.evaluate("""fib(17)""")
assertEquals(1, counter.count)
assertEquals(2584, result)
}
@Test fun multipleInterruptions() {
val counter = InterruptCounter()
quickJs.interruptHandler = counter
// Discovered experimentally, fib(20) does enough computations trigger exactly 4 interruptions.
// This program completes in ~5 ms on a 2.4 GHz Intel i9 MacBook Pro.
val result = quickJs.evaluate("""fib(20)""")
assertEquals(4, counter.count)
assertEquals(10946, result)
}
@Test fun interruptionReturnsTrueToTerminateWork() {
quickJs.interruptHandler = object : InterruptHandler {
override fun poll(): Boolean {
return true
}
}
assertEquals("interrupted", assertFailsWith<QuickJsException> {
quickJs.evaluate("""fib(20)""")
}.message)
}
@Test fun removeInterruptHandler() {
val counter = InterruptCounter()
quickJs.interruptHandler = counter
assertEquals(10946, quickJs.evaluate("""fib(20)"""))
assertEquals(4, counter.count)
quickJs.interruptHandler = null
assertEquals(10946, quickJs.evaluate("""fib(20)"""))
assertEquals(4, counter.count) // Still 4.
}
/**
* It's possible an interrupt handler may run JavaScript to query global state before returning.
* Confirm that such work can't itself be interrupted.
*/
@Test fun interruptionAreNotReentrant() {
var count = 0
quickJs.interruptHandler = object : InterruptHandler {
override fun poll(): Boolean {
count++
assertEquals(10946, quickJs.evaluate("""fib(20)"""))
return false
}
}
assertEquals(2584, quickJs.evaluate("""fib(17)"""))
assertEquals(1, count)
}
class InterruptCounter : InterruptHandler {
var count = 0
override fun poll(): Boolean {
count++
return false
}
}
}
| apache-2.0 |
TangHao1987/intellij-community | platform/configuration-store-impl/testSrc/DefaultProjectStoreTest.kt | 4 | 2513 | package com.intellij.configurationStore
import com.intellij.externalDependencies.DependencyOnPlugin
import com.intellij.externalDependencies.ExternalDependenciesManager
import com.intellij.externalDependencies.ProjectExternalDependency
import com.intellij.openapi.application.ex.ApplicationManagerEx
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.service
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.util.io.FileUtil
import com.intellij.testFramework.ProjectRule
import com.intellij.testFramework.RuleChain
import com.intellij.testFramework.TemporaryDirectory
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExternalResource
import java.io.File
class DefaultProjectStoreTest {
companion object {
ClassRule val projectRule = ProjectRule()
}
private val tempDirManager = TemporaryDirectory()
private val requiredPlugins: List<ProjectExternalDependency> = listOf(DependencyOnPlugin("fake", "0", "1"))
private val ruleChain = RuleChain(
tempDirManager,
object : ExternalResource() {
private var isDoNotSave = false
override fun before() {
val app = ApplicationManagerEx.getApplicationEx()
isDoNotSave = app.isDoNotSave()
app.doNotSave(false)
}
override fun after() {
val app = ApplicationManagerEx.getApplicationEx()
try {
app.doNotSave(isDoNotSave)
}
finally {
FileUtil.delete(File(app.stateStore.getStateStorageManager().expandMacros(StoragePathMacros.APP_CONFIG)))
}
}
},
object : ExternalResource() {
private var externalDependenciesManager: ExternalDependenciesManager? = null
override fun before() {
externalDependenciesManager = ProjectManager.getInstance().getDefaultProject().service<ExternalDependenciesManager>()
externalDependenciesManager!!.setAllDependencies(requiredPlugins)
}
override fun after() {
externalDependenciesManager?.setAllDependencies(emptyList())
}
}
)
public Rule fun getChain(): RuleChain = ruleChain
public Test fun `new project from default`() {
createProject(tempDirManager) {
assertThat(it.service<ExternalDependenciesManager>().getAllDependencies(), equalTo(requiredPlugins))
}
}
} | apache-2.0 |
rock3r/detekt | detekt-cli/src/test/kotlin/io/gitlab/arturbosch/detekt/cli/ExtensionsSpec.kt | 1 | 1278 | package io.gitlab.arturbosch.detekt.cli
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.SetupContext
import io.gitlab.arturbosch.detekt.api.UnstableApi
import io.gitlab.arturbosch.detekt.rules.documentation.LicenceHeaderLoaderExtension
import io.gitlab.arturbosch.detekt.test.NullPrintStream
import org.assertj.core.api.Assertions.assertThatCode
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.io.PrintStream
import java.net.URI
@UnstableApi
class ExtensionsSpec : Spek({
describe("Licence header extension - #2503") {
it("should not crash when using resources") {
assertThatCode {
val uris = CliArgs {
configResource = "extensions/config.yml"
}.extractUris()
LicenceHeaderLoaderExtension().init(object : SetupContext {
override val configUris: Collection<URI> = uris
override val config: Config = Config.empty
override val outPrinter: PrintStream = NullPrintStream()
override val errPrinter: PrintStream = NullPrintStream()
})
}.doesNotThrowAnyException()
}
}
})
| apache-2.0 |
ankidroid/Anki-Android | AnkiDroid/src/main/java/com/wildplot/android/parsing/Term.kt | 1 | 4837 | /****************************************************************************************
* Copyright (c) 2014 Michael Goldbach <[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.wildplot.android.parsing
class Term(termString: String, private val parser: TopLevelParser) : TreeElement {
enum class TermType {
TERM_MUL_FACTOR, TERM_DIV_FACTOR, FACTOR, INVALID
}
var termType = TermType.INVALID
private set
private var factor: Factor? = null
private var term: Term? = null
private fun initAsTermMulOrDivFactor(termString: String): Boolean {
var bracketChecker = 0
for (i in 0 until termString.length) {
if (termString[i] == '(') {
bracketChecker++
}
if (termString[i] == ')') {
bracketChecker--
}
if ((termString[i] == '*' || termString[i] == '/') && bracketChecker == 0) {
val leftSubString = termString.substring(0, i)
if (!TopLevelParser.stringHasValidBrackets(leftSubString)) {
continue
}
val leftTerm = Term(leftSubString, parser)
val isValidFirstPartTerm = leftTerm.termType != TermType.INVALID
if (!isValidFirstPartTerm) {
continue
}
val rightSubString = termString.substring(i + 1)
if (!TopLevelParser.stringHasValidBrackets(rightSubString)) {
continue
}
val rightFactor = Factor(rightSubString, parser)
val isValidSecondPartFactor = rightFactor.factorType != Factor.FactorType.INVALID
if (isValidSecondPartFactor) {
if (termString[i] == '*') {
termType = TermType.TERM_MUL_FACTOR
} else {
termType = TermType.TERM_DIV_FACTOR
}
term = leftTerm
factor = rightFactor
return true
}
}
}
return false
}
private fun initAsFactor(termString: String): Boolean {
val factor = Factor(termString, parser)
val isValidTerm = factor.factorType != Factor.FactorType.INVALID
if (isValidTerm) {
termType = TermType.FACTOR
this.factor = factor
return true
}
return false
}
@get:Throws(ExpressionFormatException::class)
override val value: Double
get() = when (termType) {
TermType.TERM_MUL_FACTOR -> term!!.value * factor!!.value
TermType.TERM_DIV_FACTOR -> term!!.value / factor!!.value
TermType.FACTOR -> factor!!.value
TermType.INVALID -> throw ExpressionFormatException("could not parse Term")
}
@get:Throws(ExpressionFormatException::class)
override val isVariable: Boolean
get() = when (termType) {
TermType.TERM_MUL_FACTOR, TermType.TERM_DIV_FACTOR -> term!!.isVariable || factor!!.isVariable
TermType.FACTOR -> factor!!.isVariable
TermType.INVALID -> throw ExpressionFormatException("could not parse Term")
}
init {
if (!TopLevelParser.stringHasValidBrackets(termString)) {
termType = TermType.INVALID
} else {
var isReady = initAsTermMulOrDivFactor(termString)
if (!isReady) {
isReady = initAsFactor(termString)
}
if (!isReady) {
termType = TermType.INVALID
}
}
}
}
| gpl-3.0 |
infinum/android_dbinspector | dbinspector/src/test/kotlin/com/infinum/dbinspector/domain/connection/ConnectionRepositoryTest.kt | 1 | 2311 | package com.infinum.dbinspector.domain.connection
import com.infinum.dbinspector.domain.Control
import com.infinum.dbinspector.domain.Interactors
import com.infinum.dbinspector.shared.BaseTest
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.mockk
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
import org.koin.core.module.Module
import org.koin.dsl.module
import org.koin.test.get
import org.mockito.kotlin.any
@DisplayName("ConnectionRepository tests")
internal class ConnectionRepositoryTest : BaseTest() {
override fun modules(): List<Module> = listOf(
module {
factory { mockk<Interactors.OpenConnection>() }
factory { mockk<Interactors.CloseConnection>() }
factory { mockk<Control.Connection>() }
}
)
@Test
fun `Connection repository open calls open interactor`() {
val interactor: Interactors.OpenConnection = get()
val control: Control.Connection = get()
val repository = ConnectionRepository(
interactor,
get(),
control
)
coEvery { interactor.invoke(any()) } returns mockk()
coEvery { control.mapper.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns ""
test {
repository.open(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 1) { control.mapper.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
}
@Test
fun `Connection repository close calls close interactor`() {
val interactor: Interactors.CloseConnection = get()
val control: Control.Connection = get()
val repository = ConnectionRepository(
get(),
interactor,
control
)
coEvery { interactor.invoke(any()) } returns Unit
coEvery { control.mapper.invoke(any()) } returns mockk()
coEvery { control.converter.invoke(any()) } returns ""
test {
repository.close(any())
}
coVerify(exactly = 1) { interactor.invoke(any()) }
coVerify(exactly = 0) { control.mapper.invoke(any()) }
coVerify(exactly = 1) { control.converter.invoke(any()) }
}
}
| apache-2.0 |
matkoniecz/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/quests/surface/DescribeGenericSurfaceDialog.kt | 1 | 1449 | package de.westnordost.streetcomplete.quests.surface
import android.content.Context
import android.content.DialogInterface
import android.view.LayoutInflater
import androidx.appcompat.app.AlertDialog
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.databinding.QuestSurfaceDetailedAnswerImpossibleBinding
class DescribeGenericSurfaceDialog(
context: Context,
onSurfaceDescribed: (txt: String) -> Unit
) : AlertDialog(context, R.style.Theme_Bubble_Dialog) {
init {
val binding = QuestSurfaceDetailedAnswerImpossibleBinding.inflate(LayoutInflater.from(context))
setTitle(context.resources.getString(R.string.quest_surface_detailed_answer_impossible_title))
setButton(DialogInterface.BUTTON_POSITIVE, context.getString(android.R.string.yes)) { _, _ ->
val txt = binding.explanationInput.text.toString().trim()
if (txt.isEmpty()) {
Builder(context)
.setMessage(R.string.quest_surface_detailed_answer_impossible_description)
.setPositiveButton(android.R.string.ok, null)
.show()
} else {
onSurfaceDescribed(txt)
}
}
setButton(
DialogInterface.BUTTON_NEGATIVE,
context.getString(android.R.string.cancel),
null as DialogInterface.OnClickListener?
)
setView(binding.root)
}
}
| gpl-3.0 |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/diagram/DiagramPath.kt | 1 | 2558 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.diagram
/**
* An abstraction for paths that can be drawn on a [Canvas].
*
* @author Paul de Vrieze
* @param <PATH_T> The type of path. This normally is the type itself.
</PATH_T> */
interface DiagramPath<PATH_T : DiagramPath<PATH_T>> {
/**
* Move to a new point. This will create a new sub-path.
*
* @param x The new X coordinate.
* @param y The new Y coordinate
* @return The path itself, to allow for method chaining.
*/
fun moveTo(x: Double, y: Double): PATH_T
/**
* Draw a line from the current point to a new point.
*
* @param x The new X coordinate.
* @param y The new Y coordinate
* @return The path itself, to allow for method chaining.
*/
fun lineTo(x: Double, y: Double): PATH_T
/**
* Draw a cubic bezier spline from the current point to a new point.
*
* @param x1 The first control point's x coordinate
* @param y1 The first control point's y coordinate.
* @param x2 The second control point's x coordinate
* @param y2 The second control point's y coordinate.
* @param x3 The endpoint's x coordinate
* @param y3 The endpoint's y coordinate.
* @return The path itself, to allow for method chaining.
*/
fun cubicTo(x1: Double, y1: Double, x2: Double, y2: Double, x3: Double, y3: Double): PATH_T
/**
* Close the current sub-path by drawing a straight line back to the
* beginning.
*
* @return The path itself, to allow for method chaining.
*/
fun close(): PATH_T
/**
* Get the bounds of the path
* @param dest The rectangle to store the bounds in (existing content is discarded)
* @param stroke The pen that represents the stroke to use.
* @return The bounds of the path
*/
fun getBounds(dest: Rectangle, stroke: Pen<*>?): Rectangle
}
| lgpl-3.0 |
googlecodelabs/android-dagger | app/src/sharedTest/java/com/example/android/dagger/LiveDataTestUtil.kt | 2 | 1520 | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.dagger
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
object LiveDataTestUtil {
/**
* Get the value from a LiveData object. We're waiting for LiveData to emit, for 2 seconds.
* Once we got a notification via onChanged, we stop observing.
*/
fun <T> getValue(liveData: LiveData<T>): T {
val data = arrayOfNulls<Any>(1)
val latch = CountDownLatch(1)
val observer = object : Observer<T> {
override fun onChanged(o: T?) {
data[0] = o
latch.countDown()
liveData.removeObserver(this)
}
}
liveData.observeForever(observer)
latch.await(2, TimeUnit.SECONDS)
@Suppress("UNCHECKED_CAST")
return data[0] as T
}
}
| apache-2.0 |
pdvrieze/ProcessManager | ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/test/loanOrigination/datatypes/LoanCustomer.kt | 1 | 924 | /*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.test.loanOrigination.datatypes
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
@SerialName("loanCustomer")
data class LoanCustomer(val customerId: String)
| lgpl-3.0 |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/GeekListActivity.kt | 1 | 4335 | package com.boardgamegeek.ui
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.MenuItem
import androidx.activity.viewModels
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.boardgamegeek.R
import com.boardgamegeek.entities.Status
import com.boardgamegeek.extensions.*
import com.boardgamegeek.provider.BggContract
import com.boardgamegeek.ui.viewmodel.GeekListViewModel
import com.google.firebase.analytics.FirebaseAnalytics
import com.google.firebase.analytics.ktx.logEvent
class GeekListActivity : TabActivity() {
private var geekListId = BggContract.INVALID_ID
private var geekListTitle: String = ""
private val viewModel by viewModels<GeekListViewModel>()
private val adapter: GeekListPagerAdapter by lazy { GeekListPagerAdapter(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
geekListId = intent.getIntExtra(KEY_ID, BggContract.INVALID_ID)
geekListTitle = intent.getStringExtra(KEY_TITLE).orEmpty()
safelySetTitle(geekListTitle)
if (savedInstanceState == null) {
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.VIEW_ITEM) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "GeekList")
param(FirebaseAnalytics.Param.ITEM_ID, geekListId.toString())
param(FirebaseAnalytics.Param.ITEM_NAME, geekListTitle)
}
}
viewModel.setId(geekListId)
viewModel.geekList.observe(this) {
it?.let { (status, data, _) ->
if (status == Status.SUCCESS && data != null) {
geekListTitle = data.title
safelySetTitle(geekListTitle)
}
}
}
}
override val optionsMenuId = R.menu.view_share
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_view -> linkToBgg("geeklist", geekListId)
R.id.menu_share -> {
val description = String.format(getString(R.string.share_geeklist_text), geekListTitle)
val uri = createBggUri("geeklist", geekListId)
share(getString(R.string.share_geeklist_subject), "$description\n\n$uri")
firebaseAnalytics.logEvent(FirebaseAnalytics.Event.SHARE) {
param(FirebaseAnalytics.Param.CONTENT_TYPE, "GeekList")
param(FirebaseAnalytics.Param.ITEM_ID, geekListId.toString())
param(FirebaseAnalytics.Param.ITEM_ID, geekListTitle)
}
}
else -> super.onOptionsItemSelected(item)
}
return true
}
override fun createAdapter(): FragmentStateAdapter {
return adapter
}
override fun getPageTitle(position: Int): CharSequence {
return when (position) {
0 -> getString(R.string.title_description)
1 -> getString(R.string.title_items)
2 -> getString(R.string.title_comments)
else -> ""
}
}
private class GeekListPagerAdapter(activity: FragmentActivity) :
FragmentStateAdapter(activity) {
override fun createFragment(position: Int): Fragment {
return when (position) {
0 -> GeekListDescriptionFragment()
1 -> GeekListItemsFragment()
2 -> GeekListCommentsFragment()
else -> ErrorFragment()
}
}
override fun getItemCount() = 3
}
companion object {
private const val KEY_ID = "GEEK_LIST_ID"
private const val KEY_TITLE = "GEEK_LIST_TITLE"
fun start(context: Context, id: Int, title: String) {
context.startActivity(createIntent(context, id, title))
}
fun startUp(context: Context, id: Int, title: String) {
context.startActivity(createIntent(context, id, title).clearTop())
}
private fun createIntent(context: Context, id: Int, title: String): Intent {
return context.intentFor<GeekListActivity>(
KEY_ID to id,
KEY_TITLE to title,
)
}
}
}
| gpl-3.0 |
songzhw/Hello-kotlin | AdvancedJ/src/main/kotlin/algorithm/strings/Palindrome回文.kt | 1 | 418 | package algorithm.strings
fun palindrome(str: String): Boolean {
val len = str.length
for (i in 0 until len) { //[0, len) || for (i in 0..len)则是[0, len]
if (str[i] != str[len - 1 - i]) {
return false
}
}
return true
}
fun main() {
println(palindrome("madam"))
println(palindrome("test"))
println(palindrome("我爱我"))
println(palindrome("woow"))
} | apache-2.0 |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/api/util/option/Option.kt | 1 | 1464 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
@file:Suppress("UNCHECKED_CAST")
package org.lanternpowered.api.util.option
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.api.util.type.TypeToken
import kotlin.reflect.KClass
/**
* Represents a option.
*
* @constructor Constructs and registers a new [Option]
* @property defaultValue The default option value
* @property type The type of option value
* @param T The option map type this option targets
* @param V The value type of this option
*/
data class Option<T : OptionMapType, V>(
val key: NamespacedKey,
val type: TypeToken<V>,
val defaultValue: V,
val mapType: Class<T>
) {
constructor(key: NamespacedKey, type: TypeToken<V>, defaultValue: V, mapType: KClass<T>) :
this(key, type, defaultValue, mapType.java)
init {
val registry = OptionMapRegistry.of(this.mapType)
// Each key per map type should be unique
check(this.key !in registry) {
"There is already a option with id '$key' registered for map type '${mapType.name}'." }
// Register the key
registry.byKey[this.key] = this
}
}
| mit |
world-federation-of-advertisers/cross-media-measurement | src/test/kotlin/org/wfanet/measurement/kingdom/service/api/v2alpha/EventGroupsServiceTest.kt | 1 | 33569 | // Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.service.api.v2alpha
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.extensions.proto.ProtoTruth.assertThat
import com.google.protobuf.ByteString
import com.google.protobuf.Timestamp
import io.grpc.Status
import io.grpc.StatusRuntimeException
import java.time.Instant
import kotlin.test.assertFailsWith
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.kotlin.any
import org.mockito.kotlin.verify
import org.wfanet.measurement.api.Version
import org.wfanet.measurement.api.v2.alpha.ListEventGroupsPageTokenKt.previousPageEnd
import org.wfanet.measurement.api.v2.alpha.listEventGroupsPageToken
import org.wfanet.measurement.api.v2alpha.DataProviderKey
import org.wfanet.measurement.api.v2alpha.EventGroup
import org.wfanet.measurement.api.v2alpha.EventGroupKey
import org.wfanet.measurement.api.v2alpha.EventGroupKt
import org.wfanet.measurement.api.v2alpha.ListEventGroupsRequest
import org.wfanet.measurement.api.v2alpha.ListEventGroupsRequestKt.filter
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerCertificateKey
import org.wfanet.measurement.api.v2alpha.MeasurementConsumerKey
import org.wfanet.measurement.api.v2alpha.copy
import org.wfanet.measurement.api.v2alpha.createEventGroupRequest
import org.wfanet.measurement.api.v2alpha.eventGroup
import org.wfanet.measurement.api.v2alpha.getEventGroupRequest
import org.wfanet.measurement.api.v2alpha.listEventGroupsRequest
import org.wfanet.measurement.api.v2alpha.listEventGroupsResponse
import org.wfanet.measurement.api.v2alpha.signedData
import org.wfanet.measurement.api.v2alpha.testing.makeDataProvider
import org.wfanet.measurement.api.v2alpha.updateEventGroupRequest
import org.wfanet.measurement.api.v2alpha.withDataProviderPrincipal
import org.wfanet.measurement.api.v2alpha.withMeasurementConsumerPrincipal
import org.wfanet.measurement.api.v2alpha.withModelProviderPrincipal
import org.wfanet.measurement.common.base64UrlEncode
import org.wfanet.measurement.common.grpc.testing.GrpcTestServerRule
import org.wfanet.measurement.common.grpc.testing.mockService
import org.wfanet.measurement.common.identity.apiIdToExternalId
import org.wfanet.measurement.common.testing.captureFirst
import org.wfanet.measurement.common.testing.verifyProtoArgument
import org.wfanet.measurement.common.toProtoTime
import org.wfanet.measurement.internal.kingdom.EventGroup as InternalEventGroup
import org.wfanet.measurement.internal.kingdom.EventGroupKt as internalEventGroupKt
import org.wfanet.measurement.internal.kingdom.EventGroupKt.details
import org.wfanet.measurement.internal.kingdom.EventGroupsGrpcKt.EventGroupsCoroutineImplBase
import org.wfanet.measurement.internal.kingdom.EventGroupsGrpcKt.EventGroupsCoroutineStub
import org.wfanet.measurement.internal.kingdom.StreamEventGroupsRequest
import org.wfanet.measurement.internal.kingdom.StreamEventGroupsRequestKt
import org.wfanet.measurement.internal.kingdom.copy
import org.wfanet.measurement.internal.kingdom.eventGroup as internalEventGroup
import org.wfanet.measurement.internal.kingdom.getEventGroupRequest as internalGetEventGroupRequest
import org.wfanet.measurement.internal.kingdom.streamEventGroupsRequest
private val CREATE_TIME: Timestamp = Instant.ofEpochSecond(123).toProtoTime()
private const val DEFAULT_LIMIT = 50
private const val WILDCARD_NAME = "dataProviders/-"
private val DATA_PROVIDER_NAME = makeDataProvider(123L)
private val DATA_PROVIDER_NAME_2 = makeDataProvider(124L)
private val DATA_PROVIDER_EXTERNAL_ID =
apiIdToExternalId(DataProviderKey.fromName(DATA_PROVIDER_NAME)!!.dataProviderId)
private const val MODEL_PROVIDER_NAME = "modelProviders/AAAAAAAAAHs"
private val EVENT_GROUP_NAME = "$DATA_PROVIDER_NAME/eventGroups/AAAAAAAAAHs"
private val EVENT_GROUP_NAME_2 = "$DATA_PROVIDER_NAME/eventGroups/AAAAAAAAAJs"
private val EVENT_GROUP_NAME_3 = "$DATA_PROVIDER_NAME/eventGroups/AAAAAAAAAKs"
private const val MEASUREMENT_CONSUMER_NAME = "measurementConsumers/AAAAAAAAAHs"
private const val MEASUREMENT_CONSUMER_NAME_2 = "measurementConsumers/BBBBBBBBBHs"
private const val MEASUREMENT_CONSUMER_CERTIFICATE_NAME =
"$MEASUREMENT_CONSUMER_NAME/certificates/AAAAAAAAAcg"
private val ENCRYPTED_METADATA = ByteString.copyFromUtf8("encryptedMetadata")
private val API_VERSION = Version.V2_ALPHA
private val EVENT_GROUP_EXTERNAL_ID =
apiIdToExternalId(EventGroupKey.fromName(EVENT_GROUP_NAME)!!.eventGroupId)
private val EVENT_GROUP_EXTERNAL_ID_2 =
apiIdToExternalId(EventGroupKey.fromName(EVENT_GROUP_NAME_2)!!.eventGroupId)
private val EVENT_GROUP_EXTERNAL_ID_3 =
apiIdToExternalId(EventGroupKey.fromName(EVENT_GROUP_NAME_3)!!.eventGroupId)
private val MEASUREMENT_CONSUMER_EXTERNAL_ID =
apiIdToExternalId(
MeasurementConsumerKey.fromName(MEASUREMENT_CONSUMER_NAME)!!.measurementConsumerId
)
private val MEASUREMENT_CONSUMER_PUBLIC_KEY_DATA = ByteString.copyFromUtf8("foodata")
private val MEASUREMENT_CONSUMER_PUBLIC_KEY_SIGNATURE = ByteString.copyFromUtf8("foosig")
private val VID_MODEL_LINES = listOf("model1", "model2")
private val EVENT_TEMPLATE_TYPES = listOf("type1", "type2")
private val EVENT_TEMPLATES =
EVENT_TEMPLATE_TYPES.map { type -> EventGroupKt.eventTemplate { this.type = type } }
private val INTERNAL_EVENT_TEMPLATES =
EVENT_TEMPLATE_TYPES.map { type ->
internalEventGroupKt.eventTemplate { fullyQualifiedType = type }
}
private val EVENT_GROUP: EventGroup = eventGroup {
name = EVENT_GROUP_NAME
measurementConsumer = MEASUREMENT_CONSUMER_NAME
measurementConsumerCertificate = MEASUREMENT_CONSUMER_CERTIFICATE_NAME
eventGroupReferenceId = "aaa"
measurementConsumerPublicKey = signedData {
data = MEASUREMENT_CONSUMER_PUBLIC_KEY_DATA
signature = MEASUREMENT_CONSUMER_PUBLIC_KEY_SIGNATURE
}
vidModelLines.addAll(VID_MODEL_LINES)
eventTemplates.addAll(EVENT_TEMPLATES)
encryptedMetadata = ENCRYPTED_METADATA
}
private val INTERNAL_EVENT_GROUP: InternalEventGroup = internalEventGroup {
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID
externalMeasurementConsumerId = MEASUREMENT_CONSUMER_EXTERNAL_ID
externalMeasurementConsumerCertificateId =
apiIdToExternalId(
MeasurementConsumerCertificateKey.fromName(MEASUREMENT_CONSUMER_CERTIFICATE_NAME)!!
.certificateId
)
providedEventGroupId = EVENT_GROUP.eventGroupReferenceId
createTime = CREATE_TIME
details = details {
apiVersion = API_VERSION.string
measurementConsumerPublicKey = MEASUREMENT_CONSUMER_PUBLIC_KEY_DATA
measurementConsumerPublicKeySignature = MEASUREMENT_CONSUMER_PUBLIC_KEY_SIGNATURE
vidModelLines.addAll(VID_MODEL_LINES)
eventTemplates.addAll(INTERNAL_EVENT_TEMPLATES)
encryptedMetadata = ENCRYPTED_METADATA
}
}
@RunWith(JUnit4::class)
class EventGroupsServiceTest {
private val internalEventGroupsMock: EventGroupsCoroutineImplBase =
mockService() {
onBlocking { getEventGroup(any()) }.thenReturn(INTERNAL_EVENT_GROUP)
onBlocking { createEventGroup(any()) }.thenReturn(INTERNAL_EVENT_GROUP)
onBlocking { updateEventGroup(any()) }.thenReturn(INTERNAL_EVENT_GROUP)
onBlocking { streamEventGroups(any()) }
.thenReturn(
flowOf(
INTERNAL_EVENT_GROUP,
INTERNAL_EVENT_GROUP.copy { externalEventGroupId = EVENT_GROUP_EXTERNAL_ID_2 },
INTERNAL_EVENT_GROUP.copy { externalEventGroupId = EVENT_GROUP_EXTERNAL_ID_3 }
)
)
}
@get:Rule val grpcTestServerRule = GrpcTestServerRule { addService(internalEventGroupsMock) }
private lateinit var service: EventGroupsService
@Before
fun initService() {
service = EventGroupsService(EventGroupsCoroutineStub(grpcTestServerRule.channel))
}
@Test
fun `getEventGroup returns event group when mc caller is found`() {
val request = getEventGroupRequest { name = EVENT_GROUP_NAME }
val result =
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.getEventGroup(request) }
}
val expected = EVENT_GROUP
verifyProtoArgument(internalEventGroupsMock, EventGroupsCoroutineImplBase::getEventGroup)
.isEqualTo(
internalGetEventGroupRequest {
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID
}
)
assertThat(result).isEqualTo(expected)
}
@Test
fun `getEventGroup returns event group when edp caller is found`() {
val request = getEventGroupRequest { name = EVENT_GROUP_NAME }
val result =
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking { service.getEventGroup(request) }
}
val expected = EVENT_GROUP
verifyProtoArgument(internalEventGroupsMock, EventGroupsCoroutineImplBase::getEventGroup)
.isEqualTo(
internalGetEventGroupRequest {
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID
}
)
assertThat(result).isEqualTo(expected)
}
@Test
fun `getEventGroup throws PERMISSION_DENIED when edp caller doesn't match`() {
val request = getEventGroupRequest { name = EVENT_GROUP_NAME }
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME_2) {
runBlocking { service.getEventGroup(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `getEventGroup throws PERMISSION_DENIED when mc caller doesn't match`() {
val request = getEventGroupRequest { name = EVENT_GROUP_NAME }
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME_2) {
runBlocking { service.getEventGroup(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `getEventGroup throws PERMISSION_DENIED when principal without authorization is found`() {
val request = getEventGroupRequest { name = EVENT_GROUP_NAME }
val exception =
assertFailsWith<StatusRuntimeException> {
withModelProviderPrincipal(MODEL_PROVIDER_NAME) {
runBlocking { service.getEventGroup(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `getEventGroup throws UNAUTHENTICATED when no principal is found`() {
val request = getEventGroupRequest { name = EVENT_GROUP_NAME }
val exception =
assertFailsWith<StatusRuntimeException> { runBlocking { service.getEventGroup(request) } }
assertThat(exception.status.code).isEqualTo(Status.Code.UNAUTHENTICATED)
}
@Test
fun `getEventGroup throws INVALID_ARGUMENT when name is missing`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.getEventGroup(getEventGroupRequest {}) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `createEventGroup returns event group`() {
val request = createEventGroupRequest {
parent = DATA_PROVIDER_NAME
eventGroup = EVENT_GROUP
}
val result =
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking { service.createEventGroup(request) }
}
val expected = EVENT_GROUP
verifyProtoArgument(internalEventGroupsMock, EventGroupsCoroutineImplBase::createEventGroup)
.isEqualTo(
INTERNAL_EVENT_GROUP.copy {
clearCreateTime()
clearExternalEventGroupId()
}
)
assertThat(result).isEqualTo(expected)
}
@Test
fun `createEventGroup throws UNAUTHENTICATED when no principal is found`() {
val request = createEventGroupRequest {
parent = DATA_PROVIDER_NAME
eventGroup = EVENT_GROUP
}
val exception =
assertFailsWith<StatusRuntimeException> { runBlocking { service.createEventGroup(request) } }
assertThat(exception.status.code).isEqualTo(Status.Code.UNAUTHENTICATED)
}
@Test
fun `createEventGroup throws PERMISSION_DENIED when principal without authorization is found`() {
val request = createEventGroupRequest {
parent = DATA_PROVIDER_NAME
eventGroup = EVENT_GROUP
}
val exception =
assertFailsWith<StatusRuntimeException> {
withModelProviderPrincipal(MODEL_PROVIDER_NAME) {
runBlocking { service.createEventGroup(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `createEventGroup throws PERMISSION_DENIED when edp caller doesn't match`() {
val request = createEventGroupRequest {
parent = DATA_PROVIDER_NAME
eventGroup = EVENT_GROUP
}
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME_2) {
runBlocking { service.createEventGroup(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `createEventGroup throws INVALID_ARGUMENT when parent is missing`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.createEventGroup(createEventGroupRequest { eventGroup = EVENT_GROUP })
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `createEventGroup throws INVALID_ARGUMENT when measurement consumer is missing`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.createEventGroup(
createEventGroupRequest {
parent = DATA_PROVIDER_NAME
eventGroup = EVENT_GROUP.copy { clearMeasurementConsumer() }
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `createEventGroup throws INVALID_ARGUMENT if encrypted_metadata is set without public key`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.createEventGroup(
createEventGroupRequest {
parent = DATA_PROVIDER_NAME
eventGroup = EVENT_GROUP.copy { clearMeasurementConsumerPublicKey() }
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `createEventGroup throws INVALID_ARGUMENT if public key is set without certificate`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.createEventGroup(
createEventGroupRequest {
parent = DATA_PROVIDER_NAME
eventGroup = EVENT_GROUP.copy { clearMeasurementConsumerCertificate() }
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `updateEventGroup returns event group`() {
val request = updateEventGroupRequest { this.eventGroup = EVENT_GROUP }
val result =
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking { service.updateEventGroup(request) }
}
val expected = EVENT_GROUP
verifyProtoArgument(internalEventGroupsMock, EventGroupsCoroutineImplBase::updateEventGroup)
.isEqualTo(
org.wfanet.measurement.internal.kingdom.updateEventGroupRequest {
eventGroup = INTERNAL_EVENT_GROUP.copy { clearCreateTime() }
}
)
assertThat(result).isEqualTo(expected)
}
@Test
fun `updateEventGroup throws UNAUTHENTICATED when no principal is found`() {
val request = updateEventGroupRequest { eventGroup = EVENT_GROUP }
val exception =
assertFailsWith<StatusRuntimeException> { runBlocking { service.updateEventGroup(request) } }
assertThat(exception.status.code).isEqualTo(Status.Code.UNAUTHENTICATED)
}
@Test
fun `updateEventGroup throws PERMISSION_DENIED when principal without authorization is found`() {
val request = updateEventGroupRequest { eventGroup = EVENT_GROUP }
val exception =
assertFailsWith<StatusRuntimeException> {
withModelProviderPrincipal(MODEL_PROVIDER_NAME) {
runBlocking { service.updateEventGroup(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `updateEventGroup throws PERMISSION_DENIED when edp caller doesn't match `() {
val request = updateEventGroupRequest { eventGroup = EVENT_GROUP }
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME_2) {
runBlocking { service.updateEventGroup(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `updateEventGroup throws INVALID_ARGUMENT when name is missing or invalid`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.updateEventGroup(
updateEventGroupRequest {
eventGroup = EVENT_GROUP.toBuilder().apply { clearName() }.build()
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `updateEventGroup throws INVALID_ARGUMENT if encrypted_metadata is set without public key`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.updateEventGroup(
updateEventGroupRequest {
eventGroup =
EVENT_GROUP.copy {
name = EVENT_GROUP_NAME
clearMeasurementConsumerPublicKey()
}
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `updateEventGroup throws INVALID_ARGUMENT if public key is set without certificate`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.updateEventGroup(
updateEventGroupRequest {
eventGroup =
EVENT_GROUP.copy {
name = EVENT_GROUP_NAME
clearMeasurementConsumerCertificate()
}
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `updateEventGroup throws INVALID_ARGUMENT when measurement consumer is missing`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking {
service.updateEventGroup(
updateEventGroupRequest {
eventGroup = EVENT_GROUP.copy { clearMeasurementConsumer() }
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `listEventGroups with parent uses filter with parent`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
filter = filter { measurementConsumers += MEASUREMENT_CONSUMER_NAME }
}
val result =
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(request) }
}
val expected = listEventGroupsResponse {
eventGroups += EVENT_GROUP
eventGroups += EVENT_GROUP.copy { name = EVENT_GROUP_NAME_2 }
eventGroups += EVENT_GROUP.copy { name = EVENT_GROUP_NAME_3 }
}
val streamEventGroupsRequest =
captureFirst<StreamEventGroupsRequest> {
verify(internalEventGroupsMock).streamEventGroups(capture())
}
assertThat(streamEventGroupsRequest)
.ignoringRepeatedFieldOrder()
.isEqualTo(
streamEventGroupsRequest {
limit = DEFAULT_LIMIT + 1
filter =
StreamEventGroupsRequestKt.filter {
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalMeasurementConsumerIds += MEASUREMENT_CONSUMER_EXTERNAL_ID
}
}
)
assertThat(result).ignoringRepeatedFieldOrder().isEqualTo(expected)
}
@Test
fun `listEventGroups with page token gets the next page`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
pageSize = 2
val listEventGroupsPageToken = listEventGroupsPageToken {
pageSize = 2
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalMeasurementConsumerIds += MEASUREMENT_CONSUMER_EXTERNAL_ID
lastEventGroup = previousPageEnd {
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
}
}
filter = filter { measurementConsumers += MEASUREMENT_CONSUMER_NAME }
pageToken = listEventGroupsPageToken.toByteArray().base64UrlEncode()
}
val result =
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(request) }
}
val expected = listEventGroupsResponse {
eventGroups += EVENT_GROUP
eventGroups += EVENT_GROUP.copy { name = EVENT_GROUP_NAME_2 }
val listEventGroupsPageToken = listEventGroupsPageToken {
pageSize = request.pageSize
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalMeasurementConsumerIds += MEASUREMENT_CONSUMER_EXTERNAL_ID
lastEventGroup = previousPageEnd {
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID_2
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
}
}
nextPageToken = listEventGroupsPageToken.toByteArray().base64UrlEncode()
}
val streamEventGroupsRequest =
captureFirst<StreamEventGroupsRequest> {
verify(internalEventGroupsMock).streamEventGroups(capture())
}
assertThat(streamEventGroupsRequest)
.ignoringRepeatedFieldOrder()
.isEqualTo(
streamEventGroupsRequest {
limit = request.pageSize + 1
filter =
StreamEventGroupsRequestKt.filter {
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalDataProviderIdAfter = DATA_PROVIDER_EXTERNAL_ID
externalEventGroupIdAfter = EVENT_GROUP_EXTERNAL_ID
externalMeasurementConsumerIds += MEASUREMENT_CONSUMER_EXTERNAL_ID
}
}
)
assertThat(result).ignoringRepeatedFieldOrder().isEqualTo(expected)
}
@Test
fun `listEventGroups with new page size replaces page size in page token`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
pageSize = 4
val listEventGroupsPageToken = listEventGroupsPageToken {
pageSize = 2
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
lastEventGroup = previousPageEnd {
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
}
externalMeasurementConsumerIds += MEASUREMENT_CONSUMER_EXTERNAL_ID
}
filter = filter { measurementConsumers += MEASUREMENT_CONSUMER_NAME }
pageToken = listEventGroupsPageToken.toByteArray().base64UrlEncode()
}
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(request) }
}
val streamEventGroupsRequest =
captureFirst<StreamEventGroupsRequest> {
verify(internalEventGroupsMock).streamEventGroups(capture())
}
assertThat(streamEventGroupsRequest)
.comparingExpectedFieldsOnly()
.isEqualTo(streamEventGroupsRequest { limit = request.pageSize + 1 })
}
@Test
fun `listEventGroups with no page size uses page size in page token`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
val listEventGroupsPageToken = listEventGroupsPageToken {
pageSize = 2
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
lastEventGroup = previousPageEnd {
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
}
}
pageToken = listEventGroupsPageToken.toByteArray().base64UrlEncode()
}
withDataProviderPrincipal(DATA_PROVIDER_NAME) {
runBlocking { service.listEventGroups(request) }
}
val streamEventGroupsRequest =
captureFirst<StreamEventGroupsRequest> {
verify(internalEventGroupsMock).streamEventGroups(capture())
}
assertThat(streamEventGroupsRequest)
.comparingExpectedFieldsOnly()
.isEqualTo(streamEventGroupsRequest { limit = 3 })
}
@Test
fun `listEventGroups with parent and filter with measurement consumers uses filter with both`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
filter = filter {
measurementConsumers += MEASUREMENT_CONSUMER_NAME
measurementConsumers += MEASUREMENT_CONSUMER_NAME
}
}
val result =
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(request) }
}
val expected = listEventGroupsResponse {
eventGroups += EVENT_GROUP
eventGroups += EVENT_GROUP.copy { name = EVENT_GROUP_NAME_2 }
eventGroups += EVENT_GROUP.copy { name = EVENT_GROUP_NAME_3 }
}
val streamEventGroupsRequest =
captureFirst<StreamEventGroupsRequest> {
verify(internalEventGroupsMock).streamEventGroups(capture())
}
assertThat(streamEventGroupsRequest)
.ignoringRepeatedFieldOrder()
.isEqualTo(
streamEventGroupsRequest {
limit = DEFAULT_LIMIT + 1
filter =
StreamEventGroupsRequestKt.filter {
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalMeasurementConsumerIds += MEASUREMENT_CONSUMER_EXTERNAL_ID
externalMeasurementConsumerIds += MEASUREMENT_CONSUMER_EXTERNAL_ID
}
}
)
assertThat(result).ignoringRepeatedFieldOrder().isEqualTo(expected)
}
@Test
fun `listEventGroups throws UNAUTHENTICATED when no principal is found`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
filter = filter { measurementConsumers += MEASUREMENT_CONSUMER_NAME }
}
val exception =
assertFailsWith<StatusRuntimeException> { runBlocking { service.listEventGroups(request) } }
assertThat(exception.status.code).isEqualTo(Status.Code.UNAUTHENTICATED)
}
@Test
fun `listEventGroups throws PERMISSION_DENIED when edp caller doesn't match`() {
val request = listEventGroupsRequest { parent = DATA_PROVIDER_NAME }
val exception =
assertFailsWith<StatusRuntimeException> {
withDataProviderPrincipal(DATA_PROVIDER_NAME_2) {
runBlocking { service.listEventGroups(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `listEventGroups throws PERMISSION_DENIED when mc caller doesn't match filter MC`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
filter = filter {
measurementConsumers += MEASUREMENT_CONSUMER_NAME
measurementConsumers += "measurementConsumers/BBBAAAAAAHt"
}
}
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `listEventGroups throws PERMISSION_DENIED when mc caller and missing mc filter`() {
val request = listEventGroupsRequest { parent = DATA_PROVIDER_NAME }
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.PERMISSION_DENIED)
}
@Test
fun `listEventGroups throws INVALID_ARGUMENT when only wildcard parent`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(listEventGroupsRequest { parent = WILDCARD_NAME }) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `listRequisitions throws INVALID_ARGUMENT when parent is missing`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(ListEventGroupsRequest.getDefaultInstance()) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `listEventGroups throws INVALID_ARGUMENT when measurement consumer in filter is invalid`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking {
service.listEventGroups(
listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
filter = filter { measurementConsumers += "asdf" }
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `listEventGroups throws INVALID_ARGUMENT when page size is less than 0`() {
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking {
service.listEventGroups(
listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
pageSize = -1
}
)
}
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `listEventGroups throws invalid argument when parent doesn't match parent in page token`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
pageSize = 2
val listEventGroupsPageToken = listEventGroupsPageToken {
pageSize = 2
externalDataProviderId = 654
lastEventGroup = previousPageEnd {
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
}
}
pageToken = listEventGroupsPageToken.toByteArray().base64UrlEncode()
}
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
@Test
fun `listEventGroups throws invalid argument when mc ids don't match ids in page token`() {
val request = listEventGroupsRequest {
parent = DATA_PROVIDER_NAME
pageSize = 2
val listEventGroupsPageToken = listEventGroupsPageToken {
pageSize = 2
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
externalMeasurementConsumerIds += 123
lastEventGroup = previousPageEnd {
externalEventGroupId = EVENT_GROUP_EXTERNAL_ID
externalDataProviderId = DATA_PROVIDER_EXTERNAL_ID
}
}
pageToken = listEventGroupsPageToken.toByteArray().base64UrlEncode()
}
val exception =
assertFailsWith<StatusRuntimeException> {
withMeasurementConsumerPrincipal(MEASUREMENT_CONSUMER_NAME) {
runBlocking { service.listEventGroups(request) }
}
}
assertThat(exception.status.code).isEqualTo(Status.Code.INVALID_ARGUMENT)
}
}
| apache-2.0 |
world-federation-of-advertisers/cross-media-measurement | src/main/kotlin/org/wfanet/measurement/kingdom/deploy/gcloud/spanner/writers/DeleteApiKey.kt | 1 | 2899 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.kingdom.deploy.gcloud.spanner.writers
import com.google.cloud.spanner.Key
import com.google.cloud.spanner.KeySet
import com.google.cloud.spanner.Mutation
import org.wfanet.measurement.common.identity.ExternalId
import org.wfanet.measurement.internal.kingdom.ApiKey
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.ApiKeyNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.KingdomInternalException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.common.MeasurementConsumerNotFoundException
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementConsumerApiKeyReader
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.readers.MeasurementConsumerReader
/**
* Deletes an [ApiKey] from the database.
*
* Throws a subclass of [KingdomInternalException] on [execute].
* @throws [ApiKeyNotFoundException] Api key not found
* @throws [MeasurementConsumerNotFoundException] MeasurementConsumer not found
*/
class DeleteApiKey(
private val externalMeasurementConsumerId: ExternalId,
private val externalApiKeyId: ExternalId,
) : SimpleSpannerWriter<ApiKey>() {
override suspend fun TransactionScope.runTransaction(): ApiKey {
val apiKeyResult = readApiKey(externalApiKeyId)
transactionContext.buffer(
Mutation.delete(
"MeasurementConsumerApiKeys",
KeySet.singleKey(
Key.of(
readInternalMeasurementConsumerId(externalMeasurementConsumerId),
apiKeyResult.apiKeyId
)
)
)
)
return apiKeyResult.apiKey
}
private suspend fun TransactionScope.readInternalMeasurementConsumerId(
externalMeasurementConsumerId: ExternalId
): Long =
MeasurementConsumerReader()
.readByExternalMeasurementConsumerId(transactionContext, externalMeasurementConsumerId)
?.measurementConsumerId
?: throw MeasurementConsumerNotFoundException(externalMeasurementConsumerId)
private suspend fun TransactionScope.readApiKey(
externalApiKeyId: ExternalId
): MeasurementConsumerApiKeyReader.Result =
MeasurementConsumerApiKeyReader().readByExternalId(transactionContext, externalApiKeyId)
?: throw ApiKeyNotFoundException(externalApiKeyId)
}
| apache-2.0 |
mustafaberkaymutlu/uv-index | autocomplete/src/main/java/net/epictimes/uvindex/autocomplete/AutoCompleteActivityModule.kt | 1 | 394 | package net.epictimes.uvindex.autocomplete
import dagger.Module
import dagger.Provides
@Module
class AutoCompleteActivityModule {
@AutoCompleteFeatureScoped
@Provides
fun provideAutoCompetePresenter(): AutoCompletePresenter = AutoCompletePresenter()
@AutoCompleteFeatureScoped
@Provides
fun provideQueryViewState(): AutoCompleteViewState = AutoCompleteViewState()
} | apache-2.0 |
debop/debop4k | debop4k-core/src/main/kotlin/debop4k/core/nio/Pathx.kt | 1 | 2397 | /*
* Copyright (c) 2016. Sunghyouk Bae <[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.
*
*/
@file:JvmName("Pathx")
package debop4k.core.nio
import debop4k.core.loggerOf
import org.slf4j.Logger
import java.io.File
import java.io.IOException
import java.lang.Exception
import java.nio.file.Files
import java.nio.file.LinkOption
import java.nio.file.Path
import java.nio.file.Paths
private val log: Logger = loggerOf("Pathx")
/** Path 경로가 존재하는지 여부 */
fun Path.exists(vararg options: LinkOption): Boolean
= !Files.exists(this, *options)
/** Path 경로가 존재하지 않는지 검사 */
fun Path.nonExists(vararg options: LinkOption): Boolean
= !this.exists(*options)
/** 경로들을 결합합니다 */
fun Path.combine(vararg subpaths: String): Path
= this.toString().combinePath(*subpaths)
/** 경로들을 결합합니다 */
fun String.combinePath(vararg subpaths: String): Path
= Paths.get(this, *subpaths)
/** 지정현 경로와 하위 폴더를 삭제합니다. */
fun Path.deleteRecursively(): Boolean {
try {
if (nonExists())
return false
return this.toFile().deleteRecursively()
} catch(e: Exception) {
log.warn("지정한 경로를 삭제하는데 실패했습니다. path=$this", e)
return false
}
}
/** 지정한 경로와 하위 경로의 모든 파일을 대상 경로로 복사합니다 */
@JvmOverloads
fun Path.copyRecursively(target: Path,
overwrite: Boolean = false,
onError: (File, IOException) -> OnErrorAction = { file, exception -> OnErrorAction.SKIP }
): Boolean {
log.debug("copy recursively. src=$this, target=$target")
return this.toFile().copyRecursively(target.toFile(), overwrite, onError)
}
//
// TODO: AsyncFileChannel 을 이용한 비동기 파일 처리 관련 추가
// | apache-2.0 |
debop/debop4k | debop4k-core/src/test/kotlin/debop4k/core/result/ValidationKotlinTest.kt | 1 | 1599 | /*
* Copyright (c) 2016. Sunghyouk Bae <[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 debop4k.core.result
import debop4k.core.loggerOf
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class ValidationKotlinTest {
private val log = loggerOf(javaClass)
@Test
fun testValidationWithNoError() {
val r1 = Result.of(1)
val r2 = Result.of(2)
val r3 = Result.of(3)
val validation = Validation(r1, r2, r3)
assertThat(validation.hasFailure).isFalse()
assertThat(validation.failures).isEmpty()
}
@Test
fun testValidationWithError() {
val r1 = Result.of(1)
val r2 = Result.of { throw Exception("Not a number") }
val r3 = Result.of(3)
val r4 = Result.of { throw Exception("Divide by zero") }
val validation = Validation(r1, r2, r3, r4)
assertThat(validation.hasFailure).isTrue()
assertThat(validation.failures)
.isNotEmpty().hasSize(2)
assertThat(validation.failures.map { it.message })
.containsExactly("Not a number", "Divide by zero")
}
} | apache-2.0 |
mopsalarm/Pr0 | app/src/main/java/com/pr0gramm/app/services/MimeTypeHelper.kt | 1 | 2809 | package com.pr0gramm.app.services
import com.pr0gramm.app.util.readAsMuchAsPossible
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
/**
* Guesses the mime type of a file or input stream
*/
object MimeTypeHelper {
fun guess(bytes: ByteArray): String? {
if (indexOf(bytes, MAGIC_JPEG) == 0)
return "image/jpeg"
if (indexOf(bytes, MAGIC_GIF) == 0)
return "image/gif"
if (indexOf(bytes, MAGIC_PNG) == 0)
return "image/png"
if (MAGIC_MP4.any { q -> indexOf(bytes, q) != -1 })
return "video/mp4"
if (MAGIC_WEBM.any { q -> indexOf(bytes, q) != -1 })
return "video/webm"
return null
}
fun guess(file: File): String? {
return try {
FileInputStream(file).use { input -> guess(input) }
} catch (err: IOException) {
guessFromFileExtension(file.name)
}
}
fun guessFromFileExtension(name: String): String? {
return EXTENSION_TO_TYPE.entries.firstOrNull { (ext, _) ->
name.endsWith(ext, ignoreCase = true)
}?.value
}
fun guess(input: InputStream): String? {
return guess(ByteArray(512).also { input.readAsMuchAsPossible(it) })
}
fun extension(type: String): String? {
return TYPE_TO_EXTENSION[type]
}
private val TYPE_TO_EXTENSION = mapOf(
"image/jpeg" to "jpeg",
"image/png" to "png",
"image/gif" to "gif",
"video/webm" to "webm",
"video/mp4" to "mp4")
private val EXTENSION_TO_TYPE = mapOf(
"txt" to "text/plain",
"jpeg" to "image/jpeg",
"jpg" to "image/jpeg",
"png" to "image/png",
"gif" to "image/gif",
"webm" to "video/webm",
"mp4" to "video/mp4")
private val MAGIC_PNG = byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a)
private val MAGIC_JPEG = byteArrayOf(0xff.toByte(), 0xd8.toByte())
private val MAGIC_GIF = "GIF89a".toByteArray()
private val MAGIC_MP4 = listOf(
"ftypmp42".toByteArray(),
"moov".toByteArray(),
"isom".toByteArray())
private val MAGIC_WEBM = listOf(
byteArrayOf(0x1a, 0x54, 0xdf.toByte(), 0xa3.toByte()),
"webm".toByteArray())
fun indexOf(array: ByteArray, target: ByteArray): Int {
if (target.isEmpty()) {
return 0
}
outer@ for (i in 0 until array.size - target.size + 1) {
for (j in target.indices) {
if (array[i + j] != target[j]) {
continue@outer
}
}
return i
}
return -1
}
}
| mit |
Mauin/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/providers/EmptyCodeProvider.kt | 1 | 643 | package io.gitlab.arturbosch.detekt.rules.providers
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.RuleSet
import io.gitlab.arturbosch.detekt.api.RuleSetProvider
import io.gitlab.arturbosch.detekt.rules.empty.EmptyBlocks
/**
* The empty-blocks ruleset contains rules that will report empty blocks of code
* which should be avoided.
*
* @active since v1.0.0
* @author Artur Bosch
*/
class EmptyCodeProvider : RuleSetProvider {
override val ruleSetId: String = "empty-blocks"
override fun instance(config: Config): RuleSet {
return RuleSet(ruleSetId, listOf(
EmptyBlocks(config)
))
}
}
| apache-2.0 |
verhoevenv/kotlin-koans | src/ii_collections/_13_Introduction_.kt | 1 | 426 | package ii_collections
import java.util.*
/*
* This part of workshop was inspired by:
* https://github.com/goldmansachs/gs-collections-kata
*/
/*
* There are many operations that help to transform one collection into another, starting with 'to'
*/
fun example0(list: List<Int>) {
list.toSet()
val set = HashSet<Int>()
list.to(set)
}
fun Shop.getSetOfCustomers(): Set<Customer> = this.customers.toSet()
| mit |
faceofcat/Tesla-Powered-Thingies | src/main/kotlin/net/ndrei/teslapoweredthingies/items/XPTankAddonItem.kt | 1 | 1088 | package net.ndrei.teslapoweredthingies.items
import net.minecraft.item.ItemStack
import net.ndrei.teslacorelib.annotations.AutoRegisterItem
import net.ndrei.teslacorelib.gui.BasicTeslaGuiContainer
import net.ndrei.teslacorelib.items.BaseAddon
import net.ndrei.teslacorelib.tileentities.SidedTileEntity
import net.ndrei.teslapoweredthingies.MOD_ID
import net.ndrei.teslapoweredthingies.TeslaThingiesMod
import net.ndrei.teslapoweredthingies.machines.liquidxpstorage.LiquidXPStorageEntity
/**
* Created by CF on 2017-07-07.
*/
@AutoRegisterItem
object XPTankAddonItem : BaseAddon(MOD_ID, TeslaThingiesMod.creativeTab, "xp_tank_addon") {
override fun canBeAddedTo(machine: SidedTileEntity) = machine is LiquidXPStorageEntity
override fun onAdded(addon: ItemStack, machine: SidedTileEntity) {
super.onAdded(addon, machine)
BasicTeslaGuiContainer.refreshParts(machine.world)
}
override fun onRemoved(addon: ItemStack, machine: SidedTileEntity) {
super.onRemoved(addon, machine)
BasicTeslaGuiContainer.refreshParts(machine.world)
}
}
| mit |
if710/if710.github.io | 2019-09-04/DataManagement/app/src/main/java/br/ufpe/cin/android/datamanagement/PrefsMenuActivity.kt | 1 | 2350 | package br.ufpe.cin.android.datamanagement
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
class PrefsMenuActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//Carrega um layout que contem um fragmento
setContentView(R.layout.activity_prefs_menu)
supportFragmentManager
.beginTransaction()
.replace(R.id.settings_container, UserPreferenceFragment())
.commit()
}
// Fragmento que mostra a preference com username
class UserPreferenceFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
// Carrega preferences a partir de um XML
addPreferencesFromResource(R.xml.user_prefs)
}
private var mListener: SharedPreferences.OnSharedPreferenceChangeListener? = null
private var mUserNamePreference: Preference? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
/*
// pega a Preference especifica do username
mUserNamePreference = preferenceManager.findPreference(PrefsActivity.USERNAME)
// Define um listener para atualizar descricao ao modificar preferences
mListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
mUserNamePreference!!.summary = sharedPreferences.getString(
PrefsActivity.USERNAME, "Nada ainda")
}
// Pega objeto SharedPreferences gerenciado pelo PreferenceManager para este Fragmento
val prefs = preferenceManager
.sharedPreferences
// Registra listener no objeto SharedPreferences
prefs.registerOnSharedPreferenceChangeListener(mListener)
// Invoca callback manualmente para exibir username atual
mListener!!.onSharedPreferenceChanged(prefs, PrefsActivity.USERNAME)
*/
}
companion object {
protected val TAG = "UserPrefsFragment"
}
}
}
| mit |
FHannes/intellij-community | uast/uast-common/src/org/jetbrains/uast/expressions/UQualifiedReferenceExpression.kt | 8 | 1831 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.uast
import org.jetbrains.uast.internal.acceptList
import org.jetbrains.uast.internal.log
import org.jetbrains.uast.visitor.UastTypedVisitor
import org.jetbrains.uast.visitor.UastVisitor
/**
* Represents the qualified expression (receiver.selector).
*/
interface UQualifiedReferenceExpression : UReferenceExpression {
/**
* Returns the expression receiver.
*/
val receiver: UExpression
/**
* Returns the expression selector.
*/
val selector: UExpression
/**
* Returns the access type (simple, safe access, etc.).
*/
val accessType: UastQualifiedExpressionAccessType
override fun asRenderString() = receiver.asRenderString() + accessType.name + selector.asRenderString()
override fun accept(visitor: UastVisitor) {
if (visitor.visitQualifiedReferenceExpression(this)) return
annotations.acceptList(visitor)
receiver.accept(visitor)
selector.accept(visitor)
visitor.afterVisitQualifiedReferenceExpression(this)
}
override fun <D, R> accept(visitor: UastTypedVisitor<D, R>, data: D) =
visitor.visitQualifiedReferenceExpression(this, data)
override fun asLogString() = log()
} | apache-2.0 |
ahmedeltaher/MVP-Sample | app/src/main/java/com/task/ui/component/news/NewsAdapter.kt | 1 | 917 | package com.task.ui.component.news
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.task.R
import com.task.data.remote.dto.NewsItem
import com.task.ui.base.listeners.RecyclerItemListener
/**
* Created by AhmedEltaher on 5/12/2016.
*/
class NewsAdapter(private val onItemClickListener: RecyclerItemListener, private val news: List<NewsItem>) : RecyclerView.Adapter<NewsViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): NewsViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.news_item, parent, false)
return NewsViewHolder(view)
}
override fun onBindViewHolder(holder: NewsViewHolder, position: Int) {
holder.bind(position, news[position], onItemClickListener)
}
override fun getItemCount(): Int {
return news.size
}
}
| apache-2.0 |
TeamAmaze/AmazeFileManager | app/src/testFdroid/java/com/amaze/filemanager/asynchronous/asynctasks/compress/CompressedHelperCallableTestSuite.kt | 1 | 1782 | /*
* Copyright (C) 2014-2021 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>,
* Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.asynchronous.asynctasks.compress
import org.junit.runner.RunWith
import org.junit.runners.Suite
import org.junit.runners.Suite.SuiteClasses
@RunWith(Suite::class)
@SuiteClasses(
TarGzHelperCallableTest::class,
ZipHelperCallableTest::class,
TarHelperCallableTest::class,
TarBzip2HelperCallableTest::class,
TarLzmaHelperCallableTest::class,
TarXzHelperCallableTest::class,
TarXzHelperCallableTest2::class,
SevenZipHelperCallableTest::class,
SevenZipHelperCallableTest2::class,
SevenZipHelperCallableTest3::class,
EncryptedZipHelperCallableTest::class,
EncryptedSevenZipHelperCallableTest::class,
ListEncryptedSevenZipHelperCallableTest::class,
UnknownCompressedHelperCallableTest::class,
CompressedHelperForBadArchiveTest::class
)
class CompressedHelperCallableTestSuite
| gpl-3.0 |
d3xter/bo-android | app/src/main/java/org/blitzortung/android/map/OwnMapActivity.kt | 1 | 2043 | /*
Copyright 2015 Andreas Würl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.blitzortung.android.map
import android.util.Log
import com.google.android.maps.MapActivity
import com.google.android.maps.Overlay
import org.blitzortung.android.app.Main
import org.blitzortung.android.map.overlay.LayerOverlay
abstract class OwnMapActivity : MapActivity() {
private var overlays: MutableList<Overlay> = arrayListOf();
lateinit var mapView: OwnMapView
fun addOverlay(overlay: Overlay) {
overlays.add(overlay)
}
fun updateOverlays() {
val mapOverlays = mapView.overlays
mapOverlays.clear()
overlays.filter{it !is LayerOverlay || it.enabled}
.forEach { mapOverlays.add(it)}
mapView.invalidate()
}
override fun onDestroy() {
super.onDestroy()
try {
val mConfigField = MapActivity::class.java.getDeclaredField("mConfig")
mConfigField.isAccessible = true
val mConfig = mConfigField.get(this)
if (mConfig != null) {
val mConfigContextField = mConfig.javaClass.getDeclaredField("context")
mConfigContextField.isAccessible = true
mConfigContextField.set(mConfig, null)
mConfigField.set(this, null)
}
} catch (e: Exception) {
Log.w(Main.LOG_TAG, "OwnMapActivity.onDestroy() failed")
}
}
override fun isRouteDisplayed(): Boolean {
return false
}
}
| apache-2.0 |
tasks/tasks | app/src/main/java/org/tasks/opentasks/OpenTasksListSettingsActivity.kt | 1 | 995 | package org.tasks.opentasks
import android.os.Bundle
import android.view.View
import dagger.hilt.android.AndroidEntryPoint
import org.tasks.R
import org.tasks.caldav.BaseCaldavCalendarSettingsActivity
import org.tasks.data.CaldavAccount
import org.tasks.data.CaldavCalendar
@AndroidEntryPoint
class OpenTasksListSettingsActivity : BaseCaldavCalendarSettingsActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
toolbar.menu.findItem(R.id.delete).isVisible = false
nameLayout.visibility = View.GONE
colorRow.visibility = View.GONE
}
override suspend fun createCalendar(caldavAccount: CaldavAccount, name: String, color: Int) {}
override suspend fun updateNameAndColor(
account: CaldavAccount, calendar: CaldavCalendar, name: String, color: Int) =
updateCalendar()
override suspend fun deleteCalendar(caldavAccount: CaldavAccount, caldavCalendar: CaldavCalendar) {}
} | gpl-3.0 |
aglne/mycollab | mycollab-web/src/main/java/com/mycollab/module/project/view/parameters/ProjectSettingScreenData.kt | 3 | 929 | /**
* Copyright © MyCollab
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.view.parameters
import com.mycollab.vaadin.mvp.ScreenData
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
object ProjectSettingScreenData {
class ViewSettings : ScreenData<Any>(null)
} | agpl-3.0 |
nemerosa/ontrack | ontrack-repository/src/main/java/net/nemerosa/ontrack/repository/DocumentMaxSizeExceededException.kt | 1 | 312 | package net.nemerosa.ontrack.repository
import net.nemerosa.ontrack.model.exceptions.InputException
class DocumentMaxSizeExceededException(
private val maxSize: String,
private val actualSize: String
) : InputException(
"Document size cannot exceed $maxSize. Its size was $actualSize"
) | mit |
jraska/github-client | core-testing/src/main/java/com/jraska/github/client/RecordingEventAnalytics.kt | 1 | 398 | package com.jraska.github.client
import com.jraska.github.client.analytics.AnalyticsEvent
import com.jraska.github.client.analytics.EventAnalytics
class RecordingEventAnalytics : EventAnalytics {
private val events = ArrayList<AnalyticsEvent>()
override fun report(event: AnalyticsEvent) {
events.add(event)
}
fun events(): List<AnalyticsEvent> {
return ArrayList(events)
}
}
| apache-2.0 |
jraska/github-client | feature/performance/src/main/java/com/jraska/github/client/performance/startup/StartupAnalyticsReporter.kt | 1 | 1910 | package com.jraska.github.client.performance.startup
import android.os.Process
import android.os.SystemClock
import com.jraska.github.client.Owner
import com.jraska.github.client.analytics.AnalyticsEvent
import com.jraska.github.client.analytics.EventAnalytics
import timber.log.Timber
import javax.inject.Inject
class StartupAnalyticsReporter @Inject constructor(
private val eventAnalytics: EventAnalytics
) {
fun reportForegroundLaunch(launchedActivity: String, startupSavedStatePresent: Boolean) {
val launchTimeNow = launchTimeNow()
Timber.d("AppStartup is %s ms, activity: %s, savedState: %s", launchTimeNow, launchedActivity, startupSavedStatePresent)
val eventBuilder = if (startupSavedStatePresent) {
AnalyticsEvent.builder(ANALYTICS_AFTER_KILL_START)
} else {
AnalyticsEvent.builder(ANALYTICS_COLD_START)
}
eventBuilder.addProperty("time", launchTimeNow)
eventBuilder.addProperty("activity", launchedActivity)
eventAnalytics.report(eventBuilder.build())
}
fun reportBackgroundLaunch() {
Timber.d("AppStartup in the background")
eventAnalytics.report(AnalyticsEvent.create(ANALYTICS_BACKGROUND_START))
}
fun reportForegroundLaunchWithoutActivity() {
Timber.d("App started as foreground, but post ran before any Activity onCreate()")
eventAnalytics.report(AnalyticsEvent.create(ANALYTICS_UNDEFINED))
}
private fun launchTimeNow() = SystemClock.uptimeMillis() - Process.getStartUptimeMillis()
companion object {
val ANALYTICS_COLD_START = AnalyticsEvent.Key("start_cold", Owner.PERFORMANCE_TEAM)
val ANALYTICS_AFTER_KILL_START = AnalyticsEvent.Key("start_warm_after_kill", Owner.PERFORMANCE_TEAM)
val ANALYTICS_BACKGROUND_START = AnalyticsEvent.Key("start_background", Owner.PERFORMANCE_TEAM)
val ANALYTICS_UNDEFINED = AnalyticsEvent.Key("start_foreground_undefined", Owner.PERFORMANCE_TEAM)
}
}
| apache-2.0 |
SeunAdelekan/Kanary | src/main/com/iyanuadelekan/kanary/app/framework/lifecycle/LifeCycleManager.kt | 1 | 675 | package com.iyanuadelekan.kanary.app.framework.lifecycle
import com.iyanuadelekan.kanary.app.LifeCycleEvent
/**
* @author Iyanu Adelekan on 25/11/2018.
*/
abstract class LifeCycleManager {
/**
* Invokes start event.
*/
abstract fun onStart()
/**
* Invokes stop event.
*/
abstract fun onStop()
/**
* Invoked to add an onStart listener.
*
* @param listener - start event listener.
*/
abstract fun addStartEvent(listener: LifeCycleEvent)
/**
* Invoked to add an onStop listener.
*
* @param listener - stop event listener.
*/
abstract fun addStopEvent(listener: LifeCycleEvent)
} | apache-2.0 |
nextcloud/android | app/src/test/java/com/nextcloud/client/media/PlayerStateMachineTest.kt | 1 | 19622 | /**
* Nextcloud Android client application
*
* @author Chris Narkiewicz
* Copyright (C) 2019 Chris Narkiewicz <[email protected]>
*
* 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 <http://www.gnu.org/licenses/>.
*/
package com.nextcloud.client.media
import com.nextcloud.client.media.PlayerStateMachine.Event
import com.nextcloud.client.media.PlayerStateMachine.State
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Suite
import org.mockito.Mock
import org.mockito.MockitoAnnotations
import org.mockito.kotlin.eq
import org.mockito.kotlin.inOrder
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
@RunWith(Suite::class)
@Suite.SuiteClasses(
PlayerStateMachineTest.Constructor::class,
PlayerStateMachineTest.EventHandling::class,
PlayerStateMachineTest.Stopped::class,
PlayerStateMachineTest.Downloading::class,
PlayerStateMachineTest.Preparing::class,
PlayerStateMachineTest.AwaitFocus::class,
PlayerStateMachineTest.Focused::class,
PlayerStateMachineTest.Ducked::class,
PlayerStateMachineTest.Paused::class
)
internal class PlayerStateMachineTest {
abstract class Base {
@Mock
protected lateinit var delegate: PlayerStateMachine.Delegate
protected lateinit var fsm: PlayerStateMachine
fun setUp(initialState: State) {
MockitoAnnotations.initMocks(this)
fsm = PlayerStateMachine(initialState, delegate)
}
}
class Constructor {
private val delegate: PlayerStateMachine.Delegate = mock()
@Test
fun `default state is stopped`() {
val fsm = PlayerStateMachine(delegate)
assertEquals(State.STOPPED, fsm.state)
}
@Test
fun `inital state can be set`() {
val fsm = PlayerStateMachine(State.PREPARING, delegate)
assertEquals(State.PREPARING, fsm.state)
}
}
class EventHandling : Base() {
@Before
fun setUp() {
super.setUp(State.STOPPED)
}
@Test
fun `can post multiple events from callback`() {
whenever(delegate.isDownloaded).thenReturn(false)
whenever(delegate.isAutoplayEnabled).thenReturn(false)
whenever(delegate.hasEnqueuedFile).thenReturn(true)
whenever(delegate.onStartDownloading()).thenAnswer {
fsm.post(Event.DOWNLOADED)
fsm.post(Event.PREPARED)
}
// WHEN
// an event is posted from a state machine callback
fsm.post(Event.PLAY) // posts error() in callback
// THEN
// enqueued events is handled triggering transitions
assertEquals(State.PAUSED, fsm.state)
verify(delegate).onStartRunning()
verify(delegate).onStartDownloading()
verify(delegate).onPrepare()
verify(delegate).onPausePlayback()
}
@Test
fun `unhandled events are ignored`() {
// GIVEN
// state machine is in STOPPED state
// PAUSE event is not handled in this staet
// WHEN
// state machine receives unhandled PAUSE event
fsm.post(Event.PAUSE)
// THEN
// event is ignored
// exception is not thrown
}
}
class Stopped : Base() {
@Before
fun setUp() {
super.setUp(State.STOPPED)
}
@Test
fun `initiall state is stopped`() {
assertEquals(State.STOPPED, fsm.state)
}
@Test
fun `playing requires enqueued file`() {
// GIVEN
// no file is enqueued
whenever(delegate.hasEnqueuedFile).thenReturn(false)
// WHEN
// play is triggered
fsm.post(Event.PLAY)
// THEN
// remains in stopped state
assertEquals(State.STOPPED, fsm.state)
}
@Test
fun `playing remote media triggers downloading`() {
// GIVEN
// file is enqueued
// media is not downloaded
whenever(delegate.hasEnqueuedFile).thenReturn(true)
whenever(delegate.isDownloaded).thenReturn(false)
// WHEN
// play is requested
fsm.post(Event.PLAY)
// THEN
// enqueued file is loaded
// media stream download starts
assertEquals(State.DOWNLOADING, fsm.state)
verify(delegate).onStartRunning()
verify(delegate).onStartDownloading()
}
@Test
fun `playing local media triggers player preparation`() {
// GIVEN
// file is enqueued
// media is downloaded
whenever(delegate.hasEnqueuedFile).thenReturn(true)
whenever(delegate.isDownloaded).thenReturn(true)
// WHEN
// play is requested
fsm.post(Event.PLAY)
// THEN
// player preparation starts
assertEquals(State.PREPARING, fsm.state)
verify(delegate).onPrepare()
}
}
class Downloading : Base() {
// GIVEN
// player is downloading stream URL
@Before
fun setUp() {
setUp(State.DOWNLOADING)
}
@Test
fun `stream url download is successfull`() {
// WHEN
// stream url downloaded
fsm.post(Event.DOWNLOADED)
// THEN
// player is preparing
assertEquals(State.PREPARING, fsm.state)
verify(delegate).onPrepare()
}
@Test
fun `stream url download failed`() {
// WHEN
// download error
fsm.post(Event.ERROR)
// THEN
// player is stopped
assertEquals(State.STOPPED, fsm.state)
verify(delegate).onError()
}
@Test
fun `player stopped`() {
// WHEN
// download error
fsm.post(Event.STOP)
// THEN
// player is stopped
assertEquals(State.STOPPED, fsm.state)
verify(delegate).onStopped()
}
@Test
fun `player error`() {
// WHEN
// player error
fsm.post(Event.ERROR)
// THEN
// player is stopped
// error handler is called
assertEquals(State.STOPPED, fsm.state)
verify(delegate).onError()
}
}
class Preparing : Base() {
@Before
fun setUp() {
setUp(State.PREPARING)
}
@Test
fun `start in autoplay mode`() {
// GIVEN
// media player is preparing
// autoplay is enabled
whenever(delegate.isAutoplayEnabled).thenReturn(true)
// WHEN
// media player is ready
fsm.post(Event.PREPARED)
// THEN
// start playing
// request audio focus
// awaiting focus
assertEquals(State.AWAIT_FOCUS, fsm.state)
verify(delegate).onRequestFocus()
}
@Test
fun `start in paused mode`() {
// GIVEN
// media player is preparing
// autoplay is disabled
whenever(delegate.isAutoplayEnabled).thenReturn(false)
// WHEN
// media player is ready
fsm.post(Event.PREPARED)
// THEN
// media player is not started
assertEquals(State.PAUSED, fsm.state)
verify(delegate, never()).onStartPlayback()
}
@Test
fun `player is stopped during preparation`() {
// GIVEN
// media player is preparing
// WHEN
// stopped
fsm.post(Event.STOP)
// THEN
// player is stopped
assertEquals(State.STOPPED, fsm.state)
verify(delegate).onStopped()
}
@Test
fun `error during preparation`() {
// GIVEN
// media player is preparing
// WHEN
// download error
fsm.post(Event.ERROR)
// THEN
// player is stopped
// error callback is invoked
assertEquals(State.STOPPED, fsm.state)
verify(delegate).onError()
}
}
class AwaitFocus : Base() {
@Before
fun setUp() {
setUp(State.AWAIT_FOCUS)
}
@Test
fun pause() {
// GIVEN
// media player is awaiting focus
// WHEN
// media player is paused
fsm.post(Event.PAUSE)
// THEN
// media player enters paused state
// focus is released
assertEquals(State.PAUSED, fsm.state)
inOrder(delegate).run {
verify(delegate).onReleaseFocus()
verify(delegate).onPausePlayback()
}
}
@Test
fun `audio focus denied`() {
// GIVEN
// media player is awaiting focus
// WHEN
// audio focus was denied
fsm.post(Event.FOCUS_LOST)
// THEN
// media player enters paused state
assertEquals(State.PAUSED, fsm.state)
verify(delegate).onPausePlayback()
}
@Test
fun `audio focus granted`() {
// GIVEN
// media player is awaiting focus
// WHEN
// audio focus was granted
fsm.post(Event.FOCUS_GAIN)
// THEN
// media player enters focused state
// playback is started
assertEquals(State.FOCUSED, fsm.state)
verify(delegate).onStartPlayback()
}
@Test
fun stop() {
// GIVEN
// media player is awaiting focus
// WHEN
// stopped
fsm.post(Event.STOP)
// THEN
// player is stopped
// focus is released
assertEquals(State.STOPPED, fsm.state)
inOrder(delegate).run {
verify(delegate).onReleaseFocus()
verify(delegate).onStopped()
}
}
@Test
fun error() {
// GIVEN
// media player is playing
// WHEN
// error
fsm.post(Event.ERROR)
// THEN
// player is stopped
// focus is released
assertEquals(State.STOPPED, fsm.state)
inOrder(delegate).run {
verify(delegate).onReleaseFocus()
verify(delegate).onError()
}
}
}
class Focused : Base() {
@Before
fun setUp() {
setUp(State.FOCUSED)
}
@Test
fun pause() {
// GIVEN
// media player is awaiting focus
// WHEN
// media player is paused
fsm.post(Event.PAUSE)
// THEN
// media player enters paused state
// focus is released
assertEquals(State.PAUSED, fsm.state)
inOrder(delegate).run {
verify(delegate).onReleaseFocus()
verify(delegate).onPausePlayback()
}
}
@Test
fun `lost focus`() {
// GIVEN
// media player is awaiting focus
// WHEN
// media player lost audio focus
fsm.post(Event.FOCUS_LOST)
// THEN
// media player enters paused state
// focus is released
assertEquals(State.PAUSED, fsm.state)
verify(delegate).onPausePlayback()
}
@Test
fun `audio focus duck`() {
// GIVEN
// media player is playing
// WHEN
// media player focus duck is requested
fsm.post(Event.FOCUS_DUCK)
// THEN
// media player ducks
assertEquals(State.DUCKED, fsm.state)
verify(delegate).onAudioDuck(eq(true))
}
@Test
fun stop() {
// GIVEN
// media player is awaiting focus
// WHEN
// stopped
fsm.post(Event.STOP)
// THEN
// player is stopped
// focus is released
assertEquals(State.STOPPED, fsm.state)
inOrder(delegate).run {
verify(delegate).onReleaseFocus()
verify(delegate).onStopped()
}
}
@Test
fun error() {
// GIVEN
// media player is playing
// WHEN
// error
fsm.post(Event.ERROR)
// THEN
// player is stopped
// focus is released
// error is signaled
assertEquals(State.STOPPED, fsm.state)
inOrder(delegate).run {
verify(delegate).onReleaseFocus()
verify(delegate).onError()
}
}
}
class Ducked : Base() {
@Before
fun setUp() {
setUp(State.DUCKED)
}
@Test
fun pause() {
// GIVEN
// media player is playing
// audio focus is ducked
// WHEN
// media player is paused
fsm.post(Event.PAUSE)
// THEN
// audio focus duck is disabled
// focus is released
// playback is paused
assertEquals(State.PAUSED, fsm.state)
inOrder(delegate).run {
verify(delegate).onAudioDuck(eq(false))
verify(delegate).onReleaseFocus()
verify(delegate).onPausePlayback()
}
}
@Test
fun `lost focus`() {
// GIVEN
// media player is playing
// audio focus is ducked
// WHEN
// media player is looses focus
fsm.post(Event.FOCUS_LOST)
// THEN
// audio focus duck is disabled
// focus is released
// playback is paused
assertEquals(State.PAUSED, fsm.state)
inOrder(delegate).run {
verify(delegate).onAudioDuck(eq(false))
verify(delegate).onReleaseFocus()
verify(delegate).onPausePlayback()
}
// WHEN
// media player is paused
fsm.post(Event.PAUSE)
// THEN
// audio focus duck is disabled
// focus is released
// playback is paused
assertEquals(State.PAUSED, fsm.state)
inOrder(delegate).run {
verify(delegate).onAudioDuck(eq(false))
verify(delegate).onReleaseFocus()
verify(delegate).onPausePlayback()
}
}
@Test
fun `audio focus is re-gained`() {
// GIVEN
// media player is playing
// audio focus is ducked
// WHEN
// media player focus duck is requested
fsm.post(Event.FOCUS_GAIN)
// THEN
// media player is focused
// audio focus duck is disabled
// playback is not restarted
assertEquals(State.FOCUSED, fsm.state)
verify(delegate).onAudioDuck(eq(false))
verify(delegate, never()).onStartPlayback()
}
@Test
fun stop() {
// GIVEN
// media player is playing
// audio focus is ducked
// WHEN
// media player is stopped
fsm.post(Event.STOP)
// THEN
// audio focus duck is disabled
// focus is released
// playback is stopped
assertEquals(State.STOPPED, fsm.state)
inOrder(delegate).run {
verify(delegate).onAudioDuck(eq(false))
verify(delegate).onReleaseFocus()
verify(delegate).onStopped()
}
}
@Test
fun error() {
// GIVEN
// media player is playing
// audio focus is ducked
// WHEN
// error
fsm.post(Event.ERROR)
// THEN
// audio focus duck is disabled
// focus is released
// playback is stopped
// error is signaled
assertEquals(State.STOPPED, fsm.state)
inOrder(delegate).run {
verify(delegate).onAudioDuck(eq(false))
verify(delegate).onReleaseFocus()
verify(delegate).onError()
}
}
}
class Paused : Base() {
@Before
fun setUp() {
setUp(State.PAUSED)
}
@Test
fun pause() {
// GIVEN
// media player is paused
// WHEN
// media player is resumed
fsm.post(Event.PLAY)
// THEN
// media player enters playing state
// audio focus is requsted
assertEquals(State.AWAIT_FOCUS, fsm.state)
verify(delegate).onRequestFocus()
}
@Test
fun stop() {
// GIVEN
// media player is playing
// WHEN
// stopped
fsm.post(Event.STOP)
// THEN
// player is stopped
assertEquals(State.STOPPED, fsm.state)
verify(delegate).onStopped()
}
@Test
fun error() {
// GIVEN
// media player is playing
// WHEN
// error
fsm.post(Event.ERROR)
// THEN
// player is stopped
// error callback is invoked
assertEquals(State.STOPPED, fsm.state)
verify(delegate).onError()
}
}
}
| gpl-2.0 |
olonho/carkot | translator/src/test/kotlin/tests/string_print_test_1/string_print_test_1.kt | 1 | 219 | fun string_print_test_1_inline(): Int {
println("STRING INLINE PRINT WORKS")
return 23
}
fun string_print_test_1_variable(): Int {
val x = "STRING VARIABLE WORKS"
val y = x
println(y)
return 1
} | mit |
nextcloud/android | app/src/main/java/com/nextcloud/client/database/migrations/RoomMigration.kt | 1 | 9260 | /*
* Nextcloud Android client application
*
* @author Álvaro Brey
* Copyright (C) 2022 Álvaro Brey
* Copyright (C) 2022 Nextcloud GmbH
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or 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 <http://www.gnu.org/licenses/>.
*
*/
package com.nextcloud.client.database.migrations
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.nextcloud.client.database.NextcloudDatabase
class RoomMigration : Migration(NextcloudDatabase.FIRST_ROOM_DB_VERSION - 1, NextcloudDatabase.FIRST_ROOM_DB_VERSION) {
override fun migrate(database: SupportSQLiteDatabase) {
migrateFilesystemTable(database)
migrateUploadsTable(database)
migrateCapabilitiesTable(database)
migrateFilesTable(database)
}
/**
* filesystem table: STRING converted to TEXT
*/
private fun migrateFilesystemTable(database: SupportSQLiteDatabase) {
val newColumns = mapOf(
"_id" to TYPE_INTEGER_PRIMARY_KEY,
"local_path" to TYPE_TEXT,
"is_folder" to TYPE_INTEGER,
"found_at" to TYPE_INTEGER,
"upload_triggered" to TYPE_INTEGER,
"syncedfolder_id" to TYPE_TEXT,
"crc32" to TYPE_TEXT,
"modified_at" to TYPE_INTEGER
)
migrateTable(database, "filesystem", newColumns)
}
/**
* uploads table: LONG converted to INTEGER
*/
private fun migrateUploadsTable(database: SupportSQLiteDatabase) {
val newColumns = mapOf(
"_id" to TYPE_INTEGER_PRIMARY_KEY,
"local_path" to TYPE_TEXT,
"remote_path" to TYPE_TEXT,
"account_name" to TYPE_TEXT,
"file_size" to TYPE_INTEGER,
"status" to TYPE_INTEGER,
"local_behaviour" to TYPE_INTEGER,
"upload_time" to TYPE_INTEGER,
"name_collision_policy" to TYPE_INTEGER,
"is_create_remote_folder" to TYPE_INTEGER,
"upload_end_timestamp" to TYPE_INTEGER,
"last_result" to TYPE_INTEGER,
"is_while_charging_only" to TYPE_INTEGER,
"is_wifi_only" to TYPE_INTEGER,
"created_by" to TYPE_INTEGER,
"folder_unlock_token" to TYPE_TEXT
)
migrateTable(database, "list_of_uploads", newColumns)
}
/**
* capabilities table: "files_drop" column removed
*/
private fun migrateCapabilitiesTable(database: SupportSQLiteDatabase) {
val newColumns = mapOf(
"_id" to TYPE_INTEGER_PRIMARY_KEY,
"account" to TYPE_TEXT,
"version_mayor" to TYPE_INTEGER,
"version_minor" to TYPE_INTEGER,
"version_micro" to TYPE_INTEGER,
"version_string" to TYPE_TEXT,
"version_edition" to TYPE_TEXT,
"extended_support" to TYPE_INTEGER,
"core_pollinterval" to TYPE_INTEGER,
"sharing_api_enabled" to TYPE_INTEGER,
"sharing_public_enabled" to TYPE_INTEGER,
"sharing_public_password_enforced" to TYPE_INTEGER,
"sharing_public_expire_date_enabled" to TYPE_INTEGER,
"sharing_public_expire_date_days" to TYPE_INTEGER,
"sharing_public_expire_date_enforced" to TYPE_INTEGER,
"sharing_public_send_mail" to TYPE_INTEGER,
"sharing_public_upload" to TYPE_INTEGER,
"sharing_user_send_mail" to TYPE_INTEGER,
"sharing_resharing" to TYPE_INTEGER,
"sharing_federation_outgoing" to TYPE_INTEGER,
"sharing_federation_incoming" to TYPE_INTEGER,
"files_bigfilechunking" to TYPE_INTEGER,
"files_undelete" to TYPE_INTEGER,
"files_versioning" to TYPE_INTEGER,
"external_links" to TYPE_INTEGER,
"server_name" to TYPE_TEXT,
"server_color" to TYPE_TEXT,
"server_text_color" to TYPE_TEXT,
"server_element_color" to TYPE_TEXT,
"server_slogan" to TYPE_TEXT,
"server_logo" to TYPE_TEXT,
"background_url" to TYPE_TEXT,
"end_to_end_encryption" to TYPE_INTEGER,
"activity" to TYPE_INTEGER,
"background_default" to TYPE_INTEGER,
"background_plain" to TYPE_INTEGER,
"richdocument" to TYPE_INTEGER,
"richdocument_mimetype_list" to TYPE_TEXT,
"richdocument_direct_editing" to TYPE_INTEGER,
"richdocument_direct_templates" to TYPE_INTEGER,
"richdocument_optional_mimetype_list" to TYPE_TEXT,
"sharing_public_ask_for_optional_password" to TYPE_INTEGER,
"richdocument_product_name" to TYPE_TEXT,
"direct_editing_etag" to TYPE_TEXT,
"user_status" to TYPE_INTEGER,
"user_status_supports_emoji" to TYPE_INTEGER,
"etag" to TYPE_TEXT,
"files_locking_version" to TYPE_TEXT
)
migrateTable(database, "capabilities", newColumns)
}
/**
* files table: "public_link" column removed
*/
private fun migrateFilesTable(database: SupportSQLiteDatabase) {
val newColumns = mapOf(
"_id" to TYPE_INTEGER_PRIMARY_KEY,
"filename" to TYPE_TEXT,
"encrypted_filename" to TYPE_TEXT,
"path" to TYPE_TEXT,
"path_decrypted" to TYPE_TEXT,
"parent" to TYPE_INTEGER,
"created" to TYPE_INTEGER,
"modified" to TYPE_INTEGER,
"content_type" to TYPE_TEXT,
"content_length" to TYPE_INTEGER,
"media_path" to TYPE_TEXT,
"file_owner" to TYPE_TEXT,
"last_sync_date" to TYPE_INTEGER,
"last_sync_date_for_data" to TYPE_INTEGER,
"modified_at_last_sync_for_data" to TYPE_INTEGER,
"etag" to TYPE_TEXT,
"etag_on_server" to TYPE_TEXT,
"share_by_link" to TYPE_INTEGER,
"permissions" to TYPE_TEXT,
"remote_id" to TYPE_TEXT,
"update_thumbnail" to TYPE_INTEGER,
"is_downloading" to TYPE_INTEGER,
"favorite" to TYPE_INTEGER,
"is_encrypted" to TYPE_INTEGER,
"etag_in_conflict" to TYPE_TEXT,
"shared_via_users" to TYPE_INTEGER,
"mount_type" to TYPE_INTEGER,
"has_preview" to TYPE_INTEGER,
"unread_comments_count" to TYPE_INTEGER,
"owner_id" to TYPE_TEXT,
"owner_display_name" to TYPE_TEXT,
"note" to TYPE_TEXT,
"sharees" to TYPE_TEXT,
"rich_workspace" to TYPE_TEXT,
"metadata_size" to TYPE_TEXT,
"locked" to TYPE_INTEGER,
"lock_type" to TYPE_INTEGER,
"lock_owner" to TYPE_TEXT,
"lock_owner_display_name" to TYPE_TEXT,
"lock_owner_editor" to TYPE_TEXT,
"lock_timestamp" to TYPE_INTEGER,
"lock_timeout" to TYPE_INTEGER,
"lock_token" to TYPE_TEXT
)
migrateTable(database, "filelist", newColumns)
}
private fun migrateTable(database: SupportSQLiteDatabase, tableName: String, newColumns: Map<String, String>) {
require(newColumns.isNotEmpty())
val newTableTempName = "${tableName}_new"
createNewTable(database, newTableTempName, newColumns)
copyData(database, tableName, newTableTempName, newColumns.keys)
replaceTable(database, tableName, newTableTempName)
}
private fun createNewTable(
database: SupportSQLiteDatabase,
newTableName: String,
columns: Map<String, String>
) {
val columnsString = columns.entries.joinToString(",") { "${it.key} ${it.value}" }
database.execSQL("CREATE TABLE $newTableName ($columnsString)")
}
private fun copyData(
database: SupportSQLiteDatabase,
tableName: String,
newTableName: String,
columnNames: Iterable<String>
) {
val columnsString = columnNames.joinToString(",")
database.execSQL(
"INSERT INTO $newTableName ($columnsString) " +
"SELECT $columnsString FROM $tableName"
)
}
private fun replaceTable(
database: SupportSQLiteDatabase,
tableName: String,
newTableTempName: String
) {
database.execSQL("DROP TABLE $tableName")
database.execSQL("ALTER TABLE $newTableTempName RENAME TO $tableName")
}
companion object {
private const val TYPE_TEXT = "TEXT"
private const val TYPE_INTEGER = "INTEGER"
private const val TYPE_INTEGER_PRIMARY_KEY = "INTEGER PRIMARY KEY"
}
}
| gpl-2.0 |
Karumi/Shot | shot-android/src/androidTest/java/com/karumi/shot/DexOpenerJUnitRunner.kt | 1 | 440 | package com.karumi.shot
import android.app.Application
import android.content.Context
import androidx.test.runner.AndroidJUnitRunner
import com.github.tmurakami.dexopener.DexOpener
class DexOpenerJUnitRunner : AndroidJUnitRunner() {
override fun newApplication(cl: ClassLoader?, className: String?, context: Context?): Application {
DexOpener.install(this)
return super.newApplication(cl, className, context)
}
}
| apache-2.0 |
kiruto/kotlin-android-mahjong | app/src/main/java/dev/yuriel/mahjan/texture/TileMgr.kt | 1 | 2839 | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 yuriel<[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package dev.yuriel.mahjan.texture
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.TextureAtlas
import com.badlogic.gdx.graphics.g2d.TextureRegion
import dev.yuriel.kotmahjan.models.Hai
import dev.yuriel.kotmahjan.models.HaiType
import dev.yuriel.kotmahjan.models.UnbelievableException
/**
* Created by yuriel on 8/5/16.
*/
object TileMgr: NormalTextureMgr("tiles.txt") {
operator fun get(hai: Hai): TextureRegion? {
val name = findTextureNameByHai(hai)
return this[name]
}
fun getBack(): TextureRegion? {
return this["back"]
}
fun getObverse(): TextureRegion? {
return this["back_side"]
}
private fun findTextureNameByHai(hai: Hai): String {
fun normal(hai: Hai): String {
val fileName: String
val haiName = hai.toString()
when (haiName.length) {
2 -> fileName = haiName
3 -> {
when(haiName.first()) {
'p' -> fileName = "aka1"
's' -> fileName = "aka2"
'm' -> fileName = "aka3"
else -> throw UnbelievableException()
}
}
else -> throw UnbelievableException()
}
return fileName
}
return when(hai.type) {
HaiType.E -> "ji1"
HaiType.S -> "ji2"
HaiType.W -> "ji3"
HaiType.N -> "ji4"
HaiType.D -> "ji5"
HaiType.H -> "ji6"
HaiType.T -> "ji7"
else -> normal(hai)
}
}
} | mit |
HedvigInsurance/bot-service | src/main/java/com/hedvig/botService/chat/StatusBuilderImpl.kt | 1 | 5799 | package com.hedvig.botService.chat
import com.hedvig.libs.translations.Translations
import java.time.DayOfWeek
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.Month
import java.util.Locale
import org.springframework.stereotype.Component
@Component
class StatusBuilderImpl(
private val translations: Translations
) : StatusBuilder {
override fun getStatusReplyMessage(now: LocalDateTime, locale: Locale): String {
val today = LocalDate.from(now)
val dayOfWeek = today.dayOfWeek!!
val hour = now.hour
val minute = now.minute
if (isChristmasPeriod(today)) {
return getRepliesOnChristmasDayReply(locale)
}
if (isUnderstaffedDay(today)) {
return getLongResponseWindowDayReply(
locale = locale,
dayStartHour = 10,
dayEndHour = 18,
hour = hour
)
}
if (isRedDay(today)) {
return getLongResponseWindowDayReply(
locale = locale,
dayStartHour = 10,
dayEndHour = 18,
hour = hour
)
}
if (isHedvigParty(today)){
return getHedvigPartyReply(
locale = locale,
hour = hour
)
}
return when (dayOfWeek) {
DayOfWeek.MONDAY,
DayOfWeek.TUESDAY,
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY,
DayOfWeek.FRIDAY -> getRegularWeekdayReply(locale, dayOfWeek, hour, minute)
DayOfWeek.SATURDAY,
DayOfWeek.SUNDAY -> getLongResponseWindowDayReply(
locale = locale,
dayStartHour = 10,
dayEndHour = 22,
hour = hour
)
}
}
private fun getRegularWeekdayReply(
locale: Locale,
dayOfWeek: DayOfWeek,
hour: Int,
minute: Int
) = when {
isRetroMeeting(dayOfWeek, hour, minute) ->
getRepliesWithinMinutes(locale, maxOf(RETRO_END_MINUTE - minute + minute % 5, 10))
hour < 3 -> getRepliesTomorrow(locale)
hour < 8 -> getRepliesAfterHour(locale, 8)
hour < 17 -> getRepliesWithinMinutes(locale, 10)
hour < 20 -> getRepliesWithinMinutes(locale, 20)
hour < 22 -> getRepliesWithinMinutes(locale, 30)
else -> getRepliesTomorrow(locale)
}
private fun getLongResponseWindowDayReply(
locale: Locale,
dayStartHour: Int,
dayEndHour: Int,
hour: Int
) = when {
hour < 3 -> getRepliesTomorrow(locale)
hour < dayStartHour -> getRepliesAfterHour(locale, dayStartHour)
hour < dayEndHour -> getRepliesWithinAnHour(locale)
else -> getRepliesTomorrow(locale)
}
private fun isRetroMeeting(dayOfWeek: DayOfWeek, hour: Int, minute: Int) =
dayOfWeek == RETRO_DAY && hour == RETRO_START_HOUR && minute <= RETRO_END_MINUTE
private fun getRepliesTomorrow(locale: Locale): String =
translations.get("BOT_SERVICE_STATUS_REPLY_TOMORROW", locale)
?: "BOT_SERVICE_STATUS_REPLY_TOMORROW"
private fun getRepliesAfterHour(locale: Locale, hour: Int): String {
val text = translations.get("BOT_SERVICE_STATUS_REPLY_AFTER_HOUR_OF_DAY", locale)
?: "BOT_SERVICE_STATUS_REPLY_AFTER_HOUR_OF_DAY"
return text.replace("{HOUR_OF_DAY}", hour.toString())
}
private fun getRepliesWithinAnHour(locale: Locale) =
translations.get("BOT_SERVICE_STATUS_REPLY_WITHIN_AN_HOUR", locale)
?: "BOT_SERVICE_STATUS_REPLY_WITHIN_AN_HOUR"
private fun getRepliesWithinMinutes(locale: Locale, minutes: Int): String {
val text = translations.get("BOT_SERVICE_STATUS_REPLY_WITHIN_MIN", locale)
?: "BOT_SERVICE_STATUS_REPLY_WITHIN_MIN"
return text.replace("{MINUTES}", minutes.toString())
}
private fun getRepliesOnChristmasDayReply(locale: Locale) =
translations.get("BOT_SERVICE_STATUS_REPLY_CHRISTMAS_DAY", locale)
?: "BOT_SERVICE_STATUS_REPLY_CHRISTMAS_DAY"
private fun isChristmasPeriod(date: LocalDate) =
date.month == Month.DECEMBER && (date.dayOfMonth == 23 || date.dayOfMonth == 24)
private fun isUnderstaffedDay(date: LocalDate) = UNDERSTAFFED_DAYS.contains(date)
private fun isRedDay(date: LocalDate) = RED_DAYS.contains(date)
private fun isHedvigParty(date: LocalDate) = date == LocalDate.of(2021, 8,31)
private fun getHedvigPartyReply(
locale: Locale,
hour: Int
) = when {
hour < 7 -> getRepliesTomorrow(locale)
hour < 8 -> getRepliesAfterHour(locale, 8)
hour < 16 -> getRepliesWithinMinutes(locale, 10)
else -> getRepliesTomorrow(locale)
}
companion object {
private val RETRO_DAY = DayOfWeek.FRIDAY
const val RETRO_START_HOUR = 11
const val RETRO_END_MINUTE = 45
private val UNDERSTAFFED_DAYS = setOf(
LocalDate.of(2020, 12, 25),
LocalDate.of(2020, 12, 26),
LocalDate.of(2020, 12, 27),
LocalDate.of(2020, 12, 31),
LocalDate.of(2021, 1, 1)
)
private val RED_DAYS = setOf(
LocalDate.of(2021, 1, 1),
LocalDate.of(2021, 1, 6),
LocalDate.of(2021, 4, 2),
LocalDate.of(2021, 4, 4),
LocalDate.of(2021, 4, 5),
LocalDate.of(2021, 5, 1),
LocalDate.of(2021, 5, 13),
LocalDate.of(2021, 5, 23),
LocalDate.of(2021, 6, 6),
LocalDate.of(2021, 6, 26),
LocalDate.of(2021, 11, 6),
LocalDate.of(2021, 12, 25),
LocalDate.of(2021, 12, 26)
)
}
}
| agpl-3.0 |
shlusiak/Freebloks-Android | game/src/main/java/de/saschahlusiak/freebloks/network/message/MessageRequestPlayer.kt | 1 | 1040 | package de.saschahlusiak.freebloks.network.message
import de.saschahlusiak.freebloks.network.*
import de.saschahlusiak.freebloks.utils.put
import java.nio.ByteBuffer
data class MessageRequestPlayer(val player: Int, val name: String?): Message(MessageType.RequestPlayer, 17) {
init {
assert(player in -1..3) { "player $player must be between -1 and 3"}
}
override fun write(buffer: ByteBuffer) {
super.write(buffer)
buffer.put(player.toByte())
val bytes = name?.toByteArray() ?: ByteArray(0)
buffer.put(bytes, 15).put(0)
}
companion object {
fun from(data: ByteBuffer): MessageRequestPlayer {
val player = data.get().toInt()
val bytes = ByteArray(16) { data.get() }
val length = bytes.indexOfFirst { it == 0.toByte() }
val name = if (length < 0) String(bytes, Charsets.UTF_8) else String(bytes, 0, length, Charsets.UTF_8)
return MessageRequestPlayer(player, name.trimEnd().ifEmpty { null })
}
}
} | gpl-2.0 |
niranjan94/show-java | app/src/androidTest/kotlin/com/njlabs/showjava/test/decompilers/dex/DexViaJadx.kt | 1 | 1160 | /*
* Show Java - A java/apk decompiler for android
* Copyright (c) 2018 Niranjan Rajendran
*
* 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.njlabs.showjava.test.decompilers.dex
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.njlabs.showjava.test.DecompilerTestBase
import com.njlabs.showjava.data.PackageInfo
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DexViaJadx: DecompilerTestBase() {
override val type: PackageInfo.Type = PackageInfo.Type.DEX
override val decompiler: String = "jadx"
} | gpl-3.0 |
BilledTrain380/sporttag-psa | app/psa-runtime-service/psa-service-group/src/main/kotlin/ch/schulealtendorf/psa/service/group/business/GroupImportManagerImpl.kt | 1 | 3748 | /*
* Copyright (c) 2018 by Nicolas Märchy
*
* This file is part of Sporttag PSA.
*
* Sporttag PSA 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.
*
* Sporttag PSA 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 Sporttag PSA. If not, see <http://www.gnu.org/licenses/>.
*
* Diese Datei ist Teil von Sporttag PSA.
*
* Sporttag PSA ist Freie Software: Sie können es unter den Bedingungen
* der GNU General Public License, wie von der Free Software Foundation,
* Version 3 der Lizenz oder (nach Ihrer Wahl) jeder späteren
* veröffentlichten Version, weiterverbreiten und/oder modifizieren.
*
* Sporttag PSA wird in der Hoffnung, dass es nützlich sein wird, aber
* OHNE JEDE GEWÄHRLEISTUNG, bereitgestellt; sogar ohne die implizite
* Gewährleistung der MARKTFÄHIGKEIT oder EIGNUNG FÜR EINEN BESTIMMTEN ZWECK.
* Siehe die GNU General Public License für weitere Details.
*
* Sie sollten eine Kopie der GNU General Public License zusammen mit diesem
* Programm erhalten haben. Wenn nicht, siehe <http://www.gnu.org/licenses/>.
*
*
*/
package ch.schulealtendorf.psa.service.group.business
import ch.schulealtendorf.psa.service.group.business.parsing.FlatParticipant
import ch.schulealtendorf.psa.service.standard.entity.CoachEntity
import ch.schulealtendorf.psa.service.standard.entity.GroupEntity
import ch.schulealtendorf.psa.service.standard.entity.ParticipantEntity
import ch.schulealtendorf.psa.service.standard.entity.TownEntity
import ch.schulealtendorf.psa.service.standard.repository.CoachRepository
import ch.schulealtendorf.psa.service.standard.repository.GroupRepository
import ch.schulealtendorf.psa.service.standard.repository.ParticipantRepository
import ch.schulealtendorf.psa.service.standard.repository.TownRepository
import mu.KotlinLogging
import org.springframework.stereotype.Component
/**
* A {@link GroupManager} which uses repositories to process its data.
*
* @author nmaerchy <[email protected]>
* @since 2.0.0
*/
@Component
class GroupImportManagerImpl(
private val groupRepository: GroupRepository,
private val participantRepository: ParticipantRepository,
private val coachRepository: CoachRepository,
private val townRepository: TownRepository
) : GroupImportManager {
private val log = KotlinLogging.logger {}
override fun import(participant: FlatParticipant) {
log.debug { "Import Participant ${participant.prename} ${participant.surname}" }
val town = townRepository.findByZipAndName(participant.zipCode, participant.town)
.orElseGet { TownEntity(zip = participant.zipCode, name = participant.town) }
val coach = coachRepository.findByName(participant.coach)
.orElseGet { CoachEntity(name = participant.coach) }
val group = groupRepository.findByName(participant.group)
.orElseGet { GroupEntity(participant.group, coach) }
val participantEntity = ParticipantEntity(
surname = participant.surname,
prename = participant.prename,
gender = participant.gender,
birthday = participant.birthday.value,
address = participant.address,
town = town,
group = group
)
participantRepository.save(participantEntity)
}
}
| gpl-3.0 |
wikimedia/apps-android-wikipedia | app/src/main/java/org/wikipedia/feed/FeedFragment.kt | 1 | 15812 | package org.wikipedia.feed
import android.net.Uri
import android.os.Bundle
import android.util.Pair
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.RecyclerView
import org.wikipedia.BackPressedHandler
import org.wikipedia.Constants.InvokeSource
import org.wikipedia.R
import org.wikipedia.WikipediaApp
import org.wikipedia.activity.FragmentUtil.getCallback
import org.wikipedia.analytics.FeedFunnel
import org.wikipedia.databinding.FragmentFeedBinding
import org.wikipedia.feed.FeedCoordinatorBase.FeedUpdateListener
import org.wikipedia.feed.configure.ConfigureActivity
import org.wikipedia.feed.configure.ConfigureItemLanguageDialogView
import org.wikipedia.feed.configure.LanguageItemAdapter
import org.wikipedia.feed.image.FeaturedImage
import org.wikipedia.feed.image.FeaturedImageCard
import org.wikipedia.feed.model.Card
import org.wikipedia.feed.model.WikiSiteCard
import org.wikipedia.feed.news.NewsCard
import org.wikipedia.feed.news.NewsItemView
import org.wikipedia.feed.random.RandomCardView
import org.wikipedia.feed.topread.TopReadArticlesActivity
import org.wikipedia.feed.topread.TopReadListCard
import org.wikipedia.feed.view.FeedAdapter
import org.wikipedia.history.HistoryEntry
import org.wikipedia.language.AppLanguageLookUpTable
import org.wikipedia.random.RandomActivity
import org.wikipedia.readinglist.sync.ReadingListSyncAdapter
import org.wikipedia.settings.Prefs
import org.wikipedia.settings.SettingsActivity
import org.wikipedia.settings.languages.WikipediaLanguagesActivity
import org.wikipedia.util.FeedbackUtil
import org.wikipedia.util.ResourceUtil
import org.wikipedia.util.UriUtil
class FeedFragment : Fragment(), BackPressedHandler {
private var _binding: FragmentFeedBinding? = null
private val binding get() = _binding!!
private lateinit var feedAdapter: FeedAdapter<View>
private val feedCallback = FeedCallback()
private val feedScrollListener = FeedScrollListener()
private val callback get() = getCallback(this, Callback::class.java)
private var app: WikipediaApp = WikipediaApp.instance
private var coordinator: FeedCoordinator = FeedCoordinator(app)
private var funnel: FeedFunnel = FeedFunnel(app)
private var shouldElevateToolbar = false
interface Callback {
fun onFeedSearchRequested(view: View)
fun onFeedVoiceSearchRequested()
fun onFeedSelectPage(entry: HistoryEntry, openInNewBackgroundTab: Boolean)
fun onFeedSelectPageWithAnimation(entry: HistoryEntry, sharedElements: Array<Pair<View, String>>)
fun onFeedAddPageToList(entry: HistoryEntry, addToDefault: Boolean)
fun onFeedMovePageToList(sourceReadingListId: Long, entry: HistoryEntry)
fun onFeedNewsItemSelected(card: NewsCard, view: NewsItemView)
fun onFeedSeCardFooterClicked()
fun onFeedShareImage(card: FeaturedImageCard)
fun onFeedDownloadImage(image: FeaturedImage)
fun onFeaturedImageSelected(card: FeaturedImageCard)
fun onLoginRequested()
fun updateToolbarElevation(elevate: Boolean)
}
private val requestFeedConfigurationLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == SettingsActivity.ACTIVITY_RESULT_FEED_CONFIGURATION_CHANGED) {
coordinator.updateHiddenCards()
refresh()
}
}
private val requestLanguageChangeLauncher = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == SettingsActivity.ACTIVITY_RESULT_LANGUAGE_CHANGED) {
refresh()
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
coordinator.more(app.wikiSite)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
super.onCreateView(inflater, container, savedInstanceState)
_binding = FragmentFeedBinding.inflate(inflater, container, false)
feedAdapter = FeedAdapter(coordinator, feedCallback)
binding.feedView.adapter = feedAdapter
binding.feedView.addOnScrollListener(feedScrollListener)
binding.swipeRefreshLayout.setColorSchemeResources(ResourceUtil.getThemedAttributeId(requireContext(), R.attr.colorAccent))
binding.swipeRefreshLayout.setOnRefreshListener { refresh() }
binding.customizeButton.setOnClickListener { showConfigureActivity(-1) }
coordinator.setFeedUpdateListener(object : FeedUpdateListener {
override fun insert(card: Card, pos: Int) {
if (isAdded) {
binding.swipeRefreshLayout.isRefreshing = false
feedAdapter.notifyItemInserted(pos)
}
}
override fun remove(card: Card, pos: Int) {
if (isAdded) {
binding.swipeRefreshLayout.isRefreshing = false
feedAdapter.notifyItemRemoved(pos)
}
}
override fun finished(shouldUpdatePreviousCard: Boolean) {
if (!isAdded) {
return
}
if (feedAdapter.itemCount < 2) {
binding.emptyContainer.visibility = View.VISIBLE
} else {
if (shouldUpdatePreviousCard) {
feedAdapter.notifyItemChanged(feedAdapter.itemCount - 1)
}
}
}
})
callback?.updateToolbarElevation(shouldElevateToolbar())
ReadingListSyncAdapter.manualSync()
Prefs.incrementExploreFeedVisitCount()
return binding.root
}
private fun showRemoveChineseVariantPrompt() {
if (app.languageState.appLanguageCodes.contains(AppLanguageLookUpTable.TRADITIONAL_CHINESE_LANGUAGE_CODE) &&
app.languageState.appLanguageCodes.contains(AppLanguageLookUpTable.SIMPLIFIED_CHINESE_LANGUAGE_CODE) &&
Prefs.shouldShowRemoveChineseVariantPrompt) {
AlertDialog.Builder(requireActivity())
.setTitle(R.string.dialog_of_remove_chinese_variants_from_app_lang_title)
.setMessage(R.string.dialog_of_remove_chinese_variants_from_app_lang_text)
.setPositiveButton(R.string.dialog_of_remove_chinese_variants_from_app_lang_edit) { _, _ -> showLanguagesActivity(InvokeSource.LANG_VARIANT_DIALOG) }
.setNegativeButton(R.string.dialog_of_remove_chinese_variants_from_app_lang_no, null)
.show()
}
Prefs.shouldShowRemoveChineseVariantPrompt = false
}
override fun onResume() {
super.onResume()
showRemoveChineseVariantPrompt()
funnel.enter()
// Explicitly invalidate the feed adapter, since it occasionally crashes the StaggeredGridLayout
// on certain devices. (TODO: investigate further)
feedAdapter.notifyDataSetChanged()
}
override fun onPause() {
super.onPause()
funnel.exit()
}
override fun onDestroyView() {
coordinator.setFeedUpdateListener(null)
binding.swipeRefreshLayout.setOnRefreshListener(null)
binding.feedView.removeOnScrollListener(feedScrollListener)
binding.feedView.adapter = null
_binding = null
super.onDestroyView()
}
override fun onDestroy() {
super.onDestroy()
coordinator.reset()
}
override fun onBackPressed(): Boolean {
return false
}
fun shouldElevateToolbar(): Boolean {
return shouldElevateToolbar
}
fun scrollToTop() {
binding.feedView.smoothScrollToPosition(0)
}
fun onGoOffline() {
feedAdapter.notifyDataSetChanged()
coordinator.requestOfflineCard()
}
fun onGoOnline() {
feedAdapter.notifyDataSetChanged()
coordinator.removeOfflineCard()
coordinator.incrementAge()
coordinator.more(app.wikiSite)
}
fun refresh() {
funnel.refresh(coordinator.age)
binding.emptyContainer.visibility = View.GONE
coordinator.reset()
feedAdapter.notifyDataSetChanged()
coordinator.more(app.wikiSite)
}
fun updateHiddenCards() {
coordinator.updateHiddenCards()
}
private inner class FeedCallback : FeedAdapter.Callback {
override fun onShowCard(card: Card?) {
card?.let {
funnel.cardShown(it.type(), getCardLanguageCode(it))
}
}
override fun onRequestMore() {
funnel.requestMore(coordinator.age)
binding.feedView.post {
if (isAdded) {
coordinator.incrementAge()
coordinator.more(app.wikiSite)
}
}
}
override fun onRetryFromOffline() {
refresh()
}
override fun onError(t: Throwable) {
FeedbackUtil.showError(requireActivity(), t)
}
override fun onSelectPage(card: Card, entry: HistoryEntry, openInNewBackgroundTab: Boolean) {
callback?.let {
it.onFeedSelectPage(entry, openInNewBackgroundTab)
funnel.cardClicked(card.type(), getCardLanguageCode(card))
}
}
override fun onSelectPage(card: Card, entry: HistoryEntry, sharedElements: Array<Pair<View, String>>) {
callback?.let {
it.onFeedSelectPageWithAnimation(entry, sharedElements)
funnel.cardClicked(card.type(), getCardLanguageCode(card))
}
}
override fun onAddPageToList(entry: HistoryEntry, addToDefault: Boolean) {
callback?.onFeedAddPageToList(entry, addToDefault)
}
override fun onMovePageToList(sourceReadingListId: Long, entry: HistoryEntry) {
callback?.onFeedMovePageToList(sourceReadingListId, entry)
}
override fun onSearchRequested(view: View) {
callback?.onFeedSearchRequested(view)
}
override fun onVoiceSearchRequested() {
callback?.onFeedVoiceSearchRequested()
}
override fun onRequestDismissCard(card: Card): Boolean {
val position = coordinator.dismissCard(card)
if (position < 0) {
return false
}
funnel.dismissCard(card.type(), position)
showDismissCardUndoSnackbar(card, position)
return true
}
override fun onRequestEditCardLanguages(card: Card) {
showCardLangSelectDialog(card)
}
override fun onRequestCustomize(card: Card) {
showConfigureActivity(card.type().code())
}
override fun onNewsItemSelected(card: NewsCard, view: NewsItemView) {
callback?.let {
it.onFeedNewsItemSelected(card, view)
funnel.cardClicked(card.type(), card.wikiSite().languageCode)
}
}
override fun onShareImage(card: FeaturedImageCard) {
callback?.onFeedShareImage(card)
}
override fun onDownloadImage(image: FeaturedImage) {
callback?.onFeedDownloadImage(image)
}
override fun onFeaturedImageSelected(card: FeaturedImageCard) {
callback?.let {
it.onFeaturedImageSelected(card)
funnel.cardClicked(card.type(), null)
}
}
override fun onAnnouncementPositiveAction(card: Card, uri: Uri) {
funnel.cardClicked(card.type(), getCardLanguageCode(card))
when {
uri.toString() == UriUtil.LOCAL_URL_LOGIN -> callback?.onLoginRequested()
uri.toString() == UriUtil.LOCAL_URL_SETTINGS -> requestLanguageChangeLauncher.launch(SettingsActivity.newIntent(requireContext()))
uri.toString() == UriUtil.LOCAL_URL_CUSTOMIZE_FEED -> {
showConfigureActivity(card.type().code())
onRequestDismissCard(card)
}
uri.toString() == UriUtil.LOCAL_URL_LANGUAGES -> showLanguagesActivity(InvokeSource.ANNOUNCEMENT)
else -> UriUtil.handleExternalLink(requireContext(), uri)
}
}
override fun onAnnouncementNegativeAction(card: Card) {
onRequestDismissCard(card)
}
override fun onRandomClick(view: RandomCardView) {
view.card?.let {
startActivity(RandomActivity.newIntent(requireActivity(), it.wikiSite(), InvokeSource.FEED))
}
}
override fun onFooterClick(card: Card) {
if (card is TopReadListCard) {
startActivity(TopReadArticlesActivity.newIntent(requireContext(), card))
}
}
override fun onSeCardFooterClicked() {
callback?.onFeedSeCardFooterClicked()
}
}
private inner class FeedScrollListener : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
super.onScrolled(recyclerView, dx, dy)
val shouldElevate = binding.feedView.firstVisibleItemPosition != 0
if (shouldElevate != shouldElevateToolbar) {
shouldElevateToolbar = shouldElevate
requireActivity().invalidateOptionsMenu()
callback?.updateToolbarElevation(shouldElevateToolbar())
}
}
}
private fun showDismissCardUndoSnackbar(card: Card, position: Int) {
val snackbar = FeedbackUtil.makeSnackbar(requireActivity(), getString(R.string.menu_feed_card_dismissed))
snackbar.setAction(R.string.reading_list_item_delete_undo) { coordinator.undoDismissCard(card, position) }
snackbar.show()
}
private fun showCardLangSelectDialog(card: Card) {
val contentType = card.type().contentType()
if (contentType != null && contentType.isPerLanguage) {
val adapter = LanguageItemAdapter(requireContext(), contentType)
val view = ConfigureItemLanguageDialogView(requireContext())
val tempDisabledList = ArrayList(contentType.langCodesDisabled)
view.setContentType(adapter.langList, tempDisabledList)
AlertDialog.Builder(requireContext())
.setView(view)
.setTitle(contentType.titleId)
.setPositiveButton(R.string.feed_lang_selection_dialog_ok_button_text) { _, _ ->
contentType.langCodesDisabled.clear()
contentType.langCodesDisabled.addAll(tempDisabledList)
refresh()
}
.setNegativeButton(R.string.feed_lang_selection_dialog_cancel_button_text, null)
.create()
.show()
}
}
private fun showConfigureActivity(invokeSource: Int) {
requestFeedConfigurationLauncher.launch(ConfigureActivity.newIntent(requireActivity(), invokeSource))
}
private fun showLanguagesActivity(invokeSource: InvokeSource) {
requestLanguageChangeLauncher.launch(WikipediaLanguagesActivity.newIntent(requireActivity(), invokeSource))
}
private fun getCardLanguageCode(card: Card?): String? {
return if (card is WikiSiteCard) card.wikiSite().languageCode else null
}
companion object {
fun newInstance(): FeedFragment {
return FeedFragment().apply {
retainInstance = true
}
}
}
}
| apache-2.0 |
vanita5/twittnuker | twittnuker/src/main/kotlin/de/vanita5/twittnuker/preference/HiddenSettingEntryPreference.kt | 1 | 2157 | /*
* Twittnuker - Twitter client for Android
*
* Copyright (C) 2013-2017 vanita5 <[email protected]>
*
* This program incorporates a modified version of Twidere.
* Copyright (C) 2012-2017 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.vanita5.twittnuker.preference
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.support.v7.preference.Preference
import android.support.v7.preference.PreferenceManager
import android.util.AttributeSet
import de.vanita5.twittnuker.constant.IntentConstants.INTENT_ACTION_HIDDEN_SETTINGS_ENTRY
class HiddenSettingEntryPreference(
context: Context,
attrs: AttributeSet? = null
) : TintedPreferenceCategory(context, attrs) {
@SuppressLint("RestrictedApi")
override fun onAttachedToHierarchy(preferenceManager: PreferenceManager?, id: Long) {
super.onAttachedToHierarchy(preferenceManager, id)
removeAll()
val entryIntent = Intent(INTENT_ACTION_HIDDEN_SETTINGS_ENTRY)
entryIntent.`package` = context.packageName
context.packageManager.queryIntentActivities(entryIntent, 0).forEach { resolveInfo ->
val activityInfo = resolveInfo.activityInfo
addPreference(Preference(context).apply {
title = activityInfo.loadLabel(context.packageManager)
intent = Intent(INTENT_ACTION_HIDDEN_SETTINGS_ENTRY).setClassName(context, activityInfo.name)
})
}
}
} | gpl-3.0 |
hummatli/MAHAndroidUpdater | android-app-updater/src/main/java/com/mobapphome/androidappupdater/tools/LocaleUpdater.kt | 1 | 488 | package com.mobapphome.androidappupdater.tools
import android.content.Context
import java.util.Locale
object LocaleUpdater {
private fun updateLocale(context: Context, language: String) {
val locale = Locale(language)
Locale.setDefault(locale)
val resources = context.resources
val configuration = resources.configuration
configuration.locale = locale
resources.updateConfiguration(configuration, resources.displayMetrics)
}
} | apache-2.0 |
stripe/stripe-android | payments-core/src/test/java/com/stripe/android/model/CardFixtures.kt | 1 | 2894 | package com.stripe.android.model
import com.stripe.android.model.parsers.CardJsonParser
import org.json.JSONObject
object CardFixtures {
internal val CARD = Card(
expMonth = 8,
expYear = 2050,
addressLine1 = AddressFixtures.ADDRESS.line1,
addressLine2 = AddressFixtures.ADDRESS.line2,
addressCity = AddressFixtures.ADDRESS.city,
addressCountry = AddressFixtures.ADDRESS.country,
addressState = AddressFixtures.ADDRESS.state,
addressZip = AddressFixtures.ADDRESS.postalCode,
currency = "USD",
name = "Jenny Rosen",
brand = CardBrand.Visa,
last4 = "4242",
id = "id"
)
internal val CARD_USD_JSON = JSONObject(
"""
{
"id": "card_189fi32eZvKYlo2CHK8NPRME",
"object": "card",
"address_city": "San Francisco",
"address_country": "US",
"address_line1": "123 Market St",
"address_line1_check": "unavailable",
"address_line2": "#345",
"address_state": "CA",
"address_zip": "94107",
"address_zip_check": "unavailable",
"brand": "Visa",
"country": "US",
"currency": "usd",
"customer": "customer77",
"cvc_check": "unavailable",
"exp_month": 8,
"exp_year": 2017,
"funding": "credit",
"fingerprint": "abc123",
"last4": "4242",
"name": "Jenny Rosen",
"metadata": {
"color": "blue",
"animal": "dog"
}
}
""".trimIndent()
)
internal val CARD_USD = requireNotNull(CardJsonParser().parse(CARD_USD_JSON))
internal val CARD_GOOGLE_PAY = requireNotNull(
CardJsonParser().parse(
JSONObject(
"""
{
"id": "card_189fi32eZvKYlo2CHK8NPRME",
"object": "card",
"address_city": "Des Moines",
"address_country": "US",
"address_line1": "123 Any Street",
"address_line1_check": "unavailable",
"address_line2": "456",
"address_state": "IA",
"address_zip": "50305",
"address_zip_check": "unavailable",
"brand": "Visa",
"country": "US",
"currency": "usd",
"customer": "customer77",
"cvc_check": "unavailable",
"exp_month": 8,
"exp_year": 2017,
"funding": "credit",
"fingerprint": "abc123",
"last4": "4242",
"name": "John Cardholder",
"tokenization_method": "android_pay",
"metadata": {
"color": "blue",
"animal": "dog"
}
}
""".trimIndent()
)
)
)
}
| mit |
joffrey-bion/mc-mining-optimizer | src/main/kotlin/org/hildan/minecraft/mining/optimizer/patterns/tunnels/TunnelSection.kt | 1 | 1259 | package org.hildan.minecraft.mining.optimizer.patterns.tunnels
import org.hildan.minecraft.mining.optimizer.blocks.Sample
/**
* Describes the dimensions of a 2D section of a tunnel.
*/
data class TunnelSection(val width: Int, val height: Int) {
fun digInto(sample: Sample, originX: Int, originY: Int, originZ: Int, length: Int, direction: Axis) {
val xMax = originX + getSizeOnAxis(Axis.X, direction, length)
val yMax = originY + getSizeOnAxis(Axis.Y, direction, length)
val zMax = originZ + getSizeOnAxis(Axis.Z, direction, length)
for (x in originX until Math.min(xMax, sample.dimensions.width)) {
for (y in originY until Math.min(yMax, sample.dimensions.height)) {
for (z in originZ until Math.min(zMax, sample.dimensions.length)) {
sample.digBlock(x, y, z)
}
}
}
}
private fun getSizeOnAxis(axis: Axis, tunnelDirection: Axis, length: Int): Int = when (axis) {
tunnelDirection -> length
Axis.Y -> height
else -> width
}
companion object {
val MAN_SIZED = TunnelSection(1, 2)
val DOUBLE_MAN_SIZED = TunnelSection(2, 2)
val BIG_CORRIDOR = TunnelSection(2, 3)
}
}
| mit |
exponent/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/sensors/modules/MagnetometerModule.kt | 2 | 1799 | // Copyright 2015-present 650 Industries. All rights reserved.
package abi44_0_0.expo.modules.sensors.modules
import android.content.Context
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorManager
import android.os.Bundle
import abi44_0_0.expo.modules.interfaces.sensors.SensorServiceInterface
import abi44_0_0.expo.modules.interfaces.sensors.services.MagnetometerServiceInterface
import abi44_0_0.expo.modules.core.Promise
import abi44_0_0.expo.modules.core.interfaces.ExpoMethod
class MagnetometerModule(reactContext: Context?) : BaseSensorModule(reactContext) {
override val eventName: String = "magnetometerDidUpdate"
override fun getName(): String = "ExponentMagnetometer"
override fun getSensorService(): SensorServiceInterface {
return moduleRegistry.getModule(MagnetometerServiceInterface::class.java)
}
override fun eventToMap(sensorEvent: SensorEvent): Bundle {
return Bundle().apply {
putDouble("x", sensorEvent.values[0].toDouble())
putDouble("y", sensorEvent.values[1].toDouble())
putDouble("z", sensorEvent.values[2].toDouble())
}
}
@ExpoMethod
fun startObserving(promise: Promise) {
super.startObserving()
promise.resolve(null)
}
@ExpoMethod
fun stopObserving(promise: Promise) {
super.stopObserving()
promise.resolve(null)
}
@ExpoMethod
fun setUpdateInterval(updateInterval: Int, promise: Promise) {
super.setUpdateInterval(updateInterval)
promise.resolve(null)
}
@ExpoMethod
fun isAvailableAsync(promise: Promise) {
val mSensorManager = context.getSystemService(Context.SENSOR_SERVICE) as SensorManager
val isAvailable = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD) != null
promise.resolve(isAvailable)
}
}
| bsd-3-clause |
joaoevangelista/Convertx | app/src/main/kotlin/io/github/joaoevangelista/convertx/op/ConversionExecutor.kt | 1 | 937 | package io.github.joaoevangelista.convertx.op
import io.github.joaoevangelista.convertx.activity.UnitsSelectedHolder
/**
* @author Joao Pedro Evangelista
*/
class ConversionExecutor {
fun execute(input: String,
onResult: (result: Double) -> Unit): Unit {
if (!input.isBlank()) {
val number = input.toDouble()
val from = UnitsSelectedHolder.fromUnit
val to = UnitsSelectedHolder.toUnit
if (to != null && from != null) {
when (from) {
is Lengths -> onResult(Conversions.ofLength(number, from, to as Lengths?).value as Double)
is Temperatures -> onResult(
Conversions.ofTemperature(number, from, to as Temperatures?).value as Double)
is Areas -> onResult(Conversions.ofArea(number, from, to as Areas?).value as Double)
is Volumes -> onResult(Conversions.ofVolume(number, from, to as Volumes?).value as Double)
}
}
}
}
}
| apache-2.0 |
peervalhoegen/SudoQ | sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/controller/menus/SudokuLoadingActivity.kt | 1 | 16407 | /*
* SudoQ is a Sudoku-App for Adroid Devices with Version 2.2 at least.
* Copyright (C) 2012 Heiko Klare, Julian Geppert, Jan-Bernhard Kordaß, Jonathan Kieling, Tim Zeitz, Timo Abele
* This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
* You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
package de.sudoq.controller.menus
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.*
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.AdapterView.OnItemLongClickListener
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.google.android.material.floatingactionbutton.FloatingActionButton
import de.sudoq.R
import de.sudoq.controller.SudoqListActivity
import de.sudoq.controller.sudoku.SudokuActivity
import de.sudoq.model.game.GameData
import de.sudoq.model.game.GameManager
import de.sudoq.model.persistence.xml.game.IGamesListRepo
import de.sudoq.model.profile.ProfileManager
import de.sudoq.persistence.game.GameRepo
import de.sudoq.persistence.game.GamesListRepo
import de.sudoq.persistence.profile.ProfileRepo
import de.sudoq.persistence.profile.ProfilesListRepo
import de.sudoq.persistence.sudokuType.SudokuTypeRepo
import java.io.*
import java.nio.charset.Charset
import java.util.*
/**
* Diese Klasse repräsentiert den Lade-Controller des Sudokuspiels. Mithilfe von
* SudokuLoading können Sudokus geladen werden und daraufhin zur SudokuActivity
* gewechselt werden.
*/
class SudokuLoadingActivity : SudoqListActivity(), OnItemClickListener, OnItemLongClickListener {
/** Attributes */
private var profileManager: ProfileManager? = null
private var adapter: SudokuLoadingAdapter? = null
private var games: List<GameData>? = null
private lateinit var profilesDir: File
private lateinit var sudokuDir: File
private lateinit var sudokuTypeRepo: SudokuTypeRepo
private lateinit var gameManager: GameManager
/* protected static MenuItem menuDeleteFinished;
private static final int MENU_DELETE_FINISHED = 0;
protected static MenuItem menuDeleteSpecific;
private static final int MENU_DELETE_SPECIFIC = 1; commented out to make sure it's not needed*/
private enum class FabStates {
DELETE, INACTIVE, GO_BACK
} //Floating Action Button
private var fabState = FabStates.INACTIVE
/**
* Wird aufgerufen, wenn SudokuLoading nach Programmstart zum ersten Mal
* geladen aufgerufen wird. Hier wird das Layout inflated und es werden
* nötige Initialisierungen vorgenommen.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
profilesDir = getDir(getString(R.string.path_rel_profiles), MODE_PRIVATE)
sudokuDir = getDir(getString(R.string.path_rel_sudokus), MODE_PRIVATE)
sudokuTypeRepo = SudokuTypeRepo(sudokuDir)
profileManager = ProfileManager(profilesDir, ProfileRepo(profilesDir),
ProfilesListRepo(profilesDir))
///init params for game*repos
profileManager!!.loadCurrentProfile()
val gameRepo = GameRepo(
profileManager!!.profilesDir!!,
profileManager!!.currentProfileID,
sudokuTypeRepo)
val gamesFile = File(profileManager!!.currentProfileDir, "games.xml")
val gamesDir = File(profileManager!!.currentProfileDir, "games")
val gamesListRepo : IGamesListRepo = GamesListRepo(gamesDir, gamesFile)
gameManager = GameManager(profileManager!!, gameRepo, gamesListRepo, sudokuTypeRepo)
//needs to be called before setcontentview which calls onContentChanged
check(!profileManager!!.noProfiles()) { "there are no profiles. this is unexpected. they should be initialized in splashActivity" }
profileManager!!.loadCurrentProfile()
setContentView(R.layout.sudokuloading)
//toolbar
initToolBar()
initFAB(this)
initialiseGames()
}
private fun initToolBar() {
val toolbar = findViewById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
val ab = supportActionBar
ab!!.setHomeAsUpIndicator(R.drawable.launcher)
ab.setDisplayHomeAsUpEnabled(true)
ab.setDisplayShowTitleEnabled(true)
}
private fun initFAB(ctx: Context) {
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setOnClickListener(object : View.OnClickListener {
var trash = ContextCompat.getDrawable(ctx, R.drawable.ic_delete_white_24dp)
var close = ContextCompat.getDrawable(ctx, R.drawable.ic_close_white_24dp)
override fun onClick(view: View) {
when (fabState) {
FabStates.INACTIVE -> {
// ...
fabState = FabStates.DELETE
fab.setImageDrawable(close)
Toast.makeText(ctx, R.string.fab_go_back, Toast.LENGTH_LONG).show()
}
FabStates.DELETE -> {
fabState = FabStates.INACTIVE
fab.setImageDrawable(trash)
}
FabStates.GO_BACK -> goBack(view)
}
}
})
}
/// Action Bar
/**
* Wird beim ersten Anzeigen des Options-Menü von SudokuLoading aufgerufen
* und initialisiert das Optionsmenü indem das Layout inflated wird.
*
* @return true falls das Options-Menü angezeigt werden kann, sonst false
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.action_bar_sudoku_loading, menu)
return true
}
/**
* Wird beim Auswählen eines Menü-Items im Options-Menü aufgerufen. Ist das
* spezifizierte MenuItem null oder ungültig, so wird nichts getan.
*
* @param item
* Das ausgewählte Menü-Item
* @return true, falls die Selection hier bearbeitet wird, false falls nicht
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_sudokuloading_delete_finished -> {
gameManager.deleteFinishedGames()
}
R.id.action_sudokuloading_delete_all -> {
gameManager.gameList.forEach { gameManager.deleteGame(it.id) }
}
else -> super.onOptionsItemSelected(item)
}
onContentChanged()
return false
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
super.onPrepareOptionsMenu(menu)
val noGames = gameManager.gameList.isEmpty()
menu.findItem(R.id.action_sudokuloading_delete_finished).isVisible = !noGames
menu.findItem(R.id.action_sudokuloading_delete_all).isVisible = !noGames
return true
}
/**
* {@inheritDoc}
*/
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
/**
* {@inheritDoc}
*/
override fun onContentChanged() {
super.onContentChanged()
initialiseGames()
profileManager!!.currentGame = if (adapter!!.isEmpty) -1 else adapter!!.getItem(0)!!.id
}
/**
* Wird aufgerufen, falls ein Element (eine View) in der AdapterView
* angeklickt wird.
*
* @param parent
* AdapterView in welcher die View etwas angeklickt wurde
* @param view
* View, welche angeklickt wurde
* @param position
* Position der angeklickten View im Adapter
* @param id
* ID der angeklickten View
*/
override fun onItemClick(parent: AdapterView<*>?, view: View, position: Int, id: Long) {
Log.d(LOG_TAG, position.toString() + "")
if (fabState == FabStates.INACTIVE) {
/* selected in order to play */
profileManager!!.currentGame = adapter!!.getItem(position)!!.id
startActivity(Intent(this, SudokuActivity::class.java))
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
} else {
/*selected in order to delete*/
gameManager.deleteGame(adapter!!.getItem(position)!!.id)
onContentChanged()
}
}
override fun onItemLongClick(
parent: AdapterView<*>?,
view: View,
position: Int,
id: Long
): Boolean {
Log.d(LOG_TAG, "LongClick on $position")
/*gather all options */
val temp_items: MutableList<CharSequence> = ArrayList()
val specialcase = false
if (specialcase) {
} else {
temp_items.add(getString(R.string.sudokuloading_dialog_play))
temp_items.add(getString(R.string.sudokuloading_dialog_delete))
if (profileManager!!.appSettings.isDebugSet) {
temp_items.add("export as text")
temp_items.add("export as file")
}
}
val builder = AlertDialog.Builder(this)
val profilesDir = getDir(getString(R.string.path_rel_profiles), MODE_PRIVATE)
val pm = ProfileManager(profilesDir, ProfileRepo(profilesDir),
ProfilesListRepo(profilesDir))
val gameRepo = GameRepo(pm.profilesDir!!, pm.currentProfileID, sudokuTypeRepo)
builder.setItems(temp_items.toTypedArray()) { dialog, item ->
val gameID = adapter!!.getItem(position)!!.id
when (item) {
0 -> { // play
profileManager!!.currentGame = gameID
val i = Intent(this@SudokuLoadingActivity, SudokuActivity::class.java)
startActivity(i)
overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
}
1 -> { // delete
gameManager.deleteGame(gameID)
onContentChanged()
}
2 -> {
val gameFile = gameRepo.getGameFile(gameID)
var str = "there was an error reading the file, sorry"
var fis: FileInputStream? = null
try {
fis = FileInputStream(gameFile)
val data = ByteArray(gameFile.length().toInt())
fis.read(data)
fis.close()
str = String(data, Charset.forName("UTF-8"))
} catch (e: FileNotFoundException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND //
//sendIntent.putExtra(Intent.EXTRA_FROM_STORAGE, gameFile);
sendIntent.putExtra(Intent.EXTRA_TEXT, str)
sendIntent.type = "text/plain"
startActivity(sendIntent)
}
3 -> {
//already defined under 2
val gameFile = gameRepo.getGameFile(gameID)
/* we can only copy from 'files' subdir, so we have to move the file there first */
val tmpFile = File(filesDir, gameFile.name)
val `in`: InputStream
val out: OutputStream
try {
`in` = FileInputStream(gameFile)
out = FileOutputStream(tmpFile)
Utility.copyFileOnStreamLevel(`in`, out)
`in`.close()
out.flush()
out.close()
} catch (e: IOException) {
e.message?.let { Log.e(LOG_TAG, it) }
Log.e(LOG_TAG, "there seems to be an io exception")
} catch (e: FileNotFoundException) {
e.message?.let { Log.e(LOG_TAG, it) }
Log.e(LOG_TAG, "there seems to be a file not found exception")
}
Log.v("file-share", "tmpfile: " + tmpFile.absolutePath)
Log.v("file-share", "gamefile is null? " + (gameFile == null))
Log.v("file-share", "gamefile getPath " + gameFile.path)
Log.v("file-share", "gamefile getAbsolutePath " + gameFile.absolutePath)
Log.v("file-share", "gamefile getName " + gameFile.name)
Log.v("file-share", "gamefile getParent " + gameFile.parent)
val fileUri = FileProvider.getUriForFile(
this@SudokuLoadingActivity,
"de.sudoq.fileprovider", tmpFile
)
Log.v("file-share", "uri is null? " + (fileUri == null))
val sendIntent = Intent()
sendIntent.action = Intent.ACTION_SEND //
//sendIntent.putExtra(Intent.EXTRA_FROM_STORAGE, gameFile);
sendIntent.putExtra(Intent.EXTRA_STREAM, fileUri)
sendIntent.type = "text/plain"
sendIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
//startActivity(Intent.createChooser(sendIntent, "Share to"));
startActivity(sendIntent)
}
}
}
val alert = builder.create()
alert.show()
return true //prevent itemclick from fire-ing as well
}
private fun initialiseGames() {
games = gameManager.gameList
// initialize ArrayAdapter for the profile names and set it
adapter = SudokuLoadingAdapter(this, games!!)
listAdapter = adapter
listView!!.onItemClickListener = this
listView!!.onItemLongClickListener = this
val noGamesTextView = findViewById<TextView>(R.id.no_games_text_view)
if (games!!.isEmpty()) {
noGamesTextView.visibility = View.VISIBLE
val fab = findViewById<FloatingActionButton>(R.id.fab)
fab.setImageDrawable(
ContextCompat.getDrawable(
this,
R.drawable.ic_arrow_back_white_24dp
)
)
fabState = FabStates.GO_BACK
} else {
noGamesTextView.visibility = View.INVISIBLE
//pass
}
}
/**
* Führt die onBackPressed-Methode aus.
*
* @param view
* unbenutzt
*/
fun goBack(view: View?) {
super.onBackPressed()
}
/**
* Just for testing!
* @return
* number of saved games
*/
val size: Int
get() = games!!.size
private inner class FAB(context: Context?) : FloatingActionButton(context) {
private var fs: FabStates? = null
fun setState(fs: FabStates?) {
this.fs = fs
val id: Int = when (fs) {
FabStates.DELETE -> R.drawable.ic_close_white_24dp
FabStates.INACTIVE -> R.drawable.ic_delete_white_24dp
else -> R.drawable.ic_arrow_back_white_24dp
}
super.setImageDrawable(ContextCompat.getDrawable(this.context, id))
}
}
companion object {
/**
* Der Log-Tag für das LogCat
*/
private val LOG_TAG = SudokuLoadingActivity::class.java.simpleName
}
} | gpl-3.0 |
JoachimR/Bible2net | app/src/main/java/de/reiss/bible2net/theword/main/content/FontSizePreferenceDialog.kt | 1 | 2397 | package de.reiss.bible2net.theword.main.content
import android.app.Dialog
import android.os.Bundle
import android.view.View
import android.widget.SeekBar
import androidx.appcompat.app.AlertDialog
import androidx.fragment.app.DialogFragment
import de.reiss.bible2net.theword.App
import de.reiss.bible2net.theword.R
import de.reiss.bible2net.theword.preferences.AppPreferences
class FontSizePreferenceDialog : DialogFragment() {
companion object {
fun createInstance() = FontSizePreferenceDialog()
}
private val appPreferences: AppPreferences by lazy {
App.component.appPreferences
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog =
activity.let { activity ->
if (activity == null) {
throw NullPointerException()
}
AlertDialog.Builder(activity)
.setTitle(getString(R.string.fontsize_dialog_title))
.setCancelable(true)
.setPositiveButton(activity.getString(R.string.fontsize_dialog_ok)) { _, _ ->
dismiss()
}
.setView(initDialogUi())
.create()
}
private fun initDialogUi(): View {
activity.let { activity ->
if (activity == null) {
throw NullPointerException()
}
val view = activity.layoutInflater.inflate(R.layout.fontsize_dialog, null)
view.findViewById<SeekBar>(R.id.fontsize_dialog_seekbar).apply {
progress = appPreferences.fontSize()
setOnSeekBarChangeListener(
object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(
seekBar: SeekBar,
progress: Int,
fromUser: Boolean
) {
if (fromUser) {
appPreferences.changeFontSize(newFontSize = progress)
}
}
override fun onStartTrackingTouch(seekBar: SeekBar) {
}
override fun onStopTrackingTouch(seekBar: SeekBar) {
}
}
)
}
return view
}
}
}
| gpl-3.0 |
Undin/intellij-rust | src/test/kotlin/org/rust/lang/core/type/RsDivergingTypeInferenceTest.kt | 6 | 1436 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.type
class RsDivergingTypeInferenceTest : RsTypificationTestBase() {
fun `test if with all branches diverging`() = testExpr("""
fn main() {
let x = if true { return; } else { return; };
x;
} //^ !
""")
fun `test one branch diverges`() = testExpr("""
fn main() {
let x = if true { return; } else { 92 };
x;
} //^ i32
""")
fun `test block diverges with explicit type annotation`() = testExpr("""
fn main() {
let x = { let _: i32 = loop {}; 92 };
x;
} //^ !
""")
fun `test match with divergence`() = testExpr("""
enum Buck { Full(u32), Empty }
fn peek() -> Buck { Buck::Empty }
fn stuff() -> u32 {
let full = match peek() {
Buck::Empty => {
return 0;
}
Buck::Full(bucket) => bucket,
};
full
} //^ u32
""")
fun `test closure with divergence`() = testExpr("""
fn main() {
let f = || {
if 2 > 1 {
return 1;
}
unreachable!();
};
let a = f();
a;
//^ i32
}
""")
}
| mit |
yzbzz/beautifullife | icore/src/main/java/com/ddu/icore/entity/BottomItemEntity.kt | 2 | 208 | package com.ddu.icore.entity
/**
* Created by yzbzz on 2017/3/31.
*/
class BottomItemEntity(var name: String = "", var resId: Int = 0, var data: String = "", var cb: ((BottomItemEntity) -> Unit)? = null)
| apache-2.0 |
cauchymop/goblob | goblobBase/src/main/java/com/cauchymop/goblob/presenter/ConfigurationViewEventProcessor.kt | 1 | 1359 | package com.cauchymop.goblob.presenter
import com.cauchymop.goblob.model.GameRepository
import com.cauchymop.goblob.model.GoGameController
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ConfigurationViewEventProcessor @Inject constructor(goGameController: GoGameController,
updater: GameViewUpdater,
gameRepository: GameRepository) : GameEventProcessor(goGameController, updater, gameRepository), ConfigurationEventListener {
override fun onBlackPlayerNameChanged(blackPlayerName: String) =
goGameController.setBlackPlayerName(blackPlayerName)
override fun onWhitePlayerNameChanged(whitePlayerName: String) =
goGameController.setWhitePlayerName(whitePlayerName)
override fun onHandicapChanged(handicap: Int) =
goGameController.setHandicap(handicap)
override fun onKomiChanged(komi: Float) =
goGameController.setKomi(komi)
override fun onBoardSizeChanged(boardSize: Int) =
goGameController.setBoardSize(boardSize)
override fun onSwapEvent() {
goGameController.swapPlayers()
updateView()
}
override fun onConfigurationValidationEvent() {
goGameController.commitConfiguration()
commitGameChanges()
}
} | apache-2.0 |
androidx/androidx | bluetooth/bluetooth-core/src/main/java/androidx/bluetooth/core/ScanFilter.kt | 3 | 15760 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.bluetooth.core
import android.bluetooth.le.ScanFilter as FwkScanFilter
import android.bluetooth.le.ScanResult as FwkScanResult
import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.ParcelUuid
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
/**
* Criteria for filtering result from Bluetooth LE scans. A {@link ScanFilter} allows clients to
* restrict scan results to only those that are of interest to them.
* <p>
* Current filtering on the following fields are supported:
* <li>Service UUIDs which identify the bluetooth gatt services running on the device.
* <li>Name of remote Bluetooth LE device.
* <li>Mac address of the remote device.
* <li>Service data which is the data associated with a service.
* <li>Manufacturer specific data which is the data associated with a particular manufacturer.
* <li>Advertising data type and corresponding data.
*
* @see BluetoothLeScanner
*/
// TODO: Add @See ScanResult once ScanResult added
@SuppressWarnings("HiddenSuperclass") // Bundleable
class ScanFilter internal constructor(
internal val impl: ScanFilterImpl
) : Bundleable {
companion object {
internal const val FIELD_FWK_SCAN_FILTER = 0
internal const val FIELD_SERVICE_SOLICITATION_UUID = 1
internal const val FIELD_SERVICE_SOLICITATION_UUID_MASK = 2
internal const val FIELD_ADVERTISING_DATA = 3
internal const val FIELD_ADVERTISING_DATA_MASK = 4
internal const val FIELD_ADVERTISING_DATA_TYPE = 5
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
@JvmField
val CREATOR: Bundleable.Creator<ScanFilter> =
object : Bundleable.Creator<ScanFilter> {
override fun fromBundle(bundle: Bundle): ScanFilter {
return bundle.getScanFilter()
}
}
internal fun keyForField(field: Int): String {
return field.toString(Character.MAX_RADIX)
}
internal fun Bundle.putScanFilter(filter: ScanFilter) {
this.putParcelable(
keyForField(FIELD_FWK_SCAN_FILTER), filter.impl.fwkInstance)
if (Build.VERSION.SDK_INT < 29) {
if (filter.serviceSolicitationUuid != null) {
this.putParcelable(
keyForField(FIELD_SERVICE_SOLICITATION_UUID),
filter.serviceSolicitationUuid)
}
if (filter.serviceSolicitationUuidMask != null) {
this.putParcelable(
keyForField(FIELD_SERVICE_SOLICITATION_UUID_MASK),
filter.serviceSolicitationUuidMask)
}
}
if (Build.VERSION.SDK_INT < 33) {
if (filter.advertisingData != null) {
this.putByteArray(
keyForField(FIELD_ADVERTISING_DATA),
filter.advertisingData)
this.putByteArray(
keyForField(FIELD_ADVERTISING_DATA_MASK),
filter.advertisingDataMask)
this.putInt(
keyForField(FIELD_ADVERTISING_DATA_TYPE),
filter.advertisingDataType)
}
}
}
internal fun Bundle.getScanFilter(): ScanFilter {
val fwkScanFilter =
Utils.getParcelableFromBundle(
this,
keyForField(FIELD_FWK_SCAN_FILTER),
android.bluetooth.le.ScanFilter::class.java
) ?: throw IllegalArgumentException(
"Bundle doesn't include a framework scan filter"
)
var args = ScanFilterArgs()
if (Build.VERSION.SDK_INT < 33) {
args.advertisingDataType = this.getInt(
keyForField(FIELD_ADVERTISING_DATA_TYPE), -1)
args.advertisingData = this.getByteArray(
keyForField(FIELD_ADVERTISING_DATA))
args.advertisingDataMask = this.getByteArray(
keyForField(FIELD_ADVERTISING_DATA_MASK))
}
if (Build.VERSION.SDK_INT < 29) {
args.serviceSolicitationUuid =
Utils.getParcelableFromBundle(
this,
keyForField(FIELD_SERVICE_SOLICITATION_UUID),
ParcelUuid::class.java
)
args.serviceSolicitationUuidMask =
Utils.getParcelableFromBundle(
this,
keyForField(FIELD_SERVICE_SOLICITATION_UUID_MASK),
ParcelUuid::class.java
)
}
return ScanFilter(fwkScanFilter, args)
}
}
val deviceName: String?
get() = impl.deviceName
val deviceAddress: String?
get() = impl.deviceAddress
val serviceUuid: ParcelUuid?
get() = impl.serviceUuid
val serviceUuidMask: ParcelUuid?
get() = impl.serviceUuidMask
val serviceDataUuid: ParcelUuid?
get() = impl.serviceDataUuid
val serviceData: ByteArray?
get() = impl.serviceData
val serviceDataMask: ByteArray?
get() = impl.serviceDataMask
val manufacturerId: Int
get() = impl.manufacturerId
val manufacturerData: ByteArray?
get() = impl.manufacturerData
val manufacturerDataMask: ByteArray?
get() = impl.manufacturerDataMask
val serviceSolicitationUuid: ParcelUuid?
get() = impl.serviceSolicitationUuid
val serviceSolicitationUuidMask: ParcelUuid?
get() = impl.serviceSolicitationUuidMask
val advertisingData: ByteArray?
get() = impl.advertisingData
val advertisingDataMask: ByteArray?
get() = impl.advertisingDataMask
val advertisingDataType: Int
get() = impl.advertisingDataType
internal constructor(fwkInstance: FwkScanFilter) : this(
if (Build.VERSION.SDK_INT >= 33) {
ScanFilterImplApi33(fwkInstance)
} else if (Build.VERSION.SDK_INT >= 29) {
ScanFilterImplApi29(fwkInstance)
} else {
ScanFilterImplApi21(fwkInstance)
}
)
constructor(
deviceName: String? = null,
deviceAddress: String? = null,
serviceUuid: ParcelUuid? = null,
serviceUuidMask: ParcelUuid? = null,
serviceDataUuid: ParcelUuid? = null,
serviceData: ByteArray? = null,
serviceDataMask: ByteArray? = null,
manufacturerId: Int = -1,
manufacturerData: ByteArray? = null,
manufacturerDataMask: ByteArray? = null,
serviceSolicitationUuid: ParcelUuid? = null,
serviceSolicitationUuidMask: ParcelUuid? = null,
advertisingData: ByteArray? = null,
advertisingDataMask: ByteArray? = null,
advertisingDataType: Int = -1 // TODO: Use ScanRecord.DATA_TYPE_NONE
) : this(ScanFilterArgs(
deviceName,
deviceAddress,
serviceUuid,
serviceUuidMask,
serviceDataUuid,
serviceData,
serviceDataMask,
manufacturerId,
manufacturerData,
manufacturerDataMask,
serviceSolicitationUuid,
serviceSolicitationUuidMask,
advertisingData,
advertisingDataMask,
advertisingDataType
))
internal constructor(args: ScanFilterArgs) : this(args.toFwkScanFilter(), args)
internal constructor(fwkInstance: FwkScanFilter, args: ScanFilterArgs) : this(
if (Build.VERSION.SDK_INT >= 33) {
ScanFilterImplApi33(fwkInstance)
} else if (Build.VERSION.SDK_INT >= 29) {
ScanFilterImplApi29(fwkInstance, args)
} else {
ScanFilterImplApi21(fwkInstance, args)
}
)
/**
* Check if the scan filter matches a {@code scanResult}. A scan result is considered as a match
* if it matches all the field filters.
*/
// TODO: add test for this method
fun matches(scanResult: FwkScanResult?): Boolean = impl.matches(scanResult)
/**
* @hide
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
override fun toBundle(): Bundle {
val bundle = Bundle()
bundle.putScanFilter(this)
return bundle
}
}
internal data class ScanFilterArgs(
var deviceName: String? = null,
var deviceAddress: String? = null,
var serviceUuid: ParcelUuid? = null,
var serviceUuidMask: ParcelUuid? = null,
var serviceDataUuid: ParcelUuid? = null,
var serviceData: ByteArray? = null,
var serviceDataMask: ByteArray? = null,
var manufacturerId: Int = -1,
var manufacturerData: ByteArray? = null,
var manufacturerDataMask: ByteArray? = null,
var serviceSolicitationUuid: ParcelUuid? = null,
var serviceSolicitationUuidMask: ParcelUuid? = null,
var advertisingData: ByteArray? = null,
var advertisingDataMask: ByteArray? = null,
var advertisingDataType: Int = -1 // TODO: Use ScanRecord.DATA_TYPE_NONE
) {
// "ClassVerificationFailure" for FwkScanFilter.Builder
// "WrongConstant" for AdvertisingDataType
@SuppressLint("ClassVerificationFailure", "WrongConstant")
internal fun toFwkScanFilter(): FwkScanFilter {
val builder = FwkScanFilter.Builder()
.setDeviceName(deviceName)
.setDeviceAddress(deviceAddress)
.setServiceUuid(serviceUuid)
if (serviceDataUuid != null) {
if (serviceDataMask == null) {
builder.setServiceData(serviceDataUuid, serviceData)
} else {
builder.setServiceData(
serviceDataUuid, serviceData, serviceDataMask)
}
}
if (manufacturerId >= 0) {
if (manufacturerDataMask == null) {
builder.setManufacturerData(manufacturerId, manufacturerData)
} else {
builder.setManufacturerData(
manufacturerId, manufacturerData, manufacturerDataMask)
}
}
if (Build.VERSION.SDK_INT >= 29 && serviceSolicitationUuid != null) {
if (serviceSolicitationUuidMask == null) {
builder.setServiceSolicitationUuid(serviceSolicitationUuid)
} else {
builder.setServiceSolicitationUuid(
serviceSolicitationUuid, serviceSolicitationUuidMask
)
}
}
if (Build.VERSION.SDK_INT >= 33 && advertisingDataType > 0) {
if (advertisingData != null && advertisingDataMask != null) {
builder.setAdvertisingDataTypeWithData(advertisingDataType,
advertisingData!!, advertisingDataMask!!)
} else {
builder.setAdvertisingDataType(advertisingDataType)
}
}
return builder.build()
}
}
internal interface ScanFilterImpl {
val deviceName: String?
val deviceAddress: String?
val serviceUuid: ParcelUuid?
val serviceUuidMask: ParcelUuid?
val serviceDataUuid: ParcelUuid?
val serviceData: ByteArray?
val serviceDataMask: ByteArray?
val manufacturerId: Int
val manufacturerData: ByteArray?
val manufacturerDataMask: ByteArray?
val serviceSolicitationUuid: ParcelUuid?
val serviceSolicitationUuidMask: ParcelUuid?
val advertisingData: ByteArray?
val advertisingDataMask: ByteArray?
val advertisingDataType: Int
val fwkInstance: FwkScanFilter
fun matches(scanResult: FwkScanResult?): Boolean
}
internal abstract class ScanFilterFwkImplApi21 internal constructor(
override val fwkInstance: FwkScanFilter
) : ScanFilterImpl {
override val deviceName: String?
get() = fwkInstance.deviceName
override val deviceAddress: String?
get() = fwkInstance.deviceAddress
override val serviceUuid: ParcelUuid?
get() = fwkInstance.serviceUuid
override val serviceUuidMask: ParcelUuid?
get() = fwkInstance.serviceUuidMask
override val serviceDataUuid: ParcelUuid?
get() = fwkInstance.serviceDataUuid
override val serviceData: ByteArray?
get() = fwkInstance.serviceData
override val serviceDataMask: ByteArray?
get() = fwkInstance.serviceDataMask
override val manufacturerId: Int
get() = fwkInstance.manufacturerId
override val manufacturerData: ByteArray?
get() = fwkInstance.manufacturerData
override val manufacturerDataMask: ByteArray?
get() = fwkInstance.manufacturerDataMask
override fun matches(scanResult: android.bluetooth.le.ScanResult?): Boolean {
return fwkInstance.matches(scanResult)
}
}
internal class ScanFilterImplApi21 internal constructor(
fwkInstance: FwkScanFilter,
override val serviceSolicitationUuid: ParcelUuid? = null,
override val serviceSolicitationUuidMask: ParcelUuid? = null,
override val advertisingData: ByteArray? = null,
override val advertisingDataMask: ByteArray? = null,
override val advertisingDataType: Int = -1 // TODO: Use ScanRecord.DATA_TYPE_NONE
) : ScanFilterFwkImplApi21(fwkInstance) {
internal constructor(fwkInstance: FwkScanFilter, args: ScanFilterArgs) : this(
fwkInstance, args.serviceSolicitationUuid, args.serviceSolicitationUuidMask,
args.advertisingData, args.advertisingDataMask, args.advertisingDataType
)
}
@RequiresApi(Build.VERSION_CODES.Q)
internal abstract class ScanFilterFwkImplApi29(
fwkInstance: FwkScanFilter
) : ScanFilterFwkImplApi21(fwkInstance) {
override val serviceSolicitationUuid: ParcelUuid?
get() = fwkInstance.serviceSolicitationUuid
override val serviceSolicitationUuidMask: ParcelUuid?
get() = fwkInstance.serviceSolicitationUuidMask
}
@RequiresApi(Build.VERSION_CODES.Q)
internal class ScanFilterImplApi29 internal constructor(
fwkInstance: FwkScanFilter,
override val advertisingData: ByteArray? = null,
override val advertisingDataMask: ByteArray? = null,
override val advertisingDataType: Int = -1 // TODO: Use ScanRecord.DATA_TYPE_NONE
) : ScanFilterFwkImplApi29(fwkInstance) {
internal constructor(fwkInstance: FwkScanFilter, args: ScanFilterArgs) : this(
fwkInstance, args.advertisingData, args.advertisingDataMask, args.advertisingDataType
)
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
internal abstract class ScanFilterFwkImplApi33(fwkInstance: FwkScanFilter) :
ScanFilterFwkImplApi29(fwkInstance) {
override val advertisingData: ByteArray?
get() = fwkInstance.advertisingData
override val advertisingDataMask: ByteArray?
get() = fwkInstance.advertisingDataMask
override val advertisingDataType: Int
get() = fwkInstance.advertisingDataType
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
internal class ScanFilterImplApi33 internal constructor(
fwkInstance: FwkScanFilter
) : ScanFilterFwkImplApi33(fwkInstance)
| apache-2.0 |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/util/SystemWindowInsetsSetter.kt | 1 | 1839 | package org.thoughtcrime.securesms.util
import android.os.Build
import android.view.View
import androidx.core.graphics.Insets
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
object SystemWindowInsetsSetter {
/**
* Updates the view whenever a layout occurs to properly set the system bar insets. setPadding is safe here because it will only trigger an extra layout
* call IF the values actually changed.
*/
fun attach(view: View, lifecycleOwner: LifecycleOwner, @WindowInsetsCompat.Type.InsetsType insetType: Int = WindowInsetsCompat.Type.systemBars()) {
val listener = view.doOnEachLayout {
val insets: Insets? = ViewCompat.getRootWindowInsets(view)?.getInsets(insetType)
if (Build.VERSION.SDK_INT > 29 && insets != null && !insets.isEmpty()) {
view.setPadding(
insets.left,
insets.top,
insets.right,
insets.bottom
)
} else {
val top = if (insetType and WindowInsetsCompat.Type.statusBars() != 0) {
ViewUtil.getStatusBarHeight(view)
} else {
0
}
val bottom = if (insetType and WindowInsetsCompat.Type.navigationBars() != 0) {
ViewUtil.getNavigationBarHeight(view)
} else {
0
}
view.setPadding(
0,
top,
0,
bottom
)
}
}
val lifecycleObserver = object : DefaultLifecycleObserver {
override fun onDestroy(owner: LifecycleOwner) {
view.removeOnLayoutChangeListener(listener)
}
}
lifecycleOwner.lifecycle.addObserver(lifecycleObserver)
}
private fun Insets.isEmpty(): Boolean {
return (top + bottom + right + left) == 0
}
}
| gpl-3.0 |
androidx/androidx | window/window-core/src/test/java/androidx/window/core/layout/WindowWidthSizeClassTest.kt | 3 | 1715 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.window.core.layout
import androidx.window.core.layout.WindowWidthSizeClass.Companion.COMPACT
import androidx.window.core.layout.WindowWidthSizeClass.Companion.EXPANDED
import androidx.window.core.layout.WindowWidthSizeClass.Companion.MEDIUM
import org.junit.Assert.assertEquals
import org.junit.Test
class WindowWidthSizeClassTest {
@Test
fun testComputeForDifferentBuckets() {
val expected = listOf(COMPACT, MEDIUM, EXPANDED)
val actual = listOf(599f, 839f, 840f)
.map { value -> WindowWidthSizeClass.compute(value) }
assertEquals(expected, actual)
}
@Test
fun testToStringContainsName() {
val expected = listOf("COMPACT", "MEDIUM", "EXPANDED")
.map { value -> "WindowWidthSizeClass: $value" }
val actual = listOf(599f, 839f, 840f)
.map { value -> WindowWidthSizeClass.compute(value).toString() }
assertEquals(expected, actual)
}
@Test(expected = IllegalArgumentException::class)
fun testInvalidSizeBucket() {
WindowWidthSizeClass.compute(-1f)
}
} | apache-2.0 |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/EXT_clip_volume_hint.kt | 1 | 898 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val EXT_clip_volume_hint = "EXTClipVolumeHint".nativeClassGL("EXT_clip_volume_hint", postfix = EXT) {
documentation =
"""
Native bindings to the $registryLink extension.
EXT_clip_volume_hint provides a mechanism for applications to indicate that they do not require clip volume clipping for primitives. It allows
applications to maximize performance in situations where they know that clipping is unnecessary. EXT_clip_volume_hint is only an indication, though,
and implementations are free to ignore it.
"""
IntConstant(
"Accepted by the target parameter of Hint and the pname parameter of GetBooleanv, GetDoublev, GetFloatv and GetIntegerv.",
"CLIP_VOLUME_CLIPPING_HINT_EXT"..0x80F0
)
} | bsd-3-clause |
InfiniteSoul/ProxerAndroid | src/main/kotlin/me/proxer/app/forum/TopicActivity.kt | 1 | 4412 | package me.proxer.app.forum
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.core.app.ShareCompat
import androidx.fragment.app.commitNow
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.utils.IconicsMenuInflaterUtil
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import me.proxer.app.R
import me.proxer.app.base.DrawerActivity
import me.proxer.app.util.extension.getSafeStringExtra
import me.proxer.app.util.extension.intentFor
import me.proxer.app.util.extension.multilineSnackbar
import me.proxer.app.util.extension.startActivity
import me.proxer.app.util.extension.subscribeAndLogErrors
import me.proxer.library.util.ProxerUrls
/**
* @author Ruben Gees
*/
class TopicActivity : DrawerActivity() {
companion object {
private const val ID_EXTRA = "id"
private const val CATEGORY_ID_EXTRA = "category_id"
private const val TOPIC_EXTRA = "topic"
private const val TOUZAI_PATH = "/touzai"
private const val TOUZAI_CATEGORY = "310"
fun navigateTo(context: Activity, id: String, categoryId: String, topic: String? = null) {
context.startActivity<TopicActivity>(
ID_EXTRA to id,
CATEGORY_ID_EXTRA to categoryId,
TOPIC_EXTRA to topic
)
}
fun getIntent(context: Context, id: String, categoryId: String, topic: String? = null): Intent {
return context.intentFor<TopicActivity>(
ID_EXTRA to id,
CATEGORY_ID_EXTRA to categoryId,
TOPIC_EXTRA to topic
)
}
}
val id: String
get() = when (intent.hasExtra(ID_EXTRA)) {
true -> intent.getSafeStringExtra(ID_EXTRA)
false -> when (intent.data?.path == TOUZAI_PATH) {
true -> intent.data?.getQueryParameter("id") ?: "-1"
else -> intent.data?.pathSegments?.getOrNull(2) ?: "-1"
}
}
val categoryId: String
get() = when (intent.hasExtra(CATEGORY_ID_EXTRA)) {
true -> intent.getSafeStringExtra(CATEGORY_ID_EXTRA)
false -> when (intent.data?.path == TOUZAI_PATH) {
true -> TOUZAI_CATEGORY
else -> intent.data?.pathSegments?.getOrNull(1) ?: "-1"
}
}
var topic: String?
get() = intent.getStringExtra(TOPIC_EXTRA)
set(value) {
intent.putExtra(TOPIC_EXTRA, value)
title = value
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupToolbar()
if (savedInstanceState == null) {
supportFragmentManager.commitNow {
replace(R.id.container, TopicFragment.newInstance())
}
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
IconicsMenuInflaterUtil.inflate(menuInflater, this, R.menu.activity_share, menu, true)
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_share -> topic
?.let {
val url = when (intent.action) {
Intent.ACTION_VIEW -> intent.dataString
else -> ProxerUrls.forumWeb(categoryId, id).toString()
}
it to url
}
?.let { (topic, url) ->
ShareCompat.IntentBuilder
.from(this)
.setText(getString(R.string.share_topic, topic, url))
.setType("text/plain")
.setChooserTitle(getString(R.string.share_title))
.startChooser()
}
}
return super.onOptionsItemSelected(item)
}
private fun setupToolbar() {
supportActionBar?.setDisplayHomeAsUpEnabled(true)
title = topic
toolbar.clicks()
.autoDisposable(this.scope())
.subscribeAndLogErrors {
topic?.also { topic ->
multilineSnackbar(topic)
}
}
}
}
| gpl-3.0 |
Adonai/Man-Man | app/src/main/java/com/adonai/manman/preferences/GlobalPrefsFragment.kt | 1 | 1932 | package com.adonai.manman.preferences
import android.app.AlertDialog
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.localbroadcastmanager.content.LocalBroadcastManager
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.adonai.manman.MainPagerActivity
import com.adonai.manman.R
import com.adonai.manman.database.DbProvider
import java.io.File
/**
* Fragment for showing and managing global preferences
*
* @author Kanedias
*/
class GlobalPrefsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.global_prefs)
findPreference<Preference>("clear.cache")!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
val builder = AlertDialog.Builder(activity)
builder.setTitle(R.string.confirm_action).setMessage(R.string.clear_cache_question)
.setNegativeButton(android.R.string.no, null).setPositiveButton(android.R.string.yes) { _, _ ->
DbProvider.helper.clearAllTables()
LocalBroadcastManager.getInstance(requireActivity()).sendBroadcast(Intent(MainPagerActivity.DB_CHANGE_NOTIFY))
}
.create()
.show()
true
}
val localArchive = File(requireActivity().cacheDir, "manpages.zip")
findPreference<Preference>("delete.local.archive")!!.onPreferenceClickListener = Preference.OnPreferenceClickListener {
if (localArchive.delete()) {
LocalBroadcastManager.getInstance(requireActivity()).sendBroadcast(Intent(MainPagerActivity.LOCAL_CHANGE_NOTIFY))
Toast.makeText(activity, R.string.deleted, Toast.LENGTH_SHORT).show()
}
true
}
}
} | gpl-3.0 |
solkin/drawa-android | app/src/main/java/com/tomclaw/drawa/share/ShareAdapter.kt | 1 | 1034 | package com.tomclaw.drawa.share
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.jakewharton.rxrelay2.PublishRelay
import com.tomclaw.drawa.R
import com.tomclaw.drawa.util.DataProvider
class ShareAdapter(
private val layoutInflater: LayoutInflater,
private val dataProvider: DataProvider<ShareItem>
) : RecyclerView.Adapter<ShareItemHolder>() {
var itemRelay: PublishRelay<ShareItem>? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ShareItemHolder {
val view = layoutInflater.inflate(R.layout.share_item_view, parent, false)
return ShareItemHolder(view, itemRelay)
}
override fun onBindViewHolder(holder: ShareItemHolder, position: Int) {
val item = dataProvider.getItem(position)
holder.bind(item)
}
override fun getItemId(position: Int): Long = dataProvider.getItem(position).id.toLong()
override fun getItemCount(): Int = dataProvider.size()
}
| apache-2.0 |
andstatus/andstatus | app/src/androidTest/kotlin/org/andstatus/app/note/SharingToThisAppTest.kt | 1 | 1639 | package org.andstatus.app.note
import org.andstatus.app.note.NoteEditor
import org.junit.Assert
import org.junit.Test
import java.util.*
class SharingToThisAppTest {
@Test
fun testInputSharedContent() {
val part1 = "This is a long a long post"
val text = "$part1 that doesn't fit into subject"
val prefix = "Note - "
val ellipsis = "…"
oneInputSharedContent(prefix, part1, text, ellipsis, false)
oneInputSharedContent(prefix, "Another text for a subject", text, ellipsis, true)
oneInputSharedContent("", "This is a long but not exact subject", text, "", true)
oneInputSharedContent("Tweet:", part1, text, ellipsis, false)
oneInputSharedContent(prefix, part1, text, "", false)
oneInputSharedContent(prefix, "", text, ellipsis, false)
oneInputSharedContent("", part1, text, ellipsis, false)
oneInputSharedContent(prefix, part1, "", ellipsis, true)
}
private fun oneInputSharedContent(prefix: String?, part1: String?, text: String?, ellipsis: String?, hasAdditionalContent: Boolean) {
val subject = prefix + part1 + ellipsis
Assert.assertEquals(part1 + ellipsis, NoteEditor.Companion.stripBeginning(subject))
Assert.assertEquals((prefix + part1).trim { it <= ' ' }, NoteEditor.Companion.stripEllipsis(subject))
Assert.assertEquals(part1, NoteEditor.Companion.stripEllipsis(NoteEditor.Companion.stripBeginning(subject)))
Assert.assertEquals(hasAdditionalContent, NoteEditor.Companion.subjectHasAdditionalContent(Optional.of(subject),
Optional.ofNullable(text)))
}
}
| apache-2.0 |
EddieVanHalen98/vision-kt | main/out/production/desktop/com/evh98/vision/desktop/DesktopLauncher.kt | 2 | 413 | package com.evh98.vision.desktop
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration
import com.evh98.vision.Vision
object DesktopLauncher {
@JvmStatic fun main(arg: Array<String>) {
val cfg = LwjglApplicationConfiguration()
cfg.width = 1280
cfg.height = 720
LwjglApplication(Vision(), cfg)
}
}
| mit |
kenrube/Fantlab-client | app/src/main/kotlin/ru/fantlab/android/ui/adapter/viewholder/AwardChildViewHolder.kt | 2 | 2217 | package ru.fantlab.android.ui.adapter.viewholder
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import kotlinx.android.synthetic.main.work_awards_child_row_item.view.*
import ru.fantlab.android.R
import ru.fantlab.android.data.dao.model.WorkAwardsChild
import ru.fantlab.android.provider.scheme.LinkParserHelper
import ru.fantlab.android.ui.widgets.FontTextView
import ru.fantlab.android.ui.widgets.ForegroundImageView
import ru.fantlab.android.ui.widgets.treeview.TreeNode
import ru.fantlab.android.ui.widgets.treeview.TreeViewAdapter
import ru.fantlab.android.ui.widgets.treeview.TreeViewBinder
class AwardChildViewHolder : TreeViewBinder<AwardChildViewHolder.ViewHolder>() {
override val layoutId: Int = R.layout.work_awards_child_row_item
override fun provideViewHolder(itemView: View) = ViewHolder(itemView)
override fun bindView(
holder: RecyclerView.ViewHolder,
position: Int,
node: TreeNode<*>,
onTreeNodeListener: TreeViewAdapter.OnTreeNodeListener?
) {
val childNode = node.content as WorkAwardsChild?
holder as AwardChildViewHolder.ViewHolder
if (childNode != null) {
Glide.with(holder.itemView.context).load("https://${LinkParserHelper.HOST_DATA}/images/awards/${childNode.awardId}")
.diskCacheStrategy(DiskCacheStrategy.ALL)
.into(holder.awardIcon)
holder.nameRus.text = childNode.nameRus
if (childNode.nameOrig.isNotEmpty()) {
holder.name.text = childNode.nameOrig
holder.name.visibility = View.VISIBLE
} else holder.name.visibility = View.GONE
if (!childNode.type.isNullOrEmpty()) {
holder.type.text = childNode.type
holder.type.visibility = View.VISIBLE
} else holder.type.visibility = View.GONE
holder.date.text = childNode.date.toString()
}
}
inner class ViewHolder(rootView: View) : TreeViewBinder.ViewHolder(rootView) {
var awardIcon: ForegroundImageView = rootView.awardIcon
var name: FontTextView = rootView.name
var nameRus: FontTextView = rootView.nameRus
var country: FontTextView = rootView.country
var type: FontTextView = rootView.type
var date: FontTextView = rootView.date
}
}
| gpl-3.0 |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/logic/GlideHelper.kt | 1 | 7759 | package at.ac.tuwien.caa.docscan.logic
import android.content.Context
import android.graphics.drawable.Drawable
import android.widget.ImageView
import at.ac.tuwien.caa.docscan.DocScanApp
import at.ac.tuwien.caa.docscan.R
import at.ac.tuwien.caa.docscan.db.model.Page
import at.ac.tuwien.caa.docscan.db.model.exif.Rotation
import at.ac.tuwien.caa.docscan.glidemodule.CropRectTransform
import at.ac.tuwien.caa.docscan.glidemodule.GlideApp
import com.bumptech.glide.load.DataSource
import com.bumptech.glide.load.engine.GlideException
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestListener
import com.bumptech.glide.request.target.Target
import com.bumptech.glide.request.transition.DrawableCrossFadeFactory
import com.bumptech.glide.signature.MediaStoreSignature
import com.bumptech.glide.signature.ObjectKey
import org.koin.java.KoinJavaComponent.inject
import timber.log.Timber
import java.io.File
/**
* A helper utility class for glide for summarizing all loading functions and styles across the app.
*/
object GlideHelper {
private val fileHandler: FileHandler by inject(FileHandler::class.java)
private val app: DocScanApp by inject(DocScanApp::class.java)
fun loadFileIntoImageView(
file: File,
rotation: Rotation,
imageView: ImageView,
style: GlideStyles,
onResourceReady: (isFirstResource: Boolean) -> Unit = {},
onResourceFailed: (isFirstResource: Boolean, e: GlideException?) -> Unit = { _, _ -> }
) {
loadIntoView(
app,
imageView,
null,
null,
file,
PageFileType.JPEG,
rotation,
style,
onResourceReady,
onResourceFailed
)
}
fun loadPageIntoImageView(
page: Page?,
imageView: ImageView,
style: GlideStyles,
callback: GlideLegacyCallback
) {
loadPageIntoImageView(
page,
imageView,
style,
page?.fileHash,
callback::onResourceReady,
callback::onResourceFailed
)
}
fun loadPageIntoImageView(
page: Page?,
imageView: ImageView,
style: GlideStyles
) {
loadPageIntoImageView(page, imageView, style, page?.fileHash, {}, { _, _ -> })
}
private fun loadPageIntoImageView(
page: Page?,
imageView: ImageView,
style: GlideStyles,
fileHash: String?,
onResourceReady: (isFirstResource: Boolean) -> Unit = {},
onResourceFailed: (isFirstResource: Boolean, e: GlideException?) -> Unit = { _, _ -> }
) {
if (page != null) {
val file = fileHandler.getFileByPage(page)
if (file != null) {
loadIntoView(
app,
imageView,
CropRectTransform(page, imageView.context),
fileHash,
file,
PageFileType.JPEG,
page.rotation,
style,
onResourceReady,
onResourceFailed
)
return
}
onResourceFailed.invoke(false, null)
}
Timber.w("Image file doesn't exist and cannot be shown with Glide!")
// clear the image view in case that the file or even the page doesn't exist
GlideApp.with(app).clear(imageView)
}
/**
* Loads an image into a imageview with Glide.
* @param fileHash if available, then this will be used as a key for caching, otherwise it fall
* backs to [MediaStoreSignature].
*
* Please note, that any kind of manipulation of the [file] during an image load may lead to very
* bad issues, where the app may crash and the file gets corrupted, always ensure that when this
* function is called, no modifications to the [file] will happen.
*/
private fun loadIntoView(
context: Context,
imageView: ImageView,
transformation: BitmapTransformation?,
fileHash: String?,
file: File,
@Suppress("SameParameterValue") fileType: PageFileType,
rotation: Rotation,
style: GlideStyles,
onResourceReady: (isFirstResource: Boolean) -> Unit = {},
onResourceFailed: (isFirstResource: Boolean, e: GlideException?) -> Unit = { _, _ -> }
) {
// Needs to be added via factory to prevent issues with partially transparent images
// see http://bumptech.github.io/glide/doc/transitions.html#cross-fading-with-placeholders-and-transparent-images
val factory = DrawableCrossFadeFactory.Builder().setCrossFadeEnabled(false).build()
val glideRequest = GlideApp.with(context)
.load(file)
// disable caching temporarily to test
// .skipMemoryCache(true)
// .diskCacheStrategy(DiskCacheStrategy.NONE)
.signature(
if (fileHash != null) {
ObjectKey(fileHash)
} else {
MediaStoreSignature(
fileType.mimeType,
file.lastModified(),
rotation.exifOrientation
)
}
)
.listener(object : RequestListener<Drawable?> {
override fun onLoadFailed(
e: GlideException?,
model: Any,
target: Target<Drawable?>,
isFirstResource: Boolean
): Boolean {
onResourceFailed(isFirstResource, e)
return false
}
override fun onResourceReady(
resource: Drawable?,
model: Any,
target: Target<Drawable?>,
dataSource: DataSource,
isFirstResource: Boolean
): Boolean {
onResourceReady(isFirstResource)
return false
}
})
val glideTransformRequest = when (style) {
GlideStyles.DEFAULT -> {
glideRequest
}
GlideStyles.CAMERA_THUMBNAIL -> {
glideRequest.transform(CircleCrop()).transition(withCrossFade(factory))
}
GlideStyles.DOCUMENT_PREVIEW -> {
glideRequest.transform(
CenterCrop(),
RoundedCorners(context.resources.getDimensionPixelSize(R.dimen.document_preview_corner_radius))
).transition(withCrossFade(factory))
}
GlideStyles.IMAGE_CROPPED -> {
glideRequest.transition(withCrossFade(factory))
}
GlideStyles.IMAGES_UNCROPPED -> {
transformation?.let {
glideRequest.transform(it).transition(withCrossFade(factory))
} ?: glideRequest.transition(withCrossFade(factory))
}
}
glideTransformRequest.into(imageView)
}
enum class GlideStyles {
DEFAULT,
CAMERA_THUMBNAIL,
DOCUMENT_PREVIEW,
IMAGE_CROPPED,
IMAGES_UNCROPPED
}
}
interface GlideLegacyCallback {
fun onResourceReady(isFirstResource: Boolean)
fun onResourceFailed(isFirstResource: Boolean, e: GlideException?)
}
| lgpl-3.0 |
jankotek/MapDB | src/test/java/org/mapdb/ser/SerializerTest.kt | 2 | 32516 | package org.mapdb.ser
import org.junit.Test
import java.io.Serializable
import java.math.BigDecimal
import java.math.BigInteger
import java.util.*
import org.junit.Assert.*
import org.mapdb.*
import org.mapdb.io.DataIO
import org.mapdb.io.DataInput2ByteArray
import org.mapdb.io.DataOutput2
import org.mapdb.io.DataOutput2ByteArray
abstract class SerializerTest<E> {
val random = Random();
abstract fun randomValue(): E
abstract val serializer: Serializer<E>
val max = 100L + TT.testScale()
open val repeat = 100
val arraySize = 10 + TT.testScale() * 10
fun assertSerEquals(v1: Any?, v2: Any?) {
assertTrue(serializer.equals(v1 as E, v2 as E))
assertEquals(serializer.hashCode(v1, 0), serializer.hashCode(v2, 0))
}
@Test fun cloneEquals(){
for(i in 0..max){
val e = randomValue()
val e2 = TT.clone(e,serializer)
assertSerEquals(e, e2)
}
}
@Test(timeout = 1000L)
fun randomNotEquals(){
// two random values should not be equal,
// test will eventually timeout if they are always equal
while(serializer.equals(randomValue(), randomValue())){
}
}
@Test(timeout = 1000L)
fun randomNotEqualHashCode(){
//two random values should not have equal hash code,
// test will eventually timeout if they are always equal
while(serializer.hashCode(randomValue(),0) == serializer.hashCode(randomValue(),0)){
}
}
open @Test fun trusted(){
assertTrue(serializer.isTrusted || serializer== Serializers.JAVA
/*|| serializer== Serializers.ELSA*/)
}
@Test fun fixedSize(){
val size = serializer.fixedSize();
if(size<0)
return;
for(i in 0..max) {
val e = randomValue()
val out = DataOutput2ByteArray()
serializer.serialize(out, e);
assertEquals(size,out.pos)
}
}
@Test fun compare() {
for (i in 0..max) {
val v1 = randomValue()
val v2 = randomValue()
serializer.compare(v1, v2)
}
}
}
abstract class GroupSerializerTest<E,G>:SerializerTest<E>(){
val serializer2:GroupSerializer<E,G>
get() = serializer as GroupSerializer<E,G>
@Test open fun valueArrayBinarySearch(){
var v = ArrayList<E>()
for (i in 0..max) {
v.add(randomValue())
}
Collections.sort(v, serializer)
val keys = serializer2.valueArrayFromArray(v.toArray())
fun check(keys:G, binary:ByteArray, e:E, diPos:Int){
val v1 = serializer2.valueArraySearch(keys, e)
val v2 = serializer2.valueArraySearch(keys, e, serializer)
val v3 = Arrays.binarySearch(serializer2.valueArrayToArray(keys), e as Any, serializer as Comparator<Any>)
assertEquals(v1, v3);
assertEquals(v1, v2);
val di = DataInput2ByteArray(binary);
val v4 = serializer2.valueArrayBinarySearch(e, di, v.size, serializer)
assertEquals(diPos, di.pos)
assertEquals(v1, v4)
}
val out = DataOutput2ByteArray();
serializer2.valueArraySerialize(out, keys)
val deserialized = serializer2.valueArrayDeserialize(DataInput2ByteArray(out.buf), v.size);
val diPos = out.pos
assertTrue(Arrays.deepEquals(serializer2.valueArrayToArray(keys), serializer2.valueArrayToArray(deserialized)))
for (i in 0..max*10) {
val e = randomValue()
check(keys, out.buf, e, diPos)
}
for(e in v){
check(keys, out.buf, e, diPos)
}
}
@Test open fun valueArrayGet(){
var v = randomArray()
val keys = serializer2.valueArrayFromArray(v)
val out = DataOutput2ByteArray()
serializer2.valueArraySerialize(out, keys)
for(i in 0 until max.toInt()){
val v1 = v[i] as E
val v2 = serializer2.valueArrayGet(keys, i)
val v3 = serializer2.valueArrayBinaryGet(DataInput2ByteArray(out.buf), max.toInt(), i)
assertTrue(serializer.equals(v1, v2))
assertTrue(serializer.equals(v1, v3))
}
}
open protected fun randomArray() = Array<Any>(max.toInt(), { i -> randomValue() as Any })
open protected fun randomValueArray() = serializer2.valueArrayFromArray(Array<Any>(arraySize.toInt(), { i -> randomValue() as Any }))
fun cloneValueArray(vals:G):G{
val out = DataOutput2ByteArray();
out.pos = 0
val size = serializer2.valueArraySize(vals)
serializer2.valueArraySerialize(out, vals);
val input = DataInput2ByteArray(out.buf)
val ret = serializer2.valueArrayDeserialize(input,size)
assertEquals(out.pos, input.pos)
return ret;
}
fun assertValueArrayEquals(vals1:G, vals2:G){
val size = serializer2.valueArraySize(vals1)
assertEquals(size, serializer2.valueArraySize(vals2))
for(i in 0 until size){
val v1 = serializer2.valueArrayGet(vals1, i)
val v2 = serializer2.valueArrayGet(vals2, i)
assertSerEquals(v1, v2)
}
}
@Test open fun valueArraySerDeser(){
// TODO size hint
// if(serializer.needsAvailableSizeHint())
// return
for(i in 0..max){
val e = randomValueArray()
val e2 = cloneValueArray(e)
assertValueArrayEquals(e,e2)
}
}
@Test open fun valueArrayDeleteValue(){
for(i in 0..max){
val vals = randomValueArray()
val valsSize = serializer2.valueArraySize(vals);
if(valsSize==0)
continue;
val pos = 1+random.nextInt(valsSize-1);
val vals2 = serializer2.valueArrayDeleteValue(vals, pos);
assertEquals(valsSize-1, serializer2.valueArraySize(vals2))
val arr1 = DataIO.arrayDelete(serializer2.valueArrayToArray(vals), pos, 1);
val arr2 = serializer2.valueArrayToArray(vals2);
arr1.forEachIndexed { i, any ->
assertSerEquals(any, arr2[i])
}
}
}
@Test open fun valueArrayCopyOfRange(){
for(i in 0..max){
val vals = randomValueArray()
val valsSize = serializer2.valueArraySize(vals);
if(valsSize<5)
continue;
val pos = 1+random.nextInt(valsSize-4);
val vals2 = serializer2.valueArrayCopyOfRange(vals,pos,pos+3);
val arr1a = serializer2.valueArrayToArray(vals);
val arr1 = Arrays.copyOfRange(arr1a, pos, pos+3)
val arr2 = serializer2.valueArrayToArray(vals2);
arr1.forEachIndexed { i, any ->
assertSerEquals(any, arr2[i])
}
}
}
//
// @Test fun btreemap(){
// val ser = serializer as GroupSerializer<Any>
// val map = BTreeMap.make(keySerializer = ser, valueSerializer = Serializers.INTEGER)
// val set = TreeSet(ser);
// for(i in 1..100)
// set.add(randomValue() as Any)
// set.forEach { map.put(it,1) }
// val iter1 = set.iterator()
// val iter2 = map.keys.iterator()
//
// while(iter1.hasNext()){
// assertTrue(iter2.hasNext())
// assertTrue(ser.equals(iter1.next(),iter2.next()))
// }
// assertFalse(iter2.hasNext())
// }
@Test fun valueArrayUpdate(){
for(i in 0..max) {
var vals = randomValueArray()
val vals2 = serializer2.valueArrayToArray(vals)
val valsSize = serializer2.valueArraySize(vals);
for (j in 0 until valsSize) {
val newVal = randomValue()
vals2[j] = newVal
vals = serializer2.valueArrayUpdateVal(vals, j, newVal)
vals2.forEachIndexed { i, any ->
assertSerEquals(any, serializer2.valueArrayGet(vals,i))
}
}
}
}
}
class Serializer_CHAR: GroupSerializerTest<Char, Any>(){
override fun randomValue() = random.nextInt().toChar()
override val serializer = Serializers.CHAR
}
//
//class Serializer_STRINGXXHASH: GroupSerializerTest<String>(){
// override fun randomValue() = TT.randomString(random.nextInt(10))
// override val serializer = Serializers.STRING_ORIGHASH
//}
class Serializer_STRING: GroupSerializerTest<String, Any>(){
override fun randomValue() = TT.randomString(random.nextInt(10))
override val serializer = Serializers.STRING
}
//class Serializer_STRING_DELTA: GroupSerializerTest<String>(){
// override fun randomValue() = TT.randomString(random.nextInt(10))
// override val serializer = Serializers.STRING_DELTA
//}
//class Serializer_STRING_DELTA2: GroupSerializerTest<String>(){
// override fun randomValue() = TT.randomString(random.nextInt(10))
// override val serializer = Serializers.STRING_DELTA2
//}
//
//
//class Serializer_STRING_INTERN: GroupSerializerTest<String>(){
// override fun randomValue() = TT.randomString(random.nextInt(10))
// override val serializer = Serializers.STRING_INTERN
//}
//
//class Serializer_STRING_ASCII: GroupSerializerTest<String>(){
// override fun randomValue() = TT.randomString(random.nextInt(10))
// override val serializer = Serializers.STRING_ASCII
//}
//
//class Serializer_STRING_NOSIZE: SerializerTest<String>(){
// override fun randomValue() = TT.randomString(random.nextInt(10))
// override val serializer = Serializers.STRING_NOSIZE
//
//}
class Serializer_LONG: GroupSerializerTest<Long,Any>(){
override fun randomValue() = random.nextLong()
override val serializer = Serializers.LONG
}
//class Serializer_LONG_PACKED: GroupSerializerTest<Long>(){
// override fun randomValue() = random.nextLong()
// override val serializer = Serializers.LONG_PACKED
//}
//
//class Serializer_LONG_DELTA: GroupSerializerTest<Long>(){
// override fun randomValue() = random.nextLong()
// override val serializer = Serializers.LONG_DELTA
// override fun randomArray(): Array<Any> {
// val v = super.randomArray()
// Arrays.sort(v)
// return v
// }
//
// override fun randomValueArray(): Any {
// val v = super.randomValueArray()
// Arrays.sort(v as LongArray)
// return v
// }
//}
class Serializer_INTEGER: GroupSerializerTest<Int, Any>(){
override fun randomValue() = random.nextInt()
override val serializer = Serializers.INTEGER
}
//class Serializer_INTEGER_PACKED: GroupSerializerTest<Int>(){
// override fun randomValue() = random.nextInt()
// override val serializer = Serializers.INTEGER_PACKED
//}
//
//class Serializer_INTEGER_DELTA: GroupSerializerTest<Int>(){
// override fun randomValue() = random.nextInt()
// override val serializer = Serializers.INTEGER_DELTA
//
// override fun randomArray(): Array<Any> {
// val v = super.randomArray()
// Arrays.sort(v)
// return v
// }
//
// override fun randomValueArray(): Any {
// val v = super.randomValueArray()
// Arrays.sort(v as IntArray)
// return v
// }
//
//}
//
//class Serializer_LONG_PACKED_ZIGZAG:SerializerTest<Long>(){
// override fun randomValue() = random.nextLong()
// override val serializer = Serializers.LONG_PACKED_ZIGZAG
//}
//
//class Serializer_INTEGER_PACKED_ZIGZAG:SerializerTest<Int>(){
// override fun randomValue() = random.nextInt()
// override val serializer = Serializers.INTEGER_PACKED_ZIGZAG
//}
class Serializer_BOOLEAN: GroupSerializerTest<Boolean,Any>(){
override fun randomValue() = random.nextBoolean()
override val serializer = Serializers.BOOLEAN
}
class Serializer_RECID: GroupSerializerTest<Long,Any>(){
override fun randomValue() = random.nextLong().and(0xFFFFFFFFFFFFL) //6 bytes
override val serializer = Serializers.RECID
}
//class Serializer_RECID_ARRAY: GroupSerializerTest<LongArray>(){
// override fun randomValue():LongArray {
// val ret = LongArray(random.nextInt(50));
// for(i in 0 until ret.size){
// ret[i] = random.nextLong().and(0xFFFFFFFFFFFFL) //6 bytes
// }
// return ret
// }
//
// override val serializer = Serializers.RECID_ARRAY
//}
class Serializer_BYTE_ARRAY: GroupSerializerTest<ByteArray, Any>(){
override fun randomValue() = TT.randomByteArray(random.nextInt(50))
override val serializer = Serializers.BYTE_ARRAY
@Test fun next_val(){
fun check(b1:ByteArray?, b2:ByteArray?){
assertArrayEquals(b1, (Serializers.BYTE_ARRAY as ByteArraySerializer).nextValue(b2))
}
check(byteArrayOf(1,1), byteArrayOf(1,0))
check(byteArrayOf(2), byteArrayOf(1))
check(byteArrayOf(2,0), byteArrayOf(1,-1))
check(null, byteArrayOf(-1,-1))
}
}
//
//class Serializer_BYTE_ARRAY_DELTA: GroupSerializerTest<ByteArray>(){
// override fun randomValue() = TT.randomByteArray(random.nextInt(50))
// override val serializer = Serializers.BYTE_ARRAY_DELTA
//}
//
//class Serializer_BYTE_ARRAY_DELTA2: GroupSerializerTest<ByteArray>(){
// override fun randomValue() = TT.randomByteArray(random.nextInt(50))
// override val serializer = Serializers.BYTE_ARRAY_DELTA2
//}
//
//class Serializer_BYTE_ARRAY_NOSIZE: SerializerTest<ByteArray>(){
// override fun randomValue() = TT.randomByteArray(random.nextInt(50))
// override val serializer = Serializers.BYTE_ARRAY_NOSIZE
//
//}
class Serializer_BYTE: GroupSerializerTest<Byte, Any>(){
override fun randomValue() = random.nextInt().toByte()
override val serializer = Serializers.BYTE
}
class Serializer_CHAR_ARRAY: GroupSerializerTest<CharArray, Any>(){
override fun randomValue():CharArray {
val ret = CharArray(random.nextInt(50));
for(i in 0 until ret.size){
ret[i] = random.nextInt().toChar()
}
return ret
}
override val serializer = Serializers.CHAR_ARRAY
//
// @Test fun prefix_submap(){
// val map = BTreeMap.make(keySerializer = serializer, valueSerializer = Serializers.STRING)
// for(i in 'a'..'f') for(j in 'a'..'f') {
// map.put(charArrayOf(i, j), "$i-$j")
// }
//
// //zero subMap
// assertEquals(0, map.prefixSubMap(charArrayOf('z')).size)
//
// var i = 'b';
// val sub = map.prefixSubMap(charArrayOf(i))
// assertEquals(6, sub.size)
// for(j in 'a'..'f')
// assertEquals("$i-$j", sub[charArrayOf(i,j)])
//
// //out of subMap range
// assertNull(sub[charArrayOf('b','z')])
//
// //max case
// i = java.lang.Character.MAX_VALUE;
// for(j in 'a'..'f')
// map.put(charArrayOf(i, j), "$i-$j")
//
// val subMax = map.prefixSubMap(charArrayOf(i))
// assertEquals(6, subMax.size)
// for(j in 'a'..'f')
// assertEquals("$i-$j", subMax[charArrayOf(i,j.toChar())])
//
// //out of subMap range
// assertNull(sub[charArrayOf(i,'z')])
//
// //max-max case
// map.put(charArrayOf(i, i), "$i-$i")
//
// val subMaxMax = map.prefixSubMap(charArrayOf(i, i))
// assertEquals("$i-$i", subMaxMax[charArrayOf(i,i)])
//
// //out of subMaxMax range
// assertNull(subMaxMax[charArrayOf(i,'a')])
//
// //min case
// i = java.lang.Character.MIN_VALUE;
// for(j in 'a'..'f')
// map.put(charArrayOf(i, j.toChar()), "$i-$j")
//
// val subMin = map.prefixSubMap(charArrayOf(i))
// assertEquals(6, subMin.size)
// for(j in 'a'..'f')
// assertEquals("$i-$j", subMin[charArrayOf(i,j)])
//
// //out of subMap range
// assertNull(sub[charArrayOf('a','z')])
//
// //min-min case
// map.put(charArrayOf(i, i), "$i-$i")
//
// val subMinMin = map.prefixSubMap(charArrayOf(i, i))
// assertEquals("$i-$i", subMinMin[charArrayOf(i,i)])
//
// //out of subMinMin range
// assertNull(subMinMin[charArrayOf(i,'a')])
// }
}
class Serializer_INT_ARRAY: GroupSerializerTest<IntArray, Any>(){
override fun randomValue():IntArray {
val ret = IntArray(random.nextInt(50));
for(i in 0 until ret.size){
ret[i] = random.nextInt()
}
return ret
}
override val serializer = Serializers.INT_ARRAY
//
// @Test fun prefix_submap(){
// val map = BTreeMap.make(keySerializer = serializer, valueSerializer = Serializers.STRING)
// for(i in 1..10) for(j in 1..10) {
// map.put(intArrayOf(i, j), "$i-$j")
// }
//
// //zero subMap
// assertEquals(0, map.prefixSubMap(intArrayOf(15)).size)
//
// var i = 5;
// val sub = map.prefixSubMap(intArrayOf(i))
// assertEquals(10, sub.size)
// for(j in 1..10)
// assertEquals("$i-$j", sub[intArrayOf(i,j)])
//
// //out of subMap range
// assertNull(sub[intArrayOf(3,5)])
//
// //max case
// i = Int.MAX_VALUE;
// for(j in 1..10)
// map.put(intArrayOf(i, j), "$i-$j")
//
// val subMax = map.prefixSubMap(intArrayOf(i))
// assertEquals(10, subMax.size)
// for(j in 1..10)
// assertEquals("$i-$j", subMax[intArrayOf(i,j)])
//
// //out of subMap range
// assertNull(sub[intArrayOf(3,5)])
//
// //max-max case
// map.put(intArrayOf(i, i), "$i-$i")
//
// val subMaxMax = map.prefixSubMap(intArrayOf(i, i))
// assertEquals("$i-$i", subMaxMax[intArrayOf(i,i)])
//
// //out of subMaxMax range
// assertNull(subMaxMax[intArrayOf(i,5)])
//
// //min case
// i = Int.MIN_VALUE;
// for(j in 1..10)
// map.put(intArrayOf(i, j), "$i-$j")
//
// val subMin = map.prefixSubMap(intArrayOf(i))
// assertEquals(10, subMin.size)
// for(j in 1..10)
// assertEquals("$i-$j", subMin[intArrayOf(i,j)])
//
// //out of subMap range
// assertNull(sub[intArrayOf(3,5)])
//
// //min-min case
// map.put(intArrayOf(i, i), "$i-$i")
//
// val subMinMin = map.prefixSubMap(intArrayOf(i, i))
// assertEquals("$i-$i", subMinMin[intArrayOf(i,i)])
//
// //out of subMinMin range
// assertNull(subMinMin[intArrayOf(i,5)])
// }
}
class Serializer_LONG_ARRAY: GroupSerializerTest<LongArray, Any>(){
override fun randomValue():LongArray {
val ret = LongArray(random.nextInt(30));
for(i in 0 until ret.size){
ret[i] = random.nextLong()
}
return ret
}
override val serializer = Serializers.LONG_ARRAY
//
// @Test fun prefix_submap(){
// val map = BTreeMap.make(keySerializer = serializer, valueSerializer = Serializers.STRING)
// for(i in 1L..10L) for(j in 1L..10L) {
// map.put(longArrayOf(i, j), "$i-$j")
// }
//
// //zero subMap
// assertEquals(0, map.prefixSubMap(longArrayOf(15)).size)
//
// var i = 5L;
// val sub = map.prefixSubMap(longArrayOf(i))
// assertEquals(10, sub.size)
// for(j in 1L..10L)
// assertEquals("$i-$j", sub[longArrayOf(i,j)])
//
// //out of subMap range
// assertNull(sub[longArrayOf(3,5)])
//
// //max case
// i = Long.MAX_VALUE;
// for(j in 1L..10L)
// map.put(longArrayOf(i, j), "$i-$j")
//
// val subMax = map.prefixSubMap(longArrayOf(i))
// assertEquals(10, subMax.size)
// for(j in 1L..10L)
// assertEquals("$i-$j", subMax[longArrayOf(i,j)])
//
// //out of subMap range
// assertNull(sub[longArrayOf(3,5)])
//
// //max-max case
// map.put(longArrayOf(i, i), "$i-$i")
//
// val subMaxMax = map.prefixSubMap(longArrayOf(i, i))
// assertEquals("$i-$i", subMaxMax[longArrayOf(i,i)])
//
// //out of subMaxMax range
// assertNull(subMaxMax[longArrayOf(i,5)])
//
// //min case
// i = Long.MIN_VALUE;
// for(j in 1L..10L)
// map.put(longArrayOf(i, j), "$i-$j")
//
// val subMin = map.prefixSubMap(longArrayOf(i))
// assertEquals(10, subMin.size)
// for(j in 1L..10L)
// assertEquals("$i-$j", subMin[longArrayOf(i,j)])
//
// //out of subMap range
// assertNull(sub[longArrayOf(3,5)])
//
// //min-min case
// map.put(longArrayOf(i, i), "$i-$i")
//
// val subMinMin = map.prefixSubMap(longArrayOf(i, i))
// assertEquals("$i-$i", subMinMin[longArrayOf(i,i)])
//
// //out of subMinMin range
// assertNull(subMinMin[longArrayOf(i,5)])
// }
}
class Serializer_DOUBLE_ARRAY: GroupSerializerTest<DoubleArray, Any>(){
override fun randomValue():DoubleArray {
val ret = DoubleArray(random.nextInt(30));
for(i in 0 until ret.size){
ret[i] = random.nextDouble()
}
return ret
}
override val serializer = Serializers.DOUBLE_ARRAY
}
class Serializer_JAVA: GroupSerializerTest<Any, Array<Any>>(){
override fun randomValue() = TT.randomString(10)
override val serializer = Serializers.JAVA
override val repeat: Int = 3
internal class Object2 : Serializable
open internal class CollidingObject(val value: String) : Serializable {
override fun hashCode(): Int {
return this.value.hashCode() and 1
}
override fun equals(obj: Any?): Boolean {
return obj is CollidingObject && obj.value == value
}
}
internal class ComparableCollidingObject(value: String) : CollidingObject(value), Comparable<ComparableCollidingObject>, Serializable {
override fun compareTo(o: ComparableCollidingObject): Int {
return value.compareTo(o.value)
}
}
@Test fun clone1(){
val v = TT.clone(Object2(), Serializers.JAVA)
assertTrue(v is Object2)
}
@Test fun clone2(){
val v = TT.clone(CollidingObject("111"), Serializers.JAVA)
assertTrue(v is CollidingObject)
assertSerEquals("111", (v as CollidingObject).value)
}
@Test fun clone3(){
val v = TT.clone(ComparableCollidingObject("111"), Serializers.JAVA)
assertTrue(v is ComparableCollidingObject)
assertSerEquals("111", (v as ComparableCollidingObject).value)
}
}
//
//class Serializer_ELSA: GroupSerializerTest<Any>(){
// override fun randomValue() = TT.randomString(10)
// override val serializer = Serializers.ELSA
//
// internal class Object2 : Serializable
//
// open internal class CollidingObject(val value: String) : Serializable {
// override fun hashCode(): Int {
// return this.value.hashCode() and 1
// }
//
// override fun equals(obj: Any?): Boolean {
// return obj is CollidingObject && obj.value == value
// }
// }
//
// internal class ComparableCollidingObject(value: String) : CollidingObject(value), Comparable<ComparableCollidingObject>, Serializable {
// override fun compareTo(o: ComparableCollidingObject): Int {
// return value.compareTo(o.value)
// }
// }
//
// @Test fun clone1(){
// val v = TT.clone(Object2(), Serializers.ELSA)
// assertTrue(v is Object2)
// }
//
// @Test fun clone2(){
// val v = TT.clone(CollidingObject("111"), Serializers.ELSA)
// assertTrue(v is CollidingObject)
// assertSerEquals("111", (v as CollidingObject).value)
// }
//
// @Test fun clone3(){
// val v = TT.clone(ComparableCollidingObject("111"), Serializers.ELSA)
// assertTrue(v is ComparableCollidingObject)
// assertSerEquals("111", (v as ComparableCollidingObject).value)
//
// }
//
//}
//
//class Serializer_DB_default: GroupSerializerTest<Any?>(){
// override fun randomValue() = TT.randomString(11)
// override val serializer = DBMaker.memoryDB().make().defaultSerializer
//
// @Test override fun trusted(){
// }
//}
//
class Serializer_UUID: GroupSerializerTest<UUID, LongArray>(){
override fun randomValue() = UUID(random.nextLong(), random.nextLong())
override val serializer = Serializers.UUID
}
class Serializer_FLOAT: GroupSerializerTest<Float, Any>(){
override fun randomValue() = random.nextFloat()
override val serializer = Serializers.FLOAT
}
class Serializer_FLOAT_ARRAY: GroupSerializerTest<FloatArray, Any>(){
override fun randomValue():FloatArray {
val ret = FloatArray(random.nextInt(50));
for(i in 0 until ret.size){
ret[i] = random.nextFloat()
}
return ret
}
override val serializer = Serializers.FLOAT_ARRAY
}
class Serializer_DOUBLE: GroupSerializerTest<Double, LongArray>(){
override fun randomValue() = random.nextDouble()
override val serializer = Serializers.DOUBLE
}
class Serializer_SHORT: GroupSerializerTest<Short, Any>(){
override fun randomValue() = random.nextInt().toShort()
override val serializer = Serializers.SHORT
}
class Serializer_SHORT_ARRAY: GroupSerializerTest<ShortArray, Any>(){
override fun randomValue():ShortArray {
val ret = ShortArray(random.nextInt(50));
for(i in 0 until ret.size){
ret[i] = random.nextInt().toShort()
}
return ret
}
override val serializer = Serializers.SHORT_ARRAY
// @Test fun prefix_submap(){
// val map = BTreeMap.make(keySerializer = serializer, valueSerializer = Serializers.STRING)
// for(i in 1..10) for(j in 1..10) {
// map.put(shortArrayOf(i.toShort(), j.toShort()), "$i-$j")
// }
//
// //zero subMap
// assertEquals(0, map.prefixSubMap(shortArrayOf(15)).size)
//
// var i = 5.toShort();
// val sub = map.prefixSubMap(shortArrayOf(i))
// assertEquals(10, sub.size)
// for(j in 1..10)
// assertEquals("$i-$j", sub[shortArrayOf(i,j.toShort())])
//
// //out of subMap range
// assertNull(sub[shortArrayOf(3,5)])
//
// //max case
// i = Short.MAX_VALUE;
// for(j in 1..10)
// map.put(shortArrayOf(i, j.toShort()), "$i-$j")
//
// val subMax = map.prefixSubMap(shortArrayOf(i))
// assertEquals(10, subMax.size)
// for(j in 1..10)
// assertEquals("$i-$j", subMax[shortArrayOf(i,j.toShort())])
//
// //out of subMap range
// assertNull(sub[shortArrayOf(3,5)])
//
// //max-max case
// map.put(shortArrayOf(i, i), "$i-$i")
//
// val subMaxMax = map.prefixSubMap(shortArrayOf(i, i))
// assertEquals("$i-$i", subMaxMax[shortArrayOf(i,i)])
//
// //out of subMaxMax range
// assertNull(subMaxMax[shortArrayOf(i,5)])
//
// //min case
// i = Short.MIN_VALUE;
// for(j in 1..10)
// map.put(shortArrayOf(i, j.toShort()), "$i-$j")
//
// val subMin = map.prefixSubMap(shortArrayOf(i))
// assertEquals(10, subMin.size)
// for(j in 1..10)
// assertEquals("$i-$j", subMin[shortArrayOf(i,j.toShort())])
//
// //out of subMap range
// assertNull(sub[shortArrayOf(3,5)])
//
// //min-min case
// map.put(shortArrayOf(i, i), "$i-$i")
//
// val subMinMin = map.prefixSubMap(shortArrayOf(i, i))
// assertEquals("$i-$i", subMinMin[shortArrayOf(i,i)])
//
// //out of subMinMin range
// assertNull(subMinMin[shortArrayOf(i,5)])
// }
}
class Serializer_BIG_INTEGER: GroupSerializerTest<BigInteger, Any>(){
override fun randomValue() = BigInteger(random.nextInt(50), random)
override val serializer = Serializers.BIG_INTEGER
}
class Serializer_BIG_DECIMAL: GroupSerializerTest<BigDecimal, Any>(){
override fun randomValue() = BigDecimal(BigInteger(random.nextInt(50), random), random.nextInt(100))
override val serializer = Serializers.BIG_DECIMAL
}
class Serializer_DATE: GroupSerializerTest<Date, Any>(){
override fun randomValue() = Date(random.nextLong())
override val serializer = Serializers.DATE
}
//class SerializerCompressionWrapperTest(): GroupSerializerTest<ByteArray>(){
// override fun randomValue() = TT.randomByteArray(random.nextInt(1000))
//
// override val serializer = SerializerCompressionWrapper(Serializers.BYTE_ARRAY as GroupSerializer<ByteArray>)
//
// @Test
// fun compression_wrapper() {
// var b = ByteArray(100)
// Random().nextBytes(b)
// assertTrue(Serializers.BYTE_ARRAY.equals(b, TT.clone(b, serializer)))
//
// b = Arrays.copyOf(b, 10000)
// assertTrue(Serializers.BYTE_ARRAY.equals(b, TT.clone(b, serializer)))
//
// val out = DataOutput2()
// serializer.serialize(out, b)
// assertTrue(out.pos < 1000)
// }
//
//}
//
//class Serializer_DeflateWrapperTest(): GroupSerializerTest<ByteArray>() {
// override fun randomValue() = TT.randomByteArray(random.nextInt(1000))
// override val serializer = SerializerCompressionDeflateWrapper(Serializers.BYTE_ARRAY as GroupSerializer<ByteArray>)
//
//
// @Test fun deflate_wrapper() {
// val c = SerializerCompressionDeflateWrapper(Serializers.BYTE_ARRAY as GroupSerializer<ByteArray>, -1,
// byteArrayOf(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 23, 4, 5, 6, 7, 8, 9, 65, 2))
//
// val b = byteArrayOf(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 6, 3, 3, 3, 3, 35, 6, 67, 7, 3, 43, 34)
//
// assertTrue(Arrays.equals(b, TT.clone(b, c)))
// }
//
//}
//
//
//open class Serializer_Array(): GroupSerializerTest<Array<Any>>(){
// override fun randomValue() = Array<Any>(random.nextInt(30), { TT.randomString(random.nextInt(30))})
//
// override val serializer = SerializerArray(Serializers.STRING as Serializer<Any>)
//
// @Test fun array() {
// val s: Serializer<Array<Any>> = SerializerArray(Serializers.INTEGER as Serializer<Any>)
//
// val a:Array<Any> = arrayOf(1, 2, 3, 4)
//
// assertTrue(Arrays.equals(a, TT.clone(a, s)))
// }
//
//}
//
//
//class Serializer_DeltaArray(): Serializer_Array(){
//
// //TODO more tests with common prefix
//
// override val serializer = SerializerArrayDelta(Serializers.STRING as Serializer<Any>)
//
//
//}
//
//
//
//class Serializer_ArrayTuple(): GroupSerializerTest<Array<Any>>(){
//
// override fun randomValue() = arrayOf(intArrayOf(random.nextInt()), longArrayOf(random.nextLong()))
//
// override val serializer = SerializerArrayTuple(Serializers.INT_ARRAY, Serializers.LONG_ARRAY)
//
//
// @Test fun prefix_submap(){
// val map = BTreeMap.make(keySerializer = SerializerArrayTuple(Serializers.INTEGER, Serializers.LONG), valueSerializer = Serializers.STRING)
// for(i in 1..10) for(j in 1L..10)
// map.put(arrayOf(i as Any,j as Any),"$i-$j")
//
// val sub = map.prefixSubMap(arrayOf(5))
// assertEquals(10, sub.size)
// for(j in 1L..10)
// assertEquals("5-$j", sub[arrayOf(5 as Any,j as Any)])
//
// assertNull(sub[arrayOf(3 as Any,5 as Any)])
// }
//
// @Test fun prefix_comparator(){
// val s = SerializerArrayTuple(Serializers.INTEGER, Serializers.INTEGER)
// assertEquals(-1, s.compare(arrayOf(-1), arrayOf(1)))
// assertEquals(1, s.compare(arrayOf(2), arrayOf(1, null)))
// assertEquals(-1, s.compare(arrayOf(1), arrayOf(1, null)))
// assertEquals(-1, s.compare(arrayOf(1), arrayOf(2, null)))
// assertEquals(-1, s.compare(arrayOf(1,2), arrayOf(1, null)))
//
// assertEquals(1, s.compare(arrayOf(2), arrayOf(1, 1)))
// assertEquals(-1, s.compare(arrayOf(1), arrayOf(1, 1)))
// assertEquals(-1, s.compare(arrayOf(1), arrayOf(2, 1)))
// assertEquals(1, s.compare(arrayOf(1,2), arrayOf(1, 1)))
// assertEquals(-1, s.compare(arrayOf(1), arrayOf(1, 2)))
// }
//}
class SerializerUtilsTest(){
@Test fun lookup(){
assertEquals(Serializers.LONG, SerializerUtils.serializerForClass(Long::class.java))
assertEquals(Serializers.LONG_ARRAY, SerializerUtils.serializerForClass(LongArray::class.java))
assertEquals(Serializers.UUID, SerializerUtils.serializerForClass(UUID::class.java))
assertEquals(Serializers.STRING, SerializerUtils.serializerForClass(String::class.java))
assertNull(SerializerUtils.serializerForClass(Serializer::class.java))
}
}
| apache-2.0 |
develar/mapsforge-tile-server | pixi/src/PixiPointTextContainer.kt | 1 | 2844 | package org.develar.mapsforgeTileServer.pixi
import org.mapsforge.core.graphics.Canvas
import org.mapsforge.core.graphics.Matrix
import org.mapsforge.core.graphics.Paint
import org.mapsforge.core.graphics.Position
import org.mapsforge.core.mapelements.MapElementContainer
import org.mapsforge.core.mapelements.SymbolContainer
import org.mapsforge.core.model.Point
import org.mapsforge.core.model.Rectangle
import org.mapsforge.map.layer.renderer.CanvasEx
import org.mapsforge.map.layer.renderer.MapElementContainerEx
class PixiPointTextContainer(private val text:String, point:Point, priority:Int, private val paintFront:Paint, private val paintBack:Paint?, symbolContainer:SymbolContainer?, position:Position, maxTextWidth:Int) : MapElementContainer(point, priority), MapElementContainerEx {
init {
boundary = computeBoundary(((paintBack ?: paintFront) as PixiPaint).getTextVisualBounds(text), maxTextWidth, position)
}
override fun draw(canvas:CanvasEx, origin:Point) {
canvas.drawText(text, (xy.x - origin.x) + boundary.left, (xy.y - origin.y) + boundary.top, paintFront, paintBack)
}
override fun clashesWith(other:MapElementContainer):Boolean {
if (super<MapElementContainer>.clashesWith(other)) {
return true;
}
return other is PixiPointTextContainer && text == other.text && getPoint().distance(other.getPoint()) < 200
}
override fun draw(canvas:Canvas, origin:Point, matrix:Matrix) = throw IllegalStateException()
override fun equals(other:Any?):Boolean {
if (!super<MapElementContainer>.equals(other)) {
return false;
}
return other is PixiPointTextContainer && text == other.text;
}
override fun hashCode():Int {
return 31 * super<MapElementContainer>.hashCode() + text.hashCode();
}
private fun computeBoundary(textVisualBounds:java.awt.Point, maxTextWidth:Int, position:Position):Rectangle {
val lines = textVisualBounds.x / maxTextWidth + 1
var boxWidth = textVisualBounds.x.toDouble()
var boxHeight = textVisualBounds.y.toDouble()
if (lines > 1) {
// a crude approximation of the size of the text box
//boxWidth = maxTextWidth.toDouble()
//boxHeight = (textHeight * lines).toDouble()
}
when (position) {
Position.CENTER -> {
return Rectangle(-boxWidth / 2, -boxHeight / 2, boxWidth / 2, boxHeight / 2)
}
Position.BELOW -> {
return Rectangle(-boxWidth / 2, 0.0, boxWidth / 2, boxHeight)
}
Position.ABOVE -> {
return Rectangle(-boxWidth / 2, -boxHeight, boxWidth / 2, 0.0)
}
Position.LEFT -> {
return Rectangle(-boxWidth, -boxHeight / 2, 0.0, boxHeight / 2)
}
Position.RIGHT -> {
return Rectangle(0.0, -boxHeight / 2, boxWidth, boxHeight / 2)
}
else -> throw UnsupportedOperationException()
}
}
} | mit |
SiimKinks/sqlitemagic | sqlitemagic-tests/app/src/androidTest/kotlin/com/siimkinks/sqlitemagic/model/persist/BulkItemsPersistWithConflictsTest.kt | 1 | 15758 | @file:Suppress("UNCHECKED_CAST")
package com.siimkinks.sqlitemagic.model.persist
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteDatabase.CONFLICT_IGNORE
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.siimkinks.sqlitemagic.DefaultConnectionTest
import com.siimkinks.sqlitemagic.createVals
import com.siimkinks.sqlitemagic.model.*
import com.siimkinks.sqlitemagic.model.insert.BulkItemsInsertTest
import com.siimkinks.sqlitemagic.model.insert.BulkItemsInsertWithConflictsTest
import com.siimkinks.sqlitemagic.model.insert.assertEarlyUnsubscribeFromInsertRollbackedAllValues
import com.siimkinks.sqlitemagic.model.insert.assertEarlyUnsubscribeFromInsertStoppedAnyFurtherWork
import com.siimkinks.sqlitemagic.model.update.BulkItemsUpdateTest
import com.siimkinks.sqlitemagic.model.update.BulkItemsUpdateWithConflictsTest
import com.siimkinks.sqlitemagic.model.update.assertEarlyUnsubscribeFromUpdateRollbackedAllValues
import com.siimkinks.sqlitemagic.model.update.assertEarlyUnsubscribeFromUpdateStoppedAnyFurtherWork
import io.reactivex.schedulers.Schedulers
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
@RunWith(AndroidJUnit4::class)
class BulkItemsPersistWithConflictsTest : DefaultConnectionTest {
@Test
fun mutableModelBulkPersistWithInsertAndIgnoreConflictSetsIds() {
assertThatDual {
testCase {
BulkItemsInsertTest.MutableModelBulkOperationSetsIds(
forModel = it,
operation = BulkPersistForInsertWithIgnoreConflictDualOperation())
}
isSuccessfulFor(
simpleMutableAutoIdTestModel,
complexMutableAutoIdTestModel)
}
}
@Test
fun simpleModelBulkPersistWithInsertAndIgnoreConflict() {
assertThatDual {
testCase {
BulkItemsInsertWithConflictsTest.SimpleModelBulkOperationWithIgnoreConflict(
forModel = it as TestModelWithUniqueColumn,
operation = BulkPersistForInsertWithIgnoreConflictDualOperation())
}
isSuccessfulFor(*SIMPLE_FIXED_ID_MODELS)
}
}
@Test
fun simpleModelBulkPersistWithUpdateAndIgnoreConflict() {
assertThatDual {
testCase {
BulkItemsUpdateWithConflictsTest.SimpleModelBulkOperationWithIgnoreConflict(
forModel = it as TestModelWithUniqueColumn,
operation = BulkPersistForUpdateWithIgnoreConflictDualOperation())
}
isSuccessfulFor(*SIMPLE_FIXED_ID_MODELS)
}
}
@Test
fun complexBulkPersistWithInsertAndIgnoreConflictWhereParentFails() {
assertThatDual {
testCase {
BulkItemsInsertWithConflictsTest.ComplexModelBulkOperationWithIgnoreConflictWhereParentFails(
forModel = it as ComplexTestModelWithUniqueColumn,
operation = BulkPersistForInsertWithIgnoreConflictDualOperation())
}
isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS)
}
}
@Test
fun complexBulkPersistWithUpdateAndIgnoreConflictWhereParentFails() {
assertThatDual {
testCase {
BulkItemsUpdateWithConflictsTest.ComplexModelBulkOperationWithIgnoreConflictWhereParentFails(
forModel = it as ComplexTestModelWithUniqueColumn,
operation = BulkPersistForUpdateWithIgnoreConflictDualOperation())
}
isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS)
}
}
@Test
fun complexBulkPersistWithInsertAndIgnoreConflictWhereChildFails() {
assertThatDual {
testCase {
BulkItemsInsertWithConflictsTest.ComplexModelBulkOperationWithIgnoreConflictWhereChildFails(
forModel = it as ComplexTestModelWithUniqueColumn,
operation = BulkPersistForInsertWithIgnoreConflictDualOperation())
}
isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS)
}
}
@Test
fun complexBulkPersistWithUpdateAndIgnoreConflictWhereChildFails() {
assertThatDual {
testCase {
BulkItemsUpdateWithConflictsTest.ComplexBulkOperationWithIgnoreConflictWhereChildFails(
forModel = it as ComplexTestModelWithUniqueColumn,
operation = BulkPersistForUpdateWithIgnoreConflictDualOperation())
}
isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS)
}
}
@Test
fun complexModelBulkPersistWithInsertAndIgnoreConflictWhereAllChildrenFail() {
assertThatDual {
testCase {
BulkItemsInsertWithConflictsTest.ComplexBulkOperationWithIgnoreConflictWhereAllChildrenFail(
forModel = it as ComplexTestModelWithUniqueColumn,
operation = BulkPersistForInsertWithIgnoreConflictWhereAllFailDualOperation())
}
isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS)
}
}
@Test
fun complexModelBulkPersistWithUpdateAndIgnoreConflictWhereAllChildrenFail() {
assertThatDual {
testCase {
BulkItemsUpdateWithConflictsTest.ComplexBulkOperationWithIgnoreConflictWhereAllChildrenFail(
forModel = it as ComplexTestModelWithUniqueColumn,
operation = BulkPersistForUpdateWithIgnoreConflictWhereAllFailDualOperation())
}
isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS)
}
}
@Test
fun bulkPersistWithInsertAndIgnoreConflictWhereAllFail() {
assertThatDual {
testCase {
BulkItemsInsertWithConflictsTest.BulkOperationWithIgnoreConflictWhereAllFail(
forModel = it,
setUp = {
val model = it as TestModelWithUniqueColumn
createVals {
val (v, _) = insertNewRandom(model)
val newRandom = it.newRandom()
model.transferUniqueVal(v, newRandom)
}
},
operation = BulkPersistForInsertWithIgnoreConflictWhereAllFailDualOperation())
}
isSuccessfulFor(*ALL_FIXED_ID_MODELS)
}
}
@Test
fun bulkPersistWithUpdateAndIgnoreConflictWhereAllFail() {
assertThatDual {
testCase {
BulkItemsUpdateWithConflictsTest.BulkOperationWithIgnoreConflictWhereAllFail(
forModel = it as TestModelWithUniqueColumn,
operation = BulkPersistForUpdateWithIgnoreConflictWhereAllFailDualOperation())
}
isSuccessfulFor(*ALL_FIXED_ID_MODELS)
}
}
@Test
fun earlyUnsubscribeFromSimpleModelPersistWithInsertAndIgnoreConflict() {
assertThatSingle {
testCase {
BulkItemsInsertWithConflictsTest.EarlyUnsubscribeWithIgnoreConflict(
"Unsubscribing in-flight bulk persist with insert and ignore conflict algorithm " +
"on simple models rollbacks all values",
forModel = it,
test = BulkPersistEarlyUnsubscribeWithIgnoreConflict(),
assertResults = assertEarlyUnsubscribeFromInsertRollbackedAllValues())
}
isSuccessfulFor(*SIMPLE_AUTO_ID_MODELS)
}
}
@Test
fun earlyUnsubscribeFromSimpleModelPersistWithUpdateAndIgnoreConflict() {
assertThatSingle {
testCase {
BulkItemsUpdateWithConflictsTest.EarlyUnsubscribeWithIgnoreConflict(
"Unsubscribing in-flight bulk persist with update and ignore conflict algorithm " +
"on simple models rollbacks all values",
forModel = it,
test = BulkPersistEarlyUnsubscribeWithIgnoreConflict(),
assertResults = assertEarlyUnsubscribeFromUpdateRollbackedAllValues())
}
isSuccessfulFor(*SIMPLE_AUTO_ID_MODELS)
}
}
@Test
fun earlyUnsubscribeFromComplexModelPersistWithInsertAndIgnoreConflict() {
assertThatSingle {
testCase {
BulkItemsInsertWithConflictsTest.EarlyUnsubscribeWithIgnoreConflict(
"Unsubscribing in-flight bulk persist with insert and ignore conflict algorithm " +
"on complex models stops any further work",
forModel = it,
test = BulkPersistEarlyUnsubscribeWithIgnoreConflict(),
assertResults = assertEarlyUnsubscribeFromInsertStoppedAnyFurtherWork())
}
isSuccessfulFor(*COMPLEX_AUTO_ID_MODELS)
}
}
@Test
fun earlyUnsubscribeFromComplexModelPersistWithUpdateAndIgnoreConflict() {
assertThatSingle {
testCase {
BulkItemsUpdateWithConflictsTest.EarlyUnsubscribeWithIgnoreConflict(
"Unsubscribing in-flight bulk persist with update and ignore conflict algorithm " +
"on complex models stops any further work",
forModel = it,
test = BulkPersistEarlyUnsubscribeWithIgnoreConflict(),
assertResults = assertEarlyUnsubscribeFromUpdateStoppedAnyFurtherWork())
}
isSuccessfulFor(*COMPLEX_AUTO_ID_MODELS)
}
}
@Test
fun streamedBulkPersistWithInsertAndIgnoreConflict() {
assertThatSingle {
testCase {
BulkItemsInsertTest.StreamedBulkOperation(
forModel = it,
test = BulkItemsPersistTest.StreamedBulkPersistWithInsertOperation(
ignoreConflict = true))
}
isSuccessfulFor(*ALL_AUTO_ID_MODELS)
}
}
@Test
fun streamedBulkPersistWithUpdateAndIgnoreConflict() {
assertThatSingle {
testCase {
BulkItemsUpdateTest.StreamedBulkOperation(
forModel = it,
test = BulkItemsPersistTest.StreamedBulkPersistWithUpdateOperation(
ignoreConflict = true))
}
isSuccessfulFor(*ALL_AUTO_ID_MODELS)
}
}
@Test
fun bulkPersistWithUpdateByUniqueColumnAndIgnoreConflict() {
assertThatDual {
testCase {
BulkItemsUpdateTest.BulkOperationByUniqueColumn(
forModel = it,
operation = BulkPersistDualOperation { model, testVals ->
model.bulkPersistBuilder(testVals)
.conflictAlgorithm(CONFLICT_IGNORE)
.byColumn((model as TestModelWithUniqueColumn).uniqueColumn)
})
}
isSuccessfulFor(*ALL_FIXED_ID_MODELS)
}
}
@Test
fun bulkPersistWithUpdateByComplexUniqueColumnAndIgnoreConflict() {
assertThatDual {
testCase {
BulkItemsUpdateTest.BulkOperationByComplexUniqueColumn(
forModel = it,
operation = BulkPersistDualOperation { model, testVals ->
model.bulkPersistBuilder(testVals)
.conflictAlgorithm(CONFLICT_IGNORE)
.byColumn((model as ComplexTestModelWithUniqueColumn).complexUniqueColumn)
})
}
isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS)
}
}
@Test
fun bulkPersistWithUpdateByComplexColumnUniqueColumnAndIgnoreConflict() {
assertThatDual {
testCase {
BulkItemsUpdateTest.BulkOperationByComplexColumnUniqueColumn(
forModel = it,
operation = BulkPersistDualOperation { model, testVals ->
model.bulkPersistBuilder(testVals)
.conflictAlgorithm(CONFLICT_IGNORE)
.byColumn((model as ComplexTestModelWithUniqueColumn).complexColumnUniqueColumn)
})
}
isSuccessfulFor(*COMPLEX_FIXED_ID_MODELS)
}
}
@Test
fun bulkPersistWithUpdateByUniqueColumnWithNullIdAndIgnoreConflict() {
assertThatDual {
testCase {
BulkItemsUpdateTest.BulkOperationByUniqueColumnWithNullId(
forModel = it,
operation = BulkPersistDualOperation { model, testVals ->
model.bulkPersistBuilder(testVals)
.conflictAlgorithm(CONFLICT_IGNORE)
.byColumn((model as TestModelWithUniqueColumn).uniqueColumn)
})
}
isSuccessfulFor(*ALL_NULLABLE_UNIQUE_AUTO_ID_MODELS)
}
}
class BulkPersistForInsertWithIgnoreConflictDualOperation<T>(private val ignoreNullValues: Boolean = false) : DualOperation<List<T>, T, Boolean> {
override fun executeTest(model: TestModel<T>, testVal: List<T>): Boolean = model
.bulkPersistBuilder(testVal)
.conflictAlgorithm(CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.execute()
override fun observeTest(model: TestModel<T>, testVal: List<T>): Boolean = model
.bulkPersistBuilder(testVal)
.conflictAlgorithm(CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.observe()
.blockingGet(1, TimeUnit.SECONDS) == null
}
class BulkPersistForUpdateWithIgnoreConflictDualOperation<T>(private val ignoreNullValues: Boolean = false) : DualOperation<BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictTestVals<T>, T, Boolean> {
override fun executeTest(model: TestModel<T>, testVal: BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictTestVals<T>): Boolean = model
.bulkPersistBuilder(testVal.allTestVals)
.conflictAlgorithm(CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.execute()
override fun observeTest(model: TestModel<T>, testVal: BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictTestVals<T>): Boolean = model
.bulkPersistBuilder(testVal.allTestVals)
.conflictAlgorithm(CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.observe()
.blockingGet(1, TimeUnit.SECONDS) == null
}
class BulkPersistForInsertWithIgnoreConflictWhereAllFailDualOperation<T>(private val ignoreNullValues: Boolean = false) : DualOperation<List<T>, T, Boolean> {
override fun executeTest(model: TestModel<T>, testVal: List<T>): Boolean =
// we expect false result indicating all operations failure
!model.bulkPersistBuilder(testVal)
.conflictAlgorithm(CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.execute()
override fun observeTest(model: TestModel<T>, testVal: List<T>): Boolean = model
.bulkPersistBuilder(testVal)
.conflictAlgorithm(CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.observe()
.blockingGet(1, TimeUnit.SECONDS) == null
}
class BulkPersistForUpdateWithIgnoreConflictWhereAllFailDualOperation<T>(private val ignoreNullValues: Boolean = false) : DualOperation<BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictWhereAllFailTestVals<T>, T, Boolean> {
override fun executeTest(model: TestModel<T>, testVal: BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictWhereAllFailTestVals<T>): Boolean =
// we expect false result indicating all operations failure
!model.bulkPersistBuilder(testVal.testVals)
.conflictAlgorithm(SQLiteDatabase.CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.execute()
override fun observeTest(model: TestModel<T>, testVal: BulkItemsUpdateWithConflictsTest.BulkUpdateWithIgnoreConflictWhereAllFailTestVals<T>): Boolean = model
.bulkPersistBuilder(testVal.testVals)
.conflictAlgorithm(SQLiteDatabase.CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.observe()
.blockingGet(1, TimeUnit.SECONDS) == null
}
class BulkPersistEarlyUnsubscribeWithIgnoreConflict<T>(private val ignoreNullValues: Boolean = false) : SingleOperation<List<T>, T, AtomicInteger> {
override fun invoke(model: TestModel<T>, testVal: List<T>): AtomicInteger {
val eventsCount = AtomicInteger(0)
val disposable = model
.bulkPersistBuilder(testVal)
.conflictAlgorithm(SQLiteDatabase.CONFLICT_IGNORE)
.also { if (ignoreNullValues) it.ignoreNullValues() }
.observe()
.subscribeOn(Schedulers.io())
.subscribe({ eventsCount.incrementAndGet() }, { eventsCount.incrementAndGet() })
Thread.sleep(10)
disposable.dispose()
Thread.sleep(500)
return eventsCount
}
}
} | apache-2.0 |
VKCOM/vk-android-sdk | api/src/main/java/com/vk/sdk/api/discover/dto/DiscoverCarouselObjectsType.kt | 1 | 1683 | /**
* 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.discover.dto
import com.google.gson.annotations.SerializedName
import kotlin.String
enum class DiscoverCarouselObjectsType(
val value: String
) {
@SerializedName("vk_app")
VK_APP("vk_app"),
@SerializedName("direct_game")
DIRECT_GAME("direct_game");
}
| mit |
xdtianyu/CallerInfo | app/src/main/java/org/xdty/callerinfo/service/MarkWindow.kt | 1 | 4497 | package org.xdty.callerinfo.service
import android.app.Service
import android.content.Context
import android.content.Intent
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.View
import android.view.View.OnFocusChangeListener
import android.view.WindowManager
import android.widget.FrameLayout
import com.pkmmte.view.CircularImageView
import org.xdty.callerinfo.R
import org.xdty.callerinfo.model.setting.Setting
import org.xdty.callerinfo.model.setting.SettingImpl
import org.xdty.callerinfo.utils.Utils
import wei.mark.standout.StandOutWindow
import wei.mark.standout.StandOutWindow.StandOutLayoutParams
import wei.mark.standout.constants.StandOutFlags
import wei.mark.standout.ui.Window
// MarkWindow is not used
class MarkWindow : StandOutWindow() {
private var mWindowManager: WindowManager? = null
private var mSettings: Setting? = null
override fun onCreate() {
super.onCreate()
mWindowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
try {
mSettings = SettingImpl.instance
return super.onStartCommand(intent, flags, startId)
} catch (e: IllegalArgumentException) {
e.printStackTrace()
stopSelf(startId)
}
return Service.START_NOT_STICKY
}
override fun getAppName(): String {
return resources.getString(R.string.mark_window)
}
override fun getAppIcon(): Int {
return R.drawable.status_icon
}
override fun createAndAttachView(id: Int, frame: FrameLayout) {
val inflater = getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
val view = inflater.inflate(R.layout.mark_window, frame, true)
bindCircleImage(view, R.id.express)
bindCircleImage(view, R.id.takeout)
bindCircleImage(view, R.id.selling)
bindCircleImage(view, R.id.harass)
bindCircleImage(view, R.id.bilk)
}
override fun attachBaseContext(newBase: Context) {
val context: Context = Utils.changeLang(newBase)
super.attachBaseContext(context)
}
private fun bindCircleImage(view: View, id: Int) {
val circularImageView = view.findViewById<View>(id) as CircularImageView
circularImageView.onFocusChangeListener = OnFocusChangeListener { v, hasFocus -> Log.e(TAG, "$v: $hasFocus") }
circularImageView.setOnClickListener { v -> Log.e(TAG, v.toString() + "xxx") }
}
override fun onMove(id: Int, window: Window, view: View, event: MotionEvent) {
super.onMove(id, window, view, event)
val x = window.layoutParams.x
val width = mSettings!!.screenWidth
val layout = window.findViewById<View>(R.id.content)
val alpha = ((width - Math.abs(x) * 1.2) / width).toFloat()
layout.alpha = alpha
when (event.action) {
MotionEvent.ACTION_UP -> if (alpha < 0.6) {
hide(id)
} else {
reset(id)
layout.alpha = 1.0f
}
}
}
fun reset(id: Int) {
val window = getWindow(id)
mWindowManager!!.updateViewLayout(window, getParams(id, window))
}
override fun getParams(id: Int, window: Window): StandOutLayoutParams {
val params = StandOutLayoutParams(id, mSettings!!.screenWidth,
mSettings!!.windowHeight, StandOutLayoutParams.CENTER,
StandOutLayoutParams.CENTER)
val x = mSettings!!.windowX
val y = mSettings!!.windowY
if (x != -1 && y != -1) {
params.x = x
params.y = y
}
params.y = (mSettings!!.defaultHeight * 1.5).toInt()
params.minWidth = mSettings!!.screenWidth
params.maxWidth = Math.max(mSettings!!.screenWidth, mSettings!!.screenHeight)
params.minHeight = mSettings!!.defaultHeight * 2
params.height = mSettings!!.defaultHeight * 5
return params
}
override fun getFlags(id: Int): Int {
return (StandOutFlags.FLAG_BODY_MOVE_ENABLE
or StandOutFlags.FLAG_WINDOW_FOCUS_INDICATOR_DISABLE)
}
override fun getThemeStyle(): Int {
return R.style.AppTheme
}
override fun isDisableMove(id: Int): Boolean {
return false
}
companion object {
private val TAG = MarkWindow::class.java.simpleName
}
} | gpl-3.0 |
TCA-Team/TumCampusApp | app/src/main/java/de/tum/in/tumcampusapp/component/tumui/lectures/adapter/LectureAppointmentsListAdapter.kt | 1 | 3751 | package de.tum.`in`.tumcampusapp.component.tumui.lectures.adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import de.tum.`in`.tumcampusapp.R
import de.tum.`in`.tumcampusapp.component.tumui.lectures.activity.LecturesAppointmentsActivity
import de.tum.`in`.tumcampusapp.component.tumui.lectures.model.LectureAppointment
import de.tum.`in`.tumcampusapp.utils.DateTimeUtils
import de.tum.`in`.tumcampusapp.utils.Utils
import org.joda.time.format.DateTimeFormat
/**
* Generates the output of the ListView on the [LecturesAppointmentsActivity] activity.
*/
class LectureAppointmentsListAdapter(
context: Context, // list of Appointments to one lecture
private val appointmentList: List<LectureAppointment>
) : BaseAdapter() {
private val inflater: LayoutInflater = LayoutInflater.from(context)
// date formats for the day output
private val endHoursOutput = DateTimeFormat.mediumTime()
private val startDateOutput = DateTimeFormat.mediumDateTime()
private val endDateOutput = DateTimeFormat.mediumDateTime()
override fun getCount() = appointmentList.size
override fun getItem(position: Int) = appointmentList[position]
override fun getItemId(position: Int) = position.toLong()
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val holder: ViewHolder
val view: View
if (convertView == null) {
view = inflater.inflate(R.layout.activity_lecturesappointments_listview, parent, false)
// save UI elements in view holder
holder = ViewHolder()
holder.appointmentTime = view.findViewById(R.id.tvTerminZeit)
holder.appointmentLocation = view.findViewById(R.id.tvTerminOrt)
holder.appointmentDetails = view.findViewById(R.id.tvTerminBetreff)
view.tag = holder
} else {
view = convertView
holder = view.tag as ViewHolder
}
val lvItem = appointmentList[position]
holder.appointmentLocation?.text = lvItem.location
holder.appointmentDetails?.text = getAppointmentDetails(lvItem)
holder.appointmentTime?.text = Utils.fromHtml(getAppointmentTime(lvItem))
return view
}
private fun getAppointmentTime(lvItem: LectureAppointment): String {
val start = lvItem.startTime
val end = lvItem.endTime
// output if same day: we only show the date once
val output = StringBuilder()
if (DateTimeUtils.isSameDay(start, end)) {
output.append(startDateOutput.print(start))
.append("–")
.append(endHoursOutput.print(end))
} else {
// show it normally
output.append(startDateOutput.print(start))
.append("–")
.append(endDateOutput.print(end))
}
// grey it, if in past
if (start.isBeforeNow) {
output.insert(0, "<font color=\"#444444\">")
output.append("</font>")
}
return output.toString()
}
private fun getAppointmentDetails(lvItem: LectureAppointment): String {
val details = StringBuilder(lvItem.type ?: "")
val title = lvItem.title
if (title != null && title.isNotEmpty()) {
details.append(" - ").append(lvItem.title)
}
return details.toString()
}
// the layout
internal class ViewHolder {
var appointmentDetails: TextView? = null
var appointmentLocation: TextView? = null
var appointmentTime: TextView? = null
}
}
| gpl-3.0 |
naosim/RPGSample | rpglib/src/main/kotlin/com/naosim/rpglib/model/script/ScriptSet.kt | 1 | 863 | package com.naosim.rpglib.model.script
class ScriptSet(val messageScriptList: Array<MessageScript>, val onEnd: () -> Unit)
class ScriptSetBuilder {
var messageScriptList: Array<MessageScript> = emptyArray()
private set
private var onEnd :() -> Unit = {}
private set
fun messageScript(vararg messageScriptList: MessageScript): ScriptSetBuilder {
this.messageScriptList = this.messageScriptList.plus(messageScriptList)
return this
}
fun messageScriptList(messageScriptList: Array<MessageScript>): ScriptSetBuilder {
this.messageScriptList = this.messageScriptList.plus(messageScriptList)
return this
}
fun onEnd(onEnd: () -> Unit): ScriptSetBuilder {
this.onEnd = onEnd
return this
}
fun build(): ScriptSet {
return ScriptSet(messageScriptList, onEnd)
}
} | mit |
felipebz/sonar-plsql | zpa-checks/src/test/kotlin/org/sonar/plsqlopen/checks/SameBranchCheckTest.kt | 1 | 1156 | /**
* 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.plsqlopen.checks
import org.junit.jupiter.api.Test
import org.sonar.plsqlopen.checks.verifier.PlSqlCheckVerifier
class SameBranchCheckTest : BaseCheckTest() {
@Test
fun test() {
PlSqlCheckVerifier.verify(getPath("same_branch.sql"), SameBranchCheck())
}
}
| lgpl-3.0 |
EmpowerOperations/getoptk | src/test/kotlin/com/empowerops/getoptk/TestHelpers.kt | 1 | 443 | package com.empowerops.getoptk
import junit.framework.AssertionFailedError
inline fun <reified X: Throwable> assertThrows(noinline callable: () -> Any): X {
try {
val result = callable()
throw AssertionFailedError("expected $callable to throw ${X::class.qualifiedName}, but it returned normally with value $result")
}
catch(ex: Throwable){ when (ex) {
is X -> return ex
else -> throw ex
}}
} | apache-2.0 |
elect86/jAssimp | src/main/kotlin/assimp/AiPostProcessStep.kt | 2 | 24646 | package assimp
/**
* Created by GBarbieri on 02.05.2017.
*/
enum class AiPostProcessStep(@JvmField val i: Int) {
/** <hr>Calculates the tangents and bitangents for the imported meshes.
*
* Does nothing if a mesh does not have normals. You might want this post processing step to be executed if you plan
* to use tangent space calculations such as normal mapping applied to the meshes. There's an importer property,
* <tt>#AI_CONFIG_PP_CT_MAX_SMOOTHING_ANGLE</tt>, which allows you to specify a maximum smoothing angle for the
* algorithm. However, usually you'll want to leave it at the default value. */
CalcTangentSpace(0x1),
/** <hr>Identifies and joins identical vertex data sets within all imported meshes.
*
* After this step is run, each mesh contains unique vertices, so a vertex may be used by multiple faces. You
* usually want to use this post processing step. If your application deals with indexed geometry, this step is
* compulsory or you'll just waste rendering time. <b>If this flag is not specified</b>, no vertices are referenced
* by more than one face and <b>no index buffer is required</b> for rendering.
*/
JoinIdenticalVertices(0x2),
/** <hr>Converts all the imported data to a left-handed coordinate space.
*
* By default the data is returned in a right-handed coordinate space (which OpenGL prefers). In this space, +X
* points to the right, +Z points towards the viewer, and +Y points upwards. In the DirectX coordinate space +X
* points to the right, +Y points upwards, and +Z points away from the viewer.
*
* You'll probably want to consider this flag if you use Direct3D for rendering. The #aiProcess_ConvertToLeftHanded
* flag supersedes this setting and bundles all conversions typically required for D3D-based applications. */
MakeLeftHanded(0x4),
// -------------------------------------------------------------------------
/** <hr>Triangulates all faces of all meshes.
*
* By default the imported mesh data might contain faces with more than 3 indices. For rendering you'll usually want
* all faces to be triangles.
* This post processing step splits up faces with more than 3 indices into triangles. Line and point primitives are
* *not* modified! If you want 'triangles only' with no other kinds of primitives, try the following solution:
* <ul>
* <li>Specify both #aiProcess_Triangulate and #aiProcess_SortByPType </li>
* <li>Ignore all point and line meshes when you process assimp's output</li>
* </ul> */
Triangulate(0x8),
// -------------------------------------------------------------------------
/** <hr>Removes some parts of the data structure (animations, materials, light sources, cameras, textures, vertex
* components).
*
* The components to be removed are specified in a separate importer property, <tt>#AI_CONFIG_PP_RVC_FLAGS</tt>.
* This is quite useful if you don't need all parts of the output structure. Vertex colors are rarely used today
* for example... Calling this step to remove unneeded data from the pipeline as early as possible results in
* increased performance and a more optimized output data structure.
* This step is also useful if you want to force Assimp to recompute normals or tangents. The corresponding steps
* don't recompute them if they're already there (loaded from the source asset). By using this step you can make
* sure they are NOT there.
*
* This flag is a poor one, mainly because its purpose is usually misunderstood. Consider the following case: a 3D
* model has been exported from a CAD app, and it has per-face vertex colors. Vertex positions can't be shared, thus
* the #aiProcess_JoinIdenticalVertices step fails to optimize the data because of these nasty little vertex colors.
* Most apps don't even process them, so it's all for nothing. By using this step, unneeded components are excluded
* as early as possible thus opening more room for internal optimizations.
*/
RemoveComponent(0x10),
/** <hr>Generates normals for all faces of all meshes.
*
* This is ignored if normals are already there at the time this flag is evaluated. Model importers try to load them
* from the source file, so they're usually already there. Face normals are shared between all points of a single
* face, so a single point can have multiple normals, which forces the library to duplicate vertices in some cases.
* #aiProcess_JoinIdenticalVertices is *senseless* then.
*
* This flag may not be specified together with #aiProcess_GenSmoothNormals. */
GenNormals(0x20),
/** <hr>Generates smooth normals for all vertices in the mesh.
*
* This is ignored if normals are already there at the time this flag is evaluated. Model importers try to load them
* from the source file, so they're usually already there.
*
* This flag may not be specified together with #aiProcess_GenNormals. There's a importer property,
* <tt>#AI_CONFIG_PP_GSN_MAX_SMOOTHING_ANGLE</tt> which allows you to specify an angle maximum for the normal
* smoothing algorithm. Normals exceeding this limit are not smoothed, resulting in a 'hard' seam between two faces.
* Using a decent angle here (e.g. 80 degrees) results in very good visual appearance. */
GenSmoothNormals(0x40),
/** <hr>Splits large meshes into smaller sub-meshes.
*
* This is quite useful for real-time rendering, where the number of triangles which can be maximally processed in a
* single draw-call is limited by the video driver/hardware. The maximum vertex buffer is usually limited too. Both
* requirements can be met with this step: you may specify both a triangle and vertex limit for a single mesh.
*
* The split limits can (and should!) be set through the <tt>#AI_CONFIG_PP_SLM_VERTEX_LIMIT</tt> and
* <tt>#AI_CONFIG_PP_SLM_TRIANGLE_LIMIT</tt> importer properties. The default values are
* <tt>#AI_SLM_DEFAULT_MAX_VERTICES</tt> and <tt>#AI_SLM_DEFAULT_MAX_TRIANGLES</tt>.
*
* Note that splitting is generally a time-consuming task, but only if there's something to split. The use of this
* step is recommended for most users.
*/
SplitLargeMeshes(0x80),
/** <hr>Removes the node graph and pre-transforms all vertices with the local transformation matrices of their nodes.
*
* The output scene still contains nodes, however there is only a root node with children, each one referencing only
* one mesh, and each mesh referencing one material. For rendering, you can simply render all meshes in order - you
* don't need to pay attention to local transformations and the node hierarchy.
* Animations are removed during this step.
* This step is intended for applications without a scenegraph.
* The step CAN cause some problems: if e.g. a mesh of the asset contains normals and another, using the same
* material index, does not, they will be brought together, but the first meshes's part of the normal list is
* zeroed. However, these artifacts are rare.
* @note The <tt>#AI_CONFIG_PP_PTV_NORMALIZE</tt> configuration property can be set to normalize the scene's spatial
* dimension to the -1...1 range. */
PreTransformVertices(0x100),
/** <hr>Limits the number of bones simultaneously affecting a single vertex to a maximum value.
*
* If any vertex is affected by more than the maximum number of bones, the least important vertex weights are
* removed and the remaining vertex weights are renormalized so that the weights still sum up to 1.
* The default bone weight limit is 4 (defined as <tt>#AI_LMW_MAX_WEIGHTS</tt> in config.h), but you can use the
* <tt>#AI_CONFIG_PP_LBW_MAX_WEIGHTS</tt> importer property to supply your own limit to the post processing step.
*
* If you intend to perform the skinning in hardware, this post processing step might be of interest to you. */
LimitBoneWeights(0x200),
/** <hr>Validates the imported scene data structure.
* This makes sure that all indices are valid, all animations and bones are linked correctly, all material
* references are correct .. etc.
*
* It is recommended that you capture Assimp's log output if you use this flag, so you can easily find out what's
* wrong if a file fails the validation. The validator is quite strict and will find *all* inconsistencies in the
* data structure... It is recommended that plugin developers use it to debug their loaders. There are two types of
* validation failures:
* <ul>
* <li>Error: There's something wrong with the imported data. Further postprocessing is not possible and the data is
* not usable at all.
* The import fails. #Importer::GetErrorString() or #aiGetErrorString() carry the error message around.</li>
* <li>Warning: There are some minor issues (e.g. 1000000 animation keyframes with the same time), but further
* postprocessing and use of the data structure is still safe. Warning details are written to the log file,
* <tt>#AI_SCENE_FLAGS_VALIDATION_WARNING</tt> is set in #aiScene::flags</li>
* </ul>
*
* This post-processing step is not time-consuming. Its use is not compulsory, but recommended. */
ValidateDataStructure(0x400),
/** <hr>Reorders triangles for better vertex cache locality.
*
* The step tries to improve the ACMR (average post-transform vertex cache miss ratio) for all meshes. The
* implementation runs in O(n) and is roughly based on the 'tipsify' algorithm
* (see <a href="http://www.cs.princeton.edu/gfx/pubs/Sander_2007_%3ETR/tipsy.pdf">this paper</a>).
*
* If you intend to render huge models in hardware, this step might be of interest to you.
* The <tt>#AI_CONFIG_PP_ICL_PTCACHE_SIZE</tt> importer property can be used to fine-tune the cache optimization. */
ImproveCacheLocality(0x800),
/** <hr>Searches for redundant/unreferenced materials and removes them.
*
* This is especially useful in combination with the #aiProcess_PreTransformVertices and #aiProcess_OptimizeMeshes
* flags.
* Both join small meshes with equal characteristics, but they can't do their work if two meshes have different
* materials. Because several material settings are lost during Assimp's import filters, (and because many exporters
* don't check for redundant materials), huge models often have materials which are are defined several times with
* exactly the same settings.
*
* Several material settings not contributing to the final appearance of a surface are ignored in all comparisons
* (e.g. the material name).
* So, if you're passing additional information through the content pipeline (probably using *magic* material
* names), don't specify this flag. Alternatively take a look at the <tt>#AI_CONFIG_PP_RRM_EXCLUDE_LIST</tt>
* importer property. */
RemoveRedundantMaterials(0x1000),
/** <hr>This step tries to determine which meshes have normal vectors that are facing inwards and inverts them.
*
* The algorithm is simple but effective: the bounding box of all vertices + their normals is compared against the
* volume of the bounding box of all vertices without their normals.
* This works well for most objects, problems might occur with planar surfaces. However, the step tries to filter
* such cases.
* The step inverts all in-facing normals. Generally it is recommended to enable this step, although the result is
* not always correct. */
FixInfacingNormals(0x2000),
/** <hr>This step splits meshes with more than one primitive type in homogeneous sub-meshes.
*
* The step is executed after the triangulation step. After the step returns, just one bit is set in
* aiMesh::primitiveTypes. This is especially useful for real-time rendering where point and line primitives are
* often ignored or rendered separately.
* You can use the <tt>#AI_CONFIG_PP_SBP_REMOVE</tt> importer property to specify which primitive types you need.
* This can be used to easily exclude lines and points, which are rarely used, from the import. */
SortByPType(0x8000),
/** <hr>This step searches all meshes for degenerate primitives and converts them to proper lines or points.
*
* A face is 'degenerate' if one or more of its points are identical.
* To have the degenerate stuff not only detected and collapsed but removed, try one of the following procedures:
* <br><b>1.</b> (if you support lines and points for rendering but don't want the degenerates)<br>
* <ul>
* <li>Specify the #aiProcess_FindDegenerates flag.
* </li>
* <li>Set the <tt>#AI_CONFIG_PP_FD_REMOVE</tt> importer property to
* 1. This will cause the step to remove degenerate triangles from the import as soon as they're detected.
* They won't pass any further pipeline steps.
* </li>
* </ul>
* <br><b>2.</b>(if you don't support lines and points at all)<br>
* <ul>
* <li>Specify the #aiProcess_FindDegenerates flag.
* </li>
* <li>Specify the #aiProcess_SortByPType flag. This moves line and point primitives to separate meshes.
* </li>
* <li>Set the <tt>#AI_CONFIG_PP_SBP_REMOVE</tt> importer property to @code aiPrimitiveType_POINTS |
* aiPrimitiveType_LINES
* @endcode to cause SortByPType to reject point and line meshes from the scene.
* </li>
* </ul>
* @note Degenerate polygons are not necessarily evil and that's why they're not removed by default. There are
* several file formats which don't support lines or points, and some exporters bypass the format specification and
* write them as degenerate triangles instead. */
FindDegenerates(0x10000),
/** <hr>This step searches all meshes for invalid data, such as zeroed normal vectors or invalid UV coords and
* removes/fixes them. This is intended to get rid of some common exporter errors.
*
* This is especially useful for normals. If they are invalid, and the step recognizes this, they will be removed
* and can later be recomputed, i.e. by the #aiProcess_GenSmoothNormals flag.<br>
* The step will also remove meshes that are infinitely small and reduce animation tracks consisting of hundreds if
* redundant keys to a single key. The <tt>AI_CONFIG_PP_FID_ANIM_ACCURACY</tt> config property decides the accuracy
* of the check for duplicate animation tracks. */
FindInvalidData(0x20000),
// -------------------------------------------------------------------------
/** <hr>This step converts non-UV mappings (such as spherical or cylindrical mapping) to proper texture coordinate
* channels.
*
* Most applications will support UV mapping only, so you will probably want to specify this step in every case.
* Note that Assimp is not always able to match the original mapping implementation of the 3D app which produced a
* model perfectly. It's always better to let the modelling app compute the UV channels - 3ds max, Maya, Blender,
* LightWave, and Modo do this for example.
*
* @note If this step is not requested, you'll need to process the <tt>#AI_MATKEY_MAPPING</tt> material property in
* order to display all assets properly.
*/
GenUVCoords(0x40000),
/** <hr>This step applies per-texture UV transformations and bakes them into stand-alone vtexture coordinate
* channels.
*
* UV transformations are specified per-texture - see the <tt>#AI_MATKEY_UVTRANSFORM</tt> material key for more
* information.
* This step processes all textures with transformed input UV coordinates and generates a new (pre-transformed) UV
* channel which replaces the old channel. Most applications won't support UV transformations, so you will probably
* want to specify this step.
*
* @note UV transformations are usually implemented in real-time apps by transforming texture coordinates at vertex
* shader stage with a 3x3 (homogenous) transformation matrix. */
TransformUVCoords(0x80000),
/** <hr>This step searches for duplicate meshes and replaces them with references to the first mesh.
*
* This step takes a while, so don't use it if speed is a concern.
* Its main purpose is to workaround the fact that many export file formats don't support instanced meshes, so
* exporters need to duplicate meshes. This step removes the duplicates again. Please note that Assimp does not
* currently support per-node material assignment to meshes, which means that identical meshes with different
* materials are currently *not* joined, although this is planned for future versions. */
FindInstances(0x100000),
/** <hr>A postprocessing step to reduce the number of meshes.
*
* This will, in fact, reduce the number of draw calls.
*
* This is a very effective optimization and is recommended to be used together with #aiProcess_OptimizeGraph,
* if possible. The flag is fully compatible with both #aiProcess_SplitLargeMeshes and #aiProcess_SortByPType. */
OptimizeMeshes(0x200000),
/** <hr>A postprocessing step to optimize the scene hierarchy.
*
* Nodes without animations, bones, lights or cameras assigned are collapsed and joined.
*
* Node names can be lost during this step. If you use special 'tag nodes' to pass additional information through
* your content pipeline, use the <tt>#AI_CONFIG_PP_OG_EXCLUDE_LIST</tt> importer property to specify a list of
* node names you want to be kept. Nodes matching one of the names in this list won't be touched or modified.
*
* Use this flag with caution. Most simple files will be collapsed to a single node, so complex hierarchies are
* usually completely lost. This is not useful for editor environments, but probably a very effective optimization
* if you just want to get the model data, convert it to your own format, and render it as fast as possible.
*
* This flag is designed to be used with #aiProcess_OptimizeMeshes for best results.
*
* @note 'Crappy' scenes with thousands of extremely small meshes packed in deeply nested nodes exist for almost
* all file formats.
* #aiProcess_OptimizeMeshes in combination with #aiProcess_OptimizeGraph usually fixes them all and makes them
* renderable. */
OptimizeGraph(0x400000),
/** <hr>This step flips all UV coordinates along the y-axis and adjusts material settings and bitangents accordingly.
*
* <b>Output UV coordinate system:</b>
* @code
* 0y|0y ---------- 1x|0y
* | |
* | |
* | |
* 0x|1y ---------- 1x|1y
* @endcode
*
* You'll probably want to consider this flag if you use Direct3D for rendering. The #aiProcess_ConvertToLeftHanded
* flag supersedes this setting and bundles all conversions typically required for D3D-based applications. */
FlipUVs(0x800000),
/** <hr>This step adjusts the output face winding order to be CW.
*
* The default face winding order is counter clockwise (CCW).
*
* <b>Output face order:</b>
* @code
* x2
*
* x0
* x1
* @endcode
*/
FlipWindingOrder(0x1000000),
/** <hr>This step splits meshes with many bones into sub-meshes so that each su-bmesh has fewer or as many bones as
* a given limit. */
SplitByBoneCount(0x2000000),
/** <hr>This step removes bones losslessly or according to some threshold.
*
* In some cases (i.e. formats that require it) exporters are forced to assign dummy bone weights to otherwise
* static meshes assigned to animated meshes. Full, weight-based skinning is expensive while animating nodes is
* extremely cheap, so this step is offered to clean up the data in that regard.
*
* Use <tt>#AI_CONFIG_PP_DB_THRESHOLD</tt> to control this.
* Use <tt>#AI_CONFIG_PP_DB_ALL_OR_NONE</tt> if you want bones removed if and only if all bones within the scene
* qualify for removal. */
aiProcess_Debone(0x4000000),
// aiProcess_GenEntityMeshes = 0x100000,
// aiProcess_OptimizeAnimations = 0x200000
// aiProcess_FixTexturePaths = 0x200000
/** @def aiProcessPreset_TargetRealtime_Fast
* @brief Default postprocess configuration optimizing the data for real-time rendering.
*
* Applications would want to use this preset to load models on end-user PCs,
* maybe for direct use in game.
*
* If you're using DirectX, don't forget to combine this value with
* the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations
* in your application apply the #aiProcess_TransformUVCoords step, too.
* @note Please take the time to read the docs for the steps enabled by this preset.
* Some of them offer further configurable properties, while some of them might not be of
* use for you so it might be better to not specify them.
*/
TargetRealtime_Fast(CalcTangentSpace.i or GenNormals.i or JoinIdenticalVertices.i or Triangulate.i or GenUVCoords.i
or SortByPType.i),
// ---------------------------------------------------------------------------------------
/** @def aiProcessPreset_TargetRealtime_Quality
* @brief Default postprocess configuration optimizing the data for real-time rendering.
*
* Unlike #aiProcessPreset_TargetRealtime_Fast, this configuration
* performs some extra optimizations to improve rendering speed and
* to minimize memory usage. It could be a good choice for a level editor
* environment where import speed is not so important.
*
* If you're using DirectX, don't forget to combine this value with
* the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations
* in your application apply the #aiProcess_TransformUVCoords step, too.
* @note Please take the time to read the docs for the steps enabled by this preset.
* Some of them offer further configurable properties, while some of them might not be
* of use for you so it might be better to not specify them.
*/
TargetRealtime_Quality(CalcTangentSpace.i or GenSmoothNormals.i or JoinIdenticalVertices.i or ImproveCacheLocality.i
or LimitBoneWeights.i or RemoveRedundantMaterials.i or SplitLargeMeshes.i or Triangulate.i or GenUVCoords.i
or SortByPType.i or FindDegenerates.i or FindInvalidData.i),
// ---------------------------------------------------------------------------------------
/** @def aiProcessPreset_TargetRealtime_MaxQuality
* @brief Default postprocess configuration optimizing the data for real-time rendering.
*
* This preset enables almost every optimization step to achieve perfectly
* optimized data. It's your choice for level editor environments where import speed
* is not important.
*
* If you're using DirectX, don't forget to combine this value with
* the #aiProcess_ConvertToLeftHanded step. If you don't support UV transformations
* in your application, apply the #aiProcess_TransformUVCoords step, too.
* @note Please take the time to read the docs for the steps enabled by this preset.
* Some of them offer further configurable properties, while some of them might not be
* of use for you so it might be better to not specify them.
*/
TargetRealtime_MaxQuality(TargetRealtime_Quality.i or FindInstances.i or ValidateDataStructure.i or OptimizeMeshes.i),
/**
* JVM custom.
*
* https://github.com/sp4cerat/Fast-Quadric-Mesh-Simplification/
*/
fastQuadricMeshSimplification(0x8000000)
}
infix fun Int.has(b: AiPostProcessStep) = and(b.i) != 0
infix fun Int.hasnt(b: AiPostProcessStep) = and(b.i) == 0
infix fun Int.or(b: AiPostProcessStep) = or(b.i)
infix fun AiPostProcessStep.or(b: AiPostProcessStep) = i or b.i
infix fun Int.wo(b: AiPostProcessStep) = and(b.i.inv())
typealias AiPostProcessStepsFlags = Int | mit |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/ast/xpath/XPathRelativePathExpr.kt | 1 | 911 | /*
* Copyright (C) 2016 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.xpath.ast.xpath
import com.intellij.psi.PsiElement
/**
* An XPath 2.0 and XQuery 1.0 `RelativePathExpr` node in the XQuery AST.
*
* The `RelativePathExpr` node is not added to the AST. It is
* combined with `PathExpr`.
*/
interface XPathRelativePathExpr : PsiElement
| apache-2.0 |
rhdunn/xquery-intellij-plugin | src/kotlin-intellij/main/uk/co/reecedunn/intellij/plugin/core/parser/Markdown.kt | 1 | 1894 | /*
* Copyright (C) 2018 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.core.parser
import com.petebevin.markdown.MarkdownProcessor
import uk.co.reecedunn.intellij.plugin.core.io.decode
import java.io.InputStream
/**
* Convert Markdown text to HTML.
*
* This provides a consistent API that can be used in the plugin, allowing the
* Markdown processor to be switched out.
*
* This logic also encodes formatting rules to make the resulting HTML usable
* in the IntelliJ inspection description pane. Specifically:
*
* 1. It wraps the generated markdown in `html` and `body` tags, as the
* IntelliJ inspection description rendering code looks for that to signify
* HTML content (otherwise, it assumes plain text and replaces all newlines
* with `<br/>` tags).
*
* 2. The first <p> tag group is removed, otherwise IntelliJ will add a blank
* line (1em top margin) at the start of the description.
*/
object Markdown {
private val md = MarkdownProcessor()
fun parse(text: String): String {
var ret = md.markdown(text)
if (ret.startsWith("<p>")) {
ret = ret.substringBefore("</p>").replace("<p>", "") + ret.substringAfter("</p>")
}
return "<html><body>\n$ret</body></html>"
}
fun parse(text: InputStream): String = parse(text.decode())
}
| apache-2.0 |
jiaminglu/kotlin-native | backend.native/tests/runtime/collections/array2.kt | 1 | 208 | fun main(args : Array<String>) {
val byteArray = Array<Byte>(5, { i -> (i * 2).toByte() })
byteArray.map { println(it) }
val intArray = Array<Int>(5, { i -> i * 4 })
println(intArray.sum())
} | apache-2.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/onboarding/analytic/OnboardingCompletedAnalyticEvent.kt | 2 | 239 | package org.stepik.android.domain.onboarding.analytic
import org.stepik.android.domain.base.analytic.AnalyticEvent
object OnboardingCompletedAnalyticEvent : AnalyticEvent {
override val name: String =
"Onboarding completed"
} | apache-2.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/domain/progress/interactor/LocalProgressInteractor.kt | 1 | 3592 | package org.stepik.android.domain.progress.interactor
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles.zip
import io.reactivex.rxkotlin.toObservable
import io.reactivex.subjects.PublishSubject
import ru.nobird.android.core.model.PagedList
import org.stepik.android.domain.assignment.repository.AssignmentRepository
import org.stepik.android.domain.course.repository.CourseRepository
import org.stepik.android.domain.progress.mapper.getProgresses
import org.stepik.android.domain.progress.repository.ProgressRepository
import org.stepik.android.domain.section.repository.SectionRepository
import org.stepik.android.domain.step.repository.StepRepository
import org.stepik.android.domain.unit.repository.UnitRepository
import org.stepik.android.model.Assignment
import org.stepik.android.model.Course
import org.stepik.android.model.Progress
import org.stepik.android.model.Section
import org.stepik.android.model.Step
import org.stepik.android.model.Unit
import javax.inject.Inject
class LocalProgressInteractor
@Inject
constructor(
private val progressRepository: ProgressRepository,
private val assignmentRepository: AssignmentRepository,
private val stepRepository: StepRepository,
private val unitRepository: UnitRepository,
private val sectionRepository: SectionRepository,
private val courseRepository: CourseRepository,
private val progressesPublisher: PublishSubject<Progress>
) {
fun updateStepsProgress(vararg stepIds: Long): Completable =
stepRepository
.getSteps(*stepIds)
.flatMapCompletable(::updateStepsProgress)
fun updateStepsProgress(steps: List<Step>): Completable =
getUnits(steps)
.flatMap { units ->
zip(getSections(units), getAssignments(steps, units))
.flatMap { (sections, assignments) ->
getCourses(sections)
.map { courses ->
assignments.getProgresses() + steps.getProgresses() + units.getProgresses() + sections.getProgresses() + courses.getProgresses()
}
}
}
.flatMap { progressIds ->
progressRepository
.getProgresses(progressIds)
}
.doOnSuccess { progresses ->
progresses.forEach(progressesPublisher::onNext)
}
.ignoreElement()
private fun getAssignments(steps: List<Step>, units: List<Unit>): Single<List<Assignment>> =
assignmentRepository
.getAssignments(units.mapNotNull(Unit::assignments).flatten().distinct())
.map { assignments ->
assignments
.filter { assignment ->
steps.any { it.id == assignment.step }
}
}
private fun getUnits(steps: List<Step>): Single<List<Unit>> =
steps
.map(Step::lesson)
.distinct()
.toObservable()
.flatMapSingle { lessonId ->
unitRepository
.getUnitsByLessonId(lessonId)
}
.reduce(emptyList()) { a, b -> a + b }
private fun getSections(units: List<Unit>): Single<List<Section>> =
sectionRepository
.getSections(units.map(Unit::section).distinct())
private fun getCourses(sections: List<Section>): Single<PagedList<Course>> =
courseRepository
.getCourses(sections.map(Section::course).distinct())
} | apache-2.0 |
marius-m/racer_test | core/src/main/java/lt/markmerkk/app/mvp/ClientPresenter.kt | 1 | 227 | package lt.markmerkk.app.mvp
import lt.markmerkk.app.entities.Movement
interface ClientPresenter : Presenter {
fun update()
/**
* Updates client movement
*/
fun updateInputMovement(movement: Movement)
} | apache-2.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepic/droid/model/code/ProgrammingLanguage.kt | 2 | 7745 | @file:Suppress("DEPRECATION")
package org.stepic.droid.model.code
import android.content.Context
import android.os.Parcel
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import org.stepic.droid.R
@Deprecated("Use string literal instead. This class is only for knowledge what programming languages are existed")
enum class ProgrammingLanguage(val serverPrintableName: String) : Parcelable {
@SerializedName("python3")
PYTHON("python3"),
@SerializedName("c++11")
CPP11("c++11"),
@SerializedName("c++")
CPP("c++"),
@SerializedName("c")
C("c"),
@SerializedName("haskell")
HASKELL("haskell"),
@SerializedName("haskell 7.10")
HASKELL7("haskell 7.10"),
@SerializedName("haskell 8.0")
HASKELL8("haskell 8.0"),
@SerializedName("java")
JAVA("java"),
@SerializedName("java8")
JAVA8("java8"),
@SerializedName("octave")
OCTAVE("octave"),
@SerializedName("asm32")
ASM32("asm32"),
@SerializedName("asm64")
ASM64("asm64"),
@SerializedName("shell")
SHELL("shell"),
@SerializedName("rust")
RUST("rust"),
@SerializedName("r")
R("r"),
@SerializedName("ruby")
RUBY("ruby"),
@SerializedName("clojure")
CLOJURE("clojure"),
@SerializedName("mono c#")
CS("mono c#"),
@SerializedName("javascript")
JAVASCRIPT("javascript"),
@SerializedName("scala")
SCALA("scala"),
@SerializedName("kotlin")
KOTLIN("kotlin"),
@SerializedName("go")
GO("go"),
@SerializedName("pascalabc")
PASCAL("pascalabc"),
@SerializedName("perl")
PERL("perl"),
SQL("sql");
override fun describeContents(): Int = 0
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeInt(ordinal)
}
companion object CREATOR : Parcelable.Creator<ProgrammingLanguage> {
override fun createFromParcel(parcel: Parcel): ProgrammingLanguage =
ProgrammingLanguage.values()[parcel.readInt()]
override fun newArray(size: Int): Array<ProgrammingLanguage?> = arrayOfNulls(size)
//make it public and resolve highlighting
@Suppress("unused")
private fun highlighting(serverName: String) {
val language = serverNameToLanguage(serverName)
when (language) {
ProgrammingLanguage.PYTHON -> TODO()
ProgrammingLanguage.CPP11 -> TODO()
ProgrammingLanguage.CPP -> TODO()
ProgrammingLanguage.C -> TODO()
ProgrammingLanguage.HASKELL -> TODO()
ProgrammingLanguage.HASKELL7 -> TODO()
ProgrammingLanguage.HASKELL8 -> TODO()
ProgrammingLanguage.JAVA -> TODO()
ProgrammingLanguage.JAVA8 -> TODO()
ProgrammingLanguage.OCTAVE -> TODO()
ProgrammingLanguage.ASM32 -> TODO()
ProgrammingLanguage.ASM64 -> TODO()
ProgrammingLanguage.SHELL -> TODO()
ProgrammingLanguage.RUST -> TODO()
ProgrammingLanguage.R -> TODO()
ProgrammingLanguage.RUBY -> TODO()
ProgrammingLanguage.CLOJURE -> TODO()
ProgrammingLanguage.CS -> TODO()
ProgrammingLanguage.JAVASCRIPT -> TODO()
ProgrammingLanguage.SCALA -> TODO()
ProgrammingLanguage.KOTLIN -> TODO()
ProgrammingLanguage.GO -> TODO()
ProgrammingLanguage.PASCAL -> TODO()
ProgrammingLanguage.PERL -> TODO()
ProgrammingLanguage.SQL -> TODO()
null -> TODO()
}
}
}
}
private fun serverNameToLanguage(serverName: String): ProgrammingLanguage? {
return ProgrammingLanguage.values()
.find {
it.serverPrintableName.equals(serverName, ignoreCase = true)
}
}
fun symbolsForLanguage(lang: String, context: Context): Array<String> {
val programmingLanguage = serverNameToLanguage(lang)
with(context.resources) {
return when (programmingLanguage) {
ProgrammingLanguage.PYTHON ->
getStringArray(R.array.frequent_symbols_py)
ProgrammingLanguage.CPP11, ProgrammingLanguage.CPP, ProgrammingLanguage.C ->
getStringArray(R.array.frequent_symbols_cpp)
ProgrammingLanguage.HASKELL, ProgrammingLanguage.HASKELL7, ProgrammingLanguage.HASKELL8 ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.JAVA, ProgrammingLanguage.JAVA8 ->
getStringArray(R.array.frequent_symbols_java)
ProgrammingLanguage.OCTAVE ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.ASM32, ProgrammingLanguage.ASM64 ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.SHELL ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.RUST ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.R ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.RUBY ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.CLOJURE ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.CS ->
getStringArray(R.array.frequent_symbols_cs)
ProgrammingLanguage.JAVASCRIPT ->
getStringArray(R.array.frequent_symbols_js)
ProgrammingLanguage.SCALA ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.KOTLIN ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.GO ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.PASCAL ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.PERL ->
getStringArray(R.array.frequent_symbols_default)
ProgrammingLanguage.SQL ->
getStringArray(R.array.frequent_symbols_sql)
null ->
getStringArray(R.array.frequent_symbols_default)
}
}
}
fun extensionForLanguage(lang: String) : String =
when (serverNameToLanguage(lang)) {
ProgrammingLanguage.PYTHON -> "py"
ProgrammingLanguage.CPP11,
ProgrammingLanguage.CPP,
ProgrammingLanguage.C -> "cpp"
ProgrammingLanguage.HASKELL,
ProgrammingLanguage.HASKELL7,
ProgrammingLanguage.HASKELL8 -> "hs"
ProgrammingLanguage.JAVA,
ProgrammingLanguage.JAVA8 -> "java"
ProgrammingLanguage.OCTAVE -> "matlab"
ProgrammingLanguage.ASM32,
ProgrammingLanguage.ASM64 -> "asm"
ProgrammingLanguage.SHELL -> "sh"
ProgrammingLanguage.RUST -> "rust"
ProgrammingLanguage.R -> "r"
ProgrammingLanguage.RUBY -> "rb"
ProgrammingLanguage.CLOJURE -> "clj"
ProgrammingLanguage.CS -> "cs"
ProgrammingLanguage.JAVASCRIPT -> "js"
ProgrammingLanguage.SCALA -> "scala"
ProgrammingLanguage.KOTLIN -> "kt"
ProgrammingLanguage.GO -> "go"
ProgrammingLanguage.PASCAL -> "pascal"
ProgrammingLanguage.PERL -> "perl"
ProgrammingLanguage.SQL -> "sql"
null -> ""
} | apache-2.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/cache/course_collection/dao/CourseCollectionDaoImpl.kt | 2 | 3073 | package org.stepik.android.cache.course_collection.dao
import android.content.ContentValues
import android.database.Cursor
import org.stepic.droid.storage.dao.DaoBase
import org.stepic.droid.storage.operations.DatabaseOperations
import org.stepic.droid.util.DbParseHelper
import org.stepic.droid.util.getInt
import org.stepic.droid.util.getLong
import org.stepic.droid.util.getString
import org.stepik.android.cache.course_collection.structure.DbStructureCourseCollection
import org.stepik.android.model.CourseCollection
import javax.inject.Inject
class CourseCollectionDaoImpl
@Inject
constructor(databaseOperations: DatabaseOperations) : DaoBase<CourseCollection>(databaseOperations) {
override fun getDefaultPrimaryColumn(): String =
DbStructureCourseCollection.Columns.ID
override fun getDbName(): String =
DbStructureCourseCollection.TABLE_NAME
override fun getDefaultPrimaryValue(persistentObject: CourseCollection): String =
persistentObject.id.toString()
override fun getContentValues(persistentObject: CourseCollection): ContentValues =
ContentValues(9)
.apply {
put(DbStructureCourseCollection.Columns.ID, persistentObject.id)
put(DbStructureCourseCollection.Columns.POSITION, persistentObject.position)
put(DbStructureCourseCollection.Columns.TITLE, persistentObject.title)
put(DbStructureCourseCollection.Columns.LANGUAGE, persistentObject.language)
put(DbStructureCourseCollection.Columns.COURSES, DbParseHelper.parseLongListToString(persistentObject.courses))
put(DbStructureCourseCollection.Columns.DESCRIPTION, persistentObject.description)
put(DbStructureCourseCollection.Columns.PLATFORM, persistentObject.platform)
put(DbStructureCourseCollection.Columns.SIMILAR_AUTHORS, DbParseHelper.parseLongListToString(persistentObject.similarAuthors))
put(DbStructureCourseCollection.Columns.SIMILAR_COURSE_LISTS, DbParseHelper.parseLongListToString(persistentObject.similarCourseLists))
}
override fun parsePersistentObject(cursor: Cursor): CourseCollection =
CourseCollection(
cursor.getLong(DbStructureCourseCollection.Columns.ID),
cursor.getInt(DbStructureCourseCollection.Columns.POSITION),
cursor.getString(DbStructureCourseCollection.Columns.TITLE)!!,
cursor.getString(DbStructureCourseCollection.Columns.LANGUAGE)!!,
DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourseCollection.Columns.COURSES)) ?: listOf(),
cursor.getString(DbStructureCourseCollection.Columns.DESCRIPTION)!!,
cursor.getInt(DbStructureCourseCollection.Columns.PLATFORM),
DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourseCollection.Columns.SIMILAR_AUTHORS)) ?: listOf(),
DbParseHelper.parseStringToLongList(cursor.getString(DbStructureCourseCollection.Columns.SIMILAR_COURSE_LISTS)) ?: listOf()
)
} | apache-2.0 |
jiaminglu/kotlin-native | Interop/Runtime/src/native/kotlin/kotlinx/cinterop/NativeCallbacks.kt | 1 | 1368 | package kotlinx.cinterop
/**
* This class provides a way to create a stable handle to any Kotlin object.
* Its [value] can be safely passed to native code e.g. to be received in a Kotlin callback.
*
* Any [StableObjPtr] should be manually [disposed][dispose]
*/
data class StableObjPtr private constructor(val value: COpaquePointer) {
companion object {
/**
* Creates a handle for given object.
*/
fun create(any: Any) = fromValue(createStablePointer(any))
/**
* Creates [StableObjPtr] from given raw value.
*
* @param value must be a [value] of some [StableObjPtr]
*/
fun fromValue(value: COpaquePointer) = StableObjPtr(value)
}
/**
* Disposes the handle. It must not be [used][get] after that.
*/
fun dispose() {
disposeStablePointer(value)
}
/**
* Returns the object this handle was [created][create] for.
*/
fun get(): Any = derefStablePointer(value)
}
@SymbolName("Kotlin_Interop_createStablePointer")
private external fun createStablePointer(any: Any): COpaquePointer
@SymbolName("Kotlin_Interop_disposeStablePointer")
private external fun disposeStablePointer(pointer: COpaquePointer)
@SymbolName("Kotlin_Interop_derefStablePointer")
private external fun derefStablePointer(pointer: COpaquePointer): Any
| apache-2.0 |
NerdNumber9/TachiyomiEH | app/src/main/java/eu/kanade/tachiyomi/data/download/DownloadStore.kt | 2 | 3973 | package eu.kanade.tachiyomi.data.download
import android.content.Context
import com.google.gson.Gson
import eu.kanade.tachiyomi.data.database.DatabaseHelper
import eu.kanade.tachiyomi.data.database.models.Manga
import eu.kanade.tachiyomi.data.download.model.Download
import eu.kanade.tachiyomi.source.SourceManager
import eu.kanade.tachiyomi.source.online.HttpSource
import uy.kohesive.injekt.injectLazy
/**
* This class is used to persist active downloads across application restarts.
*
* @param context the application context.
*/
class DownloadStore(
context: Context,
private val sourceManager: SourceManager
) {
/**
* Preference file where active downloads are stored.
*/
private val preferences = context.getSharedPreferences("active_downloads", Context.MODE_PRIVATE)
/**
* Gson instance to serialize/deserialize downloads.
*/
private val gson: Gson by injectLazy()
/**
* Database helper.
*/
private val db: DatabaseHelper by injectLazy()
/**
* Counter used to keep the queue order.
*/
private var counter = 0
/**
* Adds a list of downloads to the store.
*
* @param downloads the list of downloads to add.
*/
fun addAll(downloads: List<Download>) {
val editor = preferences.edit()
downloads.forEach { editor.putString(getKey(it), serialize(it)) }
editor.apply()
}
/**
* Removes a download from the store.
*
* @param download the download to remove.
*/
fun remove(download: Download) {
preferences.edit().remove(getKey(download)).apply()
}
/**
* Removes all the downloads from the store.
*/
fun clear() {
preferences.edit().clear().apply()
}
/**
* Returns the preference's key for the given download.
*
* @param download the download.
*/
private fun getKey(download: Download): String {
return download.chapter.id!!.toString()
}
/**
* Returns the list of downloads to restore. It should be called in a background thread.
*/
fun restore(): List<Download> {
val objs = preferences.all
.mapNotNull { it.value as? String }
.mapNotNull { deserialize(it) }
.sortedBy { it.order }
val downloads = mutableListOf<Download>()
if (objs.isNotEmpty()) {
val cachedManga = mutableMapOf<Long, Manga?>()
for ((mangaId, chapterId) in objs) {
val manga = cachedManga.getOrPut(mangaId) {
db.getManga(mangaId).executeAsBlocking()
} ?: continue
val source = sourceManager.get(manga.source) as? HttpSource ?: continue
val chapter = db.getChapter(chapterId).executeAsBlocking() ?: continue
downloads.add(Download(source, manga, chapter))
}
}
// Clear the store, downloads will be added again immediately.
clear()
return downloads
}
/**
* Converts a download to a string.
*
* @param download the download to serialize.
*/
private fun serialize(download: Download): String {
val obj = DownloadObject(download.manga.id!!, download.chapter.id!!, counter++)
return gson.toJson(obj)
}
/**
* Restore a download from a string.
*
* @param string the download as string.
*/
private fun deserialize(string: String): DownloadObject? {
return try {
gson.fromJson(string, DownloadObject::class.java)
} catch (e: Exception) {
null
}
}
/**
* Class used for download serialization
*
* @param mangaId the id of the manga.
* @param chapterId the id of the chapter.
* @param order the order of the download in the queue.
*/
data class DownloadObject(val mangaId: Long, val chapterId: Long, val order: Int)
}
| apache-2.0 |
AnnSofiAhn/15 | contest/app/src/main/kotlin/isotop/se/isotop15/backend/Dronis.kt | 1 | 550 | package isotop.se.isotop15.backend
import io.reactivex.Observable
import isotop.se.isotop15.models.DronisResponse
import retrofit2.http.GET
import retrofit2.http.Query
/**
* @author Ann-Sofi Åhn
*
* Created on 17/02/10.
*/
interface Dronis {
@GET("start")
fun startGame(): Observable<DronisResponse>
@GET("fake/start")
fun startFakeGame(@Query("n") size: Int): Observable<DronisResponse>
@GET("time")
fun getTime(): Observable<DronisResponse>
@GET("fake/time")
fun getFakeTime(): Observable<DronisResponse>
} | mit |
olivierperez/crapp | feature-dashboard/src/main/java/fr/o80/sample/featuredashboard/presentation/ui/DashboardFragment.kt | 1 | 992 | package fr.o80.sample.featuredashboard.presentation.ui
import android.os.Bundle
import fr.o80.sample.featuredashboard.R
import fr.o80.sample.featuredashboard.presentation.presenter.DashboardPresenter
import fr.o80.sample.featuredashboard.presentation.presenter.DashboardView
import fr.o80.sample.lib.core.ui.BaseFragment
import kotlinx.android.synthetic.main.fragment_dashboard.*
import javax.inject.Inject
/**
* @author Olivier Perez
*/
class DashboardFragment : BaseFragment(), DashboardView {
@Inject
lateinit var presenter: DashboardPresenter
override val layoutId: Int
get() = R.layout.fragment_dashboard
override fun presenter(): DashboardPresenter {
return presenter
}
override fun inject() {
(activity as DashboardActivity).component.inject(this)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
textView.setText(R.string.lorem_ipsum)
}
}
| apache-2.0 |
CarlosEsco/tachiyomi | source-api/src/main/java/eu/kanade/tachiyomi/source/model/Filter.kt | 3 | 1592 | package eu.kanade.tachiyomi.source.model
sealed class Filter<T>(val name: String, var state: T) {
open class Header(name: String) : Filter<Any>(name, 0)
open class Separator(name: String = "") : Filter<Any>(name, 0)
abstract class Select<V>(name: String, val values: Array<V>, state: Int = 0) : Filter<Int>(name, state)
abstract class Text(name: String, state: String = "") : Filter<String>(name, state)
abstract class CheckBox(name: String, state: Boolean = false) : Filter<Boolean>(name, state)
abstract class TriState(name: String, state: Int = STATE_IGNORE) : Filter<Int>(name, state) {
fun isIgnored() = state == STATE_IGNORE
fun isIncluded() = state == STATE_INCLUDE
fun isExcluded() = state == STATE_EXCLUDE
companion object {
const val STATE_IGNORE = 0
const val STATE_INCLUDE = 1
const val STATE_EXCLUDE = 2
}
}
abstract class Group<V>(name: String, state: List<V>) : Filter<List<V>>(name, state)
abstract class Sort(name: String, val values: Array<String>, state: Selection? = null) :
Filter<Sort.Selection?>(name, state) {
data class Selection(val index: Int, val ascending: Boolean)
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Filter<*>) return false
return name == other.name && state == other.state
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + (state?.hashCode() ?: 0)
return result
}
}
| apache-2.0 |
google/filament | android/samples/sample-texture-view/src/main/java/com/google/android/filament/textureview/MainActivity.kt | 1 | 13002 | /*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.filament.textureview
import android.animation.ValueAnimator
import android.app.Activity
import android.opengl.Matrix
import android.os.Bundle
import android.view.Choreographer
import android.view.Surface
import android.view.TextureView
import android.view.animation.LinearInterpolator
import com.google.android.filament.*
import com.google.android.filament.RenderableManager.PrimitiveType
import com.google.android.filament.VertexBuffer.AttributeType
import com.google.android.filament.VertexBuffer.VertexAttribute
import com.google.android.filament.android.DisplayHelper
import com.google.android.filament.android.UiHelper
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.channels.Channels
import kotlin.math.PI
import kotlin.math.cos
import kotlin.math.sin
class MainActivity : Activity() {
// Make sure to initialize Filament first
// This loads the JNI library needed by most API calls
companion object {
init {
Filament.init()
}
}
// The View we want to render into
private lateinit var textureView: TextureView
// UiHelper is provided by Filament to manage SurfaceView and SurfaceTexture
private lateinit var uiHelper: UiHelper
// DisplayHelper is provided by Filament to manage the display
private lateinit var displayHelper: DisplayHelper
// Choreographer is used to schedule new frames
private lateinit var choreographer: Choreographer
// Engine creates and destroys Filament resources
// Each engine must be accessed from a single thread of your choosing
// Resources cannot be shared across engines
private lateinit var engine: Engine
// A renderer instance is tied to a single surface (SurfaceView, TextureView, etc.)
private lateinit var renderer: Renderer
// A scene holds all the renderable, lights, etc. to be drawn
private lateinit var scene: Scene
// A view defines a viewport, a scene and a camera for rendering
private lateinit var view: View
// Should be pretty obvious :)
private lateinit var camera: Camera
private lateinit var material: Material
private lateinit var vertexBuffer: VertexBuffer
private lateinit var indexBuffer: IndexBuffer
// Filament entity representing a renderable object
@Entity private var renderable = 0
// A swap chain is Filament's representation of a surface
private var swapChain: SwapChain? = null
// Performs the rendering and schedules new frames
private val frameScheduler = FrameCallback()
private val animator = ValueAnimator.ofFloat(0.0f, 360.0f)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
textureView = TextureView(this)
setContentView(textureView)
choreographer = Choreographer.getInstance()
displayHelper = DisplayHelper(this)
setupSurfaceView()
setupFilament()
setupView()
setupScene()
}
private fun setupSurfaceView() {
uiHelper = UiHelper(UiHelper.ContextErrorPolicy.DONT_CHECK)
uiHelper.renderCallback = SurfaceCallback()
// NOTE: To choose a specific rendering resolution, add the following line:
// uiHelper.setDesiredSize(1280, 720)
uiHelper.attachTo(textureView)
}
private fun setupFilament() {
engine = Engine.create()
renderer = engine.createRenderer()
scene = engine.createScene()
view = engine.createView()
camera = engine.createCamera(engine.entityManager.create())
}
private fun setupView() {
scene.skybox = Skybox.Builder().color(0.035f, 0.035f, 0.035f, 1.0f).build(engine)
// NOTE: Try to disable post-processing (tone-mapping, etc.) to see the difference
// view.isPostProcessingEnabled = false
// Tell the view which camera we want to use
view.camera = camera
// Tell the view which scene we want to render
view.scene = scene
}
private fun setupScene() {
loadMaterial()
createMesh()
// To create a renderable we first create a generic entity
renderable = EntityManager.get().create()
// We then create a renderable component on that entity
// A renderable is made of several primitives; in this case we declare only 1
RenderableManager.Builder(1)
// Overall bounding box of the renderable
.boundingBox(Box(0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.01f))
// Sets the mesh data of the first primitive
.geometry(0, PrimitiveType.TRIANGLES, vertexBuffer, indexBuffer, 0, 3)
// Sets the material of the first primitive
.material(0, material.defaultInstance)
.build(engine, renderable)
// Add the entity to the scene to render it
scene.addEntity(renderable)
startAnimation()
}
private fun loadMaterial() {
readUncompressedAsset("materials/baked_color.filamat").let {
material = Material.Builder().payload(it, it.remaining()).build(engine)
}
}
private fun createMesh() {
val intSize = 4
val floatSize = 4
val shortSize = 2
// A vertex is a position + a color:
// 3 floats for XYZ position, 1 integer for color
val vertexSize = 3 * floatSize + intSize
// Define a vertex and a function to put a vertex in a ByteBuffer
data class Vertex(val x: Float, val y: Float, val z: Float, val color: Int)
fun ByteBuffer.put(v: Vertex): ByteBuffer {
putFloat(v.x)
putFloat(v.y)
putFloat(v.z)
putInt(v.color)
return this
}
// We are going to generate a single triangle
val vertexCount = 3
val a1 = PI * 2.0 / 3.0
val a2 = PI * 4.0 / 3.0
val vertexData = ByteBuffer.allocate(vertexCount * vertexSize)
// It is important to respect the native byte order
.order(ByteOrder.nativeOrder())
.put(Vertex(1.0f, 0.0f, 0.0f, 0xffff0000.toInt()))
.put(Vertex(cos(a1).toFloat(), sin(a1).toFloat(), 0.0f, 0xff00ff00.toInt()))
.put(Vertex(cos(a2).toFloat(), sin(a2).toFloat(), 0.0f, 0xff0000ff.toInt()))
// Make sure the cursor is pointing in the right place in the byte buffer
.flip()
// Declare the layout of our mesh
vertexBuffer = VertexBuffer.Builder()
.bufferCount(1)
.vertexCount(vertexCount)
// Because we interleave position and color data we must specify offset and stride
// We could use de-interleaved data by declaring two buffers and giving each
// attribute a different buffer index
.attribute(VertexAttribute.POSITION, 0, AttributeType.FLOAT3, 0, vertexSize)
.attribute(VertexAttribute.COLOR, 0, AttributeType.UBYTE4, 3 * floatSize, vertexSize)
// We store colors as unsigned bytes but since we want values between 0 and 1
// in the material (shaders), we must mark the attribute as normalized
.normalized(VertexAttribute.COLOR)
.build(engine)
// Feed the vertex data to the mesh
// We only set 1 buffer because the data is interleaved
vertexBuffer.setBufferAt(engine, 0, vertexData)
// Create the indices
val indexData = ByteBuffer.allocate(vertexCount * shortSize)
.order(ByteOrder.nativeOrder())
.putShort(0)
.putShort(1)
.putShort(2)
.flip()
indexBuffer = IndexBuffer.Builder()
.indexCount(3)
.bufferType(IndexBuffer.Builder.IndexType.USHORT)
.build(engine)
indexBuffer.setBuffer(engine, indexData)
}
private fun startAnimation() {
// Animate the triangle
animator.interpolator = LinearInterpolator()
animator.duration = 4000
animator.repeatMode = ValueAnimator.RESTART
animator.repeatCount = ValueAnimator.INFINITE
animator.addUpdateListener(object : ValueAnimator.AnimatorUpdateListener {
val transformMatrix = FloatArray(16)
override fun onAnimationUpdate(a: ValueAnimator) {
Matrix.setRotateM(transformMatrix, 0, -(a.animatedValue as Float), 0.0f, 0.0f, 1.0f)
val tcm = engine.transformManager
tcm.setTransform(tcm.getInstance(renderable), transformMatrix)
}
})
animator.start()
}
override fun onResume() {
super.onResume()
choreographer.postFrameCallback(frameScheduler)
animator.start()
}
override fun onPause() {
super.onPause()
choreographer.removeFrameCallback(frameScheduler)
animator.cancel()
}
override fun onDestroy() {
super.onDestroy()
// Stop the animation and any pending frame
choreographer.removeFrameCallback(frameScheduler)
animator.cancel();
// Always detach the surface before destroying the engine
uiHelper.detach()
// Cleanup all resources
engine.destroyEntity(renderable)
engine.destroyRenderer(renderer)
engine.destroyVertexBuffer(vertexBuffer)
engine.destroyIndexBuffer(indexBuffer)
engine.destroyMaterial(material)
engine.destroyView(view)
engine.destroyScene(scene)
engine.destroyCameraComponent(camera.entity)
// Engine.destroyEntity() destroys Filament related resources only
// (components), not the entity itself
val entityManager = EntityManager.get()
entityManager.destroy(renderable)
entityManager.destroy(camera.entity)
// Destroying the engine will free up any resource you may have forgotten
// to destroy, but it's recommended to do the cleanup properly
engine.destroy()
}
inner class FrameCallback : Choreographer.FrameCallback {
override fun doFrame(frameTimeNanos: Long) {
// Schedule the next frame
choreographer.postFrameCallback(this)
// This check guarantees that we have a swap chain
if (uiHelper.isReadyToRender) {
// If beginFrame() returns false you should skip the frame
// This means you are sending frames too quickly to the GPU
if (renderer.beginFrame(swapChain!!, frameTimeNanos)) {
renderer.render(view)
renderer.endFrame()
}
}
}
}
inner class SurfaceCallback : UiHelper.RendererCallback {
override fun onNativeWindowChanged(surface: Surface) {
swapChain?.let { engine.destroySwapChain(it) }
swapChain = engine.createSwapChain(surface, uiHelper.swapChainFlags)
displayHelper.attach(renderer, textureView.display)
}
override fun onDetachedFromSurface() {
displayHelper.detach()
swapChain?.let {
engine.destroySwapChain(it)
// Required to ensure we don't return before Filament is done executing the
// destroySwapChain command, otherwise Android might destroy the Surface
// too early
engine.flushAndWait()
swapChain = null
}
}
override fun onResized(width: Int, height: Int) {
val zoom = 1.5
val aspect = width.toDouble() / height.toDouble()
camera.setProjection(Camera.Projection.ORTHO,
-aspect * zoom, aspect * zoom, -zoom, zoom, 0.0, 10.0)
view.viewport = Viewport(0, 0, width, height)
}
}
private fun readUncompressedAsset(assetName: String): ByteBuffer {
assets.openFd(assetName).use { fd ->
val input = fd.createInputStream()
val dst = ByteBuffer.allocate(fd.length.toInt())
val src = Channels.newChannel(input)
src.read(dst)
src.close()
return dst.apply { rewind() }
}
}
}
| apache-2.0 |
jdiazcano/modulartd | editor/core/src/main/kotlin/com/jdiazcano/modulartd/ui/widgets/AnimatedButton.kt | 1 | 2772 | package com.jdiazcano.modulartd.ui.widgets
import com.badlogic.gdx.graphics.g2d.Batch
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.ui.Button
import com.jdiazcano.modulartd.beans.MapObject
import com.jdiazcano.modulartd.beans.Resource
import com.jdiazcano.modulartd.ui.AnimatedActor
import com.kotcrab.vis.ui.Focusable
import com.kotcrab.vis.ui.VisUI
import com.kotcrab.vis.ui.widget.VisImageButton
class AnimatedButton(mapObject: MapObject = MapObject.EMPTY) : Button(), Focusable {
private lateinit var style: VisImageButton.VisImageButtonStyle
var mapObject: MapObject = mapObject
set(value) {
field = value
actor.rotation = value.rotationAngle
actor.swapResource(value.resource)
}
private var drawBorder: Boolean = false
val actor = AnimatedActor(mapObject.resource)
init {
setStyle(VisImageButton.VisImageButtonStyle(VisUI.getSkin().get(VisImageButton.VisImageButtonStyle::class.java)))
add(actor).size(50F)
setSize(prefWidth, prefHeight)
addListener(object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
//TODO fix this if (!isDisabled) FocusManager.getFocus(this@AnimatedButton)
return false
}
})
}
override fun setRotation(degrees: Float) {
actor.rotation = degrees
mapObject.rotationAngle = degrees
}
override fun getRotation(): Float {
return actor.rotation
}
var resource: Resource
get() = mapObject.resource
set(value) {
actor.swapResource(value)
mapObject.resource = value
}
var animationTimer: Float
get() = actor.spriteTimer
set(value) {
actor.spriteTimer = value
}
override fun setStyle(style: Button.ButtonStyle) {
if (style !is VisImageButton.VisImageButtonStyle) throw IllegalArgumentException("style must be an ImageButtonStyle.")
super.setStyle(style)
this.style = style
}
override fun getStyle(): VisImageButton.VisImageButtonStyle {
return style
}
override fun draw(batch: Batch, parentAlpha: Float) {
super.draw(batch, parentAlpha)
if (drawBorder) style.focusBorder.draw(batch, x, y, width, height)
}
override fun setDisabled(disabled: Boolean) {
super.setDisabled(disabled)
// TODO Fix this if (disabled) FocusManager.getFocus()
}
override fun focusLost() {
drawBorder = false
}
override fun focusGained() {
drawBorder = true
}
} | apache-2.0 |
Heiner1/AndroidAPS | wear/src/test/java/info/nightscout/androidaps/testing/mocks/SharedPreferencesMock.kt | 1 | 3393 | package info.nightscout.androidaps.testing.mocks
import android.content.SharedPreferences
import android.content.SharedPreferences.OnSharedPreferenceChangeListener
class SharedPreferencesMock : SharedPreferences {
private val editor = EditorInternals()
internal class EditorInternals : SharedPreferences.Editor {
var innerMap: MutableMap<String, Any?> = HashMap()
override fun putString(k: String, v: String?): SharedPreferences.Editor {
innerMap[k] = v
return this
}
override fun putStringSet(k: String, set: Set<String>?): SharedPreferences.Editor {
innerMap[k] = set
return this
}
override fun putInt(k: String, i: Int): SharedPreferences.Editor {
innerMap[k] = i
return this
}
override fun putLong(k: String, l: Long): SharedPreferences.Editor {
innerMap[k] = l
return this
}
override fun putFloat(k: String, v: Float): SharedPreferences.Editor {
innerMap[k] = v
return this
}
override fun putBoolean(k: String, b: Boolean): SharedPreferences.Editor {
innerMap[k] = b
return this
}
override fun remove(k: String): SharedPreferences.Editor {
innerMap.remove(k)
return this
}
override fun clear(): SharedPreferences.Editor {
innerMap.clear()
return this
}
override fun commit(): Boolean {
return true
}
override fun apply() {}
}
override fun getAll(): Map<String, *> {
return editor.innerMap
}
override fun getString(k: String, s: String?): String? {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as String?
} else {
s
}
}
@Suppress("UNCHECKED_CAST")
override fun getStringSet(k: String, set: Set<String>?): Set<String>? {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Set<String>?
} else {
set
}
}
override fun getInt(k: String, i: Int): Int {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Int
} else {
i
}
}
override fun getLong(k: String, l: Long): Long {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Long
} else {
l
}
}
override fun getFloat(k: String, v: Float): Float {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Float
} else {
v
}
}
override fun getBoolean(k: String, b: Boolean): Boolean {
return if (editor.innerMap.containsKey(k)) {
editor.innerMap[k] as Boolean
} else {
b
}
}
override fun contains(k: String): Boolean {
return editor.innerMap.containsKey(k)
}
override fun edit(): SharedPreferences.Editor {
return editor
}
override fun registerOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener: OnSharedPreferenceChangeListener) {}
override fun unregisterOnSharedPreferenceChangeListener(onSharedPreferenceChangeListener: OnSharedPreferenceChangeListener) {}
} | agpl-3.0 |
exponentjs/exponent | android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/host/exp/exponent/modules/api/screens/ScreenStackHeaderSubviewManager.kt | 2 | 1353 | package abi44_0_0.host.exp.exponent.modules.api.screens
import abi44_0_0.com.facebook.react.bridge.JSApplicationIllegalArgumentException
import abi44_0_0.com.facebook.react.module.annotations.ReactModule
import abi44_0_0.com.facebook.react.uimanager.ThemedReactContext
import abi44_0_0.com.facebook.react.uimanager.annotations.ReactProp
import abi44_0_0.com.facebook.react.views.view.ReactViewGroup
import abi44_0_0.com.facebook.react.views.view.ReactViewManager
@ReactModule(name = ScreenStackHeaderSubviewManager.REACT_CLASS)
class ScreenStackHeaderSubviewManager : ReactViewManager() {
override fun getName(): String {
return REACT_CLASS
}
override fun createViewInstance(context: ThemedReactContext): ReactViewGroup {
return ScreenStackHeaderSubview(context)
}
@ReactProp(name = "type")
fun setType(view: ScreenStackHeaderSubview, type: String) {
view.type = when (type) {
"left" -> ScreenStackHeaderSubview.Type.LEFT
"center" -> ScreenStackHeaderSubview.Type.CENTER
"right" -> ScreenStackHeaderSubview.Type.RIGHT
"back" -> ScreenStackHeaderSubview.Type.BACK
"searchBar" -> ScreenStackHeaderSubview.Type.SEARCH_BAR
else -> throw JSApplicationIllegalArgumentException("Unknown type $type")
}
}
companion object {
const val REACT_CLASS = "RNSScreenStackHeaderSubview"
}
}
| bsd-3-clause |
slak44/gitforandroid | fslistview/src/main/java/slak/fslistview/FSArrayAdapter.kt | 1 | 1147 | package slak.fslistview
import android.content.Context
import android.support.annotation.LayoutRes
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import java.io.File
import java.util.ArrayList
internal class FSArrayAdapter(context: Context,
@LayoutRes resource: Int,
private val nodes: ArrayList<SelectableAdapterModel<File>>,
private val lv: FSListView
) : ArrayAdapter<SelectableAdapterModel<File>>(context, resource, nodes) {
override fun getViewTypeCount(): Int = 2
override fun getItemViewType(position: Int): Int = when (true) {
nodes[position].thing.isDirectory -> 0
nodes[position].thing.isFile -> 1
else -> 1
}
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
val v = lv.onChildViewPrepare(context, nodes[position].thing, convertView, parent)
v.text = nodes[position].thing.name
v.type = when (getItemViewType(position)) {
0 -> FSItemType.FOLDER
1 -> FSItemType.FILE
else -> FSItemType.NONE
}
return v
}
}
| mit |
Heiner1/AndroidAPS | medtronic/src/test/java/info/nightscout/androidaps/TestBase.kt | 1 | 4451 | package info.nightscout.androidaps
import dagger.android.AndroidInjector
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkUtil
import info.nightscout.androidaps.plugins.pump.common.sync.PumpSyncStorage
import info.nightscout.androidaps.plugins.pump.common.utils.ByteUtil
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.MedtronicPumpHistoryDecoder
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntry
import info.nightscout.androidaps.plugins.pump.medtronic.comm.history.pump.PumpHistoryEntryType
import info.nightscout.androidaps.plugins.pump.medtronic.util.MedtronicUtil
import info.nightscout.shared.logging.AAPSLoggerTest
import info.nightscout.androidaps.utils.rx.AapsSchedulers
import info.nightscout.androidaps.utils.rx.TestAapsSchedulers
import info.nightscout.shared.sharedPreferences.SP
import org.junit.Before
import org.junit.Rule
import org.mockito.Answers
import org.mockito.Mock
import org.mockito.Mockito
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
import java.util.*
open class TestBase {
val aapsLogger = AAPSLoggerTest()
val aapsSchedulers: AapsSchedulers = TestAapsSchedulers()
var rxBus: RxBus = RxBus(TestAapsSchedulers(), aapsLogger)
var byteUtil = ByteUtil()
var rileyLinkUtil = RileyLinkUtil()
@Mock lateinit var pumpSync: PumpSync
@Mock lateinit var pumpSyncStorage: PumpSyncStorage
@Mock(answer = Answers.RETURNS_DEEP_STUBS) lateinit var activePlugin: ActivePlugin
@Mock lateinit var sp: SP
@Mock lateinit var rh: ResourceHelper
lateinit var medtronicUtil : MedtronicUtil
lateinit var decoder : MedtronicPumpHistoryDecoder
val packetInjector = HasAndroidInjector {
AndroidInjector {
}
}
// Add a JUnit rule that will setup the @Mock annotated vars and log.
// Another possibility would be to add `MockitoAnnotations.initMocks(this) to the setup method.
@get:Rule
val mockitoRule: MockitoRule = MockitoJUnit.rule()
@Before
fun setupLocale() {
Locale.setDefault(Locale.ENGLISH)
System.setProperty("disableFirebase", "true")
}
// Workaround for Kotlin nullability.
// https://medium.com/@elye.project/befriending-kotlin-and-mockito-1c2e7b0ef791
// https://stackoverflow.com/questions/30305217/is-it-possible-to-use-mockito-in-kotlin
fun <T> anyObject(): T {
Mockito.any<T>()
return uninitialized()
}
fun preProcessListTBR(inputList: MutableList<PumpHistoryEntry>) {
var tbrs: MutableList<PumpHistoryEntry> = mutableListOf()
for (pumpHistoryEntry in inputList) {
if (pumpHistoryEntry.entryType === PumpHistoryEntryType.TempBasalRate ||
pumpHistoryEntry.entryType === PumpHistoryEntryType.TempBasalDuration) {
tbrs.add(pumpHistoryEntry)
}
}
inputList.removeAll(tbrs)
inputList.addAll(preProcessTBRs(tbrs))
sort(inputList)
//return inputList
}
private fun preProcessTBRs(TBRs_Input: MutableList<PumpHistoryEntry>): MutableList<PumpHistoryEntry> {
val tbrs: MutableList<PumpHistoryEntry> = mutableListOf()
val map: MutableMap<String?, PumpHistoryEntry?> = HashMap()
for (pumpHistoryEntry in TBRs_Input) {
if (map.containsKey(pumpHistoryEntry.DT)) {
decoder.decodeTempBasal(map[pumpHistoryEntry.DT]!!, pumpHistoryEntry)
pumpHistoryEntry.setEntryType(medtronicUtil.medtronicPumpModel, PumpHistoryEntryType.TempBasalCombined)
tbrs.add(pumpHistoryEntry)
map.remove(pumpHistoryEntry.DT)
} else {
map[pumpHistoryEntry.DT] = pumpHistoryEntry
}
}
return tbrs
}
private fun sort(list: MutableList<PumpHistoryEntry>) {
// if (list != null && !list.isEmpty()) {
// Collections.sort(list, PumpHistoryEntry.Comparator())
// }
list.sortWith(PumpHistoryEntry.Comparator())
}
@Suppress("Unchecked_Cast")
fun <T> uninitialized(): T = null as T
} | agpl-3.0 |
okode/spring-reactor-ionic | backend/src/test/kotlin/com/okode/sri/ApplicationTests.kt | 1 | 314 | package com.okode.sri
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit4.SpringRunner
@RunWith(SpringRunner::class)
@SpringBootTest
class ApplicationTests {
@Test
fun contextLoads() {
}
}
| mit |
xiprox/Tensuu | app/src/main/java/tr/xip/scd/tensuu/ui/main/MainView.kt | 1 | 585 | package tr.xip.scd.tensuu.ui.main
import android.support.v4.app.Fragment
import com.hannesdorfmann.mosby3.mvp.MvpView
import io.realm.Realm
interface MainView : MvpView {
fun setSelectedContentId(id: Int)
fun setContentFragment(fragment: Fragment, tag: String)
fun getFragmentByTag(tag: String): Fragment?
fun getCurrentNavigationId(): Int
fun showFab(show: Boolean = true)
fun showAddPointDialog(realm: Realm)
fun showAddListDialog(realm: Realm)
fun showSignOutDialog()
fun startLoginActivity()
fun startAdminToolsActivity()
fun die()
} | gpl-3.0 |
Maccimo/intellij-community | plugins/ide-features-trainer/src/training/learn/lesson/general/navigation/RecentFilesLesson.kt | 3 | 8785 | // 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.navigation
import com.intellij.CommonBundle
import com.intellij.ide.IdeBundle
import com.intellij.ide.actions.Switcher
import com.intellij.ide.actions.ui.JBListWithOpenInRightSplit
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.ui.Messages
import com.intellij.ui.SearchTextField
import com.intellij.ui.SimpleColoredComponent
import com.intellij.ui.components.JBList
import com.intellij.ui.components.fields.ExtendableTextField
import com.intellij.ui.speedSearch.SpeedSearchSupply
import com.intellij.util.ui.UIUtil
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.lesson.LessonManager
import training.util.isToStringContains
import java.awt.event.KeyEvent
import javax.swing.JComponent
import javax.swing.JLabel
import kotlin.math.min
abstract class RecentFilesLesson : KLesson("Recent Files and Locations", LessonsBundle.message("recent.files.lesson.name")) {
abstract override val sampleFilePath: String
abstract val transitionMethodName: String
abstract val transitionFileName: String
abstract val stringForRecentFilesSearch: String // should look like transitionMethodName
abstract fun LessonContext.setInitialPosition()
private val countOfFilesToOpen: Int = 20
private val countOfFilesToDelete: Int = 5
override val lessonContent: LessonContext.() -> Unit = {
sdkConfigurationTasks()
setInitialPosition()
task("GotoDeclaration") {
text(LessonsBundle.message("recent.files.first.transition", code(transitionMethodName), action(it)))
stateCheck { virtualFile.name.contains(transitionFileName) }
restoreIfModifiedOrMoved()
test { actions(it) }
}
waitBeforeContinue(500)
prepareRuntimeTask {
if (!TaskTestContext.inTestMode) {
val userDecision = Messages.showOkCancelDialog(
LessonsBundle.message("recent.files.dialog.message"),
LessonsBundle.message("recent.files.dialog.title"),
CommonBundle.message("button.ok"),
LearnBundle.message("learn.stop.lesson"),
FeaturesTrainerIcons.Img.PluginIcon
)
if (userDecision != Messages.OK) {
LessonManager.instance.stopLesson()
}
}
}
openManyFiles()
task("RecentFiles") {
text(LessonsBundle.message("recent.files.show.recent.files", action(it)))
triggerOnRecentFilesShown()
test { actions(it) }
}
task("rfd") {
text(LessonsBundle.message("recent.files.search.typing", code(it)))
triggerUI().component { ui: ExtendableTextField ->
ui.javaClass.name.contains("SpeedSearchBase\$SearchField")
}
stateCheck { checkRecentFilesSearch(it) }
restoreByUi()
test {
ideFrame {
waitComponent(Switcher.SwitcherPanel::class.java)
}
type(it)
}
}
task {
text(LessonsBundle.message("recent.files.search.jump", LessonUtil.rawEnter()))
stateCheck { virtualFile.name == sampleFilePath.substringAfterLast("/") }
restoreState {
!checkRecentFilesSearch("rfd") || previous.ui?.isShowing != true
}
test(waitEditorToBeReady = false) {
invokeActionViaShortcut("ENTER")
}
}
task("RecentFiles") {
text(LessonsBundle.message("recent.files.use.recent.files.again", action(it)))
triggerOnRecentFilesShown()
test { actions(it) }
}
var initialRecentFilesCount = -1
var curRecentFilesCount: Int
task {
text(LessonsBundle.message("recent.files.delete", strong(countOfFilesToDelete.toString()),
LessonUtil.rawKeyStroke(KeyEvent.VK_DELETE)))
triggerUI().component l@{ list: JBListWithOpenInRightSplit<*> ->
if (list != focusOwner) return@l false
if (initialRecentFilesCount == -1) {
initialRecentFilesCount = list.itemsCount
}
curRecentFilesCount = list.itemsCount
initialRecentFilesCount - curRecentFilesCount >= countOfFilesToDelete
}
restoreByUi()
test {
repeat(countOfFilesToDelete) {
invokeActionViaShortcut("DELETE")
}
}
}
task {
text(LessonsBundle.message("recent.files.close.popup", LessonUtil.rawKeyStroke(KeyEvent.VK_ESCAPE)))
stateCheck { previous.ui?.isShowing != true }
test { invokeActionViaShortcut("ESCAPE") }
}
task("RecentLocations") {
text(LessonsBundle.message("recent.files.show.recent.locations", action(it)))
val recentLocationsText = IdeBundle.message("recent.locations.popup.title")
triggerUI().component { ui: SimpleColoredComponent ->
ui.getCharSequence(true) == recentLocationsText
}
test { actions(it) }
}
task(stringForRecentFilesSearch) {
text(LessonsBundle.message("recent.files.locations.search.typing", code(it)))
stateCheck { checkRecentLocationsSearch(it) }
triggerUI().component { _: SearchTextField -> true } // needed in next task to restore if search field closed
restoreByUi()
test {
ideFrame {
waitComponent(JBList::class.java)
}
type(it)
}
}
task {
text(LessonsBundle.message("recent.files.locations.search.jump", LessonUtil.rawEnter()))
triggerAndBorderHighlight().listItem { item ->
item.isToStringContains(transitionFileName)
}
stateCheck { virtualFile.name.contains(transitionFileName) }
restoreState {
!checkRecentLocationsSearch(stringForRecentFilesSearch) || previous.ui?.isShowing != true
}
test {
waitAndUsePreviouslyFoundListItem { it.doubleClick() }
}
}
}
// Should open (countOfFilesToOpen - 1) files
open fun LessonContext.openManyFiles() {
task {
addFutureStep {
val curFile = virtualFile
val task = object : Task.Backgroundable(project, LessonsBundle.message("recent.files.progress.title"), true) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
val files = curFile.parent?.children?.filter { it.name != curFile.name }
?: throw IllegalStateException("Not found neighbour files for ${curFile.name}")
for (i in 0 until min(countOfFilesToOpen - 1, files.size)) {
invokeAndWaitIfNeeded(ModalityState.NON_MODAL) {
if (!indicator.isCanceled) {
FileEditorManager.getInstance(project).openFile(files[i], true)
indicator.fraction = (i + 1).toDouble() / (countOfFilesToOpen - 1)
}
}
}
taskInvokeLater { completeStep() }
}
}
ProgressManager.getInstance().run(task)
}
}
}
private fun TaskRuntimeContext.checkRecentFilesSearch(expected: String): Boolean {
val focusOwner = UIUtil.getParentOfType(Switcher.SwitcherPanel::class.java, focusOwner)
return focusOwner != null && checkWordInSearch(expected, focusOwner)
}
private fun TaskRuntimeContext.checkRecentLocationsSearch(expected: String): Boolean {
val focusOwner = focusOwner
return focusOwner is JBList<*> && checkWordInSearch(expected, focusOwner)
}
private fun checkWordInSearch(expected: String, component: JComponent): Boolean {
val supply = SpeedSearchSupply.getSupply(component)
val enteredPrefix = supply?.enteredPrefix ?: return false
return enteredPrefix.equals(expected, ignoreCase = true)
}
private fun TaskContext.triggerOnRecentFilesShown() {
val recentFilesText = IdeBundle.message("title.popup.recent.files")
triggerUI().component { ui: JLabel ->
ui.text == recentFilesText
}
}
override val testScriptProperties: TaskTestContext.TestScriptProperties
get() = TaskTestContext.TestScriptProperties(duration = 20)
override val suitableTips = listOf("recent-locations", "RecentFiles")
override val helpLinks: Map<String, String> get() = mapOf(
Pair(LessonsBundle.message("recent.files.locations.help.link"),
LessonUtil.getHelpLink("navigating-through-the-source-code.html#recent_locations")),
)
} | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.