content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
// GENERATED
package com.fkorotkov.openshift
import io.fabric8.openshift.api.model.DeploymentConfigStatus as model_DeploymentConfigStatus
import io.fabric8.openshift.api.model.DeploymentDetails as model_DeploymentDetails
fun model_DeploymentConfigStatus.`details`(block: model_DeploymentDetails.() -> Unit = {}) {
if(this.`details` == null) {
this.`details` = model_DeploymentDetails()
}
this.`details`.block()
}
| DSLs/kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/details.kt | 3147151327 |
package org.usfirst.frc.team4186.extensions
import edu.wpi.first.wpilibj.command.Command
import edu.wpi.first.wpilibj.command.CommandGroup
inline fun execute(
name: String,
block: CommandBuilder.() -> Unit
) = CommandBuilder(name).apply {
block()
}.target
class CommandBuilder(name: String) {
val target = CommandGroup(name)
operator fun Command.unaryPlus() = target.addParallel(this)
operator fun Command.unaryMinus() = target.addSequential(this)
operator fun Pair<Command, Double>.unaryPlus() = target.addParallel(first, second)
operator fun Pair<Command, Double>.unaryMinus() = target.addSequential(first, second)
infix fun Command.timeoutIn(timeout: Double) = Pair(this, timeout)
}
| src/main/kotlin/org/usfirst/frc/team4186/extensions/command_builder.kt | 3833004811 |
package com.excref.kotblog.blog.service.blog
import com.excref.kotblog.blog.service.blog.domain.Blog
/**
* @author Arthur Asatryan
* @since 6/10/17 7:21 PM
*/
interface BlogService {
/**
* Gets blog by uuid
*
* @param uuid The blog's uuid
* @return Blog
* @throws com.excref.kotblog.blog.service.blog.exception.BlogNotFoundForUuidException When blog not found
*/
fun getByUuid(uuid: String): Blog
/**
* Checks if blog exists for given name
*
* @param name The blog's name
* @return Boolean true if found, false otherwise
*/
fun existsForName(name: String): Boolean
/**
* Creates a new blog
*
* @param name The blog's name
* @param userUuid The user's uuid
* @return Blog if created successfully
* @throws com.excref.kotblog.blog.service.blog.exception.BlogAlreadyExistsForNameException If blog already exists
*/
fun create(name: String, userUuid: String): Blog
} | blog/service/core/src/main/kotlin/com/excref/kotblog/blog/service/blog/BlogService.kt | 2253087167 |
package eu.kanade.tachiyomi.ui.reader.loader
import eu.kanade.tachiyomi.data.cache.ChapterCache
import eu.kanade.tachiyomi.source.model.Page
import eu.kanade.tachiyomi.source.online.HttpSource
import eu.kanade.tachiyomi.ui.reader.model.ReaderChapter
import eu.kanade.tachiyomi.ui.reader.model.ReaderPage
import eu.kanade.tachiyomi.util.plusAssign
import rx.Completable
import rx.Observable
import rx.schedulers.Schedulers
import rx.subjects.PublishSubject
import rx.subjects.SerializedSubject
import rx.subscriptions.CompositeSubscription
import timber.log.Timber
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.concurrent.PriorityBlockingQueue
import java.util.concurrent.atomic.AtomicInteger
/**
* Loader used to load chapters from an online source.
*/
class HttpPageLoader(
private val chapter: ReaderChapter,
private val source: HttpSource,
private val chapterCache: ChapterCache = Injekt.get()
) : PageLoader() {
/**
* A queue used to manage requests one by one while allowing priorities.
*/
private val queue = PriorityBlockingQueue<PriorityPage>()
/**
* Current active subscriptions.
*/
private val subscriptions = CompositeSubscription()
init {
subscriptions += Observable.defer { Observable.just(queue.take().page) }
.filter { it.status == Page.QUEUE }
.concatMap { source.fetchImageFromCacheThenNet(it) }
.repeat()
.subscribeOn(Schedulers.io())
.subscribe({
}, { error ->
if (error !is InterruptedException) {
Timber.e(error)
}
})
}
/**
* Recycles this loader and the active subscriptions and queue.
*/
override fun recycle() {
super.recycle()
subscriptions.unsubscribe()
queue.clear()
// Cache current page list progress for online chapters to allow a faster reopen
val pages = chapter.pages
if (pages != null) {
Completable
.fromAction {
// Convert to pages without reader information
val pagesToSave = pages.map { Page(it.index, it.url, it.imageUrl) }
chapterCache.putPageListToCache(chapter.chapter, pagesToSave)
}
.onErrorComplete()
.subscribeOn(Schedulers.io())
.subscribe()
}
}
/**
* Returns an observable with the page list for a chapter. It tries to return the page list from
* the local cache, otherwise fallbacks to network.
*/
override fun getPages(): Observable<List<ReaderPage>> {
return chapterCache
.getPageListFromCache(chapter.chapter)
.onErrorResumeNext { source.fetchPageList(chapter.chapter) }
.map { pages ->
pages.mapIndexed { index, page ->
// Don't trust sources and use our own indexing
ReaderPage(index, page.url, page.imageUrl)
}
}
}
/**
* Returns an observable that loads a page through the queue and listens to its result to
* emit new states. It handles re-enqueueing pages if they were evicted from the cache.
*/
override fun getPage(page: ReaderPage): Observable<Int> {
return Observable.defer {
val imageUrl = page.imageUrl
// Check if the image has been deleted
if (page.status == Page.READY && imageUrl != null && !chapterCache.isImageInCache(imageUrl)) {
page.status = Page.QUEUE
}
// Automatically retry failed pages when subscribed to this page
if (page.status == Page.ERROR) {
page.status = Page.QUEUE
}
val statusSubject = SerializedSubject(PublishSubject.create<Int>())
page.setStatusSubject(statusSubject)
if (page.status == Page.QUEUE) {
queue.offer(PriorityPage(page, 1))
}
preloadNextPages(page, 4)
statusSubject.startWith(page.status)
}
}
/**
* Preloads the given [amount] of pages after the [currentPage] with a lower priority.
*/
private fun preloadNextPages(currentPage: ReaderPage, amount: Int) {
val pageIndex = currentPage.index
val pages = currentPage.chapter.pages ?: return
if (pageIndex == pages.lastIndex) return
val nextPages = pages.subList(pageIndex + 1, Math.min(pageIndex + 1 + amount, pages.size))
for (nextPage in nextPages) {
if (nextPage.status == Page.QUEUE) {
queue.offer(PriorityPage(nextPage, 0))
}
}
}
/**
* Retries a page. This method is only called from user interaction on the viewer.
*/
override fun retryPage(page: ReaderPage) {
if (page.status == Page.ERROR) {
page.status = Page.QUEUE
}
queue.offer(PriorityPage(page, 2))
}
/**
* Data class used to keep ordering of pages in order to maintain priority.
*/
private data class PriorityPage(
val page: ReaderPage,
val priority: Int
) : Comparable<PriorityPage> {
companion object {
private val idGenerator = AtomicInteger()
}
private val identifier = idGenerator.incrementAndGet()
override fun compareTo(other: PriorityPage): Int {
val p = other.priority.compareTo(priority)
return if (p != 0) p else identifier.compareTo(other.identifier)
}
}
/**
* Returns an observable of the page with the downloaded image.
*
* @param page the page whose source image has to be downloaded.
*/
private fun HttpSource.fetchImageFromCacheThenNet(page: ReaderPage): Observable<ReaderPage> {
return if (page.imageUrl.isNullOrEmpty())
getImageUrl(page).flatMap { getCachedImage(it) }
else
getCachedImage(page)
}
private fun HttpSource.getImageUrl(page: ReaderPage): Observable<ReaderPage> {
page.status = Page.LOAD_PAGE
return fetchImageUrl(page)
.doOnError { page.status = Page.ERROR }
.onErrorReturn { null }
.doOnNext { page.imageUrl = it }
.map { page }
}
/**
* Returns an observable of the page that gets the image from the chapter or fallbacks to
* network and copies it to the cache calling [cacheImage].
*
* @param page the page.
*/
private fun HttpSource.getCachedImage(page: ReaderPage): Observable<ReaderPage> {
val imageUrl = page.imageUrl ?: return Observable.just(page)
return Observable.just(page)
.flatMap {
if (!chapterCache.isImageInCache(imageUrl)) {
cacheImage(page)
} else {
Observable.just(page)
}
}
.doOnNext {
page.stream = { chapterCache.getImageFile(imageUrl).inputStream() }
page.status = Page.READY
}
.doOnError { page.status = Page.ERROR }
.onErrorReturn { page }
}
/**
* Returns an observable of the page that downloads the image to [ChapterCache].
*
* @param page the page.
*/
private fun HttpSource.cacheImage(page: ReaderPage): Observable<ReaderPage> {
page.status = Page.DOWNLOAD_IMAGE
return fetchImage(page)
.doOnNext { chapterCache.putImageToCache(page.imageUrl!!, it) }
.map { page }
}
}
| Tachiyomi-App/src/main/java/eu/kanade/tachiyomi/ui/reader/loader/HttpPageLoader.kt | 2143451858 |
package com.sksamuel.kotest.property.arbitrary
import io.kotest.assertions.retry
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.FunSpec
import io.kotest.inspectors.forAll
import io.kotest.matchers.doubles.plusOrMinus
import io.kotest.matchers.ints.shouldBeBetween
import io.kotest.matchers.shouldBe
import io.kotest.property.Arb
import io.kotest.property.RandomSource
import io.kotest.property.Sample
import io.kotest.property.arbitrary.int
import io.kotest.property.arbitrary.long
import io.kotest.property.arbitrary.orNull
import io.kotest.property.forAll
import kotlin.time.Duration
class OrNullTest : FunSpec({
test("Arb.orNull() should add null values to those generated") {
val iterations = 1000
val classifications =
forAll(iterations, Arb.int().orNull()) { num ->
classify(num == null, "null", "non-null")
true
}.classifications()
classifications["null"]?.shouldBeBetween(300, 600)
classifications["non-null"]?.shouldBeBetween(300, 600)
}
test("null probability values can be specified") {
retry(3, timeout = Duration.seconds(2), delay = Duration.seconds(0.1)) {
listOf(0.0, 0.1, 0.25, 0.5, 0.75, 0.9, 1.0)
.forAll { p: Double ->
val nullCount = Arb.long().orNull(nullProbability = p).samples(RandomSource.default())
.map(Sample<Long?>::value)
.take(1000)
.filter { it == null }
.count()
(nullCount.toDouble() / 1000) shouldBe (p plusOrMinus 0.05)
}
}
}
test("invalid null probability raise an IllegalArgumentException") {
listOf(1.01, -0.1, 4.9, 99.9)
.forAll { illegalVal ->
shouldThrow<IllegalArgumentException> { Arb.long().orNull(nullProbability = illegalVal) }
}
}
test("functions can be supplied to determine null frequency") {
listOf(true, false).forAll { isNextNull: Boolean ->
val allNull = Arb.int().orNull(isNextNull = { isNextNull }).samples(RandomSource.default())
.map(Sample<Int?>::value)
.take(100)
.all { it == null }
allNull shouldBe isNextNull
}
}
})
| kotest-property/src/jvmTest/kotlin/com/sksamuel/kotest/property/arbitrary/OrNullTest.kt | 2213878985 |
package io.heapy.komodo.file
import io.heapy.komodo.exceptions.KomodoException
import java.io.IOException
import java.io.InputStream
import java.nio.file.Files
import java.nio.file.Paths
/**
* Provider for resources located in filesystem.
*
* @author Ruslan Ibragimov
* @since 1.0
*/
class FileSystemByteStreamProvider(
private val path: String
) : ByteStreamProvider {
override fun getByteStream(): InputStream {
return try {
Files.newInputStream(Paths.get(path))
} catch (e: IOException) {
throw KomodoException("CORE-1")
}
}
}
| komodo-core/src/main/kotlin/io/heapy/komodo/file/FileSystemByteStreamProvider.kt | 617508211 |
package io.kotest.property
import io.kotest.mpp.sysprop
import kotlin.math.max
import kotlin.native.concurrent.ThreadLocal
/**
* Global object for containing settings for property testing.
*/
@ThreadLocal
object PropertyTesting {
var maxFilterAttempts: Int = 10
var shouldPrintGeneratedValues: Boolean = sysprop("kotest.proptest.output.generated-values", "false") == "true"
var shouldPrintShrinkSteps: Boolean = sysprop("kotest.proptest.output.shrink-steps", "true") == "true"
var defaultIterationCount: Int = sysprop("kotest.proptest.default.iteration.count", "1000").toInt()
var edgecasesGenerationProbability: Double = sysprop("kotest.proptest.arb.edgecases-generation-probability", "0.02").toDouble()
var edgecasesBindDeterminism: Double = sysprop("kotest.proptest.arb.edgecases-bind-determinism", "0.9").toDouble()
}
/**
* Calculates the default iterations to use for a property test.
* This value is used when a property test does not specify the iteration count.
*
* This is the max of either the [PropertyTesting.defaultIterationCount] or the
* [calculateMinimumIterations] from the supplied gens.
*/
fun computeDefaultIteration(vararg gens: Gen<*>): Int =
max(PropertyTesting.defaultIterationCount, calculateMinimumIterations(*gens))
/**
* Calculates the minimum number of iterations required for the given generators.
*
* The value per generator is calcuated as:
* - for an [Exhaustive] the total number of values is used
* - for an [Arb] the number of edge cases is used
*
* In addition, if all generators are exhaustives, then the cartesian product is used.
*/
fun calculateMinimumIterations(vararg gens: Gen<*>): Int {
return when {
gens.all { it is Exhaustive } -> gens.fold(1) { acc, gen -> gen.minIterations() * acc }
else -> gens.fold(0) { acc, gen -> max(acc, gen.minIterations()) }
}
}
fun EdgeConfig.Companion.default(): EdgeConfig = EdgeConfig(
edgecasesGenerationProbability = PropertyTesting.edgecasesGenerationProbability
)
data class PropTest(
val seed: Long? = null,
val minSuccess: Int = Int.MAX_VALUE,
val maxFailure: Int = 0,
val shrinkingMode: ShrinkingMode = ShrinkingMode.Bounded(1000),
val iterations: Int? = null,
val listeners: List<PropTestListener> = listOf(),
val edgeConfig: EdgeConfig = EdgeConfig.default()
)
fun PropTest.toPropTestConfig() =
PropTestConfig(
seed = seed,
minSuccess = minSuccess,
maxFailure = maxFailure,
iterations = iterations,
shrinkingMode = shrinkingMode,
listeners = listeners,
edgeConfig = edgeConfig
)
data class PropTestConfig(
val seed: Long? = null,
val minSuccess: Int = Int.MAX_VALUE,
val maxFailure: Int = 0,
val shrinkingMode: ShrinkingMode = ShrinkingMode.Bounded(1000),
val iterations: Int? = null,
val listeners: List<PropTestListener> = listOf(),
val edgeConfig: EdgeConfig = EdgeConfig.default()
)
interface PropTestListener {
suspend fun beforeTest(): Unit = Unit
suspend fun afterTest(): Unit = Unit
}
| kotest-property/src/commonMain/kotlin/io/kotest/property/config.kt | 2001329793 |
package deepdive.functional.monads
sealed class Option<T> {
abstract fun <U> map( f: (T) -> U ): Option<U>
abstract fun <U> flatMap( f: (T) -> Option<U> ): Option<U>
abstract fun get(): T?
abstract fun isPresent(): Boolean
abstract fun getOrElse(fallbackValue: T): T
companion object {
fun <T> of(value: T): Option<T> {
return if(value == null) None() else Some(value)
}
}
}
class Some<T> (private val value: T) : Option<T>() {
override fun <U> map( f: (T) -> U ): Option<U> = Option.of( f(value) )
override fun <U> flatMap( f: (T) -> Option<U> ): Option<U> = f(value)
override fun get(): T? = value
override fun isPresent(): Boolean = true
override fun getOrElse(fallbackValue: T): T = value
}
class None<T>: Option<T>() {
override fun <U> map( f: (T) -> U ): Option<U> = this as None<U>
override fun <U> flatMap( f: (T) -> Option<U> ): Option<U> = this as None<U>
override fun get(): T? = null
override fun isPresent(): Boolean = true
override fun getOrElse(fallbackValue: T): T = fallbackValue
} | src/main/kotlin/deepdive/functional/monads/Option.kt | 2259418242 |
/*
* Copyright (C) 2017 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.paging
import org.junit.Assert.fail
import java.util.LinkedList
import java.util.concurrent.Executor
class TestExecutor : Executor {
private val mTasks = LinkedList<Runnable>()
override fun execute(runnable: Runnable) {
mTasks.add(runnable)
}
internal fun executeAll(): Boolean {
val consumed = !mTasks.isEmpty()
var task = mTasks.poll()
while (task != null) {
task.run()
task = mTasks.poll()
}
return consumed
}
}
class FailExecutor(val string: String = "Executor expected to be unused") : Executor {
override fun execute(runnable: Runnable?) {
fail(string)
}
}
| paging/common/src/test/java/androidx/paging/Executors.kt | 961441862 |
/*
* Copyright 2017 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.android.tools.build.jetifier.processor.transform.bytecode
import com.android.tools.build.jetifier.core.config.Config
import com.android.tools.build.jetifier.core.type.JavaType
import com.android.tools.build.jetifier.core.type.TypesMap
import com.android.tools.build.jetifier.processor.transform.TransformationContext
import com.google.common.truth.Truth
import org.junit.Test
import org.objectweb.asm.ClassWriter
class CoreRemapperImplTest {
@Test
fun remapString_shouldUseFallbackForField() {
val remapper = prepareRemapper(
TypesMap(mapOf(
JavaType.fromDotVersion("androidx.test.InputConnectionCompat")
to JavaType.fromDotVersion(
"android.support.test.InputConnectionCompat")
)),
"androidx/")
val given = "androidx.test.InputConnectionCompat.CONTENT_URI"
val expected = "android.support.test.InputConnectionCompat.CONTENT_URI"
Truth.assertThat(remapper.rewriteString(given)).isEqualTo(expected)
}
private fun prepareRemapper(
typesMap: TypesMap,
restrictToPackagePrefix: String? = null
): CoreRemapperImpl {
val prefixes = if (restrictToPackagePrefix == null) {
emptySet()
} else {
setOf(restrictToPackagePrefix)
}
val config = Config.fromOptional(
restrictToPackagePrefixes = prefixes,
typesMap = typesMap)
val context = TransformationContext(config, isInReversedMode = true)
val writer = ClassWriter(0 /* flags */)
return CoreRemapperImpl(context, writer)
}
} | jetifier/jetifier/processor/src/test/kotlin/com/android/tools/build/jetifier/processor/transform/bytecode/CoreRemapperImplTest.kt | 3987129779 |
/**
* BreadWallet
*
* Created by Mihail Gutan <[email protected]> on 6/13/16.
* Copyright (c) 2016 breadwallet LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.breadwallet.tools.manager
import android.content.Context
import android.content.SharedPreferences
import android.text.format.DateUtils
import androidx.annotation.VisibleForTesting
import androidx.core.content.edit
import com.breadwallet.app.Conversion
import com.breadwallet.model.PriceAlert
import com.breadwallet.tools.util.Bip39Reader
import com.breadwallet.tools.util.ServerBundlesHelper
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.channels.BroadcastChannel
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import java.util.Currency
import java.util.Locale
import java.util.UUID
// Suppress warnings about context usage, it remains to support legacy coe.
@Suppress("UNUSED_PARAMETER")
object BRSharedPrefs {
val TAG: String = BRSharedPrefs::class.java.name
const val PREFS_NAME = "MyPrefsFile"
private const val FCM_TOKEN = "fcmToken"
private const val NOTIFICATION_ID = "notificationId"
private const val SCREEN_HEIGHT = "screenHeight"
private const val SCREEN_WIDTH = "screenWidth"
private const val BUNDLE_HASH_PREFIX = "bundleHash_"
private const val SEGWIT = "segwit"
private const val EMAIL_OPT_IN = "emailOptIn"
private const val EMAIL_OPT_IN_DISMISSED = "emailOptInDismissed"
private const val CURRENT_CURRENCY = "currentCurrency"
private const val PAPER_KEY_WRITTEN_DOWN = "phraseWritten"
private const val PREFER_STANDARD_FEE = "favorStandardFee"
private const val FEE_PREFERENCE = "feePreference"
private const val LAST_GIFT_CHECK_TIME = "lastGiftCheckTime"
@VisibleForTesting
const val RECEIVE_ADDRESS = "receive_address"
private const val FEE_RATE = "feeRate"
private const val ECONOMY_FEE_RATE = "economyFeeRate"
private const val BALANCE = "balance"
private const val SECURE_TIME = "secureTime"
private const val LAST_SYNC_TIME_PREFIX = "lastSyncTime_"
private const val LAST_RESCAN_MODE_USED_PREFIX = "lastRescanModeUsed_"
private const val LAST_SEND_TRANSACTION_BLOCK_HEIGHT_PREFIX = "lastSendTransactionBlockheight_"
private const val FEE_TIME_PREFIX = "feeTime_"
private const val ALLOW_SPEND_PREFIX = "allowSpend_"
private const val IS_CRYPTO_PREFERRED = "priceInCrypto"
private const val USE_FINGERPRINT = "useFingerprint"
private const val CURRENT_WALLET_CURRENCY_CODE = "currentWalletIso"
private const val WALLET_REWARD_ID = "walletRewardId"
private const val GEO_PERMISSIONS_REQUESTED = "geoPermissionsRequested"
private const val START_HEIGHT_PREFIX = "startHeight_"
private const val RESCAN_TIME_PREFIX = "rescanTime_"
private const val LAST_BLOCK_HEIGHT_PREFIX = "lastBlockHeight_"
private const val SCAN_RECOMMENDED_PREFIX = "scanRecommended_"
private const val PREFORK_SYNCED = "preforkSynced"
private const val CURRENCY_UNIT = "currencyUnit"
private const val USER_ID = "userId"
private const val SHOW_NOTIFICATION = "showNotification"
private const val SHARE_DATA = "shareData"
private const val NEW_WALLET = "newWallet"
private const val PROMPT_PREFIX = "prompt_"
private const val TRUST_NODE_PREFIX = "trustNode_"
private const val DEBUG_HOST = "debug_host"
private const val DEBUG_SERVER_BUNDLE = "debug_server_bundle"
private const val DEBUG_WEB_PLATFORM_URL = "debug_web_platform_url"
private const val HTTP_SERVER_PORT = "http_server_port"
private const val REWARDS_ANIMATION_SHOWN = "rewardsAnimationShown"
private const val READ_IN_APP_NOTIFICATIONS = "readInAppNotifications"
private const val PRICE_ALERTS = "priceAlerts"
private const val PRICE_ALERTS_INTERVAL = "priceAlertsInterval"
private const val LANGUAGE = "language"
private const val UNLOCK_WITH_FINGERPRINT = "unlock-with-fingerprint"
private const val CONFIRM_SEND_WITH_FINGERPRINT = "confirm-send-with-fingerprint"
private const val TRACKED_TRANSACTIONS = "tracked-transactions"
private const val APP_RATE_PROMPT_DONT_ASK_AGAIN = "app-rate-prompt-dont-ask-again"
private const val APP_RATE_PROMPT_SHOULD_PROMPT = "app-rate-prompt-should-prompt"
private const val APP_RATE_PROMPT_SHOULD_PROMPT_DEBUG = "app-rate-prompt-should-prompt-debug"
const val APP_FOREGROUNDED_COUNT = "appForegroundedCount"
const val APP_RATE_PROMPT_HAS_RATED = "appReviewPromptHasRated"
private val secureTimeFlow = MutableSharedFlow<Long>(replay = 1)
/**
* Call when Application is initialized to setup [brdPrefs].
* This removes the need for a context parameter.
*/
fun initialize(context: Context, applicationScope: CoroutineScope) {
brdPrefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
applicationScope.launch {
_trackedConversionChanges.value = getTrackedConversions()
secureTimeFlow.tryEmit(getSecureTime())
}
}
private lateinit var brdPrefs: SharedPreferences
private val promptChangeChannel = BroadcastChannel<Unit>(Channel.CONFLATED)
var lastGiftCheckTime: Long
get() = brdPrefs.getLong(LAST_GIFT_CHECK_TIME, 0L)
set(value) {
brdPrefs.edit { putLong(LAST_GIFT_CHECK_TIME, value) }
}
var phraseWroteDown: Boolean
get() = brdPrefs.getBoolean(PAPER_KEY_WRITTEN_DOWN, false)
set(value) {
brdPrefs.edit { putBoolean(PAPER_KEY_WRITTEN_DOWN, value) }
}
@JvmStatic
fun getPreferredFiatIso(): String =
brdPrefs.getString(
CURRENT_CURRENCY, try {
Currency.getInstance(Locale.getDefault()).currencyCode
} catch (e: IllegalArgumentException) {
e.printStackTrace()
Currency.getInstance(Locale.US).currencyCode
}
)!!
fun putPreferredFiatIso(iso: String) =
brdPrefs.edit {
val default = if (iso.equals(Locale.getDefault().isO3Language, ignoreCase = true)) {
null
} else iso
putString(CURRENT_CURRENCY, default)
}
fun getReceiveAddress(iso: String): String? =
brdPrefs.getString(RECEIVE_ADDRESS + iso.toUpperCase(), "")
fun putReceiveAddress(tmpAddr: String, iso: String) =
brdPrefs.edit { putString(RECEIVE_ADDRESS + iso.toUpperCase(), tmpAddr) }
@JvmStatic
fun getSecureTime() =
brdPrefs.getLong(SECURE_TIME, System.currentTimeMillis())
//secure time from the server
fun putSecureTime(date: Long) {
brdPrefs.edit { putLong(SECURE_TIME, date) }
secureTimeFlow.tryEmit(date)
}
fun secureTimeFlow(): Flow<Long> {
return secureTimeFlow
}
fun getLastSyncTime(iso: String) =
brdPrefs.getLong(LAST_SYNC_TIME_PREFIX + iso.toUpperCase(), 0)
fun putLastSyncTime(iso: String, time: Long) =
brdPrefs.edit { putLong(LAST_SYNC_TIME_PREFIX + iso.toUpperCase(), time) }
fun getLastSendTransactionBlockheight(iso: String) =
brdPrefs.getLong(LAST_SEND_TRANSACTION_BLOCK_HEIGHT_PREFIX + iso.toUpperCase(), 0)
fun putLastSendTransactionBlockheight(
iso: String,
blockHeight: Long
) = brdPrefs.edit {
putLong(LAST_SEND_TRANSACTION_BLOCK_HEIGHT_PREFIX + iso.toUpperCase(), blockHeight)
}
//if the user prefers all in crypto units, not fiat currencies
fun isCryptoPreferred(context: Context? = null): Boolean =
brdPrefs.getBoolean(IS_CRYPTO_PREFERRED, false)
//if the user prefers all in crypto units, not fiat currencies
fun setIsCryptoPreferred(b: Boolean) =
brdPrefs.edit { putBoolean(IS_CRYPTO_PREFERRED, b) }
fun getUseFingerprint(): Boolean =
brdPrefs.getBoolean(USE_FINGERPRINT, false)
fun putUseFingerprint(use: Boolean) =
brdPrefs.edit { putBoolean(USE_FINGERPRINT, use) }
fun getFeatureEnabled(feature: String): Boolean =
brdPrefs.getBoolean(feature, false)
fun putFeatureEnabled(enabled: Boolean, feature: String) =
brdPrefs.edit { putBoolean(feature, enabled) }
@JvmStatic
fun getWalletRewardId(): String? =
brdPrefs.getString(WALLET_REWARD_ID, null)
fun putWalletRewardId(id: String) =
brdPrefs.edit { putString(WALLET_REWARD_ID, id) }
fun getGeoPermissionsRequested(): Boolean =
brdPrefs.getBoolean(GEO_PERMISSIONS_REQUESTED, false)
fun putGeoPermissionsRequested(requested: Boolean) =
brdPrefs.edit { putBoolean(GEO_PERMISSIONS_REQUESTED, requested) }
fun getStartHeight(iso: String): Long =
brdPrefs.getLong(START_HEIGHT_PREFIX + iso.toUpperCase(), 0)
fun putStartHeight(iso: String, startHeight: Long) =
brdPrefs.edit { putLong(START_HEIGHT_PREFIX + iso.toUpperCase(), startHeight) }
fun getLastRescanTime(iso: String): Long =
brdPrefs.getLong(RESCAN_TIME_PREFIX + iso.toUpperCase(), 0)
fun putLastRescanTime(iso: String, time: Long) =
brdPrefs.edit { putLong(RESCAN_TIME_PREFIX + iso.toUpperCase(), time) }
fun getLastBlockHeight(iso: String): Int =
brdPrefs.getInt(LAST_BLOCK_HEIGHT_PREFIX + iso.toUpperCase(), 0)
fun putLastBlockHeight(iso: String, lastHeight: Int) =
brdPrefs.edit {
putInt(LAST_BLOCK_HEIGHT_PREFIX + iso.toUpperCase(), lastHeight)
}
fun getScanRecommended(iso: String): Boolean =
brdPrefs.getBoolean(SCAN_RECOMMENDED_PREFIX + iso.toUpperCase(), false)
fun putScanRecommended(iso: String, recommended: Boolean) =
brdPrefs.edit {
putBoolean(SCAN_RECOMMENDED_PREFIX + iso.toUpperCase(), recommended)
}
@JvmStatic
fun getDeviceId(): String =
brdPrefs.run {
if (contains(USER_ID)) {
getString(USER_ID, "")!!
} else {
UUID.randomUUID().toString().also {
edit { putString(USER_ID, it) }
}
}
}
fun getDebugHost(): String? =
brdPrefs.getString(DEBUG_HOST, "")
fun putDebugHost(host: String) =
brdPrefs.edit { putString(DEBUG_HOST, host) }
fun clearAllPrefs() = brdPrefs.edit { clear() }
@JvmStatic
fun getShowNotification(): Boolean =
brdPrefs.getBoolean(SHOW_NOTIFICATION, true)
@JvmStatic
fun putShowNotification(show: Boolean) =
brdPrefs.edit { putBoolean(SHOW_NOTIFICATION, show) }
fun getShareData(): Boolean =
brdPrefs.getBoolean(SHARE_DATA, true)
fun putShareData(show: Boolean) =
brdPrefs.edit { putBoolean(SHARE_DATA, show) }
fun getPromptDismissed(promptName: String): Boolean =
brdPrefs.getBoolean(PROMPT_PREFIX + promptName, false)
fun putPromptDismissed(promptName: String, dismissed: Boolean) =
brdPrefs.edit { putBoolean(PROMPT_PREFIX + promptName, dismissed) }
fun getTrustNode(iso: String): String? =
brdPrefs.getString(TRUST_NODE_PREFIX + iso.toUpperCase(), "")
fun putTrustNode(iso: String, trustNode: String) =
brdPrefs.edit { putString(TRUST_NODE_PREFIX + iso.toUpperCase(), trustNode) }
fun putFCMRegistrationToken(token: String) =
brdPrefs.edit { putString(FCM_TOKEN, token) }
fun getFCMRegistrationToken(): String? =
brdPrefs.getString(FCM_TOKEN, "")
fun putNotificationId(notificationId: Int) =
brdPrefs.edit { putInt(NOTIFICATION_ID, notificationId) }
fun getNotificationId(): Int =
brdPrefs.getInt(NOTIFICATION_ID, 0)
fun putScreenHeight(screenHeight: Int) =
brdPrefs.edit { putInt(SCREEN_HEIGHT, screenHeight) }
@JvmStatic
fun getScreenHeight(): Int =
brdPrefs.getInt(SCREEN_HEIGHT, 0)
fun putScreenWidth(screenWidth: Int) =
brdPrefs.edit { putInt(SCREEN_WIDTH, screenWidth) }
@JvmStatic
fun getScreenWidth(): Int =
brdPrefs.getInt(SCREEN_WIDTH, 0)
@JvmStatic
fun putBundleHash(bundleName: String, bundleHash: String) =
brdPrefs.edit { putString(BUNDLE_HASH_PREFIX + bundleName, bundleHash) }
@JvmStatic
fun getBundleHash(bundleName: String): String? =
brdPrefs.getString(BUNDLE_HASH_PREFIX + bundleName, null)
fun putIsSegwitEnabled(isEnabled: Boolean) =
brdPrefs.edit { putBoolean(SEGWIT, isEnabled) }
fun getIsSegwitEnabled(): Boolean =
brdPrefs.getBoolean(SEGWIT, false)
fun putEmailOptIn(hasOpted: Boolean) =
brdPrefs.edit { putBoolean(EMAIL_OPT_IN, hasOpted) }
fun getEmailOptIn(): Boolean =
brdPrefs.getBoolean(EMAIL_OPT_IN, false)
fun putRewardsAnimationShown(wasShown: Boolean) =
brdPrefs.edit { putBoolean(REWARDS_ANIMATION_SHOWN, wasShown) }
fun getRewardsAnimationShown(): Boolean =
brdPrefs.getBoolean(REWARDS_ANIMATION_SHOWN, false)
fun putEmailOptInDismissed(dismissed: Boolean) =
brdPrefs.edit { putBoolean(EMAIL_OPT_IN_DISMISSED, dismissed) }
fun getEmailOptInDismissed(): Boolean =
brdPrefs.getBoolean(EMAIL_OPT_IN_DISMISSED, false)
/**
* Get the debug bundle from shared preferences or empty if not available.
*
* @param bundleType Bundle type.
* @return Saved debug bundle or empty.
*/
@JvmStatic
fun getDebugBundle(bundleType: ServerBundlesHelper.Type): String? =
brdPrefs.getString(DEBUG_SERVER_BUNDLE + bundleType.name, "")
/**
* Save the bundle to use in debug mode.
*
* @param context Execution context.
* @param bundleType Bundle type.
* @param bundle Debug bundle.
*/
@JvmStatic
fun putDebugBundle(
bundleType: ServerBundlesHelper.Type,
bundle: String
) = brdPrefs.edit { putString(DEBUG_SERVER_BUNDLE + bundleType.name, bundle) }
/**
* Get the web platform debug URL from shared preferences or empty, if not available.
*
* @param context Execution context.
* @return Returns the web platform debug URL or empty.
*/
@JvmStatic
fun getWebPlatformDebugURL(): String =
brdPrefs.getString(DEBUG_WEB_PLATFORM_URL, "")!!
/**
* Saves the web platform debug URL to the shared preferences.
*
* @param context Execution context.
* @param webPlatformDebugURL The web platform debug URL to be persisted.
*/
@JvmStatic
fun putWebPlatformDebugURL(webPlatformDebugURL: String) =
brdPrefs.edit { putString(DEBUG_WEB_PLATFORM_URL, webPlatformDebugURL) }
/**
* Get the port that was used to start the HTTPServer.
*
* @param context Execution context.
* @return The last port used to start the HTTPServer.
*/
@JvmStatic
fun getHttpServerPort(): Int =
brdPrefs.getInt(HTTP_SERVER_PORT, 0)
/**
* Save the port used to start the HTTPServer.
*
* @param context Execution context.
* @param port Port used when starting the HTTPServer
*/
@JvmStatic
fun putHttpServerPort(port: Int) =
brdPrefs.edit { putInt(HTTP_SERVER_PORT, port) }
/**
* Save the given in-app notification id into the collection of read message.
*
* @param context Execution context.
* @param notificationId The id of the message that has been read.
*/
fun putReadInAppNotificationId(notificationId: String) {
val readIds = getReadInAppNotificationIds()
brdPrefs.edit {
if (!readIds.contains(notificationId)) {
putStringSet(READ_IN_APP_NOTIFICATIONS, readIds + notificationId)
}
}
}
/**
* Get the ids of the in-app notification that has been read.
*
* @param context Execution context.
* @return A set with the ids of the messages that has been read.
*/
fun getReadInAppNotificationIds(): Set<String> =
brdPrefs.getStringSet(READ_IN_APP_NOTIFICATIONS, emptySet()) ?: emptySet()
/**
* Save an int with the given key in the shared preferences.
*
* @param context Execution context.
* @param key The name of the preference.
* @param value The new value for the preference.
*/
fun putInt(key: String, value: Int) =
brdPrefs.edit { putInt(key, value) }
/**
* Retrieve an int value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defaultValue Value to return if this preference does not exist.
* @param context Execution context.
* @param key The name of the preference.
* @param defaultValue The default value to return if not present.
* @return Returns the preference value if it exists, or defValue.
*/
fun getInt(key: String, defaultValue: Int): Int =
brdPrefs.getInt(key, defaultValue)
/**
* Save an boolean with the given key in the shared preferences.
*
* @param context Execution context.
* @param key The name of the preference.
* @param value The new value for the preference.
*/
fun putBoolean(key: String, value: Boolean) =
brdPrefs.edit { putBoolean(key, value) }
/**
* Retrieve an boolean value from the preferences.
*
* @param key The name of the preference to retrieve.
* @param defaultValue Value to return if this preference does not exist.
* @param context Execution context.
* @param key The name of the preference.
* @param defaultValue The default value to return if not present.
* @return Returns the preference value if it exists, or defValue.
*/
fun getBoolean(key: String, defaultValue: Boolean): Boolean =
brdPrefs.getBoolean(key, defaultValue)
/**
* Gets the set of user defined price alerts.
*/
fun getPriceAlerts(): Set<PriceAlert> = emptySet()
/**
* Save a set of user defined price alerts.
*/
fun putPriceAlerts(priceAlerts: Set<PriceAlert>) = Unit
/**
* Gets the user defined interval in minutes between price
* alert checks.
*/
fun getPriceAlertsInterval() =
brdPrefs.getInt(PRICE_ALERTS_INTERVAL, 15)
/**
* Sets the user defined interval in minutes between price
* alert checks.
*/
fun putPriceAlertsInterval(interval: Int) =
brdPrefs.edit { putInt(PRICE_ALERTS_INTERVAL, interval) }
/** The user's language string as provided by [Locale.getLanguage]. */
var recoveryKeyLanguage: String
get() = brdPrefs.getString(LANGUAGE, Locale.getDefault().language)!!
set(value) {
val isLanguageValid = Bip39Reader.SupportedLanguage.values().any { lang ->
lang.toString() == value
}
brdPrefs.edit {
if (isLanguageValid) {
putString(LANGUAGE, value)
} else {
putString(LANGUAGE, Bip39Reader.SupportedLanguage.EN.toString())
}
}
}
/** Preference to unlock the app using the fingerprint sensor */
var unlockWithFingerprint: Boolean
get() = brdPrefs.getBoolean(UNLOCK_WITH_FINGERPRINT, getUseFingerprint())
set(value) = brdPrefs.edit {
putBoolean(UNLOCK_WITH_FINGERPRINT, value)
}
/** Preference to send money using the fingerprint sensor */
var sendMoneyWithFingerprint: Boolean
get() = brdPrefs.getBoolean(CONFIRM_SEND_WITH_FINGERPRINT, getUseFingerprint())
set(value) = brdPrefs.edit {
putBoolean(CONFIRM_SEND_WITH_FINGERPRINT, value)
}
fun preferredFiatIsoChanges() = callbackFlow<String> {
val listener = SharedPreferences.OnSharedPreferenceChangeListener { _, key ->
if (key == CURRENT_CURRENCY) offer(getPreferredFiatIso())
}
brdPrefs.registerOnSharedPreferenceChangeListener(listener)
awaitClose {
brdPrefs.unregisterOnSharedPreferenceChangeListener(listener)
}
}
private val _trackedConversionChanges = MutableStateFlow<Map<String, List<Conversion>>?>(null)
val trackedConversionChanges: Flow<Map<String, List<Conversion>>>
get() = _trackedConversionChanges
.filterNotNull()
.onStart {
_trackedConversionChanges.value?.let { emit(it) }
}
fun getTrackedConversions(): Map<String, List<Conversion>> =
brdPrefs.getStringSet(TRACKED_TRANSACTIONS, emptySet())!!
.map { Conversion.deserialize(it) }
.groupBy(Conversion::currencyCode)
fun putTrackedConversion(conversion: Conversion) {
brdPrefs.edit {
putStringSet(
TRACKED_TRANSACTIONS,
brdPrefs.getStringSet(TRACKED_TRANSACTIONS, emptySet())!! + conversion.serialize()
)
}
_trackedConversionChanges.value = getTrackedConversions()
}
fun removeTrackedConversion(conversion: Conversion) {
brdPrefs.edit {
val conversionStr = conversion.serialize()
putStringSet(
TRACKED_TRANSACTIONS,
brdPrefs.getStringSet(TRACKED_TRANSACTIONS, emptySet())!! - conversionStr
)
}
_trackedConversionChanges.value = getTrackedConversions()
}
var appRatePromptShouldPrompt: Boolean
get() = brdPrefs.getBoolean(APP_RATE_PROMPT_SHOULD_PROMPT, false)
set(value) = brdPrefs.edit { putBoolean(APP_RATE_PROMPT_SHOULD_PROMPT, value) }
.also { promptChangeChannel.offer(Unit) }
var appRatePromptShouldPromptDebug: Boolean
get() = brdPrefs.getBoolean(APP_RATE_PROMPT_SHOULD_PROMPT_DEBUG, false)
set(value) = brdPrefs.edit { putBoolean(APP_RATE_PROMPT_SHOULD_PROMPT_DEBUG, value) }
.also { promptChangeChannel.offer(Unit) }
var appRatePromptHasRated: Boolean
get() = brdPrefs.getBoolean(APP_RATE_PROMPT_HAS_RATED, false)
set(value) = brdPrefs.edit { putBoolean(APP_RATE_PROMPT_HAS_RATED, value) }
.also { promptChangeChannel.offer(Unit) }
var appRatePromptDontAskAgain: Boolean
get() = brdPrefs.getBoolean(APP_RATE_PROMPT_DONT_ASK_AGAIN, false)
set(value) = brdPrefs.edit { putBoolean(APP_RATE_PROMPT_DONT_ASK_AGAIN, value) }
.also { promptChangeChannel.offer(Unit) }
fun promptChanges(): Flow<Unit> =
promptChangeChannel.asFlow()
.onStart { emit(Unit) }
}
| app-core/src/main/java/com/breadwallet/tools/manager/BRSharedPrefs.kt | 3745790640 |
package com.example.domain.repository
import com.example.domain.dayofweek.entity.DayOfWeekMapper
import com.example.domain.dayofweek.entity.Language
interface DayOfWeekRepository {
fun getDayOfWeekMap(language: Language): DayOfWeekMapper
}
| CleanArchExample/domain/src/main/kotlin/com/example/domain/repository/DayOfWeekRepository.kt | 2366454398 |
package tel.egram.kuery.dml
import tel.egram.kuery.*
class OffsetClause<T: Table>(
val offset: Any,
val limit: LimitClause<T>,
val subject: Subject<T>,
val whereClause: WhereClause<T>?,
val orderClause: OrderClause<T>?,
val groupClause: GroupClause<T>?,
val havingClause: HavingClause<T>?) {
inline fun select(projection: (T) -> Iterable<Projection>): SelectStatement<T> {
return SelectStatement(
projection(subject.table),
subject,
whereClause,
orderClause,
limit,
this,
groupClause,
havingClause)
}
}
class Offset2Clause<T: Table, T2: Table>(
val offset: Any,
val limit2Clause: Limit2Clause<T, T2>,
val joinOn2Clause: JoinOn2Clause<T, T2>,
val whereClause: Where2Clause<T, T2>?,
val orderClause: Order2Clause<T, T2>?,
val group2Clause: Group2Clause<T, T2>?,
val having2Clause: Having2Clause<T, T2>?) {
inline fun select(projection: (T, T2) -> Iterable<Projection>): Select2Statement<T, T2> {
return Select2Statement(
projection(joinOn2Clause.subject.table, joinOn2Clause.table2),
joinOn2Clause,
whereClause,
orderClause,
limit2Clause,
this,
group2Clause,
having2Clause)
}
}
class Offset3Clause<T: Table, T2: Table, T3: Table>(
val offset: Any,
val limit3Clause: Limit3Clause<T, T2, T3>,
val joinOn3Clause: JoinOn3Clause<T, T2, T3>,
val where3Clause: Where3Clause<T, T2, T3>?,
val order3Clause: Order3Clause<T, T2, T3>?,
val group3Clause: Group3Clause<T, T2, T3>?,
val having3Clause: Having3Clause<T, T2, T3>?) {
inline fun select(projection: (T, T2, T3) -> Iterable<Projection>): Select3Statement<T, T2, T3> {
return Select3Statement(
projection(joinOn3Clause.joinOn2Clause.subject.table, joinOn3Clause.joinOn2Clause.table2, joinOn3Clause.table3),
joinOn3Clause,
where3Clause,
order3Clause,
limit3Clause,
this,
group3Clause,
having3Clause)
}
}
class Offset4Clause<T: Table, T2: Table, T3: Table, T4: Table>(
val offset: Any,
val limit4Clause: Limit4Clause<T, T2, T3, T4>,
val joinOn4Clause: JoinOn4Clause<T, T2, T3, T4>,
val where4Clause: Where4Clause<T, T2, T3, T4>?,
val order4Clause: Order4Clause<T, T2, T3, T4>?,
val group4Clause: Group4Clause<T, T2, T3, T4>?,
val having4Clause: Having4Clause<T, T2, T3, T4>?) {
inline fun select(projection: (T, T2, T3, T4) -> Iterable<Projection>): Select4Statement<T, T2, T3, T4> {
return Select4Statement(
projection(
joinOn4Clause.joinOn3Clause.joinOn2Clause.subject.table,
joinOn4Clause.joinOn3Clause.joinOn2Clause.table2,
joinOn4Clause.joinOn3Clause.table3,
joinOn4Clause.table4
),
joinOn4Clause,
where4Clause,
order4Clause,
limit4Clause,
this,
group4Clause,
having4Clause)
}
} | core/src/tel/egram/kuery/dml/OffsetClause.kt | 2827978569 |
package com.orgzly.android.ui.notes.book
import androidx.lifecycle.MediatorLiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import com.orgzly.android.App
import com.orgzly.android.data.DataRepository
import com.orgzly.android.db.entity.Book
import com.orgzly.android.db.entity.NoteView
import com.orgzly.android.ui.CommonViewModel
import com.orgzly.android.ui.SingleLiveEvent
import com.orgzly.android.ui.AppBar
import com.orgzly.android.usecase.BookCycleVisibility
import com.orgzly.android.usecase.UseCaseRunner
class BookViewModel(private val dataRepository: DataRepository, val bookId: Long) : CommonViewModel() {
private data class Params(val noteId: Long? = null)
private val params = MutableLiveData<Params>(Params())
enum class FlipperDisplayedChild {
LOADING,
LOADED,
EMPTY,
DOES_NOT_EXIST
}
val flipperDisplayedChild = MutableLiveData(FlipperDisplayedChild.LOADING)
fun setFlipperDisplayedChild(child: FlipperDisplayedChild) {
flipperDisplayedChild.value = child
}
data class Data(val book: Book?, val notes: List<NoteView>?)
val data = Transformations.switchMap(params) { _ ->
MediatorLiveData<Data>().apply {
addSource(dataRepository.getBookLiveData(bookId)) {
value = Data(it, value?.notes)
}
addSource(dataRepository.getVisibleNotesLiveData(bookId)) {
value = Data(value?.book, it)
}
}
}
companion object {
const val APP_BAR_DEFAULT_MODE = 0
const val APP_BAR_SELECTION_MODE = 1
const val APP_BAR_SELECTION_MOVE_MODE = 2
}
val appBar = AppBar(mapOf(
APP_BAR_DEFAULT_MODE to null,
APP_BAR_SELECTION_MODE to APP_BAR_DEFAULT_MODE,
APP_BAR_SELECTION_MOVE_MODE to APP_BAR_SELECTION_MODE))
fun cycleVisibility() {
data.value?.book?.let { book ->
App.EXECUTORS.diskIO().execute {
catchAndPostError {
UseCaseRunner.run(BookCycleVisibility(book))
}
}
}
}
data class NotesToRefile(val selected: Set<Long>, val count: Int)
val refileRequestEvent: SingleLiveEvent<NotesToRefile> = SingleLiveEvent()
fun refile(ids: Set<Long>) {
App.EXECUTORS.diskIO().execute {
val count = dataRepository.getNotesAndSubtreesCount(ids)
refileRequestEvent.postValue(NotesToRefile(ids, count))
}
}
val notesDeleteRequest: SingleLiveEvent<Pair<Set<Long>, Int>> = SingleLiveEvent()
fun requestNotesDelete(ids: Set<Long>) {
App.EXECUTORS.diskIO().execute {
val count = dataRepository.getNotesAndSubtreesCount(ids)
notesDeleteRequest.postValue(Pair(ids, count))
}
}
} | app/src/main/java/com/orgzly/android/ui/notes/book/BookViewModel.kt | 6389944 |
package me.sdidev.simpleroutetracker.util
const val EXTRA_ROUTE = "me.sdidev.route"
| app/src/main/java/me/sdidev/simpleroutetracker/util/Const.kt | 1208961135 |
/*
* Copyright 2019 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.itemquality.bukkit.command.itemquality
import com.rpkit.itemquality.bukkit.RPKItemQualityBukkit
import org.bukkit.command.Command
import org.bukkit.command.CommandExecutor
import org.bukkit.command.CommandSender
class ItemQualityCommand(private val plugin: RPKItemQualityBukkit): CommandExecutor {
private val itemQualityListCommand = ItemQualityListCommand(plugin)
private val itemQualitySetCommand = ItemQualitySetCommand(plugin)
override fun onCommand(sender: CommandSender, command: Command, label: String, args: Array<out String>): Boolean {
if (args.isEmpty()) {
sender.sendMessage(plugin.messages["itemquality-usage"])
return true
}
return when (args[0]) {
"list" -> itemQualityListCommand.onCommand(sender, command, label, args.drop(1).toTypedArray())
"set" -> itemQualitySetCommand.onCommand(sender, command, label, args.drop(1).toTypedArray())
else -> {
sender.sendMessage(plugin.messages["itemquality-usage"])
true
}
}
}
} | bukkit/rpk-item-quality-bukkit/src/main/kotlin/com/rpkit/itemquality/bukkit/command/itemquality/ItemQualityCommand.kt | 1159362263 |
package cvrdt.set
/**
* Created by jackqack on 21/05/17.
*/
/**
* Two-phase set.
*/
class TwoPhaseSet<V> : CvRDTSet<V, TwoPhaseSet<V>> {
private val added: GSet<V>
private val tombstone: GSet<V>
constructor() {
added = GSet()
tombstone = GSet()
}
private constructor(added: GSet<V>, tombstone: GSet<V>) {
this.added = added.copy()
this.tombstone = tombstone.copy()
}
override fun add(x: V) {
if (!tombstone.contains(x)) added.add(x)
}
override fun addAll(elements: Collection<V>): Boolean {
val filtered = elements.filter { !tombstone.contains(it) }
return added.addAll(filtered)
}
override fun contains(x: V): Boolean {
return !tombstone.contains(x) && added.contains(x)
}
override fun remove(x: V): Boolean {
if (added.contains(x)) {
tombstone.add(x)
return true
} else return false
}
override fun merge(other: TwoPhaseSet<V>) {
added.merge(other.added)
tombstone.merge(other.tombstone)
}
override fun value(): MutableSet<V> {
val s = added.value()
s.removeAll(tombstone.value())
return s
}
override fun copy(): TwoPhaseSet<V> {
return TwoPhaseSet(added, tombstone)
}
} | src/main/kotlin/crdt/cvrdt/set/TwoPhaseSet.kt | 1389725304 |
package org.evomaster.core.search.impact.impactinfocollection.sql
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.UUIDGene
import org.evomaster.core.search.impact.impactinfocollection.GeneImpact
import org.evomaster.core.search.impact.impactinfocollection.GeneImpactTest
import org.evomaster.core.search.impact.impactinfocollection.ImpactOptions
import org.evomaster.core.search.impact.impactinfocollection.MutatedGeneWithContext
import org.junit.jupiter.api.Test
import kotlin.random.Random
/**
* created by manzh on 2019-10-09
*/
class SqlUUIDGeneImpactTest : GeneImpactTest() {
override fun getGene(): Gene {
return UUIDGene("uuid")
}
override fun checkImpactType(impact: GeneImpact) {
assert(impact is SqlUUIDGeneImpact)
}
override fun simulateMutation(original: Gene, geneToMutate: Gene, mutationTag: Int): MutatedGeneWithContext {
geneToMutate as UUIDGene
val p = Random.nextBoolean()
geneToMutate.apply {
when{
mutationTag == 1 || (mutationTag == 0 && p)-> mostSigBits.value += if (mostSigBits.value+1 > Long.MAX_VALUE) -1 else 1
mutationTag == 2 || (mutationTag == 0 && !p) -> leastSigBits.value += if (leastSigBits.value+1 > Long.MAX_VALUE) -1 else 1
else -> throw IllegalArgumentException("bug")
}
}
return MutatedGeneWithContext(previous = original, current = geneToMutate)
}
@Test
fun testDate(){
var gene = getGene()
var impact = initImpact(gene)
val pairM = template( gene, impact, listOf(ImpactOptions.IMPACT_IMPROVEMENT), 1)
impact as SqlUUIDGeneImpact
var updatedImpact = pairM.second as SqlUUIDGeneImpact
assertImpact(impact, updatedImpact, ImpactOptions.IMPACT_IMPROVEMENT)
assertImpact(impact.mostSigBitsImpact, updatedImpact.mostSigBitsImpact, ImpactOptions.IMPACT_IMPROVEMENT)
assertImpact(impact.leastSigBitsImpact, updatedImpact.leastSigBitsImpact, ImpactOptions.NONE)
impact = updatedImpact
gene = pairM.first
val pairL = template(gene, impact, listOf(ImpactOptions.ONLY_IMPACT), 2)
updatedImpact = pairL.second as SqlUUIDGeneImpact
assertImpact(impact, updatedImpact, ImpactOptions.ONLY_IMPACT)
assertImpact(impact.mostSigBitsImpact, updatedImpact.mostSigBitsImpact, ImpactOptions.NONE)
assertImpact(impact.leastSigBitsImpact, updatedImpact.leastSigBitsImpact, ImpactOptions.ONLY_IMPACT)
}
} | core/src/test/kotlin/org/evomaster/core/search/impact/impactinfocollection/sql/SqlUUIDGeneImpactTest.kt | 1965530453 |
package org.evomaster.core.problem.httpws.service.auth
import org.evomaster.core.problem.api.service.auth.AuthenticationInfo
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.search.Action
/**
* should be immutable
*
* AuthenticationInfo for http based SUT
*
*/
open class HttpWsAuthenticationInfo(
name: String,
val headers: List<AuthenticationHeader>,
val cookieLogin: CookieLogin?,
val jsonTokenPostLogin: JsonTokenPostLogin?): AuthenticationInfo(name) {
init {
if(name.isBlank()){
throw IllegalArgumentException("Blank name")
}
if(headers.isEmpty() && name != "NoAuth" && cookieLogin==null && jsonTokenPostLogin==null){
throw IllegalArgumentException("Empty headers")
}
if(cookieLogin != null && jsonTokenPostLogin != null){
//TODO maybe in future might want to support both...
throw IllegalArgumentException("Specified both Cookie and Token based login. Choose just one.")
}
}
/**
* @return whether to exclude auth check (401 status code in the response) for the [action]
*/
fun excludeAuthCheck(action: Action) : Boolean{
if (action is RestCallAction && jsonTokenPostLogin != null){
return action.getName() == "POST:${jsonTokenPostLogin.endpoint}"
}
return false
}
} | core/src/main/kotlin/org/evomaster/core/problem/httpws/service/auth/HttpWsAuthenticationInfo.kt | 795502917 |
/*
* Copyright (C) 2015 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 cx.ring.tv.cards
import android.content.Context
import androidx.leanback.widget.PresenterSelector
import androidx.leanback.widget.Presenter
import cx.ring.tv.cards.iconcards.IconCardPresenter
import cx.ring.tv.cards.contacts.ContactCardPresenter
import cx.ring.R
import net.jami.services.ConversationFacade
import java.security.InvalidParameterException
import java.util.HashMap
/**
* This PresenterSelector will decide what Presenter to use depending on a given card's type.
*/
class CardPresenterSelector(private val context: Context, private val conversationFacade: ConversationFacade) :
PresenterSelector() {
private val presenters = HashMap<Card.Type, Presenter>()
override fun getPresenter(item: Any): Presenter {
val type = (item as Card).type
return presenters.getOrPut(type) {
when (type) {
Card.Type.ACCOUNT_ADD_DEVICE, Card.Type.ACCOUNT_EDIT_PROFILE, Card.Type.ACCOUNT_SHARE_ACCOUNT, Card.Type.ADD_CONTACT -> IconCardPresenter(context)
Card.Type.SEARCH_RESULT, Card.Type.CONTACT -> ContactCardPresenter(context, conversationFacade, R.style.ContactCardTheme)
Card.Type.CONTACT_ONLINE -> ContactCardPresenter(context, conversationFacade, R.style.ContactCardOnlineTheme)
Card.Type.CONTACT_WITH_USERNAME -> ContactCardPresenter(
context,
conversationFacade,
R.style.ContactCompleteCardTheme
)
Card.Type.CONTACT_WITH_USERNAME_ONLINE -> ContactCardPresenter(
context,
conversationFacade,
R.style.ContactCompleteCardOnlineTheme
)
else -> throw InvalidParameterException("Uncatched card type $type")
}
}
}
} | ring-android/app/src/main/java/cx/ring/tv/cards/CardPresenterSelector.kt | 3767255812 |
package me.proxer.library.enums
import com.serjltt.moshi.adapters.FallbackEnum
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
/**
* Enum holding the available languages of an anime.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = false)
@FallbackEnum(name = "OTHER")
enum class AnimeLanguage {
@Json(name = "gersub")
GERMAN_SUB,
@Json(name = "gerdub")
GERMAN_DUB,
@Json(name = "engsub")
ENGLISH_SUB,
@Json(name = "engdub")
ENGLISH_DUB,
@Json(name = "misc")
OTHER
}
| library/src/main/kotlin/me/proxer/library/enums/AnimeLanguage.kt | 2619198447 |
package com.github.fluidsonic.jetpack
public interface HalfOpenRange<Bound : Comparable<Bound>> {
public val start: Bound
public val endExclusive: Bound
public operator fun contains(value: Bound) =
value >= start && value < endExclusive
public fun isEmpty()
= start >= endExclusive
}
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.flipped() =
endExclusive rangeToBefore start
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.intersection(other: HalfOpenRange<Bound>) =
if (overlaps(other)) {
max(start, other.start) rangeToBefore min(endExclusive, other.endExclusive)
}
else {
null
}
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.contains(other: HalfOpenRange<Bound>) =
contains(other.start) && other.endExclusive <= endExclusive
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.overlaps(other: HalfOpenRange<Bound>) =
contains(other.start) || other.contains(start)
public fun <Bound : Comparable<Bound>, R : Comparable<R>> HalfOpenRange<Bound>.mapBounds(transform: (Bound) -> R) =
transform(start) rangeToBefore transform(endExclusive)
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.subtracting(rangeToSubtract: HalfOpenRange<Bound>): List<HalfOpenRange<Bound>> {
if (rangeToSubtract.start >= endExclusive || rangeToSubtract.endExclusive <= start) {
return listOf(this)
}
val result = mutableListOf<HalfOpenRange<Bound>>()
if (rangeToSubtract.start > start) {
result.add(start rangeToBefore rangeToSubtract.start)
}
if (rangeToSubtract.endExclusive < endExclusive) {
result.add(rangeToSubtract.endExclusive rangeToBefore endExclusive)
}
return result
}
public fun <Bound : Comparable<Bound>> HalfOpenRange<Bound>.toSequence(nextFunction: (Bound) -> Bound?) =
generateSequence(start) {
val next = nextFunction(it)
if (next != null && contains(next)) {
return@generateSequence next
}
else {
return@generateSequence null
}
}
private data class HalfOpenComparableRange<Bound : Comparable<Bound>>(
public override val start: Bound,
public override val endExclusive: Bound
) : HalfOpenRange<Bound> {
init {
require(start <= endExclusive)
}
public override fun toString() = "$start ..< $endExclusive"
}
public data class HalfOpenIntRange(
public override val start: Int,
public override val endExclusive: Int
) : HalfOpenRange<Int>, Iterable<Int> {
public override operator fun contains(value: Int) =
value in start .. (endExclusive - 1)
public override fun isEmpty()
= start >= endExclusive
public override operator fun iterator(): IntIterator {
if (start == endExclusive) {
return emptyRange.iterator()
}
return (start .. (endExclusive - 1)).iterator()
}
}
public infix fun <Bound : Comparable<Bound>> Bound.rangeToBefore(that: Bound): HalfOpenRange<Bound> = HalfOpenComparableRange(this, that)
public infix fun Int.rangeToBefore(that: Int) = HalfOpenIntRange(this, that)
private val emptyRange = 1 .. 0
| Sources/HalfOpenRange.kt | 3756214626 |
package i_introduction._8_Smart_Casts
import util.*
interface Expr
class Num(val value: Int) : Expr
class Sum(val left: Expr, val right: Expr) : Expr
fun eval(e: Expr): Int =
when (e) {
is Num -> e.value
is Sum -> eval(e.left) + eval(e.right)
is Num -> todoTask8(e)
is Sum -> todoTask8(e)
else -> throw IllegalArgumentException("Unknown expression")
}
fun todoTask8(expr: Expr): Nothing = TODO(
"""
Task 8.
Rewrite 'JavaCode8.eval()' in Kotlin using smart casts and 'when' expression.
""",
documentation = doc8(),
references = { JavaCode8().eval(expr) })
| src/i_introduction/_8_Smart_Casts/SmartCasts.kt | 1000887528 |
package org.klips.engine.rete.builder
import org.klips.dsl.Fact
import org.klips.engine.query.BindingSet
import org.klips.engine.query.FactBindingSet
import org.klips.engine.query.JoinBindingSet
import org.klips.engine.query.JoinBindingSet.JoinType
object Util {
fun select(facts:Collection<Fact>, patt:Collection<Fact>, joinType: JoinType = JoinType.Inner) = patt.map {
FactBindingSet(it, facts)
}.reduce<BindingSet, FactBindingSet> { l, r -> JoinBindingSet(l,r, joinType)}
} | src/main/java/org/klips/engine/rete/builder/Util.kt | 4253368115 |
/*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.libraries.pcc.chronicle.util
import android.util.Log
import android.util.Log.DEBUG
import android.util.Log.ERROR
import android.util.Log.INFO
import android.util.Log.VERBOSE
import android.util.Log.WARN
/** Container for Chronicle's loggers. */
object Logcat {
private const val DEFAULT_TAG: String = "Chronicle"
private const val CLIENT_TAG: String = "ChronicleClient"
private const val SERVER_TAG: String = "ChronicleServer"
/**
* [TaggedLogger] intended for use by implementations of the Chronicle interface and as a
* catch-all in situations where it doesn't make sense to implement a new logger.
*/
val default: TaggedLogger = TaggedLogger(DEFAULT_TAG)
/** [TaggedLogger] intended for use by client-side API components. */
val clientSide: TaggedLogger = TaggedLogger(CLIENT_TAG)
/** [TaggedLogger] intended for use by server-side API components. */
val serverSide: TaggedLogger = TaggedLogger(SERVER_TAG)
}
/**
* Helper class to associate a tag with logging calls. Each method simply calls the corresponding
* method in Android's native logger with the given tag.
*/
class TaggedLogger(val tag: String) {
/**
* Send a [VERBOSE] log message.
* @param msg The message you would like logged.
*/
fun v(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, VERBOSE)) {
Log.v(tag, String.format(msg, *args))
}
}
/**
* Send a [VERBOSE] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun v(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, VERBOSE)) {
Log.v(tag, String.format(msg, *args), tr)
}
}
/**
* Send a [DEBUG] log message.
* @param msg The message you would like logged.
*/
fun d(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, DEBUG)) {
Log.d(tag, String.format(msg, *args))
}
}
/**
* Send a [DEBUG] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun d(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, DEBUG)) {
Log.d(tag, String.format(msg, *args), tr)
}
}
/**
* Send an [INFO] log message.
* @param msg The message you would like logged.
*/
fun i(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, INFO)) {
Log.i(tag, String.format(msg, *args))
}
}
/**
* Send a [INFO] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun i(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, INFO)) {
Log.i(tag, String.format(msg, *args), tr)
}
}
/**
* Send a [WARN] log message.
* @param msg The message you would like logged.
*/
fun w(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, WARN)) {
Log.w(tag, String.format(msg, *args))
}
}
/**
* Send a [WARN] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun w(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, WARN)) {
Log.w(tag, String.format(msg, *args), tr)
}
}
/**
* Send a [WARN] log message and log the exception.
* @param tr An exception to log
*/
fun w(tr: Throwable) {
if (Log.isLoggable(tag, WARN)) {
Log.w(tag, tr)
}
}
/**
* Send an [ERROR] log message.
* @param msg The message you would like logged.
*/
fun e(msg: String, vararg args: Any) {
if (Log.isLoggable(tag, ERROR)) {
Log.e(tag, String.format(msg, *args))
}
}
/**
* Send a [ERROR] log message and log the exception.
* @param tr An exception to log
* @param msg The message you would like logged.
*/
fun e(tr: Throwable, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, ERROR)) {
Log.e(tag, String.format(msg, *args), tr)
}
}
/**
* Handy function to get a loggable stack trace from a Throwable
* @param tr An exception to log
*/
fun getStackTraceString(tr: Throwable): String {
return Log.getStackTraceString(tr)
}
/**
* Low-level logging call.
* @param priority The priority/type of this log message
* @param msg The message you would like logged.
* @return The number of bytes written.
*/
fun println(priority: Int, msg: String, vararg args: Any) {
if (Log.isLoggable(tag, priority)) {
Log.println(priority, tag, String.format(msg, *args))
}
}
/**
* Times the duration of the [block] and logs the provided [message] along with the duration at
* [VERBOSE] level.
*/
inline fun <T> timeVerbose(message: String, block: () -> T): T {
val start = System.nanoTime()
return try {
block()
} finally {
val duration = System.nanoTime() - start
v("%s [duration: %.3f ms]", message, duration / 1000000.0)
}
}
}
| java/com/google/android/libraries/pcc/chronicle/util/Logcat.kt | 2969501095 |
package com.simplemobiletools.flashlight.helpers
interface CameraTorchListener {
fun onTorchEnabled(isEnabled:Boolean)
}
| app/src/main/kotlin/com/simplemobiletools/flashlight/helpers/CameraTorchListener.kt | 3326586971 |
/*
* Copyright 2013-2015 Eugene Petrenko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.jonnyzzz.teamcity.plugins.node.server
import jetbrains.buildServer.web.openapi.PluginDescriptor
import com.jonnyzzz.teamcity.plugins.node.common.*
import jetbrains.buildServer.serverSide.PropertiesProcessor
import jetbrains.buildServer.serverSide.InvalidProperty
import jetbrains.buildServer.requirements.Requirement
import jetbrains.buildServer.serverSide.buildDistribution.StartingBuildAgentsFilter
import jetbrains.buildServer.serverSide.buildDistribution.AgentsFilterContext
import jetbrains.buildServer.serverSide.buildDistribution.AgentsFilterResult
import jetbrains.buildServer.serverSide.BuildPromotionManager
import jetbrains.buildServer.requirements.RequirementType
import jetbrains.buildServer.serverSide.BuildPromotion
import jetbrains.buildServer.serverSide.buildDistribution.SimpleWaitReason
/**
* @author Eugene Petrenko ([email protected])
* Date: 16.08.13 21:43
*/
class NVMRunType(val plugin : PluginDescriptor) : RunTypeBase() {
private val bean = NVMBean()
override fun getType(): String = bean.NVMFeatureType
override fun getDisplayName(): String = "Node.js NVM Installer"
override fun getDescription(): String = "Install Node.js of specified version using NVM"
override fun getEditJsp(): String = "node.nvm.edit.jsp"
override fun getViewJsp(): String = "node.nvm.view.jsp"
override fun getRunnerPropertiesProcessor(): PropertiesProcessor
= PropertiesProcessor{ arrayListOf<InvalidProperty>() }
override fun getDefaultRunnerProperties(): MutableMap<String, String>?
= hashMapOf(bean.NVMVersion to "0.10")
override fun describeParameters(parameters: Map<String, String>): String
= "Install Node.js v" + parameters[bean.NVMVersion]
override fun getRunnerSpecificRequirements(runParameters: Map<String, String>): MutableList<Requirement> {
return arrayListOf(Requirement(bean.NVMAvailable, null, RequirementType.EXISTS))
}
}
class NVMBuildStartPrecondition(val promos : BuildPromotionManager) : StartingBuildAgentsFilter {
private val nodeBean = NodeBean()
private val npmBean = NPMBean()
private val nvmBean = NVMBean()
private val runTypes = hashSetOf(nodeBean.runTypeNameNodeJs, npmBean.runTypeName)
override fun filterAgents(context: AgentsFilterContext): AgentsFilterResult {
val result = AgentsFilterResult()
val promo = context.getStartingBuild().getBuildPromotionInfo()
if (promo !is BuildPromotion) return result
val buildType = promo.getBuildType()
if (buildType == null) return result
val runners = buildType.buildRunners.filter { buildType.isEnabled(it.getId()) }
//if nothing found => skip
if (runners.isEmpty()) return result
//if our nodeJS and NPM runners are not used
if (!runners.any { runner -> runTypes.contains(runner.type)}) return result
val version = runners.firstOrNull { it.type == nvmBean.NVMFeatureType }
?.parameters
?.get(nvmBean.NVMVersion)
//skip checks if NVM feature version was specified
if (version != null) return result
//if not, let's filter unwanted agents
val agents = context.agentsForStartingBuild.filter { agent ->
//allow only if there were truly-detected NVM/NPM on the agent
with(agent.configurationParameters) {
get(nodeBean.nodeJSConfigurationParameter) != nvmBean.NVMUsed
&&
get(npmBean.nodeJSNPMConfigurationParameter) != nvmBean.NVMUsed
}
}
if (agents.isEmpty()) {
result.waitReason = SimpleWaitReason("Please add 'Node.js NVM Installer' build runner")
} else {
result.filteredConnectedAgents = agents
}
return result
}
}
| server/src/main/java/com/jonnyzzz/teamcity/plugins/node/server/NVM.kt | 1038173697 |
package com.reactnativenavigation.views.element.animators
import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ObjectAnimator
import android.view.View
import android.view.ViewGroup
import androidx.core.animation.addListener
import androidx.core.animation.doOnStart
import com.facebook.react.views.text.ReactTextView
import com.facebook.react.views.view.ReactViewBackgroundDrawable
import com.reactnativenavigation.parse.SharedElementTransitionOptions
import com.reactnativenavigation.utils.*
class BackgroundColorAnimator(from: View, to: View) : PropertyAnimatorCreator<ViewGroup>(from, to) {
override fun shouldAnimateProperty(fromChild: ViewGroup, toChild: ViewGroup): Boolean {
return fromChild.background is ReactViewBackgroundDrawable &&
toChild.background is ReactViewBackgroundDrawable && (fromChild.background as ReactViewBackgroundDrawable).color != (toChild.background as ReactViewBackgroundDrawable).color
}
override fun excludedViews() = listOf(ReactTextView::class.java)
override fun create(options: SharedElementTransitionOptions): Animator {
val backgroundColorEvaluator = BackgroundColorEvaluator(to.background as ReactViewBackgroundDrawable)
val fromColor = ColorUtils.colorToLAB(ViewUtils.getBackgroundColor(from))
val toColor = ColorUtils.colorToLAB(ViewUtils.getBackgroundColor(to))
backgroundColorEvaluator.evaluate(0f, fromColor, toColor)
return ObjectAnimator.ofObject(backgroundColorEvaluator, fromColor, toColor)
}
} | lib/android/app/src/main/java/com/reactnativenavigation/views/element/animators/BackgroundColorAnimator.kt | 2780877211 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.core.service
/**
* Implemented by platforms to provide services.
*/
interface ServicesDelegate {
/**
* Gets the service from the platform.
*
* @param type The type of the service
* @return The service
*/
operator fun <T: Service> get(type: Class<T>): T?
operator fun <T: Service> set(type: Class<T>, service: T)
} | rpk-core/src/main/kotlin/com/rpkit/core/service/ServicesDelegate.kt | 712011568 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.action
import java.util.concurrent.CopyOnWriteArrayList
class ParallelAction(vararg child: Action) : CompoundAction() {
private var firstChildStarted: Action? = null
/**
* Used by ActionHolder to combine an existing Action into a sequence without restarting it.
* It is generally not advisable for games to use this constructor directly.
*/
constructor(child1: Action, child2: Action, child1Started: Boolean) : this(child1, child2) {
if (child1Started) firstChildStarted = child1
}
/**
* This holds the children that are still active (i.e. those that haven't finished).
* During [act], children that finish are moved from here to [finishedChildren].
* When/if the ParallelAction is restarted, the finishedChildren are added back to
* this list.
*/
override val children = CopyOnWriteArrayList<Action>()
/**
* When adding a new child it is added to this list, their begin method is not called at this time.
* During [act], this each member is then moved to either [finishedChildren] or [chidren]
* depending on the result of their begin.
*/
private val unstartedChildren = mutableListOf<Action>()
/**
* During [act], and [begin], any children that finish are moved from [children] into
* this list.
* This list is then added to [children] if/when the ParallelAction is restarted.
*/
private val finishedChildren = mutableListOf<Action>()
init {
children.addAll(child)
}
override fun begin(): Boolean {
super.begin()
// If we are being restarted (from a ForeverAction, or a RepeatAction), then
// add the finished children back to the active list
if (finishedChildren.isNotEmpty()) {
children.addAll(finishedChildren)
finishedChildren.clear()
}
var finished = true
children.forEach { child ->
val childFinished = if (firstChildStarted == child) false else child.begin()
if (childFinished) {
children.remove(child)
finishedChildren.add(child)
} else {
finished = false // One child isn't finished, so we aren't finished.
}
}
// If we restart, then we don't want to treat the first child special. We need to start all children as normal.
firstChildStarted = null
unstartedChildren.clear()
return finished
}
override fun add(action: Action) {
unstartedChildren.add(action)
super.add(action)
}
override fun remove(action: Action) {
unstartedChildren.remove(action)
super.add(action)
}
override fun act(): Boolean {
if (unstartedChildren.isNotEmpty()) {
unstartedChildren.forEach {
if (it.begin()) {
finishedChildren.add(it)
} else {
children.add(it)
}
}
unstartedChildren.clear()
}
children.forEach { child ->
if (child.act()) {
children.remove(child)
// Remember this child, so that if we are restarted, then the child can be added back to the
// "children" list again.
finishedChildren.add(child)
}
}
return children.isEmpty()
}
override fun and(other: Action): ParallelAction {
add(other)
return this
}
}
| tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/action/ParallelAction.kt | 1174341603 |
package com.mizukami2005.mizukamitakamasa.qiitaclient.dagger
import com.google.gson.*
import com.mizukami2005.mizukamitakamasa.qiitaclient.client.ArticleClient
import com.mizukami2005.mizukamitakamasa.qiitaclient.client.QiitaClient
import com.google.gson.FieldNamingPolicy
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import io.realm.RealmObject
import retrofit2.Retrofit
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
class ClientModule {
@Provides
@Singleton
fun provideGson(): Gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.setExclusionStrategies(object : ExclusionStrategy {
override fun shouldSkipField(f: FieldAttributes): Boolean {
return f.declaredClass == RealmObject::class.java
}
override fun shouldSkipClass(clazz: Class<*>): Boolean {
return false
}
})
.create()
@Provides
@Singleton
fun provideRetrofit(gson: Gson): Retrofit = Retrofit.Builder()
.baseUrl("https://qiita.com")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJavaCallAdapterFactory.create())
.build()
@Provides
@Singleton
fun provideArticleClient(retrofit: Retrofit): ArticleClient =
retrofit.create(ArticleClient::class.java)
@Provides
@Singleton
fun provideQiitaClient(retrofit: Retrofit): QiitaClient =
retrofit.create(QiitaClient::class.java)
}
| app/src/main/kotlin/com/mizukami2005/mizukamitakamasa/qiitaclient/dagger/ClientModule.kt | 335165187 |
/*
* Copyright 2017 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.itachi1706.cheesecakeutilities.modules.cameraViewer
import android.Manifest
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.content.pm.PackageManager
import android.content.res.Configuration
import android.graphics.*
import android.hardware.camera2.*
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.util.Size
import android.util.SparseIntArray
import android.view.*
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import com.itachi1706.cheesecakeutilities.R
import com.itachi1706.helperlib.helpers.LogHelper
import kotlinx.android.synthetic.main.fragment_camera2_basic.*
import java.util.*
import java.util.concurrent.Semaphore
import java.util.concurrent.TimeUnit
import kotlin.collections.ArrayList
import kotlin.math.max
import kotlin.math.round
@RequiresApi(Build.VERSION_CODES.LOLLIPOP)
class Camera2BasicFragment : Fragment(), View.OnClickListener, ActivityCompat.OnRequestPermissionsResultCallback {
private val surfaceTextureListener = object : TextureView.SurfaceTextureListener {
override fun onSurfaceTextureAvailable(texture: SurfaceTexture, width: Int, height: Int) { openCamera(width, height) }
override fun onSurfaceTextureSizeChanged(texture: SurfaceTexture, width: Int, height: Int) { configureTransform(width, height) }
override fun onSurfaceTextureDestroyed(texture: SurfaceTexture) = true
override fun onSurfaceTextureUpdated(texture: SurfaceTexture) = Unit
}
private lateinit var cameraId: String
private var captureSession: CameraCaptureSession? = null
private var cameraDevice: CameraDevice? = null
private lateinit var previewSize: Size
private lateinit var largest: Size
private val stateCallback = object : CameraDevice.StateCallback() {
override fun onOpened(cameraDevice: CameraDevice) {
cameraOpenCloseLock.release()
[email protected] = cameraDevice
createCameraPreviewSession()
}
override fun onDisconnected(cameraDevice: CameraDevice) {
cameraOpenCloseLock.release()
cameraDevice.close()
[email protected] = null
}
override fun onError(cameraDevice: CameraDevice, error: Int) { onDisconnected(cameraDevice); [email protected]?.finish() }
}
private var backgroundThread: HandlerThread? = null
private var backgroundHandler: Handler? = null
private lateinit var previewRequestBuilder: CaptureRequest.Builder
private lateinit var previewRequest: CaptureRequest
private var state = STATE_PREVIEW
private val cameraOpenCloseLock = Semaphore(1)
private var flashSupported = false
private var sensorOrientation = 0
private val captureCallback = object : CameraCaptureSession.CaptureCallback() {
private fun process() {
when (state) { STATE_PREVIEW -> Unit } // Do nothing when the camera preview is working normally.
}
override fun onCaptureProgressed(session: CameraCaptureSession, request: CaptureRequest, partialResult: CaptureResult) { process() }
override fun onCaptureCompleted(session: CameraCaptureSession, request: CaptureRequest, result: TotalCaptureResult) { process() }
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? = inflater.inflate(R.layout.fragment_camera2_basic, container, false)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
flash.setOnClickListener(this)
info.setOnClickListener(this)
switch_cam.setOnClickListener(this)
}
override fun onResume() {
super.onResume()
startBackgroundThread()
if (texture.isAvailable) openCamera(texture.width, texture.height)
else texture.surfaceTextureListener = surfaceTextureListener
}
override fun onPause() {
closeCamera()
stopBackgroundThread()
super.onPause()
}
private fun requestCameraPermission() {
if (shouldShowRequestPermissionRationale(Manifest.permission.CAMERA)) ConfirmationDialog().show(childFragmentManager, FRAGMENT_DIALOG)
else requestPermissions(arrayOf(Manifest.permission.CAMERA), REQUEST_CAMERA_PERMISSION)
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
if (requestCode == REQUEST_CAMERA_PERMISSION)
if (grantResults.size != 1 || grantResults[0] != PackageManager.PERMISSION_GRANTED) ErrorDialog.newInstance(getString(R.string.request_permission)).show(childFragmentManager, FRAGMENT_DIALOG)
else super.onRequestPermissionsResult(requestCode, permissions, grantResults)
}
private fun setUpCameraOutputs(width: Int, height: Int) {
val manager = activity!!.getSystemService(Context.CAMERA_SERVICE) as CameraManager
try {
for (cameraId in manager.cameraIdList) {
if (!setupCam(manager, cameraId, width, height, true)) continue
this.cameraId = cameraId
return // We've found a viable camera and finished setting up member variables so we don't need to iterate through other available cameras.
}
} catch (e: CameraAccessException) {
LogHelper.e(TAG, e.toString())
} catch (e: NullPointerException) {
// Currently an NPE is thrown when the Camera2API is used but not supported on the
// device this code runs.
ErrorDialog.newInstance(getString(R.string.camera_error)).show(childFragmentManager, FRAGMENT_DIALOG)
}
}
private fun setupCam(manager: CameraManager, cameraId: String, width: Int, height: Int, init: Boolean = false): Boolean {
val characteristics = manager.getCameraCharacteristics(cameraId)
// We don't use a front facing camera in this sample.
val cameraDirection = characteristics.get(CameraCharacteristics.LENS_FACING)
if (cameraDirection != null &&
cameraDirection == CameraCharacteristics.LENS_FACING_FRONT && init) {
return false
}
val map = characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP) ?: return false
// For still image captures, we use the largest available size.
largest = Collections.max(listOf(*map.getOutputSizes(ImageFormat.JPEG)), CompareSizesByArea())
// Find out if we need to swap dimension to get the preview size relative to sensor coordinate.
val displayRotation = activity!!.windowManager.defaultDisplay.rotation
sensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION)!!
val swappedDimensions = areDimensionsSwapped(displayRotation)
val displaySize = Point()
activity!!.windowManager.defaultDisplay.getSize(displaySize)
val rotatedPreviewWidth = if (swappedDimensions) height else width
val rotatedPreviewHeight = if (swappedDimensions) width else height
var maxPreviewWidth = if (swappedDimensions) displaySize.y else displaySize.x
var maxPreviewHeight = if (swappedDimensions) displaySize.x else displaySize.y
if (maxPreviewWidth > MAX_PREVIEW_WIDTH) maxPreviewWidth = MAX_PREVIEW_WIDTH
if (maxPreviewHeight > MAX_PREVIEW_HEIGHT) maxPreviewHeight = MAX_PREVIEW_HEIGHT
// Danger, W.R.! Attempting to use too large a preview size could exceed the camera
// bus' bandwidth limitation, resulting in gorgeous previews but the storage of
// garbage capture data.
previewSize = chooseOptimalSize(map.getOutputSizes(SurfaceTexture::class.java), rotatedPreviewWidth, rotatedPreviewHeight, maxPreviewWidth, maxPreviewHeight, largest)
// We fit the aspect ratio of TextureView to the size of preview we picked.
if (resources.configuration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
texture.setAspectRatio(previewSize.width, previewSize.height)
} else {
texture.setAspectRatio(previewSize.height, previewSize.width)
}
// Check if the flash is supported.
flashSupported = characteristics.get(CameraCharacteristics.FLASH_INFO_AVAILABLE) == true
return true
}
private fun areDimensionsSwapped(displayRotation: Int): Boolean {
var swappedDimensions = false
when (displayRotation) {
Surface.ROTATION_0, Surface.ROTATION_180 -> if (sensorOrientation == 90 || sensorOrientation == 270) swappedDimensions = true
Surface.ROTATION_90, Surface.ROTATION_270 -> if (sensorOrientation == 0 || sensorOrientation == 180) swappedDimensions = true
else -> LogHelper.e(TAG, "Display rotation is invalid: $displayRotation")
}
return swappedDimensions
}
private fun openCamera(width: Int, height: Int, cid: String? = null) {
val permission = ContextCompat.checkSelfPermission(activity!!, Manifest.permission.CAMERA)
if (permission != PackageManager.PERMISSION_GRANTED) {
requestCameraPermission()
return
}
val manager = activity!!.getSystemService(Context.CAMERA_SERVICE) as CameraManager
if (cid.isNullOrEmpty()) setUpCameraOutputs(width, height) else {
setupCam(manager, cid, width, height, false)
this.cameraId = cid
}
flash.isEnabled = flashSupported // If camera has flash
configureTransform(width, height)
try {
// Wait for camera to open - 2.5 seconds is sufficient
if (!cameraOpenCloseLock.tryAcquire(2500, TimeUnit.MILLISECONDS)) throw RuntimeException("Time out waiting to lock camera opening.")
manager.openCamera(cameraId, stateCallback, backgroundHandler)
} catch (e: CameraAccessException) {
LogHelper.e(TAG, e.toString())
} catch (e: InterruptedException) {
throw RuntimeException("Interrupted while trying to lock camera opening.", e)
}
}
private fun closeCamera() {
try {
cameraOpenCloseLock.acquire()
captureSession?.close()
captureSession = null
cameraDevice?.close()
cameraDevice = null
} catch (e: InterruptedException) {
throw RuntimeException("Interrupted while trying to lock camera closing.", e)
} finally {
cameraOpenCloseLock.release()
}
}
private fun startBackgroundThread() {
backgroundThread = HandlerThread("CameraBackground").also { it.start() }
backgroundHandler = Handler(backgroundThread!!.looper)
}
private fun stopBackgroundThread() {
backgroundThread?.quitSafely()
try {
backgroundThread?.join()
backgroundThread = null
backgroundHandler = null
} catch (e: InterruptedException) {
LogHelper.e(TAG, e.toString())
}
}
private fun createCameraPreviewSession() {
try {
val texture = texture.surfaceTexture
texture.setDefaultBufferSize(previewSize.width, previewSize.height) // We configure the size of default buffer to be the size of camera preview we want.
val surface = Surface(texture) // This is the output Surface we need to start preview.
// We set up a CaptureRequest.Builder with the output Surface.
previewRequestBuilder = cameraDevice!!.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW)
previewRequestBuilder.addTarget(surface)
// Here, we create a CameraCaptureSession for camera preview.
cameraDevice?.createCaptureSession(listOf(surface), object : CameraCaptureSession.StateCallback() {
override fun onConfigured(cameraCaptureSession: CameraCaptureSession) {
if (cameraDevice == null) return // The camera is already closed
captureSession = cameraCaptureSession // When the session is ready, we start displaying the preview.
try {
// Auto focus should be continuous for camera preview.
previewRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE)
setAutoFlash(previewRequestBuilder) // Flash is automatically enabled when necessary.
// Finally, we start displaying the camera preview.
previewRequest = previewRequestBuilder.build()
captureSession?.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler)
} catch (e: CameraAccessException) {
LogHelper.e(TAG, e.toString())
}
}
override fun onConfigureFailed(session: CameraCaptureSession) { activity!!.runOnUiThread { Toast.makeText(activity, "Failed", Toast.LENGTH_SHORT).show() } } }, null)
} catch (e: CameraAccessException) { LogHelper.e(TAG, e.toString()) }
}
private fun configureTransform(viewWidth: Int, viewHeight: Int) {
activity ?: return
val rotation = activity!!.windowManager.defaultDisplay.rotation
val matrix = Matrix()
val viewRect = RectF(0f, 0f, viewWidth.toFloat(), viewHeight.toFloat())
val bufferRect = RectF(0f, 0f, previewSize.height.toFloat(), previewSize.width.toFloat())
val centerX = viewRect.centerX()
val centerY = viewRect.centerY()
if (Surface.ROTATION_90 == rotation || Surface.ROTATION_270 == rotation) {
bufferRect.offset(centerX - bufferRect.centerX(), centerY - bufferRect.centerY())
val scale = max(viewHeight.toFloat() / previewSize.height, viewWidth.toFloat() / previewSize.width)
with(matrix) {
setRectToRect(viewRect, bufferRect, Matrix.ScaleToFit.FILL)
postScale(scale, scale, centerX, centerY)
postRotate((90 * (rotation - 2)).toFloat(), centerX, centerY)
}
} else if (Surface.ROTATION_180 == rotation) {
matrix.postRotate(180f, centerX, centerY)
}
texture.setTransform(matrix)
}
private fun toggleFlash() {
if (activity == null) return
LogHelper.d(TAG, "toggleFlash()")
val flashState = previewRequestBuilder.get(CaptureRequest.FLASH_MODE) ?: CaptureRequest.FLASH_MODE_OFF
LogHelper.d(TAG, "Flash State: $flashState")
if (flashState != CaptureRequest.FLASH_MODE_OFF) {
previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF)
setAutoFlash(previewRequestBuilder)
} // On
else {
previewRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH)
previewRequestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON)
} // Off
previewRequest = previewRequestBuilder.build()
captureSession?.setRepeatingRequest(previewRequest, captureCallback, backgroundHandler)
}
private fun getDebugInformation(): String {
if (activity == null) return ""
val manager = activity!!.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val string = StringBuilder()
string.append("Camera Count: ${manager.cameraIdList.size}\n")
string.append("Currently Active Camera: ${this.cameraId}\n")
val c = manager.getCameraCharacteristics(cameraId)
string.append("Is Front Facing: ${c.get(CameraCharacteristics.LENS_FACING) == CameraCharacteristics.LENS_FACING_FRONT}\n")
string.append("Has Flash: $flashSupported\n")
string.append("Hardware Level Support: ${c.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL)} (${getHardwareLevelName(c.get(CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL))})\n")
string.append("Optical Image Stabilization: ${isStateAvailable(CameraCharacteristics.LENS_INFO_AVAILABLE_OPTICAL_STABILIZATION, c, CaptureRequest.LENS_OPTICAL_STABILIZATION_MODE_ON)}\n")
string.append("Electronic Image Stabilization: ${isStateAvailable(CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES, c, CaptureRequest.CONTROL_VIDEO_STABILIZATION_MODE_ON)}\n")
val mp = String.format("%.1f", (largest.width * largest.height) / 1024.0 / 1024.0).toDouble()
val mpRound = round((largest.width * largest.height) / 1024.0 / 1024.0)
string.append("Resolution: ${largest.width}x${largest.height} (${if (mpRound <=0) mp else mpRound} Megapixels)\n")
val aperature = c.get(CameraCharacteristics.LENS_INFO_AVAILABLE_APERTURES)
val aperatureString = aperature?.joinToString(",", "f/", " ") ?: "None"
string.append("Aperature Sizes: $aperatureString")
return string.toString()
}
private fun isStateAvailable(char: CameraCharacteristics.Key<IntArray>, c: CameraCharacteristics, target: Int): Boolean {
val tmp = c.get(char)
tmp?.let { it.forEach { o -> if (o == target) return true } }
return false
}
private fun getHardwareLevelName(level: Int?): String {
return when (level) {
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY -> "Legacy"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_EXTERNAL -> "External"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED -> "Limited"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_FULL -> "Full"
CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL_3 -> "L3"
else -> "Unknown"
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.flash -> toggleFlash()
R.id.info -> activity?.let { AlertDialog.Builder(it).setTitle("Debug Info").setMessage(getDebugInformation()).setPositiveButton(android.R.string.ok, null).show() }
R.id.switch_cam -> {
val manager = activity!!.getSystemService(Context.CAMERA_SERVICE) as CameraManager
val list = manager.cameraIdList.map { s -> val cameraDirection = manager.getCameraCharacteristics(s.toString()).get(CameraCharacteristics.LENS_FACING)
if (cameraDirection != null && cameraDirection == CameraCharacteristics.LENS_FACING_FRONT) "$s (Front Camera)" else "$s (Rear Camera)" }.toTypedArray()
val selected = manager.cameraIdList.indexOf(cameraId)
// Get front/rear status
AlertDialog.Builder(context).setTitle("Change Camera")
.setSingleChoiceItems(list, selected, null)
.setPositiveButton(android.R.string.ok) { dialog: DialogInterface, _ ->
dialog.dismiss()
val selPos = (dialog as AlertDialog).listView.checkedItemPosition
val selString = manager.cameraIdList[selPos]
LogHelper.d(TAG, "Sel new camera: $selPos ($selString)")
switchCam(selString.toString())
}.setNegativeButton(android.R.string.cancel, null).show()
}
}
}
private fun switchCam(newCam: String) {
LogHelper.i(TAG, "Switching Camera View from ${this.cameraId} to $newCam")
closeCamera()
openCamera(texture.width, texture.height, newCam)
}
private fun setAutoFlash(requestBuilder: CaptureRequest.Builder) {
if (flashSupported) {
requestBuilder.set(CaptureRequest.CONTROL_AE_MODE, CaptureRequest.CONTROL_AE_MODE_ON_AUTO_FLASH)
}
}
companion object {
private val ORIENTATIONS = SparseIntArray()
private const val FRAGMENT_DIALOG = "dialog"
init {
ORIENTATIONS.append(Surface.ROTATION_0, 90)
ORIENTATIONS.append(Surface.ROTATION_90, 0)
ORIENTATIONS.append(Surface.ROTATION_180, 270)
ORIENTATIONS.append(Surface.ROTATION_270, 180)
}
private const val TAG = "Camera2BasicFragment"
private const val STATE_PREVIEW = 0
private const val MAX_PREVIEW_WIDTH = 1920
private const val MAX_PREVIEW_HEIGHT = 1080
@JvmStatic private fun chooseOptimalSize(choices: Array<Size>, textureViewWidth: Int, textureViewHeight: Int, maxWidth: Int, maxHeight: Int, aspectRatio: Size): Size {
// Collect the supported resolutions that are at least as big as the preview Surface
val bigEnough = ArrayList<Size>()
// Collect the supported resolutions that are smaller than the preview Surface
val notBigEnough = ArrayList<Size>()
val w = aspectRatio.width
val h = aspectRatio.height
for (option in choices) {
if (option.width <= maxWidth && option.height <= maxHeight &&
option.height == option.width * h / w) {
if (option.width >= textureViewWidth && option.height >= textureViewHeight) bigEnough.add(option)
else notBigEnough.add(option)
}
}
// Pick the smallest of those big enough. If there is no one big enough, pick the
// largest of those not big enough.
return when {
bigEnough.size > 0 -> Collections.min(bigEnough, CompareSizesByArea())
notBigEnough.size > 0 -> Collections.max(notBigEnough, CompareSizesByArea())
else -> {
LogHelper.e(TAG, "Couldn't find any suitable preview size")
choices[0]
}
}
}
@JvmStatic fun newInstance(): Camera2BasicFragment = Camera2BasicFragment()
}
} | app/src/main/java/com/itachi1706/cheesecakeutilities/modules/cameraViewer/Camera2BasicFragment.kt | 966718870 |
/*
* Licensed under Apache-2.0
*
* Designed and developed by Aidan Follestad (@afollestad)
*/
package com.afollestad.iconrequest.remote
import io.reactivex.Observable
import okhttp3.MultipartBody
import retrofit2.http.Multipart
import retrofit2.http.POST
import retrofit2.http.Part
interface RequestManagerApi {
@Multipart
@POST("/v1/request")
fun performRequest(
@Part archive: MultipartBody.Part,
@Part appsJson: MultipartBody.Part
): Observable<ApiResponse>
}
| library/src/main/java/com/afollestad/iconrequest/remote/RequestManagerApi.kt | 778490058 |
package com.jeremiahzucker.pandroid.request.json.v5.method.exp.user
import com.jeremiahzucker.pandroid.request.BaseMethod
/**
* Created by Jeremiah Zucker on 8/22/2017.
* TODO: Not "unofficially" documented. Determine usefulness.
*/
object AccountMessageDismissed : BaseMethod()
| app/src/main/java/com/jeremiahzucker/pandroid/request/json/v5/method/exp/user/AccountMessageDismissed.kt | 1618177411 |
package ru.hyst329.openfool
import com.badlogic.gdx.Gdx
import com.badlogic.gdx.Screen
import com.badlogic.gdx.graphics.Color
import com.badlogic.gdx.graphics.GL20
import com.badlogic.gdx.graphics.Texture
import com.badlogic.gdx.graphics.g2d.Sprite
import com.badlogic.gdx.scenes.scene2d.Action
import com.badlogic.gdx.scenes.scene2d.Event
import com.badlogic.gdx.scenes.scene2d.EventListener
import com.badlogic.gdx.scenes.scene2d.Group
import com.badlogic.gdx.scenes.scene2d.InputEvent
import com.badlogic.gdx.scenes.scene2d.InputListener
import com.badlogic.gdx.scenes.scene2d.Stage
import com.badlogic.gdx.scenes.scene2d.Touchable
import com.badlogic.gdx.scenes.scene2d.actions.Actions
import com.badlogic.gdx.utils.viewport.FitViewport
import mu.KotlinLogging
import java.security.SecureRandom
import java.util.ArrayList
import java.util.HashMap
import ru.hyst329.openfool.GameScreen.GameState.BEATEN
import ru.hyst329.openfool.GameScreen.GameState.BEATING
import ru.hyst329.openfool.GameScreen.GameState.DRAWING
import ru.hyst329.openfool.GameScreen.GameState.FINISHED
import ru.hyst329.openfool.GameScreen.GameState.READY
import ru.hyst329.openfool.GameScreen.GameState.THROWING
import ru.hyst329.openfool.GameScreen.GameState.THROWN
import ru.hyst329.openfool.ResultScreen.Result.TEAM_DRAW
import ru.hyst329.openfool.ResultScreen.Result.TEAM_LOST
import ru.hyst329.openfool.ResultScreen.Result.TEAM_PARTNER_LOST
import ru.hyst329.openfool.ResultScreen.Result.TEAM_WON
import ru.hyst329.openfool.ResultScreen.Result.DRAW
import ru.hyst329.openfool.ResultScreen.Result.LOST
import ru.hyst329.openfool.ResultScreen.Result.WON
import kotlin.math.min
/**
* Created by main on 13.03.2017.
* Licensed under MIT License.
*/
private val logger = KotlinLogging.logger {}
class GameScreen(private val game: OpenFoolGame) : Screen, EventListener {
private val background: Texture
private val backgroundColor: Color
private val suitSymbols: Map<Suit, Sprite> = mapOf(
Suit.SPADES to Sprite(game.assetManager.get("suits/spades.png", Texture::class.java)),
Suit.DIAMONDS to Sprite(game.assetManager.get("suits/diamonds.png", Texture::class.java)),
Suit.CLUBS to Sprite(game.assetManager.get("suits/clubs.png", Texture::class.java)),
Suit.HEARTS to Sprite(game.assetManager.get("suits/hearts.png", Texture::class.java))
)
internal enum class GameState {
READY,
DRAWING,
THROWING,
THROWN,
BEATING,
BEATEN,
FINISHED
}
private inner class GameStateChangedAction internal constructor(private val newState: GameState) : Action() {
override fun act(delta: Float): Boolean {
gameState = newState
return true
}
}
private inner class SortAction internal constructor(private val playerIndex: Int) : Action() {
override fun act(delta: Float): Boolean {
if (playerIndex == 0)
sortPlayerCards()
return true
}
}
private val stage: Stage
private val discardPileGroup: Group
private val tableGroup: Group
private val playerGroups: Array<Group>
internal lateinit var trumpSuit: Suit
internal val players: Array<Player>
internal var attackCards = arrayOfNulls<Card>(DEAL_LIMIT)
private set
internal var defenseCards = arrayOfNulls<Card>(DEAL_LIMIT)
private set
private val cardActors = HashMap<Card, CardActor>()
internal var ruleSet = RuleSet(game.preferences)
private set
private val deck = Deck(ruleSet.lowestRank)
private val screenOrientationIsPortrait: Boolean = game.preferences.getBoolean(SettingsScreen.ORIENTATION, false)
private val cardScalePlayer = if (screenOrientationIsPortrait) CARD_SCALE_PLAYER_PORTRAIT else CARD_SCALE_PLAYER_LANDSCAPE
private val cardScaleTable = if (screenOrientationIsPortrait) CARD_SCALE_TABLE_PORTRAIT else CARD_SCALE_TABLE_LANDSCAPE
private val cardScaleAI = if (screenOrientationIsPortrait) CARD_SCALE_AI_PORTRAIT else CARD_SCALE_AI_LANDSCAPE
private val deckPosition = if (screenOrientationIsPortrait) DECK_POSITION_PORTRAIT else DECK_POSITION_LANDSCAPE
private val playerPosition = if (screenOrientationIsPortrait) PLAYER_POSITION_PORTRAIT else PLAYER_POSITION_LANDSCAPE
private val aiPosition = if (screenOrientationIsPortrait) AI_POSITION_PORTRAIT else AI_POSITION_LANDSCAPE
private val tablePosition = if (screenOrientationIsPortrait) TABLE_POSITION_PORTRAIT else TABLE_POSITION_LANDSCAPE
private val discardPilePosition = if (screenOrientationIsPortrait) DISCARD_PILE_POSITION_PORTRAIT else DISCARD_PILE_POSITION_LANDSCAPE
private val playerDelta = if (screenOrientationIsPortrait) PLAYER_DELTA_PORTRAIT else PLAYER_DELTA_LANDSCAPE
private val aiDelta = if (screenOrientationIsPortrait) AI_DELTA_PORTRAIT else AI_DELTA_LANDSCAPE
private val tableDelta = if (screenOrientationIsPortrait) TABLE_DELTA_PORTRAIT else TABLE_DELTA_LANDSCAPE
private val nextLineDelta = if (screenOrientationIsPortrait) NEXT_LINE_DELTA_PORTRAIT else NEXT_LINE_DELTA_LANDSCAPE
private val offset = if (screenOrientationIsPortrait) 384 else 640
private var currentAttackerIndex: Int = 0
private var currentThrowerIndex: Int = 0
private var playersSaidDone: Int = 0
private var isPlayerTaking: Boolean = false
private val random = SecureRandom()
private val outOfPlay: BooleanArray
private val discardPile = ArrayList<Card>()
private var gameState = DRAWING
private var oldGameState = FINISHED
private val sortingMode: Player.SortingMode
private var throwLimit = DEAL_LIMIT
private var playerDoneStatuses: BooleanArray
internal var places = IntArray(DEAL_LIMIT) { 0 }
init {
// Create the stage depending on screen orientation
if (screenOrientationIsPortrait) {
game.orientationHelper.requestOrientation(OrientationHelper.Orientation.PORTRAIT)
} else {
game.orientationHelper.requestOrientation(OrientationHelper.Orientation.LANDSCAPE)
}
stage = Stage(if (screenOrientationIsPortrait) {
FitViewport(480f, 800f)
} else {
FitViewport(800f, 480f)
})
// Initialise the stage
Gdx.input.inputProcessor = stage
// Get background color
backgroundColor = Color(game.preferences.getInteger(SettingsScreen.BACKGROUND_COLOR, 0x33cc4dff))
val backgroundNo = game.preferences.getInteger(SettingsScreen.BACKGROUND, 1)
background = game.assetManager.get("backgrounds/background$backgroundNo.png", Texture::class.java)
background.setWrap(Texture.TextureWrap.Repeat, Texture.TextureWrap.Repeat)
// Initialise suit symbols
for ((suit, sprite) in suitSymbols) {
sprite.setCenter(Gdx.graphics.width / 20f, Gdx.graphics.height / 3.2f)
sprite.setScale(0.5f)
}
// Initialise player info
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
outOfPlay = BooleanArray(ruleSet.playerCount)
val deckStyle = game.preferences.getString(SettingsScreen.DECK, "rus")
sortingMode = Player.SortingMode.fromInt(game.preferences.getInteger(SettingsScreen.SORTING_MODE, 0))
// Initialise groups
tableGroup = Group()
stage.addActor(tableGroup)
val deckGroup = Group()
stage.addActor(deckGroup)
discardPileGroup = Group()
stage.addActor(discardPileGroup)
playerGroups = Array(ruleSet.playerCount) { Group() }
for (i in 0 until ruleSet.playerCount) {
playerGroups[i] = Group()
stage.addActor(playerGroups[i])
}
// Add done/take listener
stage.addListener(object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
cardActors.values
.filter { it.x <= x && x <= it.x + it.width * it.scaleX && it.y <= y && y <= it.y + it.height * it.scaleY }
.forEach {
// We're clicked on a card
return true
}
if (currentThrower.index == 0 && attackCards[0] != null) {
currentThrower.sayDone()
return true
}
if (currentDefender.index == 0) {
currentDefender.sayTake()
return true
}
return true
}
})
// Initialise players
// TODO: Replace with settings
val playerNames = arrayOf("South", "West", "North", "East", "Center")
players = Array(ruleSet.playerCount) { i -> Player(ruleSet, playerNames[i], i) }
for (i in 0 until ruleSet.playerCount) {
players[i].addListener(this)
stage.addActor(players[i])
}
// Initialise card actors
val cards = deck.cards
val listener = object : InputListener() {
override fun touchDown(event: InputEvent?, x: Float, y: Float, pointer: Int, button: Int): Boolean {
// don't allow to act while throwing/beating
if (gameState == THROWING || gameState == BEATING) return true
if (event!!.target is CardActor) {
val cardActor = event.target as CardActor
logger.debug("Trying to click ${cardActor.card}\n")
val card = cardActor.card
val user = players[0]
if (!user.hand.contains(card)) {
System.out.printf("$card is not a user's card\n")
return true
}
if (currentThrower === user) {
user.throwCard(card, attackCards, defenseCards, trumpSuit)
return true
}
if (currentDefender === user) {
val nextPlayerHandSize = nextDefender.hand.size
if (user.cardCanBePassed(card, attackCards, defenseCards, nextPlayerHandSize))
user.passWithCard(card, attackCards, defenseCards, nextPlayerHandSize)
else user.beatWithCard(card, attackCards, defenseCards, trumpSuit)
return true
}
return false
}
return super.touchDown(event, x, y, pointer, button)
}
}
for (i in cards!!.indices) {
val c = cards[i]
val cardActor = CardActor(game, c, deckStyle)
cardActors.put(c, cardActor)
cardActor.addListener(this)
cardActor.addListener(listener)
cardActor.touchable = Touchable.enabled
deckGroup.addActor(cardActor)
cardActor.zIndex = i
}
// Starting the game
for (cardActor in cardActors.values) {
cardActor.isFaceUp = false
cardActor.setScale(cardScaleTable)
cardActor.setPosition(deckPosition[0], deckPosition[1])
// cardActor.setDebug(true);
}
// Determine trump
val trumpCard = deck.cards?.get(0)
val trump = cardActors[trumpCard]
trump?.rotation = -90.0f
trump?.isFaceUp = true
trump?.moveBy(90 * cardScaleTable, 0f)
trumpSuit = trumpCard!!.suit
logger.debug("Trump suit is $trumpSuit")
// Draw cards
for (i in 0 until ruleSet.playerCount) {
drawCardsToPlayer(i, DEAL_LIMIT)
}
// TODO: Check for redeal
// Determine the first attacker and thrower
var lowestTrump = Rank.ACE
var lowestTrumpCard = Card(Suit.SPADES, Rank.ACE)
var firstAttacker = 0
for (p in players) {
for (c in p.hand) {
if (c.suit === trumpSuit && (c.rank !== Rank.ACE && c.rank.value < lowestTrump.value || lowestTrump === Rank.ACE)) {
firstAttacker = p.index
lowestTrump = c.rank
lowestTrumpCard = c
}
}
}
if (firstAttacker != 0) {
val showingTrump = cardActors[lowestTrumpCard]
val z = showingTrump?.zIndex ?: 0
showingTrump?.addAction(Actions.sequence(object : Action() {
override fun act(delta: Float): Boolean {
showingTrump.isFaceUp = true
showingTrump.zIndex = 100
return true
}
}, Actions.delay(1.5f), object : Action() {
override fun act(delta: Float): Boolean {
showingTrump.isFaceUp = false
showingTrump.zIndex = z
return true
}
}))
}
logger.debug(players[firstAttacker].name +
" (${players[firstAttacker].index})" +
" has the lowest trump $lowestTrump")
currentAttackerIndex = firstAttacker
currentThrowerIndex = firstAttacker
}
override fun show() {
}
override fun render(delta: Float) {
Gdx.gl.glClearColor(backgroundColor.r, backgroundColor.g, backgroundColor.b, backgroundColor.a)
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT)
val opponents =
when {
ruleSet.teamPlay -> (if (outOfPlay[currentAttackerIndex]) 0 else 1) + if (outOfPlay[(currentAttackerIndex + 2) % ruleSet.playerCount]) 0 else 1
(outOfPlay.map { if (it) 0 else 1 }.fold(initial = 0) { total, current -> total + current }) > 2 -> 2
else -> 1
}
if (playersSaidDone == opponents && gameState != DRAWING
&& gameState != BEATING && gameState != THROWING) {
logger.debug("Done - all players said done!")
gameState = FINISHED
}
if (oldGameState != gameState) {
logger.debug("Game state is $gameState")
tintCards()
oldGameState = gameState
}
when (gameState) {
READY -> if (currentAttacker.index != 0) {
throwLimit = min((if (ruleSet.loweredFirstDiscardLimit
&& discardPile.isEmpty())
DEAL_LIMIT else DEAL_LIMIT - 1), currentDefender.hand.size)
currentAttacker.startTurn(trumpSuit, cardsRemaining(), players.map { it.hand.size }.toTypedArray())
}
DRAWING -> {
}
THROWING -> {
}
THROWN -> {
if (currentDefender.index != 0) {
if (!isPlayerTaking) {
currentDefender.tryBeat(attackCards, defenseCards, trumpSuit, cardsRemaining(), players.map { it.hand.size }.toTypedArray())
} else {
currentDefender.sayTake()
}
}
if (isPlayerTaking)
gameState = BEATEN
}
BEATING -> {
}
BEATEN -> {
val forcedFinish =
if (currentDefender.hand.size == 0 || attackCards[throwLimit - 1] != null) {
logger.debug("Forced to finish the turn")
gameState = FINISHED
true
} else false
if (currentThrower.index != 0) {
if (!forcedFinish)
currentThrower.throwOrDone(attackCards, defenseCards, trumpSuit, cardsRemaining(), players.map { it.hand.size }.toTypedArray())
else
currentThrower.sayDone()
}
}
FINISHED -> {
val playerTook = isPlayerTaking
val currentDefenderIndex = currentDefender.index
endTurn(if (isPlayerTaking) currentDefender.index else -1)
if (isGameOver) {
logger.debug("GAME OVER")
} else {
currentAttackerIndex += if (playerTook) 2 else 1
currentAttackerIndex %= ruleSet.playerCount
if (!ruleSet.teamPlay)
// Defender who took cannot attack anyway!
while (outOfPlay[currentAttackerIndex] ||
(playerTook && currentAttackerIndex == currentDefenderIndex)) {
currentAttackerIndex++
if (currentAttackerIndex == ruleSet.playerCount)
currentAttackerIndex = 0
if (isGameOver) break
}
currentThrowerIndex = currentAttackerIndex
logger.debug("${currentAttacker.name} (${currentAttacker.index}) -> ${currentDefender.name} (${currentDefender.index})")
}
}
}
// Draw background
game.batch.transformMatrix = stage.viewport.camera.view
game.batch.projectionMatrix = stage.viewport.camera.projection
game.batch.begin()
game.batch.color = backgroundColor
game.batch.draw(background, 0f, 0f, 0, 0, Gdx.graphics.width, Gdx.graphics.height)
game.batch.color = Color(Color.WHITE)
game.batch.end()
// Draw stage
stage.act(delta)
stage.draw()
// Draw player labels
game.batch.transformMatrix = stage.viewport.camera.view
game.batch.projectionMatrix = stage.viewport.camera.projection
game.batch.begin()
for (i in 0 until ruleSet.playerCount) {
val position = (if (i == 0) playerPosition else aiPosition).clone()
if (i > 0 && ruleSet.playerCount > 2)
position[0] += ((i - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
if (screenOrientationIsPortrait) {
if (i > 0) {
position[1] -= 320 * cardScaleAI
} else {
position[1] += 760 * cardScalePlayer
}
} else {
position[1] += 640 * if (i == 0) cardScalePlayer else cardScaleAI
}
var playerFormat = "${players[i].name} (${players[i].hand.size})"
if (playerDoneStatuses[i]) playerFormat += "\n" + game.localeBundle["PlayerDone"]
if (isPlayerTaking && currentDefender.index == i)
playerFormat += "\n" + game.localeBundle["PlayerTakes"]
game.font.draw(game.batch, playerFormat,
position[0], position[1])
}
game.font.draw(game.batch, "${cardsRemaining()}", stage.viewport.worldWidth / 10f, stage.viewport.worldHeight / 3f)
var turnString = "${currentAttacker.name} -> ${currentDefender.name}"
val newLineOrSpaces = if (screenOrientationIsPortrait) " " else "\n"
if (currentAttacker.index == 0)
turnString += newLineOrSpaces + game.localeBundle["YourTurn"]
if (currentDefender.index == 0)
turnString += newLineOrSpaces + game.localeBundle["Defend"]
suitSymbols[trumpSuit]?.draw(game.batch)
if (screenOrientationIsPortrait) {
game.font.draw(game.batch, turnString, stage.viewport.worldWidth / 5f, stage.viewport.worldHeight / 3.2f)
} else {
game.font.draw(game.batch, turnString, stage.viewport.worldWidth / 40f, stage.viewport.worldHeight / 4.8f)
}
game.batch.end()
// Check if the game is over
if (isGameOver) {
var gameResult: ResultScreen.Result = if (outOfPlay[0]) WON else LOST
if (outOfPlay.all { it })
gameResult = DRAW
if (ruleSet.teamPlay) gameResult = if (outOfPlay[0]) TEAM_WON else TEAM_LOST
if (ruleSet.teamPlay && outOfPlay[1] && outOfPlay[3] && gameResult == TEAM_WON)
gameResult = if (outOfPlay[2]) TEAM_DRAW else TEAM_PARTNER_LOST
var position = players.size
val playersPlaces: Map<Int, String> = players.map { (if (places[it.index] == 0) position-- else places[it.index]) to it.name }.toMap()
game.screen = ResultScreen(game, gameResult, playersPlaces)
dispose()
}
}
override fun resize(width: Int, height: Int) {
stage.viewport.update(width, height, true)
stage.viewport.camera.update()
}
override fun pause() {
}
override fun resume() {
}
override fun hide() {
}
override fun dispose() {
}
private fun endTurn(playerIndex: Int) {
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
val tableCards = ArrayList<Card>()
for (i in attackCards.indices) {
if (attackCards[i] != null) {
tableCards.add(attackCards[i] as Card)
//attackCards[i] = null;
}
if (defenseCards[i] != null) {
tableCards.add(defenseCards[i] as Card)
//defenseCards[i] = null;
}
}
attackCards = arrayOfNulls(DEAL_LIMIT)
defenseCards = arrayOfNulls(DEAL_LIMIT)
if (playerIndex < 0) {
for (card in tableCards) {
val cardActor = cardActors[card]
discardPile.add(card)
discardPileGroup.addActor(cardActor)
cardActor?.isFaceUp = false
cardActor?.zIndex = discardPile.size - 1
cardActor?.rotation = random.nextFloat() * 20 - 10
val dx = random.nextFloat() * 20 - 10
val dy = random.nextFloat() * 20 - 10
cardActor?.addAction(
Actions.moveTo(discardPilePosition[0] + dx, discardPilePosition[1] + dy, 0.6f))
}
} else {
val player = players[playerIndex]
for (card in tableCards) {
player.addCard(card)
val cardActor = cardActors[card]
cardActor?.isFaceUp = (playerIndex == 0)
val position = (if (playerIndex == 0) playerPosition else aiPosition).clone()
if (playerIndex > 0 && ruleSet.playerCount > 2)
position[0] += ((playerIndex - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val delta = (if (playerIndex == 0) playerDelta else aiDelta).clone()
val index = player.hand.size - 1
val posX = position[0] + index * delta[0]
val posY = position[1] + index * delta[1]
cardActor?.addAction(Actions.moveTo(posX, posY, 0.4f))
cardActor?.rotation = 0.0f
cardActor?.setScale(if (playerIndex == 0) cardScalePlayer else cardScaleAI)
playerGroups[playerIndex].addActor(cardActor)
cardActor?.zIndex = index
}
player.addAction(Actions.sequence(
Actions.delay(0.39f),
SortAction(playerIndex)
))
}
if (deck.cards?.isEmpty() == false) {
for (i in 0 until ruleSet.playerCount) {
val cardsToDraw = DEAL_LIMIT - players[i].hand.size
if (cardsToDraw > 0) {
drawCardsToPlayer(i, cardsToDraw)
}
if (deck.cards?.isEmpty() != false)
break
}
}
// Check if someone is out of play
if (deck.cards?.isEmpty() != false) {
for (i in 0 until ruleSet.playerCount) {
val oldOutOfPlay = outOfPlay[i]
outOfPlay[i] = players[i].hand.size == 0
if (outOfPlay[i] && !oldOutOfPlay) {
places[i] = outOfPlay.count { it }
}
}
}
isPlayerTaking = false
gameState = READY
}
fun tintCards() {
// Tint the available cards for throwing/beating
for (a in cardActors.values) {
a.untint()
}
when {
currentThrower === players[0] && attackCards[0] != null -> {
for (c in players[0].hand) {
val actor = cardActors[c]
// If the card cannot be thrown, grey it out
if (!players[0].cardCanBeThrown(c, attackCards, defenseCards))
actor?.tint(Color.GRAY)
}
}
currentDefender === players[0] -> {
for (c in players[0].hand) {
val actor = cardActors[c]
// If the card cannot beat, grey it out
if (!players[0].cardCanBeBeaten(c, attackCards, defenseCards, trumpSuit))
actor?.tint(Color.GRAY)
// If the card can be passed, tint it green
if (players[0].cardCanBePassed(c, attackCards, defenseCards, nextDefender.hand.size))
actor?.tint(Color.GREEN)
}
}
else -> {
}
}
}
private // TODO: Generalise
val isGameOver: Boolean
get() {
if (ruleSet.teamPlay)
return outOfPlay[0] && outOfPlay[2] || outOfPlay[1] && outOfPlay[3]
else {
// Simply check if only one player remains
return (outOfPlay.map { if (it) 0 else 1 }.fold(initial = 0) { total, current -> total + current }) <= 1
}
}
val areAllCardsBeaten: Boolean
get() {
return (0 until DEAL_LIMIT).map { (attackCards[it] != null) == (defenseCards[it] != null) }
.fold(initial = true) { total, current -> total && current }
}
internal fun cardsRemaining(): Int {
return deck.cards?.size ?: 0
}
override fun handle(event: Event): Boolean {
if (event is Player.CardThrownEvent) {
// Handle when card is thrown
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
var throwIndex = 0
while (attackCards[throwIndex] != null) throwIndex++
val throwCard = event.card
attackCards[throwIndex] = throwCard
val throwCardActor = cardActors[throwCard]
throwCardActor?.isFaceUp = true
tableGroup.addActor(throwCardActor)
throwCardActor?.zIndex = 2 * throwIndex
throwCardActor?.setScale(cardScaleTable)
val throwPos = tablePosition.clone()
throwPos[0] += (90 * throwIndex).toFloat()
if (throwIndex >= 3) {
throwPos[0] += nextLineDelta[0]
throwPos[1] += nextLineDelta[1]
}
throwCardActor?.addAction(Actions.sequence(
GameStateChangedAction(GameState.THROWING),
Actions.moveTo(throwPos[0], throwPos[1], 0.4f),
Actions.delay(0.2f),
GameStateChangedAction(GameState.THROWN)))
val thrower = event.getTarget() as Player
logger.debug("${thrower.name} (${thrower.index}) throws $throwCard")
for (i in 0 until thrower.hand.size) {
val cardActor = cardActors[thrower.hand[i]]
val position = (if (thrower.index == 0) playerPosition else aiPosition).clone()
val delta = (if (thrower.index == 0) playerDelta else aiDelta).clone()
if (thrower.index > 0 && ruleSet.playerCount > 2)
position[0] += ((thrower.index - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val posX = position[0] + i * delta[0]
val posY = position[1] + i * delta[1]
//cardActor.addAction(Actions.moveTo(posX, posY, 0.1f));
cardActor?.setPosition(posX, posY)
cardActor?.rotation = 0.0f
cardActor?.setScale(if (thrower.index == 0) cardScalePlayer else cardScaleAI)
cardActor?.zIndex = i
}
return true
}
if (event is Player.CardBeatenEvent) {
// Handle when card is beaten
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
var beatIndex = 0
while (defenseCards[beatIndex] != null) beatIndex++
val beatCard = event.card
defenseCards[beatIndex] = beatCard
val beatCardActor = cardActors[beatCard]
beatCardActor?.isFaceUp = true
tableGroup.addActor(beatCardActor)
beatCardActor?.zIndex = 2 * beatIndex + 1
beatCardActor?.setScale(cardScaleTable)
val beatPos = tablePosition.clone()
beatPos[0] += (90 * beatIndex).toFloat()
if (beatIndex >= 3) {
beatPos[0] += nextLineDelta[0]
beatPos[1] += nextLineDelta[1]
}
beatCardActor?.addAction(Actions.sequence(
GameStateChangedAction(BEATING),
Actions.moveTo(beatPos[0] + tableDelta[0], beatPos[1] + tableDelta[1], 0.4f),
Actions.delay(0.2f),
GameStateChangedAction(if (areAllCardsBeaten) BEATEN else THROWN)))
val beater = event.getTarget() as Player
logger.debug("${beater.name} (${beater.index}) beats with $beatCard\n")
for (i in 0 until beater.hand.size) {
val cardActor = cardActors[beater.hand[i]]
val position = (if (beater.index == 0) playerPosition else aiPosition).clone()
val delta = (if (beater.index == 0) playerDelta else aiDelta).clone()
if (beater.index > 0 && ruleSet.playerCount > 2)
position[0] += ((beater.index - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val posX = position[0] + i * delta[0]
val posY = position[1] + i * delta[1]
//cardActor.addAction(Actions.moveTo(posX, posY, 0.1f));
cardActor?.setPosition(posX, posY)
cardActor?.rotation = 0.0f
cardActor?.setScale(if (beater.index == 0) cardScalePlayer else cardScaleAI)
cardActor?.zIndex = i
}
return true
}
if (event is Player.CardPassedEvent) {
// Handle when player passes
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
var passIndex = 0
while (attackCards[passIndex] != null) passIndex++
val passCard = event.card
attackCards[passIndex] = passCard
val passCardActor = cardActors[passCard]
passCardActor?.isFaceUp = true
tableGroup.addActor(passCardActor)
passCardActor?.zIndex = 2 * passIndex
passCardActor?.setScale(cardScaleTable)
val passPos = tablePosition.clone()
passPos[0] += (90 * passIndex).toFloat()
if (passIndex >= 3) {
passPos[0] += nextLineDelta[0]
passPos[1] += nextLineDelta[1]
}
passCardActor?.addAction(Actions.sequence(
GameStateChangedAction(GameState.THROWING),
Actions.moveTo(passPos[0], passPos[1], 0.4f),
Actions.delay(0.2f),
GameStateChangedAction(GameState.THROWN)))
val thrower = event.getTarget() as Player
logger.debug("${thrower.name} (${thrower.index}) passes with $passCard\n")
for (i in 0 until thrower.hand.size) {
val cardActor = cardActors[thrower.hand[i]]
val position = (if (thrower.index == 0) playerPosition else aiPosition).clone()
val delta = (if (thrower.index == 0) playerDelta else aiDelta).clone()
if (thrower.index > 0 && ruleSet.playerCount > 2)
position[0] += ((thrower.index - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val posX = position[0] + i * delta[0]
val posY = position[1] + i * delta[1]
//cardActor.addAction(Actions.moveTo(posX, posY, 0.1f));
cardActor?.setPosition(posX, posY)
cardActor?.rotation = 0.0f
cardActor?.setScale(if (thrower.index == 0) cardScalePlayer else cardScaleAI)
cardActor?.zIndex = i
}
do {
currentAttackerIndex++
if (currentAttackerIndex == players.size) currentAttackerIndex = 0
} while (outOfPlay[currentAttackerIndex])
currentThrowerIndex = currentAttackerIndex
logger.debug("Passed to: ${currentAttacker.name} -> ${currentDefender.name}")
}
if (event is Player.TakeEvent) {
// Handle when player takes
playersSaidDone = 0
playerDoneStatuses = BooleanArray(ruleSet.playerCount)
isPlayerTaking = true
val player = event.getTarget() as Player
logger.debug("${player.name} (${player.index}) decides to take")
return true
}
if (event is Player.DoneEvent) {
// Handle when player says done
playersSaidDone++
currentThrowerIndex += 2
currentThrowerIndex %= ruleSet.playerCount
val player = event.getTarget() as Player
playerDoneStatuses[player.index] = true
logger.debug("${player.name} (${player.index}) says done\n")
return true
}
return false
}
private fun drawCardsToPlayer(playerIndex: Int, cardCount: Int) {
val player = players[playerIndex]
if (!deck.cards!!.isEmpty()) {
player.addAction(Actions.sequence(
GameStateChangedAction(GameState.DRAWING),
Actions.delay(0.39f),
GameStateChangedAction(READY),
SortAction(playerIndex)
))
}
for (i in 0 until cardCount) {
if (deck.cards!!.isEmpty())
break
val card = deck.draw() as Card
player.addCard(card)
val cardActor = cardActors[card]
cardActor?.isFaceUp = (playerIndex == 0)
val position = (if (playerIndex == 0) playerPosition else aiPosition).clone()
if (playerIndex > 0 && ruleSet.playerCount > 2)
position[0] += ((playerIndex - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val delta = (if (playerIndex == 0) playerDelta else aiDelta).clone()
val index = player.hand.size - 1
val posX = position[0] + index * delta[0]
val posY = position[1] + index * delta[1]
cardActor?.addAction(Actions.moveTo(posX, posY, 0.4f))
cardActor?.rotation = 0.0f
cardActor?.setScale(if (playerIndex == 0) cardScalePlayer else cardScaleAI)
playerGroups[playerIndex].addActor(cardActor)
cardActor?.zIndex = index
}
}
private val currentAttacker: Player
get() {
if (outOfPlay[currentAttackerIndex]) {
return players[(currentAttackerIndex + 2) % ruleSet.playerCount]
}
return players[currentAttackerIndex]
}
private val currentDefender: Player
get() {
var currentDefenderIndex = (currentAttackerIndex + 1) % ruleSet.playerCount
if (!ruleSet.teamPlay)
while (outOfPlay[currentDefenderIndex]) {
currentDefenderIndex++
if (currentDefenderIndex == ruleSet.playerCount)
currentDefenderIndex = 0
}
else if (outOfPlay[currentDefenderIndex]) {
return players[(currentDefenderIndex + 2) % ruleSet.playerCount]
}
return players[currentDefenderIndex]
}
private val nextDefender: Player
get() {
var nextDefenderIndex = (currentDefender.index + 1) % ruleSet.playerCount
if (!ruleSet.teamPlay)
while (outOfPlay[nextDefenderIndex]) {
nextDefenderIndex++
if (nextDefenderIndex == ruleSet.playerCount)
nextDefenderIndex = 0
}
else if (outOfPlay[nextDefenderIndex]) {
return players[(nextDefenderIndex + 2) % ruleSet.playerCount]
}
return players[nextDefenderIndex]
}
private val currentThrower: Player
get() {
if (outOfPlay[currentThrowerIndex]) {
return players[(currentThrowerIndex + 2) % ruleSet.playerCount]
}
return players[currentThrowerIndex]
}
private fun sortPlayerCards() {
// TODO: Generalise to other players
val player = players[0]
player.sortCards(sortingMode, trumpSuit)
// Reposition all cards
for (i in 0 until player.hand.size) {
val cardActor = cardActors[player.hand[i]]
val position = (if (player.index == 0) playerPosition else aiPosition).clone()
val delta = (if (player.index == 0) playerDelta else aiDelta).clone()
if (player.index > 0)
position[0] += ((player.index - 1) * offset / (ruleSet.playerCount - 2)).toFloat()
val posX = position[0] + i * delta[0]
val posY = position[1] + i * delta[1]
cardActor?.setPosition(posX, posY)
cardActor?.rotation = 0.0f
cardActor?.setScale(if (player.index == 0) cardScalePlayer else cardScaleAI)
cardActor?.zIndex = i
}
}
companion object {
private const val DEAL_LIMIT = 6
private const val CARD_SCALE_TABLE_LANDSCAPE = 0.24f
private const val CARD_SCALE_AI_LANDSCAPE = 0.18f
private const val CARD_SCALE_PLAYER_LANDSCAPE = 0.28f
// Half-widths and half-heights
private const val HW_TABLE_LANDSCAPE = CARD_SCALE_TABLE_LANDSCAPE * 180
private const val HW_AI_LANDSCAPE = CARD_SCALE_AI_LANDSCAPE * 180
private const val HW_PLAYER_LANDSCAPE = CARD_SCALE_PLAYER_LANDSCAPE * 180
private const val HH_TABLE_LANDSCAPE = CARD_SCALE_TABLE_LANDSCAPE * 270
private const val HH_AI_LANDSCAPE = CARD_SCALE_AI_LANDSCAPE * 270
private const val HH_PLAYER_LANDSCAPE = CARD_SCALE_PLAYER_LANDSCAPE * 270
private val DECK_POSITION_LANDSCAPE = floatArrayOf(60 - HW_TABLE_LANDSCAPE, 240 - HH_TABLE_LANDSCAPE)
private val DISCARD_PILE_POSITION_LANDSCAPE = floatArrayOf(680 - HW_TABLE_LANDSCAPE, 180 - HH_TABLE_LANDSCAPE)
private val PLAYER_POSITION_LANDSCAPE = floatArrayOf(240 - HW_PLAYER_LANDSCAPE, 80 - HH_PLAYER_LANDSCAPE)
private val AI_POSITION_LANDSCAPE = floatArrayOf(60 - HW_AI_LANDSCAPE, 400 - HH_AI_LANDSCAPE)
private val TABLE_POSITION_LANDSCAPE = floatArrayOf(200 - HW_TABLE_LANDSCAPE, 280 - HH_TABLE_LANDSCAPE)
private val TABLE_DELTA_LANDSCAPE = floatArrayOf(10f, -10f)
private val PLAYER_DELTA_LANDSCAPE = floatArrayOf(40f, 0f)
private val AI_DELTA_LANDSCAPE = floatArrayOf(5f, -5f)
private val NEXT_LINE_DELTA_LANDSCAPE = floatArrayOf(0f, 0f)
private const val CARD_SCALE_TABLE_PORTRAIT = 0.20f
private const val CARD_SCALE_AI_PORTRAIT = 0.10f
private const val CARD_SCALE_PLAYER_PORTRAIT = 0.36f
// Half-widths and half-heights
private const val HW_TABLE_PORTRAIT = CARD_SCALE_TABLE_PORTRAIT * 180
private const val HW_AI_PORTRAIT = CARD_SCALE_AI_PORTRAIT * 180
private const val HW_PLAYER_PORTRAIT = CARD_SCALE_PLAYER_PORTRAIT * 180
private const val HH_TABLE_PORTRAIT = CARD_SCALE_TABLE_PORTRAIT * 270
private const val HH_AI_PORTRAIT = CARD_SCALE_AI_PORTRAIT * 270
private const val HH_PLAYER_PORTRAIT = CARD_SCALE_PLAYER_PORTRAIT * 270
private val DECK_POSITION_PORTRAIT = floatArrayOf(40 - HW_TABLE_PORTRAIT, 440 - HH_TABLE_PORTRAIT)
private val DISCARD_PILE_POSITION_PORTRAIT = floatArrayOf(440 - HW_TABLE_PORTRAIT, 440 - HH_TABLE_PORTRAIT)
private val PLAYER_POSITION_PORTRAIT = floatArrayOf(120 - HW_PLAYER_PORTRAIT, 120 - HH_PLAYER_PORTRAIT)
private val AI_POSITION_PORTRAIT = floatArrayOf(20 - HW_AI_PORTRAIT, 760 - HH_AI_PORTRAIT)
private val TABLE_POSITION_PORTRAIT = floatArrayOf(160 - HW_TABLE_PORTRAIT, 480 - HH_TABLE_PORTRAIT)
private val TABLE_DELTA_PORTRAIT = floatArrayOf(10f, -10f)
private val PLAYER_DELTA_PORTRAIT = floatArrayOf(40f, 0f)
private val AI_DELTA_PORTRAIT = floatArrayOf(5f, -5f)
private val NEXT_LINE_DELTA_PORTRAIT = floatArrayOf(-270f, -120f)
}
}
| core/src/ru/hyst329/openfool/GameScreen.kt | 1045002594 |
/*
* Copyright © 2020 Wayfair. All rights reserved.
*/
package com.wayfair.brickkit.size
import com.wayfair.brickkit.BrickDataManager
class NumberOfColumnsBrickSize(numberOfColumns: Int) : BrickSize(
BrickDataManager.SPAN_COUNT / numberOfColumns,
BrickDataManager.SPAN_COUNT / numberOfColumns,
BrickDataManager.SPAN_COUNT / numberOfColumns,
BrickDataManager.SPAN_COUNT / numberOfColumns
)
| BrickKit/bricks/src/main/java/com/wayfair/brickkit/size/NumberOfColumnsBrickSize.kt | 3630725589 |
package com.electroweak.game.entity
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.math.Vector2
import com.electroweak.game.asset.Assets
import com.electroweak.game.core.Globals
import com.electroweak.game.entity.component.*
import com.electroweak.game.entity.system.Mappers
class Bullet(val bulletDamage: BulletDamage) : Entity() {
enum class BulletDamage(val damage: Float) {
WEAK(10f),
NORMAL(20f),
STRONG(30f)
}
init {
val textureComponent = TextureComponent()
val positionComponent = PositionComponent()
val sizeComponent = SizeComponent()
val rotationComponent = RotationComponent()
val bulletComponent = BulletComponent()
val velocityComponent = VelocityComponent()
val collisionComponent = CollisionComponent()
textureComponent.textureRegion = Assets.getAtlasRegion(Assets.Resource.BULLET)
positionComponent.position = Globals.SCREEN_CENTER.cpy()
sizeComponent.width = textureComponent.textureRegion.regionWidth.toFloat()
sizeComponent.height = textureComponent.textureRegion.regionHeight.toFloat()
bulletComponent.damage = bulletDamage.damage
collisionComponent.collisionHandler = object : CollisionHandler {
override fun collision(owner: Entity, entity: Entity) {
}
}
add(textureComponent)
add(positionComponent)
add(sizeComponent)
add(rotationComponent)
add(bulletComponent)
add(velocityComponent)
add(collisionComponent)
}
fun setPosition(position: Vector2) {
val positionComponent = Mappers.POSITION_MAPPER.get(this)
positionComponent.position = position
}
fun setScale(scale: Float) {
val sizeComponent = Mappers.SIZE_MAPPER.get(this)
sizeComponent.scaleX = scale
sizeComponent.scaleY = scale
}
fun setVelocity(velocity: Vector2) {
Mappers.VELOCITY_MAPPER.get(this).velocity = velocity
}
fun setRotation(rotation: Float) {
Mappers.ROTATION_MAPPER.get(this).rotation = rotation
}
fun getPosition() : Vector2 = Mappers.POSITION_MAPPER.get(this).position!!.cpy()
fun getWidth() : Float = Mappers.SIZE_MAPPER.get(this).width
fun getHeight() : Float = Mappers.SIZE_MAPPER.get(this).height
} | core/src/com/electroweak/game/entity/Bullet.kt | 2123585410 |
package com.kamelong.aodia.TimeTable
import android.app.Dialog
import android.widget.Button
import android.widget.LinearLayout
import com.kamelong.OuDia.Train
import com.kamelong.aodia.MainActivity
class OpenLineFileSelector(activity:MainActivity,listener:OnLineFileOpenSelect):Dialog(activity){
init{
val layout=LinearLayout(activity)
layout.orientation=LinearLayout.VERTICAL
setContentView(layout)
val openNormal=Button(context)
openNormal.setText("新しい路線として開く")
openNormal.setOnClickListener { listener.openAsNewLine();this.dismiss() }
val appendDown=Button(context)
appendDown.setText("下り方向に挿入する")
appendDown.setOnClickListener { listener.openAsIncludeLine(Train.DOWN);this.dismiss() }
val appendUp=Button(context)
appendUp.setText("上り方向に挿入する")
appendUp.setOnClickListener { listener.openAsIncludeLine(Train.UP);this.dismiss() }
layout.addView(openNormal)
layout.addView(appendDown)
layout.addView(appendUp)
}
}
interface OnLineFileOpenSelect{
fun openAsNewLine();
fun openAsIncludeLine(direction:Int);
}
| app/src/main/java/com/kamelong/aodia/TimeTable/OpenLineFileSelector.kt | 2887727660 |
/*
* Copyright 2017 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.orca.q
import com.netflix.spinnaker.orca.ExecutionStatus.*
import com.netflix.spinnaker.orca.pipeline.model.Execution
import com.netflix.spinnaker.orca.pipeline.model.Stage
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_AFTER
import com.netflix.spinnaker.orca.pipeline.model.SyntheticStageOwner.STAGE_BEFORE
import com.netflix.spinnaker.orca.pipeline.model.Task
/**
* @return the initial stages of the execution.
*/
fun Execution<*>.initialStages() =
getStages()
.filter { it.isInitial() }
/**
* @return the stage's first before stage or `null` if there are none.
*/
fun Stage<out Execution<*>>.firstBeforeStages() =
getExecution()
.getStages()
.filter {
it.getParentStageId() == getId() && it.getSyntheticStageOwner() == STAGE_BEFORE && it.getRequisiteStageRefIds().isEmpty()
}
/**
* @return the stage's first after stage or `null` if there are none.
*/
fun Stage<out Execution<*>>.firstAfterStages() =
getExecution()
.getStages()
.filter {
it.getParentStageId() == getId() && it.getSyntheticStageOwner() == STAGE_AFTER && it.getRequisiteStageRefIds().isEmpty()
}
fun Stage<*>.isInitial() =
getRequisiteStageRefIds() == null || getRequisiteStageRefIds().isEmpty()
/**
* @return the stage's first task or `null` if there are none.
*/
fun Stage<out Execution<*>>.firstTask() = getTasks().firstOrNull()
/**
* @return the stage's parent stage.
* @throws IllegalStateException if the stage is not synthetic.
*/
fun Stage<out Execution<*>>.parent() =
getExecution()
.getStages()
.find { it.getId() == getParentStageId() } ?: throw IllegalStateException("Not a synthetic stage")
/**
* @return the task that follows [task] or `null` if [task] is the end of the
* stage.
*/
fun Stage<out Execution<*>>.nextTask(task: Task) =
if (task.isStageEnd) {
null
} else {
val index = getTasks().indexOf(task)
getTasks()[index + 1]
}
/**
* @return the stage with the specified [refId].
* @throws IllegalArgumentException if there is no such stage.
*/
fun <T : Execution<T>> Execution<T>.stageByRef(refId: String) =
stages.find { it.refId == refId } ?: throw IllegalArgumentException("No such stage")
/**
* @return all upstream stages of this stage.
*/
fun Stage<*>.upstreamStages(): List<Stage<*>> =
getExecution().getStages().filter { it.getRefId() in getRequisiteStageRefIds().orEmpty() }
/**
* @return `true` if all upstream stages of this stage were run successfully.
*/
fun Stage<*>.allUpstreamStagesComplete(): Boolean =
upstreamStages().all { it.getStatus() in listOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED) }
fun Stage<*>.beforeStages(): List<Stage<*>> =
getExecution().getStages().filter { it.getParentStageId() == getId() && it.getSyntheticStageOwner() == STAGE_BEFORE }
fun Stage<*>.allBeforeStagesComplete(): Boolean =
beforeStages().all { it.getStatus() in listOf(SUCCEEDED, FAILED_CONTINUE, SKIPPED) }
| orca-queue/src/main/kotlin/com/netflix/spinnaker/orca/q/Executions.kt | 754137081 |
package ee.design.task
import ee.design.ModuleI
import ee.lang.ItemI
import ee.lang.StructureUnitI
import ee.task.PathResolver
import java.nio.file.Path
import java.nio.file.Paths
open class DesignPathResolver : PathResolver {
constructor(home: Path = Paths.get(""), itemToHome: MutableMap<String, String> = hashMapOf()) : super(home,
itemToHome) {
}
override fun <T : ItemI<*>> resolve(item: T): Path {
if (!itemToHome.containsKey(item.name())) {
val ret = resolve(item.parent())
if (item is StructureUnitI<*>) {
if (item is ModuleI<*>) {
return ret.parent.resolve(item.artifact())
} else {
return ret.resolve(item.artifact())
}
} else {
return ret
}
} else {
return home.resolve(itemToHome[item.name()])
}
}
}
| ee-design_task/src/main/kotlin/ee.design.task/DesignPathResolver.kt | 3340634483 |
package ee.lang.fx.view
import javafx.application.Platform
import javafx.scene.input.KeyCode
import javafx.scene.input.KeyEvent
import tornadofx.borderpane
import tornadofx.bottom
import tornadofx.center
import tornadofx.textfield
import java.util.*
import java.util.function.Consumer
class ConsoleInputView : ConsoleView("ConsoleInputView") {
private val history: MutableList<String> = ArrayList()
private var historyPointer = 0
private var onMessageReceivedHandler: Consumer<String>? = null
private val input = textfield {
addEventHandler(KeyEvent.KEY_RELEASED) { keyEvent ->
when (keyEvent.code) {
KeyCode.ENTER -> {
val text = text
out.appendText(text + System.lineSeparator())
history.add(text)
historyPointer++
if (onMessageReceivedHandler != null) {
onMessageReceivedHandler!!.accept(text)
}
clear()
}
KeyCode.UP -> {
if (historyPointer > 0) {
historyPointer--
Platform.runLater {
text = history[historyPointer]
selectAll()
}
}
}
KeyCode.DOWN -> {
if (historyPointer < history.size - 1) {
historyPointer++
Platform.runLater {
text = history[historyPointer]
selectAll()
}
}
}
else -> {
}
}
}
}
override val root = borderpane {
center { add(out) }
bottom { add(input) }
}
}
| ee-lang_fx/src/main/kotlin/ee/lang/fx/view/ConsoleInputView.kt | 3761000838 |
package com.getroadmap.r2rlib.models
import android.os.Parcel
import android.os.Parcelable
/**
* Created by jan on 11/07/16.
*
* https://www.rome2rio.com/documentation/search#Alternative
*/
open class Alternative() : Parcelable {
/**
* firstSegment integer First segment to replace (index into segments array) [1]
* lastSegment integer Last segment to replace (index into segments array) [1]
* route Route Alternative route
*/
private var firstSegment: Int? = null
private var lastSegment: Int? = null
private var route: Route? = null
constructor(parcel: Parcel) : this() {
firstSegment = parcel.readValue(Int::class.java.classLoader) as? Int
lastSegment = parcel.readValue(Int::class.java.classLoader) as? Int
route = parcel.readParcelable(Route::class.java.classLoader)
}
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeValue(firstSegment)
parcel.writeValue(lastSegment)
parcel.writeParcelable(route, flags)
}
override fun describeContents(): Int {
return 0
}
companion object CREATOR : Parcelable.Creator<Alternative> {
override fun createFromParcel(parcel: Parcel): Alternative {
return Alternative(parcel)
}
override fun newArray(size: Int): Array<Alternative?> {
return arrayOfNulls(size)
}
}
} | library/src/main/java/com/getroadmap/r2rlib/models/Alternative.kt | 1746252145 |
package com.lasthopesoftware.bluewater.client.browsing.library.views
abstract class ServerViewItem(key: Int, value: String?) : ViewItem(key, value)
| projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/library/views/ServerViewItem.kt | 434135197 |
package com.sksamuel.kotest
import io.kotest.core.spec.style.FreeSpec
import kotlin.time.ExperimentalTime
import kotlin.time.milliseconds
@UseExperimental(ExperimentalTime::class)
@Suppress("BlockingMethodInNonBlockingContext")
class MultipleTestTimeoutTest : FreeSpec() {
// The test executor was failing because as it reutilizes some threads from a thread pool.
// When using that thread pool, a task to cancel the thread is created, so that the engine can interrupt
// a test that is going forever.
// However, if the task is not cancelled, it will eventually interrupt the thread when it's running another task
// in the thread pool, interrupting a test that hasn't timed out yet, which is undesired.
init {
// 100 millis sleep will "accumulate" between tests. If the context is still shared, one of them will fail
// due to timeout.
"Test 1".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 2".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 3".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 4".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 5".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 6".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
"Test 7".config(timeout = 300.milliseconds) {
Thread.sleep(100)
}
}
}
| kotest-tests/kotest-tests-core/src/jvmTest/kotlin/com/sksamuel/kotest/MultipleTestTimeoutTest.kt | 2500576612 |
/*
* Kaesekaestchen
* A simple Dots'n'Boxes Game for Android
*
* Copyright (C) Stefan Oltmann
*
* Contact : [email protected]
* Homepage: https://github.com/StefanOltmann/Kaesekaestchen
*
* This file is part of Kaesekaestchen.
*
* Kaesekaestchen 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.
*
* Kaesekaestchen 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 Kaesekaestchen. If not, see <http://www.gnu.org/licenses/>.
*/
package de.stefan_oltmann.kaesekaestchen.ui.activities
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.drawerlayout.widget.DrawerLayout
import androidx.drawerlayout.widget.DrawerLayout.LOCK_MODE_LOCKED_CLOSED
import androidx.navigation.findNavController
import androidx.navigation.ui.setupWithNavController
import com.google.android.material.navigation.NavigationView
import de.stefan_oltmann.kaesekaestchen.R
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar: Toolbar = findViewById(R.id.toolbar)
setSupportActionBar(toolbar)
/* Es wird keine Seitennavigation benutzt. Daher dauerhaft deaktiviert. */
val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout)
drawerLayout.setDrawerLockMode(LOCK_MODE_LOCKED_CLOSED)
val navView: NavigationView = findViewById(R.id.nav_view)
val navController = findNavController(R.id.nav_host_fragment)
navView.setupWithNavController(navController)
}
/**
* Diese Methode muss überschrieben werden, wenn ein Menü angezeigt werden
* soll. Die App benutzt dieses um ein Beenden-Menü anzubieten.
*/
override fun onCreateOptionsMenu(menu: Menu): Boolean {
super.onCreateOptionsMenu(menu)
menuInflater.inflate(R.menu.menu, menu)
return true
}
/**
* Wurde in der Menüleiste eine Option gewählt, wird diese Methode
* aufgerufen.
*/
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.app_beenden)
finish()
return super.onOptionsItemSelected(item)
}
}
| app/src/main/java/de/stefan_oltmann/kaesekaestchen/ui/activities/MainActivity.kt | 1646277456 |
package fr.smarquis.fcm.viewmodel
import android.app.Application
import android.os.Build.MANUFACTURER
import android.os.Build.MODEL
import androidx.lifecycle.LiveData
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ServerValue
import com.google.firebase.database.ValueEventListener
import fr.smarquis.fcm.BuildConfig
import fr.smarquis.fcm.data.model.Presence
import fr.smarquis.fcm.data.model.Presence.*
import fr.smarquis.fcm.data.model.Token
import fr.smarquis.fcm.usecase.GetTokenUseCase
import fr.smarquis.fcm.utils.uuid
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
class PresenceLiveData(
application: Application,
database: FirebaseDatabase,
getTokenUseCase: GetTokenUseCase,
scope: CoroutineScope,
) : LiveData<Presence>(Offline), ValueEventListener, CoroutineScope by scope {
private var token: Token? = null
private val presenceRef: DatabaseReference = database.getReference(".info/connected")
private val connectionRef: DatabaseReference = database.getReference("devices/${uuid(application)}").apply {
onDisconnect().removeValue()
}
init {
launch {
getTokenUseCase().collectLatest {
token = it
updateMetadata()
}
}
}
override fun onActive() {
presenceRef.addValueEventListener(this)
DatabaseReference.goOnline()
updateMetadata()
}
override fun onInactive() {
clearMetadata()
DatabaseReference.goOffline()
presenceRef.removeEventListener(this)
value = Offline
}
override fun onCancelled(error: DatabaseError) {
value = Error(error)
}
override fun onDataChange(snapshot: DataSnapshot) {
value = when (snapshot.getValue(Boolean::class.java)) {
true -> Online
false, null -> Offline
}
updateMetadata()
}
private fun updateMetadata() = connectionRef.setValue(metadata(token))
private fun clearMetadata() = connectionRef.removeValue()
private fun metadata(token: Token?) = mapOf(
"name" to if (MODEL.lowercase().startsWith(MANUFACTURER.lowercase())) MODEL else MANUFACTURER.lowercase() + " " + MODEL,
"token" to when (token) {
is Token.Success -> token.value
Token.Loading, is Token.Failure, null -> null
},
"version" to BuildConfig.VERSION_CODE,
"timestamp" to ServerValue.TIMESTAMP
)
} | app/src/main/java/fr/smarquis/fcm/viewmodel/PresenceLiveData.kt | 1661043165 |
/*
* Copyright @ 2021 - present 8x8, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.rtp.rtp.header_extensions
import org.jitsi.rtp.rtp.RtpPacket
import org.jitsi.rtp.rtp.header_extensions.HeaderExtensionHelpers.Companion.getDataLengthBytes
import java.nio.charset.StandardCharsets
/**
* https://datatracker.ietf.org/doc/html/rfc7941#section-4.1.1
* Note: this is only the One-Byte Format, because we don't support Two-Byte yet.
* 0 1 2 3
* 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | ID | len | SDES item text value ... |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
class SdesHeaderExtension {
companion object {
const val DATA_OFFSET = 1
fun getTextValue(ext: RtpPacket.HeaderExtension): String =
getTextValue(ext.currExtBuffer, ext.currExtOffset)
fun setTextValue(ext: RtpPacket.HeaderExtension, sdesValue: String) =
setTextValue(ext.currExtBuffer, ext.currExtOffset, sdesValue)
private fun getTextValue(buf: ByteArray, offset: Int): String {
val dataLength = getDataLengthBytes(buf, offset)
/* RFC 7941 says the value in RTP is UTF-8. But we use this for MID and RID values
* which are define for SDP in RFC 5888 and RFC 4566 as ASCII only. Thus we don't
* support UTF-8 to keep things simpler. */
return String(buf, offset + SdesHeaderExtension.DATA_OFFSET, dataLength, StandardCharsets.US_ASCII)
}
private fun setTextValue(buf: ByteArray, offset: Int, sdesValue: String) {
val dataLength = getDataLengthBytes(buf, offset)
assert(dataLength == sdesValue.length) { "buffer size doesn't match SDES value length" }
System.arraycopy(
sdesValue.toByteArray(StandardCharsets.US_ASCII), 0, buf,
offset + SdesHeaderExtension.DATA_OFFSET, sdesValue.length
)
}
}
}
| rtp/src/main/kotlin/org/jitsi/rtp/rtp/header_extensions/SdesHeaderExtension.kt | 48668973 |
package net.pterodactylus.sone.core
import net.pterodactylus.sone.core.FreenetInterface.InsertToken
import net.pterodactylus.sone.core.FreenetInterface.InsertTokenSupplier
import net.pterodactylus.sone.data.TemporaryImage
import net.pterodactylus.sone.data.impl.*
import net.pterodactylus.sone.test.getInstance
import net.pterodactylus.sone.test.mock
import net.pterodactylus.sone.test.whenever
import net.pterodactylus.sone.web.baseInjector
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.notNullValue
import org.junit.Test
import org.mockito.ArgumentMatchers.any
import org.mockito.ArgumentMatchers.eq
import org.mockito.Mockito.doThrow
import org.mockito.Mockito.never
import org.mockito.Mockito.verify
/**
* Unit test for [ImageInserter].
*/
class ImageInserterTest {
private val temporaryImage = mock<TemporaryImage>().apply { whenever(id).thenReturn("image-id") }
private val image = ImageImpl("image-id")
private val freenetInterface = mock<FreenetInterface>()
private val insertToken = mock<InsertToken>()
private val insertTokenSupplier: InsertTokenSupplier = mock<InsertTokenSupplier>().apply { whenever(apply(any())).thenReturn(insertToken) }
private val imageInserter = ImageInserter(freenetInterface, insertTokenSupplier)
@Test
fun `inserter inserts image`() {
imageInserter.insertImage(temporaryImage, image)
verify(freenetInterface).insertImage(eq(temporaryImage), eq(image), any(InsertToken::class.java))
}
@Test
fun `exception when inserting image is ignored`() {
doThrow(SoneException::class.java).whenever(freenetInterface).insertImage(eq(temporaryImage), eq(image), any(InsertToken::class.java))
imageInserter.insertImage(temporaryImage, image)
verify(freenetInterface).insertImage(eq(temporaryImage), eq(image), any(InsertToken::class.java))
}
@Test
fun `cancelling image insert that is not running does nothing`() {
imageInserter.cancelImageInsert(image)
verify(insertToken, never()).cancel()
}
@Test
fun `cancelling image cancels the insert token`() {
imageInserter.insertImage(temporaryImage, image)
imageInserter.cancelImageInsert(image)
verify(insertToken).cancel()
}
@Test
fun `image inserter can be created by dependency injection`() {
assertThat(baseInjector.getInstance<ImageInserter>(), notNullValue())
}
}
| src/test/kotlin/net/pterodactylus/sone/core/ImageInserterTest.kt | 3523329033 |
package glass.phil.auto.moshi
import com.google.auto.common.MoreElements.getPackage
import com.google.auto.common.MoreElements.isType
import com.google.auto.common.Visibility
import javax.lang.model.element.Element
import javax.lang.model.element.Modifier.STATIC
val Element.packageName get() = getPackage(this).qualifiedName.toString()
fun Element.hasAnnotation(simpleName: String) = annotationMirrors
.map { it.annotationType.asElement().simpleName }.any { it.contentEquals(simpleName) }
fun Element.isVisibleTo(other: Element) = getPackage(this) == getPackage(other) ||
Visibility.effectiveVisibilityOfElement(this) == Visibility.PUBLIC
fun Element.isEffectivelyStatic(): Boolean {
if (enclosingElement == null || !isType(enclosingElement)) {
return true
}
return modifiers.contains(STATIC) && enclosingElement.isEffectivelyStatic()
}
fun Element.generatedName(name: String = simpleName.toString()): String {
if (enclosingElement == null || !isType(enclosingElement)) {
return name
}
return enclosingElement.generatedName("${enclosingElement.simpleName}_$name")
}
| processor/src/main/kotlin/glass/phil/auto/moshi/Elements.kt | 4276716833 |
package com.github.giacomoparisi.droidbox.recycler
import androidx.databinding.ViewDataBinding
/**
* Created by Giacomo Parisi on 10/04/17.
* https://github.com/giacomoParisi
*/
/**
*
* Factory class used to create a DroidViewHolder for a specifc item
* Every DroidItem need this
*/
interface ViewHolderFactory<in B : ViewDataBinding, D: DroidItem> {
/**
*
* Create a DroidViewHolder instance for the specific item ViewDataBinding
*
* @param binding The ViewDataBinding object of the DroidItem
*/
fun newInstance(binding: B): DroidViewHolder<D>
}
| droidbox/src/main/java/com/github/giacomoparisi/droidbox/recycler/ViewHolderFactory.kt | 2852660056 |
package org.jlleitschuh.gradle.ktlint.android
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](https://d.android.com/tools/testing).
*/
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getInstrumentation().targetContext
assertEquals("org.jlleitschuh.gradle.ktlint.android", appContext.packageName)
}
}
| samples/android-app/src/androidTest/java/org/jlleitschuh/gradle/ktlint/android/ExampleInstrumentedTest.kt | 2847917584 |
/*
* Copyright 2019 Jacques Supcik
*
* 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 ch.supcik.tpf873
import android.os.Bundle
import io.flutter.app.FlutterActivity
import io.flutter.plugins.GeneratedPluginRegistrant
class MainActivity: FlutterActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
GeneratedPluginRegistrant.registerWith(this)
}
}
| android/app/src/main/kotlin/ch/supcik/tpf873/MainActivity.kt | 3186553260 |
package org.meganekkovr.xml
import android.content.Context
import org.meganekkovr.Entity
/**
* Define `opacity` attribute.
*/
internal class OpacityHandler : XmlAttributeParser.XmlAttributeHandler {
override val attributeName = "opacity"
override fun parse(entity: Entity, rawValue: String, context: Context) {
val opacity = rawValue.toFloatOrNull() ?: return
entity.opacity = opacity
}
}
| library/src/main/java/org/meganekkovr/xml/OpacityHandler.kt | 2050861270 |
package io.particle.android.sdk.tinker
import io.particle.android.sdk.cloud.ParticleDevice
import io.particle.android.sdk.tinker.DeviceUiState.FLASHING
import io.particle.android.sdk.tinker.DeviceUiState.OFFLINE
import io.particle.android.sdk.tinker.DeviceUiState.ONLINE_NOT_USING_TINKER
import io.particle.android.sdk.tinker.DeviceUiState.ONLINE_USING_TINKER
import io.particle.sdk.app.R.id
enum class DeviceUiState(val contentViewId: Int) {
ONLINE_USING_TINKER(id.tinker_content_view),
ONLINE_NOT_USING_TINKER(id.flash_tinker_frame),
OFFLINE(id.device_offline_text),
FLASHING(id.flashing_progress_spinner);
}
val ParticleDevice.uiState: DeviceUiState
get() {
return when {
!this.isConnected -> OFFLINE
this.isFlashing -> FLASHING
this.isRunningTinker -> ONLINE_USING_TINKER
else -> ONLINE_NOT_USING_TINKER
}
}
| app/src/main/java/io/particle/android/sdk/tinker/DeviceUiState.kt | 3506602414 |
package com.waz.zclient.storage.userdatabase.clients
import com.waz.zclient.storage.db.users.migration.USER_DATABASE_MIGRATION_127_TO_128
import com.waz.zclient.storage.userdatabase.UserDatabaseMigrationTest
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import org.junit.Assert.assertEquals
import org.junit.Test
@ExperimentalCoroutinesApi
class ClientsTable127to128MigrationTest : UserDatabaseMigrationTest(127, 128) {
@Test
fun givenClientIntoClientsTableVersion127_whenMigratedToVersion128_thenAssertDataIsStillIntact() {
val id = "testId"
val data = "testData"
ClientsTableTestHelper.insertClient(
id = id,
data = data,
openHelper = testOpenHelper
)
validateMigration(USER_DATABASE_MIGRATION_127_TO_128)
runBlocking {
with(allClients()[0]) {
assertEquals(this.id, id)
assertEquals(this.data, data)
}
}
}
private suspend fun allClients() =
getDatabase().userClientDao().allClients()
}
| storage/src/androidTest/kotlin/com/waz/zclient/storage/userdatabase/clients/ClientsTable127to128MigrationTest.kt | 4088970247 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.actions
import com.intellij.execution.ExecutionException
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import org.rust.cargo.project.settings.toolchain
import org.rust.cargo.toolchain.RustToolchain
import org.rust.ide.notifications.showBalloon
import org.rust.lang.core.psi.isRustFile
class RustfmtFileAction : DumbAwareAction() {
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabled = getContext(e) != null
}
override fun actionPerformed(e: AnActionEvent) {
val (project, toolchain, file) = getContext(e) ?: return
val cargo = toolchain.rawCargo()
try {
cargo.reformatFile(project, file)
} catch (e: ExecutionException) {
val message = e.message ?: ""
// #1131 - Check if we get a `no such subcommand: fmt` and let the user know to install fmt
if ("no such subcommand: fmt" in message) {
project.showBalloon("Install rustfmt: https://github.com/rust-lang-nursery/rustfmt", NotificationType.ERROR)
} else {
project.showBalloon(message, NotificationType.ERROR)
}
}
}
private fun getContext(e: AnActionEvent): Triple<Project, RustToolchain, VirtualFile>? {
val project = e.project ?: return null
val toolchain = project.toolchain ?: return null
val file = e.getData(CommonDataKeys.VIRTUAL_FILE) ?: return null
if (!(file.isInLocalFileSystem && file.isRustFile)) return null
return Triple(project, toolchain, file)
}
}
| src/main/kotlin/org/rust/ide/actions/RustfmtFileAction.kt | 782154434 |
package sklegg.game
/**
* Created by scott on 12/23/16.
* Holds configuration options for current game
*/
class GameConfig {
/* TODO: read from game.properties */
var turnsPerGame: Int = 1000
var numSectors: Int = 100
var initialCredits: Int = 50000
var initialFighters: Int = 1000
var initialHolds: Int = 50
} | src/main/kotlin/sklegg/game/GameConfig.kt | 638353179 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.composables
import app.cash.paparazzi.HtmlReportWriter
import app.cash.paparazzi.SnapshotHandler
import app.cash.paparazzi.SnapshotVerifier
private val isVerifying: Boolean =
System.getProperty("paparazzi.test.verify")?.toBoolean() == true
internal fun determineHandler(maxPercentDifference: Double): SnapshotHandler {
return if (isVerifying) {
SnapshotVerifier(maxPercentDifference)
} else {
HtmlReportWriter()
}
}
| composables/src/test/kotlin/com/google/android/horologist/composables/DetermineHandler.kt | 3571299014 |
/*
* Copyright (C) 2020 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.common.util
import android.app.Activity
import android.content.Context
import com.android.billingclient.api.AcknowledgePurchaseParams
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClientStateListener
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.BillingResult
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.PurchasesUpdatedListener
import com.android.billingclient.api.SkuDetails
import com.android.billingclient.api.SkuDetailsParams
import com.android.billingclient.api.acknowledgePurchase
import com.android.billingclient.api.queryPurchaseHistory
import com.android.billingclient.api.querySkuDetails
import com.moez.QKSMS.manager.AnalyticsManager
import com.moez.QKSMS.manager.BillingManager
import io.reactivex.Observable
import io.reactivex.subjects.BehaviorSubject
import io.reactivex.subjects.Subject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class BillingManagerImpl @Inject constructor(
context: Context,
private val analyticsManager: AnalyticsManager
) : BillingManager, BillingClientStateListener, PurchasesUpdatedListener {
private val productsSubject: Subject<List<SkuDetails>> = BehaviorSubject.create()
override val products: Observable<List<BillingManager.Product>> = productsSubject
.map { skuDetailsList ->
skuDetailsList.map { skuDetails ->
BillingManager.Product(skuDetails.sku, skuDetails.price, skuDetails.priceCurrencyCode)
}
}
private val purchaseListSubject = BehaviorSubject.create<List<Purchase>>()
override val upgradeStatus: Observable<Boolean> = purchaseListSubject
.map { purchases ->
purchases
.filter { it.purchaseState == Purchase.PurchaseState.PURCHASED }
.any { it.sku in skus }
}
.distinctUntilChanged()
.doOnNext { upgraded -> analyticsManager.setUserProperty("Upgraded", upgraded) }
private val skus = listOf(BillingManager.SKU_PLUS, BillingManager.SKU_PLUS_DONATE)
private val billingClient: BillingClient = BillingClient.newBuilder(context)
.setListener(this)
.enablePendingPurchases()
.build()
private val billingClientState = MutableSharedFlow<Int>(
replay = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
init {
billingClientState.tryEmit(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
}
override suspend fun checkForPurchases() = executeServiceRequest {
// Load the cached data
queryPurchases()
// On a fresh device, the purchase might not be cached, and so we'll need to force a refresh
billingClient.queryPurchaseHistory(BillingClient.SkuType.INAPP)
queryPurchases()
}
override suspend fun queryProducts() = executeServiceRequest {
val params = SkuDetailsParams.newBuilder()
.setSkusList(skus)
.setType(BillingClient.SkuType.INAPP)
val (billingResult, skuDetailsList) = billingClient.querySkuDetails(params.build())
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
productsSubject.onNext(skuDetailsList.orEmpty())
}
}
override suspend fun initiatePurchaseFlow(activity: Activity, sku: String) = executeServiceRequest {
val skuDetails = withContext(Dispatchers.IO) {
val params = SkuDetailsParams.newBuilder()
.setType(BillingClient.SkuType.INAPP)
.setSkusList(listOf(sku))
.build()
billingClient.querySkuDetails(params).skuDetailsList?.firstOrNull()!!
}
val params = BillingFlowParams.newBuilder().setSkuDetails(skuDetails)
billingClient.launchBillingFlow(activity, params.build())
}
override fun onPurchasesUpdated(result: BillingResult, purchases: MutableList<Purchase>?) {
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
GlobalScope.launch(Dispatchers.IO) {
handlePurchases(purchases.orEmpty())
}
}
}
private suspend fun queryPurchases() {
val result = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
if (result.responseCode == BillingClient.BillingResponseCode.OK) {
handlePurchases(result.purchasesList.orEmpty())
}
}
private suspend fun handlePurchases(purchases: List<Purchase>) = executeServiceRequest {
purchases.forEach { purchase ->
if (!purchase.isAcknowledged) {
val params = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.purchaseToken)
.build()
Timber.i("Acknowledging purchase ${purchase.orderId}")
val result = billingClient.acknowledgePurchase(params)
Timber.i("Acknowledgement result: ${result.responseCode}, ${result.debugMessage}")
}
}
purchaseListSubject.onNext(purchases)
}
private suspend fun executeServiceRequest(runnable: suspend () -> Unit) {
if (billingClientState.first() != BillingClient.BillingResponseCode.OK) {
Timber.i("Starting billing service")
billingClient.startConnection(this)
}
billingClientState.first { state -> state == BillingClient.BillingResponseCode.OK }
runnable()
}
override fun onBillingSetupFinished(result: BillingResult) {
Timber.i("Billing response: ${result.responseCode}")
billingClientState.tryEmit(result.responseCode)
}
override fun onBillingServiceDisconnected() {
Timber.i("Billing service disconnected")
billingClientState.tryEmit(BillingClient.BillingResponseCode.SERVICE_DISCONNECTED)
}
}
| presentation/src/withAnalytics/java/com/moez/QKSMS/common/util/BillingManagerImpl.kt | 1446145811 |
package com.s13g.aoc.aoc2018
class AocVm(private val ipIdx: Int, private val program: List<Instruction>) {
private var ip = 0
private val reg = intArrayOf(0, 0, 0, 0, 0, 0)
private val ops = createOperations()
fun runUntilHalt() {
while (true) {
if (!next()) break
}
}
fun runUntilIp(ipHalt: Int) {
do {
if (!next()) break
} while (ip != ipHalt)
}
/** Returns false, if the program execution halted */
private fun next(): Boolean {
if (program.size <= ip) return false
val instr = program[ip]
// val preDbgStr = "ip=$ip [${reg.joinToString(", ")}] $instr"
reg[ipIdx] = ip
ops[instr.op]!!(instr.params, reg)
ip = reg[ipIdx]
ip++
// println("$preDbgStr [${reg.joinToString(", ")}]")
return true
}
fun getReg(i: Int) = reg[i]
}
fun parseInstructions(program: List<String>): List<Instruction> {
val result = arrayListOf<Instruction>()
for (line in program) {
if (line.startsWith("#")) continue
val split = line.split(" ")
assert(split.size == 4) { println("Invalid instruction: '$line'") }
result.add(Instruction(split[0],
Params(split[1].toInt(), split[2].toInt(), split[3].toInt())))
}
return result
}
data class Instruction(val op: String, val params: Params) {
override fun toString() = "$op $params"
}
data class Params(val a: Int, val b: Int, val c: Int) {
override fun toString() = "$a $b $c"
}
typealias Operation = (Params, IntArray) -> Unit
private fun createOperations(): HashMap<String, Operation> {
return hashMapOf(
Pair("addr", ::addr),
Pair("addi", ::addi),
Pair("mulr", ::mulr),
Pair("muli", ::muli),
Pair("banr", ::banr),
Pair("bani", ::bani),
Pair("borr", ::borr),
Pair("bori", ::bori),
Pair("setr", ::setr),
Pair("seti", ::seti),
Pair("gtir", ::gtir),
Pair("gtri", ::gtri),
Pair("gtrr", ::gtrr),
Pair("eqir", ::eqir),
Pair("eqri", ::eqri),
Pair("eqrr", ::eqrr))
}
private fun addr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] + reg[param.b]
}
private fun addi(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] + param.b
}
private fun mulr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] * reg[param.b]
}
private fun muli(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] * param.b
}
private fun banr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] and reg[param.b]
}
private fun bani(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] and param.b
}
private fun borr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] or reg[param.b]
}
private fun bori(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a] or param.b
}
private fun setr(param: Params, reg: IntArray) {
reg[param.c] = reg[param.a]
}
private fun seti(param: Params, reg: IntArray) {
reg[param.c] = param.a
}
private fun gtir(param: Params, reg: IntArray) {
reg[param.c] = if (param.a > reg[param.b]) 1 else 0
}
private fun gtri(param: Params, reg: IntArray) {
reg[param.c] = if (reg[param.a] > param.b) 1 else 0
}
private fun gtrr(param: Params, reg: IntArray) {
reg[param.c] = if (reg[param.a] > reg[param.b]) 1 else 0
}
private fun eqir(param: Params, reg: IntArray) {
reg[param.c] = if (param.a == reg[param.b]) 1 else 0
}
private fun eqri(param: Params, reg: IntArray) {
reg[param.c] = if (reg[param.a] == param.b) 1 else 0
}
private fun eqrr(param: Params, reg: IntArray) {
reg[param.c] = if (reg[param.a] == reg[param.b]) 1 else 0
}
/** A way to understand the program better. */
class Decompiler(val ipIndex: Int) {
fun decompileProgram(program: List<Instruction>) {
for ((n, instr) in program.withIndex()) {
print("${n.toString().padStart(2, '0')} ")
when (instr.op) {
"addr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} + ${reg(instr.params.b)}")
}
"addi" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} + ${instr.params.b}")
}
"mulr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} * ${reg(instr.params.b)}")
}
"muli" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} * ${instr.params.b}")
}
"banr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} & ${reg(instr.params.b)}")
}
"bani" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} & ${instr.params.b}")
}
"borr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} | ${reg(instr.params.b)}")
}
"bori" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)} | ${instr.params.b}")
}
"setr" -> {
println("${reg(instr.params.c)} = ${reg(instr.params.a)}")
}
"seti" -> {
println("${reg(instr.params.c)} = ${instr.params.a}")
}
"gtir" -> {
println("${reg(instr.params.c)} = boolToInt(${instr.params.a} > ${reg(instr.params.b)})")
}
"gtri" -> {
println("${reg(instr.params.c)} = boolToInt(${reg(instr.params.a)} > ${instr.params.b})")
}
"gtrr" -> {
println("${reg(instr.params.c)} = boolToInt(${reg(instr.params.a)} > ${reg(instr.params.b)})")
}
"eqir" -> {
println("${reg(instr.params.c)} = boolToInt(${instr.params.a} == ${reg(instr.params.b)})")
}
"eqri" -> {
println("${reg(instr.params.c)} = boolToInt(${reg(instr.params.a)} == ${instr.params.b})")
}
"eqrr" -> {
println("${reg(instr.params.c)} = boolToInt(${reg(instr.params.a)} == ${reg(instr.params.b)})")
}
else -> {
println("[MISSING: '${instr.op}']")
}
}
}
}
private fun reg(reg: Int) = if (reg == ipIndex) "ip" else "reg[$reg]"
}
| kotlin/src/com/s13g/aoc/aoc2018/AocVm.kt | 986374636 |
package org.seasar.doma.it.criteria
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.seasar.doma.it.IntegrationTestEnvironment
import org.seasar.doma.jdbc.Config
import org.seasar.doma.jdbc.SqlLogType
import org.seasar.doma.kotlin.jdbc.criteria.KNativeSql
@ExtendWith(IntegrationTestEnvironment::class)
class KNativeSqlInsertTest(config: Config) {
private val nativeSql = KNativeSql(config)
@Test
fun settings() {
val d = Department_()
val count = nativeSql
.insert(
d
) {
comment = "insert department"
queryTimeout = 1000
sqlLogType = SqlLogType.RAW
batchSize = 20
}
.values {
value(d.departmentId, 99)
value(d.departmentNo, 99)
value(d.departmentName, "aaa")
value(d.location, "bbb")
value(d.version, 1)
}
.execute()
assertEquals(1, count)
}
@Test
fun insert() {
val d = Department_()
val count = nativeSql
.insert(d)
.values {
value(d.departmentId, 99)
value(d.departmentNo, 99)
value(d.departmentName, "aaa")
value(d.location, "bbb")
value(d.version, 1)
}
.execute()
assertEquals(1, count)
}
@Test
fun insert_select_entity() {
val da = DepartmentArchive_()
val d = Department_()
val count = nativeSql
.insert(da)
.select { from(d).where { `in`(d.departmentId, listOf(1, 2)) } }
.execute()
assertEquals(2, count)
}
@Test
fun insert_select_properties() {
val da = DepartmentArchive_()
val d = Department_()
val count = nativeSql
.insert(da)
.select {
from(d).where { `in`(d.departmentId, listOf(1, 2)) }.select(
d.departmentId,
d.departmentNo,
d.departmentName,
d.location,
d.version
)
}
.execute()
assertEquals(2, count)
}
@Test
fun insert_select_using_same_entityMetamodel() {
val da = Department_("DEPARTMENT_ARCHIVE")
val d = Department_()
val count = nativeSql.insert(da).select { from(d) }.execute()
assertEquals(4, count)
}
}
| integration-test-kotlin/src/test/kotlin/org/seasar/doma/it/criteria/KNativeSqlInsertTest.kt | 3298462985 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.base.ui.components
import androidx.annotation.StringRes
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.heading
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import com.google.android.horologist.base.ui.ExperimentalHorologistBaseUiApi
/**
* An alternative function to [Title] that allows a string resource id to be passed as text.
*/
@ExperimentalHorologistBaseUiApi
@Composable
public fun Title(
@StringRes textId: Int,
modifier: Modifier = Modifier
) {
Title(
text = stringResource(id = textId),
modifier = modifier
)
}
/**
* This composable fulfils the redlines of the following components:
* - Primary title;
*/
@ExperimentalHorologistBaseUiApi
@Composable
public fun Title(
text: String,
modifier: Modifier = Modifier
) {
Text(
text = text,
modifier = modifier.semantics { heading() },
textAlign = TextAlign.Center,
overflow = TextOverflow.Ellipsis,
maxLines = 3,
style = MaterialTheme.typography.title3
)
}
| base-ui/src/main/java/com/google/android/horologist/base/ui/components/Title.kt | 2784407140 |
package tokyo.tommy_kw.weather.model.entity.request
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
import java.util.*
/**
* Created by tommy on 16/01/13.
*/
data class Flags(
@SerializedName("sources") @Expose val sources:List<String>,
@SerializedName("isd-stations") @Expose val isdStations:List<String>,
@SerializedName("madis-stations") @Expose val madisStations:List<String>,
@SerializedName("lamp-stations") @Expose val lampStations:List<String>,
@SerializedName("darksky-stations") @Expose val darkskyStations:List<String>,
@SerializedName("units") @Expose val units: String
)
| app/src/main/java/tokyo/tommy_kw/weather/model/entity/request/Flags.kt | 3330498474 |
/*
* MIT License
*
* Copyright (c) 2019 emufog contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package emufog.graph
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertFalse
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Assertions.assertNull
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
internal class EdgeTest {
private val defaultAS = AS(1)
private val defaultSource = defaultAS.createBackboneNode(2)
private val defaultDestination = defaultAS.createEdgeNode(3)
private val defaultEdge = Edge(4, defaultSource, defaultDestination, 10F, 1000F)
@Test
fun `test the constructor fields`() {
assertEquals(defaultSource, defaultEdge.source)
assertEquals(defaultDestination, defaultDestination)
assertEquals(4, defaultEdge.id)
assertEquals(10F, defaultEdge.latency)
assertEquals(1000F, defaultEdge.bandwidth)
}
@Test
fun `negative latency should fail`() {
assertThrows<IllegalArgumentException> {
Edge(0, defaultSource, defaultDestination, -1F, 10F)
}
}
@Test
fun `negative bandwidth should fail`() {
assertThrows<IllegalArgumentException> {
Edge(0, defaultSource, defaultDestination, 10F, -1F)
}
}
@Test
fun `hashCode should return the id`() {
assertEquals(4, defaultEdge.hashCode())
}
@Test
fun `toString should return the expected format`() {
assertEquals("Edge: 4", defaultEdge.toString())
}
@Test
fun `equals with different edge with same id should return true`() {
val node = AS(4).createBackboneNode(42)
val edge = Edge(4, node, defaultDestination, 1F, 1F)
assertEquals(edge, defaultEdge)
assertFalse(edge === defaultEdge)
}
@Test
fun `equals with different edge with different id should return false`() {
val node = AS(4).createBackboneNode(42)
val edge = Edge(1024, node, defaultDestination, 1F, 1F)
assertNotEquals(edge, defaultEdge)
assertFalse(edge === defaultEdge)
}
@Test
fun `equals with same object should return true`() {
assertEquals(defaultEdge, defaultEdge)
}
@Test
fun `equals with null should return false`() {
assertNotEquals(defaultEdge, null)
}
@Test
fun `isCrossASEdge should return true for different AS`() {
val node = AS(4).createBackboneNode(42)
val edge = Edge(1024, node, defaultDestination, 1F, 1F)
assertTrue(edge.isCrossASEdge())
}
@Test
fun `isCrossASEdge should return false for same AS`() {
assertFalse(defaultEdge.isCrossASEdge())
}
@Test
fun `getDestinationForSource should return the opposing end`() {
assertEquals(defaultSource, defaultEdge.getDestinationForSource(defaultDestination))
assertEquals(defaultDestination, defaultEdge.getDestinationForSource(defaultSource))
}
@Test
fun `getDestinationForSource should return null if node is not part of edge`() {
val node = AS(4).createBackboneNode(42)
val edge = Edge(1024, node, defaultDestination, 1F, 1F)
assertNull(edge.getDestinationForSource(defaultSource))
}
@Test
fun `source and destination should update if node type changes`() {
val system = AS(4)
val node1 = system.createBackboneNode(41)
val node2 = system.createBackboneNode(42)
val edge = Edge(0, node1, node2, 1F, 1F)
assertEquals(node1, edge.source)
assertEquals(node2, edge.destination)
val node1Replacement = system.replaceByEdgeNode(node1)
val node2Replacement = system.replaceByEdgeNode(node2)
assertEquals(node1Replacement, edge.source)
assertEquals(node2Replacement, edge.destination)
}
@Test
fun ass() {
val system = AS(0)
val node1 = BackboneNode(1, AS(1))
val node2 = system.createBackboneNode(2)
val edge = Edge(0, node1, node2, 1F, 1F)
assertEquals(node2, edge.destination)
assertThrows<IllegalStateException> {
edge.source
}
}
} | src/test/kotlin/emufog/graph/EdgeTest.kt | 4075172804 |
package transformers
import org.jetbrains.dokka.base.testApi.testRunner.BaseAbstractTest
import org.jetbrains.dokka.model.DEnum
import org.jetbrains.dokka.model.WithCompanion
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
class SuppressTagFilterTest : BaseAbstractTest() {
private val configuration = dokkaConfiguration {
sourceSets {
sourceSet {
sourceRoots = listOf("src")
}
}
}
@Test
fun `should filter classes with suppress tag`() {
testInline(
"""
|/src/suppressed/NotSuppressed.kt
|/**
| * sample docs
|*/
|class NotSuppressed
|/src/suppressed/Suppressed.kt
|/**
| * sample docs
| * @suppress
|*/
|class Suppressed
""".trimIndent(), configuration
) {
preMergeDocumentablesTransformationStage = { modules ->
assertEquals(
"NotSuppressed",
modules.flatMap { it.packages }.flatMap { it.classlikes }.singleOrNull()?.name
)
}
}
}
@Test
fun `should filter functions with suppress tag`() {
testInline(
"""
|/src/suppressed/Suppressed.kt
|class Suppressed {
| /**
| * sample docs
| * @suppress
| */
| fun suppressedFun(){ }
|}
""".trimIndent(), configuration
) {
preMergeDocumentablesTransformationStage = { modules ->
assertNull(modules.flatMap { it.packages }.flatMap { it.classlikes }.flatMap { it.functions }
.firstOrNull { it.name == "suppressedFun" })
}
}
}
@Test
fun `should filter top level functions`() {
testInline(
"""
|/src/suppressed/Suppressed.kt
|/**
| * sample docs
| * @suppress
| */
|fun suppressedFun(){ }
|
|/**
| * Sample
| */
|fun notSuppressedFun() { }
""".trimIndent(), configuration
) {
preMergeDocumentablesTransformationStage = { modules ->
assertNull(modules.flatMap { it.packages }.flatMap { it.functions }
.firstOrNull { it.name == "suppressedFun" })
}
}
}
@Test
fun `should filter setter`() {
testInline(
"""
|/src/suppressed/Suppressed.kt
|var property: Int
|/** @suppress */
|private set
""".trimIndent(), configuration
) {
preMergeDocumentablesTransformationStage = { modules ->
val prop = modules.flatMap { it.packages }.flatMap { it.properties }
.find { it.name == "property" }
assertNotNull(prop)
assertNotNull(prop.getter)
assertNull(prop.setter)
}
}
}
@Test
fun `should filter top level type aliases`() {
testInline(
"""
|/src/suppressed/suppressed.kt
|/**
| * sample docs
| * @suppress
| */
|typealias suppressedTypeAlias = String
|
|/**
| * Sample
| */
|typealias notSuppressedTypeAlias = String
""".trimIndent(), configuration
) {
preMergeDocumentablesTransformationStage = { modules ->
assertNull(modules.flatMap { it.packages }.flatMap { it.typealiases }
.firstOrNull { it.name == "suppressedTypeAlias" })
assertNotNull(modules.flatMap { it.packages }.flatMap { it.typealiases }
.firstOrNull { it.name == "notSuppressedTypeAlias" })
}
}
}
@Test
fun `should filter companion object`() {
testInline(
"""
|/src/suppressed/Suppressed.kt
|class Suppressed {
|/**
| * @suppress
| */
|companion object {
| val x = 1
|}
|}
""".trimIndent(), configuration
) {
preMergeDocumentablesTransformationStage = { modules ->
assertNull((modules.flatMap { it.packages }.flatMap { it.classlikes }
.firstOrNull { it.name == "Suppressed" } as? WithCompanion)?.companion)
}
}
}
@Test
fun `should suppress inner classlike`() {
testInline(
"""
|/src/suppressed/Testing.kt
|class Testing {
| /**
| * Sample
| * @suppress
| */
| inner class Suppressed {
| val x = 1
| }
|}
""".trimIndent(), configuration
) {
preMergeDocumentablesTransformationStage = { modules ->
val testingClass = modules.flatMap { it.packages }.flatMap { it.classlikes }.single()
assertNull(testingClass.classlikes.firstOrNull())
}
}
}
@Test
fun `should suppress enum entry`() {
testInline(
"""
|/src/suppressed/Testing.kt
|enum class Testing {
| /**
| * Sample
| * @suppress
| */
| SUPPRESSED,
|
| /**
| * Not suppressed
| */
| NOT_SUPPRESSED
|}
""".trimIndent(), configuration
) {
preMergeDocumentablesTransformationStage = { modules ->
val testingClass = modules.flatMap { it.packages }.flatMap { it.classlikes }.single() as DEnum
assertEquals(listOf("NOT_SUPPRESSED"), testingClass.entries.map { it.name })
}
}
}
} | plugins/base/src/test/kotlin/transformers/SuppressTagFilterTest.kt | 1787848299 |
package com.automation.remarks.kirk.test
import com.automation.remarks.kirk.Kirk.Companion.drive
import com.automation.remarks.kirk.conditions.multiple
import com.automation.remarks.kirk.conditions.options
import com.automation.remarks.kirk.conditions.selected
import com.automation.remarks.kirk.ext.select
import org.testng.annotations.Test
/**
* Created by sergey on 25.07.17.
*/
class SelectListTest : BaseTest() {
val secondPage = "${url}second_page.html"
@Test
fun testCanSelectOptionByText() {
drive {
to(secondPage)
val select = select(".genres")
select.selectOption("Alt folk")
select.shouldHave(selected("Alt folk"))
}
}
@Test
fun testCanSelectOptionByIndex() {
drive {
to(secondPage)
val select = select(".genres")
select.selectOption(3)
select.shouldHave(selected("G-Funk"))
}
}
@Test
fun testSelectIsMultiple() {
drive {
to(secondPage)
select(".genres").shouldBe(multiple)
}
}
@Test
fun testCanGetAllOption() {
drive {
to(secondPage)
select(".genres").shouldHave(options("Alt folk", "Chiptunes", "Electroclash", "G-Funk", "Hair metal"))
}
}
} | kirk-core/src/test/kotlin/com/automation/remarks/kirk/test/SelectListTest.kt | 2807162249 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.language
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.vladsch.md.nav.language.api.MdStripTrailingSpacesDocumentFilter
import com.vladsch.md.nav.language.api.MdStripTrailingSpacesExtension
import com.vladsch.md.nav.psi.element.*
import com.vladsch.md.nav.psi.util.MdTokenSets
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.md.nav.psi.util.MdVisitHandler
import com.vladsch.plugin.util.psi.isIn
import com.vladsch.plugin.util.psi.isTypeIn
// NOTE: this should be the first extension used, the rest can override its handlers
// so it is not registered but hard-coded in com.vladsch.md.nav.language.MdStripTrailingSpacesSmartFilter
class MdStripTrailingSpacesCoreExtension : MdStripTrailingSpacesExtension {
override fun setStripTrailingSpacesFilters(filter: MdStripTrailingSpacesDocumentFilter) {
val keepTrailingLineBreak = filter.codeStyleSettings.isKeepLineBreakSpaces
val keepCodeTrailingSpaces = filter.codeStyleSettings.keepVerbatimTrailingSpaces
val handler = CoreStripSpacedHandler(filter, keepTrailingLineBreak, keepCodeTrailingSpaces)
filter.addHandlers(
MdVisitHandler(MdOrderedListItem::class.java, handler::visit),
MdVisitHandler(MdUnorderedListItem::class.java, handler::visit),
MdVisitHandler(MdTextBlock::class.java, handler::visit),
MdVisitHandler(MdVerbatim::class.java, handler::visit),
MdVisitHandler(MdBlankLine::class.java, handler::visit)
)
}
private class CoreStripSpacedHandler internal constructor(
val filter: MdStripTrailingSpacesDocumentFilter,
val keepTrailingLineBreak: Boolean,
val keepCodeTrailingSpaces: Boolean
) {
fun visit(it: MdVerbatim) {
if (keepCodeTrailingSpaces) {
filter.disableOffsetRange(it.getContentRange(true), false)
filter.visitChildren(it);
}
}
fun visit(it: MdBlankLine) {
if (keepCodeTrailingSpaces) {
filter.disableOffsetRange(it.textRange, true)
}
}
fun visit(it: MdTextBlock) {
if (keepTrailingLineBreak) {
filter.disableOffsetRange(it.node.textRange, true)
}
}
fun visit(it: MdListItem) {
if (keepTrailingLineBreak) {
val firstChild = it.firstChild
var nextChild = firstChild?.nextSibling ?: firstChild
if (nextChild is LeafPsiElement && nextChild.isTypeIn(MdTokenSets.TASK_LIST_ITEM_MARKERS)) {
nextChild = nextChild.nextSibling
}
if (nextChild.isIn(MdTypes.EOL) || nextChild is LeafPsiElement && nextChild.isTypeIn(MdTokenSets.LIST_ITEM_MARKER_SET)) {
filter.disableOffsetRange(it.node.textRange, true)
}
}
filter.visitChildren(it);
}
}
}
| src/main/java/com/vladsch/md/nav/language/MdStripTrailingSpacesCoreExtension.kt | 4042163992 |
/*
* Copyright 2017 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.home
import app.tivi.ContentViewSetter
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@InstallIn(SingletonComponent::class)
@Module
object StandardContentViewModule {
@Provides
fun provideContentViewSetter(): ContentViewSetter = ContentViewSetter { activity, view ->
activity.setContentView(view)
}
}
| app/src/standard/kotlin/app/tivi/home/StandardContentViewModule.kt | 855341931 |
package me.lazmaid.fireredux.view.home
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.ViewGroup
import com.github.kittinunf.reactiveandroid.support.v7.widget.rx_itemsWith
import com.github.kittinunf.reactiveandroid.view.rx_click
import kotlinx.android.synthetic.main.activity_home.*
import me.lazmaid.fireredux.R
import me.lazmaid.fireredux.model.Note
import me.lazmaid.fireredux.navigation.StoreNavigator
import me.lazmaid.fireredux.presentation.HomeViewModelStore
import me.lazmaid.fireredux.presentation.HomeViewModelStore.Action
import me.lazmaid.fireredux.repository.NoteRepositoryImpl
import me.lazmaid.fireredux.view.BaseActivity
import rx.Observable
class HomeActivity : BaseActivity<HomeViewModelStore>() {
override val viewModelStore: HomeViewModelStore by lazy {
HomeViewModelStore(StoreNavigator(this), NoteRepositoryImpl())
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_home)
setSupportActionBar(tbHome)
rvNotes.apply {
layoutManager = LinearLayoutManager(this@HomeActivity)
}
fabCreate.rx_click().subscribe {
viewModelStore.dispatch(Action.CreateNewNoteAction())
}
}
override fun onStart() {
super.onStart()
val stateObservable = viewModelStore.stateChanged.share()
val notesObservable = stateObservable.map { it.items }.bindUntilDestroyed()
rvNotes.rx_itemsWith(notesObservable, onCreateViewHolder = { parent: ViewGroup?, viewType: Int ->
val view = layoutInflater.inflate(R.layout.item_note, parent, false)
HomeNoteItemViewHolder(view)
}, onBindViewHolder = { holder: HomeNoteItemViewHolder, position: Int, item: Note ->
holder.bindView(item)
holder.itemView.rx_click().bindUntilDestroyed().subscribe {
viewModelStore.dispatch(Action.OpenNoteDetailAction(item))
}
})
viewModelStore.dispatch(Action.GetNotesAction())
}
}
| app/src/main/java/me/lazmaid/fireredux/view/home/HomeActivity.kt | 2441246733 |
package io.quarkus.it.panache.reactive.kotlin
enum class Status {
LIVING,
DECEASED
}
| integration-tests/hibernate-reactive-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/reactive/kotlin/Status.kt | 2098656705 |
package pl.geostreaming.rstore.vertx.cl
import io.vertx.core.Vertx
import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.runBlocking
import org.junit.Test
import pl.geostreaming.rstore.core.model.RsCluster
import pl.geostreaming.rstore.core.model.RsClusterDef
import pl.geostreaming.rstore.core.node.ReplTestBase
/**
* Created by lkolek on 13.07.2017.
*/
class TestReplicaVerticle: ReplTestBase() {
@Test
fun test1() {
val REC_SIZE = 1_000_000;
val v = Vertx.vertx();
val cfg = RsClusterDef.Builder()
.withNode(1,"localhost:8000")
.withNode(2,"localhost:8001")
.withReplicationFactor(2)
.build();
val cl = RsCluster(cfg);
val rv1 = ReplicaVerticle("/repl", cl, 1,makeDb(1, false) );
val rv2 = ReplicaVerticle("/repl", cl, 2,makeDb(2, false) );
v.deployVerticle(rv1) { println("rv1 deployed") }
runBlocking {
delay(3000);
// insert some data!
println("----- inserting")
rv1.runOnContext {
(0..1000).forEach { i ->
val x1 = rv1.repl.put(randByteArray(REC_SIZE));
// delay(1)
// val x2 = rv1.repl.put("${i}-aaa-7618237815387153768".toByteArray());
// val x3 = rv1.repl.put("${i}-aaa3-7618237815387153768".toByteArray());
}
v.deployVerticle(rv2) { println("rv2 deployed") }
}
delay(50_000);
}
v.close();
}
} | rstore-vertxcl/src/test/java/pl/geostreaming/rstore/vertx/cl/TestReplicaVerticle.kt | 2042449622 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.update
import com.intellij.ide.plugins.PluginManager
import com.intellij.ide.util.PropertiesComponent
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.PermanentInstallationID
import com.intellij.openapi.application.ex.ApplicationInfoEx
import com.intellij.openapi.components.ApplicationComponent
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.editor.EditorFactory
import com.intellij.openapi.editor.event.EditorFactoryAdapter
import com.intellij.openapi.editor.event.EditorFactoryEvent
import com.intellij.openapi.extensions.PluginId
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.JDOMUtil
import com.intellij.openapi.util.SystemInfo
import com.intellij.util.io.HttpRequests
import org.jdom.JDOMException
import org.rust.lang.core.psi.isRustFile
import java.io.IOException
import java.net.URLEncoder
import java.net.UnknownHostException
import java.util.concurrent.TimeUnit
class UpdateComponent : ApplicationComponent, Disposable {
override fun getComponentName(): String = javaClass.name
override fun initComponent() {
if (!ApplicationManager.getApplication().isUnitTestMode) {
EditorFactory.getInstance().addEditorFactoryListener(EDITOR_LISTENER, this)
}
}
override fun disposeComponent() {
// NOP
}
override fun dispose() = disposeComponent()
object EDITOR_LISTENER : EditorFactoryAdapter() {
override fun editorCreated(event: EditorFactoryEvent) {
val document = event.editor.document
val file = FileDocumentManager.getInstance().getFile(document)
if (file != null && file.isRustFile) {
update()
}
}
}
companion object {
private val LAST_UPDATE: String = "org.rust.LAST_UPDATE"
private val PLUGIN_ID: String = "org.rust.lang"
private val LOG = Logger.getInstance(UpdateComponent::class.java)
fun update() {
val properties = PropertiesComponent.getInstance()
val lastUpdate = properties.getOrInitLong(LAST_UPDATE, 0L)
val shouldUpdate = lastUpdate == 0L || System.currentTimeMillis() - lastUpdate > TimeUnit.DAYS.toMillis(1)
if (shouldUpdate) {
properties.setValue(LAST_UPDATE, System.currentTimeMillis().toString())
val url = updateUrl
ApplicationManager.getApplication().executeOnPooledThread {
try {
HttpRequests.request(url).connect {
try {
JDOMUtil.load(it.reader)
} catch (e: JDOMException) {
LOG.warn(e)
}
LOG.info("updated: $url")
}
} catch (ignored: UnknownHostException) {
// No internet connections, no need to log anything
} catch (e: IOException) {
LOG.warn(e)
}
}
}
}
private val updateUrl: String get() {
val applicationInfo = ApplicationInfoEx.getInstanceEx()
val buildNumber = applicationInfo.build.asString()
val plugin = PluginManager.getPlugin(PluginId.getId(PLUGIN_ID))!!
val pluginId = plugin.pluginId.idString
val os = URLEncoder.encode("${SystemInfo.OS_NAME} ${SystemInfo.OS_VERSION}", Charsets.UTF_8.name())
val uid = PermanentInstallationID.get()
val baseUrl = "https://plugins.jetbrains.com/plugins/list"
return "$baseUrl?pluginId=$pluginId&build=$buildNumber&pluginVersion=${plugin.version}&os=$os&uuid=$uid"
}
}
}
| src/main/kotlin/org/rust/ide/update/UpdateComponent.kt | 1569831375 |
/*
* Copyright (c) 2016-2019 PSPDFKit GmbH. All rights reserved.
*
* THIS SOURCE CODE AND ANY ACCOMPANYING DOCUMENTATION ARE PROTECTED BY INTERNATIONAL COPYRIGHT LAW
* AND MAY NOT BE RESOLD OR REDISTRIBUTED. USAGE IS BOUND TO THE PSPDFKIT LICENSE AGREEMENT.
* UNAUTHORIZED REPRODUCTION OR DISTRIBUTION IS SUBJECT TO CIVIL AND CRIMINAL PENALTIES.
* This notice may not be removed from this file
*/
package com.pspdfkit.labs.quickdemo
import org.junit.Assert.assertEquals
import org.junit.Test
/**
* Example local unit test, which will execute on the development machine (host).
* @see [Testing documentation](http://d.android.com/tools/testing)
*/
class ExampleUnitTest {
@Test
@Throws(Exception::class)
fun addition_isCorrect() {
assertEquals(4, (2 + 2).toLong())
}
} | app/src/test/java/com/pspdfkit/labs/quickdemo/ExampleUnitTest.kt | 2028123146 |
package com.scottmeschke.resume2017.core.experience.repo
import com.scottmeschke.resume2017.core.experience.Position
import com.scottmeschke.resume2017.core.experience.Project
import io.reactivex.Observable
/**
* Created by Scott on 5/12/2017.
*/
interface ExperienceRepository {
fun allPositions(): Observable<List<Position>>
fun allProjects(): Observable<List<Project>>
fun position(id: String): Observable<Position>
fun project(id: String): Observable<Project>
}
| resume2017/app/src/main/java/com/scottmeschke/resume2017/core/experience/repo/ExperienceRepo.kt | 3018670935 |
/******************************************************************************
* Copyright 2016 Edinson E. Padrón Urdaneta
*
* 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.epadronu.balin.core
/* ***************************************************************************/
/* ***************************************************************************/
import com.github.epadronu.balin.config.ConfigurationSetup
import org.openqa.selenium.JavascriptExecutor
import org.openqa.selenium.WebDriver
import org.openqa.selenium.support.ui.ExpectedCondition
import org.openqa.selenium.support.ui.WebDriverWait
/* ***************************************************************************/
/* ***************************************************************************/
internal class BrowserImpl(
override val configurationSetup: ConfigurationSetup,
override val driver: WebDriver = configurationSetup.driverFactory()) : Browser, WebDriver by driver {
override val js = object : JavaScriptExecutor {
override fun execute(vararg args: Any, async: Boolean, script: () -> String): Any? {
if (driver is JavascriptExecutor) {
return when (async) {
false -> driver.executeScript(script(), *args)
else -> driver.executeAsyncScript(script(), *args)
}
}
throw UnsupportedOperationException()
}
}
}
/* ***************************************************************************/
| src/main/kotlin/com/github/epadronu/balin/core/BrowserImpl.kt | 841511902 |
package com.lbbento.pitchupapp.util
import android.media.AudioFormat
import android.media.AudioRecord
class AudioRecorderUtil {
companion object {
val SAMPLE_RATES = intArrayOf(44100)
fun getSampleRate(): Int {
var sampleRate = -1
for (rate in SAMPLE_RATES) {
val bufferSize = AudioRecord.getMinBufferSize(rate, AudioFormat.CHANNEL_IN_STEREO, AudioFormat.ENCODING_PCM_16BIT)
if (bufferSize > 0) {
sampleRate = rate
}
}
return sampleRate
}
}
} | app/src/main/kotlin/com/lbbento/pitchupapp/util/AudioRecorderUtil.kt | 4028263665 |
package me.panpf.sketch.sample.item
import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.ProgressBar
import android.widget.TextView
import me.panpf.adapter.AssemblyItem
import me.panpf.adapter.AssemblyItemFactory
import me.panpf.adapter.ktx.bindView
import me.panpf.sketch.sample.R
import me.panpf.sketch.sample.bean.AppScanning
class AppScanningItemFactory : AssemblyItemFactory<AppScanning>() {
override fun match(o: Any?): Boolean {
return o is AppScanning
}
override fun createAssemblyItem(viewGroup: ViewGroup): AppListHeaderItem {
return AppListHeaderItem(R.layout.list_item_app_scanning, viewGroup)
}
inner class AppListHeaderItem(itemLayoutId: Int, parent: ViewGroup) : AssemblyItem<AppScanning>(itemLayoutId, parent) {
private val textView: TextView by bindView(R.id.text_appScanningItem)
private val progressBar: ProgressBar by bindView(R.id.progress_appScanningItem)
override fun onConfigViews(context: Context) {
}
override fun onSetData(i: Int, scanning: AppScanning?) {
scanning ?: return
if (scanning.running) {
val progress = if (scanning.totalLength > 0) (scanning.completedLength.toFloat() / scanning.totalLength * 100).toInt() else 0
textView.text = String.format("已发现%d个安装包, %d%%", scanning.count, progress)
progressBar.visibility = View.VISIBLE
} else {
textView.text = String.format("共发现%d个安装包,用时%d秒", scanning.count, scanning.time / 1000)
progressBar.visibility = View.GONE
}
}
}
}
| sample/src/main/java/me/panpf/sketch/sample/item/AppScanningItemFactory.kt | 661980510 |
package com.ddiehl.android.htn.listings.inbox
import androidx.fragment.app.FragmentActivity
import com.ddiehl.android.htn.di.ActivityScope
import dagger.Module
import dagger.Provides
@Module
class PrivateMessageActivityModule {
@Provides
@ActivityScope
fun provideFragmentActivity(activity: PrivateMessageActivity): FragmentActivity = activity
}
| app/src/main/java/com/ddiehl/android/htn/listings/inbox/PrivateMessageActivityModule.kt | 3006933367 |
package org.kale.mail
import com.sun.mail.imap.IMAPFolder
import com.sun.mail.imap.IMAPStore
import org.apache.logging.log4j.LogManager
import java.time.Instant
import java.util.*
import javax.mail.*
import javax.mail.internet.MimeMessage
import javax.mail.search.ComparisonTerm
import javax.mail.search.ReceivedDateTerm
/**
*
*/
class StoreWrapper(val account: EmailAccountConfig,
val store: IMAPStore = createStore("imaps"), // default to ssl connection
val dryRun: Boolean = false
) {
//
// Public
//
val expunge = (dryRun == false)
fun scanFolder(folderName: String, callback: MailCallback, startUID: Long = -1, doFirstRead: Boolean = true): Unit {
checkStore()
ImapFolderScanner(this, folderName, callback, startUID, doFirstRead).startScanning()
}
fun getMessages(folderName: String, limit: Int = 0): List<MessageHelper>
{
return getMessages(folderName, { folder ->
val start = if (limit <= 0 || limit >= folder.getMessageCount()) 1 else folder.getMessageCount() - limit + 1
val count = folder.getMessageCount()
folder.getMessages(start, count)
})
}
fun getMessagesAfterUID(folderName: String, start: Long) =
getMessagesByUIDRange(folderName, start + 1)
fun getMessagesByUIDRange(folderName: String, startUID: Long,
endUID: Long = UIDFolder.LASTUID): List<MessageHelper>
{
return getMessages(folderName, {folder ->
if (folder !is IMAPFolder)
throw imapError(folder)
folder.getMessagesByUID(startUID, endUID)
})
}
fun getEmailsBeforeDate(folderName: String, date: Instant) =
getEmailsBeforeDate(folderName, Date.from(date))
fun getEmailsBeforeDate(folderName: String, date: Date): List<MessageHelper> {
val olderThan = ReceivedDateTerm(ComparisonTerm.LT, date)
return getMessages(folderName, { folder ->
fetch(folder.search(olderThan), folder)
})
}
fun getEmailsAfterDate(folderName: String, instant: Instant) =
getEmailsAfterDate(folderName,Date.from(instant))
fun getEmailsAfterDate(folderName: String, date: Date): List<MessageHelper> {
val newerThan = ReceivedDateTerm(ComparisonTerm.GT, date)
return getMessages(folderName, { folder ->
fetch(folder.search(newerThan), folder)
})
}
fun getEmailsByUID(folderName: String, ids: List<Long>): List<MessageHelper> {
return getMessages(folderName, { folder ->
if (folder !is IMAPFolder)
throw imapError(folder)
folder.getMessagesByUID(ids.toLongArray())
})
}
fun moveTo(toFolderName: String, m: MessageHelper) {
if (dryRun) {
logger.info("DRY RUN -- moving message from: ${m.from} subject: ${m.subject} to folder: $toFolderName")
return
}
val fromFolder = getFolder(m.folderName)
val toFolder = getFolder(toFolderName)
try {
if (!toFolder.exists()){
logger.warn("ignoring request to move message to folder that does not exist: $toFolderName")
return
}
val message = getMessageByUID(fromFolder, m.uid)
val newMessage = MimeMessage(message)
newMessage.removeHeader(MoveHeader)
newMessage.addHeader(MoveHeader, toFolderName)
val messageArray = arrayOf(newMessage)
logger.info("moving mail from: ${m.from} subject: ${m.subject} " +
"from folder: ${m.folderName} to folder: $toFolderName")
toFolder.appendMessages(messageArray)
message.setFlag(Flags.Flag.DELETED, true)
} catch (e: Exception){
logger.warn("failed moving message to folder: $toFolderName", e)
} finally {
closeFolder(fromFolder)
closeFolder(toFolder)
}
}
fun delete(permanent: Boolean, m: MessageHelper): Unit {
if (dryRun) {
logger.info("DRY RUN -- deleting message from: ${m.from} subject: ${m.subject}")
return
}
if (permanent)
permanentDelete(m)
else
moveTo(MailUtils.trashFolder(account), m)
}
fun permanentDelete(m: MessageHelper) {
val folder = getFolder(m.folderName)
try {
val message = getMessageByUID(folder,m.uid)
message.setFlag(Flags.Flag.DELETED, true)
} finally {
closeFolder(folder)
}
}
fun getFolders(): List<FolderWrapper> {
checkStore()
return store.getDefaultFolder().list("*").map{f -> FolderWrapper.create(f, this)}
}
fun hasFolder(name: String): Boolean {
return getFolder(name).exists()
}
//
// Internal
//
internal fun getMessageByUID(folder: Folder, uid: Long): MimeMessage {
if (folder !is IMAPFolder)
throw imapError(folder)
return folder.getMessageByUID(uid) as MimeMessage
}
internal fun <T>doWithFolder(folderName: String, lambda: (Folder) -> T): T {
val folder = getFolder(folderName)
try {
return lambda(folder)
} finally {
closeFolder(folder)
}
}
fun getMessages(folderName: String, lambda: (Folder) -> Array<Message>): List<MessageHelper>
{
return doWithFolder(folderName, { folder ->
val messages = lambda(folder)
fetch(messages, folder)
messages.map{MessageHelper.create(it, this)}
})
}
internal fun getFolder(folderName: String): Folder {
checkStore()
val folder = store.getFolder(folderName)
folder.open(getPermission())
return folder
}
internal fun closeFolder(folder: Folder?) {
if (folder != null && folder.isOpen()) {
try {
folder.close(expunge)
} catch (e: Exception) {
logger.info(e)
}
}
}
private fun imapError(folder: Folder): Exception {
return RuntimeException("folder: ${folder.name} for: ${account.user} does not support UID's")
}
private fun fetchMessages(messages: Array<Message>) = messages.map {
MessageHelper.create(it as MimeMessage, this)}
private fun getPermission() = if (dryRun) Folder.READ_ONLY else Folder.READ_WRITE
private fun getEmails(messages: Array<Message>, folder: Folder): List<MessageHelper> {
fetch(messages, folder)
return messages.map { m: Message -> MessageHelper.create(m as MimeMessage, this) }
}
fun checkStore(): Boolean {
if (!store.isConnected) {
logger.info("store connecting to account: ${account.imapHost} user: ${account.user}")
store.connect(account.imapHost, account.user, account.password)
return true
} else {
return false
}
}
companion object {
val logger = LogManager.getLogger(StoreWrapper::class.java.name)
val defaultFetchProfile = createDefaultFetchProfile()
val MoveHeader = "Mailscript-Move"
private fun fetch(messages: Array<Message>, folder: Folder): Array<Message> {
logger.debug("fetching ${messages.count()} email(s) from ${folder.name}")
folder.fetch(messages, defaultFetchProfile)
logger.debug("finishing fetch for ${folder.getName()}")
return messages
}
fun createStore(storeName: String,
session: Session = Session.getDefaultInstance(Properties(), null)): IMAPStore {
return session.getStore(storeName) as IMAPStore
}
fun createDefaultFetchProfile(): FetchProfile {
val fp = FetchProfile()
fp.add(FetchProfile.Item.ENVELOPE)
fp.add(FetchProfile.Item.FLAGS)
fp.add(FetchProfile.Item.SIZE)
fp.add(UIDFolder.FetchProfileItem.UID)
fp.add(IMAPFolder.FetchProfileItem.HEADERS) //load all headers
return fp
}
}
}
| src/main/kotlin/org/kale/mail/StoreWrapper.kt | 4012830050 |
/*
* Copyright (c) 2021 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.testutils
import android.content.Context
import anki.backend.BackendError
import net.ankiweb.rsdroid.Backend
import net.ankiweb.rsdroid.BackendException.BackendDbException.BackendDbLockedException
import net.ankiweb.rsdroid.BackendFactory
import org.mockito.Mockito
/** Test helper:
* causes getCol to emulate an exception caused by having another AnkiDroid instance open on the same collection
*/
class BackendEmulatingOpenConflict(context: Context) : Backend(context) {
@Suppress("UNUSED_PARAMETER")
override fun openCollection(
collectionPath: String,
mediaFolderPath: String,
mediaDbPath: String,
logPath: String,
forceSchema11: Boolean
) {
val error = Mockito.mock(BackendError::class.java)
throw BackendDbLockedException(error)
}
companion object {
fun enable() {
BackendFactory.setOverride() { context, _, _ -> BackendEmulatingOpenConflict(context) }
}
fun disable() {
BackendFactory.setOverride(null)
}
}
}
| AnkiDroid/src/test/java/com/ichi2/testutils/BackendEmulatingOpenConflict.kt | 2746369953 |
package de.westnordost.streetcomplete.data.upload
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import javax.inject.Inject
import javax.inject.Singleton
/** Controls uploading */
@Singleton class UploadController @Inject constructor(
private val context: Context
): UploadProgressSource {
private var uploadServiceIsBound = false
private var uploadService: UploadService.Interface? = null
private val uploadServiceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
uploadService = service as UploadService.Interface
uploadService?.setProgressListener(uploadProgressRelay)
}
override fun onServiceDisconnected(className: ComponentName) {
uploadService = null
}
}
private val uploadProgressRelay = UploadProgressRelay()
/** @return true if an upload is running */
override val isUploadInProgress: Boolean get() =
uploadService?.isUploadInProgress == true
var showNotification: Boolean
get() = uploadService?.showUploadNotification == true
set(value) { uploadService?.showUploadNotification = value }
init {
bindServices()
}
/** Collect and upload all changes made by the user */
fun upload() {
if (uploadService == null) return
context.startService(UploadService.createIntent(context))
}
private fun bindServices() {
uploadServiceIsBound = context.bindService(
Intent(context, UploadService::class.java),
uploadServiceConnection, Context.BIND_AUTO_CREATE
)
}
private fun unbindServices() {
if (uploadServiceIsBound) context.unbindService(uploadServiceConnection)
uploadServiceIsBound = false
}
override fun addUploadProgressListener(listener: UploadProgressListener) {
uploadProgressRelay.addListener(listener)
}
override fun removeUploadProgressListener(listener: UploadProgressListener) {
uploadProgressRelay.removeListener(listener)
}
}
| app/src/main/java/de/westnordost/streetcomplete/data/upload/UploadController.kt | 47847207 |
/*
* Copyright © 2019. Sir Wellington.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tech.sirwellington.alchemy.http
import com.google.gson.JsonElement
import tech.sirwellington.alchemy.annotations.access.Internal
import tech.sirwellington.alchemy.annotations.access.NonInstantiable
import tech.sirwellington.alchemy.arguments.AlchemyAssertion
import tech.sirwellington.alchemy.arguments.Arguments.checkThat
import tech.sirwellington.alchemy.arguments.FailedAssertionException
import tech.sirwellington.alchemy.arguments.assertions.*
/**
* @author SirWellington
*/
@Internal
@NonInstantiable
internal object HttpAssertions
{
@JvmStatic
fun validHttpStatusCode(): AlchemyAssertion<Int>
{
/*
* See https://www.whoishostingthis.com/resources/http-status-codes
*/
return greaterThanOrEqualTo(100).and(lessThanOrEqualTo(600))
}
/*
* TODO: Add check to see if the class structure is that of a POJO.
*/
@JvmStatic
fun <Response> validResponseClass(): AlchemyAssertion<Class<Response>>
{
return AlchemyAssertion { klass ->
checkThat(klass).isA(nonNullReference())
checkThat(klass == Void::class.java)
.usingMessage("Response class cannot be null")
.isA(falseStatement())
}
}
@JvmStatic
fun ready(): AlchemyAssertion<HttpRequest>
{
return AlchemyAssertion { request ->
checkThat(request)
.usingMessage("Request missing")
.isA(nonNullReference())
checkThat(request.method)
.usingMessage("Request missing HTTP Method")
.isA(nonNullReference())
checkThat(request.url)
.usingMessage("Request missing URL")
.isA(nonNullReference())
checkThat(request.url!!.protocol)
.isA(stringBeginningWith("http"))
}
}
@JvmStatic
fun validContentType(): AlchemyAssertion<String>
{
return AlchemyAssertion assertion@ { contentType ->
checkThat(contentType)
.usingMessage("missing Content-Type")
.isA(nonEmptyString())
if (contentType.contains(ContentTypes.APPLICATION_JSON))
{
return@assertion
}
if (contentType.contains(ContentTypes.PLAIN_TEXT))
{
return@assertion
}
throw FailedAssertionException("Not a valid JSON content Type: " + contentType)
}
}
@JvmStatic
fun validRequest(): AlchemyAssertion<HttpRequest>
{
return AlchemyAssertion { request ->
checkThat(request)
.usingMessage("missing HTTP Request")
.isA(nonNullReference())
checkThat(request.url)
.usingMessage("missing request URL")
.isA(nonNullReference())
}
}
@JvmStatic
fun jsonArray(): AlchemyAssertion<JsonElement>
{
return AlchemyAssertion { json ->
checkThat<JsonElement>(json).isA(nonNullReference())
if (!json.isJsonArray)
{
throw FailedAssertionException("Expecting JSON Array, instead: " + json)
}
}
}
@JvmStatic
fun okResponse(): AlchemyAssertion<HttpResponse>
{
return AlchemyAssertion { response ->
checkThat(response).isA(nonNullReference())
if (!response.isOk)
{
throw FailedAssertionException("Http Response not OK. Status Code: " + response.statusCode())
}
}
}
}
| src/main/java/tech/sirwellington/alchemy/http/HttpAssertions.kt | 3517510203 |
package it.sephiroth.android.library.tooltip_demo
import android.graphics.Rect
import android.widget.CheckBox
import androidx.annotation.IdRes
import androidx.core.view.doOnPreDraw
import androidx.test.espresso.Espresso.onData
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.replaceText
import androidx.test.espresso.assertion.ViewAssertions
import androidx.test.espresso.assertion.ViewAssertions.doesNotExist
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.AndroidJUnit4
import androidx.test.uiautomator.UiDevice
import org.hamcrest.Matchers.*
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.util.concurrent.CountDownLatch
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@get:Rule
val activityRule = ActivityTestRule(MainActivity::class.java)
val device = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation())
@Test
fun testTooltipCreated() {
onView(withId(R.id.text_duration)).perform(replaceText("5000"))
onView(withId(R.id.text_fade)).perform(replaceText("100"))
onView(withId(R.id.button1)).perform(click())
Thread.sleep(200)
onView(withId(R.id.tooltip)).check(matches(isDisplayed()))
Thread.sleep(5400)
onView(withId(R.id.tooltip)).check(doesNotExist())
}
@Test
fun test_closeInside() {
onView(withId(R.id.text_duration)).perform(replaceText("0"))
onView(withId(R.id.text_fade)).perform(replaceText("100"))
check(R.id.switch1)
check(R.id.switch2)
uncheck(R.id.switch3)
onView(withId(R.id.spinner_gravities)).perform(click())
onData(allOf(isA(String::class.java), `is`("TOP"))).perform(click())
onView(withId(R.id.spinner_gravities)).check(matches(withSpinnerText(containsString("TOP"))))
Thread.sleep(200)
onView(withId(R.id.button1)).perform(click())
Thread.sleep(200)
onView(withId(R.id.tooltip)).check(matches(isDisplayed()))
val latch = CountDownLatch(1)
val rect = Rect()
val tooltipContent = activityRule.activity.tooltip!!.contentView!!
tooltipContent.doOnPreDraw {
it.getHitRect(rect)
latch.countDown()
}
latch.await()
// click outside
device.click(rect.centerX(), rect.bottom + 10)
Thread.sleep(500)
onView(withId(R.id.tooltip)).check(matches(isDisplayed()))
// click inside the tooltip
onView(withId(R.id.tooltip)).perform(click())
Thread.sleep(500)
onView(withId(R.id.tooltip)).check(doesNotExist())
}
@Test
fun test_closeOutside() {
onView(withId(R.id.text_duration)).perform(replaceText("0"))
onView(withId(R.id.text_fade)).perform(replaceText("100"))
uncheck(R.id.switch1)
check(R.id.switch3)
check(R.id.switch2)
selectSpinnerValue(R.id.spinner_gravities, "TOP")
Thread.sleep(200)
onView(withId(R.id.button1)).perform(click())
Thread.sleep(200)
onView(withId(R.id.tooltip)).check(matches(isDisplayed()))
val tooltipRect = getTooltipRect()
// click inside the tooltip
onView(withId(R.id.tooltip)).perform(click())
Thread.sleep(500)
// check is still displayed
onView(withId(R.id.tooltip)).check(matches(isDisplayed()))
device.click(tooltipRect.centerX(), tooltipRect.bottom + 100)
Thread.sleep(500)
// tooltip removed
onView(withId(R.id.tooltip)).check(doesNotExist())
}
private fun check(@IdRes id: Int) {
if (!activityRule.activity.findViewById<CheckBox>(id).isChecked)
onView(withId(id)).perform(click())
onView(withId(id)).check(ViewAssertions.matches(isChecked()))
}
private fun uncheck(@IdRes id: Int) {
if (activityRule.activity.findViewById<CheckBox>(id).isChecked)
onView(withId(id)).perform(click())
onView(withId(id)).check(ViewAssertions.matches(isNotChecked()))
}
private fun selectSpinnerValue(@IdRes id: Int, value: String) {
onView(withId(id)).perform(click())
onData(allOf(isA(String::class.java), `is`(value))).perform(click())
onView(withId(id)).check(matches(withSpinnerText(containsString(value))))
}
private fun getTooltipRect(): Rect {
val latch = CountDownLatch(1)
val rect = Rect()
val tooltipContent = activityRule.activity.tooltip!!.contentView!!
tooltipContent.doOnPreDraw {
it.getHitRect(rect)
latch.countDown()
}
latch.await()
return rect
}
}
| app/src/androidTest/java/it/sephiroth/android/library/tooltip_demo/MainActivityTest.kt | 730662251 |
package org.wordpress.android.fluxc.release
import org.greenrobot.eventbus.Subscribe
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.CoreMatchers.hasItem
import org.junit.Assert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Ignore
import org.junit.Test
import org.wordpress.android.fluxc.TestUtils
import org.wordpress.android.fluxc.generated.EncryptedLogActionBuilder
import org.wordpress.android.fluxc.release.ReleaseStack_EncryptedLogTest.TestEvents.ENCRYPTED_LOG_UPLOADED_SUCCESSFULLY
import org.wordpress.android.fluxc.release.ReleaseStack_EncryptedLogTest.TestEvents.ENCRYPTED_LOG_UPLOAD_FAILED_WITH_INVALID_UUID
import org.wordpress.android.fluxc.store.EncryptedLogStore
import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded
import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded.EncryptedLogFailedToUpload
import org.wordpress.android.fluxc.store.EncryptedLogStore.OnEncryptedLogUploaded.EncryptedLogUploadedSuccessfully
import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.InvalidRequest
import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogError.TooManyRequests
import org.wordpress.android.fluxc.store.EncryptedLogStore.UploadEncryptedLogPayload
import java.io.File
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import javax.inject.Inject
private const val NUMBER_OF_LOGS_TO_UPLOAD = 2
private const val TEST_UUID_PREFIX = "TEST-UUID-"
private const val INVALID_UUID = "INVALID_UUID" // Underscore is not allowed
@Ignore("Temporarily disabled: Tests are only failing in CircleCI and will be debugged next week")
class ReleaseStack_EncryptedLogTest : ReleaseStack_Base() {
@Inject lateinit var encryptedLogStore: EncryptedLogStore
private var nextEvent: TestEvents? = null
private enum class TestEvents {
NONE,
ENCRYPTED_LOG_UPLOADED_SUCCESSFULLY,
ENCRYPTED_LOG_UPLOAD_FAILED_WITH_INVALID_UUID
}
@Throws(Exception::class)
override fun setUp() {
super.setUp()
mReleaseStackAppComponent.inject(this)
init()
nextEvent = TestEvents.NONE
}
@Test
fun testQueueForUpload() {
nextEvent = ENCRYPTED_LOG_UPLOADED_SUCCESSFULLY
val testIds = testIds()
mCountDownLatch = CountDownLatch(testIds.size)
testIds.forEach { uuid ->
val payload = UploadEncryptedLogPayload(
uuid = uuid,
file = createTempFileWithContent(suffix = uuid, content = "Testing FluxC log upload for $uuid"),
shouldStartUploadImmediately = true
)
mDispatcher.dispatch(EncryptedLogActionBuilder.newUploadLogAction(payload))
}
assertTrue(mCountDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS))
}
@Test
fun testQueueForUploadForInvalidUuid() {
nextEvent = ENCRYPTED_LOG_UPLOAD_FAILED_WITH_INVALID_UUID
mCountDownLatch = CountDownLatch(1)
val payload = UploadEncryptedLogPayload(
uuid = INVALID_UUID,
file = createTempFile(suffix = INVALID_UUID),
shouldStartUploadImmediately = true
)
mDispatcher.dispatch(EncryptedLogActionBuilder.newUploadLogAction(payload))
assertTrue(mCountDownLatch.await(TestUtils.DEFAULT_TIMEOUT_MS.toLong(), TimeUnit.MILLISECONDS))
}
@Suppress("unused")
@Subscribe
fun onEncryptedLogUploaded(event: OnEncryptedLogUploaded) {
when (event) {
is EncryptedLogUploadedSuccessfully -> {
assertThat(nextEvent, `is`(ENCRYPTED_LOG_UPLOADED_SUCCESSFULLY))
assertThat(testIds(), hasItem(event.uuid))
}
is EncryptedLogFailedToUpload -> {
when (event.error) {
is TooManyRequests -> {
// If we are hitting too many requests, we just ignore the test as restarting it will not help
assertThat(event.willRetry, `is`(true))
}
is InvalidRequest -> {
assertThat(nextEvent, `is`(ENCRYPTED_LOG_UPLOAD_FAILED_WITH_INVALID_UUID))
assertThat(event.willRetry, `is`(false))
}
else -> {
throw AssertionError("Unexpected error occurred in onEncryptedLogUploaded: ${event.error}")
}
}
}
}
mCountDownLatch.countDown()
}
private fun testIds() = (1..NUMBER_OF_LOGS_TO_UPLOAD).map { i ->
"$TEST_UUID_PREFIX$i"
}
private fun createTempFileWithContent(suffix: String, content: String): File {
val file = createTempFile(suffix = suffix)
file.writeText(content)
return file
}
}
| example/src/androidTest/java/org/wordpress/android/fluxc/release/ReleaseStack_EncryptedLogTest.kt | 485574399 |
/*
* Copyright 2019 Johannes Donath <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* 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.basinmc.faucet.event.extension
import org.basinmc.faucet.event.StatelessEvent
import org.basinmc.faucet.extension.Extension
import org.basinmc.faucet.extension.Extension.Phase
import org.basinmc.faucet.util.BitMask
/**
* @author [Johannes Donath](mailto:[email protected])
*/
interface ExtensionRunEvent<S> : ExtensionPhaseEvent<S> {
/**
* {@inheritDoc}
*/
override val currentPhase: Phase
get() = Phase.LOADED
/**
* {@inheritDoc}
*/
override val targetPhase: Phase
get() = Phase.RUNNING
class Pre @JvmOverloads constructor(extension: Extension, state: State = State.RUN) :
AbstractStatefulExtensionEvent<State>(extension, state), ExtensionRunEvent<State>
class Post(extension: Extension) : AbstractExtensionEvent<Unit>(extension),
ExtensionRunEvent<Unit>, StatelessEvent
class State(mask: Int) : BitMask<State>(mask) {
override val definition = Companion
companion object : Definition<State> {
val RUN = State(1)
override val values = listOf(RUN)
override fun newInstance(mask: Int) = State(mask)
}
}
}
| faucet/src/main/kotlin/org/basinmc/faucet/event/extension/ExtensionRunEvent.kt | 245504251 |
package runtimemodels.chazm.model.relation
import runtimemodels.chazm.api.entity.Attribute
import runtimemodels.chazm.api.entity.AttributeId
import runtimemodels.chazm.api.entity.Role
import runtimemodels.chazm.api.entity.RoleId
import runtimemodels.chazm.api.id.UniqueId
import runtimemodels.chazm.api.relation.Needs
import runtimemodels.chazm.model.event.AbstractEvent
import runtimemodels.chazm.model.event.EventType
import runtimemodels.chazm.model.message.M
import java.util.*
import javax.inject.Inject
/**
* The [NeedsEvent] class indicates that there is an update about a [Needs] relation.
*
* @author Christopher Zhong
* @since 7.0.0
*/
open class NeedsEvent @Inject internal constructor(
category: EventType,
needs: Needs
) : AbstractEvent(category) {
/**
* Returns a [UniqueId] that represents a [Role].
*
* @return a [UniqueId].
*/
val roleId: RoleId = needs.role.id
/**
* Returns a [UniqueId] that represents a [Attribute].
*
* @return a [UniqueId].
*/
val attributeId: AttributeId = needs.attribute.id
override fun equals(other: Any?): Boolean {
if (other is NeedsEvent) {
return super.equals(other) && roleId == other.roleId && attributeId == other.attributeId
}
return false
}
override fun hashCode(): Int = Objects.hash(category, roleId, attributeId)
override fun toString(): String = M.EVENT_WITH_2_IDS[super.toString(), roleId, attributeId]
companion object {
private const val serialVersionUID = -2368504360543452399L
}
}
| chazm-model/src/main/kotlin/runtimemodels/chazm/model/relation/NeedsEvent.kt | 930260674 |
package runtimemodels.chazm.api.id
import runtimemodels.chazm.api.organization.Organization
/**
* The [Identifiable] interface is used to mark entities of an [Organization] that can be uniquely identified.
*
* @param <T> the type for the [UniqueId].
* @param <U> the subtype of the [UniqueId].
*
* @author Christopher Zhong
* @since 7.0.0
*/
@FunctionalInterface
interface Identifiable<T : Any, U : UniqueId<T>> {
/**
* The `id`.
*/
val id: U
}
| chazm-api/src/main/kotlin/runtimemodels/chazm/api/id/Identifiable.kt | 4074757473 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.item.enchantment
import org.spongepowered.api.data.persistence.DataContainer
import org.spongepowered.api.data.persistence.Queries
import org.spongepowered.api.item.enchantment.Enchantment
import org.spongepowered.api.item.enchantment.EnchantmentType
data class LanternEnchantment(private val enchantmentType: EnchantmentType, private val level: Int) : Enchantment {
override fun getType(): EnchantmentType = this.enchantmentType
override fun getLevel(): Int = this.level
override fun getContentVersion(): Int = 1
override fun toContainer(): DataContainer {
return DataContainer.createNew()
.set(Queries.CONTENT_VERSION, contentVersion)
.set(Queries.ENCHANTMENT_ID, type.key)
.set(Queries.LEVEL, level)
}
}
| src/main/kotlin/org/lanternpowered/server/item/enchantment/LanternEnchantment.kt | 2763149022 |
/*
* Copyright (C) 2018 Tobias Raatiniemi
*
* 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, version 2 of the License.
*
* 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 me.raatiniemi.worker.data.projects
import androidx.room.*
import androidx.room.ForeignKey.CASCADE
import me.raatiniemi.worker.domain.model.TimeInterval
@Entity(
tableName = "time_intervals",
foreignKeys = [
ForeignKey(
entity = ProjectEntity::class,
parentColumns = ["_id"],
childColumns = ["project_id"],
onDelete = CASCADE
)
],
indices = [
Index(name = "index_project_id", value = ["project_id"])
]
)
data class TimeIntervalEntity(
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "_id")
val id: Long = 0,
@ColumnInfo(name = "project_id")
val projectId: Long,
@ColumnInfo(name = "start_in_milliseconds")
val startInMilliseconds: Long,
@ColumnInfo(name = "stop_in_milliseconds")
val stopInMilliseconds: Long = 0,
val registered: Long = 0
) {
internal fun toTimeInterval() = TimeInterval(
id = id,
projectId = projectId,
startInMilliseconds = startInMilliseconds,
stopInMilliseconds = stopInMilliseconds,
isRegistered = registered == 1L
)
}
internal fun TimeInterval.toEntity() = TimeIntervalEntity(
id = id ?: 0,
projectId = projectId,
startInMilliseconds = startInMilliseconds,
stopInMilliseconds = stopInMilliseconds,
registered = if (isRegistered) {
1
} else {
0
}
)
| app/src/main/java/me/raatiniemi/worker/data/projects/TimeIntervalEntity.kt | 488310707 |
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.focus.web
object Config {
const val DEFAULT_NEW_RENDERER = true
const val EXPERIMENT_DESCRIPTOR_GECKOVIEW_ENGINE = "use-gecko-nightly"
const val EXPERIMENT_DESCRIPTOR_HOME_SCREEN_TIPS = "use-homescreen-tips-nightly"
}
| app/src/nightly/java/org/mozilla/focus/web/Config.kt | 337220584 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.effect.entity
import org.lanternpowered.api.key.NamespacedKey
import org.lanternpowered.server.catalog.DefaultCatalogType
class LanternEntityEffectType(key: NamespacedKey) : DefaultCatalogType(key), EntityEffectType
| src/main/kotlin/org/lanternpowered/server/effect/entity/LanternEntityEffectType.kt | 3949760666 |
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.updates
import com.intellij.openapi.updateSettings.impl.*
import com.intellij.openapi.util.BuildNumber
import com.intellij.testFramework.fixtures.BareTestFixtureTestCase
import com.intellij.util.loadElement
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertNull
// unless stated otherwise, the behavior described in cases is true for 162+
class UpdateStrategyTest : BareTestFixtureTestCase() {
@Test fun `channel contains no builds`() {
val result = check("IU-145.258", ChannelStatus.RELEASE, """<channel id="IDEA_Release" status="release" licensing="release"/>""")
assertNull(result.newBuild)
}
@Test fun `already on the latest build`() {
val result = check("IU-145.258", ChannelStatus.RELEASE, """
<channel id="IDEA15_Release" status="release" licensing="release">
<build number="143.2332" version="15.0.5"/>
</channel>
<channel id="IDEA_Release" status="release" licensing="release">
<build number="145.258" version="2016.1"/>
</channel>""")
assertNull(result.newBuild)
}
@Test fun `patch exclusions`() {
val channels = """
<channel id="IDEA_Release" status="release" licensing="release">
<build number="145.597" version="2016.1.1">
<patch from="145.596"/>
<patch from="145.258" exclusions="win,mac,unix"/>
</build>
</channel>"""
assertNotNull(check("IU-145.596", ChannelStatus.RELEASE, channels).patches)
assertNull(check("IU-145.258", ChannelStatus.RELEASE, channels).patches)
}
@Test fun `order of builds does not matter`() {
val resultDesc = check("IU-143.2332", ChannelStatus.RELEASE, """
<channel id="IDEA_Release" status="release" licensing="release">
<build number="145.597" version="2016.1.1"/>
<build number="145.258" version="2016.1"/>
</channel>""")
assertBuild("145.597", resultDesc.newBuild)
val resultAsc = check("IU-143.2332", ChannelStatus.RELEASE, """
<channel id="IDEA_Release" status="release" licensing="release">
<build number="145.258" version="2016.1"/>
<build number="145.597" version="2016.1.1"/>
</channel>""")
assertBuild("145.597", resultAsc.newBuild)
}
@Test fun `newer updates are preferred`() {
val result = check("IU-145.258", ChannelStatus.EAP, """
<channel id="IDEA_EAP" status="eap" licensing="eap">
<build number="145.596" version="2016.1.1 EAP"/>
</channel>
<channel id="IDEA_Release" status="release" licensing="release">
<build number="145.597" version="2016.1.1"/>
</channel>""")
assertBuild("145.597", result.newBuild)
}
@Test fun `newer updates are preferred over more stable ones`() {
val result = check("IU-145.257", ChannelStatus.EAP, """
<channel id="IDEA_EAP" status="eap" licensing="eap">
<build number="145.596" version="2016.1.1 EAP"/>
</channel>
<channel id="IDEA_Beta" status="beta" licensing="release">
<build number="145.257" version="2016.1 RC2"/>
</channel>
<channel id="IDEA_Release" status="release" licensing="release">
<build number="145.258" version="2016.1"/>
</channel>""")
assertBuild("145.596", result.newBuild)
}
@Test fun `newer updates from non-allowed channels are ignored`() {
val channels = """
<channel id="IDEA_EAP" status="eap" licensing="eap">
<build number="145.596" version="2016.1.1 EAP"/>
</channel>
<channel id="IDEA_Beta" status="beta" licensing="release">
<build number="145.257" version="2016.1 RC2"/>
</channel>
<channel id="IDEA_Release" status="release" licensing="release">
<build number="145.258" version="2016.1"/>
</channel>"""
assertBuild("145.258", check("IU-145.256", ChannelStatus.RELEASE, channels).newBuild)
assertNull(check("IU-145.258", ChannelStatus.RELEASE, channels).newBuild)
}
@Test fun `ignored updates are excluded`() {
val result = check("IU-145.258", ChannelStatus.EAP, """
<channel id="IDEA_EAP" status="eap" licensing="eap">
<build number="145.596" version="2016.1.1 EAP"/>
<build number="145.595" version="2016.1.1 EAP"/>
</channel>""", listOf("145.596"))
assertBuild("145.595", result.newBuild)
}
@Test fun `ignored same-baseline updates do not hide new major releases`() {
val result = check("IU-145.971", ChannelStatus.RELEASE, """
<channel id="IDEA_Release" status="release" licensing="release">
<build number="145.1617" version="2016.1.3"/>
<build number="145.2070" version="2016.1.4"/>
<build number="171.4424" version="2017.1.3"/>
</channel>""", listOf("145.1617", "145.2070"))
assertBuild("171.4424", result.newBuild)
}
@Test fun `updates can be targeted for specific builds (different builds)`() {
val channels = """
<channel id="IDEA_EAP" status="eap" licensing="eap">
<build number="145.596" version="2016.1.1 EAP" targetSince="145.595" targetUntil="145.*"/> <!-- this build is not for everyone -->
<build number="145.595" version="2016.1.1 EAP"/>
</channel>"""
assertBuild("145.595", check("IU-145.258", ChannelStatus.EAP, channels).newBuild)
assertBuild("145.596", check("IU-145.595", ChannelStatus.EAP, channels).newBuild)
}
@Test fun `updates can be targeted for specific builds (same build)`() {
val channels = """
<channel id="IDEA_EAP" status="release" licensing="release">
<build number="163.101" version="2016.3.1" targetSince="163.0" targetUntil="163.*"><message>bug fix</message></build>
<build number="163.101" version="2016.3.1"><message>new release</message></build>
</channel>"""
assertEquals("new release", check("IU-145.258", ChannelStatus.RELEASE, channels).newBuild?.message)
assertEquals("bug fix", check("IU-163.50", ChannelStatus.RELEASE, channels).newBuild?.message)
}
@Test fun `updates from the same baseline are preferred (unified channels)`() {
val result = check("IU-143.2287", ChannelStatus.EAP, """
<channel id="IDEA_EAP" status="eap" licensing="eap">
<build number="143.2330" version="15.0.5 EAP"/>
<build number="145.600" version="2016.1.2 EAP"/>
</channel>
<channel id="IDEA_Release" status="release" licensing="release">
<build number="143.2332" version="15.0.5"/>
<build number="145.597" version="2016.1.1"/>
</channel>""")
assertBuild("143.2332", result.newBuild)
}
// since 163
@Test fun `updates from the same baseline are preferred (per-release channels)`() {
val result = check("IU-143.2287", ChannelStatus.EAP, """
<channel id="IDEA_143_EAP" status="eap" licensing="eap">
<build number="143.2330" version="15.0.5 EAP"/>
</channel>
<channel id="IDEA_143_Release" status="release" licensing="release">
<build number="143.2332" version="15.0.5"/>
</channel>
<channel id="IDEA_145_EAP" status="eap" licensing="eap">
<build number="145.600" version="2016.1.2 EAP"/>
</channel>
<channel id="IDEA_Release_145" status="release" licensing="release">
<build number="145.597" version="2016.1.1"/>
</channel>""")
assertBuild("143.2332", result.newBuild)
}
@Test fun `cross-baseline updates are perfectly legal`() {
val result = check("IU-143.2332", ChannelStatus.EAP, """
<channel id="IDEA_Release" status="release" licensing="release">
<build number="143.2332" version="15.0.5"/>
<build number="145.597" version="2016.1.1"/>
</channel>""")
assertBuild("145.597", result.newBuild)
}
@Test fun `variable-length build numbers are supported`() {
val channels = """
<channel id="IDEA_Release" status="release" licensing="release">
<build number="162.11.10" version="2016.2"/>
</channel>"""
assertBuild("162.11.10", check("IU-145.597", ChannelStatus.RELEASE, channels).newBuild)
assertBuild("162.11.10", check("IU-162.7.23", ChannelStatus.RELEASE, channels).newBuild)
assertNull(check("IU-162.11.11", ChannelStatus.RELEASE, channels).newBuild)
val result = check("IU-162.11.10", ChannelStatus.RELEASE, """
<channel id="IDEA_Release" status="release" licensing="release">
<build number="162.48" version="2016.2.1 EAP"/>
</channel>""")
assertBuild("162.48", result.newBuild)
}
@Test fun `for duplicate builds, first matching channel is preferred`() {
val build = """<build number="163.9166" version="2016.3.1"/>"""
val eap15 = """<channel id="IDEA15_EAP" status="eap" licensing="eap" majorVersion="15">$build</channel>"""
val eap = """<channel id="IDEA_EAP" status="eap" licensing="eap" majorVersion="2016">$build</channel>"""
val beta15 = """<channel id="IDEA15_Beta" status="beta" licensing="release" majorVersion="15">$build</channel>"""
val beta = """<channel id="IDEA_Beta" status="beta" licensing="release" majorVersion="2016">$build</channel>"""
val release15 = """<channel id="IDEA15_Release" status="release" licensing="release" majorVersion="15">$build</channel>"""
val release = """<channel id="IDEA_Release" status="release" licensing="release" majorVersion="2016">$build</channel>"""
// note: this is a test; in production, release builds should never be proposed via channels with EAP licensing
assertEquals("IDEA15_EAP", check("IU-163.1", ChannelStatus.EAP, (eap15 + eap + beta15 + beta + release15 + release)).updatedChannel?.id)
assertEquals("IDEA_EAP", check("IU-163.1", ChannelStatus.EAP, (eap + eap15 + beta + beta15 + release + release15)).updatedChannel?.id)
assertEquals("IDEA15_EAP", check("IU-163.1", ChannelStatus.EAP, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel?.id)
assertEquals("IDEA_EAP", check("IU-163.1", ChannelStatus.EAP, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel?.id)
assertEquals("IDEA15_Beta", check("IU-163.1", ChannelStatus.BETA, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel?.id)
assertEquals("IDEA_Beta", check("IU-163.1", ChannelStatus.BETA, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel?.id)
assertEquals("IDEA15_Release", check("IU-163.1", ChannelStatus.RELEASE, (eap15 + eap + beta15 + beta + release15 + release)).updatedChannel?.id)
assertEquals("IDEA_Release", check("IU-163.1", ChannelStatus.RELEASE, (eap + eap15 + beta + beta15 + release + release15)).updatedChannel?.id)
assertEquals("IDEA15_Release", check("IU-163.1", ChannelStatus.RELEASE, (release15 + release + beta15 + beta + eap15 + eap)).updatedChannel?.id)
assertEquals("IDEA_Release", check("IU-163.1", ChannelStatus.RELEASE, (release + release15 + beta + beta15 + eap + eap15)).updatedChannel?.id)
}
@Test fun `building linear patch chain`() {
val result = check("IU-182.3569.1", ChannelStatus.EAP, """
<channel id="IDEA_EAP" status="eap" licensing="eap">
<build number="182.3684.40" version="2018.2 RC2">
<patch from="182.3684.2" size="from 1 to 8"/>
</build>
<build number="182.3684.2" version="2018.2 RC">
<patch from="182.3569.1" size="2"/>
</build>
</channel>""")
assertBuild("182.3684.40", result.newBuild)
assertThat(result.patches?.chain).isEqualTo(listOf("182.3569.1", "182.3684.2", "182.3684.40").map(BuildNumber::fromString))
assertThat(result.patches?.size).isEqualTo("10")
}
@Test fun `building patch chain across channels`() {
val result = check("IU-182.3684.40", ChannelStatus.EAP, """
<channel id="IDEA_EAP" status="eap" licensing="eap">
<build number="182.3684.40" version="2018.2 RC2">
<patch from="182.3684.2"/>
</build>
</channel>
<channel id="IDEA_Release" status="release" licensing="release">
<build number="182.3684.41" version="2018.2">
<patch from="182.3684.40"/>
</build>
</channel>
<channel id="IDEA_Stable_EAP" status="eap" licensing="release">
<build number="182.3911.2" version="2018.2.1 EAP">
<patch from="182.3684.41"/>
</build>
</channel>""")
assertBuild("182.3911.2", result.newBuild)
assertThat(result.patches?.chain).isEqualTo(listOf("182.3684.40", "182.3684.41", "182.3911.2").map(BuildNumber::fromString))
assertThat(result.patches?.size).isNull()
}
private fun check(currentBuild: String,
selectedChannel: ChannelStatus,
testData: String,
ignoredBuilds: List<String> = emptyList()): CheckForUpdateResult {
val updates = UpdatesInfo(loadElement("""
<products>
<product name="IntelliJ IDEA">
<code>IU</code>
${testData}
</product>
</products>"""))
val settings = object : UserUpdateSettings {
override fun getSelectedChannelStatus() = selectedChannel
override fun getIgnoredBuildNumbers() = ignoredBuilds
}
val result = UpdateStrategy(BuildNumber.fromString(currentBuild), updates, settings).checkForUpdates()
assertEquals(UpdateStrategy.State.LOADED, result.state)
return result
}
private fun assertBuild(expected: String, build: BuildInfo?) {
assertEquals(expected, build?.number?.asStringWithoutProductCode())
}
} | platform/platform-tests/testSrc/com/intellij/ide/updates/UpdateStrategyTest.kt | 388988955 |
/*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tv.reference.shared.watchprogress
import androidx.lifecycle.LiveData
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.PrimaryKey
import androidx.room.Query
/**
* Room class and interface for tracking watch progress of videos.
*
* This is basically how much of a video the user has watched according to ExoPlayer, which allows
* users to resume from where they were watching the video previously.
*/
@Entity(tableName = "watch_progress")
data class WatchProgress(
// A unique identifier for the video
@PrimaryKey
@ColumnInfo(name = "video_id") var videoId: String,
@ColumnInfo(name = "start_position") var startPosition: Long
)
@Dao
interface WatchProgressDao {
@Query("SELECT * FROM watch_progress WHERE video_id = :videoId LIMIT 1")
fun getWatchProgressByVideoId(videoId: String): LiveData<WatchProgress>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(watchProgress: WatchProgress)
@Query("DELETE FROM watch_progress")
suspend fun deleteAll()
}
| step_4_completed/src/main/java/com/android/tv/reference/shared/watchprogress/WatchProgress.kt | 619251048 |
/*
* Copyright (C) 2018 Simon Vig Therkildsen
*
* 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 net.simonvt.cathode.ui.lists
import android.content.Context
import androidx.lifecycle.LiveData
import net.simonvt.cathode.actions.invokeSync
import net.simonvt.cathode.actions.user.SyncLists
import net.simonvt.cathode.common.data.MappedCursorLiveData
import net.simonvt.cathode.entity.UserList
import net.simonvt.cathode.entitymapper.UserListListMapper
import net.simonvt.cathode.entitymapper.UserListMapper
import net.simonvt.cathode.provider.ProviderSchematic.Lists
import net.simonvt.cathode.ui.RefreshableViewModel
import javax.inject.Inject
class ListsViewModel @Inject constructor(
context: Context,
private val syncLists: SyncLists
) : RefreshableViewModel() {
val lists: LiveData<List<UserList>>
init {
lists = MappedCursorLiveData(
context,
Lists.LISTS,
UserListMapper.projection,
null,
null,
null,
UserListListMapper
)
}
override suspend fun onRefresh() {
syncLists.invokeSync(SyncLists.Params())
}
}
| cathode/src/main/java/net/simonvt/cathode/ui/lists/ListsViewModel.kt | 1933376987 |
package com.makeevapps.simpletodolist.ui.activity
import android.arch.lifecycle.Observer
import android.arch.lifecycle.ViewModelProviders
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.Toolbar
import android.view.LayoutInflater
import com.makeevapps.simpletodolist.R
import com.makeevapps.simpletodolist.databinding.ActivityMainBinding
import com.makeevapps.simpletodolist.databinding.ViewMenuHeaderBinding
import com.makeevapps.simpletodolist.enums.MainMenuItemType
import com.makeevapps.simpletodolist.ui.fragment.CalendarFragment
import com.makeevapps.simpletodolist.ui.fragment.TodayFragment
import com.makeevapps.simpletodolist.utils.DateUtils
import com.makeevapps.simpletodolist.utils.UIUtils
import com.makeevapps.simpletodolist.viewmodel.MainViewModel
import com.mikepenz.materialdrawer.Drawer
import com.mikepenz.materialdrawer.DrawerBuilder
import com.mikepenz.materialdrawer.holder.DimenHolder
import com.mikepenz.materialdrawer.holder.StringHolder
import com.mikepenz.materialdrawer.model.DividerDrawerItem
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem
class MainActivity : BaseActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
private lateinit var drawer: Drawer
companion object {
fun getActivityIntent(context: Context, clearFlag: Boolean = true): Intent {
val intent = Intent(context, MainActivity::class.java)
if (clearFlag) intent.addFlags(UIUtils.getClearFlags())
return intent
}
}
val model: MainViewModel by lazy {
ViewModelProviders.of(this).get(MainViewModel::class.java)
}
val binding: ActivityMainBinding by lazy {
DataBindingUtil.setContentView<ActivityMainBinding>(this, R.layout.activity_main)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding.controller = this
binding.model = model
model.preferenceManager.getSharedPreferences().registerOnSharedPreferenceChangeListener(this)
val headerBinding = DataBindingUtil.inflate<ViewMenuHeaderBinding>(LayoutInflater.from(this), R.layout
.view_menu_header, null, false)
headerBinding.controller = this
headerBinding.date = DateUtils.currentTime()
drawer = DrawerBuilder()
.withActivity(this)
.withHeader(headerBinding.root)
.withHeaderHeight(DimenHolder.fromDp(200))
.withTranslucentStatusBar(false)
.withHasStableIds(true)
.withSavedInstance(savedInstanceState)
.addDrawerItems(
createMenuItemByType(MainMenuItemType.TODAY, true),
createMenuItemByType(MainMenuItemType.CALENDAR, true),
DividerDrawerItem(),
createMenuItemByType(MainMenuItemType.SETTINGS, false)
)
.withSelectedItem(1)
.withOnDrawerItemClickListener { _, _, drawerItem ->
if (drawerItem != null) {
val menuItem = MainMenuItemType.getItemById(drawerItem.identifier)
selectMenuItem(menuItem)
}
false
}
.build()
if (savedInstanceState == null) {
selectMenuItem(MainMenuItemType.TODAY)
}
observeTaskData()
}
private fun createMenuItemByType(type: MainMenuItemType, selectable: Boolean): PrimaryDrawerItem {
return PrimaryDrawerItem()
.withIdentifier(type.id)
.withName(type.textResId)
.withIcon(type.imageResId)
.withSelectable(selectable)
.withIconTintingEnabled(true)
}
private fun observeTaskData() {
model.getTasksCount().observe(this, Observer<Int> { tasksCount ->
if (tasksCount != null) {
drawer.updateBadge(1, StringHolder("$tasksCount"))
}
})
}
private fun selectMenuItem(menuItem: MainMenuItemType) {
when (menuItem) {
MainMenuItemType.TODAY -> {
showFragment(TodayFragment.newInstance())
}
MainMenuItemType.CALENDAR -> {
showFragment(CalendarFragment.newInstance())
}
MainMenuItemType.SETTINGS -> {
startActivity(SettingsActivity.getActivityIntent(this))
}
}
}
private fun showFragment(fragment: Fragment) {
//val lastFragment = supportFragmentManager.findFragmentById(R.id.container)
supportFragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commitNowAllowingStateLoss()
}
fun setToolbar(toolbar: Toolbar, homeAsUp: Boolean, homeEnabled: Boolean, title: String?) {
setSupportActionBar(toolbar, homeAsUp, homeEnabled, title)
drawer.setToolbar(this, toolbar, true)
//drawer.drawerLayout.setStatusBarBackgroundColor(ContextCompat.getColor(this, R.color.status_bar))
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (!key.isNullOrEmpty() && key == getString(R.string.is24HourFormat)) {
selectMenuItem(MainMenuItemType.getItemById(drawer.currentSelection))
}
}
override fun onSaveInstanceState(outState: Bundle?) {
val newOutState = drawer.saveInstanceState(outState)
super.onSaveInstanceState(newOutState)
}
override fun onBackPressed() {
if (drawer.isDrawerOpen) {
drawer.closeDrawer()
} else {
super.onBackPressed()
}
}
override fun onDestroy() {
model.preferenceManager.getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this)
super.onDestroy()
}
}
| app/src/main/java/com/makeevapps/simpletodolist/ui/activity/MainActivity.kt | 3603116630 |
package com.pr0gramm.app.ui
import android.net.Uri
import com.google.code.regexp.Pattern
import com.pr0gramm.app.Instant
import com.pr0gramm.app.feed.FeedFilter
import com.pr0gramm.app.feed.FeedType
import com.pr0gramm.app.ui.fragments.CommentRef
import java.util.*
object FilterParser {
fun parse(uri: Uri, notificationTime: Instant? = null): FeedFilterWithStart? {
val uriPath = uri.encodedPath ?: "/"
val commentId = extractCommentId(uriPath)
// get the path without optional comment link
val path = uriPath.replaceFirst(reCommentSuffix, "")
for (pattern in patterns) {
val matcher = pattern.matcher(path)
if (!matcher.matches()) {
continue
}
val encodedGroups = matcher.namedGroups().firstOrNull()?.toMap() ?: continue
val values = encodedGroups.mapValues { decodeUrlComponent(it.value) }
var filter = FeedFilter().withFeedType(FeedType.NEW)
if (values["type"] == "top") {
filter = filter.withFeedType(FeedType.PROMOTED)
}
if (values["type"] == "stalk") {
filter = filter.withFeedType(FeedType.STALK)
}
val tag = values["tag"]
val user = values["user"]
if (!user.isNullOrBlank()) {
when (val subcategory = values["subcategory"]) {
null, "uploads" -> {
filter = filter
.withFeedType(FeedType.NEW)
.basicWithUser(user)
.withTagsNoReset(tag)
}
else -> {
val collectionTitle = subcategory.replaceFirstChar { ch ->
if (ch.isLowerCase()) ch.titlecase(Locale.getDefault()) else ch.toString()
}
filter = filter
.withFeedType(FeedType.NEW)
.basicWithCollection(user, subcategory, collectionTitle)
}
}
}
if (filter.tags == null && !tag.isNullOrBlank()) {
filter = filter.withTagsNoReset(tag)
}
val itemId = values["id"]?.toLongOrNull()
return FeedFilterWithStart(filter, itemId, commentId, notificationTime)
}
return null
}
private fun decodeUrlComponent(value: String): String {
return Uri.decode(value)
}
/**
* Returns the comment id from the path or null, if no comment id
* is provided.
*/
private fun extractCommentId(path: String): Long? {
val matcher = Pattern.compile(":comment([0-9]+)$").matcher(path)
return if (matcher.find()) matcher.group(1).toLongOrNull() else null
}
private val reCommentSuffix = ":comment[0-9]+$".toRegex()
private val pFeed = Pattern.compile("^/(?<type>new|top|stalk)$")
private val pFeedId = Pattern.compile("^/(?<type>new|top|stalk)/(?<id>[0-9]+)$")
private val pUser = Pattern.compile("^/user/(?<user>[^/]+)/?$")
private val pUserUploads = Pattern.compile("^/user/(?<user>[^/]+)/(?<subcategory>uploads|[^/]+)/?$")
private val pUserUploadsId = Pattern.compile("^/user/(?<user>[^/]+)/(?<subcategory>uploads|[^/]+)/(?<id>[0-9]+)$")
private val pUserUploadsWithTag = Pattern.compile("^/user/(?<user>[^/]+)/(?<subcategory>uploads)/(?<tag>[^/]+)$")
private val pUserUploadsWithTagId =
Pattern.compile("^/user/(?<user>[^/]+)/(?<subcategory>uploads|[^/]+)/(?<tag>[^/]+)/(?<id>[0-9]+)$")
private val pTag = Pattern.compile("^/(?<type>new|top)/(?<tag>[^/]+)$")
private val pTagId = Pattern.compile("^/(?<type>new|top)/(?<tag>[^/]+)/(?<id>[0-9]+)$")
private val patterns = listOf(
pFeed,
pFeedId,
pUser,
pUserUploads,
pUserUploadsId,
pUserUploadsWithTag,
pUserUploadsWithTagId,
pTag,
pTagId,
)
}
class FeedFilterWithStart(
val filter: FeedFilter, start: Long?, commentId: Long?,
notificationTime: Instant?
) {
val start: CommentRef? = if (start != null) CommentRef(start, commentId, notificationTime) else null
}
| app/src/main/java/com/pr0gramm/app/ui/FilterParser.kt | 2654333325 |
package io.gitlab.arturbosch.detekt.api
import java.io.PrintStream
/**
* @author Artur Bosch
*/
abstract class ConsoleReport : Extension {
fun print(printer: PrintStream, detektion: Detektion) {
render(detektion)?.let {
printer.println(it)
}
}
abstract fun render(detektion: Detektion): String?
}
| detekt-api/src/main/kotlin/io/gitlab/arturbosch/detekt/api/ConsoleReport.kt | 3082101545 |
package com.lasthopesoftware.bluewater.client.connection.builder.lookup.GivenServerInfoErrorXml
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.RequestServerInfoXml
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.ServerDiscoveryException
import com.lasthopesoftware.bluewater.client.connection.builder.lookup.ServerLookup
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
import xmlwise.Xmlwise
import java.util.concurrent.ExecutionException
class WhenParsingTheServerInfo {
companion object {
private var exception: ServerDiscoveryException? = null
@BeforeClass
@JvmStatic
fun before() {
val serverInfoXml = mockk<RequestServerInfoXml>()
every { serverInfoXml.promiseServerInfoXml(any()) } returns Promise(
Xmlwise.createXml(
"""<?xml version="1.0" encoding="UTF-8"?>
<Response Status="Error">
<msg>Keyid gooPc not found.</msg></Response>"""
)
)
val serverLookup = ServerLookup(serverInfoXml)
try {
serverLookup.promiseServerInformation(LibraryId(14)).toFuture().get()
} catch (e: ExecutionException) {
exception = e.cause as? ServerDiscoveryException ?: throw e
}
}
}
@Test
fun thenAServerDiscoveryExceptionIsThrownWithTheCorrectMessage() {
assertThat(exception?.message).contains("Keyid gooPc not found.")
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/builder/lookup/GivenServerInfoErrorXml/WhenParsingTheServerInfo.kt | 2818117418 |
package za.org.grassroot2.services
import android.support.annotation.WorkerThread
import io.reactivex.FlowableEmitter
import io.reactivex.Maybe
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
abstract class NetworkResource<L, R>(emitter: FlowableEmitter<Resource<L>>) {
protected var localResultPresent = false
@WorkerThread
abstract fun local() : Maybe<L>
@WorkerThread
abstract fun remote(): Observable<R>
init {
val disposable = local().map { Resource.loading(it) }.subscribe( {
emitter.onNext(it)
}, { it.printStackTrace() })
if (shouldFetch()) {
remote().subscribeOn(Schedulers.io()).observeOn(Schedulers.io()).subscribe({ r ->
disposable.dispose()
saveResult(r)
local().map { Resource.success(it) }.subscribe( {
emitter.onNext(it)
emitter.onComplete()
})
}, { it.printStackTrace() })
}
}
@WorkerThread
abstract fun saveResult(data: R)
protected abstract fun shouldFetch(): Boolean
}
| app/src/main/java/za/org/grassroot2/services/NetworkResource.kt | 2337164994 |
package com.lasthopesoftware.bluewater.client.playback.view.nowplaying.menu
import android.widget.ImageButton
import androidx.recyclerview.widget.RecyclerView
import com.lasthopesoftware.bluewater.R
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.details.ViewFileDetailsClickListener
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.AbstractFileListItemMenuBuilder
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.FileListItemContainer
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.FileListItemNowPlayingRegistrar
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.menu.FileNameTextViewSetter
import com.lasthopesoftware.bluewater.client.browsing.items.menu.LongClickViewAnimatorListener
import com.lasthopesoftware.bluewater.client.playback.file.PositionedFile
import com.lasthopesoftware.bluewater.client.playback.service.broadcasters.PlaylistEvents
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.menu.listeners.FileSeekToClickListener
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.menu.listeners.RemovePlaylistFileClickListener
import com.lasthopesoftware.bluewater.client.playback.view.nowplaying.storage.INowPlayingRepository
import com.lasthopesoftware.bluewater.shared.android.view.LazyViewFinder
import com.lasthopesoftware.bluewater.shared.android.view.ViewUtils
import com.lasthopesoftware.bluewater.shared.promises.extensions.LoopedInPromise
class NowPlayingFileListItemMenuBuilder(private val nowPlayingRepository: INowPlayingRepository, private val fileListItemNowPlayingRegistrar: FileListItemNowPlayingRegistrar)
: AbstractFileListItemMenuBuilder<NowPlayingFileListItemMenuBuilder.ViewHolder>(R.layout.layout_now_playing_file_item_menu) {
override fun newViewHolder(fileItemMenu: FileListItemContainer) = ViewHolder(fileItemMenu)
inner class ViewHolder internal constructor(private val fileListItemContainer: FileListItemContainer)
: RecyclerView.ViewHolder(fileListItemContainer.viewAnimator) {
private val viewFileDetailsButtonFinder = LazyViewFinder<ImageButton>(itemView, R.id.btnViewFileDetails)
private val playButtonFinder = LazyViewFinder<ImageButton>(itemView, R.id.btnPlaySong)
private val removeButtonFinder = LazyViewFinder<ImageButton>(itemView, R.id.btnRemoveFromPlaylist)
private val fileNameTextViewSetter = FileNameTextViewSetter(fileListItemContainer.findTextView())
var fileListItemNowPlayingHandler: AutoCloseable? = null
fun update(positionedFile: PositionedFile) {
val fileListItem = fileListItemContainer
val textView = fileListItem.findTextView()
val serviceFile = positionedFile.serviceFile
fileNameTextViewSetter.promiseTextViewUpdate(serviceFile)
val position = positionedFile.playlistPosition
val viewFlipper = fileListItem.viewAnimator
nowPlayingRepository
.nowPlaying
.eventually(LoopedInPromise.response({ np ->
textView.setTypeface(null, ViewUtils.getActiveListItemTextViewStyle(position == np.playlistPosition))
viewFlipper.isSelected = position == np.playlistPosition
}, textView.context))
fileListItemNowPlayingHandler?.close()
fileListItemNowPlayingHandler = fileListItemNowPlayingRegistrar.registerNewHandler(fileListItem) { _, intent ->
val playlistPosition = intent.getIntExtra(PlaylistEvents.PlaylistParameters.playlistPosition, -1)
textView.setTypeface(null, ViewUtils.getActiveListItemTextViewStyle(position == playlistPosition))
viewFlipper.isSelected = position == playlistPosition
}
LongClickViewAnimatorListener.tryFlipToPreviousView(viewFlipper)
playButtonFinder.findView().setOnClickListener(FileSeekToClickListener(viewFlipper, position))
viewFileDetailsButtonFinder.findView().setOnClickListener(ViewFileDetailsClickListener(viewFlipper, serviceFile))
removeButtonFinder.findView().setOnClickListener(RemovePlaylistFileClickListener(viewFlipper, position))
}
}
}
| projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/playback/view/nowplaying/menu/NowPlayingFileListItemMenuBuilder.kt | 11160449 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.