repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
komu/siilinkari | src/test/kotlin/siilinkari/translator/BasicBlockGraphTest.kt | 1 | 739 | package siilinkari.translator
import org.junit.Test
import siilinkari.objects.value
import kotlin.test.assertFailsWith
class BasicBlockGraphTest {
val graph = BasicBlockGraph()
@Test
fun jumpBackwardsDoesNotMaintainBalance() {
val end = BasicBlock()
graph.start += IR.Push(42.value)
graph.start += IR.Push(42.value)
graph.start.endWithBranch(graph.start, end)
end += IR.Push(42.value)
assertInvalidStackUse()
}
@Test
fun stackUnderflow() {
graph.start += IR.Pop
assertInvalidStackUse()
}
private fun assertInvalidStackUse() {
assertFailsWith<InvalidStackUseException> {
graph.buildStackDepthMap()
}
}
}
| mit |
chrisbanes/tivi | data/src/main/java/app/tivi/data/repositories/search/SearchRepository.kt | 1 | 2214 | /*
* Copyright 2018 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.data.repositories.search
import androidx.collection.LruCache
import app.tivi.data.daos.ShowTmdbImagesDao
import app.tivi.data.daos.TiviShowDao
import app.tivi.data.resultentities.ShowDetailed
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class SearchRepository @Inject constructor(
private val showTmdbImagesDao: ShowTmdbImagesDao,
private val showDao: TiviShowDao,
private val tmdbDataSource: TmdbSearchDataSource
) {
private val cache by lazy { LruCache<String, LongArray>(32) }
suspend fun search(query: String): List<ShowDetailed> {
if (query.isBlank()) {
return emptyList()
}
val cacheValues = cache[query]
if (cacheValues != null) {
return cacheValues.map { showDao.getShowWithIdDetailed(it)!! }
}
// We need to hit TMDb instead
return try {
val tmdbResult = tmdbDataSource.search(query)
tmdbResult.map { (show, images) ->
val showId = showDao.getIdOrSavePlaceholder(show)
if (images.isNotEmpty()) {
showTmdbImagesDao.saveImagesIfEmpty(showId, images.map { it.copy(showId = showId) })
}
showId
}.also { results ->
// We need to save the search results
cache.put(query, results.toLongArray())
}.mapNotNull {
// Finally map back to a TiviShow instance
showDao.getShowWithIdDetailed(it)
}
} catch (e: Exception) {
emptyList()
}
}
}
| apache-2.0 |
charlesmadere/smash-ranks-android | smash-ranks-android/app/src/test/java/com/garpr/android/data/models/PollFrequencyTest.kt | 1 | 792 | package com.garpr.android.data.models
import com.garpr.android.test.BaseTest
import org.junit.Assert.assertEquals
import org.junit.Test
class PollFrequencyTest : BaseTest() {
@Test
fun testTimeInSeconds() {
assertEquals(28800L, PollFrequency.EVERY_8_HOURS.timeInSeconds)
assertEquals(86400L, PollFrequency.DAILY.timeInSeconds)
assertEquals(172800L, PollFrequency.EVERY_2_DAYS.timeInSeconds)
assertEquals(259200L, PollFrequency.EVERY_3_DAYS.timeInSeconds)
assertEquals(432000L, PollFrequency.EVERY_5_DAYS.timeInSeconds)
assertEquals(604800L, PollFrequency.WEEKLY.timeInSeconds)
assertEquals(864000L, PollFrequency.EVERY_10_DAYS.timeInSeconds)
assertEquals(1209600L, PollFrequency.EVERY_2_WEEKS.timeInSeconds)
}
}
| unlicense |
alygin/intellij-rust | src/main/kotlin/org/rust/lang/core/psi/ext/RsTypeDeclarationElement.kt | 1 | 636 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import org.rust.lang.core.types.ty.Ty
/**
* Psi element that defines a type and thus lives in types namespace.
* Archetypal inheritors are structs an enums. Type aliases are type
* declarations, while constants and statics are not. Notably, traits
* are type declarations: a bare trait denotes a trait object type.
*
* Curiously, impls are also type declarations: they declare a type of
* Self.
*/
interface RsTypeDeclarationElement : RsCompositeElement {
val declaredType: Ty
}
| mit |
alygin/intellij-rust | src/main/kotlin/org/rust/ide/annotator/RsExpressionAnnotator.kt | 2 | 4043 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.annotator
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.lang.annotation.AnnotationHolder
import com.intellij.lang.annotation.Annotator
import com.intellij.psi.PsiElement
import com.intellij.util.SmartList
import org.rust.ide.annotator.fixes.AddStructFieldsFix
import org.rust.ide.intentions.RemoveParenthesesFromExprIntention
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.ext.*
import java.util.*
import java.io.FileNotFoundException
import java.io.IOException
class RsExpressionAnnotator : Annotator {
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
element.accept(RedundantParenthesisVisitor(holder))
if (element is RsStructLiteral) {
val decl = element.path.reference.resolve() as? RsFieldsOwner
if (decl != null) {
checkStructLiteral(holder, decl, element.structLiteralBody)
}
}
}
private fun checkStructLiteral(
holder: AnnotationHolder,
decl: RsFieldsOwner,
expr: RsStructLiteralBody
) {
expr.structLiteralFieldList
.filter { it.reference.resolve() == null }
.forEach {
holder.createErrorAnnotation(it.identifier, "No such field")
.highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL
}
for (field in expr.structLiteralFieldList.findDuplicateReferences()) {
holder.createErrorAnnotation(field.identifier, "Duplicate field")
}
if (expr.dotdot != null) return // functional update, no need to declare all the fields.
val declaredFields = expr.structLiteralFieldList.map { it.referenceName }.toSet()
val missingFields = decl.namedFields.filter { it.name !in declaredFields && !it.queryAttributes.hasCfgAttr() }
if (decl is RsStructItem && decl.kind == RsStructKind.UNION) {
if (expr.structLiteralFieldList.size > 1) {
holder.createErrorAnnotation(expr, "Union expressions should have exactly one field")
}
} else {
if (missingFields.isNotEmpty()) {
val structNameRange = expr.parent.childOfType<RsPath>()?.textRange
if (structNameRange != null)
holder.createErrorAnnotation(structNameRange, "Some fields are missing")
.registerFix(AddStructFieldsFix(decl.namedFields, missingFields, expr), expr.parent.textRange)
}
}
}
}
private class RedundantParenthesisVisitor(private val holder: AnnotationHolder) : RsVisitor() {
override fun visitCondition(o: RsCondition) =
o.expr.warnIfParens("Predicate expression has unnecessary parentheses")
override fun visitRetExpr(o: RsRetExpr) =
o.expr.warnIfParens("Return expression has unnecessary parentheses")
override fun visitMatchExpr(o: RsMatchExpr) =
o.expr.warnIfParens("Match expression has unnecessary parentheses")
override fun visitForExpr(o: RsForExpr) =
o.expr.warnIfParens("For loop expression has unnecessary parentheses")
override fun visitParenExpr(o: RsParenExpr) =
o.expr.warnIfParens("Redundant parentheses in expression")
private fun RsExpr?.warnIfParens(message: String) {
if (this !is RsParenExpr) return
val fix = RemoveParenthesesFromExprIntention()
if (fix.isAvailable(this))
holder.createWeakWarningAnnotation(this, message)
.registerFix(RemoveParenthesesFromExprIntention())
}
}
private fun <T : RsReferenceElement> Collection<T>.findDuplicateReferences(): Collection<T> {
val names = HashSet<String>(size)
val result = SmartList<T>()
for (item in this) {
val name = item.referenceName
if (name in names) {
result += item
}
names += name
}
return result
}
| mit |
MyDogTom/detekt | detekt-migration/src/test/kotlin/io/gitlab/arturbosch/detekt/migration/MigrateImportsTest.kt | 1 | 1127 | package io.gitlab.arturbosch.detekt.migration
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.test.compileContentForTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
/**
* @author Artur Bosch
*/
internal class MigrateImportsTest {
@Test
fun migrate() {
val ktFile = compileContentForTest(
"""
package hello
import io.gitlab.arturbosch.detekt.migration
import hello.hello
fun main(args: Array<String>) {}
"""
)
val expected = """
package hello
import io.gitlab.arturbosch.detekt.migration
import bye.bye
fun main(args: Array<String>) {}
"""
MigrateImportsRule(MigrationTestConfig).visit(ktFile)
assertThat(ktFile.text).isEqualTo(expected)
}
}
object MigrationTestConfig : Config {
private val map = hashMapOf("imports" to hashMapOf("hello.hello" to "bye.bye"))
override fun subConfig(key: String): Config {
if (key == "migration") return this else return Config.empty
}
override fun <T : Any> valueOrDefault(key: String, default: T): T {
@Suppress("UNCHECKED_CAST")
return map[key] as T? ?: default
}
}
| apache-2.0 |
outadoc/Twistoast-android | keolisprovider/src/main/kotlin/fr/outadev/android/transport/timeo/dto/DescriptionDTO.kt | 1 | 1385 | /*
* Twistoast - DescriptionDTO.kt
* Copyright (C) 2013-2016 Baptiste Candellier
*
* Twistoast 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.
*
* Twistoast 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 fr.outadev.android.transport.timeo.dto
import org.simpleframework.xml.Element
/**
* Represents the details of a stop and line in the XML API.
*
* @author outadoc
*/
class DescriptionDTO {
@field:Element(name = "code") var code: Int = -1
@field:Element(name = "arret") lateinit var arret: String
@field:Element(name = "ligne") lateinit var ligne: String
@field:Element(name = "ligne_nom") lateinit var ligne_nom: String
@field:Element(name = "sens") lateinit var sens: String
@field:Element(name = "vers", required = false) var vers: String? = null
@field:Element(name = "couleur") var couleur: String? = null
}
| gpl-3.0 |
Fitbit/MvRx | mvrx/src/main/kotlin/com/airbnb/mvrx/MavericksFactory.kt | 1 | 4403 | package com.airbnb.mvrx
import androidx.annotation.RestrictTo
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
internal class MavericksFactory<VM : MavericksViewModel<S>, S : MavericksState>(
private val viewModelClass: Class<out VM>,
private val stateClass: Class<out S>,
private val viewModelContext: ViewModelContext,
private val key: String,
private val stateRestorer: ((S) -> S)?,
private val forExistingViewModel: Boolean = false,
private val initialStateFactory: MavericksStateFactory<VM, S> = RealMavericksStateFactory()
) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (stateRestorer == null && forExistingViewModel) {
throw ViewModelDoesNotExistException(viewModelClass, viewModelContext, key)
}
val viewModel = createViewModel(
viewModelClass,
stateClass,
viewModelContext,
stateRestorer ?: { it },
initialStateFactory
)
return viewModel as T
}
}
@Suppress("UNCHECKED_CAST")
private fun <VM : MavericksViewModel<S>, S : MavericksState> createViewModel(
viewModelClass: Class<out VM>,
stateClass: Class<out S>,
viewModelContext: ViewModelContext,
stateRestorer: (S) -> S,
initialStateFactory: MavericksStateFactory<VM, S>
): MavericksViewModelWrapper<VM, S> {
val initialState = initialStateFactory.createInitialState(viewModelClass, stateClass, viewModelContext, stateRestorer)
val factoryViewModel = viewModelClass.factoryCompanion()?.let { factoryClass ->
try {
factoryClass.getMethod("create", ViewModelContext::class.java, MavericksState::class.java)
.invoke(factoryClass.instance(), viewModelContext, initialState) as VM?
} catch (exception: NoSuchMethodException) {
// Check for JvmStatic method.
viewModelClass.getMethod("create", ViewModelContext::class.java, MavericksState::class.java)
.invoke(null, viewModelContext, initialState) as VM?
}
}
val viewModel = requireNotNull(factoryViewModel ?: createDefaultViewModel(viewModelClass, initialState)) {
if (viewModelClass.constructors.firstOrNull()?.parameterTypes?.size?.let { it > 1 } == true) {
"${viewModelClass.simpleName} takes dependencies other than initialState. " +
"It must have companion object implementing ${MavericksViewModelFactory::class.java.simpleName} " +
"with a create method returning a non-null ViewModel."
} else {
"${viewModelClass::class.java.simpleName} must have primary constructor with a " +
"single non-optional parameter that takes initial state of ${stateClass.simpleName}."
}
}
return MavericksViewModelWrapper(viewModel)
}
@Suppress("UNCHECKED_CAST", "NestedBlockDepth")
private fun <VM : MavericksViewModel<S>, S : MavericksState> createDefaultViewModel(viewModelClass: Class<VM>, state: S): VM? {
// If we are checking for a default ViewModel, we expect only a single default constructor. Any other case
// is a misconfiguration and we will throw an appropriate error under further inspection.
if (viewModelClass.constructors.size == 1) {
val primaryConstructor = viewModelClass.constructors[0]
if (primaryConstructor.parameterTypes.size == 1 && primaryConstructor.parameterTypes[0].isAssignableFrom(state::class.java)) {
if (!primaryConstructor.isAccessible) {
try {
primaryConstructor.isAccessible = true
} catch (e: SecurityException) {
throw IllegalStateException("ViewModel class is not public and MvRx could not make the primary constructor accessible.", e)
}
}
return primaryConstructor?.newInstance(state) as? VM
}
}
return null
}
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
@InternalMavericksApi
open class ViewModelDoesNotExistException(message: String) : IllegalStateException(message) {
constructor(
viewModelClass: Class<*>,
viewModelContext: ViewModelContext,
key: String
) : this("ViewModel of type ${viewModelClass.name} for ${viewModelContext.owner}[$key] does not exist yet!")
}
| apache-2.0 |
http4k/http4k | http4k-contract/src/main/kotlin/org/http4k/contract/openapi/v3/JsonToJsonSchema.kt | 1 | 3645 | package org.http4k.contract.openapi.v3
import org.http4k.format.Json
import org.http4k.format.JsonType
import org.http4k.lens.ParamMeta
import org.http4k.util.IllegalSchemaException
import org.http4k.util.JsonSchema
import org.http4k.util.JsonSchemaCreator
class JsonToJsonSchema<NODE>(
private val json: Json<NODE>,
private val refLocationPrefix: String = "components/schemas"
) : JsonSchemaCreator<NODE, NODE> {
override fun toSchema(obj: NODE, overrideDefinitionId: String?, refModelNamePrefix: String?) =
JsonSchema(obj, emptySet()).toSchema(overrideDefinitionId, refModelNamePrefix ?: "")
private fun JsonSchema<NODE>.toSchema(
overrideDefinitionId: String? = null,
refModelNamePrefix: String
): JsonSchema<NODE> =
when (json.typeOf(node)) {
JsonType.Object -> objectSchema(overrideDefinitionId, refModelNamePrefix)
JsonType.Array -> arraySchema(overrideDefinitionId, refModelNamePrefix)
JsonType.String -> JsonSchema(ParamMeta.StringParam.schema(json.string(json.text(node))), definitions)
JsonType.Integer -> numberSchema()
JsonType.Number -> numberSchema()
JsonType.Boolean -> JsonSchema(ParamMeta.BooleanParam.schema(json.boolean(json.bool(node))), definitions)
JsonType.Null -> throw IllegalSchemaException("Cannot use a null value in a schema!")
else -> throw IllegalSchemaException("unknown type")
}
private fun JsonSchema<NODE>.numberSchema(): JsonSchema<NODE> {
val text = json.text(node)
val schema = when {
text.contains(".") -> ParamMeta.NumberParam.schema(json.number(text.toBigDecimal()))
else -> ParamMeta.IntegerParam.schema(json.number(text.toBigInteger()))
}
return JsonSchema(schema, definitions)
}
private fun JsonSchema<NODE>.arraySchema(
overrideDefinitionId: String?,
refModelNamePrefix: String
): JsonSchema<NODE> {
val (node, definitions) = json.elements(node).toList().firstOrNull()?.let {
JsonSchema(it, definitions).toSchema(overrideDefinitionId, refModelNamePrefix)
} ?: throw IllegalSchemaException("Cannot use an empty list to generate a schema!")
return JsonSchema(json { obj("type" to string("array"), "items" to node) }, definitions)
}
private fun JsonSchema<NODE>.objectSchema(
overrideDefinitionId: String?,
refModelNamePrefix: String
): JsonSchema<NODE> {
val (fields, subDefinitions) = json.fields(node)
.filter { json.typeOf(it.second) != JsonType.Null } // filter out null fields for which type can't be inferred
.fold(listOf<Pair<String, NODE>>() to definitions) { (memoFields, memoDefinitions), (first, second) ->
JsonSchema(second, memoDefinitions).toSchema(refModelNamePrefix = refModelNamePrefix)
.let { memoFields + (first to it.node) to it.definitions }
}
val newDefinition = json {
obj(
"type" to string("object"),
"required" to array(emptyList()),
"properties" to obj(fields)
)
}
val definitionId = refModelNamePrefix + (overrideDefinitionId ?: ("object" + newDefinition.hashCode()))
val allDefinitions = subDefinitions + (definitionId to newDefinition)
return JsonSchema(json { obj("\$ref" to string("#/$refLocationPrefix/$definitionId")) }, allDefinitions)
}
private fun ParamMeta.schema(example: NODE): NODE = json { obj("type" to string(value), "example" to example) }
}
| apache-2.0 |
danfma/kodando | kodando-mithril/src/main/kotlin/kodando/mithril/Events.kt | 1 | 113 | package kodando.mithril
typealias EventHandlerWithArgument<T> = (T) -> Unit
typealias EventHandler = () -> Unit
| mit |
laurencegw/jenjin | jenjin-core/src/main/kotlin/com/binarymonks/jj/core/physics/collisions/SoundCollision.kt | 1 | 688 | package com.binarymonks.jj.core.physics.collisions
import com.badlogic.gdx.physics.box2d.Contact
import com.badlogic.gdx.physics.box2d.Fixture
import com.binarymonks.jj.core.audio.SoundMode
import com.binarymonks.jj.core.physics.CollisionHandler
import com.binarymonks.jj.core.scenes.Scene
/**
* Triggers a sounds on collision
*/
class SoundCollision(
var soundName: String? = null,
var mode: SoundMode = SoundMode.NORMAL
) : CollisionHandler() {
override fun collision(me: Scene, myFixture: Fixture, other: Scene, otherFixture: Fixture, contact: Contact): Boolean {
me.soundEffects.triggerSound(checkNotNull(soundName), mode)
return false
}
} | apache-2.0 |
paintmonkey/foresale-ai | foresale-ai/app/src/main/java/nl/pixelcloud/foresale_ai/domain/Card.kt | 1 | 342 | package nl.pixelcloud.foresale_ai.domain
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
/**
* Created by Rob Peek on 18/06/16.
*/
open class Card {
@SerializedName("Value")
@Expose
open var value : Int = 0
override fun toString() : String {
return "" + value
}
} | mit |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/sequentialparsers/SequentialParserManager.kt | 1 | 924 | package org.intellij.markdown.parser.sequentialparsers
abstract class SequentialParserManager {
abstract fun getParserSequence(): List<SequentialParser>
fun runParsingSequence(tokensCache: TokensCache, rangesToParse: List<IntRange>): Collection<SequentialParser.Node> {
val result = ArrayList<SequentialParser.Node>()
var parsingSpaces = ArrayList<List<IntRange>>()
parsingSpaces.add(rangesToParse)
for (sequentialParser in getParserSequence()) {
val nextLevelSpaces = ArrayList<List<IntRange>>()
for (parsingSpace in parsingSpaces) {
val currentResult = sequentialParser.parse(tokensCache, parsingSpace)
result.addAll(currentResult.parsedNodes)
nextLevelSpaces.addAll(currentResult.rangesToProcessFurther)
}
parsingSpaces = nextLevelSpaces
}
return result
}
}
| apache-2.0 |
valich/intellij-markdown | src/commonMain/kotlin/org/intellij/markdown/parser/markerblocks/impl/AtxHeaderMarkerBlock.kt | 1 | 2834 | package org.intellij.markdown.parser.markerblocks.impl
import org.intellij.markdown.IElementType
import org.intellij.markdown.MarkdownElementTypes
import org.intellij.markdown.MarkdownTokenTypes
import org.intellij.markdown.parser.LookaheadText
import org.intellij.markdown.parser.ProductionHolder
import org.intellij.markdown.parser.constraints.MarkdownConstraints
import org.intellij.markdown.parser.markerblocks.MarkerBlock
import org.intellij.markdown.parser.markerblocks.MarkerBlockImpl
import org.intellij.markdown.parser.sequentialparsers.SequentialParser
class AtxHeaderMarkerBlock(myConstraints: MarkdownConstraints,
productionHolder: ProductionHolder,
headerRange: IntRange,
tailStartPos: Int,
endOfLinePos: Int)
: MarkerBlockImpl(myConstraints, productionHolder.mark()) {
override fun allowsSubBlocks(): Boolean = false
init {
val curPos = productionHolder.currentPosition
productionHolder.addProduction(listOf(SequentialParser.Node(
curPos + headerRange.first..curPos + headerRange.last + 1, MarkdownTokenTypes.ATX_HEADER
), SequentialParser.Node(
curPos + headerRange.last + 1..tailStartPos, MarkdownTokenTypes.ATX_CONTENT
), SequentialParser.Node(
tailStartPos..endOfLinePos, MarkdownTokenTypes.ATX_HEADER
)))
}
override fun isInterestingOffset(pos: LookaheadText.Position): Boolean = true
private val nodeType = calcNodeType(headerRange.last - headerRange.first + 1)
private fun calcNodeType(headerSize: Int): IElementType {
when (headerSize) {
1 -> return MarkdownElementTypes.ATX_1
2 -> return MarkdownElementTypes.ATX_2
3 -> return MarkdownElementTypes.ATX_3
4 -> return MarkdownElementTypes.ATX_4
5 -> return MarkdownElementTypes.ATX_5
6 -> return MarkdownElementTypes.ATX_6
else -> return MarkdownElementTypes.ATX_6
}
}
override fun getDefaultNodeType(): IElementType {
return nodeType
}
override fun getDefaultAction(): MarkerBlock.ClosingAction {
return MarkerBlock.ClosingAction.DONE
}
override fun calcNextInterestingOffset(pos: LookaheadText.Position): Int {
return pos.nextLineOrEofOffset
}
override fun doProcessToken(pos: LookaheadText.Position,
currentConstraints: MarkdownConstraints): MarkerBlock.ProcessingResult {
if (pos.offsetInCurrentLine == -1) {
return MarkerBlock.ProcessingResult(MarkerBlock.ClosingAction.DROP, MarkerBlock.ClosingAction.DONE, MarkerBlock.EventAction.PROPAGATE)
}
return MarkerBlock.ProcessingResult.CANCEL
}
} | apache-2.0 |
k-r-g/FrameworkBenchmarks | frameworks/Kotlin/http4k/core/src/main/kotlin/WorldRoutes.kt | 7 | 2577 |
import com.fasterxml.jackson.databind.JsonNode
import org.http4k.core.Body
import org.http4k.core.Method.GET
import org.http4k.core.Response
import org.http4k.core.Status.Companion.NOT_FOUND
import org.http4k.core.Status.Companion.OK
import org.http4k.core.with
import org.http4k.format.Jackson.array
import org.http4k.format.Jackson.json
import org.http4k.format.Jackson.number
import org.http4k.format.Jackson.obj
import org.http4k.lens.Query
import org.http4k.routing.bind
import java.lang.Math.max
import java.lang.Math.min
import java.sql.Connection
import java.sql.ResultSet.CONCUR_READ_ONLY
import java.sql.ResultSet.TYPE_FORWARD_ONLY
import java.util.*
object WorldRoutes {
private val jsonBody = Body.json().toLens()
private val numberOfQueries = Query
.map {
try {
min(max(it.toInt(), 1), 500)
} catch (e: Exception) {
1
}
}
.defaulted("queries", 1)
fun queryRoute(database: Database) = "/db" bind GET to {
database.withConnection {
findWorld(it, randomWorld())
}?.let { Response(OK).with(jsonBody of it) } ?: Response(NOT_FOUND)
}
fun multipleRoute(database: Database) = "/queries" bind GET to {
val worlds = database.withConnection {
con ->
(1..numberOfQueries(it)).mapNotNull { findWorld(con, randomWorld()) }
}
Response(OK).with(jsonBody of array(worlds))
}
fun updateRoute(database: Database) = "/updates" bind GET to {
val worlds = database.withConnection {
con ->
(1..numberOfQueries(it)).mapNotNull {
val id = randomWorld()
updateWorld(con, id)
findWorld(con, id)
}
}
Response(OK).with(jsonBody of array(worlds))
}
private fun findWorld(it: Connection, id: Int): JsonNode? {
val stmtSelect = it.prepareStatement("select * from world where id = ?", TYPE_FORWARD_ONLY, CONCUR_READ_ONLY)
stmtSelect.setInt(1, id)
return stmtSelect.executeQuery().toList {
obj("id" to number(it.getInt("id")), "randomNumber" to number(it.getInt("randomNumber")))
}.firstOrNull()
}
private fun updateWorld(it: Connection, id: Int) {
val stmtSelect = it.prepareStatement("update world set randomNumber = ? where id = ?")
stmtSelect.setInt(1, randomWorld())
stmtSelect.setInt(2, id)
stmtSelect.executeUpdate()
}
private fun randomWorld() = Random().nextInt(9999) + 1
} | bsd-3-clause |
xiaopansky/Sketch | sample/src/main/java/me/panpf/sketch/sample/bean/BaiduImageSearchResult.kt | 1 | 985 | package me.panpf.sketch.sample.bean
import com.google.gson.annotations.SerializedName
class BaiduImageSearchResult {
@SerializedName("listNum")
var total: Int = 0
@SerializedName("data")
var imageList: List<BaiduImage>? = null
}
class BaiduImage {
@SerializedName("thumbURL")
val thumbURL: String? = null
@SerializedName("middleURL")
val middleURL: String? = null
@SerializedName("hoverURL")
val hoverURL: String? = null
@SerializedName("replaceUrl")
private val replaceUrlList: List<ReplaceUrl>? = null
@SerializedName("width")
val width: Int = 0
@SerializedName("height")
val height: Int = 0
val url: String?
get() {
return if (hoverURL != middleURL && hoverURL != thumbURL) {
hoverURL
} else {
replaceUrlList?.lastOrNull()?.objUrl
}
}
}
class ReplaceUrl {
@SerializedName("ObjURL")
var objUrl: String? = null
} | apache-2.0 |
langara/USpek | ktjsreactsample/src/jsTest/kotlin/playground/ExampleTest.kt | 1 | 535 | package playground
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.promise
import kotlin.coroutines.CoroutineContext
import kotlin.test.Test
// temporary workaround from: https://github.com/Kotlin/kotlinx.coroutines/issues/1996
val testScope = MainScope()
val testCoroutineContext: CoroutineContext = testScope.coroutineContext
fun runBlockingTest(block: suspend () -> Unit): dynamic = testScope.promise { block() }
class ExampleTest {
@Test
fun exampleTest() = runBlockingTest { lsoDelayMs = 5; example() }
}
| apache-2.0 |
GymDon-P-Q11Info-13-15/game | Game Commons/src/de/gymdon/inf1315/game/Mine.kt | 1 | 550 | package de.gymdon.inf1315.game
class Mine(x: Int, y: Int) : Building() {
var superior = true
init {
this.x = x
this.y = y
this.hp = 1
this.cost = 0
this.defense = 0
}
override fun occupy(p: Player) {
this.owner = p
this.hp = 5000
this.defense = 40
if (this.superior)
this.income = 150
else
this.income = 50
}
override fun clicked(phase: Int): BooleanArray {
options[5] = false
return options
}
}
| gpl-3.0 |
tipsy/javalin | javalin/src/main/java/io/javalin/core/validation/NullableValidator.kt | 1 | 728 | /*
* Javalin - https://javalin.io
* Copyright 2017 David Åse
* Licensed under Apache 2.0: https://github.com/tipsy/javalin/blob/master/LICENSE
*/
package io.javalin.core.validation
open class NullableValidator<T>(fieldName: String, typedValue: T? = null, stringSource: StringSource<T>? = null) : BaseValidator<T>(fieldName, typedValue, stringSource) {
constructor(stringValue: String?, clazz: Class<T>, fieldName: String) :
this(fieldName, null, StringSource<T>(stringValue, clazz))
fun check(check: Check<T?>, error: String) = addRule(fieldName, check, error) as NullableValidator<T>
fun check(check: Check<T?>, error: ValidationError<T>) = addRule(fieldName, check, error) as NullableValidator<T>
}
| apache-2.0 |
LordAkkarin/Beacon | github-api/src/main/kotlin/tv/dotstart/beacon/github/operations/RepositoryOperations.kt | 1 | 3042 | /*
* Copyright 2020 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 tv.dotstart.beacon.github.operations
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
import okhttp3.Request
import tv.dotstart.beacon.github.error.ServiceException
import tv.dotstart.beacon.github.error.repository.NoSuchRepositoryException
import tv.dotstart.beacon.github.model.repository.Release
/**
* Provides access to various repository related operations.
*
* @author [Johannes Donath](mailto:[email protected])
* @date 13/12/2020
*/
class RepositoryOperations(
client: OkHttpClient,
objectMapper: ObjectMapper,
urlFactory: HttpUrlFactory,
/**
* Identifies the owner of the target repository (such as a user or organization).
*/
val repositoryOwner: String,
/**
* Identifies the target repository.
*/
val repositoryName: String) : AbstractOperations(client, objectMapper, urlFactory) {
private fun createUrl(block: HttpUrl.Builder.() -> Unit) = this.urlFactory {
addEncodedPathSegment("repos")
addPathSegment(repositoryOwner)
addPathSegment(repositoryName)
this.block()
}
/**
* Retrieves a listing of releases for this repository.
*
* @throws NullPointerException when [page] is given but [resultsPerPage] remains unset.
*/
fun listReleases(resultsPerPage: Int? = null, page: Int? = null): List<Release> {
if (page != null) {
requireNotNull(resultsPerPage)
}
val url = this.createUrl {
addEncodedPathSegment("releases")
if (resultsPerPage != null) {
addQueryParameter("per_page", resultsPerPage.toString())
}
if (page != null) {
addQueryParameter("page", page.toString())
}
}
val request = Request.Builder()
.url(url)
.build()
return this.client.newCall(request).execute().use { response ->
if (!response.isSuccessful && response.code != 404) {
throw ServiceException(
"Received illegal response code ${response.code} for request to repository $repositoryOwner/$repositoryName")
}
response.body
?.let {
this.objectMapper.readValue<List<Release>>(it.string())
}
?: throw NoSuchRepositoryException(this.repositoryOwner, this.repositoryName)
}
}
}
| apache-2.0 |
cemrich/zapp | app/src/main/java/de/christinecoenen/code/zapp/app/mediathek/api/result/MediathekAnswer.kt | 1 | 203 | package de.christinecoenen.code.zapp.app.mediathek.api.result
import androidx.annotation.Keep
@Keep
data class MediathekAnswer(
val err: String? = null,
val result: MediathekAnswerResult? = null
)
| mit |
pdvrieze/ProcessManager | PE-common/src/commonMain/kotlin/nl/adaptivity/process/processModel/PredecessorInfo.kt | 1 | 2234 | /*
* Copyright (c) 2018.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.processModel
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import nl.adaptivity.process.processModel.engine.XmlCondition
import nl.adaptivity.xmlutil.serialization.XmlElement
import nl.adaptivity.xmlutil.serialization.XmlValue
@Serializable
class PredecessorInfo private constructor(
@SerialName("predecessor")
@XmlValue(true) val id: String,
@SerialName("condition")
@XmlElement(false)
private val rawCondition: String? = null,
@SerialName("label")
@XmlElement(false)
val conditionLabel: String? = null
) {
val condition: Condition?
get() = rawCondition?.let { XmlCondition(it, conditionLabel) }
init {
if (id.isEmpty()) throw IllegalArgumentException("Empty id's are not valid")
}
constructor(id: String, condition: Condition? = null) :
this(id, condition?.condition, condition?.label)
override fun toString(): String {
return "PredecessorInfo(id='$id', condition=$condition)"
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is PredecessorInfo) return false
if (id != other.id) return false
if ((condition?: "") != (other.condition ?: "")) return false
if ((conditionLabel != other.conditionLabel)) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + (condition?.hashCode() ?: 0)
return result
}
}
| lgpl-3.0 |
songzhw/Hello-kotlin | Advanced_hm/src/main/kotlin/ca/six/kjdemo/functions/hof/BaseHtmlElement.kt | 1 | 844 | package ca.six.kjdemo.functions.hof
// <html>这种元素就只有children, 基本没有content. <span>这种就又有content又有name.
open class BaseHtmlElement(val name: String, val content: String = "") : HTMLElement{
val children = ArrayList<HTMLElement>()
val attrs = HashMap<String, String>() //存<img src alt>中的src与alt的
override fun render(sb: StringBuilder, indent: String): String {
sb.append("$indent<$name>\n")
if(content.isNotBlank()){ //全是空格也会返回true
sb.append("$indent $content\n")
}
children.forEach { it.render(sb, "$indent$indent") }
sb.append("$indent</$name>\n")
return sb.toString()
}
override fun toString(): String {
val sb = StringBuilder()
render(sb, " ")
return sb.toString()
}
} | apache-2.0 |
ccomeaux/boardgamegeek4android | app/src/main/java/com/boardgamegeek/ui/NewPlayPlayerIsNewFragment.kt | 1 | 5893 | package com.boardgamegeek.ui
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.activityViewModels
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.boardgamegeek.R
import com.boardgamegeek.databinding.FragmentNewPlayPlayerIsNewBinding
import com.boardgamegeek.databinding.RowNewPlayPlayerIsNewBinding
import com.boardgamegeek.entities.NewPlayPlayerEntity
import com.boardgamegeek.extensions.*
import com.boardgamegeek.ui.viewmodel.NewPlayViewModel
import kotlin.properties.Delegates
class NewPlayPlayerIsNewFragment : Fragment() {
private var _binding: FragmentNewPlayPlayerIsNewBinding? = null
private val binding get() = _binding!!
private val viewModel by activityViewModels<NewPlayViewModel>()
private val adapter: PlayersAdapter by lazy { PlayersAdapter(viewModel) }
@Suppress("RedundantNullableReturnType")
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
_binding = FragmentNewPlayPlayerIsNewBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.recyclerView.adapter = adapter
viewModel.mightBeNewPlayers.observe(viewLifecycleOwner) { entity ->
adapter.players = entity.sortedBy { it.seat }
}
binding.nextButton.setOnClickListener {
viewModel.finishPlayerIsNew()
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onResume() {
super.onResume()
(activity as? AppCompatActivity)?.supportActionBar?.setSubtitle(R.string.title_new_players)
}
private class Diff(private val oldList: List<NewPlayPlayerEntity>, private val newList: List<NewPlayPlayerEntity>) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].isNew == newList[newItemPosition].isNew
}
}
private class PlayersAdapter(private val viewModel: NewPlayViewModel)
: RecyclerView.Adapter<PlayersAdapter.PlayersViewHolder>() {
var players: List<NewPlayPlayerEntity> by Delegates.observable(emptyList()) { _, oldValue, newValue ->
val diffCallback = Diff(oldValue, newValue)
val diffResult = DiffUtil.calculateDiff(diffCallback)
diffResult.dispatchUpdatesTo(this)
}
init {
setHasStableIds(true)
}
override fun getItemCount() = players.size
override fun getItemId(position: Int): Long {
return players.getOrNull(position)?.id?.hashCode()?.toLong() ?: RecyclerView.NO_ID
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlayersViewHolder {
return PlayersViewHolder(parent.inflate(R.layout.row_new_play_player_is_new))
}
override fun onBindViewHolder(holder: PlayersViewHolder, position: Int) {
holder.bind(position)
}
inner class PlayersViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = RowNewPlayPlayerIsNewBinding.bind(itemView)
fun bind(position: Int) {
val entity = players.getOrNull(position)
entity?.let { player ->
binding.nameView.text = player.name
binding.usernameView.setTextOrHide(player.username)
if (player.color.isBlank()) {
binding.colorView.isInvisible = true
binding.teamView.isVisible = false
binding.seatView.setTextColor(Color.TRANSPARENT.getTextColor())
} else {
val color = player.color.asColorRgb()
if (color == Color.TRANSPARENT) {
binding.colorView.isInvisible = true
binding.teamView.setTextOrHide(player.color)
} else {
binding.colorView.setColorViewValue(color)
binding.colorView.isVisible = true
binding.teamView.isVisible = false
}
binding.seatView.setTextColor(color.getTextColor())
}
if (player.seat == null) {
binding.sortView.setTextOrHide(player.sortOrder)
binding.seatView.isInvisible = true
} else {
binding.sortView.isVisible = false
binding.seatView.text = player.seat.toString()
binding.seatView.isVisible = true
}
binding.isNewCheckBox.isChecked = player.isNew
binding.isNewCheckBox.setOnCheckedChangeListener { _, isChecked ->
viewModel.addIsNewToPlayer(player.id, isChecked)
binding.isNewCheckBox.setOnCheckedChangeListener { _, _ -> }
}
}
}
}
}
}
| gpl-3.0 |
songzhw/Hello-kotlin | AdvancedJ/temp/kotlin/utils/ImmediateSchedulerRule.kt | 1 | 908 | package utils
import io.reactivex.Scheduler
import io.reactivex.plugins.RxJavaPlugins
import io.reactivex.schedulers.Schedulers
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
class ImmediateSchedulerRule(val scheduler: Scheduler = Schedulers.trampoline()) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
val ret = object : Statement() {
override fun evaluate() {
RxJavaPlugins.setIoSchedulerHandler { scheduler }
RxJavaPlugins.setComputationSchedulerHandler { scheduler }
RxJavaPlugins.setNewThreadSchedulerHandler { scheduler }
try {
base.evaluate()
} finally {
RxJavaPlugins.reset()
}
}
}
return ret
}
}
| apache-2.0 |
dafi/commonutils | app/src/main/java/com/ternaryop/utils/text/Html.kt | 1 | 1099 | package com.ternaryop.utils.text
import java.util.regex.Pattern
/**
* Surround all pattern strings found on text with a ** (bold) tag
* @param pattern the pattern to surround
* @param text the whole string
* @return the string with highlighted patterns
** */
fun String.htmlHighlightPattern(pattern: String): String {
if (pattern.isBlank()) {
return this
}
val sb = StringBuffer()
val m = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE).matcher(this)
while (m.find()) {
// get substring to preserve case
m.appendReplacement(sb, "<b>" + substring(m.start(), m.end()) + "</b>")
}
m.appendTail(sb)
return sb.toString()
}
/**
* Strip all specified HTML tags contained into string
* @param tags tags separated by pipe (eg "a|br|img")
* @param string html string to strip
* @return stripped string
*/
fun String.stripHtmlTags(tags: String): String {
return if (tags.isBlank()) {
this
} else {
Pattern.compile("""</?($tags).*?>""", Pattern.CASE_INSENSITIVE)
.matcher(this).replaceAll("")
}
}
| mit |
LanternPowered/LanternServer | src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/ClientVehicleControlsDecoder.kt | 1 | 2272 | /*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import io.netty.util.AttributeKey
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.BulkPacket
import org.lanternpowered.server.network.packet.Packet
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientSneakStatePacket
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientVehicleJumpPacket
import org.lanternpowered.server.network.vanilla.packet.type.play.ClientMovementInputPacket
object ClientVehicleControlsDecoder : PacketDecoder<Packet> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): Packet {
var sideways = buf.readFloat()
var forwards = buf.readFloat()
val flags = buf.readByte().toInt()
val jump = flags and 0x1 != 0
val sneak = flags and 0x2 != 0
val packets = mutableListOf<Packet>()
val lastSneak = ctx.session.attr(SNEAKING).getAndSet(sneak) ?: false
if (lastSneak != sneak)
packets += ClientSneakStatePacket(sneak)
val lastJump = ctx.session.attr(JUMPING).getAndSet(jump) ?: false
if (lastJump != jump && ctx.session.attr(ClientPlayerActionDecoder.CANCEL_NEXT_JUMP_MESSAGE).getAndSet(false) != true)
packets += ClientVehicleJumpPacket(jump, 0f)
// The mc client already applies the sneak speed, but we want to choose it
if (sneak) {
sideways /= 0.3f
forwards /= 0.3f
}
packets += ClientMovementInputPacket(forwards, sideways)
return if (packets.size == 1) packets[0] else BulkPacket(packets)
}
private val SNEAKING = AttributeKey.valueOf<Boolean>("last-sneaking-state")
private val JUMPING = AttributeKey.valueOf<Boolean>("last-jumping-state")
}
| mit |
davidwhitman/changelogs | dataprovider/src/main/java/com/thunderclouddev/dataprovider/Mapper.kt | 1 | 6049 | /*
* Copyright (c) 2017.
* Distributed under the GNU GPLv3 by David Whitman.
* https://www.gnu.org/licenses/gpl-3.0.en.html
*
* This source code is made available to help others learn. Please don't clone my app.
*/
package com.thunderclouddev.dataprovider
import com.thunderclouddev.persistence.DbAppInfo
import com.thunderclouddev.persistence.DbAppInfoEntity
import com.thunderclouddev.playstoreapi.model.ApiAppInfo
internal fun AppInfo.toDatabaseModel() =
DbAppInfoEntity().apply {
packageName = [email protected]
versionCode = [email protected]
title = [email protected]
descriptionHtml = [email protected]
shortDescription = [email protected]
versionName = [email protected]
rating = [email protected]
bayesianMeanRating = [email protected]
ratingsCount = [email protected]
oneStarRatings = [email protected]
twoStarRatings = [email protected]
threeStarRatings = [email protected]
fourStarRatings = [email protected]
fiveStarRatings = [email protected]
developerId = [email protected]
developer = [email protected]
developerEmail = [email protected]
developerWebsite = [email protected]
downloadsCount = [email protected]
downloadsCountString = [email protected]
installSizeBytes = [email protected]
recentChangesHtml = [email protected]
updateDate = [email protected]
category = [email protected]
links = com.thunderclouddev.persistence.Links([email protected] ?: emptyMap())
offer = com.thunderclouddev.persistence.Offer([email protected]?.micros,
[email protected]?.currencyCode,
[email protected]?.formattedAmount,
[email protected]?.offerType)
permissions = [email protected]?.map { com.thunderclouddev.persistence.Permission(it.name) }
contentRating = [email protected]
}
internal fun DbAppInfo.toModel() =
AppInfo(
packageName = this.packageName,
versionCode = this.versionCode,
title = this.title,
descriptionHtml = this.descriptionHtml,
shortDescription = this.shortDescription,
versionName = this.versionName,
rating = this.rating,
bayesianMeanRating = this.bayesianMeanRating,
ratingsCount = this.ratingsCount,
oneStarRatings = this.oneStarRatings,
twoStarRatings = this.twoStarRatings,
threeStarRatings = this.threeStarRatings,
fourStarRatings = this.fourStarRatings,
fiveStarRatings = this.fiveStarRatings,
developerId = this.developerId,
developer = this.developer,
developerEmail = this.developerEmail,
developerWebsite = this.developerWebsite,
downloadsCount = this.downloadsCount,
downloadsCountString = this.downloadsCountString,
installSizeBytes = this.installSizeBytes,
recentChangesHtml = this.recentChangesHtml,
updateDate = this.updateDate,
category = this.category,
links = Links(this.links ?: emptyMap()),
offer = Offer(this.offer?.micros,
this.offer?.currencyCode,
this.offer?.formattedAmount,
this.offer?.offerType),
permissions = this.permissions?.map { Permission(it.name) },
contentRating = this.contentRating)
internal fun ApiAppInfo.toModel() =
AppInfo(
packageName = this.packageName,
versionCode = this.versionCode,
title = this.title,
descriptionHtml = this.descriptionHtml,
shortDescription = this.shortDescription,
versionName = this.versionName,
rating = this.rating,
bayesianMeanRating = this.bayesianMeanRating,
ratingsCount = this.ratingsCount,
oneStarRatings = this.oneStarRatings,
twoStarRatings = this.twoStarRatings,
threeStarRatings = this.threeStarRatings,
fourStarRatings = this.fourStarRatings,
fiveStarRatings = this.fiveStarRatings,
developerId = this.developerId,
developer = this.developer,
developerEmail = this.developerEmail,
developerWebsite = this.developerWebsite,
downloadsCount = this.downloadsCount,
downloadsCountString = this.downloadsCountString,
installSizeBytes = this.installSizeBytes,
recentChangesHtml = this.recentChangesHtml,
updateDate = this.updateDate,
category = this.category,
links = if (this.links != null) Links(this.links!!) else null,
offer = Offer(micros = this.offer?.micros,
currencyCode = this.offer?.currencyCode,
formattedAmount = this.offer?.formattedAmount,
offerType = this.offer?.offerType),
permissions = this.permissions?.map(::Permission),
contentRating = this.contentRating
) | gpl-3.0 |
Ruben-Sten/TeXiFy-IDEA | test/nl/hannahsten/texifyidea/util/RootFileTest.kt | 1 | 744 | package nl.hannahsten.texifyidea.util
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import nl.hannahsten.texifyidea.inspections.latex.probablebugs.LatexFileNotFoundInspection
class RootFileTest : BasePlatformTestCase() {
override fun getTestDataPath(): String {
return "test/resources/util/rootfile"
}
fun testTwoLevelDeepInclusion() {
myFixture.enableInspections(LatexFileNotFoundInspection())
myFixture.copyFileToProject("main.tex")
myFixture.copyFileToProject("contents/level-one.tex")
myFixture.copyFileToProject("contents/level-two/level-three.tex")
myFixture.configureByFile("contents/level-two/level-two.tex")
myFixture.checkHighlighting()
}
} | mit |
McGars/percents | feature/details/src/main/java/com/gars/percents/details/presentation/event/UiDetailsEvent.kt | 1 | 163 | package com.gars.percents.details.presentation.event
sealed class UiDetailsEvent {
object Ready : UiDetailsEvent()
object BackToHome : UiDetailsEvent()
} | apache-2.0 |
PaulWoitaschek/Voice | data/src/main/kotlin/voice/data/repo/internals/migrations/Migration44.kt | 1 | 1741 | package voice.data.repo.internals.migrations
import android.content.ContentValues
import android.database.sqlite.SQLiteDatabase
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.squareup.anvil.annotations.ContributesMultibinding
import voice.common.AppScope
import voice.data.repo.internals.getString
import javax.inject.Inject
@ContributesMultibinding(
scope = AppScope::class,
boundType = Migration::class,
)
class Migration44
@Inject constructor() : IncrementalMigration(44) {
override fun migrate(db: SupportSQLiteDatabase) {
db.query("SELECT * FROM bookSettings").use { bookSettingsCursor ->
while (bookSettingsCursor.moveToNext()) {
val bookId = bookSettingsCursor.getString("id")
val currentFile = bookSettingsCursor.getString("currentFile")
db.query("SELECT * FROM chapters WHERE bookId =?", arrayOf(bookId)).use { chapterCursor ->
var chapterForCurrentFileFound = false
while (!chapterForCurrentFileFound && chapterCursor.moveToNext()) {
val chapterFile = chapterCursor.getString("file")
if (chapterFile == currentFile) {
chapterForCurrentFileFound = true
}
}
if (!chapterForCurrentFileFound) {
if (chapterCursor.moveToFirst()) {
val firstChapterFile = chapterCursor.getString("file")
val contentValues = ContentValues().apply {
put("currentFile", firstChapterFile)
put("positionInChapter", 0)
}
db.update("bookSettings", SQLiteDatabase.CONFLICT_FAIL, contentValues, "id =?", arrayOf(bookId))
}
}
}
}
}
}
}
| gpl-3.0 |
andreyfomenkov/green-cat | plugin/src/test/ru/fomenkov/plugin/util/TestUtils.kt | 1 | 90 | package ru.fomenkov.plugin.util
fun fromResources(fileName: String) = "src/res/$fileName" | apache-2.0 |
PaulWoitaschek/Voice | app/src/main/kotlin/voice/app/uitools/ViewBindingHolder.kt | 1 | 490 | package voice.app.uitools
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import voice.common.conductor.InflateBinding
abstract class ViewBindingHolder<B : ViewBinding>(val binding: B) : RecyclerView.ViewHolder(binding.root) {
constructor(parent: ViewGroup, inflateBinding: InflateBinding<B>) : this(
inflateBinding(LayoutInflater.from(parent.context), parent, false),
)
}
| gpl-3.0 |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/service/receivers/file/GivenAFileWritePermissionsError/AndWritePermissionsAreNotGranted/WhenReceivingTheNotification.kt | 1 | 1472 | package com.lasthopesoftware.bluewater.client.stored.service.receivers.file.GivenAFileWritePermissionsError.AndWritePermissionsAreNotGranted
import com.lasthopesoftware.bluewater.client.stored.library.items.files.AccessStoredFiles
import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile
import com.lasthopesoftware.bluewater.client.stored.sync.receivers.file.StoredFileWritePermissionsReceiver
import com.lasthopesoftware.bluewater.shared.promises.extensions.FuturePromise
import com.namehillsoftware.handoff.promises.Promise
import org.assertj.core.api.Assertions.assertThat
import org.junit.BeforeClass
import org.junit.Test
import org.mockito.Mockito
import java.util.*
class WhenReceivingTheNotification {
@Test
fun thenAReadPermissionsRequestIsSent() {
assertThat(requestedWritePermissionLibraries).containsOnly(22)
}
companion object {
private val requestedWritePermissionLibraries: MutableList<Int> = LinkedList()
@BeforeClass
@JvmStatic
fun before() {
val storedFileAccess = Mockito.mock(
AccessStoredFiles::class.java
)
Mockito.`when`(storedFileAccess.getStoredFile(14))
.thenReturn(Promise(StoredFile().setId(14).setLibraryId(22)))
val storedFileWritePermissionsReceiver = StoredFileWritePermissionsReceiver(
{ false }, { e: Int -> requestedWritePermissionLibraries.add(e) },
storedFileAccess
)
FuturePromise(storedFileWritePermissionsReceiver.receive(14)).get()
}
}
}
| lgpl-3.0 |
danrien/projectBlueWater | projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/client/browsing/library/access/LibraryRemoval.kt | 2 | 1487 | package com.lasthopesoftware.bluewater.client.browsing.library.access
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.ProvideSelectedLibraryId
import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectBrowserLibrary
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.stored.library.items.IStoredItemAccess
import com.namehillsoftware.handoff.promises.Promise
class LibraryRemoval(
private val storedItems: IStoredItemAccess,
private val libraryStorage: ILibraryStorage,
private val selectedLibraryIdProvider: ProvideSelectedLibraryId,
private val libraryProvider: ILibraryProvider,
private val librarySelection: SelectBrowserLibrary) : RemoveLibraries {
override fun removeLibrary(library: Library): Promise<*> {
val promisedNewLibrarySelection =
selectedLibraryIdProvider.selectedLibraryId
.eventually {
if (library.libraryId != it) Promise.empty()
else libraryProvider.allLibraries.eventually { libraries ->
val firstOtherLibrary = libraries.firstOrNull { l -> l.libraryId != library.libraryId }
if (firstOtherLibrary != null) librarySelection.selectBrowserLibrary(firstOtherLibrary.libraryId)
else Promise.empty()
}
}
return promisedNewLibrarySelection.eventually {
Promise.whenAll(
storedItems.disableAllLibraryItems(library.libraryId),
libraryStorage.removeLibrary(library))
}
}
}
| lgpl-3.0 |
Chimerapps/moshi-generator | moshi-generator/src/main/kotlin/com/chimerapps/moshigenerator/SimpleLogger.kt | 1 | 987 | package com.chimerapps.moshigenerator
import java.io.PrintWriter
import java.io.StringWriter
import javax.annotation.processing.Messager
import javax.tools.Diagnostic
/**
* @author Nicola Verbeeck
* Date 26/05/2017.
*/
class SimpleLogger(val messager: Messager) {
fun logInfo(message: String, error: Throwable? = null) {
messager.printMessage(Diagnostic.Kind.NOTE, makeMessage(message, error))
}
fun logError(message: String, error: Throwable? = null) {
messager.printMessage(Diagnostic.Kind.WARNING, makeMessage(message, error))
}
companion object {
private fun makeMessage(message: String, error: Throwable?): String {
if (error == null)
return message
val stringWriter = StringWriter()
PrintWriter(stringWriter).use {
it.println(message)
error.printStackTrace(it)
}
return stringWriter.buffer.toString()
}
}
} | apache-2.0 |
danrien/projectBlueWater | projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/sync/GivenASetOfStoredItems/WhenSyncingTheStoredItemsAndAnErrorOccursDownloading.kt | 1 | 4046 | package com.lasthopesoftware.bluewater.client.stored.library.sync.GivenASetOfStoredItems
import com.lasthopesoftware.bluewater.client.browsing.items.Item
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.ProvideLibraryFiles
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.access.parameters.FileListParameters
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.stored.library.items.IStoredItemAccess
import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItem
import com.lasthopesoftware.bluewater.client.stored.library.items.StoredItemServiceFileCollector
import com.lasthopesoftware.bluewater.client.stored.library.items.files.AccessStoredFiles
import com.lasthopesoftware.bluewater.client.stored.library.items.files.PruneStoredFiles
import com.lasthopesoftware.bluewater.client.stored.library.items.files.StoredFileSystemFileProducer
import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobProcessor
import com.lasthopesoftware.bluewater.client.stored.library.items.files.job.StoredFileJobState
import com.lasthopesoftware.bluewater.client.stored.library.items.files.repository.StoredFile
import com.lasthopesoftware.bluewater.client.stored.library.items.files.updates.UpdateStoredFiles
import com.lasthopesoftware.bluewater.client.stored.library.sync.LibrarySyncsHandler
import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import java.io.ByteArrayInputStream
import java.io.IOException
class WhenSyncingTheStoredItemsAndAnErrorOccursDownloading {
companion object {
private val storedFileJobResults by lazy {
val storedItemAccessMock = mockk<IStoredItemAccess>()
every { storedItemAccessMock.promiseStoredItems(LibraryId(42)) } returns Promise(
setOf(
StoredItem(1, 14, StoredItem.ItemType.ITEM)
)
)
val fileListParameters = FileListParameters.getInstance()
val mockFileProvider = mockk<ProvideLibraryFiles>()
every { mockFileProvider.promiseFiles(LibraryId(42), FileListParameters.Options.None, *fileListParameters.getFileListParameters(Item(14))) } returns Promise(
listOf(
ServiceFile(1),
ServiceFile(2),
ServiceFile(4),
ServiceFile(10)
)
)
val storedFilesPruner = mockk<PruneStoredFiles>()
every { storedFilesPruner.pruneDanglingFiles() } returns Unit.toPromise()
every { storedFilesPruner.pruneStoredFiles(any()) } returns Unit.toPromise()
val storedFilesUpdater = mockk<UpdateStoredFiles>()
every { storedFilesUpdater.promiseStoredFileUpdate(any(), any()) } answers {
Promise(
StoredFile(
firstArg(),
1,
secondArg(),
"fake-file-name",
true
)
)
}
val accessStoredFiles = mockk<AccessStoredFiles>()
every { accessStoredFiles.markStoredFileAsDownloaded(any()) } answers { Promise(firstArg<StoredFile>()) }
val librarySyncHandler = LibrarySyncsHandler(
StoredItemServiceFileCollector(
storedItemAccessMock,
mockFileProvider,
fileListParameters
),
storedFilesPruner,
storedFilesUpdater,
StoredFileJobProcessor(
StoredFileSystemFileProducer(),
accessStoredFiles,
{ _, f ->
if (f.serviceId == 2) Promise(IOException())
else Promise(ByteArrayInputStream(ByteArray(0)))
},
{ true },
{ true },
{ _, _ -> })
)
librarySyncHandler.observeLibrarySync(LibraryId(42))
.filter { j -> j.storedFileJobState == StoredFileJobState.Downloaded }
.map { j -> j.storedFile }
.toList()
.blockingGet()
}
}
@Test
fun thenTheOtherFilesInTheStoredItemsAreSynced() {
assertThat(storedFileJobResults.map { it.serviceId }).containsExactly(1, 4, 10)
}
}
| lgpl-3.0 |
GeoffreyMetais/vlc-android | application/vlc-android/src/org/videolan/vlc/gui/browser/FileBrowserFragment.kt | 1 | 6745 | /*
* *************************************************************************
* FileBrowserFragment.java
* **************************************************************************
* Copyright © 2015 VLC authors and VideoLAN
* Author: Geoffrey Métais
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
* ***************************************************************************
*/
package org.videolan.vlc.gui.browser
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import org.videolan.medialibrary.MLServiceLocator
import org.videolan.medialibrary.interfaces.media.MediaWrapper
import org.videolan.medialibrary.media.MediaLibraryItem
import org.videolan.resources.AndroidDevices
import org.videolan.resources.CTX_FAV_ADD
import org.videolan.tools.removeFileProtocole
import org.videolan.vlc.ExternalMonitor
import org.videolan.vlc.R
import org.videolan.vlc.gui.helpers.MedialibraryUtils
import org.videolan.vlc.gui.helpers.hf.OtgAccess
import org.videolan.vlc.gui.helpers.hf.requestOtgRoot
import org.videolan.vlc.util.FileUtils
import org.videolan.vlc.viewmodels.browser.TYPE_FILE
import org.videolan.vlc.viewmodels.browser.getBrowserModel
@ObsoleteCoroutinesApi
@ExperimentalCoroutinesApi
open class FileBrowserFragment : BaseBrowserFragment() {
private var needsRefresh: Boolean = false
override val categoryTitle: String
get() = getString(R.string.directories)
override fun createFragment(): Fragment {
return FileBrowserFragment()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupBrowser()
}
override fun onStart() {
super.onStart()
if (needsRefresh) viewModel.browseRoot()
}
override fun onStop() {
super.onStop()
if (isRootDirectory && adapter.isEmpty()) needsRefresh = true
}
override fun registerSwiperRefreshlayout() {
if (!isRootDirectory)
super.registerSwiperRefreshlayout()
else
swipeRefreshLayout.isEnabled = false
}
protected open fun setupBrowser() {
viewModel = getBrowserModel(category = TYPE_FILE, url = if (!isRootDirectory) mrl else null, showHiddenFiles = showHiddenFiles)
}
override fun getTitle(): String = if (isRootDirectory)
categoryTitle
else {
when {
currentMedia != null -> when {
TextUtils.equals(AndroidDevices.EXTERNAL_PUBLIC_DIRECTORY, mrl?.removeFileProtocole()) -> getString(R.string.internal_memory)
this is FilePickerFragment -> currentMedia!!.uri.toString()
else -> currentMedia!!.title
}
this is FilePickerFragment -> mrl ?: ""
else -> FileUtils.getFileNameFromPath(mrl)
}
}
public override fun browseRoot() {
viewModel.browseRoot()
}
override fun onClick(v: View, position: Int, item: MediaLibraryItem) {
if (item.itemType == MediaLibraryItem.TYPE_MEDIA) {
val mw = item as MediaWrapper
if ("otg://" == mw.location) {
val title = getString(R.string.otg_device_title)
val rootUri = OtgAccess.otgRoot.value
if (rootUri != null && ExternalMonitor.devices.size == 1) {
browseOtgDevice(rootUri, title)
} else {
lifecycleScope.launchWhenStarted {
val uri = OtgAccess.otgRoot.filterNotNull().first()
browseOtgDevice(uri, title)
}
requireActivity().requestOtgRoot()
}
return
}
}
super.onClick(v, position, item)
}
override fun onCtxAction(position: Int, option: Long) {
val mw = this.adapter.getItem(position) as MediaWrapper?
when (option) {
CTX_FAV_ADD -> lifecycleScope.launch { browserFavRepository.addLocalFavItem(mw!!.uri, mw.title, mw.artworkURL) }
else -> super.onCtxAction(position, option)
}
}
override fun onMainActionClick(v: View, position: Int, item: MediaLibraryItem) {}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
if (!(this is FilePickerFragment || this is StorageBrowserFragment))
inflater.inflate(R.menu.fragment_option_network, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun containerActivity() = requireActivity()
override val isNetwork = false
override val isFile = true
override fun onPrepareOptionsMenu(menu: Menu) {
super.onPrepareOptionsMenu(menu)
val item = menu.findItem(R.id.ml_menu_save) ?: return
item.isVisible = !isRootDirectory && mrl!!.startsWith("file")
lifecycleScope.launchWhenStarted {
mrl?.let {
val isScanned = withContext(Dispatchers.IO) { MedialibraryUtils.isScanned(it) }
menu.findItem(R.id.ml_menu_scan)?.isVisible = !isRootDirectory && it.startsWith("file") && !isScanned
}
val isFavorite = mrl != null && browserFavRepository.browserFavExists(Uri.parse(mrl))
item.setIcon(if (isFavorite)
R.drawable.ic_menu_bookmark_w
else
R.drawable.ic_menu_bookmark_outline_w)
item.setTitle(if (isFavorite) R.string.favorites_remove else R.string.favorites_add)
}
}
private fun browseOtgDevice(uri: Uri, title: String) {
val mw = MLServiceLocator.getAbstractMediaWrapper(uri)
mw.type = MediaWrapper.TYPE_DIR
mw.title = title
handler.post { browse(mw, true) }
}
}
| gpl-2.0 |
AoEiuV020/PaNovel | api/src/test/java/cc/aoeiuv020/panovel/api/site/ZhuajiTest.kt | 1 | 3122 | package cc.aoeiuv020.panovel.api.site
import org.junit.Test
/**
* Created by AoEiuV020 on 2018.06.09-19:48:19.
*/
class ZhuajiTest : BaseNovelContextText(Zhuaji::class) {
@Test
fun search() {
search("都市")
search("麻衣神算子", "骑马钓鱼", "2471")
search("劫天运", "浮梦流年", "2294")
}
@Test
fun detail() {
detail("2471", "2471", "麻衣神算子", "骑马钓鱼",
"https://img.zhuaji.org/2/2471/2471s.jpg",
"爷爷教了我一身算命的本事,却在我帮人算了三次命后,离开了我。\n" +
"从此之后,我不光给活人看命,还要给死人看,更要给……\n" +
"更新:每天中午12点之前一更,下午四点之前一更,加更的话,都在晚上",
"2017-04-20 00:00:00")
detail("2294", "2294", "劫天运", "浮梦流年",
"https://img.zhuaji.org/2/2294/2294s.jpg",
"本书原名《养鬼为祸》\n" +
"我从出生前就给人算计了,五阴俱全,天生招厉鬼,懂行的先生说我活不过七岁,死后是要给人养成血衣小鬼害人的。\n" +
"外婆为了救我,给我娶了童养媳,让我过起了安生日子,虽然后来我发现媳妇姐姐不是人……\n" +
"从小苟延馋喘的我能活到现在,本已习惯逆来顺受,可唯独外婆被人害死了这件事。\n" +
"为此,我不顾因果报应,继承了外婆养鬼的职业,发誓要把害死她的人全都送下地狱。",
"2018-06-09 00:00:00")
}
@Test
fun chapters() {
chapters("2471", "第001章 看相", "2471/913859", null,
"番外(3)", "2471/4984164", null,
1726)
chapters("2294", "第一章 算计", "2294/843846", null,
"第三千七百七十四章 八剑", "2294/14740604", null,
3775)
}
@Test
fun content() {
content("2471/913859",
"我叫李初一,今年二十岁整,跟爷爷相依为命," +
"目前在北方一个小县城经营一家花圈寿衣店," +
"我们店的门脸是自己的房子,一栋两层的小楼,一楼有我们的住房," +
"还有我们那家寿衣店的门脸,二楼是往外租的房子,有四家租户。",
"所以在去之前,我还要好好地打扮一下,把我最好的一面展露在小花和她母亲的面前," +
"当然我还要先去县城的商城里,给小花和她的家人挑选一些拿得出手的礼物。",
39)
content("2294/14740604",
"“未必?你不是说你快要死了,让我们看你坐化登仙么?”修鱼兰玉一脸的诧异,目光带着审视态度。",
"请记住本书首发域名:.。手机版阅读网址:m.",
41)
}
} | gpl-3.0 |
tasks/tasks | app/src/main/java/org/tasks/data/UpgraderDao.kt | 1 | 1030 | package org.tasks.data
import androidx.room.Dao
import androidx.room.Query
@Dao
interface UpgraderDao {
@Query("""
SELECT task.*, caldav_task.*
FROM tasks AS task
INNER JOIN caldav_tasks AS caldav_task ON _id = cd_task
WHERE cd_deleted = 0
""")
suspend fun tasksWithVtodos(): List<CaldavTaskContainer>
@Query("""
SELECT tasks._id
FROM tasks
INNER JOIN tags ON tags.task = tasks._id
INNER JOIN caldav_tasks ON cd_task = tasks._id
GROUP BY tasks._id
""")
suspend fun tasksWithTags(): List<Long>
@Query("""
SELECT task.*, caldav_task.*
FROM tasks AS task
INNER JOIN caldav_tasks AS caldav_task ON _id = cd_task
INNER JOIN caldav_lists ON cd_calendar = cdl_uuid
WHERE cd_deleted = 0
AND cdl_account = :account AND cdl_url = :url
""")
suspend fun getOpenTasksForList(account: String, url: String): List<CaldavTaskContainer>
@Query("UPDATE tasks SET hideUntil = :startDate WHERE _id = :task")
fun setStartDate(task: Long, startDate: Long)
} | gpl-3.0 |
robertwb/incubator-beam | learning/katas/kotlin/Common Transforms/Aggregation/Min/src/org/apache/beam/learning/katas/commontransforms/aggregation/min/Task.kt | 9 | 1635 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.beam.learning.katas.commontransforms.aggregation.min
import org.apache.beam.learning.katas.util.Log
import org.apache.beam.sdk.Pipeline
import org.apache.beam.sdk.options.PipelineOptionsFactory
import org.apache.beam.sdk.transforms.Create
import org.apache.beam.sdk.transforms.Min
import org.apache.beam.sdk.values.PCollection
object Task {
@JvmStatic
fun main(args: Array<String>) {
val options = PipelineOptionsFactory.fromArgs(*args).create()
val pipeline = Pipeline.create(options)
val numbers = pipeline.apply(Create.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
val output = applyTransform(numbers)
output.apply(Log.ofElements())
pipeline.run()
}
@JvmStatic
fun applyTransform(input: PCollection<Int>): PCollection<Int> {
return input.apply(Min.integersGlobally())
}
} | apache-2.0 |
fallGamlet/DnestrCinema | app/src/main/java/com/fallgamlet/dnestrcinema/ui/news/NewsViewModelImpl.kt | 1 | 1272 | package com.fallgamlet.dnestrcinema.ui.news
import androidx.lifecycle.ViewModel
import com.fallgamlet.dnestrcinema.app.AppFacade
import com.fallgamlet.dnestrcinema.domain.models.NewsItem
import com.fallgamlet.dnestrcinema.utils.LiveDataUtils
import com.fallgamlet.dnestrcinema.utils.reactive.mapTrue
import com.fallgamlet.dnestrcinema.utils.reactive.schedulersIoToUi
import com.fallgamlet.dnestrcinema.utils.reactive.subscribeDisposable
class NewsViewModelImpl : ViewModel() {
val viewState = NewsViewState()
private var newsItems: List<NewsItem> = emptyList()
init {
loadData()
}
fun loadData() {
val client = AppFacade.instance.netClient ?: return
viewState.loading.value = true
client.news
.schedulersIoToUi()
.doOnNext { newsItems = it }
.doOnError { viewState.error.value = it }
.mapTrue()
.doOnComplete {
viewState.items.value = newsItems
viewState.loading.value = false
}
.subscribeDisposable()
}
fun refreshViewState() {
LiveDataUtils.refreshSignal(
viewState.error,
viewState.loading
)
viewState.items.value = newsItems
}
}
| gpl-3.0 |
nickthecoder/paratask | paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/table/Column.kt | 1 | 1407 | /*
ParaTask Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.paratask.table
import javafx.beans.value.ObservableValue
import javafx.scene.control.TableColumn
import uk.co.nickthecoder.paratask.util.Labelled
import uk.co.nickthecoder.paratask.util.uncamel
open class Column<R, T>(
val name: String,
width: Int? = null,
override val label: String = name.uncamel(),
val getter: (R) -> T,
val filterGetter: (R) -> Any? = getter)
: TableColumn<WrappedRow<R>, T>(label), Labelled {
init {
@Suppress("UNCHECKED_CAST")
setCellValueFactory { p -> p.value.observable(name, getter) as ObservableValue<T> }
isEditable = false
if (width != null) {
prefWidth = width.toDouble()
}
}
}
| gpl-3.0 |
pgutkowski/KGraphQL | src/test/kotlin/com/github/pgutkowski/kgraphql/specification/language/FragmentsSpecificationTest.kt | 1 | 6246 | package com.github.pgutkowski.kgraphql.specification.language
import com.github.pgutkowski.kgraphql.Actor
import com.github.pgutkowski.kgraphql.RequestException
import com.github.pgutkowski.kgraphql.Specification
import com.github.pgutkowski.kgraphql.assertNoErrors
import com.github.pgutkowski.kgraphql.defaultSchema
import com.github.pgutkowski.kgraphql.deserialize
import com.github.pgutkowski.kgraphql.executeEqualQueries
import com.github.pgutkowski.kgraphql.expect
import com.github.pgutkowski.kgraphql.extract
import com.github.pgutkowski.kgraphql.extractOrNull
import com.github.pgutkowski.kgraphql.integration.BaseSchemaTest
import com.github.pgutkowski.kgraphql.integration.BaseSchemaTest.Companion.INTROSPECTION_QUERY
import org.hamcrest.CoreMatchers
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.not
import org.hamcrest.CoreMatchers.notNullValue
import org.hamcrest.CoreMatchers.nullValue
import org.hamcrest.CoreMatchers.startsWith
import org.hamcrest.MatcherAssert
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
@Specification("2.8 Fragments")
class FragmentsSpecificationTest {
val age = 232
val actorName = "Boguś Linda"
val id = "BLinda"
data class ActorWrapper(val id: String, val actualActor: Actor)
val schema = defaultSchema {
query("actor") {
resolver { -> ActorWrapper(id, Actor(actorName, age)) }
}
}
val BaseTestSchema = object : BaseSchemaTest() {}
@Test
fun `fragment's fields are added to the query at the same level as the fragment invocation`() {
val expected = mapOf("data" to mapOf(
"actor" to mapOf(
"id" to id,
"actualActor" to mapOf("name" to actorName, "age" to age)
))
)
executeEqualQueries(schema,
expected,
"{actor{id, actualActor{name, age}}}",
"{actor{ ...actWrapper}} fragment actWrapper on ActorWrapper {id, actualActor{ name, age }}"
)
}
@Test
fun `fragments can be nested`() {
val expected = mapOf("data" to mapOf(
"actor" to mapOf(
"id" to id,
"actualActor" to mapOf("name" to actorName, "age" to age)
))
)
executeEqualQueries(schema,
expected,
"{actor{id, actualActor{name, age}}}",
"{actor{ ...actWrapper}} fragment act on Actor{name, age} fragment actWrapper on ActorWrapper {id, actualActor{ ...act }}"
)
}
@Test
fun `Inline fragments may also be used to apply a directive to a group of fields`() {
val response = deserialize(schema.execute(
"query (\$expandedInfo : Boolean!){actor{actualActor{name ... @include(if: \$expandedInfo){ age }}}}",
"{\"expandedInfo\":false}"
))
assertNoErrors(response)
assertThat(extractOrNull(response, "data/actor/actualActor/name"), equalTo("Boguś Linda"))
assertThat(extractOrNull(response, "data/actor/actualActor/age"), nullValue())
}
@Test
fun `query with inline fragment with type condition`() {
val map = BaseTestSchema.execute("{people{name, age, ... on Actor {isOld} ... on Director {favActors{name}}}}")
assertNoErrors(map)
for (i in map.extract<List<*>>("data/people").indices) {
val name = map.extract<String>("data/people[$i]/name")
when (name) {
"David Fincher" /* director */ -> {
MatcherAssert.assertThat(map.extract<List<*>>("data/people[$i]/favActors"), CoreMatchers.notNullValue())
MatcherAssert.assertThat(extractOrNull<Boolean>(map, "data/people[$i]/isOld"), CoreMatchers.nullValue())
}
"Brad Pitt" /* actor */ -> {
MatcherAssert.assertThat(map.extract<Boolean>("data/people[$i]/isOld"), CoreMatchers.notNullValue())
MatcherAssert.assertThat(extractOrNull<List<*>>(map, "data/people[$i]/favActors"), CoreMatchers.nullValue())
}
}
}
}
@Test
fun `query with external fragment with type condition`() {
val map = BaseTestSchema.execute("{people{name, age ...act ...dir}} fragment act on Actor {isOld} fragment dir on Director {favActors{name}}")
assertNoErrors(map)
for (i in map.extract<List<*>>("data/people").indices) {
val name = map.extract<String>("data/people[$i]/name")
when (name) {
"David Fincher" /* director */ -> {
MatcherAssert.assertThat(map.extract<List<*>>("data/people[$i]/favActors"), CoreMatchers.notNullValue())
MatcherAssert.assertThat(extractOrNull<Boolean>(map, "data/people[$i]/isOld"), CoreMatchers.nullValue())
}
"Brad Pitt" /* actor */ -> {
MatcherAssert.assertThat(map.extract<Boolean>("data/people[$i]/isOld"), CoreMatchers.notNullValue())
MatcherAssert.assertThat(extractOrNull<List<*>>(map, "data/people[$i]/favActors"), CoreMatchers.nullValue())
}
}
}
}
@Test
fun `multiple nested fragments are handled`() {
val map = BaseTestSchema.execute(INTROSPECTION_QUERY)
val fields = map.extract<List<Map<String,*>>>("data/__schema/types[0]/fields")
fields.forEach { field ->
assertThat(field["name"], notNullValue())
}
}
@Test
fun `queries with recursive fragments are denied`() {
expect<RequestException>("Fragment spread circular references are not allowed"){
BaseTestSchema.execute("""
query IntrospectionQuery {
__schema {
types {
...FullType
}
}
}
fragment FullType on __Type {
fields(includeDeprecated: true) {
name
type {
...FullType
}
}
}
""")
}
}
}
| mit |
nemerosa/ontrack | ontrack-extension-github/src/test/java/net/nemerosa/ontrack/extension/github/indicators/compliance/GitHubComplianceIndicatorsIT.kt | 1 | 7451 | package net.nemerosa.ontrack.extension.github.indicators.compliance
import net.nemerosa.ontrack.extension.github.AbstractGitHubTestSupport
import net.nemerosa.ontrack.extension.github.TestOnGitHub
import net.nemerosa.ontrack.extension.github.catalog.GitHubSCMCatalogSettings
import net.nemerosa.ontrack.extension.github.githubTestEnv
import net.nemerosa.ontrack.extension.indicators.computing.*
import net.nemerosa.ontrack.extension.indicators.model.IndicatorService
import net.nemerosa.ontrack.extension.scm.catalog.CatalogLinkService
import net.nemerosa.ontrack.extension.scm.catalog.SCMCatalog
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class GitHubComplianceIndicatorsIT : AbstractGitHubTestSupport() {
@Autowired
private lateinit var complianceIndicators: GitHubComplianceIndicators
@Autowired
private lateinit var computingService: IndicatorComputingService
@Autowired
private lateinit var indicatorService: IndicatorService
@Autowired
private lateinit var configurableIndicatorService: ConfigurableIndicatorService
@Autowired
private lateinit var repositoryMustHaveDescription: RepositoryMustHaveDescription
@Autowired
private lateinit var repositoryTeamMustHaveDescription: RepositoryTeamMustHaveDescription
@Autowired
private lateinit var repositoryDefaultBranchShouldBeMain: RepositoryDefaultBranchShouldBeMain
@Autowired
private lateinit var repositoryMustHaveMaintainingTeam: RepositoryMustHaveMaintainingTeam
@Autowired
private lateinit var repositoryMustNotHaveAnyAdmin: RepositoryMustNotHaveAnyAdmin
@Autowired
private lateinit var repositoryMustHaveAReadme: RepositoryMustHaveAReadme
// @Autowired
// TODO private lateinit var repositoryShouldBeInternalOrPrivate: RepositoryShouldBeInternalOrPrivate
@Autowired
private lateinit var scmCatalog: SCMCatalog
@Autowired
private lateinit var catalogLinkService: CatalogLinkService
@Test
fun `Getting the list of configurable compliance indicators`() {
val indicators = complianceIndicators.configurableIndicators
// Checks the one about the description is present
assertNotNull(indicators.find { it.id == "github-compliance-repository-team-must-have-description" }) { indicator ->
assertEquals("A repository team MUST have the {regex} expression in its description", indicator.name)
assertEquals(1, indicator.attributes.size)
val attribute = indicator.attributes.first()
assertEquals("regex", attribute.key)
assertEquals("Regular expression", attribute.name)
assertEquals(ConfigurableIndicatorAttributeType.REGEX, attribute.type)
assertEquals(true, attribute.required)
}
}
@TestOnGitHub
fun `Getting all configurable compliance indicators for a given repository`() {
// Saves the compliance indicators (restoring previous values after the test)
repositoryDefaultBranchShouldBeMain.save(enabled = true)
repositoryMustHaveDescription.save(enabled = true)
repositoryMustHaveMaintainingTeam.save(enabled = true)
repositoryTeamMustHaveDescription.save(enabled = true)
repositoryMustNotHaveAnyAdmin.save(enabled = true)
repositoryMustHaveAReadme.save(enabled = true)
// TODO repositoryShouldBeInternalOrPrivate.save(enabled = true)
withSettings(GitHubSCMCatalogSettings::class) {
try {
// Project setup
project {
gitHubRealConfig()
// Make sure to launch the SCM catalog indexation
settingsManagerService.saveSettings(
GitHubSCMCatalogSettings(
orgs = listOf(githubTestEnv.organization),
autoMergeTimeout = GitHubSCMCatalogSettings.DEFAULT_AUTO_MERGE_TIMEOUT,
autoMergeInterval = GitHubSCMCatalogSettings.DEFAULT_AUTO_MERGE_INTERVAL,
)
)
scmCatalog.collectSCMCatalog { println(it) }
catalogLinkService.computeCatalogLinks()
// Saves the list of indicators
computingService.compute(complianceIndicators, this)
// Gets the list of indicators after they have been saved
val indicators = indicatorService.getAllProjectIndicators(this)
// Map key x values
val values = indicators.associate {
it.type.id to it.value
}
// Checks some values
assertEquals(
true,
values[RepositoryDefaultBranchShouldBeMain.ID],
"Test repo default branch should be main"
)
assertEquals(
false,
values[RepositoryMustHaveMaintainingTeam.ID],
"Test repo must has no maintaining team"
)
assertEquals(
true,
values[RepositoryTeamMustHaveDescription.ID],
"Test repo must have a description"
)
assertEquals(true, values[RepositoryMustHaveDescription.ID], "Test repo must have a description")
assertEquals(true, values[RepositoryMustNotHaveAnyAdmin.ID], "Test repo has no admin")
assertEquals(true, values[RepositoryMustHaveAReadme.ID], "Test repo must have a readme")
// TODO assertEquals(false, values[RepositoryShouldBeInternalOrPrivate.ID])
}
} finally {
listOf(
repositoryDefaultBranchShouldBeMain,
repositoryMustHaveDescription,
repositoryMustHaveMaintainingTeam,
repositoryTeamMustHaveDescription,
repositoryMustNotHaveAnyAdmin,
repositoryMustHaveAReadme,
// TODO repositoryShouldBeInternalOrPrivate,
).forEach { it.delete() }
}
}
}
private fun GitHubComplianceCheck<*, *>.save(
enabled: Boolean,
link: String? = null,
values: Map<String, String?> = emptyMap(),
) {
toConfigurableIndicatorType().save(enabled, link, values)
}
private fun ConfigurableIndicatorType<*, *>.save(
enabled: Boolean,
link: String? = null,
values: Map<String, String?> = emptyMap(),
) {
configurableIndicatorService.saveConfigurableIndicator(
type = this,
state = ConfigurableIndicatorState(
enabled = enabled,
link = link,
values = ConfigurableIndicatorState.toAttributeList(this, values),
)
)
}
private fun GitHubComplianceCheck<*, *>.delete() {
toConfigurableIndicatorType().delete()
}
private fun ConfigurableIndicatorType<*, *>.delete() {
configurableIndicatorService.saveConfigurableIndicator(
type = this,
state = null,
)
}
} | mit |
nemerosa/ontrack | ontrack-extension-bitbucket-cloud/src/main/java/net/nemerosa/ontrack/extension/bitbucket/cloud/property/BitbucketCloudConfigurator.kt | 1 | 1710 | package net.nemerosa.ontrack.extension.bitbucket.cloud.property
import net.nemerosa.ontrack.extension.git.model.GitConfiguration
import net.nemerosa.ontrack.extension.git.model.GitConfigurator
import net.nemerosa.ontrack.extension.git.model.GitPullRequest
import net.nemerosa.ontrack.extension.issues.IssueServiceRegistry
import net.nemerosa.ontrack.extension.issues.model.ConfiguredIssueService
import net.nemerosa.ontrack.model.structure.Project
import net.nemerosa.ontrack.model.structure.PropertyService
import org.springframework.stereotype.Component
@Component
class BitbucketCloudConfigurator(
private val propertyService: PropertyService,
private val issueServiceRegistry: IssueServiceRegistry,
): GitConfigurator {
override fun isProjectConfigured(project: Project): Boolean =
propertyService.hasProperty(project, BitbucketCloudProjectConfigurationPropertyType::class.java)
override fun getConfiguration(project: Project): GitConfiguration? =
propertyService.getProperty(project, BitbucketCloudProjectConfigurationPropertyType::class.java)
.value
?.run {
BitbucketCloudGitConfiguration(
this,
getConfiguredIssueService(this)
)
}
override fun getPullRequest(configuration: GitConfiguration, id: Int): GitPullRequest? {
TODO("Not yet implemented")
}
private fun getConfiguredIssueService(property: BitbucketCloudProjectConfigurationProperty): ConfiguredIssueService? =
property.issueServiceConfigurationIdentifier
?.takeIf { it.isNotBlank() }
?.let { issueServiceRegistry.getConfiguredIssueService(it) }
} | mit |
BOINC/boinc | android/BOINC/app/src/test/java/edu/berkeley/boinc/rpc/HostInfoParserTest.kt | 3 | 24652 | /*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2021 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.util.Log
import android.util.Xml
import edu.berkeley.boinc.rpc.HostInfoParser.Companion.parse
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.modules.junit4.PowerMockRunner
import org.xml.sax.ContentHandler
import org.xml.sax.SAXException
@RunWith(PowerMockRunner::class)
@PrepareForTest(Log::class, Xml::class)
class HostInfoParserTest {
private lateinit var hostInfoParser: HostInfoParser
private lateinit var expected: HostInfo
@Before
fun setUp() {
hostInfoParser = HostInfoParser()
expected = HostInfo()
}
@Test(expected = UninitializedPropertyAccessException::class)
fun `When Rpc string is null then expect UninitializedPropertyAccessException`() {
PowerMockito.mockStatic(Xml::class.java)
parse(null)
}
@Test(expected = UninitializedPropertyAccessException::class)
fun `When Rpc string is empty then expect UninitializedPropertyAccessException`() {
PowerMockito.mockStatic(Xml::class.java)
parse("")
}
@Test
@Throws(Exception::class)
fun `When SAXException is thrown then expect null`() {
PowerMockito.mockStatic(Xml::class.java)
PowerMockito.mockStatic(Log::class.java)
PowerMockito.doThrow(SAXException()).`when`(
Xml::class.java, "parse", ArgumentMatchers.anyString(), ArgumentMatchers.any(
ContentHandler::class.java
)
)
Assert.assertNull(parse(""))
}
@Test
@Throws(SAXException::class)
fun `When 'localName' is empty then expect element started`() {
hostInfoParser.startElement(null, "", null, null)
Assert.assertTrue(hostInfoParser.mElementStarted)
}
@Test
@Throws(SAXException::class)
fun `When 'localName' is host_info tag then expect element not started`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
Assert.assertFalse(hostInfoParser.mElementStarted)
}
@Test(expected = UninitializedPropertyAccessException::class)
@Throws(SAXException::class)
fun `When 'localName' is empty then expect UninitializedPropertyAccessException`() {
hostInfoParser.startElement(null, "", null, null)
hostInfoParser.hostInfo
}
@Test
@Throws(SAXException::class)
fun `When 'localName' is host_info tag then expect default HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has timezone then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.TIMEZONE, null, null)
hostInfoParser.characters("1".toCharArray(), 0, 1)
hostInfoParser.endElement(null, HostInfo.Fields.TIMEZONE, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.timezone = 1
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has domain_name and invalid timezone then expect HostInfo with only domain name`() {
PowerMockito.mockStatic(Log::class.java)
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.DOMAIN_NAME, null, null)
hostInfoParser.characters(DOMAIN_NAME.toCharArray(), 0, 11)
hostInfoParser.endElement(null, HostInfo.Fields.DOMAIN_NAME, null)
hostInfoParser.startElement(null, HostInfo.Fields.TIMEZONE, null, null)
hostInfoParser.characters("One".toCharArray(), 0, 3)
hostInfoParser.endElement(null, HostInfo.Fields.TIMEZONE, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.domainName = DOMAIN_NAME
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has domain_name then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.DOMAIN_NAME, null, null)
hostInfoParser.characters(DOMAIN_NAME.toCharArray(), 0, 11)
hostInfoParser.endElement(null, HostInfo.Fields.DOMAIN_NAME, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.domainName = DOMAIN_NAME
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has ip_address then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.IP_ADDR, null, null)
hostInfoParser.characters(IP_ADDRESS.toCharArray(), 0, IP_ADDRESS.length)
hostInfoParser.endElement(null, HostInfo.Fields.IP_ADDR, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.ipAddress = IP_ADDRESS
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has host_cpid then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.HOST_CPID, null, null)
hostInfoParser.characters(HOST_CPID.toCharArray(), 0, HOST_CPID.length)
hostInfoParser.endElement(null, HostInfo.Fields.HOST_CPID, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.hostCpid = HOST_CPID
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has no_of_cpus then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_NCPUS, null, null)
hostInfoParser.characters("1".toCharArray(), 0, 1)
hostInfoParser.endElement(null, HostInfo.Fields.P_NCPUS, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.noOfCPUs = 1
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has vendor then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_VENDOR, null, null)
hostInfoParser.characters(VENDOR.toCharArray(), 0, VENDOR.length)
hostInfoParser.endElement(null, HostInfo.Fields.P_VENDOR, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.cpuVendor = VENDOR
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has model then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_MODEL, null, null)
hostInfoParser.characters(MODEL.toCharArray(), 0, MODEL.length)
hostInfoParser.endElement(null, HostInfo.Fields.P_MODEL, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.cpuModel = MODEL
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has features then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_FEATURES, null, null)
hostInfoParser.characters(FEATURES.toCharArray(), 0, FEATURES.length)
hostInfoParser.endElement(null, HostInfo.Fields.P_FEATURES, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.cpuFeatures = FEATURES
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has floating_point_ops then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_FPOPS, null, null)
hostInfoParser.characters("1.5".toCharArray(), 0, 3)
hostInfoParser.endElement(null, HostInfo.Fields.P_FPOPS, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.cpuFloatingPointOps = 1.5
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has integer_ops then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_IOPS, null, null)
hostInfoParser.characters("1.5".toCharArray(), 0, 3)
hostInfoParser.endElement(null, HostInfo.Fields.P_IOPS, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.cpuIntegerOps = 1.5
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has membw then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_MEMBW, null, null)
hostInfoParser.characters("1.5".toCharArray(), 0, 3)
hostInfoParser.endElement(null, HostInfo.Fields.P_MEMBW, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.cpuMembw = 1.5
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has calculated then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_CALCULATED, null, null)
hostInfoParser.characters("0".toCharArray(), 0, 1)
hostInfoParser.endElement(null, HostInfo.Fields.P_CALCULATED, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.cpuCalculated = 0L
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has product_name then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.PRODUCT_NAME, null, null)
hostInfoParser.characters(PRODUCT_NAME.toCharArray(), 0, PRODUCT_NAME.length)
hostInfoParser.endElement(null, HostInfo.Fields.PRODUCT_NAME, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.productName = PRODUCT_NAME
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has mem_in_bytes then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.M_NBYTES, null, null)
hostInfoParser.characters(BYTES_IN_1_GB_STR.toCharArray(), 0, BYTES_IN_1_GB_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.M_NBYTES, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.memoryInBytes = 1073741824.0
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has mem_cache then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.M_CACHE, null, null)
hostInfoParser.characters(BYTES_IN_1_GB_STR.toCharArray(), 0, BYTES_IN_1_GB_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.M_CACHE, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.memoryCache = 1073741824.0
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has mem_swap then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.M_SWAP, null, null)
hostInfoParser.characters(BYTES_IN_1_GB_STR.toCharArray(), 0, BYTES_IN_1_GB_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.M_SWAP, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.memorySwap = 1073741824.0
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has disk_total then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.D_TOTAL, null, null)
hostInfoParser.characters(TOTAL_SPACE_STR.toCharArray(), 0, TOTAL_SPACE_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.D_TOTAL, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.totalDiskSpace = TOTAL_SPACE.toDouble()
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has disk_free then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.D_FREE, null, null)
hostInfoParser.characters(FREE_SPACE_STR.toCharArray(), 0, FREE_SPACE_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.D_FREE, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.freeDiskSpace = FREE_SPACE.toDouble()
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has os_name then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.OS_NAME, null, null)
hostInfoParser.characters(OS_NAME.toCharArray(), 0, OS_NAME.length)
hostInfoParser.endElement(null, HostInfo.Fields.OS_NAME, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.osName = OS_NAME
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has os_version then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.OS_VERSION, null, null)
hostInfoParser.characters(OS_VERSION.toCharArray(), 0, OS_VERSION.length)
hostInfoParser.endElement(null, HostInfo.Fields.OS_VERSION, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.osVersion = OS_VERSION
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has virtualbox_version then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.VIRTUALBOX_VERSION, null, null)
hostInfoParser.characters(VIRTUALBOX_VERSION.toCharArray(), 0, VIRTUALBOX_VERSION.length)
hostInfoParser.endElement(null, HostInfo.Fields.VIRTUALBOX_VERSION, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.virtualBoxVersion = VIRTUALBOX_VERSION
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
@Test
@Throws(SAXException::class)
fun `When Xml HostInfo has all attributes then expect matching HostInfo`() {
hostInfoParser.startElement(null, HostInfoParser.HOST_INFO_TAG, null, null)
hostInfoParser.startElement(null, HostInfo.Fields.TIMEZONE, null, null)
hostInfoParser.characters("1".toCharArray(), 0, 1)
hostInfoParser.endElement(null, HostInfo.Fields.TIMEZONE, null)
hostInfoParser.startElement(null, HostInfo.Fields.DOMAIN_NAME, null, null)
hostInfoParser.characters(DOMAIN_NAME.toCharArray(), 0, 11)
hostInfoParser.endElement(null, HostInfo.Fields.DOMAIN_NAME, null)
hostInfoParser.startElement(null, HostInfo.Fields.IP_ADDR, null, null)
hostInfoParser.characters(IP_ADDRESS.toCharArray(), 0, IP_ADDRESS.length)
hostInfoParser.endElement(null, HostInfo.Fields.IP_ADDR, null)
hostInfoParser.startElement(null, HostInfo.Fields.HOST_CPID, null, null)
hostInfoParser.characters(HOST_CPID.toCharArray(), 0, HOST_CPID.length)
hostInfoParser.endElement(null, HostInfo.Fields.HOST_CPID, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_NCPUS, null, null)
hostInfoParser.characters("1".toCharArray(), 0, 1)
hostInfoParser.endElement(null, HostInfo.Fields.P_NCPUS, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_VENDOR, null, null)
hostInfoParser.characters(VENDOR.toCharArray(), 0, VENDOR.length)
hostInfoParser.endElement(null, HostInfo.Fields.P_VENDOR, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_MODEL, null, null)
hostInfoParser.characters(MODEL.toCharArray(), 0, MODEL.length)
hostInfoParser.endElement(null, HostInfo.Fields.P_MODEL, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_FEATURES, null, null)
hostInfoParser.characters(FEATURES.toCharArray(), 0, FEATURES.length)
hostInfoParser.endElement(null, HostInfo.Fields.P_FEATURES, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_FPOPS, null, null)
hostInfoParser.characters("1.5".toCharArray(), 0, 3)
hostInfoParser.endElement(null, HostInfo.Fields.P_FPOPS, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_IOPS, null, null)
hostInfoParser.characters("1.5".toCharArray(), 0, 3)
hostInfoParser.endElement(null, HostInfo.Fields.P_IOPS, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_MEMBW, null, null)
hostInfoParser.characters("1.5".toCharArray(), 0, 3)
hostInfoParser.endElement(null, HostInfo.Fields.P_MEMBW, null)
hostInfoParser.startElement(null, HostInfo.Fields.P_CALCULATED, null, null)
hostInfoParser.characters("0".toCharArray(), 0, 1)
hostInfoParser.endElement(null, HostInfo.Fields.P_CALCULATED, null)
hostInfoParser.startElement(null, HostInfo.Fields.PRODUCT_NAME, null, null)
hostInfoParser.characters(PRODUCT_NAME.toCharArray(), 0, PRODUCT_NAME.length)
hostInfoParser.endElement(null, HostInfo.Fields.PRODUCT_NAME, null)
hostInfoParser.startElement(null, HostInfo.Fields.M_NBYTES, null, null)
hostInfoParser.characters(BYTES_IN_1_GB_STR.toCharArray(), 0, BYTES_IN_1_GB_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.M_NBYTES, null)
hostInfoParser.startElement(null, HostInfo.Fields.M_CACHE, null, null)
hostInfoParser.characters(BYTES_IN_1_GB_STR.toCharArray(), 0, BYTES_IN_1_GB_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.M_CACHE, null)
hostInfoParser.startElement(null, HostInfo.Fields.M_SWAP, null, null)
hostInfoParser.characters(BYTES_IN_1_GB_STR.toCharArray(), 0, BYTES_IN_1_GB_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.M_SWAP, null)
hostInfoParser.startElement(null, HostInfo.Fields.D_TOTAL, null, null)
hostInfoParser.characters(TOTAL_SPACE_STR.toCharArray(), 0, TOTAL_SPACE_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.D_TOTAL, null)
hostInfoParser.startElement(null, HostInfo.Fields.D_FREE, null, null)
hostInfoParser.characters(FREE_SPACE_STR.toCharArray(), 0, FREE_SPACE_STR.length)
hostInfoParser.endElement(null, HostInfo.Fields.D_FREE, null)
hostInfoParser.startElement(null, HostInfo.Fields.OS_NAME, null, null)
hostInfoParser.characters(OS_NAME.toCharArray(), 0, OS_NAME.length)
hostInfoParser.endElement(null, HostInfo.Fields.OS_NAME, null)
hostInfoParser.startElement(null, HostInfo.Fields.OS_VERSION, null, null)
hostInfoParser.characters(OS_VERSION.toCharArray(), 0, OS_VERSION.length)
hostInfoParser.endElement(null, HostInfo.Fields.OS_VERSION, null)
hostInfoParser.startElement(null, HostInfo.Fields.VIRTUALBOX_VERSION, null, null)
hostInfoParser.characters(VIRTUALBOX_VERSION.toCharArray(), 0, VIRTUALBOX_VERSION.length)
hostInfoParser.endElement(null, HostInfo.Fields.VIRTUALBOX_VERSION, null)
hostInfoParser.endElement(null, HostInfoParser.HOST_INFO_TAG, null)
expected.timezone = 1
expected.domainName = DOMAIN_NAME
expected.ipAddress = IP_ADDRESS
expected.hostCpid = HOST_CPID
expected.noOfCPUs = 1
expected.cpuVendor = VENDOR
expected.cpuModel = MODEL
expected.cpuFeatures = FEATURES
expected.cpuFloatingPointOps = 1.5
expected.cpuIntegerOps = 1.5
expected.cpuMembw = 1.5
expected.cpuCalculated = 0L
expected.productName = PRODUCT_NAME
expected.memoryInBytes = BYTES_IN_1_GB.toDouble()
expected.memoryCache = BYTES_IN_1_GB.toDouble()
expected.memorySwap = BYTES_IN_1_GB.toDouble()
expected.totalDiskSpace = TOTAL_SPACE.toDouble()
expected.freeDiskSpace = FREE_SPACE.toDouble()
expected.osName = OS_NAME
expected.osVersion = OS_VERSION
expected.virtualBoxVersion = VIRTUALBOX_VERSION
Assert.assertEquals(expected, hostInfoParser.hostInfo)
}
companion object {
private const val BYTES_IN_1_GB = 1073741824
private const val BYTES_IN_1_GB_STR = BYTES_IN_1_GB.toString()
private const val DOMAIN_NAME = "Domain Name"
private const val IP_ADDRESS = "IP Address"
private const val HOST_CPID = "Host CPID"
private const val VENDOR = "Vendor"
private const val MODEL = "Model"
private const val FEATURES = "Features"
private const val PRODUCT_NAME = "Product Name"
private const val TOTAL_SPACE = BYTES_IN_1_GB * 16L
private const val TOTAL_SPACE_STR = TOTAL_SPACE.toString()
private const val FREE_SPACE = BYTES_IN_1_GB * 12L
private const val FREE_SPACE_STR = FREE_SPACE.toString()
private const val OS_NAME = "Android"
private const val OS_VERSION = "Q"
private const val VIRTUALBOX_VERSION = "6.0.18"
}
}
| lgpl-3.0 |
d9n/intellij-rust | src/main/kotlin/org/rust/cargo/CargoConstants.kt | 1 | 547 | package org.rust.cargo
object CargoConstants {
const val MANIFEST_FILE = "Cargo.toml"
const val LOCK_FILE = "Cargo.lock"
const val BUILD_RS_FILE = "build.rs"
const val RUSTC_ENV_VAR = "RUSTC"
const val RUST_BACTRACE_ENV_VAR = "RUST_BACKTRACE"
object Commands {
val RUN = "run"
val TEST = "test"
}
object ProjectLayout {
val binaries = listOf("src/bin")
val sources = listOf("src", "examples")
val tests = listOf("tests", "benches")
val target = "target"
}
}
| mit |
cbeust/kobalt | src/main/kotlin/com/beust/kobalt/plugin/kotlin/KotlinBuildConfig.kt | 3 | 1508 | package com.beust.kobalt.plugin.kotlin
import com.beust.kobalt.Variant
import com.beust.kobalt.api.BuildConfig
import com.beust.kobalt.api.BuildConfigField
import com.beust.kobalt.api.KobaltContext
import com.beust.kobalt.api.Project
import com.beust.kobalt.internal.BaseBuildConfig
import com.google.inject.Singleton
@Singleton
class KotlinBuildConfig : BaseBuildConfig() {
override fun generate(field: BuildConfigField) = with(field) {
" val $name : $type = $value"
}
override fun generateBuildConfig(project: Project, context: KobaltContext, packageName: String, variant: Variant,
buildConfigs: List<BuildConfig>) : String {
val lines = arrayListOf<String>()
with(lines) {
add("package $packageName")
add("")
add("class BuildConfig {")
add(" companion object {")
add(generate("String", "PRODUCT_FLAVOR", "\"" + variant.productFlavor.name + "\""))
add(generate("String", "BUILD_TYPE", "\"" + variant.buildType.name + "\""))
add(generate("Boolean", "DEBUG",
if (variant.productFlavor.name.equals("debug", ignoreCase = true)) {
"true"
} else {
"false"
}))
addAll(generateCommonPart(project, context, buildConfigs))
add(" }")
add("}")
add("")
}
return lines.joinToString("\n")
}
}
| apache-2.0 |
mockk/mockk | modules/mockk/src/commonMain/kotlin/io/mockk/impl/verify/AllCallsCallVerifier.kt | 1 | 1494 | package io.mockk.impl.verify
import io.mockk.Invocation
import io.mockk.MockKGateway
import io.mockk.MockKGateway.VerificationParameters
import io.mockk.RecordedCall
import io.mockk.impl.log.SafeToString
import io.mockk.impl.stub.StubRepository
import io.mockk.impl.verify.VerificationHelpers.allInvocations
import io.mockk.impl.verify.VerificationHelpers.reportCalls
class AllCallsCallVerifier(
stubRepo: StubRepository,
safeToString: SafeToString
) : UnorderedCallVerifier(stubRepo, safeToString) {
override fun verify(
verificationSequence: List<RecordedCall>,
params: VerificationParameters
): MockKGateway.VerificationResult {
val result = super.verify(verificationSequence, params)
if (result.matches) {
val allInvocations = verificationSequence.allInvocations(stubRepo)
val nonMatchingInvocations = allInvocations
.filter { invoke -> doesNotMatchAnyCalls(verificationSequence, invoke) }
if (nonMatchingInvocations.isNotEmpty()) {
return MockKGateway.VerificationResult.Failure(safeToString.exec {
"some calls were not matched: $nonMatchingInvocations" + reportCalls(verificationSequence,
allInvocations)
})
}
}
return result
}
private fun doesNotMatchAnyCalls(calls: List<RecordedCall>, invoke: Invocation) =
!calls.any { call -> call.matcher.match(invoke) }
} | apache-2.0 |
MimiReader/mimi-reader | mimi-app/src/main/java/com/emogoth/android/phone/mimi/db/dao/BoardAccess.kt | 1 | 2102 | package com.emogoth.android.phone.mimi.db.dao
import androidx.room.Dao
import androidx.room.Query
import androidx.room.Update
import com.emogoth.android.phone.mimi.db.MimiDatabase
import com.emogoth.android.phone.mimi.db.models.Board
import io.reactivex.Flowable
import io.reactivex.Single
@Dao
abstract class BoardAccess : BaseDao<Board>() {
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE}")
abstract fun getAll(): Flowable<List<Board>>
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1")
abstract fun getVisibleBoards(): Flowable<List<Board>>
@Query(value = "SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.NAME} ASC")
abstract fun getAllOrderByName(): Flowable<List<Board>>
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.TITLE} ASC")
abstract fun getAllOrderByTitle(): Flowable<List<Board>>
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.ACCESS_COUNT} DESC")
abstract fun getAllOrderByAccessCount(): Flowable<List<Board>>
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.POST_COUNT} DESC")
abstract fun getAllOrderByPostCount(): Flowable<List<Board>>
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.LAST_ACCESSED} DESC")
abstract fun getAllOrderByLastAccessed(): Flowable<List<Board>>
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.FAVORITE} DESC")
abstract fun getAllOrderByFavorite(): Flowable<List<Board>>
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.VISIBLE} == 1 ORDER BY ${Board.ORDER_INDEX} ASC")
abstract fun getAllOrderByCustom(): Flowable<List<Board>>
@Query("SELECT * FROM ${MimiDatabase.BOARDS_TABLE} WHERE ${Board.NAME} = :boardName")
abstract fun getBoard(boardName: String): Single<Board>
@Update
abstract fun updateBoard(vararg board: Board): Int
}
| apache-2.0 |
soywiz/korge | korge/src/commonMain/kotlin/com/soywiz/korge/tiled/TiledMapViewRef.kt | 1 | 1038 | package com.soywiz.korge.tiled
import com.soywiz.korge.debug.*
import com.soywiz.korge.render.*
import com.soywiz.korge.view.*
import com.soywiz.korio.file.*
import com.soywiz.korui.*
class TiledMapViewRef() : Container(), ViewLeaf, ViewFileRef by ViewFileRef.Mixin() {
override suspend fun forceLoadSourceFile(views: Views, currentVfs: VfsFile, sourceFile: String?) {
baseForceLoadSourceFile(views, currentVfs, sourceFile)
removeChildren()
addChild(currentVfs["$sourceFile"].readTiledMap().createView())
}
override fun renderInternal(ctx: RenderContext) {
this.lazyLoadRenderInternal(ctx, this)
super.renderInternal(ctx)
}
override fun buildDebugComponent(views: Views, container: UiContainer) {
container.uiCollapsibleSection("TiledMap") {
uiEditableValue(::sourceFile, kind = UiTextEditableValue.Kind.FILE(views.currentVfs) {
it.extensionLC == "tmx"
})
}
super.buildDebugComponent(views, container)
}
}
| apache-2.0 |
wbrawner/SimpleMarkdown | app/src/play/java/com/wbrawner/simplemarkdown/utility/CrashlyticsErrorHandler.kt | 1 | 892 | package com.wbrawner.simplemarkdown.utility
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.wbrawner.simplemarkdown.BuildConfig
import timber.log.Timber
import kotlin.reflect.KProperty
class CrashlyticsErrorHandler : ErrorHandler {
private val crashlytics = FirebaseCrashlytics.getInstance()
override fun enable(enable: Boolean) {
crashlytics.setCrashlyticsCollectionEnabled(enable)
}
override fun reportException(t: Throwable, message: String?) {
@Suppress("ConstantConditionIf")
if (BuildConfig.DEBUG) {
Timber.e(t, "Caught exception: $message")
}
crashlytics.recordException(t)
}
}
class errorHandlerImpl {
operator fun getValue(thisRef: Any, property: KProperty<*>): ErrorHandler {
return impl
}
companion object {
val impl = CrashlyticsErrorHandler()
}
}
| apache-2.0 |
vondear/RxTools | RxUI/src/main/java/com/tamsiree/rxui/view/dialog/wheel/WheelAdapter.kt | 1 | 616 | package com.tamsiree.rxui.view.dialog.wheel
/**
* @author tamsiree
*/
interface WheelAdapter {
/**
* Gets items count
* @return the count of wheel items
*/
val itemsCount: Int
/**
* Gets a wheel item by index.
*
* @param index the item index
* @return the wheel item text or null
*/
fun getItem(index: Int): String?
/**
* Gets maximum item length. It is used to determine the wheel width.
* If -1 is returned there will be used the default wheel width.
*
* @return the maximum item length or -1
*/
val maximumLength: Int
} | apache-2.0 |
panpf/sketch | sketch/src/androidTest/java/com/github/panpf/sketch/test/decode/internal/DefaultDrawableDecoderTest.kt | 1 | 3737 | /*
* Copyright (C) 2022 panpf <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.panpf.sketch.test.decode.internal
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.github.panpf.sketch.cache.CachePolicy.DISABLED
import com.github.panpf.sketch.datasource.DataFrom
import com.github.panpf.sketch.decode.ImageInfo
import com.github.panpf.sketch.decode.internal.DefaultDrawableDecoder
import com.github.panpf.sketch.request.DisplayRequest
import com.github.panpf.sketch.resize.Precision.LESS_PIXELS
import com.github.panpf.sketch.test.utils.TestAssets
import com.github.panpf.sketch.test.utils.getTestContextAndNewSketch
import com.github.panpf.sketch.test.utils.intrinsicSize
import com.github.panpf.sketch.test.utils.ratio
import com.github.panpf.sketch.test.utils.samplingByTarget
import com.github.panpf.sketch.test.utils.size
import com.github.panpf.sketch.test.utils.toRequestContext
import com.github.panpf.sketch.util.Size
import kotlinx.coroutines.runBlocking
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DefaultDrawableDecoderTest {
@Test
fun testDecode() {
val (context, sketch) = getTestContextAndNewSketch()
val imageSize = Size(1291, 1936)
val resizeSize = Size(500, 400)
val request = DisplayRequest(context, TestAssets.SAMPLE_JPEG_URI) {
resultCachePolicy(DISABLED)
resizeSize(resizeSize)
resizePrecision(LESS_PIXELS)
}
request.let {
runBlocking {
val fetchResult = sketch.components.newFetcher(it).fetch()
DefaultDrawableDecoder.Factory()
.create(sketch, it.toRequestContext(), fetchResult)
.decode()
}
}.apply {
Assert.assertEquals(samplingByTarget(imageSize, resizeSize), drawable.intrinsicSize)
Assert.assertEquals(imageInfo.size.ratio, drawable.intrinsicSize.ratio)
Assert.assertEquals(ImageInfo(1291, 1936, "image/jpeg", 1), imageInfo)
Assert.assertEquals(DataFrom.LOCAL, dataFrom)
Assert.assertEquals(listOf("InSampledTransformed(4)"), transformedList)
}
}
@Test
fun testFactoryEqualsAndHashCode() {
val element1 = DefaultDrawableDecoder.Factory()
val element11 = DefaultDrawableDecoder.Factory()
val element2 = DefaultDrawableDecoder.Factory()
Assert.assertNotSame(element1, element11)
Assert.assertNotSame(element1, element2)
Assert.assertNotSame(element2, element11)
Assert.assertEquals(element1, element1)
Assert.assertEquals(element1, element11)
Assert.assertEquals(element1, element2)
Assert.assertEquals(element2, element11)
Assert.assertNotEquals(element1, null)
Assert.assertNotEquals(element1, Any())
Assert.assertEquals(element1.hashCode(), element1.hashCode())
Assert.assertEquals(element1.hashCode(), element11.hashCode())
Assert.assertEquals(element1.hashCode(), element2.hashCode())
Assert.assertEquals(element2.hashCode(), element11.hashCode())
}
} | apache-2.0 |
edsilfer/star-wars-wiki | app/src/main/java/br/com/edsilfer/android/starwarswiki/view/activities/SplashActivity.kt | 1 | 1021 | package br.com.edsilfer.android.starwarswiki.view.activities
import android.os.Bundle
import br.com.edsilfer.android.starwarswiki.R
import br.com.edsilfer.android.starwarswiki.commons.Router.launchHomepageActivity
import br.com.edsilfer.kotlin_support.extensions.paintStatusBar
import br.com.tyllt.view.contracts.BaseView
import org.jetbrains.anko.doAsync
/**
* Executes splash screen every time application is started
*/
class SplashActivity : BaseActivity(), BaseView {
companion object {
private const val ARG_SPLASH_ENTRY_TIME = 800.toLong()
}
override fun getContext() = this
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
paintStatusBar(android.R.color.black, true)
setContentView(R.layout.activity_splash)
doAsync {
Thread.sleep(ARG_SPLASH_ENTRY_TIME)
runOnUiThread {
launchHomepageActivity(this@SplashActivity)
finish()
}
}
}
}
| apache-2.0 |
stripe/stripe-android | paymentsheet-example/src/androidTestDebug/java/com/stripe/android/test/core/TestConstants.kt | 1 | 688 | package com.stripe.android.test.core
import androidx.test.platform.app.InstrumentationRegistry
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
const val INDIVIDUAL_TEST_TIMEOUT_SECONDS = 90L
const val HOOKS_PAGE_LOAD_TIMEOUT = 60L
const val TEST_IBAN_NUMBER = "DE89370400440532013000"
val testArtifactDirectoryOnDevice by lazy {
val pattern = "yyyy-MM-dd-HH-mm"
val simpleDateFormat = SimpleDateFormat(pattern)
val date = simpleDateFormat.format(Date())
File(
// Path is /data/user/0/com.stripe.android.paymentsheet.example/files/
InstrumentationRegistry.getInstrumentation().targetContext.filesDir,
"$date/"
)
}
| mit |
stripe/stripe-android | payments-core/src/main/java/com/stripe/android/model/parsers/Stripe3ds2AuthResultJsonParser.kt | 1 | 7051 | package com.stripe.android.model.parsers
import com.stripe.android.core.model.StripeJsonUtils.optString
import com.stripe.android.core.model.parsers.ModelJsonParser
import com.stripe.android.model.Stripe3ds2AuthResult
import org.json.JSONArray
import org.json.JSONObject
internal class Stripe3ds2AuthResultJsonParser : ModelJsonParser<Stripe3ds2AuthResult> {
override fun parse(json: JSONObject): Stripe3ds2AuthResult {
return Stripe3ds2AuthResult(
id = json.getString(FIELD_ID),
created = json.getLong(FIELD_CREATED),
liveMode = json.getBoolean(FIELD_LIVEMODE),
source = json.getString(FIELD_SOURCE),
state = json.optString(FIELD_STATE),
ares = json.optJSONObject(FIELD_ARES)?.let {
AresJsonParser().parse(it)
},
error = json.optJSONObject(FIELD_ERROR)?.let {
ThreeDS2ErrorJsonParser().parse(it)
},
fallbackRedirectUrl = optString(json, FIELD_FALLBACK_REDIRECT_URL),
creq = optString(json, FIELD_CREQ)
)
}
internal class AresJsonParser : ModelJsonParser<Stripe3ds2AuthResult.Ares> {
override fun parse(json: JSONObject): Stripe3ds2AuthResult.Ares {
return Stripe3ds2AuthResult.Ares(
threeDSServerTransId = optString(json, FIELD_THREE_DS_SERVER_TRANS_ID),
acsChallengeMandated = optString(json, FIELD_ACS_CHALLENGE_MANDATED),
acsSignedContent = optString(json, FIELD_ACS_SIGNED_CONTENT),
acsTransId = json.getString(FIELD_ACS_TRANS_ID),
acsUrl = optString(json, FIELD_ACS_URL),
authenticationType = optString(json, FIELD_AUTHENTICATION_TYPE),
cardholderInfo = optString(json, FIELD_CARDHOLDER_INFO),
messageType = json.getString(FIELD_MESSAGE_TYPE),
messageVersion = json.getString(FIELD_MESSAGE_VERSION),
sdkTransId = optString(json, FIELD_SDK_TRANS_ID),
transStatus = optString(json, FIELD_TRANS_STATUS),
messageExtension = json.optJSONArray(FIELD_MESSAGE_EXTENSION)?.let {
MessageExtensionJsonParser().parse(it)
}
)
}
private companion object {
private const val FIELD_ACS_CHALLENGE_MANDATED = "acsChallengeMandated"
private const val FIELD_ACS_SIGNED_CONTENT = "acsSignedContent"
private const val FIELD_ACS_TRANS_ID = "acsTransID"
private const val FIELD_ACS_URL = "acsURL"
private const val FIELD_AUTHENTICATION_TYPE = "authenticationType"
private const val FIELD_CARDHOLDER_INFO = "cardholderInfo"
private const val FIELD_MESSAGE_EXTENSION = "messageExtension"
private const val FIELD_MESSAGE_TYPE = "messageType"
private const val FIELD_MESSAGE_VERSION = "messageVersion"
private const val FIELD_SDK_TRANS_ID = "sdkTransID"
private const val FIELD_TRANS_STATUS = "transStatus"
private const val FIELD_THREE_DS_SERVER_TRANS_ID = "threeDSServerTransID"
}
}
internal class MessageExtensionJsonParser :
ModelJsonParser<Stripe3ds2AuthResult.MessageExtension> {
fun parse(jsonArray: JSONArray): List<Stripe3ds2AuthResult.MessageExtension> {
return (0 until jsonArray.length())
.mapNotNull { jsonArray.optJSONObject(it) }
.map { parse(it) }
}
override fun parse(json: JSONObject): Stripe3ds2AuthResult.MessageExtension {
val dataJson = json.optJSONObject(FIELD_DATA)
val data = if (dataJson != null) {
val keys = dataJson.names() ?: JSONArray()
(0 until keys.length())
.map { idx -> keys.getString(idx) }
.map { key -> mapOf(key to dataJson.getString(key)) }
.fold(emptyMap<String, String>()) { acc, map -> acc.plus(map) }
} else {
emptyMap()
}
return Stripe3ds2AuthResult.MessageExtension(
name = optString(json, FIELD_NAME),
criticalityIndicator = json.optBoolean(FIELD_CRITICALITY_INDICATOR),
id = optString(json, FIELD_ID),
data = data.toMap()
)
}
private companion object {
private const val FIELD_NAME = "name"
private const val FIELD_ID = "id"
private const val FIELD_CRITICALITY_INDICATOR = "criticalityIndicator"
private const val FIELD_DATA = "data"
}
}
internal class ThreeDS2ErrorJsonParser : ModelJsonParser<Stripe3ds2AuthResult.ThreeDS2Error> {
override fun parse(json: JSONObject): Stripe3ds2AuthResult.ThreeDS2Error {
return Stripe3ds2AuthResult.ThreeDS2Error(
threeDSServerTransId = json.getString(FIELD_THREE_DS_SERVER_TRANS_ID),
acsTransId = optString(json, FIELD_ACS_TRANS_ID),
dsTransId = optString(json, FIELD_DS_TRANS_ID),
errorCode = json.getString(FIELD_ERROR_CODE),
errorComponent = json.getString(FIELD_ERROR_COMPONENT),
errorDescription = json.getString(FIELD_ERROR_DESCRIPTION),
errorDetail = json.getString(FIELD_ERROR_DETAIL),
errorMessageType = optString(json, FIELD_ERROR_MESSAGE_TYPE),
messageType = json.getString(FIELD_MESSAGE_TYPE),
messageVersion = json.getString(FIELD_MESSAGE_VERSION),
sdkTransId = optString(json, FIELD_SDK_TRANS_ID)
)
}
private companion object {
private const val FIELD_THREE_DS_SERVER_TRANS_ID = "threeDSServerTransID"
private const val FIELD_ACS_TRANS_ID = "acsTransID"
private const val FIELD_DS_TRANS_ID = "dsTransID"
private const val FIELD_ERROR_CODE = "errorCode"
private const val FIELD_ERROR_COMPONENT = "errorComponent"
private const val FIELD_ERROR_DESCRIPTION = "errorDescription"
private const val FIELD_ERROR_DETAIL = "errorDetail"
private const val FIELD_ERROR_MESSAGE_TYPE = "errorMessageType"
private const val FIELD_MESSAGE_TYPE = "messageType"
private const val FIELD_MESSAGE_VERSION = "messageVersion"
private const val FIELD_SDK_TRANS_ID = "sdkTransID"
}
}
private companion object {
private const val FIELD_ID = "id"
private const val FIELD_ARES = "ares"
private const val FIELD_CREATED = "created"
private const val FIELD_CREQ = "creq"
private const val FIELD_ERROR = "error"
private const val FIELD_FALLBACK_REDIRECT_URL = "fallback_redirect_url"
private const val FIELD_LIVEMODE = "livemode"
private const val FIELD_SOURCE = "source"
private const val FIELD_STATE = "state"
}
}
| mit |
stripe/stripe-android | example/src/main/java/com/stripe/example/service/ExampleEphemeralKeyProvider.kt | 1 | 1746 | package com.stripe.example.service
import android.content.Context
import androidx.annotation.Size
import com.stripe.android.EphemeralKeyProvider
import com.stripe.android.EphemeralKeyUpdateListener
import com.stripe.example.Settings
import com.stripe.example.module.BackendApiFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
/**
* An implementation of [EphemeralKeyProvider] that can be used to generate
* ephemeral keys on the backend.
*/
internal class ExampleEphemeralKeyProvider(
backendUrl: String,
private val workContext: CoroutineContext
) : EphemeralKeyProvider {
constructor(context: Context) : this(
Settings(context).backendUrl,
Dispatchers.IO
)
private val backendApi = BackendApiFactory(backendUrl).create()
override fun createEphemeralKey(
@Size(min = 4) apiVersion: String,
keyUpdateListener: EphemeralKeyUpdateListener
) {
CoroutineScope(workContext).launch {
val response =
kotlin.runCatching {
backendApi
.createEphemeralKey(hashMapOf("api_version" to apiVersion))
.string()
}
withContext(Dispatchers.Main) {
response.fold(
onSuccess = {
keyUpdateListener.onKeyUpdate(it)
},
onFailure = {
keyUpdateListener
.onKeyUpdateFailure(0, it.message.orEmpty())
}
)
}
}
}
}
| mit |
syrop/Victor-Events | events/src/main/kotlin/pl/org/seva/events/comm/CommDeleteFragment.kt | 1 | 1858 | /*
* Copyright (C) 2019 Wiktor Nizio
*
* 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/>.
*
* If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp
*/
package pl.org.seva.events.comm
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import kotlinx.android.synthetic.main.fr_comm_delete.*
import kotlinx.coroutines.launch
import pl.org.seva.events.R
import pl.org.seva.events.main.extension.*
class CommDeleteFragment : Fragment(R.layout.fr_comm_delete) {
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
val comm = commViewModel.value.comm
title = getString(R.string.comm_delete_title).replace(NAME_PLACEHOLDER, comm.name)
prompt.text = getString(R.string.comm_delete_prompt).bold(NAME_PLACEHOLDER, comm.name)
ok {
lifecycleScope.launch {
comm.delete()
longToast(getString(R.string.comm_delete_toast).bold(NAME_PLACEHOLDER, comm.name))
back()
}
}
cancel {
back()
}
}
companion object {
const val NAME_PLACEHOLDER = "[name]"
}
}
| gpl-3.0 |
stripe/stripe-android | stripecardscan/src/main/java/com/stripe/android/stripecardscan/payment/card/PanFormatter.kt | 1 | 6266 | package com.stripe.android.stripecardscan.payment.card
/*
* The following are known PAN formats. The information in this table was taken from
* https://baymard.com/checkout-usability/credit-card-patterns and indirectly from
* https://web.archive.org/web/20170822221741/https://www.discovernetwork.com/downloads/IPP_VAR_Compliance.pdf
*
* | ------------------------- | ------- | ------------------------------------ |
* | Issuer | PAN Len | Display Format |
* | ------------------------- | ------- | ------------------------------------ |
* | American Express | 15 | 4 - 6 - 5 |
* | Diners Club International | 14 | 4 - 6 - 4 |
* | Diners Club International | 15 | Unknown |
* | Diners Club International | 16 | 4 - 4 - 4 - 4 |
* | Diners Club International | 17 | Unknown |
* | Diners Club International | 18 | Unknown |
* | Diners Club International | 19 | Unknown |
* | Discover | 16 | 4 - 4 - 4 - 4 |
* | Discover | 17 | Unknown |
* | Discover | 18 | Unknown |
* | Discover | 19 | Unknown |
* | MasterCard | 16 | 4 - 4 - 4 - 4 |
* | MasterCard (Maestro) | 12 | Unknown |
* | MasterCard (Maestro) | 13 | 4 - 4 - 5 |
* | MasterCard (Maestro) | 14 | Unknown |
* | MasterCard (Maestro) | 15 | 4 - 6 - 5 |
* | MasterCard (Maestro) | 16 | 4 - 4 - 4 - 4 |
* | MasterCard (Maestro) | 17 | Unknown |
* | MasterCard (Maestro) | 18 | Unknown |
* | MasterCard (Maestro) | 19 | 4 - 4 - 4 - 4 - 3 |
* | UnionPay | 16 | 4 - 4 - 4 - 4 |
* | UnionPay | 17 | Unknown |
* | UnionPay | 18 | Unknown |
* | UnionPay | 19 | 6 - 13 |
* | Visa | 16 | 4 - 4 - 4 - 4 |
* | ------------------------- | ------- | ------------------------------------ |
*/
/**
* Format a card PAN for display.
*/
internal fun formatPan(pan: String) = normalizeCardNumber(pan).let {
val issuer = getCardIssuer(pan)
val formatter = CUSTOM_PAN_FORMAT_TABLE[issuer]?.get(pan.length)
?: PAN_FORMAT_TABLE[issuer]?.get(pan.length) ?: DEFAULT_PAN_FORMATTERS[pan.length]
formatter?.formatPan(pan) ?: pan
}
/**
* Add a new way to format a PAN
*/
internal fun addFormatPan(cardIssuer: CardIssuer, length: Int, vararg blockSizes: Int) {
CUSTOM_PAN_FORMAT_TABLE.getOrPut(cardIssuer, { mutableMapOf() })[length] =
PanFormatter(*blockSizes)
}
/**
* A class that can format a PAN for display given a list of number block sizes.
*/
private class PanFormatter(vararg blockSizes: Int) {
private val blockIndices = blockSizesToIndicies(blockSizes)
private fun blockSizesToIndicies(blockSizes: IntArray): List<Int> {
var currentIndex = 0
return blockSizes.map {
val newValue = it + currentIndex
currentIndex = newValue
newValue
}
}
/**
* Format the PAN for display using the number block sizes.
*/
fun formatPan(pan: String): String {
val builder = StringBuilder()
for (i in pan.indices) {
if (i in blockIndices) {
builder.append(' ')
}
builder.append(pan[i])
}
return builder.toString()
}
}
/**
* A mapping of [CardIssuer] to length and [PanFormatter]
*/
private val PAN_FORMAT_TABLE: Map<CardIssuer, Map<Int, PanFormatter>> = mapOf(
CardIssuer.AmericanExpress to mapOf(
15 to PanFormatter(4, 6, 5)
),
CardIssuer.DinersClub to mapOf(
14 to PanFormatter(4, 6, 4),
15 to PanFormatter(4, 6, 5), // Best guess
16 to PanFormatter(4, 4, 4, 4),
17 to PanFormatter(4, 4, 4, 5), // Best guess
18 to PanFormatter(4, 4, 4, 6), // Best guess
19 to PanFormatter(4, 4, 4, 4, 3) // Best guess
),
CardIssuer.Discover to mapOf(
16 to PanFormatter(4, 4, 4, 4),
17 to PanFormatter(4, 4, 4, 4, 1), // Best guess
18 to PanFormatter(4, 4, 4, 4, 2), // Best guess
19 to PanFormatter(4, 4, 4, 4, 3) // Best guess
),
CardIssuer.MasterCard to mapOf(
12 to PanFormatter(4, 4, 4), // Best guess
13 to PanFormatter(4, 4, 5),
14 to PanFormatter(4, 6, 4), // Best guess
15 to PanFormatter(4, 6, 5),
16 to PanFormatter(4, 4, 4, 4),
17 to PanFormatter(4, 4, 4, 5), // Best guess
18 to PanFormatter(4, 4, 4, 6), // Best guess
19 to PanFormatter(4, 4, 4, 4, 3) // Best guess
),
CardIssuer.UnionPay to mapOf(
16 to PanFormatter(4, 4, 4, 4),
17 to PanFormatter(4, 4, 4, 5), // Best guess
18 to PanFormatter(4, 4, 4, 6), // Best guess
19 to PanFormatter(6, 13)
),
CardIssuer.Visa to mapOf(
16 to PanFormatter(4, 4, 4, 4)
)
)
/**
* Default length [PanFormatter] mappings.
*/
private val DEFAULT_PAN_FORMATTERS: Map<Int, PanFormatter> = mapOf(
12 to PanFormatter(4, 4, 4),
13 to PanFormatter(4, 4, 5),
14 to PanFormatter(4, 6, 4),
15 to PanFormatter(4, 6, 5),
16 to PanFormatter(4, 4, 4, 4),
17 to PanFormatter(4, 4, 4, 5),
18 to PanFormatter(4, 4, 4, 2),
19 to PanFormatter(4, 4, 4, 4, 3)
)
/**
* A mapping of [CardIssuer] to length and [PanFormatter]
*/
private val CUSTOM_PAN_FORMAT_TABLE: MutableMap<CardIssuer, MutableMap<Int, PanFormatter>> =
mutableMapOf()
| mit |
akvo/akvo-caddisfly | caddisfly-app/app/src/androidTest/java/org/akvo/caddisfly/util/TestHelper.kt | 1 | 13464 | /*
* Copyright (C) Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Caddisfly.
*
* Akvo Caddisfly 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.
*
* Akvo Caddisfly 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 Akvo Caddisfly. If not, see <http://www.gnu.org/licenses/>.
*/
@file:Suppress("DEPRECATION")
package org.akvo.caddisfly.util
import android.app.Activity
import android.content.Intent
import android.content.res.Configuration
import android.content.res.Resources
import android.graphics.drawable.ColorDrawable
import android.os.Build
import android.preference.PreferenceManager
import android.provider.Settings
import android.view.View
import androidx.annotation.StringRes
import androidx.core.content.ContextCompat
import androidx.test.espresso.Espresso
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.NoMatchingViewException
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation
import androidx.test.rule.ActivityTestRule
import androidx.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import androidx.test.runner.lifecycle.Stage.RESUMED
import androidx.test.uiautomator.*
import org.akvo.caddisfly.BuildConfig
import org.akvo.caddisfly.R
import org.akvo.caddisfly.common.AppConstants.FLOW_SURVEY_PACKAGE_NAME
import org.akvo.caddisfly.helper.FileHelper
import org.akvo.caddisfly.helper.FileHelper.getUnitTestImagesFolder
import org.akvo.caddisfly.util.TestUtil.childAtPosition
import org.hamcrest.Matchers.`is`
import org.hamcrest.Matchers.allOf
import org.junit.Assert
import timber.log.Timber
import java.io.File
import java.util.*
lateinit var mDevice: UiDevice
fun isStripPatchAvailable(name: String = "."): Boolean {
val file = File(getUnitTestImagesFolder(), "$name.yuv")
return file.exists()
}
/**
* Skip opening external Survey if the tests are running in Firebase Test Lab
* or if the phone OS is too old
*/
fun skipOpeningExternalApp(model: Int = Build.VERSION_CODES.LOLLIPOP): Boolean {
try {
val testLabSetting: String = Settings.System.getString(
getInstrumentation().targetContext.contentResolver, "firebase.test.lab")
if ("true" == testLabSetting) {
return true
}
} catch (e: IllegalStateException) {
}
return model < Build.VERSION_CODES.LOLLIPOP
}
object TestHelper {
private val STRING_HASH_MAP_EN = HashMap<String, String>()
private val STRING_HASH_MAP_ES = HashMap<String, String>()
private val STRING_HASH_MAP_FR = HashMap<String, String>()
private val STRING_HASH_MAP_IN = HashMap<String, String>()
private lateinit var currentHashMap: Map<String, String>
private var screenshotCount = -1
val currentActivity: Activity
get() {
val currentActivity = arrayOf<Any>({ null })
getInstrumentation().runOnMainSync {
val resumedActivities = ActivityLifecycleMonitorRegistry.getInstance()
.getActivitiesInStage(RESUMED)
if (resumedActivities.iterator().hasNext()) {
currentActivity[0] = resumedActivities.iterator().next() as Activity
}
}
return currentActivity[0] as Activity
}
private fun addString(key: String, vararg values: String) {
STRING_HASH_MAP_EN[key] = values[0]
if (values.size > 1) {
STRING_HASH_MAP_ES[key] = values[1]
STRING_HASH_MAP_FR[key] = values[2]
STRING_HASH_MAP_IN[key] = values[3]
} else {
STRING_HASH_MAP_ES[key] = values[0]
STRING_HASH_MAP_FR[key] = values[0]
STRING_HASH_MAP_IN[key] = values[0]
}
}
fun getString(@StringRes resourceId: Int): String {
return getString(currentActivity, resourceId)
}
fun getString(activity: Activity, @StringRes resourceId: Int): String {
val currentResources = activity.resources
val assets = currentResources.assets
val metrics = currentResources.displayMetrics
val config = Configuration(currentResources.configuration)
config.locale = Locale(BuildConfig.TEST_LANGUAGE)
val res = Resources(assets, metrics, config)
return res.getString(resourceId)
}
fun loadData(activity: Activity, languageCode: String) {
STRING_HASH_MAP_EN.clear()
STRING_HASH_MAP_ES.clear()
STRING_HASH_MAP_FR.clear()
STRING_HASH_MAP_IN.clear()
val currentResources = activity.resources
val assets = currentResources.assets
val metrics = currentResources.displayMetrics
val config = Configuration(currentResources.configuration)
config.locale = Locale(languageCode)
val res = Resources(assets, metrics, config)
addString(TestConstant.LANGUAGE, "English", "Español", "Français", "Bahasa Indonesia")
// addString("otherLanguage", "Français", "English");
addString(TestConstant.FLUORIDE, res.getString(R.string.fluoride))
addString("chlorine", res.getString(R.string.freeChlorine))
addString("survey", res.getString(R.string.survey))
addString("sensors", res.getString(R.string.sensors))
addString("electricalConductivity", res.getString(R.string.electricalConductivity))
addString("unnamedDataPoint", res.getString(R.string.unnamedDataPoint))
addString("createNewDataPoint", res.getString(R.string.addDataPoint))
addString(TestConstant.USE_EXTERNAL_SOURCE, res.getString(R.string.useExternalSource))
addString(TestConstant.GO_TO_TEST, res.getString(R.string.goToTest))
addString("next", res.getString(R.string.next))
// Restore device-specific locale
Resources(assets, metrics, currentResources.configuration)
currentHashMap = when (languageCode) {
"en" -> STRING_HASH_MAP_EN
"es" -> STRING_HASH_MAP_ES
"in" -> STRING_HASH_MAP_IN
else -> STRING_HASH_MAP_FR
}
}
fun takeScreenshot() {
takeScreenshot("app", screenshotCount++)
}
fun takeScreenshot(name: String, page: Int) {
if (BuildConfig.TAKE_SCREENSHOTS) {
val folder = FileHelper.getScreenshotFolder()
val path = File(folder, name + "-" + BuildConfig.TEST_LANGUAGE + "-" +
String.format("%02d", page + 1) + ".png")
if (!folder.exists()) {
folder.mkdirs()
}
mDevice.takeScreenshot(path, 0.1f, 30)
}
}
fun goToMainScreen() {
var found = false
while (!found) {
try {
onView(withId(R.id.button_info)).check(matches(isDisplayed()))
found = true
} catch (e: NoMatchingViewException) {
Espresso.pressBack()
}
}
}
fun activateTestMode() {
// @Suppress("ConstantConditionIf")
// if (!IS_TEST_MODE) {
//
// onView(withId(R.id.button_info)).perform(click())
//
// onView(withText(R.string.about)).check(matches(isDisplayed())).perform(click())
//
// val version = CaddisflyApp.getAppVersion(false)
//
// onView(withText(version)).check(matches(isDisplayed()))
//
// enterDiagnosticMode()
//
// onView(withId(R.id.actionSettings)).perform(click())
//
// clickListViewItem("Test Mode")
// }
goToMainScreen()
}
fun clickExternalSourceButton(index: Int) {
var buttonText = currentHashMap[TestConstant.GO_TO_TEST]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
assert(buttonText != null)
buttonText = buttonText!!.toUpperCase()
}
findButtonInScrollable(buttonText!!)
val buttons = mDevice.findObjects(By.text(buttonText))
if (index < buttons.size) {
buttons[index].click()
} else {
val listView = UiScrollable(UiSelector())
try {
listView.scrollToEnd(1)
} catch (e: UiObjectNotFoundException) {
e.printStackTrace()
}
val buttons1 = mDevice.findObjects(By.text(buttonText))
buttons1[buttons1.size - 1].click()
}
// New Android OS seems to popup a button for external app
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
sleep(1000)
mDevice.findObject(By.text("Akvo Caddisfly")).click()
sleep(1000)
}
mDevice.waitForWindowUpdate("", 2000)
sleep(4000)
}
fun clickExternalSourceButton(text: String) {
try {
var buttonText = currentHashMap[text]
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
assert(buttonText != null)
buttonText = buttonText!!.toUpperCase()
}
findButtonInScrollable(buttonText!!)
mDevice.findObject(UiSelector().text(buttonText)).click()
// New Android OS seems to popup a button for external app
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M && (text == TestConstant.USE_EXTERNAL_SOURCE || text == TestConstant.GO_TO_TEST)) {
sleep(1000)
mDevice.findObject(By.text("Akvo Caddisfly")).click()
sleep(1000)
}
mDevice.waitForWindowUpdate("", 2000)
} catch (e: UiObjectNotFoundException) {
Timber.e(e)
}
}
fun gotoSurveyForm() {
val context = getInstrumentation().context
val intent = context.packageManager.getLaunchIntentForPackage(FLOW_SURVEY_PACKAGE_NAME)
intent?.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK)
context.startActivity(intent)
if (!currentHashMap["unnamedDataPoint"]?.let { clickListViewItem(it) }!!) {
val addButton = mDevice.findObject(UiSelector()
.resourceId("org.akvo.flow:id/add_data_point_fab"))
try {
if (addButton.exists() && addButton.isEnabled) {
addButton.click()
}
} catch (e: UiObjectNotFoundException) {
Timber.e(e)
}
}
}
fun enterDiagnosticMode() {
for (i in 0..9) {
onView(withId(R.id.textVersion)).perform(click())
}
}
fun leaveDiagnosticMode() {
onView(withId(R.id.fabDisableDiagnostics)).perform(click())
}
fun clearPreferences(activityTestRule: ActivityTestRule<*>) {
val prefs = PreferenceManager.getDefaultSharedPreferences(activityTestRule.activity)
prefs.edit().clear().apply()
}
fun navigateUp() {
onView(allOf<View>(withContentDescription(R.string.navigate_up),
isDisplayed())).perform(click())
}
fun isDeviceInitialized(): Boolean {
return ::mDevice.isInitialized
}
fun clickSubmitButton() {
onView(allOf(withId(R.id.buttonSubmit), withText(R.string.submitResult),
childAtPosition(
allOf(withId(R.id.buttonsLayout),
childAtPosition(
withClassName(`is`("android.widget.RelativeLayout")),
2)),
0),
isDisplayed())).perform(click())
}
fun clickCloseButton() {
onView(allOf(withId(R.id.buttonClose), withText(R.string.close),
childAtPosition(
allOf(withId(R.id.buttonsLayout),
childAtPosition(
withClassName(`is`("android.widget.RelativeLayout")),
2)),
1),
isDisplayed())).perform(click())
}
fun clickStartButton() {
onView(allOf(withId(R.id.buttonStart), withText(R.string.start),
childAtPosition(
childAtPosition(
withClassName(`is`<String>("android.widget.RelativeLayout")),
2),
2),
isDisplayed())).perform(click())
}
fun clickSubmitResultButton() {
onView(allOf(withId(R.id.buttonSubmitResult), withText(R.string.submitResult), isDisplayed()))
.perform(click())
}
fun assertBackgroundColor(view: Int, color: Int) {
val bar = currentActivity.findViewById<View>(view)
val actualColor = (bar.background as ColorDrawable).color
val expectedColor = ContextCompat.getColor(currentActivity, color)
Assert.assertEquals(actualColor, expectedColor)
}
}
| gpl-3.0 |
hannesa2/owncloud-android | owncloudData/src/main/java/com/owncloud/android/data/user/datasources/LocalUserDataSource.kt | 2 | 1082 | /**
* ownCloud Android client application
*
* @author Abel García de Prada
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.data.user.datasources
import com.owncloud.android.domain.user.model.UserQuota
interface LocalUserDataSource {
fun saveQuotaForAccount(
accountName: String,
userQuota: UserQuota
)
fun getQuotaForAccount(
accountName: String
): UserQuota?
fun deleteQuotaForAccount(
accountName: String
)
}
| gpl-2.0 |
AndroidX/androidx | glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/ImageProviders.kt | 3 | 1001 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.glance.appwidget
import android.net.Uri
import androidx.glance.ImageProvider
internal class UriImageProvider(val uri: Uri) : ImageProvider {
override fun toString() = "UriImageProvider(uri='$uri')"
}
/**
* Image resource from a URI.
*
* @param uri The URI of the image to be displayed.
*/
fun ImageProvider(uri: Uri): ImageProvider = UriImageProvider(uri)
| apache-2.0 |
Nunnery/MythicDrops | src/main/kotlin/com/tealcube/minecraft/bukkit/mythicdrops/settings/language/command/MythicCustomCreateMessages.kt | 1 | 2428 | /*
* This file is part of MythicDrops, licensed under the MIT License.
*
* Copyright (C) 2019 Richard Harrah
*
* 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.tealcube.minecraft.bukkit.mythicdrops.settings.language.command
import com.squareup.moshi.JsonClass
import com.tealcube.minecraft.bukkit.mythicdrops.api.settings.language.command.CustomCreateMessages
import com.tealcube.minecraft.bukkit.mythicdrops.getNonNullString
import org.bukkit.configuration.ConfigurationSection
@JsonClass(generateAdapter = true)
data class MythicCustomCreateMessages internal constructor(
override val success: String = "",
override val failure: String = "",
override val requiresItem: String = "",
override val requiresItemMeta: String = "",
override val requiresDisplayName: String = ""
) : CustomCreateMessages {
companion object {
fun fromConfigurationSection(configurationSection: ConfigurationSection) = MythicCustomCreateMessages(
success = configurationSection.getNonNullString("success"),
failure = configurationSection.getNonNullString("failure"),
requiresItem = configurationSection.getNonNullString("requires-item"),
requiresItemMeta = configurationSection.getNonNullString("requires-item-meta"),
requiresDisplayName = configurationSection.getNonNullString("requires-display-name")
)
}
}
| mit |
Undin/intellij-rust | src/test/kotlin/org/rust/ide/intentions/ReplaceLineCommentWithBlockCommentIntentionTest.kt | 3 | 1791 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.intentions
class ReplaceLineCommentWithBlockCommentIntentionTest : RsIntentionTestBase(ReplaceLineCommentWithBlockCommentIntention::class) {
fun `test convert single line comment to block`() = doAvailableTest("""
// /*caret*/Hello, World!
""", """
/* /*caret*/Hello, World! */
""")
fun `test convert multiple line comments to block`() = doAvailableTest("""
// First
// /*caret*/Second
// Third
""", """
/*
First
Second
Third
*//*caret*/
""")
fun `test convert multiple line comments with spaces to block`() = doAvailableTest("""
// First
// /*caret*/Second
// Third
""", """
/*
First
Second
Third
*//*caret*/
""")
fun `test convert multiple line comments with indent to block`() = doAvailableTest("""
fn foo() {
// First
// Second/*caret*/
let x = 1;
}
""", """
fn foo() {
/*
First
Second
*/
/*caret*/let x = 1;
}
""")
// TODO: This does not work because EOL comments are children of `RsFunction` and `prevSibling` is `null`
fun `test convert multiple line comments with indent members`() = expect<AssertionError> {
doAvailableTest("""
trait Foo {
// First
// Second/*caret*/
fn foo() {}
}
""", """
trait Foo {
/*
First
Second
*/
/*caret*/fn foo() {}
}
""")
}
}
| mit |
arcuri82/testing_security_development_enterprise_systems | advanced/exercise-solutions/card-game/part-08/cards/src/test/kotlin/org/tsdes/advanced/exercises/cardgame/cards/RestApiTest.kt | 2 | 1828 | package org.tsdes.advanced.exercises.cardgame.cards
import io.restassured.RestAssured
import io.restassured.RestAssured.given
import io.restassured.internal.common.assertion.AssertParameter.notNull
import org.hamcrest.Matchers.*
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.boot.web.server.LocalServerPort
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit.jupiter.SpringExtension
import org.tsdes.advanced.exercises.cardgame.cards.RestApi.Companion.LATEST
import javax.annotation.PostConstruct
@ActiveProfiles("test")
@ExtendWith(SpringExtension::class)
@SpringBootTest(classes = [(Application::class)],
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
internal class RestApiTest{
@LocalServerPort
protected var port = 0
@PostConstruct
fun init(){
RestAssured.baseURI = "http://localhost"
RestAssured.port = port
RestAssured.enableLoggingOfRequestAndResponseIfValidationFails()
}
@Test
fun testGetImg(){
given().get("/api/cards/imgs/001-monster.svg")
.then()
.statusCode(200)
.contentType("image/svg+xml")
.header("cache-control", `is`(notNullValue()))
}
@Test
fun testGetCollection(){
given().get("/api/cards/collection_$LATEST")
.then()
.statusCode(200)
.body("data.cards.size", greaterThan(10))
}
@Test
fun testGetCollectionOldVersion(){
given().get("/api/cards/collection_v0_002")
.then()
.statusCode(200)
.body("data.cards.size", greaterThan(10))
}
} | lgpl-3.0 |
charleskorn/batect | app/src/unitTest/kotlin/batect/docker/client/DockerImagesClientSpec.kt | 1 | 18648 | /*
Copyright 2017-2020 Charles Korn.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package batect.docker.client
import batect.docker.DockerImage
import batect.docker.DockerRegistryCredentialsException
import batect.docker.ImageBuildFailedException
import batect.docker.ImagePullFailedException
import batect.docker.api.ImagesAPI
import batect.docker.build.DockerImageBuildContext
import batect.docker.build.DockerImageBuildContextFactory
import batect.docker.build.DockerfileParser
import batect.docker.pull.DockerImageProgress
import batect.docker.pull.DockerImageProgressReporter
import batect.docker.pull.DockerRegistryCredentials
import batect.docker.pull.DockerRegistryCredentialsProvider
import batect.execution.CancellationContext
import batect.testutils.createForEachTest
import batect.testutils.createLoggerForEachTest
import batect.testutils.equalTo
import batect.testutils.given
import batect.testutils.on
import batect.testutils.runForEachTest
import batect.testutils.withCause
import batect.testutils.withMessage
import batect.utils.Json
import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import com.natpryce.hamkrest.and
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.throws
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.doAnswer
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.eq
import com.nhaarman.mockitokotlin2.mock
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.whenever
import kotlinx.serialization.json.JsonObject
import okio.Sink
import org.mockito.invocation.InvocationOnMock
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
import java.nio.file.Files
object DockerImagesClientSpec : Spek({
describe("a Docker images client") {
val api by createForEachTest { mock<ImagesAPI>() }
val credentialsProvider by createForEachTest { mock<DockerRegistryCredentialsProvider>() }
val imageBuildContextFactory by createForEachTest { mock<DockerImageBuildContextFactory>() }
val dockerfileParser by createForEachTest { mock<DockerfileParser>() }
val logger by createLoggerForEachTest()
val imageProgressReporter by createForEachTest { mock<DockerImageProgressReporter>() }
val imageProgressReporterFactory = { imageProgressReporter }
val client by createForEachTest { DockerImagesClient(api, credentialsProvider, imageBuildContextFactory, dockerfileParser, logger, imageProgressReporterFactory) }
describe("building an image") {
val fileSystem by createForEachTest { Jimfs.newFileSystem(Configuration.unix()) }
val buildDirectory by createForEachTest { fileSystem.getPath("/path/to/build/dir") }
val buildArgs = mapOf(
"some_name" to "some_value",
"some_other_name" to "some_other_value"
)
val dockerfilePath = "some-Dockerfile-path"
val imageTags = setOf("some_image_tag", "some_other_image_tag")
val outputSink by createForEachTest { mock<Sink>() }
val cancellationContext by createForEachTest { mock<CancellationContext>() }
val context = DockerImageBuildContext(emptySet())
given("the Dockerfile exists") {
val resolvedDockerfilePath by createForEachTest { buildDirectory.resolve(dockerfilePath) }
beforeEachTest {
Files.createDirectories(buildDirectory)
Files.createFile(resolvedDockerfilePath)
whenever(imageBuildContextFactory.createFromDirectory(buildDirectory, dockerfilePath)).doReturn(context)
whenever(dockerfileParser.extractBaseImageNames(resolvedDockerfilePath)).doReturn(setOf("nginx:1.13.0", "some-other-image:2.3.4"))
}
given("getting the credentials for the base image succeeds") {
val image1Credentials = mock<DockerRegistryCredentials>()
val image2Credentials = mock<DockerRegistryCredentials>()
beforeEachTest {
whenever(credentialsProvider.getCredentials("nginx:1.13.0")).doReturn(image1Credentials)
whenever(credentialsProvider.getCredentials("some-other-image:2.3.4")).doReturn(image2Credentials)
}
on("a successful build") {
val output = """
|{"stream":"Step 1/5 : FROM nginx:1.13.0"}
|{"status":"pulling the image"}
|{"stream":"\n"}
|{"stream":" ---\u003e 3448f27c273f\n"}
|{"stream":"Step 2/5 : RUN apt update \u0026\u0026 apt install -y curl \u0026\u0026 rm -rf /var/lib/apt/lists/*"}
|{"stream":"\n"}
|{"stream":" ---\u003e Using cache\n"}
|{"stream":" ---\u003e 0ceae477da9d\n"}
|{"stream":"Step 3/5 : COPY index.html /usr/share/nginx/html"}
|{"stream":"\n"}
|{"stream":" ---\u003e b288a67b828c\n"}
|{"stream":"Step 4/5 : COPY health-check.sh /tools/"}
|{"stream":"\n"}
|{"stream":" ---\u003e 951e32ae4f76\n"}
|{"stream":"Step 5/5 : HEALTHCHECK --interval=2s --retries=1 CMD /tools/health-check.sh"}
|{"stream":"\n"}
|{"stream":" ---\u003e Running in 3de7e4521d69\n"}
|{"stream":"Removing intermediate container 3de7e4521d69\n"}
|{"stream":" ---\u003e 24125bbc6cbe\n"}
|{"aux":{"ID":"sha256:24125bbc6cbe08f530e97c81ee461357fa3ba56f4d7693d7895ec86671cf3540"}}
|{"stream":"Successfully built 24125bbc6cbe\n"}
""".trimMargin()
val imagePullProgress = DockerImageProgress("Doing something", 10, 20)
beforeEachTest {
stubProgressUpdate(imageProgressReporter, output.lines()[0], imagePullProgress)
whenever(api.build(any(), any(), any(), any(), any(), any(), any(), any())).doAnswer(sendProgressAndReturnImage(output, DockerImage("some-image-id")))
}
val statusUpdates by createForEachTest { mutableListOf<DockerImageBuildProgress>() }
val onStatusUpdate = fun(p: DockerImageBuildProgress) {
statusUpdates.add(p)
}
val result by runForEachTest { client.build(buildDirectory, buildArgs, dockerfilePath, imageTags, outputSink, cancellationContext, onStatusUpdate) }
it("builds the image") {
verify(api).build(eq(context), eq(buildArgs), eq(dockerfilePath), eq(imageTags), eq(setOf(image1Credentials, image2Credentials)), eq(outputSink), eq(cancellationContext), any())
}
it("returns the ID of the created image") {
assertThat(result.id, equalTo("some-image-id"))
}
it("sends status updates as the build progresses") {
assertThat(
statusUpdates, equalTo(
listOf(
DockerImageBuildProgress(1, 5, "FROM nginx:1.13.0", null),
DockerImageBuildProgress(1, 5, "FROM nginx:1.13.0", imagePullProgress),
DockerImageBuildProgress(2, 5, "RUN apt update && apt install -y curl && rm -rf /var/lib/apt/lists/*", null),
DockerImageBuildProgress(3, 5, "COPY index.html /usr/share/nginx/html", null),
DockerImageBuildProgress(4, 5, "COPY health-check.sh /tools/", null),
DockerImageBuildProgress(5, 5, "HEALTHCHECK --interval=2s --retries=1 CMD /tools/health-check.sh", null)
)
)
)
}
}
on("the daemon sending image pull information before sending any step progress information") {
val output = """
|{"status":"pulling the image"}
|{"stream":"Step 1/5 : FROM nginx:1.13.0"}
|{"status":"pulling the image"}
|{"stream":"\n"}
|{"stream":" ---\u003e 3448f27c273f\n"}
|{"stream":"Step 2/5 : RUN apt update \u0026\u0026 apt install -y curl \u0026\u0026 rm -rf /var/lib/apt/lists/*"}
""".trimMargin()
val imagePullProgress = DockerImageProgress("Doing something", 10, 20)
val statusUpdates by createForEachTest { mutableListOf<DockerImageBuildProgress>() }
beforeEachTest {
stubProgressUpdate(imageProgressReporter, output.lines()[0], imagePullProgress)
whenever(api.build(any(), any(), any(), any(), any(), any(), any(), any())).doAnswer(sendProgressAndReturnImage(output, DockerImage("some-image-id")))
val onStatusUpdate = fun(p: DockerImageBuildProgress) {
statusUpdates.add(p)
}
client.build(buildDirectory, buildArgs, dockerfilePath, imageTags, outputSink, cancellationContext, onStatusUpdate)
}
it("sends status updates only once the first step is started") {
assertThat(
statusUpdates, equalTo(
listOf(
DockerImageBuildProgress(1, 5, "FROM nginx:1.13.0", null),
DockerImageBuildProgress(1, 5, "FROM nginx:1.13.0", imagePullProgress),
DockerImageBuildProgress(2, 5, "RUN apt update && apt install -y curl && rm -rf /var/lib/apt/lists/*", null)
)
)
)
}
}
}
given("getting credentials for the base image fails") {
val exception = DockerRegistryCredentialsException("Could not load credentials: something went wrong.")
beforeEachTest {
whenever(credentialsProvider.getCredentials("nginx:1.13.0")).thenThrow(exception)
}
on("building the image") {
it("throws an appropriate exception") {
assertThat(
{ client.build(buildDirectory, buildArgs, dockerfilePath, imageTags, outputSink, cancellationContext, {}) }, throws<ImageBuildFailedException>(
withMessage("Could not build image: Could not load credentials: something went wrong.")
and withCause(exception)
)
)
}
}
}
}
given("the Dockerfile does not exist") {
on("building the image") {
it("throws an appropriate exception") {
assertThat(
{ client.build(buildDirectory, buildArgs, dockerfilePath, imageTags, outputSink, cancellationContext, {}) },
throws<ImageBuildFailedException>(withMessage("Could not build image: the Dockerfile 'some-Dockerfile-path' does not exist in '/path/to/build/dir'"))
)
}
}
}
given("the Dockerfile exists but is not a child of the build directory") {
val dockerfilePathOutsideBuildDir = "../some-Dockerfile"
val resolvedDockerfilePath by createForEachTest { buildDirectory.resolve(dockerfilePathOutsideBuildDir) }
beforeEachTest {
Files.createDirectories(buildDirectory)
Files.createFile(resolvedDockerfilePath)
}
on("building the image") {
it("throws an appropriate exception") {
assertThat(
{ client.build(buildDirectory, buildArgs, dockerfilePathOutsideBuildDir, imageTags, outputSink, cancellationContext, {}) },
throws<ImageBuildFailedException>(withMessage("Could not build image: the Dockerfile '../some-Dockerfile' is not a child of '/path/to/build/dir'"))
)
}
}
}
}
describe("pulling an image") {
val cancellationContext by createForEachTest { mock<CancellationContext>() }
given("the image does not exist locally") {
beforeEachTest {
whenever(api.hasImage("some-image")).thenReturn(false)
}
given("getting credentials for the image succeeds") {
val credentials = mock<DockerRegistryCredentials>()
beforeEachTest {
whenever(credentialsProvider.getCredentials("some-image")).thenReturn(credentials)
}
on("pulling the image") {
val firstProgressUpdate = Json.parser.parseJson("""{"thing": "value"}""").jsonObject
val secondProgressUpdate = Json.parser.parseJson("""{"thing": "other value"}""").jsonObject
beforeEachTest {
whenever(imageProgressReporter.processProgressUpdate(firstProgressUpdate)).thenReturn(DockerImageProgress("Doing something", 10, 20))
whenever(imageProgressReporter.processProgressUpdate(secondProgressUpdate)).thenReturn(null)
whenever(api.pull(any(), any(), any(), any())).then { invocation ->
@Suppress("UNCHECKED_CAST")
val onProgressUpdate = invocation.arguments[3] as (JsonObject) -> Unit
onProgressUpdate(firstProgressUpdate)
onProgressUpdate(secondProgressUpdate)
null
}
}
val progressUpdatesReceived by createForEachTest { mutableListOf<DockerImageProgress>() }
val image by runForEachTest { client.pull("some-image", cancellationContext) { progressUpdatesReceived.add(it) } }
it("calls the Docker CLI to pull the image") {
verify(api).pull(eq("some-image"), eq(credentials), eq(cancellationContext), any())
}
it("sends notifications for all relevant progress updates") {
assertThat(progressUpdatesReceived, equalTo(listOf(DockerImageProgress("Doing something", 10, 20))))
}
it("returns the Docker image") {
assertThat(image, equalTo(DockerImage("some-image")))
}
}
}
given("getting credentials for the image fails") {
val exception = DockerRegistryCredentialsException("Could not load credentials: something went wrong.")
beforeEachTest {
whenever(credentialsProvider.getCredentials("some-image")).thenThrow(exception)
}
on("pulling the image") {
it("throws an appropriate exception") {
assertThat({ client.pull("some-image", cancellationContext, {}) }, throws<ImagePullFailedException>(
withMessage("Could not pull image 'some-image': Could not load credentials: something went wrong.")
and withCause(exception)
))
}
}
}
}
on("when the image already exists locally") {
beforeEachTest { whenever(api.hasImage("some-image")).thenReturn(true) }
val image by runForEachTest { client.pull("some-image", cancellationContext, {}) }
it("does not call the Docker CLI to pull the image again") {
verify(api, never()).pull(any(), any(), any(), any())
}
it("returns the Docker image") {
assertThat(image, equalTo(DockerImage("some-image")))
}
}
}
}
})
private fun stubProgressUpdate(reporter: DockerImageProgressReporter, input: String, update: DockerImageProgress) {
val json = Json.parser.parseJson(input).jsonObject
whenever(reporter.processProgressUpdate(eq(json))).thenReturn(update)
}
private fun sendProgressAndReturnImage(progressUpdates: String, image: DockerImage) = { invocation: InvocationOnMock ->
@Suppress("UNCHECKED_CAST")
val onProgressUpdate = invocation.arguments.last() as (JsonObject) -> Unit
progressUpdates.lines().forEach { line ->
onProgressUpdate(Json.parser.parseJson(line).jsonObject)
}
image
}
| apache-2.0 |
petropavel13/2photo-android | TwoPhoto/app/src/main/java/com/github/petropavel13/twophoto/model/LimitedResultsList.kt | 1 | 382 | package com.github.petropavel13.twophoto.model
import com.google.api.client.util.Key
/**
* Created by petropavel on 25/03/15.
*/
abstract class LimitedResultsList<RESULTS_TYPE> {
@Key public var count: Int = 0
@Key public var next: String? = null
@Key public var previous: String? = null
@Key public var results: List<RESULTS_TYPE> = emptyList<RESULTS_TYPE>()
} | mit |
androidx/androidx | camera/camera-camera2-pipe-integration/src/main/java/androidx/camera/camera2/pipe/integration/adapter/CamcorderProfileProviderAdapter.kt | 3 | 3469 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.integration.adapter
import android.media.CamcorderProfile
import android.os.Build
import androidx.annotation.Nullable
import androidx.annotation.RequiresApi
import androidx.camera.core.Logger
import androidx.camera.core.impl.CamcorderProfileProvider
import androidx.camera.core.impl.CamcorderProfileProxy
/**
* Adapt the [CamcorderProfileProvider] interface to [CameraPipe].
*/
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
class CamcorderProfileProviderAdapter(cameraIdString: String) : CamcorderProfileProvider {
private val hasValidCameraId: Boolean
private val cameraId: Int
init {
var hasValidCameraId = false
var intCameraId = -1
try {
intCameraId = cameraIdString.toInt()
hasValidCameraId = true
} catch (e: NumberFormatException) {
Logger.w(
TAG,
"Camera id is not an integer: " +
"$cameraIdString, unable to create CamcorderProfileProvider"
)
}
this.hasValidCameraId = hasValidCameraId
cameraId = intCameraId
// TODO(b/241296464): CamcorderProfileResolutionQuirk and CamcorderProfileResolutionValidator
}
override fun hasProfile(quality: Int): Boolean {
if (!hasValidCameraId) {
return false
}
return CamcorderProfile.hasProfile(cameraId, quality)
// TODO: b241296464 CamcorderProfileResolutionQuirk and
// CamcorderProfileResolutionValidator. If has quick, check if the proxy profile has
// valid video resolution
}
override fun get(quality: Int): CamcorderProfileProxy? {
if (!hasValidCameraId) {
return null
}
return if (!CamcorderProfile.hasProfile(cameraId, quality)) {
null
} else getProfileInternal(quality)
// TODO: b241296464 CamcorderProfileResolutionQuirk and
// CamcorderProfileResolutionValidator. If has quick, check if the proxy profile has
// valid video resolution
}
@Nullable
@Suppress("DEPRECATION")
private fun getProfileInternal(quality: Int): CamcorderProfileProxy? {
var profile: CamcorderProfile? = null
try {
profile = CamcorderProfile.get(cameraId, quality)
} catch (e: RuntimeException) {
// CamcorderProfile.get() will throw
// - RuntimeException if not able to retrieve camcorder profile params.
// - IllegalArgumentException if quality is not valid.
Logger.w(TAG, "Unable to get CamcorderProfile by quality: $quality", e)
}
return if (profile != null) CamcorderProfileProxy.fromCamcorderProfile(profile) else null
}
companion object {
private const val TAG = "CamcorderProfileProviderAdapter"
}
} | apache-2.0 |
androidx/androidx | compose/integration-tests/demos/src/main/java/androidx/compose/integration/demos/Demos.kt | 3 | 1496 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.integration.demos
import androidx.compose.animation.demos.AnimationDemos
import androidx.compose.foundation.demos.FoundationDemos
import androidx.compose.foundation.layout.demos.LayoutDemos
import androidx.compose.integration.demos.common.DemoCategory
import androidx.compose.foundation.demos.text.TextDemos
import androidx.compose.material.demos.MaterialDemos
import androidx.compose.material3.demos.Material3Demos
import androidx.compose.ui.demos.CoreDemos
import androidx.navigation.compose.demos.NavigationDemos
/**
* [DemoCategory] containing all the top level demo categories.
*/
val AllDemosCategory = DemoCategory(
"Jetpack Compose Demos",
listOf(
AnimationDemos,
FoundationDemos,
CoreDemos,
LayoutDemos,
MaterialDemos,
Material3Demos,
NavigationDemos,
TextDemos
)
) | apache-2.0 |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/util/BottomOffsetDecoration.kt | 1 | 826 | package org.thoughtcrime.securesms.util
import android.graphics.Rect
import android.view.View
import androidx.annotation.Px
import androidx.recyclerview.widget.RecyclerView
/**
* Adds some empty space to the bottom of a recyclerview. Useful if you need some "dead space" at the bottom of the list to account for floating menus that may
* otherwise cover up the bottom entries of the list.
*/
class BottomOffsetDecoration(@Px private val bottomOffset: Int) : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
super.getItemOffsets(outRect, view, parent, state)
if (parent.getChildAdapterPosition(view) == state.itemCount - 1) {
outRect.set(0, 0, 0, bottomOffset)
} else {
outRect.set(0, 0, 0, 0)
}
}
}
| gpl-3.0 |
nrizzio/Signal-Android | app/src/main/java/org/thoughtcrime/securesms/contacts/sync/CdsTemporaryErrorBottomSheet.kt | 1 | 2552 | package org.thoughtcrime.securesms.contacts.sync
import android.content.ActivityNotFoundException
import android.content.Intent
import android.os.Bundle
import android.view.ContextThemeWrapper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.fragment.app.FragmentManager
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.FixedRoundedCornerBottomSheetDialogFragment
import org.thoughtcrime.securesms.databinding.CdsTemporaryErrorBottomSheetBinding
import org.thoughtcrime.securesms.keyvalue.SignalStore
import org.thoughtcrime.securesms.util.BottomSheetUtil
import org.thoughtcrime.securesms.util.CommunicationActions
import kotlin.time.Duration.Companion.milliseconds
/**
* Bottom sheet shown when CDS is rate-limited, preventing us from temporarily doing a refresh.
*/
class CdsTemporaryErrorBottomSheet : FixedRoundedCornerBottomSheetDialogFragment() {
private lateinit var binding: CdsTemporaryErrorBottomSheetBinding
override val peekHeightPercentage: Float = 0.75f
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = CdsTemporaryErrorBottomSheetBinding.inflate(inflater.cloneInContext(ContextThemeWrapper(inflater.context, themeResId)), container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val days: Int = (SignalStore.misc().cdsBlockedUtil - System.currentTimeMillis()).milliseconds.inWholeDays.toInt()
binding.timeText.text = resources.getQuantityString(R.plurals.CdsTemporaryErrorBottomSheet_body1, days, days)
binding.learnMoreButton.setOnClickListener {
CommunicationActions.openBrowserLink(requireContext(), "https://support.signal.org/hc/articles/360007319011#android_contacts_error")
}
binding.settingsButton.setOnClickListener {
val intent = Intent().apply {
action = Intent.ACTION_VIEW
data = android.provider.ContactsContract.Contacts.CONTENT_URI
}
try {
startActivity(intent)
} catch (e: ActivityNotFoundException) {
Toast.makeText(context, R.string.CdsPermanentErrorBottomSheet_no_contacts_toast, Toast.LENGTH_SHORT).show()
}
}
}
companion object {
@JvmStatic
fun show(fragmentManager: FragmentManager) {
val fragment = CdsTemporaryErrorBottomSheet()
fragment.show(fragmentManager, BottomSheetUtil.STANDARD_BOTTOM_SHEET_FRAGMENT_TAG)
}
}
}
| gpl-3.0 |
klazuka/intellij-elm | src/test/kotlin/org/elm/lang/core/lexer/ElmLexerTestCaseBase.kt | 1 | 2832 | /*
The MIT License (MIT)
Derived from intellij-rust
Copyright (c) 2015 Aleksey Kladov, Evgeny Kurbatsky, Alexey Kudinkin and contributors
Copyright (c) 2016 JetBrains
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 org.elm.lang.core.lexer
import com.intellij.lexer.Lexer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.util.text.StringUtil
import com.intellij.openapi.vfs.CharsetToolkit
import com.intellij.testFramework.LexerTestCase
import com.intellij.testFramework.UsefulTestCase
import org.elm.lang.ElmTestCase
import org.elm.lang.pathToGoldTestFile
import org.elm.lang.pathToSourceTestFile
import org.jetbrains.annotations.NonNls
import java.io.IOException
abstract class ElmLexerTestCaseBase : LexerTestCase(), ElmTestCase {
override fun getDirPath(): String = throw UnsupportedOperationException()
// NOTE(matkad): this is basically a copy-paste of doFileTest.
// The only difference is that encoding is set to utf-8
protected fun doTest(lexer: Lexer = createLexer()) {
val filePath = pathToSourceTestFile(getTestName(false))
var text = ""
try {
val fileText = FileUtil.loadFile(filePath.toFile(), CharsetToolkit.UTF8)
text = StringUtil.convertLineSeparators(if (shouldTrim()) fileText.trim() else fileText)
} catch (e: IOException) {
fail("can't load file " + filePath + ": " + e.message)
}
doTest(text, null, lexer)
}
override fun doTest(@NonNls text: String, expected: String?, lexer: Lexer) {
val result = printTokens(text, 0, lexer)
if (expected != null) {
UsefulTestCase.assertSameLines(expected, result)
} else {
UsefulTestCase.assertSameLinesWithFile(pathToGoldTestFile(getTestName(false)).toFile().canonicalPath, result)
}
}
}
| mit |
DemonWav/StatCraft | src/main/kotlin/com/demonwav/statcraft/ExtFunctions.kt | 1 | 8491 | /*
* StatCraft Bukkit Plugin
*
* Copyright (c) 2016 Kyle Wood (DemonWav)
* https://www.demonwav.com
*
* MIT License
*/
package com.demonwav.statcraft
import com.mysema.query.QueryException
import com.mysema.query.sql.RelationalPath
import com.mysema.query.sql.SQLQuery
import com.mysema.query.sql.dml.SQLInsertClause
import com.mysema.query.sql.dml.SQLUpdateClause
import java.nio.ByteBuffer
import java.sql.Connection
import java.util.UUID
inline fun <T : AutoCloseable, R> T.use(block: T.() -> R): R {
var closed = false
try {
return block()
} catch (e: Exception) {
closed = true
try {
close()
} catch (closeException: Exception) {}
throw e
} finally {
if (!closed) {
close()
}
}
}
fun UUID.toByte(): ByteArray {
val byteBuffer = ByteBuffer.wrap(ByteArray(16))
byteBuffer.putLong(mostSignificantBits)
byteBuffer.putLong(leastSignificantBits)
return byteBuffer.array()
}
fun ByteArray.toUUID(): UUID {
val buffer = ByteBuffer.wrap(this)
return UUID(buffer.long, buffer.long)
}
inline fun <T> MutableIterable<T>.iter(func: MutableIterator<T>.(T) -> Unit) {
val iter = iterator()
while (iter.hasNext()) {
val item = iter.next()
iter.func(item)
}
}
/**
* Run an insert/update query on the given table. This method handles the clause object creation and fall-through
* to update when insert fails. This method run on the thread it is called, all threading must be managed by the
* caller.
*
* @param insertClause The action to run for the insert query
* @param updateClause The action to run for the update query if the insert fails
* @param plugin The StatCraft object
*/
/* TODO inline */ fun <T : RelationalPath<*>> T.runQuery(insertClause: (T, SQLInsertClause) -> Unit,
updateClause: (T, SQLUpdateClause) -> Unit,
connection: Connection,
plugin: StatCraft) {
try {
val clause = plugin.databaseManager.getInsertClause(connection, this) ?: return
insertClause(this, clause)
} catch (e: QueryException) {
val clause = plugin.databaseManager.getUpdateClause(connection, this) ?: return
updateClause(this, clause)
}
}
/**
* Run an insert/update query on the given table. This method handles the clause object creation and fall-through
* to update when insert fails. This method run on the thread it is called, all threading must be managed by the
* caller. This also allows work to be done before the insert and update queries. The work function can return any
* object, and this object will be passed to the insert and update functions, and in that order. Because of this, if
* the object is modified in the insert function, these modifications will be present in the update function.
*
* @param workBefore The action to run before the queries, returning an object which will be passed to the two queries
* @param insertClause The action to run for the insert query
* @param updateClause The action to run for the update query if the insert fails
* @param plugin The StatCraft object
*/
/* TODO inline */ fun <T : RelationalPath<*>, R> T.runQuery(workBefore: (T, SQLQuery) -> R,
insertClause: (T, SQLInsertClause, R) -> Unit,
updateClause: (T, SQLUpdateClause, R) -> Unit,
connection: Connection,
plugin: StatCraft) {
val r = workBefore(this, plugin.databaseManager.getNewQuery(connection) ?: return)
try {
val clause = plugin.databaseManager.getInsertClause(connection, this) ?: return
insertClause(this, clause, r)
} catch (e: QueryException) {
val clause = plugin.databaseManager.getUpdateClause(connection, this) ?: return
updateClause(this, clause, r)
}
}
/**
* Run an insert/update query on the given table. This method handles the clause object creation and fall-through
* to update when insert fails. This method run on the thread it is called, all threading must be managed by the
* caller.
*
* For convenience this method also allows a player's UUID and world UUID to be passed in. The database id of the
* player and world will be fetched before the insert and update functions are called, and the id will be passed to
* them. This is not an expensive operation as both of these values are cached.
*
* Thanks to type inferencing no type parameters should need to be explicitly provided.
*
* @param playerId The UUID of the relevant player
* @param worldName The UUID of the relevant world
* @param insertClause The action to run for the insert query
* @param updateClause The action to run for the update query if the insert fails
* @param plugin The StatCraft object
*/
/* TODO inline */ fun <T : RelationalPath<*>> T.runQuery(playerId: UUID,
worldName: String,
insertClause: (T, SQLInsertClause, Int, Int) -> Unit,
updateClause: (T, SQLUpdateClause, Int, Int) -> Unit,
connection: Connection,
plugin: StatCraft) {
val id = plugin.databaseManager.getPlayerId(playerId) ?: return
val wid = plugin.databaseManager.getWorldId(worldName) ?: return
try {
val clause = plugin.databaseManager.getInsertClause(connection, this) ?: return
insertClause(this, clause, id, wid)
} catch (e: QueryException) {
val clause = plugin.databaseManager.getUpdateClause(connection, this) ?: return
updateClause(this, clause, id, wid)
}
}
/**
* Run an insert/update query on the given table. This method handles the clause object creation and fall-through
* to update when insert fails. This method run on the thread it is called, all threading must be managed by the
* caller. This also allows work to be done before the insert and update queries. The work function can return any
* object, and this object will be passed to the insert and update functions, and in that order. Because of this, if
* the object is modified in the insert function, these modifications will be present in the update function.
*
* For convenience this method also allows a player's UUID and a world's UUID to be passed in. The database id of
* the player and world will be fetched before the insert and update functions are called, and the id will be
* passed to them. This is not an expensive operation as both of these values are cached.
*
* Thanks to type inferencing no type parameters should need to be explicitly provided.
*
* @param playerId The UUID of the relevant player
* @param worldName The UUID of the relevant world
* @param workBefore The action to run before the queries, returning an object which will be passed to the two queries
* @param insertClause The action to run for the insert query
* @param updateClause The action to run for the update query if the insert fails
* @param plugin The StatCraft object
*/
/* TODO inline */ fun <T : RelationalPath<*>, R> T.runQuery(playerId: UUID,
worldName: String,
workBefore: (T, SQLQuery, Int, Int) -> R,
insertClause: (T, SQLInsertClause, Int, Int, R) -> Unit,
updateClause: (T, SQLUpdateClause, Int, Int, R) -> Unit,
connection: Connection,
plugin: StatCraft) {
val id = plugin.databaseManager.getPlayerId(playerId) ?: return
val wid = plugin.databaseManager.getWorldId(worldName) ?: return
val r = workBefore(this, plugin.databaseManager.getNewQuery(connection) ?: return, id, wid)
try {
val clause = plugin.databaseManager.getInsertClause(connection, this) ?: return
insertClause(this, clause, id, wid, r)
} catch (e: QueryException) {
val clause = plugin.databaseManager.getUpdateClause(connection, this) ?: return
updateClause(this, clause, id, wid, r)
}
}
| mit |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_occlusion_query.kt | 1 | 6228 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val ARB_occlusion_query = "ARBOcclusionQuery".nativeClassGL("ARB_occlusion_query", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension defines a mechanism whereby an application can query the number of pixels (or, more precisely, samples) drawn by a primitive or group of
primitives.
The primary purpose of such a query (hereafter referred to as an "occlusion query") is to determine the visibility of an object. Typically, the
application will render the major occluders in the scene, then perform an occlusion query for the bounding box of each detail object in the scene. Only
if said bounding box is visible, i.e., if at least one sample is drawn, should the corresponding object be drawn.
The earlier ${registryLinkTo("HP", "occlusion_test")} extension defined a similar mechanism, but it had two major shortcomings.
${ul(
"It returned the result as a simple GL11#TRUE/GL11#FALSE result, when in fact it is often useful to know exactly how many samples were drawn.",
"""
It provided only a simple "stop-and-wait" model for using multiple queries. The application begins an occlusion test and ends it; then, at some
later point, it asks for the result, at which point the driver must stop and wait until the result from the previous test is back before the
application can even begin the next one. This is a very simple model, but its performance is mediocre when an application wishes to perform many
queries, and it eliminates most of the opportunities for parallelism between the CPU and GPU.
"""
)}
This extension solves both of those problems. It returns as its result the number of samples that pass the depth and stencil tests, and it encapsulates
occlusion queries in "query objects" that allow applications to issue many queries before asking for the result of any one. As a result, they can
overlap the time it takes for the occlusion query results to be returned with other, more useful work, such as rendering other parts of the scene or
performing other computations on the CPU.
There are many situations where a pixel/sample count, rather than a boolean result, is useful.
${ul(
"Objects that are visible but cover only a very small number of pixels can be skipped at a minimal reduction of image quality.",
"""
Knowing exactly how many pixels an object might cover may help the application decide which level-of-detail model should be used. If only a few
pixels are visible, a low-detail model may be acceptable.
""",
"""
"Depth peeling" techniques, such as order-independent transparency, need to know when to stop rendering more layers; it is difficult to determine a
priori how many layers are needed. A boolean result allows applications to stop when more layers will not affect the image at all, but this will
likely result in unacceptable performance. Instead, it makes more sense to stop rendering when the number of pixels in each layer falls below a
given threshold.
""",
"""
Occlusion queries can replace glReadPixels of the depth buffer to determine whether (for example) a light source is visible for the purposes of a
lens flare effect or a halo to simulate glare. Pixel counts allow you to compute the percentage of the light source that is visible, and the
brightness of these effects can be modulated accordingly.
"""
)}
${GL15.promoted}
"""
IntConstant(
"Accepted by the {@code target} parameter of BeginQueryARB, EndQueryARB, and GetQueryivARB.",
"SAMPLES_PASSED_ARB"..0x8914
)
val QUERY_PARAMETERS = IntConstant(
"Accepted by the {@code pname} parameter of GetQueryivARB.",
"QUERY_COUNTER_BITS_ARB"..0x8864,
"CURRENT_QUERY_ARB"..0x8865
).javaDocLinks
val QUERY_OBJECT_PARAMETERS = IntConstant(
"Accepted by the {@code pname} parameter of GetQueryObjectivARB and GetQueryObjectuivARB.",
"QUERY_RESULT_ARB"..0x8866,
"QUERY_RESULT_AVAILABLE_ARB"..0x8867
).javaDocLinks
void(
"GenQueriesARB",
"Generates query object names.",
AutoSize("ids")..GLsizei.IN("n", "the number of query object names to be generated"),
ReturnParam..GLuint_p.OUT("ids", "a buffer in which the generated query object names are stored")
)
void(
"DeleteQueriesARB",
"Deletes named query objects.",
AutoSize("ids")..GLsizei.IN("n", "the number of query objects to be deleted"),
SingleValue("id")..const..GLuint_p.IN("ids", "an array of query objects to be deleted")
)
GLboolean(
"IsQueryARB",
"Determine if a name corresponds to a query object.",
GLuint.IN("id", "a value that may be the name of a query object")
)
void(
"BeginQueryARB",
"Creates a query object and makes it active.",
GLenum.IN("target", "the target type of query object established", QUERY_TARGETS),
GLuint.IN("id", "the name of a query object")
)
void(
"EndQueryARB",
"Marks the end of the sequence of commands to be tracked for the active query specified by {@code target}.",
GLenum.IN("target", "the query object target", QUERY_TARGETS)
)
void(
"GetQueryivARB",
"Returns parameters of a query object target.",
GLenum.IN("target", "the query object target", QUERY_TARGETS),
GLenum.IN("pname", "the symbolic name of a query object target parameter", QUERY_PARAMETERS),
Check(1)..ReturnParam..GLint_p.OUT("params", "the requested data")
)
void(
"GetQueryObjectivARB",
"Returns the integer value of a query object parameter.",
GLuint.IN("id", "the name of a query object"),
GLenum.IN("pname", "the symbolic name of a query object parameter", QUERY_OBJECT_PARAMETERS),
Check(1)..ReturnParam..GLint_p.OUT("params", "the requested data")
)
void(
"GetQueryObjectuivARB",
"Unsigned version of #GetQueryObjectivARB().",
GLuint.IN("id", "the name of a query object"),
GLenum.IN("pname", "the symbolic name of a query object parameter", QUERY_OBJECT_PARAMETERS),
Check(1)..ReturnParam..GLuint_p.OUT("params", "the requested data")
)
} | bsd-3-clause |
bsmr-java/lwjgl3 | modules/templates/src/main/kotlin/org/lwjgl/opengl/templates/ARB_point_sprite.kt | 1 | 1878 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package org.lwjgl.opengl.templates
import org.lwjgl.generator.*
import org.lwjgl.opengl.*
val ARB_point_sprite = "ARBPointSprite".nativeClassGL("ARB_point_sprite", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
Applications such as particle systems have tended to use OpenGL quads rather than points to render their geometry, since they would like to use a
custom-drawn texture for each particle, rather than the traditional OpenGL round antialiased points, and each fragment in a point has the same texture
coordinates as every other fragment.
Unfortunately, specifying the geometry for these quads can be expensive, since it quadruples the amount of geometry required, and may also require the
application to do extra processing to compute the location of each vertex.
The purpose of this extension is to allow such applications to use points rather than quads. When #POINT_SPRITE_ARB is enabled, the state of point
antialiasing is ignored. For each texture unit, the app can then specify whether to replace the existing texture coordinates with point sprite texture
coordinates, which are interpolated across the point.
${GL20.promoted}
"""
IntConstant(
"""
Accepted by the {@code cap} parameter of Enable, Disable, and IsEnabled, by the {@code pname} parameter of GetBooleanv, GetIntegerv, GetFloatv, and
GetDoublev, and by the {@code target} parameter of TexEnvi, TexEnviv, TexEnvf, TexEnvfv, GetTexEnviv, and GetTexEnvfv.
""",
"POINT_SPRITE_ARB"..0x8861
)
IntConstant(
"""
When the {@code target} parameter of TexEnvf, TexEnvfv, TexEnvi, TexEnviv, GetTexEnvfv, or GetTexEnviv is POINT_SPRITE_ARB, then the value of
{@code pname} may be.
""",
"COORD_REPLACE_ARB"..0x8862
)
} | bsd-3-clause |
edx/edx-app-android | OpenEdXMobile/src/main/java/org/edx/mobile/util/Version.kt | 1 | 5302 | package org.edx.mobile.util
import java.text.ParseException
import java.util.*
import kotlin.math.abs
import kotlin.math.min
/**
* Simple representation of the app's version.
*/
class Version
/**
* Create a new instance from the provided version string.
*
* @param version The version string. The first three present dot-separated
* tokens will be parsed as major, minor, and patch version
* numbers respectively, and any further tokens will be
* discarded.
* @throws ParseException If one or more of the first three present dot-
* separated tokens contain non-numeric characters.
*/
@Throws(ParseException::class)
constructor(version: String) : Comparable<Version> {
/**
* The version numbers
*/
private val numbers = IntArray(3)
/**
* @return The major version.
*/
val majorVersion: Int
get() = getVersionAt(0)
/**
* @return The minor version.
*/
val minorVersion: Int
get() = getVersionAt(1)
/**
* @return The patch version.
*/
val patchVersion: Int
get() = getVersionAt(2)
init {
val numberStrings = version.split("\\.".toRegex())
val versionsCount = min(NUMBERS_COUNT, numberStrings.size)
for (i in 0 until versionsCount) {
val numberString = numberStrings[i]
/* Integer.parseInt() parses a string as a signed integer value, and
* there is no available method for parsing as unsigned instead.
* Therefore, we first check the first character manually to see
* whether it's a plus or minus sign, and throw a ParseException if
* it is.
*/
val firstChar = numberString[0]
if (firstChar == '-' || firstChar == '+') {
throw VersionParseException(0)
}
try {
numbers[i] = Integer.parseInt(numberString)
} catch (e: NumberFormatException) {
// Rethrow as a checked ParseException
throw VersionParseException(version.indexOf(numberString))
}
}
}
/**
* Returns the version number at the provided index.
*
* @param index The index at which to get the version number
* @return The version number.
*/
private fun getVersionAt(index: Int): Int {
return if (index < numbers.size) numbers[index] else 0
}
override fun equals(other: Any?): Boolean {
return this === other || (other is Version && Arrays.equals(numbers, other.numbers))
}
override fun compareTo(other: Version): Int {
for (i in 0 until NUMBERS_COUNT) {
val number = numbers[i]
val otherNumber = other.numbers[i]
if (number != otherNumber) {
return if (number < otherNumber) -1 else 1
}
}
return 0
}
override fun hashCode(): Int {
return Arrays.hashCode(numbers)
}
override fun toString(): String {
when (numbers.size) {
0 -> return ""
1 -> return numbers[0].toString()
}
val sb = StringBuilder()
sb.append(numbers[0])
for (i in 1 until numbers.size) {
sb.append(".")
sb.append(numbers[i])
}
return sb.toString()
}
/**
* Convenience subclass of [ParseException], with the detail
* message already provided.
*/
private class VersionParseException
/**
* Constructs a new instance of this class with its stack
* trace, detail message and the location of the error filled
* in.
*
* @param location The location of the token at which the parse
* exception occurred.
*/
(location: Int) : ParseException("Token couldn't be parsed as a valid number.", location)
/**
* Compares this version with the specified version, to determine if minor versions'
* difference between both is greater than or equal to the specified value.
*
* @param otherVersion The version to compare to this instance.
* @param minorVersionsDiff Value difference to compare between versions.
* @return `true` if difference is greater than or equal to the specified value,
* `false` otherwise.
*/
fun isNMinorVersionsDiff(otherVersion: Version,
minorVersionsDiff: Int): Boolean {
// Difference in major version is consider to be valid for any minor versions difference
return abs(this.majorVersion - otherVersion.majorVersion) >= 1 || abs(this.minorVersion - otherVersion.minorVersion) >= minorVersionsDiff
}
/**
* Compares this version with the specified version and determine if both have same major and
* minor versions.
*
* @param otherVersion The version to compare to this instance.
* @return `true` if both have same major and minor versions, `false` otherwise.
*/
fun hasSameMajorMinorVersion(otherVersion: Version): Boolean {
return this.majorVersion == otherVersion.majorVersion && this.minorVersion == otherVersion.minorVersion
}
companion object {
/**
* The number of version number tokens to parse.
*/
private const val NUMBERS_COUNT = 3
}
}
| apache-2.0 |
EventFahrplan/EventFahrplan | commons/src/test/java/info/metadude/android/eventfahrplan/commons/temporal/DateFormatterFormattedTime24HourTest.kt | 1 | 5000 | package info.metadude.android.eventfahrplan.commons.temporal
import com.google.common.truth.Truth.assertThat
import info.metadude.android.eventfahrplan.commons.temporal.DateFormatterFormattedTime24HourTest.TestParameter.Companion.parse
import info.metadude.android.eventfahrplan.commons.testing.withTimeZone
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import org.threeten.bp.ZoneOffset
/**
* Covers the time zone aware time rendering of [DateFormatter.getFormattedTime24Hour].
* - Iterating all valid time zone offsets
* - Iterating all hours of a day
* - Testing with summer and winter time
*
* Regardless which time zone is set at the device always the time zone of the event/session will
* be rendered.
*
* TODO: TechDebt: Once the app offers an option to render sessions in the device time zone this test must be adapted.
*/
@RunWith(Parameterized::class)
class DateFormatterFormattedTime24HourTest(
private val timeZoneId: String
) {
companion object {
private val timeZoneOffsets = -12..14
@JvmStatic
@Parameterized.Parameters(name = "{index}: timeZoneId = {0}")
fun data() = timeZoneOffsets.map { arrayOf("GMT$it") }
}
@Test
fun `getFormattedTime24Hour 2021-03-27`() = testEach(listOf(
"2021-03-27T00:01:00+01:00" to "00:01",
"2021-03-27T01:00:00+01:00" to "01:00",
"2021-03-27T02:00:00+01:00" to "02:00",
"2021-03-27T03:00:00+01:00" to "03:00",
"2021-03-27T04:00:00+01:00" to "04:00",
"2021-03-27T05:00:00+01:00" to "05:00",
"2021-03-27T06:00:00+01:00" to "06:00",
"2021-03-27T07:00:00+01:00" to "07:00",
"2021-03-27T08:00:00+01:00" to "08:00",
"2021-03-27T09:00:00+01:00" to "09:00",
"2021-03-27T10:00:00+01:00" to "10:00",
"2021-03-27T11:00:00+01:00" to "11:00",
"2021-03-27T12:00:00+01:00" to "12:00",
"2021-03-27T13:00:00+01:00" to "13:00",
"2021-03-27T14:00:00+01:00" to "14:00",
"2021-03-27T15:00:00+01:00" to "15:00",
"2021-03-27T16:00:00+01:00" to "16:00",
"2021-03-27T17:00:00+01:00" to "17:00",
"2021-03-27T18:00:00+01:00" to "18:00",
"2021-03-27T19:00:00+01:00" to "19:00",
"2021-03-27T20:00:00+01:00" to "20:00",
"2021-03-27T21:00:00+01:00" to "21:00",
"2021-03-27T22:00:00+01:00" to "22:00",
"2021-03-27T23:00:00+01:00" to "23:00",
"2021-03-27T23:59:00+01:00" to "23:59",
))
@Test
fun `getFormattedTime24Hour 2021-03-28`() = testEach(listOf(
"2021-03-28T00:01:00+02:00" to "00:01",
"2021-03-28T01:00:00+02:00" to "01:00",
"2021-03-28T02:00:00+02:00" to "02:00", // TechDebt: Daylight saving time is ignored here.
"2021-03-28T03:00:00+02:00" to "03:00",
"2021-03-28T04:00:00+02:00" to "04:00",
"2021-03-28T05:00:00+02:00" to "05:00",
"2021-03-28T06:00:00+02:00" to "06:00",
"2021-03-28T07:00:00+02:00" to "07:00",
"2021-03-28T08:00:00+02:00" to "08:00",
"2021-03-28T09:00:00+02:00" to "09:00",
"2021-03-28T10:00:00+02:00" to "10:00",
"2021-03-28T11:00:00+02:00" to "11:00",
"2021-03-28T12:00:00+02:00" to "12:00",
"2021-03-28T13:00:00+02:00" to "13:00",
"2021-03-28T14:00:00+02:00" to "14:00",
"2021-03-28T15:00:00+02:00" to "15:00",
"2021-03-28T16:00:00+02:00" to "16:00",
"2021-03-28T17:00:00+02:00" to "17:00",
"2021-03-28T18:00:00+02:00" to "18:00",
"2021-03-28T19:00:00+02:00" to "19:00",
"2021-03-28T20:00:00+02:00" to "20:00",
"2021-03-28T21:00:00+02:00" to "21:00",
"2021-03-28T22:00:00+02:00" to "22:00",
"2021-03-28T23:00:00+02:00" to "23:00",
"2021-03-28T23:59:00+02:00" to "23:59",
))
private fun testEach(pairs: List<Pair<String, String>>) {
pairs.forEach { (dateTime, expectedFormattedTime) ->
val (moment, offset) = parse(dateTime)
withTimeZone(timeZoneId) {
val formattedTime = DateFormatter.newInstance(useDeviceTimeZone = false).getFormattedTime24Hour(moment, offset)
assertThat(formattedTime).isEqualTo(expectedFormattedTime)
}
}
}
private data class TestParameter(val moment: Moment, val offset: ZoneOffset) {
companion object {
fun parse(dateTime: String) = TestParameter(
parseMoment(dateTime),
parseTimeZoneOffset(dateTime)
)
private fun parseMoment(text: String): Moment {
val milliseconds = DateParser.parseDateTime(text)
return Moment.ofEpochMilli(milliseconds)
}
private fun parseTimeZoneOffset(text: String): ZoneOffset {
val seconds = DateParser.parseTimeZoneOffset(text)
return ZoneOffset.ofTotalSeconds(seconds)
}
}
}
}
| apache-2.0 |
andstatus/andstatus | app/src/androidTest/kotlin/org/andstatus/app/context/ActivityTest.kt | 1 | 2220 | /**
* Copyright (C) 2017 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.context
import android.app.Activity
import android.app.Instrumentation
import android.content.Intent
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.ActivityTestRule
import io.vavr.control.CheckedRunnable
import org.andstatus.app.util.IgnoreInTravis1
import org.andstatus.app.util.ScreenshotOnFailure
import org.apache.geode.test.junit.ConditionalIgnore
import org.apache.geode.test.junit.rules.ConditionalIgnoreRule
import org.junit.Rule
/** Helper for Activity tests, based on https://google.github.io/android-testing-support-library/
* See https://developer.android.com/training/testing/ui-testing/espresso-testing.html
*/
@ConditionalIgnore(IgnoreInTravis1::class)
abstract class ActivityTest<T : Activity> {
@Rule
@JvmField
var conditionalIgnoreRule: ConditionalIgnoreRule = ConditionalIgnoreRule()
@Rule
@JvmField
var mActivityRule: ActivityTestRule<T> = object : ActivityTestRule<T>(getActivityClass()) {
override fun getActivityIntent(): Intent? {
return [email protected]()
}
}
protected abstract fun getActivityClass(): Class<T>
protected open fun getActivityIntent(): Intent? {
return null
}
val activity: T get() = mActivityRule.getActivity()
fun getInstrumentation(): Instrumentation {
return InstrumentationRegistry.getInstrumentation()
}
/** Make screenshot on failure */
fun wrap(runnable: CheckedRunnable) {
ScreenshotOnFailure.screenshotWrapper(activity, runnable)
}
}
| apache-2.0 |
IRA-Team/VKPlayer | app/src/main/java/com/irateam/vkplayer/api/service/UserService.kt | 1 | 3584 | /*
* Copyright (C) 2015 IRA-Team
*
* 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.irateam.vkplayer.api.service
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.irateam.vkplayer.api.AbstractQuery
import com.irateam.vkplayer.api.Query
import com.irateam.vkplayer.api.VKQuery
import com.irateam.vkplayer.model.User
import com.irateam.vkplayer.util.extension.isNetworkAvailable
import com.vk.sdk.api.VKApiConst
import com.vk.sdk.api.VKParameters
import com.vk.sdk.api.VKRequest
import com.vk.sdk.api.VKResponse
import com.vk.sdk.api.methods.VKApiUsers
import com.vk.sdk.api.model.VKApiUser
class UserService {
private val context: Context
private val sharedPreferences: SharedPreferences
constructor(context: Context) {
this.context = context
this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
}
fun getCurrentCached(): Query<User> {
return CachedCurrentUserQuery()
}
fun getCurrent(): Query<User> = if (context.isNetworkAvailable()) {
val params = VKParameters.from(VKApiConst.FIELDS, VKApiUser.FIELD_PHOTO_100)
val request = VKApiUsers().get(params)
CurrentUserQuery(request)
} else {
CachedCurrentUserQuery()
}
private fun parseFromPreferences(): User {
val id = sharedPreferences.getInt(USER_ID, -1)
val firstName = sharedPreferences.getString(USER_FIRST_NAME, "")
val lastName = sharedPreferences.getString(USER_SECOND_NAME, "")
val photo100px = sharedPreferences.getString(USER_PHOTO_URL, "")
return User(id, firstName, lastName, photo100px)
}
private fun parseFromVKResponse(response: VKResponse): User {
val responseBody = response.json.getJSONArray("response")
val rawUser = responseBody.getJSONObject(0)
return User(
rawUser.optInt("id"),
rawUser.optString("first_name"),
rawUser.optString("last_name"),
rawUser.optString("photo_100"))
}
private fun saveToPreferences(user: User) = sharedPreferences.edit()
.putInt(USER_ID, user.id)
.putString(USER_FIRST_NAME, user.firstName)
.putString(USER_SECOND_NAME, user.lastName)
.putString(USER_PHOTO_URL, user.photo100px)
.apply()
private inner class CurrentUserQuery(request: VKRequest) : VKQuery<User>(request) {
override fun parse(response: VKResponse): User {
val user = parseFromVKResponse(response)
saveToPreferences(user)
return user
}
}
private inner class CachedCurrentUserQuery : AbstractQuery<User>() {
override fun query(): User = parseFromPreferences()
}
companion object {
private val USER_ID = "user_id"
private val USER_FIRST_NAME = "user_first_name"
private val USER_SECOND_NAME = "user_second_name"
private val USER_PHOTO_URL = "user_photo_url"
}
}
| apache-2.0 |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/database/table/ActorEndpointTable.kt | 1 | 1706 | /*
* Copyright (c) 2018 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.database.table
import android.database.sqlite.SQLiteDatabase
import org.andstatus.app.data.DbUtils
/** Collections of URIs for Actors */
object ActorEndpointTable {
val TABLE_NAME: String = "actorendpoints"
val ACTOR_ID: String = ActorTable.ACTOR_ID
/** [org.andstatus.app.net.social.ActorEndpointType] */
val ENDPOINT_TYPE: String = "endpoint_type"
/** Index of an endpoint of a particular [.ENDPOINT_TYPE], starting from 0 */
val ENDPOINT_INDEX: String = "endpoint_index"
val ENDPOINT_URI: String = "endpoint_uri"
fun create(db: SQLiteDatabase) {
DbUtils.execSQL(db, "CREATE TABLE " + TABLE_NAME + " ("
+ ACTOR_ID + " INTEGER NOT NULL,"
+ ENDPOINT_TYPE + " INTEGER NOT NULL,"
+ ENDPOINT_INDEX + " INTEGER NOT NULL DEFAULT 0,"
+ ENDPOINT_URI + " TEXT NOT NULL,"
+ " CONSTRAINT pk_" + TABLE_NAME + " PRIMARY KEY (" + ACTOR_ID + " ASC, " + ENDPOINT_TYPE + " ASC, " + ENDPOINT_INDEX + " ASC)"
+ ")")
}
}
| apache-2.0 |
TUWien/DocScan | app/src/main/java/at/ac/tuwien/caa/docscan/db/dao/UserDao.kt | 1 | 730 | package at.ac.tuwien.caa.docscan.db.dao
import androidx.annotation.Keep
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import at.ac.tuwien.caa.docscan.db.model.User
import kotlinx.coroutines.flow.Flow
@Keep
@Dao
interface UserDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertUser(user: User)
@Query("DELETE FROM ${User.TABLE_NAME_USERS}")
suspend fun deleteUser()
@Query("SELECT * FROM ${User.TABLE_NAME_USERS} WHERE ${User.KEY_ID} = ${User.USER_ID}")
fun getUserAsFlow(): Flow<User?>
@Query("SELECT * FROM ${User.TABLE_NAME_USERS} WHERE ${User.KEY_ID} = ${User.USER_ID}")
suspend fun getUser(): User?
}
| lgpl-3.0 |
esofthead/mycollab | mycollab-scheduler/src/main/java/com/mycollab/module/project/schedule/email/service/ProjectRiskRelayEmailNotificationActionImpl.kt | 3 | 13235 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.project.schedule.email.service
import com.hp.gagawa.java.elements.A
import com.hp.gagawa.java.elements.Span
import com.hp.gagawa.java.elements.Text
import com.mycollab.common.MonitorTypeConstants
import com.mycollab.common.i18n.GenericI18Enum
import com.mycollab.common.i18n.OptionI18nEnum.StatusI18nEnum
import com.mycollab.core.MyCollabException
import com.mycollab.core.utils.StringUtils
import com.mycollab.html.FormatUtils
import com.mycollab.html.LinkUtils
import com.mycollab.module.mail.MailUtils
import com.mycollab.module.project.ProjectLinkGenerator
import com.mycollab.module.project.ProjectResources
import com.mycollab.module.project.ProjectTypeConstants
import com.mycollab.module.project.domain.ProjectRelayEmailNotification
import com.mycollab.module.project.domain.Risk
import com.mycollab.module.project.domain.SimpleRisk
import com.mycollab.module.project.i18n.MilestoneI18nEnum
import com.mycollab.module.project.i18n.OptionI18nEnum.RiskConsequence
import com.mycollab.module.project.i18n.OptionI18nEnum.RiskProbability
import com.mycollab.module.project.i18n.RiskI18nEnum
import com.mycollab.module.project.service.MilestoneService
import com.mycollab.module.project.service.RiskService
import com.mycollab.module.user.AccountLinkGenerator
import com.mycollab.module.user.service.UserService
import com.mycollab.schedule.email.ItemFieldMapper
import com.mycollab.schedule.email.MailContext
import com.mycollab.schedule.email.format.DateFieldFormat
import com.mycollab.schedule.email.format.FieldFormat
import com.mycollab.schedule.email.format.I18nFieldFormat
import com.mycollab.schedule.email.project.ProjectRiskRelayEmailNotificationAction
import com.mycollab.spring.AppContextUtil
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.config.BeanDefinition
import org.springframework.context.annotation.Scope
import org.springframework.stereotype.Component
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
class ProjectRiskRelayEmailNotificationActionImpl : SendMailToAllMembersAction<SimpleRisk>(), ProjectRiskRelayEmailNotificationAction {
@Autowired private lateinit var riskService: RiskService
private val mapper = ProjectFieldNameMapper()
override fun getItemName(): String = StringUtils.trim(bean!!.name, 100)
override fun getProjectName(): String = bean!!.projectName
override fun getCreateSubject(context: MailContext<SimpleRisk>): String = context.getMessage(
RiskI18nEnum.MAIL_CREATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCreateSubjectNotification(context: MailContext<SimpleRisk>): String =
context.getMessage(RiskI18nEnum.MAIL_CREATE_ITEM_SUBJECT, projectLink(), userLink(context), riskLink())
override fun getUpdateSubject(context: MailContext<SimpleRisk>): String = context.getMessage(
RiskI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getUpdateSubjectNotification(context: MailContext<SimpleRisk>): String =
context.getMessage(RiskI18nEnum.MAIL_UPDATE_ITEM_SUBJECT, projectLink(), userLink(context), riskLink())
override fun getCommentSubject(context: MailContext<SimpleRisk>): String = context.getMessage(
RiskI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, bean!!.projectName, context.changeByUserFullName, getItemName())
override fun getCommentSubjectNotification(context: MailContext<SimpleRisk>): String =
context.getMessage(RiskI18nEnum.MAIL_COMMENT_ITEM_SUBJECT, projectLink(), userLink(context), riskLink())
private fun projectLink() = A(ProjectLinkGenerator.generateProjectLink(bean!!.projectid)).
appendText(StringUtils.trim(bean!!.projectName, 50)).setType(bean!!.projectName).write()
private fun userLink(context: MailContext<SimpleRisk>) = A(AccountLinkGenerator.generateUserLink(context.user.username)).
appendText(StringUtils.trim(context.changeByUserFullName, 50)).write()
private fun riskLink() = A(ProjectLinkGenerator.generateRiskPreviewLink(bean!!.projectShortName, bean!!.ticketKey)).appendText(getItemName()).write()
override fun getItemFieldMapper(): ItemFieldMapper = mapper
override fun getBeanInContext(notification: ProjectRelayEmailNotification): SimpleRisk? =
riskService.findById(notification.typeid.toInt(), notification.saccountid)
override fun getType(): String = ProjectTypeConstants.RISK
override fun getTypeId(): String = "${bean!!.id}"
override fun buildExtraTemplateVariables(context: MailContext<SimpleRisk>) {
val emailNotification = context.emailNotification
val summary = bean!!.name
val summaryLink = ProjectLinkGenerator.generateRiskPreviewFullLink(siteUrl, bean!!.projectShortName, bean!!.ticketKey)
val avatarId = if (projectMember != null) projectMember!!.memberAvatarId else ""
val userAvatar = LinkUtils.newAvatar(avatarId)
val makeChangeUser = "${userAvatar.write()} ${emailNotification.changeByUserFullName}"
val actionEnum = when (emailNotification.action) {
MonitorTypeConstants.CREATE_ACTION -> RiskI18nEnum.MAIL_CREATE_ITEM_HEADING
MonitorTypeConstants.UPDATE_ACTION -> RiskI18nEnum.MAIL_UPDATE_ITEM_HEADING
MonitorTypeConstants.ADD_COMMENT_ACTION -> RiskI18nEnum.MAIL_COMMENT_ITEM_HEADING
else -> throw MyCollabException("Not support action ${emailNotification.action}")
}
contentGenerator.putVariable("projectName", bean!!.projectName)
contentGenerator.putVariable("projectNotificationUrl", ProjectLinkGenerator.generateProjectSettingFullLink(siteUrl, bean!!.projectid))
contentGenerator.putVariable("actionHeading", context.getMessage(actionEnum, makeChangeUser))
contentGenerator.putVariable("name", summary)
contentGenerator.putVariable("summaryLink", summaryLink)
}
class ProjectFieldNameMapper : ItemFieldMapper() {
init {
put(Risk.Field.name, GenericI18Enum.FORM_NAME, true)
put(Risk.Field.description, GenericI18Enum.FORM_DESCRIPTION, true)
put(Risk.Field.probability, I18nFieldFormat(Risk.Field.probability.name, RiskI18nEnum.FORM_PROBABILITY,
RiskProbability::class.java))
put(Risk.Field.consequence, I18nFieldFormat(Risk.Field.consequence.name, RiskI18nEnum.FORM_CONSEQUENCE, RiskConsequence::class.java))
put(Risk.Field.startdate, DateFieldFormat(Risk.Field.startdate.name, GenericI18Enum.FORM_START_DATE))
put(Risk.Field.enddate, DateFieldFormat(Risk.Field.enddate.name, GenericI18Enum.FORM_END_DATE))
put(Risk.Field.duedate, DateFieldFormat(Risk.Field.duedate.name, GenericI18Enum.FORM_DUE_DATE))
put(Risk.Field.status, I18nFieldFormat(Risk.Field.status.name, GenericI18Enum.FORM_STATUS,
StatusI18nEnum::class.java))
put(Risk.Field.milestoneid, MilestoneFieldFormat(Risk.Field.milestoneid.name, MilestoneI18nEnum.SINGLE))
put(Risk.Field.assignuser, AssigneeFieldFormat(Risk.Field.assignuser.name, GenericI18Enum.FORM_ASSIGNEE))
put(Risk.Field.createduser, RaisedByFieldFormat(Risk.Field.createduser.name, RiskI18nEnum.FORM_RAISED_BY))
put(Risk.Field.response, RiskI18nEnum.FORM_RESPONSE, true)
}
}
class AssigneeFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) {
override fun formatField(context: MailContext<*>): String {
val risk = context.wrappedBean as SimpleRisk
return if (risk.assignuser != null) {
val userAvatarLink = MailUtils.getAvatarLink(risk.assignToUserAvatarId, 16)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(risk.saccountid),
risk.assignuser)
val link = FormatUtils.newA(userLink, risk.assignedToUserFullName)
FormatUtils.newLink(img, link).write()
} else Span().write()
}
override fun formatField(context: MailContext<*>, value: String): String {
return if (StringUtils.isBlank(value)) {
Span().write()
} else {
val userService = AppContextUtil.getSpringBean(UserService::class.java)
val user = userService.findUserByUserNameInAccount(value, context.saccountid)
if (user != null) {
val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(context.saccountid),
user.username)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val link = FormatUtils.newA(userLink, user.displayName!!)
FormatUtils.newLink(img, link).write()
} else value
}
}
}
class RaisedByFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) {
override fun formatField(context: MailContext<*>): String {
val risk = context.wrappedBean as SimpleRisk
return if (risk.createduser != null) {
val userAvatarLink = MailUtils.getAvatarLink(risk.raisedByUserAvatarId, 16)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(risk.saccountid),
risk.createduser)
val link = FormatUtils.newA(userLink, risk.raisedByUserFullName)
FormatUtils.newLink(img, link).write()
} else Span().write()
}
override fun formatField(context: MailContext<*>, value: String): String {
if (StringUtils.isBlank(value)) {
return Span().write()
}
val userService = AppContextUtil.getSpringBean(UserService::class.java)
val user = userService.findUserByUserNameInAccount(value, context.saccountid)
return if (user != null) {
val userAvatarLink = MailUtils.getAvatarLink(user.avatarid, 16)
val userLink = AccountLinkGenerator.generatePreviewFullUserLink(MailUtils.getSiteUrl(context.saccountid),
user.username)
val img = FormatUtils.newImg("avatar", userAvatarLink)
val link = FormatUtils.newA(userLink, user.displayName!!)
FormatUtils.newLink(img, link).write()
} else value
}
}
class MilestoneFieldFormat(fieldName: String, displayName: Enum<*>) : FieldFormat(fieldName, displayName) {
override fun formatField(context: MailContext<*>): String {
val risk = context.wrappedBean as SimpleRisk
return if (risk.milestoneid != null) {
val img = Text(ProjectResources.getFontIconHtml(ProjectTypeConstants.MILESTONE))
val milestoneLink = ProjectLinkGenerator.generateMilestonePreviewFullLink(context.siteUrl, risk.projectid,
risk.milestoneid)
val link = FormatUtils.newA(milestoneLink, risk.milestoneName!!)
FormatUtils.newLink(img, link).write()
} else Span().write()
}
override fun formatField(context: MailContext<*>, value: String): String {
if (StringUtils.isBlank(value)) {
return Span().write()
}
val milestoneId = value.toInt()
val milestoneService = AppContextUtil.getSpringBean(MilestoneService::class.java)
val milestone = milestoneService.findById(milestoneId, context.saccountid)
return if (milestone != null) {
val img = Text(ProjectResources.getFontIconHtml(ProjectTypeConstants.MILESTONE))
val milestoneLink = ProjectLinkGenerator.generateMilestonePreviewFullLink(context.siteUrl,
milestone.projectid, milestone.id)
val link = FormatUtils.newA(milestoneLink, milestone.name)
return FormatUtils.newLink(img, link).write()
} else value
}
}
} | agpl-3.0 |
hidroh/tldroid | app/src/test/kotlin/io/github/hidroh/tldroid/NetworkConnectionTest.kt | 1 | 2268 | package io.github.hidroh.tldroid
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okio.Okio
import org.assertj.core.api.Assertions
import org.junit.After
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class NetworkConnectionTest {
private val server: MockWebServer = MockWebServer()
@Before
fun setUp() {
server.start()
}
@Test
fun testGetResponseCode() {
server.enqueue(MockResponse().setResponseCode(200))
val connection = NetworkConnection(server.url("/index.json").toString())
connection.connect()
Assertions.assertThat(connection.getResponseCode()).isEqualTo(200)
connection.disconnect()
}
@Test
fun testGetInputStream() {
server.enqueue(MockResponse().setBody("{}"))
val connection = NetworkConnection(server.url("/index.json").toString())
connection.connect()
Assertions.assertThat(Okio.buffer(Okio.source(connection.getInputStream())).readUtf8())
.isEqualTo("{}")
connection.disconnect()
}
@Test
fun testNoInputStream() {
server.enqueue(MockResponse().setResponseCode(404))
val connection = NetworkConnection(server.url("/index.json").toString())
connection.connect()
Assertions.assertThat(connection.getInputStream()).isNull()
connection.disconnect()
}
@Test
fun testModified() {
server.enqueue(MockResponse().setResponseCode(304).setHeader("Last-Modified",
"Fri, 03 Jun 2016 17:11:33 GMT"))
val connection = NetworkConnection(server.url("/index.json").toString())
connection.setIfModifiedSince(0L)
connection.connect()
Assertions.assertThat(connection.getLastModified()).isEqualTo(1464973893000L)
connection.disconnect()
}
@Test
fun testMissingConnect() {
val connection = NetworkConnection("/index.json")
connection.setIfModifiedSince(0L) // should ignore
Assertions.assertThat(connection.getResponseCode()).isEqualTo(0)
Assertions.assertThat(connection.getInputStream()).isNull()
Assertions.assertThat(connection.getLastModified()).isEqualTo(0L)
connection.disconnect() // should fail silently
}
@After
fun tearDown() {
server.shutdown()
}
} | apache-2.0 |
world-federation-of-advertisers/panel-exchange-client | src/main/kotlin/org/wfanet/panelmatch/client/launcher/CoroutineLauncher.kt | 1 | 1556 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.panelmatch.client.launcher
import kotlinx.coroutines.CoroutineName
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.coroutines.plus
import org.wfanet.measurement.api.v2alpha.ExchangeStep
import org.wfanet.measurement.api.v2alpha.ExchangeStepAttemptKey
import org.wfanet.panelmatch.client.launcher.ExchangeStepValidator.ValidatedExchangeStep
/** Executes an [ExchangeStep] in a new coroutine in [scope]. */
class CoroutineLauncher(
private val scope: CoroutineScope = CoroutineScope(Dispatchers.Default),
private val stepExecutor: ExchangeStepExecutor
) : JobLauncher {
override suspend fun execute(step: ValidatedExchangeStep, attemptKey: ExchangeStepAttemptKey) {
(scope + SupervisorJob()).launch(CoroutineName(attemptKey.toName())) {
stepExecutor.execute(step, attemptKey)
}
}
}
| apache-2.0 |
REDNBLACK/advent-of-code2016 | src/main/kotlin/day08/Advent8.kt | 1 | 5056 | package day08
import array2d
import day08.Operation.Type.*
import parseInput
import splitToLines
/**
You come across a door implementing what you can only assume is an implementation of two-factor authentication after a long game of requirements telephone.
To get past the door, you first swipe a keycard (no problem; there was one on a nearby desk). Then, it displays a code on a little screen, and you type that code on a keypad. Then, presumably, the door unlocks.
Unfortunately, the screen has been smashed. After a few minutes, you've taken everything apart and figured out how it works. Now you just have to work out what the screen would have displayed.
The magnetic strip on the card you swiped encodes a series of instructions for the screen; these instructions are your puzzle input. The screen is 50 pixels wide and 6 pixels tall, all of which start off, and is capable of three somewhat peculiar operations:
rect AxB turns on all of the pixels in a rectangle at the top-left of the screen which is A wide and B tall.
rotate row y=A by B shifts all of the pixels in row A (0 is the top row) right by B pixels. Pixels that would fall off the right end appear at the left end of the row.
rotate column x=A by B shifts all of the pixels in column A (0 is the left column) down by B pixels. Pixels that would fall off the bottom appear at the top of the column.
For example, here is a simple sequence on a smaller screen:
rect 3x2 creates a small rectangle in the top-left corner:
###....
###....
.......
rotate column x=1 by 1 rotates the second column down by one pixel:
#.#....
###....
.#.....
rotate row y=0 by 4 rotates the top row right by four pixels:
....#.#
###....
.#.....
rotate column x=1 by 1 again rotates the second column down by one pixel, causing the bottom pixel to wrap back to the top:
.#..#.#
#.#....
.#.....
As you can see, this display technology is extremely powerful, and will soon dominate the tiny-code-displaying-screen market. That's what the advertisement on the back of the display tries to convince you, anyway.
There seems to be an intermediate check of the voltage used by the display: after you swipe your card, if the screen did work, how many pixels should be lit?
--- Part Two ---
You notice that the screen is only capable of displaying capital letters; in the font it uses, each letter is 5 pixels wide and 6 tall.
After you swipe your card, what code is the screen trying to display?
*/
fun main(args: Array<String>) {
val test = """rect 3x2
|rotate column x=1 by 1
|rotate row y=0 by 4
|rotate column x=1 by 1""".trimMargin()
val resultMatrix1 = execute(test, array2d(3, 7) { false })
println(resultMatrix1.countFilled() == 6)
val input = parseInput("day8-input.txt")
val resultMatrix2 = execute(input, array2d(6, 50) { false })
println(resultMatrix2.countFilled())
resultMatrix2.drawMatrix()
}
data class Operation(val type: Operation.Type, val payload1: Int, val payload2: Int) {
enum class Type { CREATE, ROTATE_ROW, ROTATE_COLUMN }
}
fun execute(input: String, matrix: Array<Array<Boolean>>): Array<Array<Boolean>> {
fun <T> Array<Array<T>>.shiftDown(x: Int) {
val height = size - 1
val bottom = this[height][x]
for (y in height downTo 0) {
this[y][x] = if (y > 0) this[y - 1][x] else bottom
}
}
fun <T> Array<Array<T>>.shiftRight(y: Int) {
val width = this[0].size - 1
val right = this[y][width]
for (x in width downTo 0) {
this[y][x] = if (x > 0) this[y][x - 1] else right
}
}
fun <T> Array<Array<T>>.fill(value: T, maxWidth: Int, maxHeight: Int) {
for (w in 0 until maxWidth) {
for (h in 0 until maxHeight) {
this[h][w] = value
}
}
}
for ((type, p1, p2) in parseOperations(input)) {
when (type) {
CREATE -> matrix.fill(true, p1, p2)
ROTATE_COLUMN -> repeat(p2, { matrix.shiftDown(p1) })
ROTATE_ROW -> repeat(p2, { matrix.shiftRight(p1) })
}
}
return matrix
}
private fun Array<Array<Boolean>>.drawMatrix() = map { it.map { if (it) '█' else '▒' }.joinToString("") }
.joinToString(System.lineSeparator())
.let(::println)
private fun Array<Array<Boolean>>.countFilled() = sumBy { it.sumBy { if (it) 1 else 0 } }
private fun parseOperations(input: String) = input.splitToLines()
.map {
val (payload1, payload2) = Regex("""(\d+)""")
.findAll(it)
.map { it.value }
.map(String::toInt)
.toList()
val type = when {
"rect" in it -> CREATE
"rotate row" in it -> ROTATE_ROW
"rotate column" in it -> ROTATE_COLUMN
else -> throw IllegalArgumentException()
}
Operation(type = type, payload1 = payload1, payload2 = payload2)
}
| mit |
raxden/square | square-commons/src/main/java/com/raxdenstudios/square/interceptor/commons/telephony/HasTelephonyInterceptor.kt | 2 | 295 | package com.raxdenstudios.square.interceptor.commons.telephony
import com.raxdenstudios.square.interceptor.HasInterceptor
/**
* Created by Ángel Gómez on 30/12/2016.
*/
interface HasTelephonyInterceptor : HasInterceptor {
fun onCallStateChanged(state: Int, incomingNumber: String)
}
| apache-2.0 |
inorichi/tachiyomi-extensions | multisrc/overrides/madara/boyslove/src/BoysLove.kt | 1 | 2050 | package eu.kanade.tachiyomi.extension.en.boyslove
import eu.kanade.tachiyomi.annotations.Nsfw
import eu.kanade.tachiyomi.multisrc.madara.Madara
@Nsfw
class BoysLove : Madara("BoysLove", "https://boyslove.me", "en") {
override fun getGenreList() = listOf(
Genre("Action", "action"),
Genre("Adult", "adult"),
Genre("Adventure", "adventure"),
Genre("Boys Love", "boys-love"),
Genre("Cartoon", "cartoon"),
Genre("Comedy", "comedy"),
Genre("Comic", "comic"),
Genre("Complete", "complete"),
Genre("Cooking", "cooking"),
Genre("Doujinshi", "doujinshi"),
Genre("Drama", "drama"),
Genre("Ecchi", "ecchi"),
Genre("Fanstasy", "fantasy"),
Genre("Gender bender", "gender-bender"),
Genre("Harem", "harem"),
Genre("Historical", "historical"),
Genre("Horror", "horror"),
Genre("Isekai", "Isekai"),
Genre("Josei", "josei"),
Genre("Live action", "live-action"),
Genre("Manga", "manga"),
Genre("Manhua", "manhua"),
Genre("Manhwa", "manhwa"),
Genre("Martial arts", "martial-arts"),
Genre("Mature", "mature"),
Genre("Mecha", "mecha"),
Genre("Medical", "medical"),
Genre("Mystery", "mystery"),
Genre("One shot", "one-shot"),
Genre("Psychological", "psychological"),
Genre("Romance", "romance"),
Genre("School Life", "school-life"),
Genre("Sci-fi", "sci-fi"),
Genre("Seinen", "seinen"),
Genre("Shoujo", "shoujo"),
Genre("Shoujo ai", "shoujo-ai"),
Genre("Shounen", "shounen"),
Genre("Shounen ai", "shounen-ai"),
Genre("Slice of Life", "slice-of-life"),
Genre("Smut", "smut"),
Genre("Sports", "sports"),
Genre("Supernatural", "supernatural"),
Genre("Thriller", "thriller"),
Genre("Webtoon", "webtoon"),
Genre("Webtoons", "webtoons"),
Genre("Yaoi", "yaoi"),
Genre("Yuri", "yuri"),
)
}
| apache-2.0 |
Schlangguru/paperless-uploader | app/src/main/java/de/schlangguru/paperlessuploader/services/remote/PaperlessServiceProvider.kt | 1 | 1954 | package de.schlangguru.paperlessuploader.services.remote
import de.schlangguru.paperlessuploader.BuildConfig
import de.schlangguru.paperlessuploader.services.local.Settings
import okhttp3.Credentials
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
/**
* Returns a [PaperlessService] using retrofit.
*/
class PaperlessServiceProvider {
companion object {
fun createService (
settings: Settings = Settings(),
baseURL: String = settings.apiURL
) : PaperlessService {
val httpLoggingInterceptor = HttpLoggingInterceptor()
httpLoggingInterceptor.level = if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE
val client = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(BasicAuthInterceptor(settings))
.build()
val retrofit = Retrofit.Builder()
.baseUrl(baseURL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build()
return retrofit.create(PaperlessService::class.java)
}
}
class BasicAuthInterceptor(
private val settings: Settings
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val credentials = Credentials.basic(settings.username, settings.password)
val authRequest = chain.request().newBuilder().addHeader("Authorization", credentials).build()
return chain.proceed(authRequest)
}
}
} | mit |
saki4510t/libcommon | app/src/main/java/com/serenegiant/widget/CameraDelegator.kt | 1 | 10214 | @file:Suppress("DEPRECATION")
package com.serenegiant.widget
/*
* libcommon
* utility/helper classes for myself
*
* Copyright (c) 2014-2022 saki [email protected]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.annotation.SuppressLint
import android.graphics.SurfaceTexture
import android.hardware.Camera
import android.os.Handler
import android.util.Log
import android.view.View
import androidx.annotation.WorkerThread
import com.serenegiant.camera.CameraConst
import com.serenegiant.camera.CameraUtils
import com.serenegiant.utils.HandlerThreadHandler
import com.serenegiant.utils.HandlerUtils
import java.io.IOException
import java.util.concurrent.CopyOnWriteArraySet
/**
* カメラプレビュー処理の委譲クラス
*/
class CameraDelegator(
view: View,
width: Int, height: Int,
cameraRenderer: ICameraRenderer) {
/**
* 映像が更新されたときの通知用コールバックリスナー
*/
interface OnFrameAvailableListener {
fun onFrameAvailable()
}
/**
* カメラ映像をGLSurfaceViewへ描画するためのGLSurfaceView.Rendererインターフェース
*/
interface ICameraRenderer {
fun hasSurface(): Boolean
fun onPreviewSizeChanged(width: Int, height: Int)
/**
* カメラ映像受け取り用のSurface/SurfaceHolder/SurfaceTexture/SurfaceViewを取得
* @return
*/
fun getInputSurface(): Any
}
//--------------------------------------------------------------------------------
private val mView: View
private val mSync = Any()
val cameraRenderer: ICameraRenderer
private val mListeners: MutableSet<OnFrameAvailableListener> = CopyOnWriteArraySet()
private var mCameraHandler: Handler? = null
/**
* カメラ映像幅を取得
* @return
*/
var requestWidth: Int
private set
/**
* カメラ映像高さを取得
* @return
*/
var requestHeight: Int
private set
var previewWidth: Int
private set
var previewHeight: Int
private set
var isPreviewing: Boolean
private set
private var mScaleMode = SCALE_STRETCH_FIT
private var mCamera: Camera? = null
@Volatile
private var mResumed = false
init {
if (DEBUG) Log.v(TAG, String.format("コンストラクタ:(%dx%d)", width, height))
mView = view
@Suppress("LeakingThis")
this.cameraRenderer = cameraRenderer
this.requestWidth = width
this.requestHeight = height
this.previewWidth = width
this.previewHeight = height
isPreviewing = false
}
@Throws(Throwable::class)
protected fun finalize() {
release()
}
/**
* 関連するリソースを廃棄する
*/
fun release() {
synchronized(mSync) {
if (mCameraHandler != null) {
if (DEBUG) Log.v(TAG, "release:")
mCameraHandler!!.removeCallbacksAndMessages(null)
HandlerUtils.NoThrowQuit(mCameraHandler)
mCameraHandler = null
}
}
}
/**
* GLSurfaceView#onResumeが呼ばれたときの処理
*/
fun onResume() {
if (DEBUG) Log.v(TAG, "onResume:")
mResumed = true
if (cameraRenderer.hasSurface()) {
if (mCameraHandler == null) {
if (DEBUG) Log.v(TAG, "surface already exist")
startPreview(requestWidth, requestHeight)
}
}
}
/**
* GLSurfaceView#onPauseが呼ばれたときの処理
*/
fun onPause() {
if (DEBUG) Log.v(TAG, "onPause:")
mResumed = false
// just request stop previewing
stopPreview()
}
/**
* 映像が更新されたときのコールバックリスナーを登録
* @param listener
*/
fun addListener(listener: OnFrameAvailableListener?) {
if (DEBUG) Log.v(TAG, "addListener:$listener")
if (listener != null) {
mListeners.add(listener)
}
}
/**
* 映像が更新されたときのコールバックリスナーの登録を解除
* @param listener
*/
fun removeListener(listener: OnFrameAvailableListener) {
if (DEBUG) Log.v(TAG, "removeListener:$listener")
mListeners.remove(listener)
}
/**
* 映像が更新されたときのコールバックを呼び出す
*/
fun callOnFrameAvailable() {
for (listener in mListeners) {
try {
listener.onFrameAvailable()
} catch (e: Exception) {
mListeners.remove(listener)
}
}
}
var scaleMode: Int
/**
* 現在のスケールモードを取得
* @return
*/
get() {
if (DEBUG) Log.v(TAG, "getScaleMode:$mScaleMode")
return mScaleMode
}
/**
* スケールモードをセット
* @param mode
*/
set(mode) {
if (DEBUG) Log.v(TAG, "setScaleMode:$mode")
if (mScaleMode != mode) {
mScaleMode = mode
}
}
/**
* カメラ映像サイズを変更要求
* @param width
* @param height
*/
fun setVideoSize(width: Int, height: Int) {
if (DEBUG) Log.v(TAG, String.format("setVideoSize:(%dx%d)", width, height))
if (requestWidth != width || (requestHeight != height)) {
requestWidth = width
requestHeight = height
// FIXME 既にカメラから映像取得中ならカメラを再設定しないといけない
if (isPreviewing) {
stopPreview()
startPreview(width, height)
}
}
}
/**
* プレビュー開始
* @param width
* @param height
*/
fun startPreview(width: Int, height: Int) {
if (DEBUG) Log.v(TAG, String.format("startPreview:(%dx%d)", width, height))
synchronized(mSync) {
if (mCameraHandler == null) {
mCameraHandler = HandlerThreadHandler.createHandler("CameraHandler")
}
isPreviewing = true
mCameraHandler!!.post {
handleStartPreview(width, height)
}
}
}
/**
* プレビュー終了
*/
fun stopPreview() {
if (DEBUG) Log.v(TAG, "stopPreview:$mCamera")
synchronized(mSync) {
isPreviewing = false
if (mCamera != null) {
mCamera!!.stopPreview()
if (mCameraHandler != null) {
mCameraHandler!!.post {
handleStopPreview()
release()
}
}
}
}
}
//--------------------------------------------------------------------------------
/**
* カメラプレビュー開始の実体
* @param width
* @param height
*/
@SuppressLint("WrongThread")
@WorkerThread
private fun handleStartPreview(width: Int, height: Int) {
if (DEBUG) Log.v(TAG, "CameraThread#handleStartPreview:(${width}x${height})")
var camera: Camera?
synchronized(mSync) {
camera = mCamera
}
if (camera == null) {
// This is a sample project so just use 0 as camera ID.
// it is better to selecting camera is available
try {
val cameraId = CameraUtils.findCamera(CameraConst.FACING_BACK)
camera = Camera.open(cameraId)
val params = camera!!.parameters
if (params != null) {
val focusModes = params.supportedFocusModes
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO)) {
params.focusMode = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO
if (DEBUG) Log.i(TAG, "handleStartPreview:FOCUS_MODE_CONTINUOUS_VIDEO")
} else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
params.focusMode = Camera.Parameters.FOCUS_MODE_AUTO
if (DEBUG) Log.i(TAG, "handleStartPreview:FOCUS_MODE_AUTO")
} else {
if (DEBUG) Log.i(TAG, "handleStartPreview:Camera does not support autofocus")
}
params.setRecordingHint(true)
CameraUtils.chooseVideoSize(params, width, height)
val fps = CameraUtils.chooseFps(params, 1.0f, 120.0f)
// rotate camera preview according to the device orientation
val degrees = CameraUtils.setupRotation(cameraId, mView, camera!!, params)
camera!!.parameters = params
// get the actual preview size
val previewSize = camera!!.parameters.previewSize
// 画面の回転状態に合わせてプレビューの映像サイズの縦横を入れ替える
if (degrees % 180 == 0) {
previewWidth = previewSize.width
previewHeight = previewSize.height
} else {
previewWidth = previewSize.height
previewHeight = previewSize.width
}
Log.d(TAG, String.format("handleStartPreview:(%dx%d)→rot%d(%dx%d),fps(%d-%d)",
previewSize.width, previewSize.height,
degrees, previewWidth, previewHeight,
fps?.get(0), fps?.get(1)))
// adjust view size with keeping the aspect ration of camera preview.
// here is not a UI thread and we should request parent view to execute.
mView.post {
cameraRenderer.onPreviewSizeChanged(previewWidth, previewHeight)
}
// カメラ映像受け取り用Surfaceをセット
val surface = cameraRenderer.getInputSurface()
if (surface is SurfaceTexture) {
surface.setDefaultBufferSize(previewWidth, previewHeight)
}
CameraUtils.setPreviewSurface(camera!!, surface)
}
} catch (e: IOException) {
Log.e(TAG, "handleStartPreview:", e)
if (camera != null) {
camera!!.release()
camera = null
}
} catch (e: RuntimeException) {
Log.e(TAG, "handleStartPreview:", e)
if (camera != null) {
camera!!.release()
camera = null
}
}
// start camera preview display
camera?.startPreview()
synchronized(mSync) {
mCamera = camera
}
}
}
/**
* カメラプレビュー終了の実体
*/
@WorkerThread
private fun handleStopPreview() {
if (DEBUG) Log.v(TAG, "CameraThread#handleStopPreview:")
synchronized(mSync) {
if (mCamera != null) {
mCamera!!.stopPreview()
mCamera!!.release()
mCamera = null
}
}
}
companion object {
private const val DEBUG = true // TODO set false on release
private val TAG = CameraDelegator::class.java.simpleName
const val SCALE_STRETCH_FIT = 0
const val SCALE_KEEP_ASPECT_VIEWPORT = 1
const val SCALE_KEEP_ASPECT = 2
const val SCALE_CROP_CENTER = 3
const val DEFAULT_PREVIEW_WIDTH = 1280
const val DEFAULT_PREVIEW_HEIGHT = 720
private const val TARGET_FPS_MS = 60 * 1000
}
}
| apache-2.0 |
westnordost/StreetComplete | app/src/main/java/de/westnordost/streetcomplete/view/StreetSideSelectPuzzle.kt | 1 | 7562 | package de.westnordost.streetcomplete.view
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Matrix
import android.graphics.Shader
import android.graphics.drawable.BitmapDrawable
import android.util.AttributeSet
import android.view.*
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.RelativeLayout
import androidx.core.view.doOnPreDraw
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.ktx.getBitmapDrawable
import de.westnordost.streetcomplete.ktx.showTapHint
import kotlinx.android.synthetic.main.side_select_puzzle.view.*
import kotlin.math.*
/** A very custom view that conceptually shows the left and right side of a street. Both sides
* are clickable.<br>
* It is possible to set an image for the left and for the right side individually, the image set
* is repeated vertically (repeated along the street). Setting a text for each side is also
* possible.<br>
* The whole displayed street can be rotated and it is possible to only show the right side, for
* example for one-way streets. */
class StreetSideSelectPuzzle @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), StreetRotateable {
var onClickSideListener: ((isRight: Boolean) -> Unit)? = null
set(value) {
field = value
if (value == null) {
leftSideContainer.setOnClickListener(null)
rightSideContainer.setOnClickListener(null)
leftSideContainer.isClickable = false
rightSideContainer.isClickable = false
} else {
rotateContainer.isClickable = false
leftSideContainer.setOnClickListener { value.invoke(false) }
rightSideContainer.setOnClickListener { value.invoke(true) }
}
}
var onClickListener: (() -> Unit)? = null
set(value) {
field = value
if (value == null) {
rotateContainer.setOnClickListener(null)
rotateContainer.isClickable = false
} else {
leftSideContainer.isClickable = false
rightSideContainer.isClickable = false
rotateContainer.setOnClickListener { value.invoke() }
}
}
private var leftImage: Image? = null
private var rightImage: Image? = null
private var isLeftImageSet: Boolean = false
private var isRightImageSet: Boolean = false
private var onlyShowingOneSide: Boolean = false
init {
LayoutInflater.from(context).inflate(R.layout.side_select_puzzle, this, true)
doOnPreDraw {
leftSideImage.pivotX = leftSideContainer.width.toFloat()
rightSideImage.pivotX = 0f
}
addOnLayoutChangeListener { _, left, top, right, bottom, _, _, _, _ ->
val width = min(bottom - top, right - left)
val height = max(bottom - top, right - left)
val params = rotateContainer.layoutParams
if(width != params.width || height != params.height) {
params.width = width
params.height = height
rotateContainer.layoutParams = params
}
val streetWidth = if (onlyShowingOneSide) width else width / 2
val leftImage = leftImage
if (!isLeftImageSet && leftImage != null) {
setStreetDrawable(leftImage, streetWidth, leftSideImage, true)
isLeftImageSet = true
}
val rightImage = rightImage
if (!isRightImageSet && rightImage != null) {
setStreetDrawable(rightImage, streetWidth, rightSideImage, false)
isRightImageSet = true
}
}
}
override fun setEnabled(enabled: Boolean) {
super.setEnabled(enabled)
foreground = if (enabled) null else resources.getDrawable(R.drawable.background_transparent_grey)
leftSideContainer.isEnabled = enabled
rightSideContainer.isEnabled = enabled
}
override fun setStreetRotation(rotation: Float) {
rotateContainer.rotation = rotation
val scale = abs(cos(rotation * PI / 180)).toFloat()
rotateContainer.scaleX = 1 + scale * 2 / 3f
rotateContainer.scaleY = 1 + scale * 2 / 3f
}
fun setLeftSideImage(image: Image?) {
leftImage = image
replace(image, leftSideImage, true)
}
fun setRightSideImage(image: Image?) {
rightImage = image
replace(image, rightSideImage, false)
}
fun replaceLeftSideImage(image: Image?) {
leftImage = image
replaceAnimated(image, leftSideImage, true)
}
fun replaceRightSideImage(image: Image?) {
rightImage = image
replaceAnimated(image, rightSideImage, false)
}
fun setLeftSideText(text: String?) {
leftSideTextView.setText(text)
}
fun setRightSideText(text: String?) {
rightSideTextView.setText(text)
}
fun showLeftSideTapHint() {
leftSideContainer.showTapHint(300)
}
fun showRightSideTapHint() {
rightSideContainer.showTapHint(1200)
}
fun showOnlyRightSide() {
isRightImageSet = false
onlyShowingOneSide = true
val params = RelativeLayout.LayoutParams(0, 0)
params.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
strut.layoutParams = params
}
fun showOnlyLeftSide() {
isLeftImageSet = false
onlyShowingOneSide = true
val params = RelativeLayout.LayoutParams(0, 0)
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
strut.layoutParams = params
}
fun showBothSides() {
isRightImageSet = false
isLeftImageSet = isRightImageSet
onlyShowingOneSide = false
val params = RelativeLayout.LayoutParams(0, 0)
params.addRule(RelativeLayout.CENTER_HORIZONTAL)
strut.layoutParams = params
}
private fun replace(image: Image?, imgView: ImageView, flip180Degrees: Boolean) {
val width = if (onlyShowingOneSide) rotateContainer.width else rotateContainer.width / 2
if (width == 0) return
setStreetDrawable(image, width, imgView, flip180Degrees)
}
private fun replaceAnimated(image: Image?, imgView: ImageView, flip180Degrees: Boolean) {
replace(image, imgView, flip180Degrees)
(imgView.parent as View).bringToFront()
imgView.scaleX = 3f
imgView.scaleY = 3f
imgView.animate().scaleX(1f).scaleY(1f)
}
private fun setStreetDrawable(image: Image?, width: Int, imageView: ImageView, flip180Degrees: Boolean) {
if (image == null) {
imageView.setImageDrawable(null)
} else {
val drawable = scaleToWidth(resources.getBitmapDrawable(image), width, flip180Degrees)
drawable.tileModeY = Shader.TileMode.REPEAT
imageView.setImageDrawable(drawable)
}
}
private fun scaleToWidth(drawable: BitmapDrawable, width: Int, flip180Degrees: Boolean): BitmapDrawable {
val m = Matrix()
val scale = width.toFloat() / drawable.intrinsicWidth
m.postScale(scale, scale)
if (flip180Degrees) m.postRotate(180f)
val bitmap = Bitmap.createBitmap(
drawable.bitmap, 0, 0,
drawable.intrinsicWidth, drawable.intrinsicHeight, m, true
)
return BitmapDrawable(resources, bitmap)
}
}
interface StreetRotateable {
fun setStreetRotation(rotation: Float)
}
| gpl-3.0 |
rhdunn/xquery-intellij-plugin | src/lang-xpath/main/uk/co/reecedunn/intellij/plugin/xpath/psi/impl/xpath/XPathSchemaAttributeTestPsiImpl.kt | 1 | 2289 | /*
* Copyright (C) 2016, 2019-2021 Reece H. Dunn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package uk.co.reecedunn.intellij.plugin.xpath.psi.impl.xpath
import com.intellij.lang.ASTNode
import com.intellij.openapi.util.Key
import uk.co.reecedunn.intellij.plugin.core.psi.ASTWrapperPsiElement
import uk.co.reecedunn.intellij.plugin.core.sequences.children
import uk.co.reecedunn.intellij.plugin.xdm.functions.op.qname_presentation
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmAttributeNode
import uk.co.reecedunn.intellij.plugin.xdm.types.XdmItemType
import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue
import uk.co.reecedunn.intellij.plugin.xpath.ast.xpath.XPathSchemaAttributeTest
class XPathSchemaAttributeTestPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), XPathSchemaAttributeTest {
companion object {
private val TYPE_NAME = Key.create<String>("TYPE_NAME")
}
// region ASTDelegatePsiElement
override fun subtreeChanged() {
super.subtreeChanged()
clearUserData(TYPE_NAME)
}
// endregion
// region XPathSchemaAttributeTest
override val nodeName: XsQNameValue?
get() = children().filterIsInstance<XsQNameValue>().firstOrNull()
// endregion
// region XdmSequenceType
override val typeName: String
get() = computeUserDataIfAbsent(TYPE_NAME) {
nodeName?.let {
"schema-attribute(${qname_presentation(it)})"
} ?: "schema-attribute(<unknown>)"
}
override val itemType: XdmItemType
get() = this
override val lowerBound: Int = 1
override val upperBound: Int = 1
// endregion
// region XdmItemType
override val typeClass: Class<*> = XdmAttributeNode::class.java
// endregion
}
| apache-2.0 |
kohesive/klutter | elasticsearch-6.x/src/main/kotlin/uy/klutter/elasticsearch/Results.kt | 1 | 604 | package uy.klutter.elasticsearch
import com.fasterxml.jackson.core.type.TypeReference
import org.elasticsearch.action.search.SearchResponse
import org.elasticsearch.search.SearchHits
inline fun <reified T: Any> SearchResponse.getHitsAsObjects(): Sequence<T> {
return getHits().getHits().asSequence().map { EsConfig.objectMapper.readValue<T>(it.sourceAsString, object : TypeReference<T>(){}) }
}
inline fun <reified T: Any> SearchHits.getHitsAsObjects(): Sequence<T> {
return getHits().asSequence().map { EsConfig.objectMapper.readValue<T>(it.sourceAsString, object : TypeReference<T>(){}) }
}
| mit |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/view/course_list/ui/fragment/CourseListVisitedHorizontalFragment.kt | 1 | 5217 | package org.stepik.android.view.course_list.ui.fragment
import android.os.Bundle
import android.view.View
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import kotlinx.android.synthetic.main.item_course_list.*
import org.stepic.droid.R
import org.stepic.droid.analytic.Analytic
import org.stepic.droid.base.App
import org.stepic.droid.core.ScreenManager
import org.stepic.droid.preferences.SharedPreferenceHelper
import org.stepic.droid.ui.util.CoursesSnapHelper
import org.stepik.android.domain.course.analytic.CourseViewSource
import org.stepik.android.domain.course_payments.mapper.DefaultPromoCodeMapper
import org.stepik.android.presentation.course_continue.model.CourseContinueInteractionSource
import org.stepik.android.presentation.course_list.CourseListView
import org.stepik.android.presentation.course_list.CourseListVisitedPresenter
import org.stepik.android.view.course.mapper.DisplayPriceMapper
import org.stepik.android.view.course_list.delegate.CourseContinueViewDelegate
import org.stepik.android.view.course_list.delegate.CourseListViewDelegate
import org.stepik.android.view.ui.delegate.ViewStateDelegate
import javax.inject.Inject
class CourseListVisitedHorizontalFragment : Fragment(R.layout.item_course_list) {
companion object {
fun newInstance(): Fragment =
CourseListVisitedHorizontalFragment()
}
@Inject
internal lateinit var analytic: Analytic
@Inject
internal lateinit var screenManager: ScreenManager
@Inject
internal lateinit var viewModelFactory: ViewModelProvider.Factory
@Inject
internal lateinit var sharedPreferenceHelper: SharedPreferenceHelper
@Inject
internal lateinit var defaultPromoCodeMapper: DefaultPromoCodeMapper
@Inject
internal lateinit var displayPriceMapper: DisplayPriceMapper
private lateinit var courseListViewDelegate: CourseListViewDelegate
private val courseListVisitedPresenter: CourseListVisitedPresenter by viewModels { viewModelFactory }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
injectComponent()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
containerCarouselCount.isVisible = false
courseListPlaceholderNoConnection.isVisible = false
courseListPlaceholderEmpty.isVisible = false
containerTitle.text = resources.getString(R.string.visited_courses_title)
with(courseListCoursesRecycler) {
val rowCount = 1
layoutManager = LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false)
itemAnimator?.changeDuration = 0
val snapHelper = CoursesSnapHelper(rowCount)
snapHelper.attachToRecyclerView(this)
}
catalogBlockContainer.setOnClickListener {
screenManager.showVisitedCourses(requireContext())
}
val viewStateDelegate = ViewStateDelegate<CourseListView.State>()
viewStateDelegate.addState<CourseListView.State.Idle>()
viewStateDelegate.addState<CourseListView.State.Loading>(view, catalogBlockContainer, courseListCoursesRecycler)
viewStateDelegate.addState<CourseListView.State.Content>(view, catalogBlockContainer, courseListCoursesRecycler)
viewStateDelegate.addState<CourseListView.State.Empty>()
viewStateDelegate.addState<CourseListView.State.NetworkError>()
courseListViewDelegate = CourseListViewDelegate(
analytic = analytic,
courseContinueViewDelegate = CourseContinueViewDelegate(
activity = requireActivity(),
analytic = analytic,
screenManager = screenManager
),
courseListTitleContainer = catalogBlockContainer,
courseItemsRecyclerView = courseListCoursesRecycler,
courseListViewStateDelegate = viewStateDelegate,
onContinueCourseClicked = { courseListItem ->
courseListVisitedPresenter
.continueCourse(
course = courseListItem.course,
viewSource = CourseViewSource.Visited,
interactionSource = CourseContinueInteractionSource.COURSE_WIDGET
)
},
defaultPromoCodeMapper = defaultPromoCodeMapper,
displayPriceMapper = displayPriceMapper,
itemAdapterDelegateType = CourseListViewDelegate.ItemAdapterDelegateType.SMALL
)
courseListVisitedPresenter.fetchCourses()
}
private fun injectComponent() {
App.component()
.courseListVisitedComponentBuilder()
.build()
.inject(this)
}
override fun onStart() {
super.onStart()
courseListVisitedPresenter.attachView(courseListViewDelegate)
}
override fun onStop() {
courseListVisitedPresenter.detachView(courseListViewDelegate)
super.onStop()
}
} | apache-2.0 |
Akjir/WiFabs | src/main/kotlin/net/kejira/wifabs/util/TFXExtensions.kt | 1 | 2187 | /*
* Copyright (c) 2017 Stefan Neubert
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.kejira.wifabs.util
import javafx.event.EventTarget
import javafx.scene.Node
import javafx.scene.control.TitledPane
import javafx.scene.layout.HBox
import javafx.scene.layout.Priority
import javafx.scene.layout.Region
import javafx.scene.layout.VBox
import tornadofx.*
import kotlin.reflect.KClass
fun EventTarget.hspacer(width: Double): Region {
val spacer = Region()
spacer.prefWidth = width
return opcr(this, spacer, null)
}
fun EventTarget.hspacer(): Region {
val spacer = Region()
HBox.setHgrow(spacer, Priority.ALWAYS)
return opcr(this, spacer)
}
fun EventTarget.titledpane(title: String, node: Node, collapsible: Boolean): TitledPane {
val pane = TitledPane(title, node)
pane.isCollapsible = collapsible
return opcr(this, pane)
}
fun EventTarget.vspacer(height: Double): Region {
val spacer = Region()
spacer.prefHeight = height
return opcr(this, spacer)
}
fun EventTarget.vspacer(): Region {
val spacer = Region()
VBox.setVgrow(spacer, Priority.ALWAYS)
return opcr(this, spacer)
}
| mit |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/functions/kt2739.kt | 5 | 211 | // KT-2739 Error type inferred for hashSet(Pair, Pair, Pair)
fun <T> foo(vararg ts: T): T? = null
class Pair<A>(a: A)
fun box(): String {
val v = foo(Pair(1))
return if (v == null) "OK" else "fail"
}
| apache-2.0 |
jiaminglu/kotlin-native | backend.native/tests/external/codegen/box/traits/inheritedFun.kt | 5 | 135 | //KT-2206
interface A {
fun f():Int = 239
}
class B() : A
fun box() : String {
return if (B().f() == 239) "OK" else "fail"
}
| apache-2.0 |
StepicOrg/stepic-android | app/src/main/java/org/stepik/android/presentation/course_revenue/CourseRevenueViewModel.kt | 1 | 498 | package org.stepik.android.presentation.course_revenue
import ru.nobird.android.presentation.redux.container.ReduxViewContainer
import ru.nobird.android.view.redux.viewmodel.ReduxViewModel
class CourseRevenueViewModel(
reduxViewContainer: ReduxViewContainer<CourseRevenueFeature.State, CourseRevenueFeature.Message, CourseRevenueFeature.Action.ViewAction>
) : ReduxViewModel<CourseRevenueFeature.State, CourseRevenueFeature.Message, CourseRevenueFeature.Action.ViewAction>(reduxViewContainer) | apache-2.0 |
jiaminglu/kotlin-native | backend.native/tests/datagen/literals/strdedup2.kt | 1 | 147 | fun main(args : Array<String>) {
val str1 = ""
val str2 = "hello".subSequence(2, 2)
println(str1 == str2)
println(str1 === str2)
}
| apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.