content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package alraune.back
//import alraune.back.AlRenderPile_killme.rawHTML
import alraune.shared.AlSharedPile_killme
import com.fasterxml.jackson.core.JsonGenerator
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializerProvider
import com.fasterxml.jackson.databind.ser.std.StdSerializer
import vgrechka.*
import java.sql.Connection
import javax.servlet.http.HttpServletResponse
import kotlin.reflect.KProperty1
//class AlkRequestContext {
//
//// /**
//// * @return null
//// * - if no session cookie
//// * - if no session with corresponding UUID in DB
//// * - TODO:vgrechka session expiration (results in deletion, so above applies?)
//// *
//// * @bailout if user is banned
//// */
//// val maybeUserWithParams: AlUserWithParams? get() {
//// val clazz = Class.forName("alraune.back.AlRequestContext")
//// val alRequestContext = clazz.getDeclaredMethod("get").invoke(null)
//// val lazyInstance = clazz.getDeclaredField("maybeUserWithParams").get(alRequestContext)
//// return lazyInstance.javaClass.getDeclaredMethod("get").invoke(lazyInstance) as AlUserWithParams?
//// }
////
////
//// val user get() = maybeUserWithParams!!
//
//// var connection by notNullOnce<Connection>()
////
//// fun <T> useConnection(block: () -> T): T {
//// connection = AlGlobalContext.dataSource.connection
//// connection.use {
//// return block()
//// }
//// }
//
//}
//fun insideMarkers(id: AlDomid, content: Renderable? = null, tamperWithAttrs: (Attrs) -> Attrs = {it}): Tag {
// val beginMarker = AlSharedPile_killme.beginContentMarkerForDOMID(id)
// val endMarker = AlSharedPile_killme.endContentMarkerForDOMID(id)
// return kdiv{o->
// o- rawHTML(beginMarker)
// o- kdiv(tamperWithAttrs(Attrs(domid = id))){o->
// o- content
// }
// o- rawHTML(endMarker)
// }
//}
interface FuckingField {
val value: String
fun validate()
fun render(): Renderable
fun noValidation()
}
class FieldContext {
val fields = mutableListOf<FuckingField>()
var hasErrors = false
fun validate() {
for (field in fields)
field.validate()
}
fun noValidation() {
for (field in fields)
field.noValidation()
}
}
//fun declareField(ctx: FieldContext,
// prop: KProperty0<String>,
// title: String,
// validator: (String?) -> ValidationResult,
// fieldType: FieldType = FieldType.TEXT): FuckingField {
// val field = object : FuckingField {
// private var vr by notNullOnce<ValidationResult>()
//
// override val value get() = vr.sanitizedString
//
// override fun noValidation() {
// vr = ValidationResult(sanitizedString = prop.get(), error = null)
// }
//
//// override fun validate() {
//// fun noise(x: String) = AlRequestContext.the.log.debug(x)
//// noise(::declareField.name + ": prop = ${prop.name}")
////
//// vr = validator(prop.get())
//// noise(" vr = $vr")
//// val theError = when {
//// AlRequestContext.the.isPost -> vr.error
//// else -> null
//// }
//// if (theError != null)
//// ctx.hasErrors = true
//// }
//
// override fun render(): Renderable {
// val theError = vr.error
// val id = AlSharedPile.fieldDOMID(name = prop.name)
// return kdiv.className("form-group"){o->
// if (theError != null)
// o.amend(Style(marginBottom = "0"))
// o - klabel(text = title)
// val control = when (fieldType) {
// FieldType.TEXT -> kinput(Attrs(type = "text", id = id, value = vr.sanitizedString, className = "form-control")) {}
// FieldType.TEXTAREA -> ktextarea(Attrs(id = id, rows = 5, className = "form-control"), text = vr.sanitizedString)
// }
// o - kdiv(Style(position = "relative")){o->
// o - control
// if (theError != null) {
// o - kdiv(Style(marginTop = "5px", marginRight = "9px", textAlign = "right", color = "${Color.RED_700}"))
// .text(theError)
// // TODO:vgrechka Shift red circle if control has scrollbar
// o - kdiv(Style(width = "15px", height = "15px", backgroundColor = "${Color.RED_300}",
// borderRadius = "10px", position = "absolute", top = "10px", right = "8px"))
// }
// }
// }
// }
// }
// ctx.fields += field
// return field
//}
interface WithFieldContext {
val fieldCtx: FieldContext
}
//class OrderParamsFields(val data: OrderParamsFormPostData) : WithFieldContext {
// val f = AlFields.order
// val v = AlBackPile
// override val fieldCtx = FieldContext()
//
// val email = declareField(fieldCtx, data::email, f.email.title, v::validateEmail)
// val contactName = declareField(fieldCtx, data::name, f.contactName.title, v::validateName)
// val phone = declareField(fieldCtx, data::phone, f.phone.title, v::validatePhone)
// val documentTitle = declareField(fieldCtx, data::documentTitle, f.documentTitle.title, v::validateDocumentTitle)
// val documentDetails = declareField(fieldCtx, data::documentDetails, f.documentDetails.title, v::validateDocumentDetails, FieldType.TEXTAREA)
// val numPages = declareField(fieldCtx, data::numPages, f.numPages.title, v::validateNumPages)
// val numSources = declareField(fieldCtx, data::numSources, f.numSources.title, v::validateNumSources)
//}
//val rctx get() = AlkRequestContext.the
object AlBackDebug {
// val idToRequestContext = ConcurrentHashMap<String, AlkRequestContext>()
@Volatile var _nextCycling2 = 0
@Volatile var _nextCycling3 = 0
fun nextCycling2(): Int {
val res = _nextCycling2++
if (_nextCycling2 > 1)
_nextCycling2 = 0
return res
}
fun nextCycling3(): Int {
val res = _nextCycling3++
if (_nextCycling3 > 2)
_nextCycling3 = 0
return res
}
}
class PropertyNameSerializer : StdSerializer<KProperty1<*, *>>(KProperty1::class.java, true) {
override fun serialize(value: KProperty1<*, *>, gen: JsonGenerator, provider: SerializerProvider) {
gen.writeString(value.name)
}
}
| attic/alraune/alraune-back/src/alraune-back.kt | 3484301656 |
package frameExtFunExtFun
fun main(args: Array<String>) {
Outer().run()
}
class A {
val aProp = 1
fun aMyFun() = 1
}
class Outer {
val outerProp = 1
fun outerMyFun() = 1
fun A.foo() {
val valFoo = 1
class LocalClass {
val lcProp = 1
fun B.test() {
val valTest = 1
lambda {
//Breakpoint!
outerProp + aProp + lcProp + bProp + valFoo + valTest
}
}
fun run() {
B().test()
}
}
LocalClass().run()
}
fun run() {
A().foo()
}
}
class B {
val bProp = 1
fun bMyFun() = 1
}
fun lambda(f: () -> Unit) {
f()
}
// PRINT_FRAME
// EXPRESSION: valFoo
// RESULT: 1: I
// EXPRESSION: valTest
// RESULT: 1: I
// EXPRESSION: aProp
// RESULT: 1: I
// EXPRESSION: outerProp
// RESULT: 1: I
// EXPRESSION: bProp
// RESULT: 1: I
// EXPRESSION: aMyFun()
// RESULT: 1: I
// EXPRESSION: outerMyFun()
// RESULT: 1: I
// EXPRESSION: bMyFun()
// RESULT: 1: I | plugins/kotlin/jvm-debugger/test/testData/evaluation/singleBreakpoint/frame/frameExtFunExtFun.kt | 755767179 |
package sample
class K {
companion object {
fun bar(p: (Int, String) -> Unit): K = K()
}
}
fun foo(){
val k : K = <caret>
}
// ELEMENT: bar
// TAIL_TEXT: "(p: (Int, String) -> Unit) (sample)"
| plugins/kotlin/completion/tests/testData/handlers/smart/ClassObjectMethod4.kt | 3588548674 |
fun foo() {
var a = 0
for (i in 0..42)
a++<caret>
}
}
| plugins/kotlin/idea/tests/testData/intentions/operatorToFunction/postfixPlusPlusInLoop.kt | 3920535073 |
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.refactoring.rename.impl
import com.intellij.model.Pointer
import com.intellij.model.search.SearchRequest
import com.intellij.model.search.SearchService
import com.intellij.model.search.impl.buildTextUsageQuery
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.project.Project
import com.intellij.psi.search.SearchScope
import com.intellij.refactoring.rename.api.*
import com.intellij.util.Query
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
fun buildQuery(project: Project, target: RenameTarget, options: RenameOptions): Query<UsagePointer> {
return buildUsageQuery(project, target, options).mapping {
ApplicationManager.getApplication().assertReadAccessAllowed()
it.createPointer()
}
}
internal fun buildUsageQuery(project: Project, target: RenameTarget, options: RenameOptions): Query<out RenameUsage> {
ApplicationManager.getApplication().assertReadAccessAllowed()
val queries = ArrayList<Query<out RenameUsage>>()
queries += searchRenameUsages(project, target, options.searchScope)
if (options.textOptions.commentStringOccurrences == true) {
queries += buildTextResultsQueries(project, target, options.searchScope, ReplaceTextTargetContext.IN_COMMENTS_AND_STRINGS)
}
if (options.textOptions.textOccurrences == true) {
queries += buildTextResultsQueries(project, target, options.searchScope, ReplaceTextTargetContext.IN_PLAIN_TEXT)
}
return SearchService.getInstance().merge(queries)
}
private fun searchRenameUsages(project: Project, target: RenameTarget, searchScope: SearchScope): Query<out RenameUsage> {
return SearchService.getInstance().searchParameters(
DefaultRenameUsageSearchParameters(project, target, searchScope)
)
}
private class DefaultRenameUsageSearchParameters(
private val project: Project,
target: RenameTarget,
override val searchScope: SearchScope
) : RenameUsageSearchParameters {
private val pointer: Pointer<out RenameTarget> = target.createPointer()
override fun areValid(): Boolean = pointer.dereference() != null
override fun getProject(): Project = project
override val target: RenameTarget get() = requireNotNull(pointer.dereference())
}
private fun buildTextResultsQueries(project: Project,
target: RenameTarget,
searchScope: SearchScope,
context: ReplaceTextTargetContext): List<Query<out RenameUsage>> {
val replaceTextTargets: Collection<ReplaceTextTarget> = target.textTargets(context)
val result = ArrayList<Query<out RenameUsage>>(replaceTextTargets.size)
for ((searchRequest: SearchRequest, usageTextByName: UsageTextByName) in replaceTextTargets) {
val effectiveSearchScope: SearchScope = searchRequest.searchScope?.let(searchScope::intersectWith) ?: searchScope
val fileUpdater = fileRangeUpdater(usageTextByName)
result += buildTextUsageQuery(project, searchRequest, effectiveSearchScope, context.searchContexts)
.mapping {
TextRenameUsage(it, fileUpdater, context)
}
}
return result
}
| platform/lang-impl/src/com/intellij/refactoring/rename/impl/search.kt | 447824140 |
// "Create member function 'A.unaryMinus'" "true"
class A<T>(val n: T)
fun <U> test(u: U) {
val a: A<U> = <caret>-A(u)
} | plugins/kotlin/idea/tests/testData/quickfix/createFromUsage/createFunction/unaryOperations/minusOnUserTypeWithTypeParams.kt | 1560734062 |
// RUNTIME_WITH_KOTLIN_TEST
import kotlin.test.*
fun foo() {
val a = "a"
val b = "a"
assertTrue<caret>(a == b)
} | plugins/kotlin/idea/tests/testData/inspectionsLocal/replaceAssertBooleanWithAssertEquality/assertTrueEQEQ.kt | 346084140 |
package baz
import foo.z
fun test() = z + 1 | plugins/kotlin/idea/tests/testData/refactoring/inline/inlineVariableOrProperty/property/multiplePackages.4.kt | 3373752256 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
@file:JvmName("FacetTestUtils")
package com.intellij.facet.mock
import com.intellij.facet.FacetType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.application.runWriteActionAndWait
import com.intellij.openapi.util.Disposer
inline fun <T> runWithRegisteredFacetTypes(vararg types: FacetType<*, *>, action: () -> T): T {
val disposable = Disposer.newDisposable()
for (type in types) {
registerFacetType(type, disposable)
}
try {
return action()
}
finally {
Disposer.dispose(disposable)
}
}
fun registerFacetType(type: FacetType<*, *>, disposable: Disposable) {
val facetTypeDisposable = Disposer.newDisposable()
Disposer.register(disposable, Disposable {
runWriteActionAndWait {
Disposer.dispose(facetTypeDisposable)
}
})
runWriteActionAndWait {
FacetType.EP_NAME.point.registerExtension(type, facetTypeDisposable)
}
}
| platform/testFramework/src/com/intellij/facet/mock/facetTestUtils.kt | 274275754 |
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.filePrediction.features.history
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManagerListener
class FilePredictionProjectListener : ProjectManagerListener {
override fun projectClosing(project: Project) {
FilePredictionHistory.getInstanceIfCreated(project)?.saveFilePredictionHistory(project)
}
} | plugins/filePrediction/src/com/intellij/filePrediction/features/history/FilePredictionProjectListener.kt | 3898845000 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.structuralsearch.replace
import org.jetbrains.kotlin.idea.structuralsearch.KotlinSSRReplaceTest
class KotlinSSRQualifiedExpressionReplaceTest : KotlinSSRReplaceTest() {
fun testQualifiedExpressionReceiverWithCountFilter() {
doTest(
searchPattern = "'_BEFORE{0,1}.'_FUN()",
replacePattern = "'_BEFORE.foo('_ARG)",
match = """
fun main() {
bar()
}
""".trimIndent(),
result = """
fun main() {
foo()
}
""".trimIndent()
)
}
fun testDoubleQualifiedExpression() {
doTest(
searchPattern = """
'_REC.foo = '_INIT
'_REC.bar = '_INIT
""".trimIndent(),
replacePattern = """
'_REC.fooBar = '_INIT
""".trimIndent(),
match = """
fun main() {
x.foo = true
x.bar = true
}
""".trimIndent(),
result = """
fun main() {
x.fooBar = true
}
""".trimIndent()
)
}
} | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/replace/KotlinSSRQualifiedExpressionReplaceTest.kt | 2068430005 |
import java.util.*
internal class A {
private val collection: MutableCollection<String>
init {
collection = createCollection()
}
fun createCollection(): MutableCollection<String> {
return ArrayList()
}
fun foo() {
collection.add("1")
}
fun getCollection(): Collection<String> {
return collection
}
}
| plugins/kotlin/j2k/old/tests/testData/fileOrElement/mutableCollections/FunctionReturnValue2.kt | 3924563170 |
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.diagnostics.DiagnosticWithParameters2
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.inspections.ConstantConditionIfInspection
import org.jetbrains.kotlin.idea.intentions.SimplifyBooleanWithConstantsIntention
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
class SimplifyComparisonFix(element: KtExpression, val value: Boolean) : KotlinQuickFixAction<KtExpression>(element) {
override fun getFamilyName() = KotlinBundle.message("simplify.0.to.1", element.toString(), value)
override fun getText() = KotlinBundle.message("simplify.comparison")
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val element = element ?: return
val replacement = KtPsiFactory(element).createExpression("$value")
val result = element.replaced(replacement)
val booleanExpression = result.getNonStrictParentOfType<KtBinaryExpression>()
val simplifyIntention = SimplifyBooleanWithConstantsIntention()
if (booleanExpression != null && simplifyIntention.isApplicableTo(booleanExpression)) {
simplifyIntention.applyTo(booleanExpression, editor)
} else {
simplifyIntention.removeRedundantAssertion(result)
}
val ifExpression = result.getStrictParentOfType<KtIfExpression>()?.takeIf { it.condition == result }
if (ifExpression != null) ConstantConditionIfInspection.applyFixIfSingle(ifExpression)
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic): IntentionAction? {
val expression = diagnostic.psiElement as? KtExpression ?: return null
val value = (diagnostic as? DiagnosticWithParameters2<*, *, *>)?.b as? Boolean ?: return null
return SimplifyComparisonFix(expression, value)
}
}
} | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/SimplifyComparisonFix.kt | 821799794 |
fun ktTestWithParen() {
TestWithParen.foo("SomeTest", 1<caret>)
}
//INFO: <div class='definition'><pre><i><span style="color:#808000;">@</span><a href="psi_element://org.jetbrains.annotations.Contract"><code><span style="color:#808000;">Contract</span></code></a><span style="">(</span><span style="">value</span><span style=""> = </span><span style="color:#008000;font-weight:bold;">"_, _ -> new"</span><span style="">, </span><span style="">pure</span><span style=""> = </span><span style="color:#000080;font-weight:bold;">true</span><span style="">)</span></i>
//INFO: <i><span style="color:#808000;">@</span><a href="psi_element://org.jetbrains.annotations.NotNull"><code><span style="color:#808000;">NotNull</span></code></a></i>
//INFO: <span style="color:#000080;font-weight:bold;">public static</span> <a href="psi_element://java.lang.Object"><code><span style="color:#000000;">Object</span></code></a><span style="">[]</span> <span style="color:#000000;">foo</span><span style="">(</span><br> <a href="psi_element://java.lang.String"><code><span style="color:#000000;">String</span></code></a> <span style="">str</span><span style="">,</span>
//INFO: <span style="color:#000080;font-weight:bold;">int</span> <span style="">num</span><br><span style="">)</span></pre></div><div class='content'>
//INFO: Java Method
//INFO: </div><table class='sections'><tr><td valign='top' class='section'><p><i>Inferred</i><br> annotations:</td><td valign='top'><p><i><span style="color:#808000;">@</span><a href="psi_element://org.jetbrains.annotations.Contract"><span style="color:#808000;">org.jetbrains.annotations.Contract</span></a><span style="">(</span><span style="">value</span><span style=""> = </span><span style="color:#008000;font-weight:bold;">"_, _ -> new"</span><span style="">, </span><span style="">pure</span><span style=""> = </span><span style="color:#000080;font-weight:bold;">true</span><span style="">)</span></i><br><i><span style="color:#808000;">@</span><a href="psi_element://org.jetbrains.annotations.NotNull"><span style="color:#808000;">org.jetbrains.annotations.NotNull</span></a></i></td></table><div class="bottom"><icon src="AllIcons.Nodes.Class"> <a href="psi_element://TestWithParen"><code><span style="color:#000000;">TestWithParen</span></code></a></div>
| plugins/kotlin/idea/tests/testData/editor/quickDoc/JavaMethodUsedInKotlinInParen.kt | 1684422169 |
/*
* Copyright 2000-2020 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.stats.completion.logger
import com.intellij.stats.completion.network.assertNotEDT
import com.intellij.stats.completion.storage.FilePathProvider
import java.io.File
class LogFileManager(private val filePathProvider: FilePathProvider, private val chunkSizeLimit: Int = MAX_CHUNK_SIZE) : FileLogger {
private companion object {
const val MAX_CHUNK_SIZE = 30 * 1024
}
private var storage = LineStorage()
override fun printLines(lines: List<String>) {
synchronized(this) {
for (line in lines) {
storage.appendLine(line)
}
if (storage.size > chunkSizeLimit) {
flushImpl()
}
}
}
override fun flush() {
synchronized(this) {
if (storage.size > 0) {
flushImpl()
}
}
}
private fun flushImpl() {
saveDataChunk(storage)
filePathProvider.cleanupOldFiles()
storage = LineStorage()
}
private fun saveDataChunk(storage: LineStorage) {
assertNotEDT()
val dir = filePathProvider.getStatsDataDirectory()
val tmp = File(dir, "tmp_data.gz")
storage.dump(tmp)
tmp.renameTo(filePathProvider.getUniqueFile())
}
} | plugins/stats-collector/src/com/intellij/stats/completion/logger/LogFileManager.kt | 3106708987 |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.completion.ml.personalization.session
import kotlin.math.max
import kotlin.math.min
class PeriodTracker {
private val durations: MutableList<Long> = mutableListOf()
fun minDuration(currentPeriod: Long?): Long? {
val pastMin = durations.minOrNull()
if (pastMin == null) return currentPeriod
if (currentPeriod != null) {
return min(pastMin, currentPeriod)
}
return pastMin
}
fun maxDuration(currentPeriod: Long?): Long? {
val pastMax = durations.maxOrNull()
if (pastMax == null) return currentPeriod
if (currentPeriod != null) {
return max(pastMax, currentPeriod)
}
return pastMax
}
fun average(currentPeriod: Long?): Double {
if (durations.isEmpty()) return currentPeriod?.toDouble() ?: 0.0
val pastAvg = durations.average()
if (currentPeriod == null) return pastAvg
val n = durations.size
return pastAvg * n / (n + 1) + currentPeriod / (n + 1)
}
fun count(currentPeriod: Long?): Int = durations.size + (if (currentPeriod != null) 1 else 0)
fun totalTime(currentPeriod: Long?): Long = durations.sum() + (currentPeriod ?: 0)
fun addDuration(duration: Long) {
durations.add(duration)
}
} | plugins/completion-ml-ranking/src/com/intellij/completion/ml/personalization/session/PeriodTracker.kt | 3052463445 |
fun foo(b1: Boolean, b2: Boolean) {
when {
<caret>
}
}
// EXIST: b1
// EXIST: b2
// ABSENT: true
// ABSENT: false
// ABSENT: else
| plugins/kotlin/completion/tests/testData/smart/whenEntry/WhenWithNoSubject1.kt | 1833136699 |
// PROBLEM: none
val <caret>withGetter get() = 42 | plugins/kotlin/idea/tests/testData/inspectionsLocal/mayBeConstant/getter.kt | 1550717527 |
/*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * 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.sinyuk.fanfou.util.span
internal class WordPosition(var start: Int, var end: Int) {
override fun toString(): String {
return "WordPosition{" +
"upload=" + start +
", end=" + end +
'}'.toString()
}
} | presentation/src/main/java/com/sinyuk/fanfou/util/span/WordPosition.kt | 1005173999 |
package biz.dealnote.messenger.util
/**
* Created by ruslan.kolbasa on 01.02.2017.
* phoenix
*/
class Pair<F, S>(val first: F, val second: S) {
companion object {
fun <F, S> create(first: F, second: S): Pair<F, S> {
return Pair(first, second)
}
}
}
| app/src/main/java/biz/dealnote/messenger/util/Pair.kt | 51166626 |
package com.github.stakkato95.kmusic.mvp.di.component
import com.github.stakkato95.kmusic.mvp.di.module.AppModule
import com.github.stakkato95.kmusic.mvp.di.module.RepositoryModule
import com.github.stakkato95.kmusic.mvp.di.module.TrackInfoModule
import com.github.stakkato95.kmusic.mvp.di.module.TrackProgressModule
import com.github.stakkato95.kmusic.mvp.di.scope.ApplicationScope
import dagger.Component
/**
* Created by artsiomkaliaha on 04.10.17.
*/
@Component(modules = [AppModule::class, RepositoryModule::class])
@ApplicationScope
interface AppComponent {
fun plusSingleTrackComponent(): SingleTrackComponent
fun plusTrackProgressComponent(module: TrackProgressModule): TrackProgressComponent
fun plusTrackInfoComponent(module: TrackInfoModule): TrackInfoComponent
} | KMusic/app/src/main/java/com/github/stakkato95/kmusic/mvp/di/component/AppComponent.kt | 1102395978 |
package pl.lizardproject.qe2017.model
class Item(val id: Int?, val name: String, val category: Category, val priority: Priority, val user: User, val isChecked: Boolean = false) {
fun checkItem(check: Boolean) = Item(id, name, category, priority, user, check)
} | Aplikacja/app/src/main/kotlin/pl/lizardproject/qe2017/model/Item.kt | 547255729 |
/*
* Copyright 2002-2022 the original author or 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.headers
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer
import org.springframework.security.web.header.writers.XXssProtectionHeaderWriter.HeaderValue
/**
* A Kotlin DSL to configure the [HttpSecurity] XSS protection header using
* idiomatic Kotlin code.
*
* @author Eleftheria Stein
* @author Daniel Garnier-Moiroux
* @since 5.3
* @property headerValue the value of the X-XSS-Protection header. OWASP recommends [HeaderValue.DISABLED].
*/
@HeadersSecurityMarker
class XssProtectionConfigDsl {
var headerValue: HeaderValue? = null
private var disabled = false
/**
* Do not include the X-XSS-Protection header in the response.
*/
fun disable() {
disabled = true
}
internal fun get(): (HeadersConfigurer<HttpSecurity>.XXssConfig) -> Unit {
return { xssProtection ->
headerValue?.also { xssProtection.headerValue(headerValue) }
if (disabled) {
xssProtection.disable()
}
}
}
}
| config/src/main/kotlin/org/springframework/security/config/annotation/web/headers/XssProtectionConfigDsl.kt | 2588058457 |
package com.mapzen.erasermap.model
import com.mapzen.android.lost.api.LostApiClient
interface LocationClientManager {
fun getClient(): LostApiClient
fun connect()
fun disconnect()
fun addRunnableToRunOnConnect(runnable: Runnable)
}
| app/src/main/kotlin/com/mapzen/erasermap/model/LocationClientManager.kt | 3390134263 |
package com.alexstyl.specialdates.person
import android.view.View
import com.alexstyl.specialdates.Strings
import com.alexstyl.specialdates.contact.Contact
import com.alexstyl.specialdates.date.ContactEvent
import com.alexstyl.specialdates.date.Date
class PersonDetailsViewModelFactory(private val strings: Strings, private val ageCalculator: AgeCalculator) {
operator fun invoke(contact: Contact, dateOfBirth: ContactEvent?, isVisible: Boolean): PersonInfoViewModel {
val ageAndStarSignBuilder = StringBuilder()
if (dateOfBirth != null) {
ageAndStarSignBuilder.append(ageCalculator.ageOf(dateOfBirth.date))
if (ageAndStarSignBuilder.isNotEmpty()) {
ageAndStarSignBuilder.append(", ")
}
ageAndStarSignBuilder.append(starSignOf(dateOfBirth.date))
}
return PersonInfoViewModel(contact.displayName.toString(),
ageAndStarSignBuilder.toString(),
if (ageAndStarSignBuilder.isEmpty()) View.GONE else View.VISIBLE,
contact.imagePath,
isVisible)
}
private fun starSignOf(birthday: Date): String {
val starSign = StarSign.forDateOfBirth(birthday)
return strings.nameOf(starSign) + " " + starSign.emoji
}
}
| android_mobile/src/main/java/com/alexstyl/specialdates/person/PersonDetailsViewModelFactory.kt | 2175951362 |
package ds.meterscanner.mvvm
import android.content.Context
import android.support.v7.util.DiffUtil
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import ds.meterscanner.adapter.DiffCallback
import java.lang.reflect.ParameterizedType
abstract class SimpleAdapter<H : RecyclerView.ViewHolder, D : Any>(
data: List<D> = emptyList()
) : RecyclerView.Adapter<H>() {
lateinit protected var context: Context
var data: List<D> = data
set(value) {
val diffResult = DiffUtil.calculateDiff(DiffCallback(field, value))
field = value
diffResult.dispatchUpdatesTo(this)
}
override fun getItemCount(): Int = data.size
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
context = recyclerView.context
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): H {
val inflater = LayoutInflater.from(parent.context)
val view = inflater.inflate(layoutId, parent, false)
return instantiateHolder(view)
}
override fun onBindViewHolder(holder: H, position: Int) {
val item = getItem(position)
onFillView(holder, item, position)
}
fun getItem(position: Int): D = data[position]
override fun getItemId(position: Int): Long = position.toLong()
protected abstract val layoutId: Int
protected abstract fun onFillView(holder: H, item: D, position: Int): Any
open protected fun instantiateHolder(view: View): H = getHolderType().getConstructor(View::class.java).newInstance(view)
@Suppress("UNCHECKED_CAST")
private fun getHolderType(): Class<H> = getParametrizedType(javaClass).actualTypeArguments[0] as Class<H>
private fun getParametrizedType(clazz: Class<*>): ParameterizedType =
if (clazz.superclass == SimpleAdapter::class.java) { // check that we are at the top of the hierarchy
clazz.genericSuperclass as ParameterizedType
} else {
getParametrizedType(clazz.superclass)
}
}
| app/src/main/java/ds/meterscanner/mvvm/SimpleAdapter.kt | 2590196935 |
package debugattach
import settings.ApplicationSettings
import utils.pathForPid
import com.intellij.execution.process.ProcessInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.IconLoader
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.UserDataHolder
import com.intellij.xdebugger.attach.*
import com.jetbrains.python.sdk.PythonSdkType
import com.jetbrains.python.sdk.PythonSdkUtil
import javax.swing.Icon
private val mayaPathsKey = Key<MutableMap<Int, String>>("mayaPathsMap")
class MayaAttachDebuggerProvider : XAttachDebuggerProvider {
override fun getPresentationGroup(): XAttachPresentationGroup<ProcessInfo> {
return MayaAttachGroup.INSTANCE
}
override fun getAvailableDebuggers(project: Project, attachHost: XAttachHost, processInfo: ProcessInfo, userData: UserDataHolder): MutableList<XAttachDebugger> {
if (!processInfo.executableName.toLowerCase().contains("maya")) return mutableListOf()
val exePath = processInfo.executableCannonicalPath.let {
if (it.isPresent) it.get() else pathForPid(processInfo.pid) ?: return mutableListOf()
}.toLowerCase()
val currentSdk = ApplicationSettings.INSTANCE.mayaSdkMapping.values.firstOrNull {
exePath.contains(it.mayaPath.toLowerCase())
} ?: return mutableListOf()
val mayaPathMap = userData.getUserData(mayaPathsKey) ?: mutableMapOf()
mayaPathMap[processInfo.pid] = currentSdk.mayaPath
userData.putUserData(mayaPathsKey, mayaPathMap)
PythonSdkUtil.findSdkByPath(currentSdk.mayaPyPath)?.let {
return mutableListOf(MayaAttachDebugger(it, currentSdk))
}
return mutableListOf()
}
override fun isAttachHostApplicable(attachHost: XAttachHost): Boolean = attachHost is LocalAttachHost
}
private class MayaAttachDebugger(sdk: Sdk, private val mayaSdk: ApplicationSettings.SdkInfo) : XAttachDebugger {
private val mySdkHome: String? = sdk.homePath
private val myName: String = "${PythonSdkType.getInstance().getVersionString(sdk)} ($mySdkHome)"
override fun getDebuggerDisplayName(): String {
return myName
}
override fun attachDebugSession(project: Project, attachHost: XAttachHost, processInfo: ProcessInfo) {
val runner = MayaAttachToProcessDebugRunner(project, processInfo.pid, mySdkHome, mayaSdk)
runner.launch()
}
}
private class MayaAttachGroup : XAttachProcessPresentationGroup {
companion object {
val INSTANCE = MayaAttachGroup()
}
override fun getItemDisplayText(project: Project, processInfo: ProcessInfo, userData: UserDataHolder): String {
val mayaPaths = userData.getUserData(mayaPathsKey) ?: return processInfo.executableDisplayName
return mayaPaths[processInfo.pid] ?: processInfo.executableDisplayName
}
override fun getProcessDisplayText(project: Project, info: ProcessInfo, userData: UserDataHolder): String {
return getItemDisplayText(project, info, userData)
}
override fun getItemIcon(project: Project, processInfo: ProcessInfo, userData: UserDataHolder): Icon {
return IconLoader.getIcon("/icons/MayaCharm_ToolWindow.png", this::class.java)
}
override fun getProcessIcon(project: Project, info: ProcessInfo, userData: UserDataHolder): Icon {
return getItemIcon(project, info, userData)
}
override fun getGroupName(): String {
return "Maya"
}
override fun getOrder(): Int {
return -100
}
}
| src/main/kotlin/debugattach/MayaAttachDebuggerProvider.kt | 3698098027 |
/*
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.uamp.media.library
import android.net.Uri
import android.support.v4.media.MediaBrowserCompat.MediaItem
import android.support.v4.media.MediaDescriptionCompat.STATUS_NOT_DOWNLOADED
import android.support.v4.media.MediaMetadataCompat
import com.example.android.uamp.media.extensions.album
import com.example.android.uamp.media.extensions.albumArtUri
import com.example.android.uamp.media.extensions.artist
import com.example.android.uamp.media.extensions.displayDescription
import com.example.android.uamp.media.extensions.displayIconUri
import com.example.android.uamp.media.extensions.displaySubtitle
import com.example.android.uamp.media.extensions.displayTitle
import com.example.android.uamp.media.extensions.downloadStatus
import com.example.android.uamp.media.extensions.duration
import com.example.android.uamp.media.extensions.flag
import com.example.android.uamp.media.extensions.genre
import com.example.android.uamp.media.extensions.id
import com.example.android.uamp.media.extensions.mediaUri
import com.example.android.uamp.media.extensions.title
import com.example.android.uamp.media.extensions.trackCount
import com.example.android.uamp.media.extensions.trackNumber
import com.google.gson.Gson
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.IOException
import java.io.InputStreamReader
import java.net.URL
import java.util.concurrent.TimeUnit
/**
* Source of [MediaMetadataCompat] objects created from a basic JSON stream.
*
* The definition of the JSON is specified in the docs of [JsonMusic] in this file,
* which is the object representation of it.
*/
internal class JsonSource(private val source: Uri) : AbstractMusicSource() {
companion object {
const val ORIGINAL_ARTWORK_URI_KEY = "com.example.android.uamp.JSON_ARTWORK_URI"
}
private var catalog: List<MediaMetadataCompat> = emptyList()
init {
state = STATE_INITIALIZING
}
override fun iterator(): Iterator<MediaMetadataCompat> = catalog.iterator()
override suspend fun load() {
updateCatalog(source)?.let { updatedCatalog ->
catalog = updatedCatalog
state = STATE_INITIALIZED
} ?: run {
catalog = emptyList()
state = STATE_ERROR
}
}
/**
* Function to connect to a remote URI and download/process the JSON file that corresponds to
* [MediaMetadataCompat] objects.
*/
private suspend fun updateCatalog(catalogUri: Uri): List<MediaMetadataCompat>? {
return withContext(Dispatchers.IO) {
val musicCat = try {
downloadJson(catalogUri)
} catch (ioException: IOException) {
return@withContext null
}
// Get the base URI to fix up relative references later.
val baseUri = catalogUri.toString().removeSuffix(catalogUri.lastPathSegment ?: "")
val mediaMetadataCompats = musicCat.music.map { song ->
// The JSON may have paths that are relative to the source of the JSON
// itself. We need to fix them up here to turn them into absolute paths.
catalogUri.scheme?.let { scheme ->
if (!song.source.startsWith(scheme)) {
song.source = baseUri + song.source
}
if (!song.image.startsWith(scheme)) {
song.image = baseUri + song.image
}
}
val jsonImageUri = Uri.parse(song.image)
val imageUri = AlbumArtContentProvider.mapUri(jsonImageUri)
MediaMetadataCompat.Builder()
.from(song)
.apply {
displayIconUri = imageUri.toString() // Used by ExoPlayer and Notification
albumArtUri = imageUri.toString()
// Keep the original artwork URI for being included in Cast metadata object.
putString(ORIGINAL_ARTWORK_URI_KEY, jsonImageUri.toString())
}
.build()
}.toList()
// Add description keys to be used by the ExoPlayer MediaSession extension when
// announcing metadata changes.
mediaMetadataCompats.forEach { it.description.extras?.putAll(it.bundle) }
mediaMetadataCompats
}
}
/**
* Attempts to download a catalog from a given Uri.
*
* @param catalogUri URI to attempt to download the catalog form.
* @return The catalog downloaded, or an empty catalog if an error occurred.
*/
@Throws(IOException::class)
private fun downloadJson(catalogUri: Uri): JsonCatalog {
val catalogConn = URL(catalogUri.toString())
val reader = BufferedReader(InputStreamReader(catalogConn.openStream()))
return Gson().fromJson(reader, JsonCatalog::class.java)
}
}
/**
* Extension method for [MediaMetadataCompat.Builder] to set the fields from
* our JSON constructed object (to make the code a bit easier to see).
*/
fun MediaMetadataCompat.Builder.from(jsonMusic: JsonMusic): MediaMetadataCompat.Builder {
// The duration from the JSON is given in seconds, but the rest of the code works in
// milliseconds. Here's where we convert to the proper units.
val durationMs = TimeUnit.SECONDS.toMillis(jsonMusic.duration)
id = jsonMusic.id
title = jsonMusic.title
artist = jsonMusic.artist
album = jsonMusic.album
duration = durationMs
genre = jsonMusic.genre
mediaUri = jsonMusic.source
albumArtUri = jsonMusic.image
trackNumber = jsonMusic.trackNumber
trackCount = jsonMusic.totalTrackCount
flag = MediaItem.FLAG_PLAYABLE
// To make things easier for *displaying* these, set the display properties as well.
displayTitle = jsonMusic.title
displaySubtitle = jsonMusic.artist
displayDescription = jsonMusic.album
displayIconUri = jsonMusic.image
// Add downloadStatus to force the creation of an "extras" bundle in the resulting
// MediaMetadataCompat object. This is needed to send accurate metadata to the
// media session during updates.
downloadStatus = STATUS_NOT_DOWNLOADED
// Allow it to be used in the typical builder style.
return this
}
/**
* Wrapper object for our JSON in order to be processed easily by GSON.
*/
class JsonCatalog {
var music: List<JsonMusic> = ArrayList()
}
/**
* An individual piece of music included in our JSON catalog.
* The format from the server is as specified:
* ```
* { "music" : [
* { "title" : // Title of the piece of music
* "album" : // Album title of the piece of music
* "artist" : // Artist of the piece of music
* "genre" : // Primary genre of the music
* "source" : // Path to the music, which may be relative
* "image" : // Path to the art for the music, which may be relative
* "trackNumber" : // Track number
* "totalTrackCount" : // Track count
* "duration" : // Duration of the music in seconds
* "site" : // Source of the music, if applicable
* }
* ]}
* ```
*
* `source` and `image` can be provided in either relative or
* absolute paths. For example:
* ``
* "source" : "https://www.example.com/music/ode_to_joy.mp3",
* "image" : "ode_to_joy.jpg"
* ``
*
* The `source` specifies the full URI to download the piece of music from, but
* `image` will be fetched relative to the path of the JSON file itself. This means
* that if the JSON was at "https://www.example.com/json/music.json" then the image would be found
* at "https://www.example.com/json/ode_to_joy.jpg".
*/
@Suppress("unused")
class JsonMusic {
var id: String = ""
var title: String = ""
var album: String = ""
var artist: String = ""
var genre: String = ""
var source: String = ""
var image: String = ""
var trackNumber: Long = 0
var totalTrackCount: Long = 0
var duration: Long = -1
var site: String = ""
}
| common/src/main/java/com/example/android/uamp/media/library/JsonSource.kt | 3991448324 |
package com.orgzly.android.db.dao
import androidx.lifecycle.LiveData
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.orgzly.android.db.entity.Book
import com.orgzly.android.db.entity.BookAction
@Dao
abstract class BookDao : BaseDao<Book> {
@Query("SELECT * FROM books WHERE id = :id")
abstract fun get(id: Long): Book?
@Query("SELECT * FROM books WHERE name = :name")
abstract fun get(name: String): Book?
@Query("SELECT * FROM books WHERE id = :id")
abstract fun getLiveData(id: Long): LiveData<Book> // null not allowed, use List
@Query("SELECT * FROM books WHERE last_action_type = :type")
abstract fun getWithActionType(type: BookAction.Type): List<Book>
@Insert
abstract fun insertBooks(vararg books: Book): LongArray
@Update
abstract fun updateBooks(vararg book: Book): Int
@Query("UPDATE books SET preface = :preface, title = :title WHERE id = :id")
abstract fun updatePreface(id: Long, preface: String?, title: String?)
@Query("UPDATE books SET last_action_type = :type, last_action_message = :message, last_action_timestamp = :timestamp WHERE id = :id")
abstract fun updateLastAction(id: Long, type: BookAction.Type, message: String, timestamp: Long)
@Query("UPDATE books SET last_action_type = :type, last_action_message = :message, last_action_timestamp = :timestamp, sync_status = :status WHERE id = :id")
abstract fun updateLastActionAndSyncStatus(id: Long, type: BookAction.Type, message: String, timestamp: Long, status: String?): Int
@Query("UPDATE books SET last_action_type = :type, last_action_message = :message, last_action_timestamp = :timestamp, sync_status = :status WHERE last_action_type = :whereType")
abstract fun updateStatusToCanceled(whereType: BookAction.Type, type: BookAction.Type, message: String, timestamp: Long, status: String?): Int
@Query("UPDATE books SET name = :name WHERE id = :id")
abstract fun updateName(id: Long, name: String): Int
@Query("UPDATE books SET is_dummy = :dummy WHERE id = :id")
abstract fun updateDummy(id: Long, dummy: Boolean)
@Query("UPDATE books SET mtime = :mtime, is_modified = 1 WHERE id IN (:ids)")
abstract fun setIsModified(ids: Set<Long>, mtime: Long): Int
@Query("UPDATE books SET is_modified = 0 WHERE id IN (:ids)")
abstract fun setIsNotModified(ids: Set<Long>): Int
fun getOrInsert(name: String): Long =
get(name).let {
it?.id ?: insert(Book(0, name, isDummy = true))
}
}
| app/src/main/java/com/orgzly/android/db/dao/BookDao.kt | 1509028818 |
package com.rpkit.blocklog.bukkit.listener
import com.rpkit.blocklog.bukkit.RPKBlockLoggingBukkit
import com.rpkit.blocklog.bukkit.block.RPKBlockChangeImpl
import com.rpkit.blocklog.bukkit.block.RPKBlockHistoryProvider
import org.bukkit.event.EventHandler
import org.bukkit.event.EventPriority.MONITOR
import org.bukkit.event.Listener
import org.bukkit.event.block.BlockFormEvent
class BlockFormListener(private val plugin: RPKBlockLoggingBukkit): Listener {
@EventHandler(priority = MONITOR)
fun onBlockForm(event: BlockFormEvent) {
val blockHistoryProvider = plugin.core.serviceManager.getServiceProvider(RPKBlockHistoryProvider::class)
val blockHistory = blockHistoryProvider.getBlockHistory(event.block)
val blockChange = RPKBlockChangeImpl(
blockHistory = blockHistory,
time = System.currentTimeMillis(),
profile = null,
minecraftProfile = null,
character = null,
from = event.block.type,
to = event.newState.type,
reason = "FORM"
)
blockHistoryProvider.addBlockChange(blockChange)
}
} | bukkit/rpk-block-logging-bukkit/src/main/kotlin/com/rpkit/blocklog/bukkit/listener/BlockFormListener.kt | 800071976 |
package com.petertackage.kotlinoptions
/**
* @return an [Iterable] containing all elements of the original [Iterable] which are [Some].
*/
fun <T : Any> Iterable<Option<T>>.filterNotNone(): Iterable<T> {
return mapNotNull(Option<T>::toNullable)
}
/** @Deprecated
* @return an [Iterable] containing all elements of the original [Iterable] which are [Some].
*/
@Deprecated("Does not alight with kotlin naming convention",
ReplaceWith("filterNotNone()"))
fun <T : Any> Iterable<Option<T>>.filterIfSome(): Iterable<T> {
return filterNotNone()
}
/**
* @return an [Iterable] containing all elements of the original [Iterable] which are [Some] and that satisfy [predicate].
*/
fun <T : Any> Iterable<Option<T>>.filterNotNone(predicate: (T) -> Boolean): Iterable<T> {
return mapNotNull(Option<T>::toNullable).filter(predicate)
}
/** @Deprecated
* @return an [Iterable] containing all elements of the original [Iterable] which are [Some] and that satisfy [predicate].
*/
@Deprecated("Does not alight with kotlin naming convention",
ReplaceWith("filterNotNone(predicate)"))
fun <T : Any> Iterable<Option<T>>.filterIfSome(predicate: (T) -> Boolean): Iterable<T> {
return filterNotNone(predicate)
}
| kotlin-options/src/main/kotlin/com/petertackage/kotlinoptions/IterableExtensions.kt | 400227152 |
/*
Copyright 2015 Andreas Würl
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package org.blitzortung.android.alert.handler
import kotlin.math.min
internal class AggregatingAlertSector(
val label: String,
val minimumSectorBearing: Float,
val maximumSectorBearing: Float,
val ranges: List<AggregatingAlertSectorRange>
) {
var closestStrikeDistance: Float = Float.POSITIVE_INFINITY
private set
fun updateClosestStrikeDistance(distance: Float) {
closestStrikeDistance = min(distance, closestStrikeDistance)
}
}
| app/src/main/java/org/blitzortung/android/alert/handler/AggregatingAlertSector.kt | 432602657 |
package i_introduction._12_Extensions_On_Collections
import util.*
fun todoTask12(): Nothing = TODO(
"""
Task 12.
In Kotlin standard library there are lots of extension functions that make the work with collections more convenient.
Rewrite the previous example once more using an extension function 'sortedDescending'.
Kotlin code can be easily mixed with Java code.
Thus in Kotlin we don't introduce our own collections, but use standard Java ones (slightly improved).
Read about read-only and mutable views on Java collections.
""",
documentation = doc12()
)
fun task12(): List<Int> {
// todoTask12()
return arrayListOf(1, 5, 2).sortedDescending()
}
| src/i_introduction/_12_Extensions_On_Collections/ExtensionsOnCollections.kt | 890344898 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.codeInsight.intention
import com.intellij.lang.Language
import com.intellij.lang.LanguageExtension
import com.intellij.openapi.components.ServiceManager
import com.intellij.psi.*
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.uast.UClass
import org.jetbrains.uast.UDeclaration
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UastContext
/**
* Extension Point provides language-abstracted code modifications for JVM-based languages.
*
* Each method should return nullable code modification ([IntentionAction]) or list of code modifications which could be empty.
* If method returns `null` or empty list this means that operation on given elements is not supported or not yet implemented for a language.
*
* Every new added method should return `null` or empty list by default and then be overridden in implementations for each language if it is possible.
*
* @since 2017.2
*/
@ApiStatus.Experimental
abstract class JvmCommonIntentionActionsFactory {
open fun createChangeModifierAction(declaration: @JvmCommon PsiModifierListOwner,
@PsiModifier.ModifierConstant modifier: String,
shouldPresent: Boolean): IntentionAction? =
//Fallback if Uast-version of method is overridden
createChangeModifierAction(declaration.asUast<UDeclaration>(), modifier, shouldPresent)
open fun createAddCallableMemberActions(info: MethodInsertionInfo): List<IntentionAction> = emptyList()
open fun createAddBeanPropertyActions(psiClass: @JvmCommon PsiClass,
propertyName: String,
@PsiModifier.ModifierConstant visibilityModifier: String,
propertyType: PsiType,
setterRequired: Boolean,
getterRequired: Boolean): List<IntentionAction> =
//Fallback if Uast-version of method is overridden
createAddBeanPropertyActions(psiClass.asUast<UClass>(), propertyName, visibilityModifier, propertyType, setterRequired, getterRequired)
companion object : LanguageExtension<JvmCommonIntentionActionsFactory>(
"com.intellij.codeInsight.intention.jvmCommonIntentionActionsFactory") {
@JvmStatic
override fun forLanguage(l: Language): JvmCommonIntentionActionsFactory? = super.forLanguage(l)
}
//A fallback to old api
@Deprecated("use or/and override @JvmCommon-version of this method instead")
open fun createChangeModifierAction(declaration: UDeclaration,
@PsiModifier.ModifierConstant modifier: String,
shouldPresent: Boolean): IntentionAction? = null
@Deprecated("use or/and override @JvmCommon-version of this method instead")
open fun createAddBeanPropertyActions(uClass: UClass,
propertyName: String,
@PsiModifier.ModifierConstant visibilityModifier: String,
propertyType: PsiType,
setterRequired: Boolean,
getterRequired: Boolean): List<IntentionAction> = emptyList()
}
@ApiStatus.Experimental
sealed class MethodInsertionInfo(
val targetClass: @JvmCommon PsiClass,
@PsiModifier.ModifierConstant
val modifiers: List<String> = emptyList(),
val typeParams: List<PsiTypeParameter> = emptyList(),
val parameters: List<@JvmCommon PsiParameter> = emptyList()
) {
@Deprecated("use `targetClass`", ReplaceWith("targetClass"))
val containingClass: UClass
get() = targetClass.asUast<UClass>()
companion object {
@JvmStatic
fun constructorInfo(targetClass: @JvmCommon PsiClass, parameters: List<@JvmCommon PsiParameter>) =
Constructor(targetClass = targetClass, parameters = parameters)
@JvmStatic
fun simpleMethodInfo(containingClass: @JvmCommon PsiClass,
methodName: String,
@PsiModifier.ModifierConstant modifier: String,
returnType: PsiType,
parameters: List<@JvmCommon PsiParameter>) =
Method(name = methodName,
modifiers = listOf(modifier),
targetClass = containingClass,
returnType = returnType,
parameters = parameters)
}
class Method(
targetClass: @JvmCommon PsiClass,
val name: String,
modifiers: List<String> = emptyList(),
typeParams: List<@JvmCommon PsiTypeParameter> = emptyList(),
val returnType: PsiType,
parameters: List<@JvmCommon PsiParameter> = emptyList(),
val isAbstract: Boolean = false
) : MethodInsertionInfo(targetClass, modifiers, typeParams, parameters)
class Constructor(
targetClass: @JvmCommon PsiClass,
modifiers: List<String> = emptyList(),
typeParams: List<@JvmCommon PsiTypeParameter> = emptyList(),
parameters: List<@JvmCommon PsiParameter> = emptyList()
) : MethodInsertionInfo(targetClass, modifiers, typeParams, parameters)
}
@Deprecated("remove after kotlin plugin will be ported")
private inline fun <reified T : UElement> PsiElement.asUast(): T = when (this) {
is T -> this
else -> this.let { ServiceManager.getService(project, UastContext::class.java).convertElement(this, null, T::class.java) as T? }
?: throw UnsupportedOperationException("cant convert $this to ${T::class}")
} | java/java-analysis-api/src/com/intellij/codeInsight/intention/JvmCommonIntentionActionsFactory.kt | 1142501158 |
package chat.rocket.android.chatrooms.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import chat.rocket.android.chatrooms.adapter.ItemHolder
import chat.rocket.android.chatrooms.adapter.LoadingItemHolder
import chat.rocket.android.chatrooms.adapter.RoomUiModelMapper
import chat.rocket.android.chatrooms.domain.FetchChatRoomsInteractor
import chat.rocket.android.chatrooms.infrastructure.ChatRoomsRepository
import chat.rocket.android.server.infrastructure.ConnectionManager
import chat.rocket.android.util.livedata.transform
import chat.rocket.android.util.livedata.wrap
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatAuthException
import chat.rocket.common.util.ifNull
import chat.rocket.core.internal.realtime.socket.model.State
import chat.rocket.core.internal.rest.spotlight
import chat.rocket.core.model.SpotlightResult
import com.shopify.livedataktx.distinct
import com.shopify.livedataktx.map
import com.shopify.livedataktx.nonNull
import kotlinx.coroutines.async
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.lang.IllegalArgumentException
import kotlin.coroutines.coroutineContext
class ChatRoomsViewModel(
private val connectionManager: ConnectionManager,
private val interactor: FetchChatRoomsInteractor,
private val repository: ChatRoomsRepository,
private val mapper: RoomUiModelMapper
) : ViewModel() {
private val query = MutableLiveData<Query>()
val loadingState = MutableLiveData<LoadingState>()
private val runContext = newSingleThreadContext("chat-rooms-view-model")
private val client = connectionManager.client
private var loaded = false
var showLastMessage = true
fun getChatRooms(): LiveData<RoomsModel> {
return Transformations.switchMap(query) { query ->
return@switchMap if (query.isSearch()) {
[email protected](runContext) { _, data: MutableLiveData<RoomsModel> ->
val string = (query as Query.Search).query
// debounce, to not query while the user is writing
delay(200)
// TODO - find a better way for cancellation checking
if (!coroutineContext.isActive) return@wrap
val rooms = repository.search(string).let { mapper.map(it, showLastMessage = this.showLastMessage) }
data.postValue(rooms.toMutableList() + LoadingItemHolder())
if (!coroutineContext.isActive) return@wrap
val spotlight = spotlight(query.query)?.let { mapper.map(it, showLastMessage = this.showLastMessage) }
if (!coroutineContext.isActive) return@wrap
spotlight?.let {
data.postValue(rooms.toMutableList() + spotlight)
}.ifNull {
data.postValue(rooms)
}
}
} else {
repository.getChatRooms(query.asSortingOrder())
.nonNull()
.distinct()
.transform(runContext) { rooms ->
val mappedRooms = rooms?.let {
mapper.map(rooms, query.isGrouped(), this.showLastMessage)
}
if (loaded && mappedRooms?.isEmpty() == true) {
loadingState.postValue(LoadingState.Loaded(0))
}
mappedRooms
}
}
}
}
fun getUsersRoomListLocal(string: String): List<ItemHolder<*>> {
val rooms = GlobalScope.async(Dispatchers.IO) {
return@async repository.search(string).let { mapper.map(it, showLastMessage = showLastMessage) }
}
return runBlocking { rooms.await() }
}
fun getUsersRoomListSpotlight(string: String): List<ItemHolder<*>>? {
val rooms = GlobalScope.async(Dispatchers.IO) {
return@async spotlight(string)?.let { mapper.map(it, showLastMessage = showLastMessage) }
}
return runBlocking { rooms.await() }
}
private suspend fun spotlight(query: String): SpotlightResult? {
return try {
retryIO { client.spotlight(query) }
} catch (ex: Exception) {
ex.printStackTrace()
null
}
}
fun getStatus(): MutableLiveData<State> {
return connectionManager.stateLiveData.nonNull().distinct().map { state ->
if (state is State.Connected) fetchRooms()
state
}
}
private fun fetchRooms() {
GlobalScope.launch {
setLoadingState(LoadingState.Loading(repository.count()))
try {
interactor.refreshChatRooms()
setLoadingState(LoadingState.Loaded(repository.count()))
loaded = true
} catch (ex: Exception) {
Timber.d(ex, "Error refreshing chatrooms")
Timber.d(ex, "Message: $ex")
if (ex is RocketChatAuthException) {
setLoadingState(LoadingState.AuthError)
} else {
setLoadingState(LoadingState.Error(repository.count()))
}
}
}
}
fun setQuery(query: Query) {
this.query.value = query
}
private suspend fun setLoadingState(state: LoadingState) {
withContext(Dispatchers.Main) {
loadingState.value = state
}
}
}
typealias RoomsModel = List<ItemHolder<*>>
sealed class LoadingState {
data class Loading(val count: Long) : LoadingState()
data class Loaded(val count: Long) : LoadingState()
data class Error(val count: Long) : LoadingState()
object AuthError : LoadingState()
}
sealed class Query {
data class ByActivity(val grouped: Boolean = false, val unreadOnTop: Boolean = false) : Query()
data class ByName(val grouped: Boolean = false, val unreadOnTop: Boolean = false ) : Query()
data class Search(val query: String) : Query()
}
fun Query.isSearch(): Boolean = this is Query.Search
fun Query.isGrouped(): Boolean {
return when(this) {
is Query.Search -> false
is Query.ByName -> grouped
is Query.ByActivity -> grouped
}
}
fun Query.isUnreadOnTop(): Boolean {
return when(this) {
is Query.Search -> false
is Query.ByName -> unreadOnTop
is Query.ByActivity -> unreadOnTop
}
}
fun Query.asSortingOrder(): ChatRoomsRepository.Order {
return when(this) {
is Query.ByName -> {
if (grouped && !unreadOnTop) {
ChatRoomsRepository.Order.GROUPED_NAME
}
else if(unreadOnTop && !grouped){
ChatRoomsRepository.Order.UNREAD_ON_TOP_NAME
}
else if(unreadOnTop && grouped){
ChatRoomsRepository.Order.UNREAD_ON_TOP_GROUPED_NAME
}
else {
ChatRoomsRepository.Order.NAME
}
}
is Query.ByActivity -> {
if (grouped && !unreadOnTop) {
ChatRoomsRepository.Order.GROUPED_ACTIVITY
}
else if(unreadOnTop && !grouped){
ChatRoomsRepository.Order.UNREAD_ON_TOP_ACTIVITY
}
else if(unreadOnTop && grouped){
ChatRoomsRepository.Order.UNREAD_ON_TOP_GROUPED_ACTIVITY
}
else {
ChatRoomsRepository.Order.ACTIVITY
}
}
else -> throw IllegalArgumentException("Should be ByName or ByActivity")
}
} | app/src/main/java/chat/rocket/android/chatrooms/viewmodel/ChatRoomsViewModel.kt | 3929122283 |
package me.proxer.library.api.list
import me.proxer.library.ProxerCall
import me.proxer.library.api.PagingLimitEndpoint
import me.proxer.library.entity.list.IndustryCore
import me.proxer.library.enums.Country
/**
* Endpoint for retrieving a list of industries.
*
* @author Ruben Gees
*/
class IndustryListEndpoint internal constructor(
private val internalApi: InternalApi
) : PagingLimitEndpoint<List<IndustryCore>> {
private var page: Int? = null
private var limit: Int? = null
private var searchStart: String? = null
private var search: String? = null
private var country: Country? = null
override fun page(page: Int?) = this.apply { this.page = page }
override fun limit(limit: Int?) = this.apply { this.limit = limit }
/**
* Sets the query to search for only from the start.
*/
fun searchStart(searchStart: String?) = this.apply { this.searchStart = searchStart }
/**
* Sets the query to search for.
*/
fun search(search: String?) = this.apply { this.search = search }
/**
* Sets the country to filter by.
*/
fun country(country: Country?) = this.apply { this.country = country }
override fun build(): ProxerCall<List<IndustryCore>> {
return internalApi.industryList(searchStart, search, country, page, limit)
}
}
| library/src/main/kotlin/me/proxer/library/api/list/IndustryListEndpoint.kt | 3935163220 |
package util.client
import communication.CommunicationProtos
import java.io.InputStream
import java.net.Socket
/**
* @author Sergey Voytovich ([email protected]) on 10.04.16
*/
class TaskWorker(private val port: Int, private val clientId: String) {
private val localhost = "localhost"
private var requestId: Long = 0
fun list(): CommunicationProtos.ListTasksResponse {
val request: CommunicationProtos.ServerRequest = getRequestBuilder()
.setList(CommunicationProtos.ListTasks.newBuilder().build())
.build()
val response = writeRequestAndGetResponse(request)
return response.listResponse
}
fun submit(a: CommunicationProtos.Task.Param,
b: CommunicationProtos.Task.Param,
p: CommunicationProtos.Task.Param,
m: CommunicationProtos.Task.Param,
n: Long): CommunicationProtos.SubmitTaskResponse {
val taskRequest = CommunicationProtos.Task.newBuilder()
.setA(toParam(a))
.setB(toParam(b))
.setP(toParam(p))
.setM(toParam(m))
.setN(n)
.build()
val request = getRequestBuilder()
.setSubmit(CommunicationProtos.SubmitTask.newBuilder().setTask(taskRequest))
.build()
val response = writeRequestAndGetResponse(request)
return response.submitResponse
}
fun subscribe(taskId: Int): CommunicationProtos.SubscribeResponse {
val subscribeRequest: CommunicationProtos.Subscribe = CommunicationProtos.Subscribe.newBuilder()
.setTaskId(taskId)
.build()
val request = getRequestBuilder()
.setSubscribe(subscribeRequest)
.build()
val response = writeRequestAndGetResponse(request)
return response.subscribeResponse
}
private fun writeRequestAndGetResponse(_request: CommunicationProtos.ServerRequest): CommunicationProtos.ServerResponse {
val request = CommunicationProtos.WrapperMessage.newBuilder()
.setRequest(_request)
.build()
Socket(localhost, port).use {
it.outputStream.write(request.serializedSize)
request.writeTo(it.outputStream);
val response = getResponse(it.inputStream)
return response
}
}
fun toParam(p: CommunicationProtos.Task.Param): CommunicationProtos.Task.Param {
if (p.hasDependentTaskId()) {
return CommunicationProtos.Task.Param.newBuilder()
.setDependentTaskId(p.value.toInt())
.build()
}
return CommunicationProtos.Task.Param.newBuilder()
.setValue(p.value)
.build()
}
private fun getResponse(ism: InputStream): CommunicationProtos.ServerResponse {
return CommunicationProtos.WrapperMessage.parseDelimitedFrom(ism).response
}
private fun getRequestBuilder(): CommunicationProtos.ServerRequest.Builder {
return CommunicationProtos.ServerRequest.newBuilder()
.setClientId(clientId)
.setRequestId(getNextId())
}
private fun getNextId(): Long {
return ++requestId
}
}
| csc/2016/vsv_1/test/util.client/TaskWorker.kt | 2614647778 |
package org.jetbrains.exposed.sql.statements
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.IColumnType
import org.jetbrains.exposed.sql.Query
import org.jetbrains.exposed.sql.Transaction
import java.sql.PreparedStatement
class InsertSelectStatement(val columns: List<Column<*>>, val selectQuery: Query, val isIgnore: Boolean = false): Statement<Int>(StatementType.INSERT, listOf(columns.first().table)) {
init {
if (columns.isEmpty()) error("Can't insert without provided columns")
val tables = columns.distinctBy { it.table }
if (tables.count() > 1) error("Can't insert to different tables ${tables.joinToString { it.name }} from single select")
if (columns.size != selectQuery.set.fields.size) error("Columns count doesn't equal to query columns count")
}
override fun PreparedStatement.executeInternal(transaction: Transaction): Int? = executeUpdate()
override fun arguments(): Iterable<Iterable<Pair<IColumnType, Any?>>> = selectQuery.arguments()
override fun prepareSQL(transaction: Transaction): String =
transaction.db.dialect.insert(isIgnore, targets.single(), columns, selectQuery.prepareSQL(transaction), transaction)
}
| extra/exposed/src/main/kotlin/org/jetbrains/exposed/sql/statements/InsertSelectStatement.kt | 419355603 |
package com.jayrave.falkon.dao.update
import com.jayrave.falkon.dao.testLib.*
import com.jayrave.falkon.dao.update.testLib.UpdateSqlBuilderForTesting
import com.jayrave.falkon.engine.Type
import com.jayrave.falkon.engine.TypedNull
import com.jayrave.falkon.sqlBuilders.UpdateSqlBuilder
import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Connector.SimpleConnector
import com.jayrave.falkon.sqlBuilders.lib.WhereSection.Predicate.OneArgPredicate
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown
import org.junit.Test
import com.jayrave.falkon.dao.testLib.NullableFlagPairConverter as NFPC
class UpdateBuilderImplTest {
@Test
fun `update without where`() {
val bundle = Bundle.default()
val table = bundle.table
val engine = bundle.engine
val updateSqlBuilder = bundle.updateSqlBuilder
// build & compile
val builder = UpdateBuilderImpl(table, updateSqlBuilder).values { set(table.int, 5) }
val actualUpdate = builder.build()
builder.compile()
// build expected update
val expectedSql = updateSqlBuilder.build(table.name, listOf(table.int.name), null)
val expectedUpdate = UpdateImpl(table.name, expectedSql, listOf(5))
// Verify
assertEquality(actualUpdate, expectedUpdate)
assertThat(engine.compiledStatementsForUpdate).hasSize(1)
val statement = engine.compiledStatementsForUpdate.first()
assertThat(statement.tableName).isEqualTo(table.name)
assertThat(statement.sql).isEqualTo(expectedSql)
assertThat(statement.boundArgs).hasSize(1)
assertThat(statement.intBoundAt(1)).isEqualTo(5)
}
@Test
fun `update with where`() {
val bundle = Bundle.default()
val table = bundle.table
val engine = bundle.engine
val updateSqlBuilder = bundle.updateSqlBuilder
// build & compile
val builder = UpdateBuilderImpl(table, updateSqlBuilder)
.values { set(table.int, 5) }
.where()
.eq(table.string, "test")
val actualUpdate = builder.build()
builder.update()
// build expected update
val expectedSql = updateSqlBuilder.build(
table.name, listOf(table.int.name),
listOf(OneArgPredicate(OneArgPredicate.Type.EQ, table.string.name))
)
val expectedUpdate = UpdateImpl(table.name, expectedSql, listOf(5, "test"))
// Verify
assertEquality(actualUpdate, expectedUpdate)
assertThat(engine.compiledStatementsForUpdate).hasSize(1)
val statement = engine.compiledStatementsForUpdate.first()
assertThat(statement.tableName).isEqualTo(table.name)
assertThat(statement.sql).isEqualTo(expectedSql)
assertThat(statement.boundArgs).hasSize(2)
assertThat(statement.intBoundAt(1)).isEqualTo(5)
assertThat(statement.stringBoundAt(2)).isEqualTo("test")
}
@Test
fun `update multiple columns`() {
val bundle = Bundle.default()
val table = bundle.table
val engine = bundle.engine
val updateSqlBuilder = bundle.updateSqlBuilder
// build & compile
val builder = UpdateBuilderImpl(table, updateSqlBuilder).values {
set(table.int, 5)
set(table.string, "test")
}
val actualUpdate = builder.build()
builder.update()
// build expected insert
val expectedSql = updateSqlBuilder.build(
table.name, listOf(table.int.name, table.string.name), null
)
val expectedUpdate = UpdateImpl(table.name, expectedSql, listOf(5, "test"))
// Verify
assertEquality(actualUpdate, expectedUpdate)
assertThat(engine.compiledStatementsForUpdate).hasSize(1)
val statement = engine.compiledStatementsForUpdate.first()
assertThat(statement.tableName).isEqualTo(table.name)
assertThat(statement.sql).isEqualTo(expectedSql)
assertThat(statement.boundArgs).hasSize(2)
assertThat(statement.intBoundAt(1)).isEqualTo(5)
assertThat(statement.stringBoundAt(2)).isEqualTo("test")
}
@Test
fun `update via adder or ender reports correct row count & compiled statement gets closed`() {
testUpdateReportsCorrectRowCount { table: TableForTest ->
UpdateBuilderImpl(table, UPDATE_SQL_BUILDER).values { set(table.int, 5) }.update()
}
}
@Test
fun `update via predicate adder or ender reports correct row count & compiled statement gets closed`() {
testUpdateReportsCorrectRowCount { table: TableForTest ->
UpdateBuilderImpl(table, UPDATE_SQL_BUILDER)
.values { set(table.int, 5) }
.where()
.eq(table.int, 6)
.update()
}
}
@Test
fun `compiled statement gets closed even if update via adder or ender throws`() {
testStatementGetsClosedEvenIfUpdateThrows { table: TableForTest ->
UpdateBuilderImpl(table, UPDATE_SQL_BUILDER).values { set(table.int, 5) }.update()
}
}
@Test
fun `compiled statement gets closed even if update via predicate adder or ender throws`() {
testStatementGetsClosedEvenIfUpdateThrows { table: TableForTest ->
UpdateBuilderImpl(table, UPDATE_SQL_BUILDER)
.values { set(table.int, 5) }
.where()
.eq(table.int, 6)
.update()
}
}
@Test
fun `setting value for an already set column, overrides the existing value`() {
val bundle = Bundle.default()
val table = bundle.table
val engine = bundle.engine
val updateSqlBuilder = bundle.updateSqlBuilder
// build & compile
val initialValue = 5
val overwritingValue = initialValue + 1
val builder = UpdateBuilderImpl(table, updateSqlBuilder).values {
set(table.int, initialValue)
set(table.int, overwritingValue)
}
val actualUpdate = builder.build()
builder.update()
// build expected insert
val expectedSql = updateSqlBuilder.build(table.name, listOf(table.int.name), null)
val expectedUpdate = UpdateImpl(table.name, expectedSql, listOf(overwritingValue))
// Verify
assertEquality(actualUpdate, expectedUpdate)
assertThat(engine.compiledStatementsForUpdate).hasSize(1)
val statement = engine.compiledStatementsForUpdate.first()
assertThat(statement.tableName).isEqualTo(table.name)
assertThat(statement.sql).isEqualTo(expectedSql)
assertThat(statement.boundArgs).hasSize(1)
assertThat(statement.intBoundAt(1)).isEqualTo(overwritingValue)
}
@Test
fun `setting values for columns does not fire an update`() {
val bundle = Bundle.default()
val table = bundle.table
val engine = bundle.engine
val updateSqlBuilder = bundle.updateSqlBuilder
UpdateBuilderImpl(table, updateSqlBuilder).values { set(table.int, 5) }
assertThat(engine.compiledStatementsForUpdate).isEmpty()
}
@Test
fun `all types are bound correctly`() {
val bundle = Bundle.default()
val table = bundle.table
val engine = bundle.engine
val updateSqlBuilder = bundle.updateSqlBuilder
// build & compile
val builder = UpdateBuilderImpl(table, updateSqlBuilder)
.values {
set(table.short, 5.toShort())
set(table.int, 6)
set(table.long, 7L)
set(table.float, 8F)
set(table.double, 9.toDouble())
set(table.string, "test 10")
set(table.blob, byteArrayOf(11))
set(table.flagPair, FlagPair(false, true))
set(table.nullableShort, null)
set(table.nullableInt, null)
set(table.nullableLong, null)
set(table.nullableFloat, null)
set(table.nullableDouble, null)
set(table.nullableString, null)
set(table.nullableBlob, null)
set(table.nullableFlagPair, null)
}.where()
.eq(table.short, 12.toShort()).and()
.eq(table.int, 13).and()
.eq(table.long, 14L).and()
.eq(table.float, 15F).and()
.eq(table.double, 16.toDouble()).and()
.eq(table.string, "test 17").and()
.eq(table.blob, byteArrayOf(18)).and()
.eq(table.flagPair, FlagPair(true, false)).and()
.gt(table.nullableShort, null).and()
.gt(table.nullableInt, null).and()
.gt(table.nullableLong, null).and()
.gt(table.nullableFloat, null).and()
.gt(table.nullableDouble, null).and()
.gt(table.nullableString, null).and()
.gt(table.nullableBlob, null).and()
.gt(table.nullableFlagPair, null)
val actualUpdate = builder.build()
builder.update()
// build expected insert
val expectedSql = updateSqlBuilder.build(
table.name,
listOf(
table.short.name, table.int.name, table.long.name, table.float.name,
table.double.name, table.string.name, table.blob.name, table.flagPair.name,
table.nullableShort.name, table.nullableInt.name, table.nullableLong.name,
table.nullableFloat.name, table.nullableDouble.name,
table.nullableString.name, table.nullableBlob.name,
table.nullableFlagPair.name
),
listOf(
OneArgPredicate(OneArgPredicate.Type.EQ, table.short.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.EQ, table.int.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.EQ, table.long.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.EQ, table.float.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.EQ, table.double.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.EQ, table.string.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.EQ, table.blob.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.EQ, table.flagPair.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.GREATER_THAN, table.nullableShort.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.GREATER_THAN, table.nullableInt.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.GREATER_THAN, table.nullableLong.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.GREATER_THAN, table.nullableFloat.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.GREATER_THAN, table.nullableDouble.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.GREATER_THAN, table.nullableString.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.GREATER_THAN, table.nullableBlob.name),
SimpleConnector(SimpleConnector.Type.AND),
OneArgPredicate(OneArgPredicate.Type.GREATER_THAN, table.nullableFlagPair.name)
)
)
val expectedUpdate = UpdateImpl(
table.name, expectedSql,
listOf(
5.toShort(), 6, 7L, 8F, 9.0, "test 10", byteArrayOf(11),
NFPC.asShort(FlagPair(false, true)),
TypedNull(Type.SHORT), TypedNull(Type.INT), TypedNull(Type.LONG),
TypedNull(Type.FLOAT), TypedNull(Type.DOUBLE), TypedNull(Type.STRING),
TypedNull(Type.BLOB), TypedNull(NFPC.dbType),
12.toShort(), 13, 14L, 15F, 16.0, "test 17", byteArrayOf(18),
NFPC.asShort(FlagPair(true, false)),
TypedNull(Type.SHORT), TypedNull(Type.INT), TypedNull(Type.LONG),
TypedNull(Type.FLOAT), TypedNull(Type.DOUBLE), TypedNull(Type.STRING),
TypedNull(Type.BLOB), TypedNull(NFPC.dbType)
)
)
// Verify
assertEquality(actualUpdate, expectedUpdate)
assertThat(engine.compiledStatementsForUpdate).hasSize(1)
val statement = engine.compiledStatementsForUpdate.first()
assertThat(statement.tableName).isEqualTo(table.name)
assertThat(statement.sql).isEqualTo(expectedSql)
assertThat(statement.boundArgs).hasSize(32)
assertThat(statement.shortBoundAt(1)).isEqualTo(5.toShort())
assertThat(statement.intBoundAt(2)).isEqualTo(6)
assertThat(statement.longBoundAt(3)).isEqualTo(7L)
assertThat(statement.floatBoundAt(4)).isEqualTo(8F)
assertThat(statement.doubleBoundAt(5)).isEqualTo(9.toDouble())
assertThat(statement.stringBoundAt(6)).isEqualTo("test 10")
assertThat(statement.blobBoundAt(7)).isEqualTo(byteArrayOf(11))
assertThat(statement.shortBoundAt(8)).isEqualTo(NFPC.asShort(FlagPair(false, true)))
assertThat(statement.isNullBoundAt(9)).isTrue()
assertThat(statement.isNullBoundAt(10)).isTrue()
assertThat(statement.isNullBoundAt(11)).isTrue()
assertThat(statement.isNullBoundAt(12)).isTrue()
assertThat(statement.isNullBoundAt(13)).isTrue()
assertThat(statement.isNullBoundAt(14)).isTrue()
assertThat(statement.isNullBoundAt(15)).isTrue()
assertThat(statement.isNullBoundAt(16)).isTrue()
assertThat(statement.shortBoundAt(17)).isEqualTo(12.toShort())
assertThat(statement.intBoundAt(18)).isEqualTo(13)
assertThat(statement.longBoundAt(19)).isEqualTo(14L)
assertThat(statement.floatBoundAt(20)).isEqualTo(15F)
assertThat(statement.doubleBoundAt(21)).isEqualTo(16.toDouble())
assertThat(statement.stringBoundAt(22)).isEqualTo("test 17")
assertThat(statement.blobBoundAt(23)).isEqualTo(byteArrayOf(18))
assertThat(statement.shortBoundAt(24)).isEqualTo(NFPC.asShort(FlagPair(true, false)))
assertThat(statement.isNullBoundAt(25)).isTrue()
assertThat(statement.isNullBoundAt(26)).isTrue()
assertThat(statement.isNullBoundAt(27)).isTrue()
assertThat(statement.isNullBoundAt(28)).isTrue()
assertThat(statement.isNullBoundAt(29)).isTrue()
assertThat(statement.isNullBoundAt(30)).isTrue()
assertThat(statement.isNullBoundAt(31)).isTrue()
assertThat(statement.isNullBoundAt(32)).isTrue()
}
private class Bundle(
val table: TableForTest, val engine: EngineForTestingBuilders,
val updateSqlBuilder: UpdateSqlBuilder) {
companion object {
fun default(): Bundle {
val engine = EngineForTestingBuilders.createWithOneShotStatements()
val table = TableForTest(configuration = defaultTableConfiguration(engine))
return Bundle(table, engine, UPDATE_SQL_BUILDER)
}
}
}
companion object {
private val UPDATE_SQL_BUILDER = UpdateSqlBuilderForTesting()
private fun assertEquality(actualUpdate: Update, expectedUpdate: Update) {
assertThat(actualUpdate.tableName).isEqualTo(expectedUpdate.tableName)
assertThat(actualUpdate.sql).isEqualTo(expectedUpdate.sql)
assertThat(actualUpdate.arguments).containsExactlyElementsOf(expectedUpdate.arguments)
}
private fun testUpdateReportsCorrectRowCount(updateOp: (TableForTest) -> Int) {
val numberOfRowsAffected = 8745
val engine = EngineForTestingBuilders.createWithOneShotStatements(
updateProvider = { tableName, sql ->
IntReturningOneShotCompiledStatementForTest(
tableName, sql, numberOfRowsAffected
)
}
)
val table = TableForTest(configuration = defaultTableConfiguration(engine))
assertThat(updateOp.invoke(table)).isEqualTo(numberOfRowsAffected)
// Assert that the statement was executed and closed
val statement = engine.compiledStatementsForUpdate.first()
assertThat(statement.isExecuted).isTrue()
assertThat(statement.isClosed).isTrue()
}
private fun testStatementGetsClosedEvenIfUpdateThrows(updateOp: (TableForTest) -> Int) {
val engine = EngineForTestingBuilders.createWithOneShotStatements(
updateProvider = { tableName, sql ->
IntReturningOneShotCompiledStatementForTest(
tableName, sql, shouldThrowOnExecution = true
)
}
)
val exceptionWasThrown = try {
updateOp.invoke(TableForTest(configuration = defaultTableConfiguration(engine)))
false
} catch (e: Exception) {
true
}
when {
!exceptionWasThrown -> failBecauseExceptionWasNotThrown(Exception::class.java)
else -> {
// Assert that the statement was not successfully executed but closed
val statement = engine.compiledStatementsForUpdate.first()
assertThat(statement.wasExecutionAttempted).isTrue()
assertThat(statement.isExecuted).isFalse()
assertThat(statement.isClosed).isTrue()
}
}
}
}
} | falkon-dao/src/test/kotlin/com/jayrave/falkon/dao/update/UpdateBuilderImplTest.kt | 875972359 |
package br.odb.giovanni.game
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.media.MediaPlayer
import br.odb.giovanni.R
import br.odb.giovanni.engine.Constants
class Monster(resources: Resources, private val kill: MediaPlayer) : Actor() {
var actorTarget: Actor? = null
private var timeToMove: Long = 0
init {
animation.addFrame(BitmapFactory.decodeResource(resources, R.drawable.monster_3))
animation.addFrame(BitmapFactory.decodeResource(resources, R.drawable.monster_4))
direction = 3
}
override fun tick(timeInMS: Long) {
super.tick(timeInMS)
timeToMove -= timeInMS
timeToMove = if (timeToMove < 0) {
300
} else {
return
}
val currentX = position.x / Constants.BASE_TILE_WIDTH
val currentY = position.y / Constants.BASE_TILE_HEIGHT
val targetX = actorTarget!!.position.x / Constants.BASE_TILE_WIDTH
val targetY = actorTarget!!.position.y / Constants.BASE_TILE_HEIGHT
val dirX: Float = when {
targetX < currentX -> {
-0.5f
}
targetX > currentX -> {
0.5f
}
else -> {
0f
}
}
val dirY: Float = when {
targetY < currentY -> {
-0.5f
}
targetY > currentY -> {
0.5f
}
else -> {
0f
}
}
//try to move around obstacle
when {
level!!.mayMoveTo(currentX + dirX, currentY + dirY) -> {
move(Constants.BASE_TILE_WIDTH * dirX, Constants.BASE_TILE_HEIGHT * dirY )
}
level!!.mayMoveTo(currentX, currentY + 0.5f) -> {
move(0f, Constants.BASE_TILE_HEIGHT * 0.5f)
}
level!!.mayMoveTo(currentX + 0.5f, currentY) -> {
move(Constants.BASE_TILE_WIDTH * 0.5f, 0.0f)
}
level!!.mayMoveTo(currentX - 0.5f, currentY) -> {
move(Constants.BASE_TILE_WIDTH * -0.5f, 0.0f)
}
level!!.mayMoveTo(currentX, currentY - 0.5f) -> {
move(0f, Constants.BASE_TILE_HEIGHT * 0.5f)
}
}
}
override fun touched(actor: Actor?) {
if (actor is Monster) {
kill.start()
kill()
}
}
public override fun didMove() {}
} | app/src/main/java/br/odb/giovanni/game/Monster.kt | 1095829189 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.core.asset
import com.almasb.fxgl.core.EngineService
import java.net.URL
/**
*
* @author Almas Baimagambetov ([email protected])
*/
abstract class AssetLoaderService : EngineService() {
abstract fun <T> load(assetType: AssetType, fileName: String): T
abstract fun <T> load(assetType: AssetType, url: URL): T
/**
* @return URL to an asset file, [name] (relative) must start with /assets/
*/
abstract fun getURL(name: String): URL
} | fxgl-core/src/main/kotlin/com/almasb/fxgl/core/asset/AssetLoaderService.kt | 904888283 |
package actor.proto.router.fixture
import actor.proto.mailbox.Dispatcher
import actor.proto.mailbox.Mailbox
import actor.proto.mailbox.MessageInvoker
import actor.proto.mailbox.SystemMessage
import kotlinx.coroutines.runBlocking
class TestMailboxHandler : MessageInvoker, Dispatcher {
private var escalatedFailures: MutableList<Exception> = mutableListOf()
override suspend fun invokeSystemMessage(msg: SystemMessage) {
return //(TestMessagemsg).taskCompletionSource.task
}
override suspend fun invokeUserMessage(msg: Any) {
return //(msg as TestMessage).taskCompletionSource.
}
override suspend fun escalateFailure(reason: Exception, message: Any) {
escalatedFailures.add(reason)
}
override var throughput: Int = 10
override fun schedule(mailbox:Mailbox) {
runBlocking { mailbox.run() }
}
}
| proto-router/src/test/kotlin/actor/proto/router/fixture/TestMailboxHandler.kt | 4168784786 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
package com.facebook.react
import android.os.Bundle
import org.junit.Assert.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class ReactActivityDelegateTest {
@Test
fun delegateWithConcurrentRoot_populatesInitialPropsCorrectly() {
val delegate =
object : ReactActivityDelegate(null, "test-delegate") {
override fun isConcurrentRootEnabled() = true
public val inspectLaunchOptions: Bundle?
get() = getLaunchOptions()
}
assertNotNull(delegate.inspectLaunchOptions)
assertTrue(delegate.inspectLaunchOptions!!.containsKey("concurrentRoot"))
assertTrue(delegate.inspectLaunchOptions!!.getBoolean("concurrentRoot"))
}
@Test
fun delegateWithoutConcurrentRoot_hasNullInitialProperties() {
val delegate =
object : ReactActivityDelegate(null, "test-delegate") {
override fun isConcurrentRootEnabled() = false
public val inspectLaunchOptions: Bundle?
get() = getLaunchOptions()
}
assertNull(delegate.inspectLaunchOptions)
}
@Test
fun delegateWithConcurrentRoot_composesInitialPropertiesCorrectly() {
val delegate =
object : ReactActivityDelegate(null, "test-delegate") {
override fun isConcurrentRootEnabled() = true
override fun getLaunchOptions(): Bundle =
Bundle().apply { putString("test-property", "test-value") }
public val inspectLaunchOptions: Bundle?
get() = getLaunchOptions()
}
assertNotNull(delegate.inspectLaunchOptions)
assertTrue(delegate.inspectLaunchOptions!!.containsKey("concurrentRoot"))
assertTrue(delegate.inspectLaunchOptions!!.getBoolean("concurrentRoot"))
assertTrue(delegate.inspectLaunchOptions!!.containsKey("test-property"))
assertEquals("test-value", delegate.inspectLaunchOptions!!.getString("test-property"))
}
}
| ReactAndroid/src/test/java/com/facebook/react/ReactActivityDelegateTest.kt | 3687853918 |
/*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.editor
import javafx.scene.input.KeyCode
import uk.co.nickthecoder.paratask.gui.ApplicationAction
object EditorActions {
val nameToActionMap = mutableMapOf<String, ApplicationAction>()
val NEW = EditorAction("new", KeyCode.N, control = true, label = "New", tooltip = "Create a New Resource")
val RUN = EditorAction("run", KeyCode.R, control = true, label = "Run", tooltip = "Run the game")
val TEST = EditorAction("test", KeyCode.T, control = true, label = "Test", tooltip = "Test the game")
val RELOAD = EditorAction("reload", KeyCode.F5, label = "Reload", tooltip = "Reload textures, fonts & sounds")
val OPEN = EditorAction("open", KeyCode.O, control = true, label = "Open", tooltip = "Open Resource")
val SAVE = EditorAction("save", KeyCode.S, control = true, label = "Save")
val ACCORDION_ONE = EditorAction("accordion.one", KeyCode.F4)
val ACCORDION_TWO = EditorAction("accordion.two", KeyCode.F5)
val ACCORDION_THREE = EditorAction("accordion.three", KeyCode.F6)
val ACCORDION_FOUR = EditorAction("accordion.four", KeyCode.F7)
val ACCORDION_FIVE = EditorAction("accordion.five", KeyCode.F8)
val SHOW_COSTUME_PICKER = EditorAction("show.costumePicker", KeyCode.CONTEXT_MENU)
val ESCAPE = EditorAction("escape", KeyCode.ESCAPE)
val DELETE = EditorAction("delete", KeyCode.DELETE)
val UNDO = EditorAction("undo", KeyCode.Z, control = true)
val REDO = EditorAction("redo", KeyCode.Z, control = true, shift = true)
val ZOOM_RESET = EditorAction("zoom.reset", KeyCode.DIGIT0, control = true)
val ZOOM_IN1 = EditorAction("zoom.in", KeyCode.PLUS, control = true)
val ZOOM_IN2 = EditorAction("zoom.out", KeyCode.EQUALS, control = true)
val ZOOM_OUT = EditorAction("zoom.out", KeyCode.MINUS, control = true)
val SNAPS_EDIT = EditorAction("snaps.edit", KeyCode.NUMBER_SIGN, control = true, shift = true, tooltip = "Edit Snapping")
val SNAP_TO_GRID_TOGGLE = EditorAction("snap.grid.toggle", KeyCode.NUMBER_SIGN, control = true)
val SNAP_TO_GUIDES_TOGGLE = EditorAction("snap.guides.toggle", KeyCode.G, control = true)
val SNAP_TO_OTHERS_TOGGLE = EditorAction("snap.others.toggle", KeyCode.O, control = true)
val SNAP_ROTATION_TOGGLE = EditorAction("snap.rotation.toggle", KeyCode.R, control = true)
val RESET_ZORDERS = EditorAction("zOrders.reset", KeyCode.Z, control = true, shift = true, label = "Reset All Z-Orders")
val STAMPS = listOf(KeyCode.DIGIT1, KeyCode.DIGIT2, KeyCode.DIGIT3, KeyCode.DIGIT4, KeyCode.DIGIT5, KeyCode.DIGIT6, KeyCode.DIGIT7, KeyCode.DIGIT8, KeyCode.DIGIT9)
.mapIndexed { index, keyCode -> EditorAction("stamp$index", keyCode, control = true) }
val TAB_CLOSE = EditorAction("tab.close", KeyCode.W, control = true, label = "Close Tab")
val RELOAD_SCRIPTS = EditorAction("scripts.reload", KeyCode.F5, label = "Reload Scripts", tooltip = "Reload all scripts")
}
| tickle-editor/src/main/kotlin/uk/co/nickthecoder/tickle/editor/EditorActions.kt | 4264545396 |
package icurves.util
import icurves.CurvesApp
import icurves.algorithm.ClosedBezierSpline
import javafx.geometry.Point2D
import javafx.scene.paint.Color
import javafx.scene.shape.CubicCurveTo
import javafx.scene.shape.LineTo
import javafx.scene.shape.MoveTo
import javafx.scene.shape.Path
import java.util.*
/**
* The algorithm is adapted from AS3
* http://www.cartogrammar.com/blog/actionscript-curves-update/
*
* @author Almas Baimagambetov ([email protected])
*/
object BezierApproximation {
private val z = 0.5
private val angleFactor = 0.75
fun smoothPath2(originalPoints: MutableList<Point2D>, smoothFactor: Int): List<Path> {
val pair = ClosedBezierSpline.GetCurveControlPoints(originalPoints.toTypedArray())
val points = originalPoints.plus(originalPoints[0])
val result = arrayListOf<Path>()
val firstPt = 0
val lastPt = points.size
for (i in firstPt..lastPt - 2){
val path = Path()
path.elements.add(MoveTo(points[i].x, points[i].y))
val j = if (i == lastPt - 2) 0 else i + 1
path.elements.add(CubicCurveTo(
pair.key[i].x, pair.key[i].y,
pair.value[j].x, pair.value[j].y,
//controlPts[i].second.x, controlPts[i].second.y,
//controlPts[i+1].first.x, controlPts[i+1].first.y,
points[i+1].x, points[i+1].y)
)
path.fill = Color.TRANSPARENT
result.add(path)
}
return result
}
fun smoothPath(points: MutableList<Point2D>, smoothFactor: Int): List<Path> {
// to make a closed cycle
points.add(points[0])
val result = arrayListOf<Path>()
val firstPt = 0
val lastPt = points.size
// store the two control points (of a cubic Bezier curve) for each point
val controlPts = arrayListOf<Pair<Point2D, Point2D>>()
for (i in firstPt until lastPt) {
controlPts.add(Pair(Point2D.ZERO, Point2D.ZERO))
}
// loop through all the points to get curve control points for each
for (i in firstPt until lastPt) {
val prevPoint = if (i-1 < 0) points[points.size-2] else points[i-1]
val currPoint = points[i]
val nextPoint = if (i+1 == points.size) points[1] else points[i+1]
var a = prevPoint.distance(currPoint)
if (a < 0.001) a = .001; // Correct for near-zero distances, a cheap way to prevent division by zero
var b = currPoint.distance(nextPoint)
if (b < 0.001) b = .001;
var c = prevPoint.distance(nextPoint)
if (c < 0.001) c = .001
var cos = (b*b + a*a - c*c) / (2*b*a)
// ensure cos is between -1 and 1 so that Math.acos will work
if (cos < -1)
cos = -1.0
else if (cos > 1)
cos = 1.0
// angle formed by the two sides of the triangle (described by the three points above) adjacent to the current point
val C = Math.acos(cos)
// Duplicate set of points. Start by giving previous and next points values RELATIVE to the current point.
var aPt = Point2D(prevPoint.x-currPoint.x,prevPoint.y-currPoint.y);
var bPt = Point2D(currPoint.x,currPoint.y);
var cPt = Point2D(nextPoint.x-currPoint.x,nextPoint.y-currPoint.y);
/*
We'll be adding adding the vectors from the previous and next points to the current point,
but we don't want differing magnitudes (i.e. line segment lengths) to affect the direction
of the new vector. Therefore we make sure the segments we use, based on the duplicate points
created above, are of equal length. The angle of the new vector will thus bisect angle C
(defined above) and the perpendicular to this is nice for the line tangent to the curve.
The curve control points will be along that tangent line.
*/
if (a > b){
//aPt.normalize(b); // Scale the segment to aPt (bPt to aPt) to the size of b (bPt to cPt) if b is shorter.
aPt = aPt.normalize().multiply(b)
} else if (b > a){
//cPt.normalize(a); // Scale the segment to cPt (bPt to cPt) to the size of a (aPt to bPt) if a is shorter.
cPt = cPt.normalize().multiply(a)
}
// Offset aPt and cPt by the current point to get them back to their absolute position.
aPt = aPt.add(currPoint.x,currPoint.y)
cPt = cPt.add(currPoint.x,currPoint.y)
// Get the sum of the two vectors, which is perpendicular to the line along which our curve control points will lie.
var ax = bPt.x-aPt.x // x component of the segment from previous to current point
var ay = bPt.y-aPt.y
var bx = bPt.x-cPt.x // x component of the segment from next to current point
var by = bPt.y-cPt.y
var rx = ax + bx; // sum of x components
var ry = ay + by;
// Correct for three points in a line by finding the angle between just two of them
if (rx == 0.0 && ry == 0.0){
rx = -bx; // Really not sure why this seems to have to be negative
ry = by;
}
// Switch rx and ry when y or x difference is 0. This seems to prevent the angle from being perpendicular to what it should be.
if (ay == 0.0 && by == 0.0){
rx = 0.0;
ry = 1.0;
} else if (ax == 0.0 && bx == 0.0){
rx = 1.0;
ry = 0.0;
}
val theta = Math.atan2(ry,rx) // angle of the new vector
var controlDist = Math.min(a, b) * z; // Distance of curve control points from current point: a fraction the length of the shorter adjacent triangle side
val controlScaleFactor = C/Math.PI; // Scale the distance based on the acuteness of the angle. Prevents big loops around long, sharp-angled triangles.
controlDist *= ((1.0-angleFactor) + angleFactor*controlScaleFactor); // Mess with this for some fine-tuning
val controlAngle = theta+Math.PI/2; // The angle from the current point to control points: the new vector angle plus 90 degrees (tangent to the curve).
var controlPoint2 = polarToCartesian(controlDist, controlAngle); // Control point 2, curving to the next point.
var controlPoint1 = polarToCartesian(controlDist, controlAngle+Math.PI); // Control point 1, curving from the previous point (180 degrees away from control point 2).
// Offset control points to put them in the correct absolute position
controlPoint1 = controlPoint1.add(currPoint);
controlPoint2 = controlPoint2.add(currPoint);
/*
Haven't quite worked out how this happens, but some control points will be reversed.
In this case controlPoint2 will be farther from the next point than controlPoint1 is.
Check for that and switch them if it's true.
*/
if (controlPoint2.distance(nextPoint) > controlPoint1.distance(nextPoint)){
controlPts[i] = Pair(controlPoint2, controlPoint1) // Add the two control points to the array in reverse order
} else {
controlPts[i] = Pair(controlPoint1, controlPoint2) // Otherwise add the two control points to the array in normal order
}
}
// a b c ab ac ad bc abc abd acd abcd
CurvesApp.getInstance().settings.globalMap["controlPoints"] = controlPts
val straightLines:Boolean = true; // Change to true if you want to use lineTo for straight lines of 3 or more points rather than curves. You'll get straight lines but possible sharp corners!
// Loop through points to draw cubic Bézier curves through the penultimate point, or through the last point if the line is closed.
for (i in firstPt..lastPt - 2){
val path = Path()
path.elements.add(MoveTo(points[i].x, points[i].y))
// Determine if multiple points in a row are in a straight line
val isStraight:Boolean = ( ( i > 0 && Math.atan2(points[i].y-points[i-1].y, points[i].x-points[i-1].x)
== Math.atan2(points[i+1].y-points[i].y, points[i+1].x - points[i].x) )
|| ( i < points.size - 2 && Math.atan2(points[i+2].y-points[i+1].y,points[i+2].x-points[i+1].x)
== Math.atan2(points[i+1].y-points[i].y,points[i+1].x-points[i].x) ) );
if (straightLines && isStraight){
path.elements.add(LineTo(points[i+1].x,points[i+1].y))
} else {
// BezierSegment instance using the current point, its second control point, the next point's first control point, and the next point
// var t = 0.01
// while (t < 1.01) {
//
// val point = getBezierValue(points[i], controlPts[i].second, controlPts[i+1].first, points[i+1], t)
// path.elements.add(LineTo(point.x, point.y))
//
// t += 1.0 / smoothFactor
// }
path.elements.add(CubicCurveTo(
controlPts[i].second.x, controlPts[i].second.y,
controlPts[i+1].first.x, controlPts[i+1].first.y,
points[i+1].x, points[i+1].y)
)
}
path.fill = Color.TRANSPARENT
result.add(path)
}
return result
}
//
// fun pathThruPoints(points: MutableList<Point2D>,
// smoothFactor: Int,
// closedCycle: Boolean = true,
// z: Double = 0.5,
// angleFactor: Double = 0.75): List<Path> {
//
// if (closedCycle)
// points.add(points[0])
//
// val result = ArrayList<Path>()
//
// // Ordinarily, curve calculations will start with the second point and go through the second-to-last point
// var firstPt = 1;
// var lastPt = points.size - 1;
//
// // Check if this is a closed line (the first and last points are the same)
// if (points[0].x == points[points.size-1].x && points[0].y == points[points.size-1].y){
// // Include first and last points in curve calculations
// firstPt = 0
// lastPt = points.size
// }
//
// val controlPts = ArrayList<Pair<Point2D, Point2D>>() // An array to store the two control points (of a cubic Bézier curve) for each point
// for (i in 0..points.size - 1) {
// controlPts.add(Pair(Point2D.ZERO, Point2D.ZERO))
// }
//
// // Loop through all the points (except the first and last if not a closed line) to get curve control points for each.
// for (i in firstPt..lastPt - 1) {
//
// // The previous, current, and next points
// var p0 = if (i-1 < 0) points[points.size-2] else points[i-1]; // If the first point (of a closed line), use the second-to-last point as the previous point
// var p1 = points[i];
// var p2 = if (i+1 == points.size) points[1] else points[i+1]; // If the last point (of a closed line), use the second point as the next point
//
// var a = p0.distance(p1) // Distance from previous point to current point
// if (a < 0.001) a = .001; // Correct for near-zero distances, a cheap way to prevent division by zero
// var b = p1.distance(p2); // Distance from current point to next point
// if (b < 0.001) b = .001;
// var c = p0.distance(p2); // Distance from previous point to next point
// if (c < 0.001) c = .001;
// var cos = (b*b+a*a-c*c)/(2*b*a);
//
//
//
//
//
//
//
//
// // Make sure above value is between -1 and 1 so that Math.acos will work
// if (cos < -1)
// cos = -1.0;
// else if (cos > 1)
// cos = 1.0;
//
// var C = Math.acos(cos); // Angle formed by the two sides of the triangle (described by the three points above) adjacent to the current point
// // Duplicate set of points. Start by giving previous and next points values RELATIVE to the current point.
// var aPt = Point2D(p0.x-p1.x,p0.y-p1.y);
// var bPt = Point2D(p1.x,p1.y);
// var cPt = Point2D(p2.x-p1.x,p2.y-p1.y);
//
// /*
// We'll be adding adding the vectors from the previous and next points to the current point,
// but we don't want differing magnitudes (i.e. line segment lengths) to affect the direction
// of the new vector. Therefore we make sure the segments we use, based on the duplicate points
// created above, are of equal length. The angle of the new vector will thus bisect angle C
// (defined above) and the perpendicular to this is nice for the line tangent to the curve.
// The curve control points will be along that tangent line.
// */
//
// if (a > b){
// //aPt.normalize(b); // Scale the segment to aPt (bPt to aPt) to the size of b (bPt to cPt) if b is shorter.
// aPt = aPt.normalize().multiply(b)
// } else if (b > a){
// //cPt.normalize(a); // Scale the segment to cPt (bPt to cPt) to the size of a (aPt to bPt) if a is shorter.
// cPt = cPt.normalize().multiply(a)
// }
//
// // Offset aPt and cPt by the current point to get them back to their absolute position.
// aPt = aPt.add(p1.x,p1.y);
// cPt = cPt.add(p1.x,p1.y);
//
// // Get the sum of the two vectors, which is perpendicular to the line along which our curve control points will lie.
// var ax = bPt.x-aPt.x; // x component of the segment from previous to current point
// var ay = bPt.y-aPt.y;
// var bx = bPt.x-cPt.x; // x component of the segment from next to current point
// var by = bPt.y-cPt.y;
// var rx = ax + bx; // sum of x components
// var ry = ay + by;
//
// // Correct for three points in a line by finding the angle between just two of them
// if (rx == 0.0 && ry == 0.0){
// rx = -bx; // Really not sure why this seems to have to be negative
// ry = by;
// }
// // Switch rx and ry when y or x difference is 0. This seems to prevent the angle from being perpendicular to what it should be.
// if (ay == 0.0 && by == 0.0){
// rx = 0.0;
// ry = 1.0;
// } else if (ax == 0.0 && bx == 0.0){
// rx = 1.0;
// ry = 0.0;
// }
//
// //var r = Math.sqrt(rx*rx+ry*ry); // length of the summed vector - not being used, but there it is anyway
// var theta = Math.atan2(ry,rx); // angle of the new vector
//
// var controlDist = Math.min(a,b)*z; // Distance of curve control points from current point: a fraction the length of the shorter adjacent triangle side
// var controlScaleFactor = C/Math.PI; // Scale the distance based on the acuteness of the angle. Prevents big loops around long, sharp-angled triangles.
//
// controlDist *= ((1.0-angleFactor) + angleFactor*controlScaleFactor); // Mess with this for some fine-tuning
//
// var controlAngle = theta+Math.PI/2; // The angle from the current point to control points: the new vector angle plus 90 degrees (tangent to the curve).
//
//
// var controlPoint2 = polarToCartesian(controlDist, controlAngle); // Control point 2, curving to the next point.
// var controlPoint1 = polarToCartesian(controlDist, controlAngle+Math.PI); // Control point 1, curving from the previous point (180 degrees away from control point 2).
//
// // Offset control points to put them in the correct absolute position
// controlPoint1 = controlPoint1.add(p1.x,p1.y);
// controlPoint2 = controlPoint2.add(p1.x,p1.y);
//
// /*
// Haven't quite worked out how this happens, but some control points will be reversed.
// In this case controlPoint2 will be farther from the next point than controlPoint1 is.
// Check for that and switch them if it's true.
// */
// if (controlPoint2.distance(p2) > controlPoint1.distance(p2)){
// controlPts[i] = Pair(controlPoint2,controlPoint1); // Add the two control points to the array in reverse order
// } else {
// controlPts[i] = Pair(controlPoint1,controlPoint2); // Otherwise add the two control points to the array in normal order
// }
//
// // Uncomment to draw lines showing where the control points are.
// /*
// g.moveTo(p1.x,p1.y);
// g.lineTo(controlPoint2.x,controlPoint2.y);
// g.moveTo(p1.x,p1.y);
// g.lineTo(controlPoint1.x,controlPoint1.y);
// */
// }
//
//
// //
// // CURVE CONSTRUCTION VIA ELEMENTS
// //
//
// //path.elements.add(MoveTo(points[0].x, points[0].y))
//
//
//
// var straightLines:Boolean = true; // Change to true if you want to use lineTo for straight lines of 3 or more points rather than curves. You'll get straight lines but possible sharp corners!
//
// // Loop through points to draw cubic Bézier curves through the penultimate point, or through the last point if the line is closed.
// for (i in firstPt..lastPt - 2){
//
// val path = Path()
//
// path.elements.add(MoveTo(points[i].x, points[i].y))
//
// // Determine if multiple points in a row are in a straight line
// var isStraight:Boolean = ( ( i > 0 && Math.atan2(points[i].y-points[i-1].y, points[i].x-points[i-1].x)
// == Math.atan2(points[i+1].y-points[i].y, points[i+1].x - points[i].x) )
// || ( i < points.size - 2 && Math.atan2(points[i+2].y-points[i+1].y,points[i+2].x-points[i+1].x)
// == Math.atan2(points[i+1].y-points[i].y,points[i+1].x-points[i].x) ) );
//
// if (straightLines && isStraight){
// path.elements.add(LineTo(points[i+1].x,points[i+1].y))
// } else {
//
// // BezierSegment instance using the current point, its second control point, the next point's first control point, and the next point
// //var bezier:BezierSegment = new BezierSegment(points[i], controlPts[i].second, controlPts[i+1].first, points[i+1]);
//
// // Construct the curve out of 100 segments (adjust number for less/more detail)
//
// var t = 0.01
// while (t < 1.01) {
//
// val point = getBezierValue(points[i], controlPts[i].second, controlPts[i+1].first, points[i+1], t)
// path.elements.add(LineTo(point.x, point.y))
//
// t += 1.0 / smoothFactor
// }
// }
//
// path.fill = Color.TRANSPARENT
// result.add(path)
// }
//
// // moveTo
// // lineTo * 10 * numPoints
// // closePath
//
// //println("Path elements: ${path.elements}")
//
//// if (closedCycle)
//// path.elements.add(ClosePath())
//
// //path.fill = Color.TRANSPARENT
//
// return result
// }
/**
* Polar to Cartesian conversion.
*/
private fun polarToCartesian(len: Double, angle: Double): Point2D {
return Point2D(len * Math.cos(angle), len * Math.sin(angle))
}
/**
* Cubic bezier equation from
* http://stackoverflow.com/questions/5634460/quadratic-bezier-curve-calculate-point
*/
private fun getBezierValue(p1: Point2D, p2: Point2D, p3: Point2D, p4: Point2D, t: Double): Point2D {
val x = Math.pow(1 - t, 3.0) * p1.x + 3 * t * Math.pow(1 - t, 2.0) * p2.x + 3 * t*t * (1 - t) * p3.x + t*t*t*p4.x
val y = Math.pow(1 - t, 3.0) * p1.y + 3 * t * Math.pow(1 - t, 2.0) * p2.y + 3 * t*t * (1 - t) * p3.y + t*t*t*p4.y
return Point2D(x, y)
}
} | src/main/kotlin/icurves/util/BezierApproximation.kt | 707788562 |
package com.github.daemontus.jafra
import org.junit.Test
import java.util.concurrent.BlockingQueue
import java.util.concurrent.LinkedBlockingQueue
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertTrue
open class MockMasterMessenger : TokenMessenger {
var mc: Int = 0
val queue: BlockingQueue<Token> = LinkedBlockingQueue<Token>()
@Synchronized
override fun sendToNextAsync(token: Token) {
mc += 1
queue.add(token)
}
override fun receiveFromPrevious(): Token = queue.take()
override fun isMaster() = true
}
class MasterTerminatorTest {
@Test(timeout = 2000)
fun complexTest() {
var flag = 1
var count = 0
val comm = object : MockMasterMessenger() {
override fun receiveFromPrevious(): Token {
val t = queue.take()
if (t.flag == 2) {
return t
} else {
//we use dirty flag first to simulate the environment that received the messages
return Token(Math.min(t.flag + flag, 1), t.count + count) //2 because 2 messages are sent
}
}
}
val terminator = Terminator.createNew(comm)
terminator.messageSent()
count++ //message created in system
terminator.messageReceived() //message received
Thread(Runnable {
try {
Thread.sleep(100)
count-- //pair for first message Sent
terminator.messageSent()
terminator.setDone()
Thread.sleep(100)
count++ //message created in system
terminator.messageReceived() //message received
Thread.sleep(100)
count-- //pair for second message Sent
Thread.sleep(100)
flag = 0
terminator.setDone()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}).start()
terminator.waitForTermination()
assertTrue(comm.queue.isEmpty())
assertTrue(comm.mc > 2) //this can cycle for quite a long time, so we just know it's going to be a big number
}
@Test(timeout = 1000)
fun receivedMessagesAfterStart() {
var flag = 1
val comm = object : MockMasterMessenger() {
override fun receiveFromPrevious(): Token {
val t = queue.take()
if (t.flag == 2) {
return t
} else {
//we use dirty flag first to simulate the environment that received the messages
return Token(Math.min(t.flag + flag, 1), t.count + 2) //2 because 2 messages are sent
}
}
}
val terminator = Terminator.createNew(comm)
Thread(Runnable {
try {
Thread.sleep(200)
terminator.messageReceived()
Thread.sleep(100)
terminator.messageReceived()
Thread.sleep(100)
flag = 0
terminator.setDone()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}).start()
terminator.waitForTermination()
assertTrue(comm.queue.isEmpty())
assertEquals(2, comm.mc)
}
@Test(timeout = 1000)
fun sentMessagesAfterStart() {
var flag = 1
val comm = object : MockMasterMessenger() {
override fun receiveFromPrevious(): Token {
val t = queue.take()
if (t.flag == 2) {
return t
} else {
//we use dirty flag first to simulate the environment that received the messages
return Token(Math.min(t.flag + flag, 1), t.count - 2) //2 because 2 messages are sent
}
}
}
val terminator = Terminator.createNew(comm)
Thread(object : Runnable {
override fun run() {
try {
Thread.sleep(50)
terminator.messageSent()
Thread.sleep(50)
terminator.messageSent()
flag = 0
terminator.setDone()
} catch (e: InterruptedException) {
e.printStackTrace()
}
}
}).start()
terminator.waitForTermination()
assertTrue(comm.queue.isEmpty())
assertEquals(2, comm.mc)
}
@Test(timeout = 1000)
fun receiveMessagesBeforeDone() {
//we don't need to simulate flags here, since message send does not modify environment flags
val comm = object : MockMasterMessenger() {
override fun receiveFromPrevious(): Token {
val token = queue.take()
if (token.flag == 2) return token
return Token(token.flag, token.count + 2) // +2 for two sent messages
}
}
//receive and finish work before start
val terminator = Terminator.createNew(comm)
terminator.messageReceived()
Thread.sleep(100)
terminator.messageReceived()
terminator.setDone()
terminator.waitForTermination()
assertEquals(2, comm.mc)
assertTrue(comm.queue.isEmpty())
//receive before start and finish after start
val terminator2 = Terminator.createNew(comm)
terminator2.messageReceived()
Thread(object : Runnable {
override fun run() {
Thread.sleep(400)
terminator2.setDone()
}
}).start()
Thread.sleep(100)
terminator2.messageReceived()
terminator2.waitForTermination()
//only one message is needed to conclude termination, since
//environment is clean and probe is sent only at the first setDone
assertEquals(4, comm.mc)
assertTrue(comm.queue.isEmpty())
}
@Test(timeout = 1000)
fun sendMessagesBeforeDone() {
val comm = object : MockMasterMessenger() {
var flag: Int = 1
override fun receiveFromPrevious(): Token {
val t = queue.take()
if (t.flag == 2) {
return t
} else {
//we use dirty flag first to simulate the environment that received the messages
val r = Token(Math.min(t.flag + flag, 1), t.count - 2) //2 because 2 messages are sent
flag = 0
return r
}
}
}
val terminator = Terminator.createNew(comm)
terminator.messageSent()
Thread.sleep(100)
terminator.messageSent()
terminator.setDone()
terminator.waitForTermination()
assertTrue(comm.queue.isEmpty())
assertEquals(0, comm.flag)
//one with dirty flag, second to verify, last as poison pill
assertEquals(3, comm.mc)
}
@Test(timeout = 1000)
fun wrongUse() {
val comm = MockMasterMessenger()
val terminator = Terminator.createNew(comm)
terminator.setDone()
//terminator not working
assertFailsWith(IllegalStateException::class) {
terminator.setDone()
}
assertFailsWith(IllegalStateException::class) {
terminator.messageSent()
}
terminator.waitForTermination()
//terminator finalized
assertFailsWith(IllegalStateException::class) {
terminator.setDone()
}
assertFailsWith(IllegalStateException::class) {
terminator.messageSent()
}
assertFailsWith(IllegalStateException::class) {
terminator.messageReceived()
}
assertFailsWith(IllegalStateException::class) {
terminator.waitForTermination()
}
}
@Test(timeout = 1000)
fun noMessages() {
//In case there are no other messages, terminator should finish after first onDone call
//It should send exactly two tokens - one for termination check, second as poison pill
val comm = MockMasterMessenger()
val terminator = Terminator.createNew(comm)
terminator.setDone()
terminator.waitForTermination()
assertEquals(2, comm.mc)
assertTrue(comm.queue.isEmpty())
}
} | src/test/kotlin/com/github/daemontus/jafra/MasterTerminatorTest.kt | 2314097813 |
package gorden.krefreshlayout.demo.ui
import android.app.Activity
import android.content.Intent
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.FragmentManager
import gorden.krefreshlayout.demo.R
import gorden.krefreshlayout.demo.ui.fragment.*
import kotlinx.android.synthetic.main.activity_sample.*
class SampleActivity : AppCompatActivity() {
private var mFragment:ISampleFragment? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_sample)
text_title.text = intent.getStringExtra("name")
btn_back.setOnClickListener {
finish()
}
btn_setting.setOnClickListener {
val intent = Intent("SettingActivity")
intent.putExtra("header",mFragment?.headerPosition)
intent.putExtra("pincontent",mFragment?.pinContent)
intent.putExtra("keepheader",mFragment?.keepHeaderWhenRefresh)
intent.putExtra("durationoffset",mFragment?.durationOffset)
intent.putExtra("refreshtime",mFragment?.refreshTime)
startActivityForResult(intent,612)
}
val position = intent.getIntExtra("position",0)
val manager:FragmentManager = supportFragmentManager
when(position){
0-> mFragment = SampleAFragment()
1-> mFragment = SampleBFragment()
2-> mFragment = SampleCFragment()
3-> mFragment = SampleDFragment()
4-> mFragment = SampleEFragment()
5-> mFragment = SampleFFragment()
6-> mFragment = SampleGFragment()
7-> mFragment = SampleHFragment()
8-> mFragment = SampleIFragment()
9-> mFragment = SampleJFragment()
else ->mFragment = SampleAFragment()
}
manager.beginTransaction().replace(R.id.frame_content,mFragment).commit()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 612&&resultCode == Activity.RESULT_OK){
mFragment?.headerPosition = data!!.getIntExtra("header",mFragment!!.headerPosition)
mFragment?.pinContent = data.getBooleanExtra("pincontent",mFragment!!.pinContent)
mFragment?.keepHeaderWhenRefresh = data.getBooleanExtra("keepheader",mFragment!!.keepHeaderWhenRefresh)
mFragment?.durationOffset = data.getLongExtra("durationoffset",mFragment!!.durationOffset)
mFragment?.refreshTime = data.getLongExtra("refreshtime",mFragment!!.refreshTime)
}
}
}
| app_kotlin/src/main/kotlin/gorden/krefreshlayout/demo/ui/SampleActivity.kt | 3266643228 |
package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.commands.AbstractCommand
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.perfectdreams.loritta.morenitta.utils.Constants
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.common.locale.LocaleKeyData
import net.perfectdreams.loritta.morenitta.api.commands.Command
import java.awt.image.BufferedImage
import java.io.File
import javax.imageio.ImageIO
import net.perfectdreams.loritta.morenitta.LorittaBot
class PerdaoCommand(loritta: LorittaBot) : AbstractCommand(loritta, "perdao", listOf("perdão"), net.perfectdreams.loritta.common.commands.CommandCategory.IMAGES) {
companion object {
val TEMPLATE by lazy { ImageIO.read(File(Constants.ASSETS_FOLDER, "perdao.png")) }
}
override fun getDescriptionKey() = LocaleKeyData("commands.command.forgive.description")
override fun getExamplesKey() = Command.SINGLE_IMAGE_EXAMPLES_KEY
// TODO: Fix Usage
override fun needsToUploadFiles(): Boolean {
return true
}
override suspend fun run(context: CommandContext,locale: BaseLocale) {
val contextImage = context.getImageAt(0) ?: run { Constants.INVALID_IMAGE_REPLY.invoke(context); return; }
// RULE OF THREE!!11!
// larguraOriginal - larguraDoContextImage
// alturaOriginal - X
val newHeight = (contextImage.width * TEMPLATE.height) / TEMPLATE.width
val scaledTemplate = TEMPLATE.getScaledInstance(contextImage.width, Math.max(newHeight, 1), BufferedImage.SCALE_SMOOTH)
contextImage.graphics.drawImage(scaledTemplate, 0, contextImage.height - scaledTemplate.getHeight(null), null)
context.sendFile(contextImage, "perdao.png", context.getAsMention(true))
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/PerdaoCommand.kt | 1601524696 |
/*
* Copyright © 2020 Wayfair. All rights reserved.
*/
package com.wayfair.brickkit.size
import com.wayfair.brickkit.BrickDataManager
class FullPhoneThirdTabletBrickSize : BrickSize(
BrickDataManager.SPAN_COUNT,
BrickDataManager.SPAN_COUNT,
BrickDataManager.SPAN_COUNT / 3,
BrickDataManager.SPAN_COUNT / 3
)
| BrickKit/bricks/src/main/java/com/wayfair/brickkit/size/FullPhoneThirdTabletBrickSize.kt | 3406555732 |
package at.cpickl.gadsu.service
fun GapiCredentials.Companion.testInstance() = GapiCredentials("testClientId", "testClientSecret")
| src/test/kotlin/at/cpickl/gadsu/service/test_infra.kt | 845547637 |
data class Tuple86<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20, T21, T22, T23, T24, T25, T26, T27, T28, T29, T30, T31, T32, T33, T34, T35, T36, T37, T38, T39, T40, T41, T42, T43, T44, T45, T46, T47, T48, T49, T50, T51, T52, T53, T54, T55, T56, T57, T58, T59, T60, T61, T62, T63, T64, T65, T66, T67, T68, T69, T70, T71, T72, T73, T74, T75, T76, T77, T78, T79, T80, T81, T82, T83, T84, T85, T86>(val item1: T1, val item2: T2, val item3: T3, val item4: T4, val item5: T5, val item6: T6, val item7: T7, val item8: T8, val item9: T9, val item10: T10, val item11: T11, val item12: T12, val item13: T13, val item14: T14, val item15: T15, val item16: T16, val item17: T17, val item18: T18, val item19: T19, val item20: T20, val item21: T21, val item22: T22, val item23: T23, val item24: T24, val item25: T25, val item26: T26, val item27: T27, val item28: T28, val item29: T29, val item30: T30, val item31: T31, val item32: T32, val item33: T33, val item34: T34, val item35: T35, val item36: T36, val item37: T37, val item38: T38, val item39: T39, val item40: T40, val item41: T41, val item42: T42, val item43: T43, val item44: T44, val item45: T45, val item46: T46, val item47: T47, val item48: T48, val item49: T49, val item50: T50, val item51: T51, val item52: T52, val item53: T53, val item54: T54, val item55: T55, val item56: T56, val item57: T57, val item58: T58, val item59: T59, val item60: T60, val item61: T61, val item62: T62, val item63: T63, val item64: T64, val item65: T65, val item66: T66, val item67: T67, val item68: T68, val item69: T69, val item70: T70, val item71: T71, val item72: T72, val item73: T73, val item74: T74, val item75: T75, val item76: T76, val item77: T77, val item78: T78, val item79: T79, val item80: T80, val item81: T81, val item82: T82, val item83: T83, val item84: T84, val item85: T85, val item86: T86) {
}
| src/main/kotlin/com/github/kmizu/kollection/tuples/Tuple86.kt | 3468276191 |
package ee.design.json
import ee.design.appendTypes
import org.slf4j.LoggerFactory
import java.nio.file.Paths
object JsonToDesignMain {
private val log = LoggerFactory.getLogger(javaClass)
@JvmStatic
fun main(args: Array<String>) {
val json = JsonToDesign(mutableMapOf(),
mutableMapOf("rel.self" to "Link", "Href" to "Link", "AspectId" to "n.String", "ETag" to "n.String",
"Errors" to "n.String", "TenantId" to "n.String", "TypeId" to "n.String"),
mutableSetOf("AspectId", "ETag", "Errors", "TenantId", "TypeId"))
val alreadyGeneratedTypes = mutableMapOf<String, String>()
val buffer = StringBuffer()
val dslTypes = json.toDslTypes(Paths.get("/home/z000ru5y/dev/s2r/cdm/cdm_schema.json"))
buffer.appendTypes(log, dslTypes, alreadyGeneratedTypes)
log.info(buffer.toString())
}
} | ee-design_json/src/test/kotlin/ee/design/json/JsonToDesignMain.kt | 3019055200 |
package com.braintreepayments.api
import androidx.fragment.app.testing.FragmentScenario
import androidx.lifecycle.Lifecycle
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.ViewActions.click
import androidx.test.espresso.action.ViewActions.typeText
import androidx.test.espresso.assertion.ViewAssertions.matches
import androidx.test.espresso.matcher.ViewMatchers.*
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.braintreepayments.api.CardNumber.*
import com.braintreepayments.api.dropin.R
import com.braintreepayments.cardform.utils.CardType
import junit.framework.TestCase.assertNull
import org.hamcrest.CoreMatchers.not
import org.junit.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class AddCardFragmentUITest {
@Test
fun whenStateIsRESUMED_buttonTextIsAddCard() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
}
onView(isRoot()).perform(waitFor(500))
// TODO: migrate assertions to use plain text instead of internal view ids
onView(withId(R.id.bt_button)).check(matches(withText(R.string.bt_next)))
}
@Test
fun whenStateIsRESUMED_cardNumberFieldIsFocused() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
onView(withId(R.id.bt_card_form_card_number)).check(matches(isFocused()))
}
@Test
fun whenStateIsRESUMED_andNonCardNumberError_doesNotShowError() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
fragment.dropInViewModel.setCardTokenizationError(
ErrorWithResponse.fromJson(IntegrationTestFixtures.CREDIT_CARD_EXPIRATION_ERROR_RESPONSE))
assertNull(fragment.cardForm.cardEditText.textInputLayoutParent?.error)
}
}
@Test
fun whenStateIsRESUMED_sendsAnalyticsEvent() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
val activity = fragment.requireActivity()
val fragmentManager = fragment.parentFragmentManager
fragmentManager.setFragmentResultListener(DropInEvent.REQUEST_KEY, activity) { _, result ->
val event = DropInEvent.fromBundle(result)
assertEquals(DropInEventType.SEND_ANALYTICS, event.type)
assertEquals("card.selected", event.getString(DropInEventProperty.ANALYTICS_EVENT_NAME))
}
}
}
@Test
fun whenStateIsRESUMED_onSubmitButtonClick_whenCardFormValid_showsLoader() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
}
onView(isRoot()).perform(waitFor(500))
onView(withId(R.id.bt_card_form_card_number)).perform(typeText(VISA))
onView(withId(R.id.bt_button)).perform(click())
onView(withId(R.id.bt_button)).check(matches(not(isDisplayed())))
onView(withId(R.id.bt_animated_button_loading_indicator)).check(matches(isDisplayed()))
}
@Test
fun whenStateIsRESUMED_onSubmitButtonClick_whenCardFormNotValid_showsSubmitButton() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
}
onView(isRoot()).perform(waitFor(500))
onView(withId(R.id.bt_card_form_card_number)).perform(typeText(INVALID_VISA))
onView(withId(R.id.bt_button)).perform(click())
onView(withId(R.id.bt_button)).check(matches(isDisplayed()))
onView(withId(R.id.bt_animated_button_loading_indicator)).check(matches(not(isDisplayed())))
}
@Test
fun whenStateIsRESUMED_onSubmitButtonClick_whenCardTypeNotSupported_showsSubmitButton() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
}
onView(isRoot()).perform(waitFor(500))
onView(withId(R.id.bt_card_form_card_number)).perform(typeText(AMEX))
onView(withId(R.id.bt_button)).perform(click())
onView(withId(R.id.bt_button)).check(matches(isDisplayed()))
onView(withId(R.id.bt_animated_button_loading_indicator)).check(matches(not(isDisplayed())))
}
@Test
fun whenStateIsRESUMED_onSubmitButtonClickWithValidCardNumber_sendsAddCardEvent() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
}
onView(isRoot()).perform(waitFor(500))
onView(withId(R.id.bt_card_form_card_number)).perform(typeText(VISA))
onView(withId(R.id.bt_button)).perform(click())
scenario.onFragment { fragment ->
val activity = fragment.requireActivity()
val fragmentManager = fragment.parentFragmentManager
fragmentManager.setFragmentResultListener(DropInEvent.REQUEST_KEY, activity) { _, result ->
val event = DropInEvent.fromBundle(result)
assertEquals(DropInEventType.ADD_CARD_SUBMIT, event.type)
assertEquals(VISA, event.getString(DropInEventProperty.CARD_NUMBER))
}
}
}
@Test
fun whenStateIsRESUMED_whenCardNumberValidationErrorsArePresentInViewModel_displaysErrorsInlineToUser() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
fragment.dropInViewModel.setCardTokenizationError(
ErrorWithResponse.fromJson(IntegrationTestFixtures.CREDIT_CARD_ERROR_RESPONSE))
assertEquals(fragment.context?.getString(R.string.bt_card_number_invalid),
fragment.cardForm.cardEditText.textInputLayoutParent?.error)
}
}
@Test
fun whenStateIsRESUMED_whenCardNumberIsDuplicate_displaysErrorsInlineToUser() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
fragment.dropInViewModel.setCardTokenizationError(
ErrorWithResponse.fromJson(IntegrationTestFixtures.ERRORS_CREDIT_CARD_DUPLICATE))
assertEquals(fragment.context?.getString(R.string.bt_card_already_exists),
fragment.cardForm.cardEditText.textInputLayoutParent?.error)
}
}
@Test
fun whenStateIsRESUMED_whenCardFromInvalid_showsSubmitButton() {
val scenario = FragmentScenario.launchInContainer(AddCardFragment::class.java, null, R.style.bt_drop_in_activity_theme)
scenario.moveToState(Lifecycle.State.RESUMED)
scenario.onFragment { fragment ->
fragment.dropInViewModel.setSupportedCardTypes(listOf(CardType.VISA))
fragment.dropInViewModel.setCardTokenizationError(
ErrorWithResponse.fromJson(IntegrationTestFixtures.CREDIT_CARD_ERROR_RESPONSE))
}
onView(withId(R.id.bt_button)).check(matches(isDisplayed()))
}
}
| Drop-In/src/androidTest/java/com/braintreepayments/api/AddCardFragmentUITest.kt | 1074277531 |
package io.polymorphicpanda.kspec.engine
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import io.polymorphicpanda.kspec.KSpec
import io.polymorphicpanda.kspec.config.KSpecConfig
import io.polymorphicpanda.kspec.context
import io.polymorphicpanda.kspec.describe
import io.polymorphicpanda.kspec.engine.discovery.DiscoveryRequest
import io.polymorphicpanda.kspec.engine.execution.ExecutionNotifier
import io.polymorphicpanda.kspec.engine.execution.ExecutionRequest
import io.polymorphicpanda.kspec.it
import io.polymorphicpanda.kspec.tag.SimpleTag
import org.junit.Test
/**
* @author Ranie Jade Ramiso
*/
class AroundHookTest {
object Tag1: SimpleTag()
@Test
fun testMatchTag() {
val builder = StringBuilder()
val config = KSpecConfig()
val notifier = ExecutionNotifier()
val engine = KSpecEngine(notifier)
config.around(Tag1::class) { context, chain ->
builder.appendln(context.description)
chain.next(context)
}
class TestSpec: KSpec() {
override fun spec() {
describe("group") {
context("context", Tag1) {
it("example") { }
}
it("another example", Tag1) { }
}
}
}
val result = engine.discover(DiscoveryRequest(listOf(TestSpec::class), config))
val expected = """
context: context
it: example
it: another example
""".trimIndent()
engine.execute(ExecutionRequest(result))
assertThat(builder.trimEnd().toString(), equalTo(expected))
}
@Test
fun testMatchAll() {
val builder = StringBuilder()
val config = KSpecConfig()
val notifier = ExecutionNotifier()
val engine = KSpecEngine(notifier)
config.around { context, chain ->
builder.appendln(context.description)
chain.next(context)
}
class TestSpec: KSpec() {
override fun spec() {
describe("group") {
context("context", Tag1) {
it("example") { }
}
it("another example", Tag1) { }
}
}
}
val result = engine.discover(DiscoveryRequest(listOf(TestSpec::class), config))
val expected = """
${TestSpec::class.java.name}
describe: group
context: context
it: example
it: another example
""".trimIndent()
engine.execute(ExecutionRequest(result))
assertThat(builder.trimEnd().toString(), equalTo(expected))
}
}
| kspec-engine/src/test/kotlin/io/polymorphicpanda/kspec/engine/AroundHookTest.kt | 3737857450 |
package io.kotest.extensions.http
import io.ktor.client.HttpClient
import io.ktor.client.request.HttpRequestBuilder
import io.ktor.client.request.header
import io.ktor.client.request.request
import io.ktor.client.request.url
import io.ktor.client.statement.HttpResponse
import io.ktor.http.HttpMethod
fun parseHttpRequest(lines: List<String>): HttpRequestBuilder {
val builder = HttpRequestBuilder()
val method = HttpMethod.DefaultMethods.find { lines[0].startsWith(it.value) } ?: HttpMethod.Get
builder.method = method
val url = lines[0].removePrefix(method.value).trim()
builder.url(url)
lines.drop(1).takeWhile { it.isNotBlank() }.map {
val (key, value) = it.split(':')
builder.header(key, value)
}
val body = lines.drop(1).dropWhile { it.isNotBlank() }.joinToString("\n").trim()
builder.body = body
return builder
}
suspend fun runRequest(req: HttpRequestBuilder): HttpResponse {
val client = HttpClient()
return client.request<HttpResponse>(req)
}
| kotest-extensions/kotest-extensions-http/src/commonMain/kotlin/io/kotest/extensions/http/parser.kt | 3654677176 |
package com.lasthopesoftware.bluewater.client.stored.library.sync.GivenOneLibraryToSync
import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile
import com.lasthopesoftware.bluewater.client.browsing.library.access.FakeLibraryProvider
import com.lasthopesoftware.bluewater.client.browsing.library.repository.Library
import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId
import com.lasthopesoftware.bluewater.client.stored.library.sync.CollectServiceFilesForSync
import com.lasthopesoftware.bluewater.client.stored.library.sync.SyncChecker
import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture
import com.namehillsoftware.handoff.promises.Promise
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class WhenCheckingIfSyncIsNecessary {
companion object {
private val isSyncNeeded by lazy {
val collector = mockk<CollectServiceFilesForSync>()
every { collector.promiseServiceFilesToSync(any()) } returns Promise(emptySet())
every { collector.promiseServiceFilesToSync(LibraryId(11)) } returns Promise(
listOf(
ServiceFile(3),
ServiceFile(6)))
SyncChecker(
FakeLibraryProvider(
Library().setId(3),
Library().setId(11),
Library().setId(10)
), collector)
.promiseIsSyncNeeded()
.toFuture()
.get()
}
}
@Test
fun thenSyncIsNeeded() {
assertThat(isSyncNeeded).isTrue
}
}
| projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/stored/library/sync/GivenOneLibraryToSync/WhenCheckingIfSyncIsNecessary.kt | 3500757036 |
package furhatos.app.fortuneteller.gestures
import furhatos.gestures.BasicParams
import furhatos.gestures.defineGesture
val cSmile = defineGesture("cSmile") {
frame(0.5, persist = true) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
}
fun rollHead(strength: Double = 1.0, duration: Double = 1.0) =
defineGesture("rollHead") {
frame(0.4, duration) {
BasicParams.NECK_ROLL to strength
}
reset(duration + 0.1)
}
val FallAsleep = defineGesture("FallAsleep") {
frame(0.5, persist = true) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
}
val MySmile = defineGesture("MySmile") {
frame(0.32, 0.72) {
BasicParams.SMILE_CLOSED to 2.0
}
frame(0.2, 0.72) {
BasicParams.BROW_UP_LEFT to 4.0
BasicParams.BROW_UP_RIGHT to 4.0
}
frame(0.16, 0.72) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 0.1
}
reset(1.04)
}
val TripleBlink = defineGesture("TripleBlink") {
frame(0.1, 0.3) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(0.3, 0.5) {
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
}
frame(0.5, 0.7) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(0.7, 0.9) {
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
BasicParams.BROW_UP_LEFT to 2.0
BasicParams.BROW_UP_RIGHT to 2.0
}
frame(0.9, 1.1) {
BasicParams.BLINK_LEFT to 1.0
BasicParams.BLINK_RIGHT to 1.0
}
frame(1.1, 1.4) {
BasicParams.BLINK_LEFT to 0.1
BasicParams.BLINK_RIGHT to 0.1
}
frame(1.4, 1.5) {
BasicParams.BROW_UP_LEFT to 0
BasicParams.BROW_UP_RIGHT to 0
}
reset(1.5)
} | FortuneTeller/src/main/kotlin/furhatos/app/fortuneteller/gestures/gestures.kt | 1536564397 |
package com.github.emulio.scrapers.tgdb.model
data class Genre(
val id: Int,
val name: String
) | core/src/main/com/github/emulio/scrapers/tgdb/model/Genre.kt | 103021695 |
package com.mcxiaoke.koi.ext
import android.os.Bundle
/**
* User: mcxiaoke
* Date: 16/1/26
* Time: 16:43
*/
inline fun Bundle(body: Bundle.() -> Unit): Bundle {
val bundle = Bundle()
bundle.body()
return bundle
}
inline fun Bundle(loader: ClassLoader, body: Bundle.() -> Unit): Bundle {
val bundle = Bundle(loader)
bundle.body()
return bundle
}
inline fun Bundle(capacity: Int, body: Bundle.() -> Unit): Bundle {
val bundle = Bundle(capacity)
bundle.body()
return bundle
}
inline fun Bundle(b: Bundle?, body: Bundle.() -> Unit): Bundle {
val bundle = Bundle(b)
bundle.body()
return bundle
}
| core/src/main/kotlin/com/mcxiaoke/koi/ext/Bundle.kt | 1059127940 |
/*
* Copyright (C) 2016 Mihály Szabó
*
* 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 org.libreplicator.json.api
import kotlin.reflect.KClass
data class JsonMixin(val targetClass: KClass<*>, val sourceClass: KClass<*>)
| libreplicator-json-api/src/main/kotlin/org/libreplicator/json/api/JsonMixin.kt | 7117714 |
package net.halawata.artich.model
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseHelper(val context: Context): SQLiteOpenHelper(context, "artich.db", null, 1) {
override fun onCreate(p0: SQLiteDatabase?) {
p0?.execSQL("CREATE TABLE t_menu_common (id INTEGER PRIMARY KEY, name TEXT)")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(1, 'JavaScript')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(2, 'Ruby')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(3, 'Python')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(4, 'iOS')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(5, 'PHP')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(6, 'Rails')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(7, 'Android')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(8, 'Swift')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(9, 'Java')")
p0?.execSQL("INSERT INTO t_menu_common(id, name) VALUES(10, 'AWS')")
p0?.execSQL("CREATE TABLE t_menu_hatena (id INTEGER PRIMARY KEY, name TEXT)")
p0?.execSQL("CREATE TABLE t_menu_qiita (id INTEGER PRIMARY KEY, name TEXT)")
p0?.execSQL("CREATE TABLE t_menu_gnews (id INTEGER PRIMARY KEY, name TEXT)")
p0?.execSQL("CREATE TABLE t_mute_hatena (id INTEGER PRIMARY KEY, name TEXT)")
p0?.execSQL("CREATE TABLE t_mute_qiita (id INTEGER PRIMARY KEY, name TEXT)")
p0?.execSQL("CREATE TABLE t_mute_gnews (id INTEGER PRIMARY KEY, name TEXT)")
}
override fun onUpgrade(p0: SQLiteDatabase?, p1: Int, p2: Int) {
p0?.execSQL("DROP TABLE IF EXISTS t_menu_common")
p0?.execSQL("DROP TABLE IF EXISTS t_menu_hatena")
p0?.execSQL("DROP TABLE IF EXISTS t_menu_qiita")
p0?.execSQL("DROP TABLE IF EXISTS t_menu_gnews")
p0?.execSQL("DROP TABLE IF EXISTS t_mute_hatena")
p0?.execSQL("DROP TABLE IF EXISTS t_mute_qiita")
p0?.execSQL("DROP TABLE IF EXISTS t_mute_gnews")
onCreate(p0)
}
}
| app/src/main/java/net/halawata/artich/model/DatabaseHelper.kt | 2899555252 |
package de.ph1b.audiobook.features
import android.app.Activity
import android.content.Intent
import com.bluelinelabs.conductor.Controller
import de.ph1b.audiobook.data.Book2
import de.ph1b.audiobook.features.bookOverview.EditCoverDialogController
import javax.inject.Inject
private const val REQUEST_CODE = 7
class GalleryPicker
@Inject constructor() {
private var pickForBookId: Book2.Id? = null
fun pick(bookId: Book2.Id, controller: Controller) {
pickForBookId = bookId
val intent = Intent(Intent.ACTION_PICK)
.setType("image/*")
controller.startActivityForResult(intent, REQUEST_CODE)
}
fun parse(requestCode: Int, resultCode: Int, data: Intent?): EditCoverDialogController.Arguments? {
if (requestCode != REQUEST_CODE) {
return null
}
return if (resultCode == Activity.RESULT_OK) {
val imageUri = data?.data
val bookId = pickForBookId
if (imageUri == null || bookId == null) {
null
} else {
EditCoverDialogController.Arguments(imageUri, bookId)
}
} else {
null
}
}
}
| app/src/main/kotlin/de/ph1b/audiobook/features/GalleryPicker.kt | 295913877 |
package de.fabmax.calc.layout
import de.fabmax.calc.MainActivity
import de.fabmax.calc.ui.*
import de.fabmax.lightgl.util.CharMap
import de.fabmax.lightgl.util.Color
import de.fabmax.lightgl.util.GlFont
/**
* Definition of the calculator phone layout. Quite hacky but it does the trick for this prototype.
*/
fun phoneLayout(activity: MainActivity): Layout {
// Used colors, fixme: take them from R.colors
val lightGray = Color("#e1e7ea")
val gray = Color("#78909c")
val darkGray = Color("#536771")
val cyan = Color("#8cf2f2")
val petrol = Color("#26c6da")
// CharMap is used to generate the font textures. It must contain all string characters
// used in the layout (but preferably not more to save texture memory)
val chars = CharMap(" 0123456789.=+-/sincotaer()^vlgCLRDELw" + CalcPanel.TIMES +
CalcPanel.DIVISION + CalcPanel.PI + CalcPanel.SQRT)
// Different font styles used in the layout
val fontCfgNums = GlFont.FontConfig(activity.assets, "Roboto-Light.ttf", chars, dp(32f, activity))
val fontCfgSmall = GlFont.FontConfig(activity.assets, "Roboto-Light.ttf", chars, dp(18f, activity))
val fontCfgLarge = GlFont.FontConfig(activity.assets, "Roboto-Thin.ttf", chars, dp(44f, activity))
// Builder FTW!
return layout(activity) {
bounds(rw(-0.5f), rh(-0.5f), rw(1.0f), rh(1.0f))
val calcPanel = calcPanel {
init {
color = lightGray
fontConfig = fontCfgLarge
fontColor = gray
}
port {
bounds(dp(0f), dp(0f), dp(16f), rw(1.02f), rh(0.26f), dp(0f))
textSize = 1f
}
land {
bounds(dp(0f), dp(0f), dp(16f), rw(1.025f), rh(0.31f), dp(0f))
textSize = 0.75f
}
}
var texts = arrayListOf("7", "8", "9", "4", "5", "6", "1", "2", "3", ".", "0", "")
for (i in 0..11) {
button {
init {
color = darkGray
fontConfig = fontCfgNums
fontColor = lightGray
text = texts[i]
onClickListener = { -> calcPanel.buttonPressed(text) }
}
port {
textSize = 1f
bounds(rw(1 / 4f * (i % 3)), rh(1 / 4f + (i / 3) * 0.15f), rw(1 / 4f), rh(0.15f))
}
land {
textSize = .8f
bounds(rw(1 / 8f * (i % 3)), rh(0.3f + (i / 3) * 0.175f), rw(1 / 8f), rh(0.175f))
}
}
}
texts = arrayListOf("+", "-", CalcPanel.TIMES.toString(), CalcPanel.DIVISION.toString())
for (i in 0..3) {
button {
init {
fontConfig = fontCfgSmall
fontColor = darkGray
text = texts[i]
onClickListener = { -> calcPanel.buttonPressed(text) }
}
port {
bounds(rw(0.74f), rh(1 / 4f + i * 0.15f), dp(8f), rw(.26f), rh(0.15f), dp(0f))
color = cyan
}
land {
bounds(rw(0.375f), rh(0.3f + i * 0.175f), dp(8f), rw(1 / 8f), rh(0.175f), dp(0f))
color = petrol
}
}
}
texts = arrayListOf("CLR", "DEL", "view", "=")
for (i in 0..3) {
button {
init {
color = petrol
fontConfig = fontCfgSmall
fontColor = darkGray
text = texts[i]
when (text) {
"view" -> onClickListener = { -> activity.toggleCamera() }
else -> onClickListener = { -> calcPanel.buttonPressed(text) }
}
val interpolator = ParabolicBoundsInterpolator(layoutConfig)
interpolator.amplitudeZ = dp((4 - i) * 50f, context)
layoutConfig.boundsInterpolator = interpolator
}
port {
bounds(rw(.26f * i - .01f), rh(0.85f), dp(-16f), rw(.26f), rh(0.16f), dp(0f))
if (texts[i] == "=") {
bounds(rw(.74f), rh(0.85f), dp(8f), rw(.26f), rh(0.15f), dp(0f))
color = cyan
}
}
land {
bounds(rw(.5f), rh(.3f + i * .175f), dp(8f), rw(1 / 8f), rh(0.175f), dp(0f))
}
}
}
texts = arrayListOf("sin", "cos", "tan", "ln", "log", "inv", CalcPanel.SQRT.toString(),
CalcPanel.PI.toString(), "e", "^", "(", ")")
for (i in 0..11) {
button {
init {
id = texts[i]
color = cyan
fontConfig = fontCfgSmall
fontColor = darkGray
text = texts[i]
when (text) {
"inv" -> onClickListener = { -> activity.flipFunctions() }
else -> onClickListener = { -> calcPanel.buttonPressed(text) }
}
}
port {
bounds(rw(1.4f + 1 / 8f * (i % 3) + i / 3 * .25f), rh(1 / 4f + (i / 3) * 0.15f),
dp((i / 3 + 1) * -50f), rw(1 / 4f), rh(0.15f), dp(0f))
}
land {
bounds(rw(0.625f + 1 / 8f * (i % 3)), rh(0.3f + (i / 3) * 0.175f),
rw(1 / 8f), rh(0.175f))
}
}
}
}
} | app/src/main/kotlin/de/fabmax/calc/layout/PhoneLayout.kt | 1233276073 |
package org.fdroid.download
import io.ktor.client.plugins.ResponseException
import kotlinx.coroutines.runBlocking
import java.io.IOException
/**
* HTTP POST a JSON string to the URL configured in the constructor.
*/
public class HttpPoster(
private val httpManager: HttpManager,
private val url: String,
) {
@Throws(IOException::class)
public fun post(json: String) {
runBlocking {
try {
httpManager.post(url, json)
} catch (e: ResponseException) {
throw IOException(e)
}
}
}
}
| libs/download/src/androidMain/kotlin/org/fdroid/download/HttpPoster.kt | 3524513822 |
package io.particle.android.sdk.ui.devicelist
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.snakydesign.livedataextensions.distinctUntilChanged
import com.snakydesign.livedataextensions.map
import com.snakydesign.livedataextensions.switchMap
import io.particle.android.sdk.cloud.BroadcastContract
import io.particle.android.sdk.cloud.ParticleCloudSDK
import io.particle.android.sdk.cloud.ParticleDevice
import io.particle.android.sdk.ui.devicelist.OnlineStatusFilter.ALL_SELECTED
import io.particle.android.sdk.ui.devicelist.OnlineStatusFilter.NONE_SELECTED
import io.particle.android.sdk.ui.devicelist.OnlineStatusFilter.OFFLINE_ONLY
import io.particle.android.sdk.ui.devicelist.OnlineStatusFilter.ONLINE_ONLY
import io.particle.mesh.common.android.livedata.BroadcastReceiverLD
import io.particle.mesh.common.android.livedata.castAndPost
import io.particle.mesh.common.android.livedata.castAndSetOnMainThread
import io.particle.mesh.setup.flow.Scopes
import mu.KLogger
import mu.KotlinLogging
val defaultDeviceListConfig = DeviceListViewConfig(
SortCriteria.ONLINE_STATUS,
OnlineStatusFilter.NONE_SELECTED,
emptySet()
)
open class DeviceFilter(
fullDeviceListLD: LiveData<List<ParticleDevice>>
) {
var filteredDeviceListLD: LiveData<List<ParticleDevice>>
val deviceListViewConfigLD: MutableLiveData<DeviceListViewConfig> = MutableLiveData()
protected var currentConfig: DeviceListViewConfig
get() {
return _currentConfig
}
set(value) {
if (value == _currentConfig) {
log.debug { "New config matches; doing nothing." }
return
}
log.debug { "Changing config to: $value" }
_currentConfig = value
deviceListViewConfigLD.castAndPost(_currentConfig)
}
private var _currentConfig: DeviceListViewConfig
protected open val log: KLogger = KotlinLogging.logger {}
init {
_currentConfig = defaultDeviceListConfig
deviceListViewConfigLD.castAndSetOnMainThread(_currentConfig)
filteredDeviceListLD = deviceListViewConfigLD
.distinctUntilChanged()
.switchMap {
fullDeviceListLD.map { sortAndFilterDeviceList(it, currentConfig) }
}
}
fun applyNewConfig(newConfig: DeviceListViewConfig) {
log.debug { "Applying new config: $newConfig" }
currentConfig = newConfig
}
fun resetConfig() {
applyNewConfig(defaultDeviceListConfig)
}
}
class DraftDeviceFilter(
private val deviceFilter: DeviceFilter,
fullDeviceListLD: LiveData<List<ParticleDevice>>
) : DeviceFilter(fullDeviceListLD) {
override val log: KLogger = KotlinLogging.logger {}
fun commitDraftConfig() {
log.debug { "Committing draft config" }
deviceFilter.applyNewConfig(currentConfig)
}
fun updateFromLiveConfig() {
log.info { "Updating draft to use current live config" }
currentConfig = deviceFilter.deviceListViewConfigLD.value!!
}
fun updateNameQuery(query: String?) {
log.info { "updateNameQuery(): query=$query" }
val newQuery = if (query.isNullOrBlank()) null else query
currentConfig = currentConfig.copy(deviceNameQueryString = newQuery)
}
fun updateSort(sortCriteria: SortCriteria) {
log.info { "updateSort(): sortCriteria=$sortCriteria" }
currentConfig = currentConfig.copy(sortCriteria = sortCriteria)
}
fun updateOnlineStatus(onlineStatusFilter: OnlineStatusFilter) {
log.info { "updateOnlineStatus(): onlineStatusFilter=$onlineStatusFilter" }
fun returnOppositeFilter(filter: OnlineStatusFilter): OnlineStatusFilter {
return when (filter) {
ALL_SELECTED -> NONE_SELECTED
NONE_SELECTED -> ALL_SELECTED
ONLINE_ONLY -> OFFLINE_ONLY
OFFLINE_ONLY -> ONLINE_ONLY
}
}
val newFilter = when (currentConfig.onlineStatusFilter) {
ALL_SELECTED -> returnOppositeFilter(onlineStatusFilter)
NONE_SELECTED -> onlineStatusFilter
ONLINE_ONLY -> if (onlineStatusFilter == ONLINE_ONLY) {
NONE_SELECTED
} else {
ALL_SELECTED
}
OFFLINE_ONLY -> if (onlineStatusFilter == OFFLINE_ONLY) {
NONE_SELECTED
} else {
ALL_SELECTED
}
}
currentConfig = currentConfig.copy(onlineStatusFilter = newFilter)
}
fun includeDeviceInDeviceTypeFilter(toInclude: DeviceTypeFilter) {
log.info { "includeDeviceInDeviceTypeFilter(): toInclude=$toInclude" }
val newDeviceTypes = currentConfig.deviceTypeFilters.plus(toInclude)
currentConfig = currentConfig.copy(deviceTypeFilters = newDeviceTypes)
}
fun removeDeviceFromDeviceTypeFilter(toRemove: DeviceTypeFilter) {
log.info { "removeDeviceFromDeviceTypeFilter(): toRemove=$toRemove" }
val newDeviceTypes = currentConfig.deviceTypeFilters.minus(toRemove)
currentConfig = currentConfig.copy(deviceTypeFilters = newDeviceTypes)
}
}
class DeviceFilterViewModel(app: Application) : AndroidViewModel(app) {
val fullDeviceListLD: LiveData<List<ParticleDevice>> = MutableLiveData()
val currentDeviceFilter = DeviceFilter(fullDeviceListLD)
val draftDeviceFilter = DraftDeviceFilter(currentDeviceFilter, fullDeviceListLD)
private val cloud = ParticleCloudSDK.getCloud()
private val devicesUpdatedBroadcast: BroadcastReceiverLD<Int>
private val refreshObserver = Observer<Any?> { refreshDevices() }
private val scopes = Scopes()
private var firstRefreshRequested = false
private val log = KotlinLogging.logger {}
init {
// arbitrary value that always changes every time we receive the broadcast, telling us to
// retrieve the new devices
var initialValue = 0
devicesUpdatedBroadcast = BroadcastReceiverLD(
app,
BroadcastContract.BROADCAST_DEVICES_UPDATED,
{ ++initialValue },
true
)
devicesUpdatedBroadcast.observeForever(refreshObserver)
}
override fun onCleared() {
super.onCleared()
scopes.cancelAll()
devicesUpdatedBroadcast.removeObserver(refreshObserver)
}
fun refreshDevices() {
scopes.onMain { doRefreshDevices() }
}
private suspend fun doRefreshDevices() {
val deviceList = try {
scopes.withWorker {
cloud.getDevices()
}
} catch (ex: Exception) {
return
}
fullDeviceListLD.castAndPost(deviceList)
val config = currentDeviceFilter.deviceListViewConfigLD.value!!
currentDeviceFilter.applyNewConfig(config)
if (!firstRefreshRequested) {
// make sure devices are as "live" as possible
loadDeviceDetails(deviceList)
firstRefreshRequested = true
}
}
private fun loadDeviceDetails(devices: List<ParticleDevice>) {
scopes.onWorker {
for (device in devices) {
if (device.isConnected) {
try {
device.refresh()
} catch (ex: Exception) {
// This is just an optimization to give online devices their full
// function/variable info faster; no need to do anything if it fails
continue
}
}
}
}
}
}
| app/src/main/java/io/particle/android/sdk/ui/devicelist/DeviceFilterViewModel.kt | 2039446026 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.testing
import android.os.Looper
import com.facebook.litho.ComponentTree
import java.util.concurrent.ArrayBlockingQueue
import java.util.concurrent.BlockingQueue
import org.robolectric.Shadows
import org.robolectric.annotation.LooperMode
import org.robolectric.shadows.ShadowLooper
/**
* Helper class extracting looper functionality from [BackgroundLayoutLooperRule] that can be reused
* in other TestRules
*/
class ThreadLooperController(
val layoutLooper: ShadowLooper =
Shadows.shadowOf(
Whitebox.invokeMethod<Any>(ComponentTree::class.java, "getDefaultLayoutThreadLooper")
as Looper)
) : BaseThreadLooperController {
private lateinit var messageQueue: BlockingQueue<Message>
private var isInitialized = false
override fun init() {
messageQueue = ArrayBlockingQueue(100)
val layoutLooperThread = LayoutLooperThread(layoutLooper, messageQueue)
layoutLooperThread.start()
isInitialized = true
}
override fun clean() {
if (!isInitialized) {
return
}
quitSync()
if (ShadowLooper.looperMode() != LooperMode.Mode.PAUSED) {
layoutLooper.quitUnchecked()
}
isInitialized = false
}
private fun quitSync() {
val semaphore = TimeOutSemaphore(0)
messageQueue.add(Message(MessageType.QUIT, semaphore))
semaphore.acquire()
}
/**
* Runs one task on the background thread, blocking until it completes successfully or throws an
* exception.
*/
override fun runOneTaskSync() {
val semaphore = TimeOutSemaphore(0)
messageQueue.add(Message(MessageType.DRAIN_ONE, semaphore))
semaphore.acquire()
}
/**
* Runs through all tasks on the background thread, blocking until it completes successfully or
* throws an exception.
*/
override fun runToEndOfTasksSync() {
val semaphore = TimeOutSemaphore(0)
messageQueue.add(Message(MessageType.DRAIN_ALL, semaphore))
semaphore.acquire()
}
override fun runToEndOfTasksAsync(): TimeOutSemaphore? {
val semaphore = TimeOutSemaphore(0)
messageQueue.add(Message(MessageType.DRAIN_ALL, semaphore))
return semaphore
}
}
enum class MessageType {
DRAIN_ONE,
DRAIN_ALL,
QUIT
}
class Message constructor(val messageType: MessageType, val semaphore: TimeOutSemaphore)
@SuppressWarnings("CatchGeneralException")
private class LayoutLooperThread(layoutLooper: ShadowLooper, messages: BlockingQueue<Message>) :
Thread(
Runnable {
var keepGoing = true
while (keepGoing) {
val message: Message =
try {
messages.take()
} catch (e: InterruptedException) {
throw RuntimeException(e)
}
try {
when (message.messageType) {
MessageType.DRAIN_ONE -> {
layoutLooper.runOneTask()
message.semaphore.release()
}
MessageType.DRAIN_ALL -> {
layoutLooper.runToEndOfTasks()
message.semaphore.release()
}
MessageType.QUIT -> {
keepGoing = false
message.semaphore.release()
}
}
} catch (e: Exception) {
message.semaphore.setException(e)
message.semaphore.release()
}
}
})
| litho-testing/src/main/java/com/facebook/litho/testing/ThreadLooperController.kt | 2352701997 |
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.kotlin.bordereffects
object NiceColor {
val RED: Int
get() = 0xffee4035.toInt()
val ORANGE: Int
get() = 0xfff37736.toInt()
val YELLOW: Int
get() = 0xfffdf498.toInt()
val GREEN: Int
get() = 0xff7bc043.toInt()
val BLUE: Int
get() = 0xff0392cf.toInt()
val MAGENTA: Int
get() = 0xffba02cf.toInt()
}
| sample/src/main/java/com/facebook/samples/litho/kotlin/bordereffects/NiceColor.kt | 2687005260 |
package shark
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
import shark.FilteringLeakingObjectFinder.LeakingObjectFilter
import shark.HeapObject.HeapInstance
import shark.ReferencePattern.InstanceFieldPattern
import shark.ReferencePattern.StaticFieldPattern
import shark.ValueHolder.ReferenceHolder
import java.io.File
class LeakTraceRenderingTest {
@get:Rule
var testFolder = TemporaryFolder()
private lateinit var hprofFile: File
@Before
fun setUp() {
hprofFile = testFolder.newFile("temp.hprof")
}
@Test fun rendersSimplePath() {
hprofFile.dump {
"GcRoot" clazz {
staticField["leak"] = "Leaking" watchedInstance {}
}
}
val analysis = hprofFile.checkForLeaks<HeapAnalysisSuccess>()
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersDeobfuscatedSimplePath() {
hprofFile.dump {
"a" clazz {
staticField["b.c"] = "Leaking" watchedInstance {}
}
}
val proguardMappingText = """
GcRoot -> a:
type leak -> b.c
""".trimIndent()
val reader = ProguardMappingReader(proguardMappingText.byteInputStream(Charsets.UTF_8))
val analysis = hprofFile.checkForLeaks<HeapAnalysisSuccess>(
proguardMapping = reader.readProguardMapping()
)
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersLeakingWithReason() {
hprofFile.dump {
"GcRoot" clazz {
staticField["instanceA"] = "ClassA" instance {
field["instanceB"] = "ClassB" instance {
field["leak"] = "Leaking" watchedInstance {}
}
}
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>(
objectInspectors = listOf(object : ObjectInspector {
override fun inspect(
reporter: ObjectReporter
) {
reporter.whenInstanceOf("ClassB") {
leakingReasons += "because reasons"
}
}
}), leakingObjectFinder = FilteringLeakingObjectFinder(listOf(LeakingObjectFilter { heapObject ->
heapObject is HeapInstance && heapObject instanceOf "ClassB"
}))
)
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.instanceA
│ ~~~~~~~~~
├─ ClassA instance
│ Leaking: UNKNOWN
│ ↓ ClassA.instanceB
│ ~~~~~~~~~
╰→ ClassB instance
Leaking: YES (because reasons)
"""
}
@Test fun rendersLabelsOnAllNodes() {
hprofFile.dump {
"GcRoot" clazz {
staticField["leak"] = "Leaking" watchedInstance {}
}
}
val analysis = hprofFile.checkForLeaks<HeapAnalysisSuccess>(
objectInspectors = listOf(object : ObjectInspector {
override fun inspect(
reporter: ObjectReporter
) {
reporter.labels += "¯\\_(ツ)_/¯"
}
})
)
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ¯\_(ツ)_/¯
│ ↓ static GcRoot.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
¯\_(ツ)_/¯
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersExclusion() {
hprofFile.dump {
"GcRoot" clazz {
staticField["instanceA"] = "ClassA" instance {
field["leak"] = "Leaking" watchedInstance {}
}
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>(
referenceMatchers = listOf(
LibraryLeakReferenceMatcher(pattern = InstanceFieldPattern("ClassA", "leak"))
)
)
analysis rendersLibraryLeak """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.instanceA
│ ~~~~~~~~~
├─ ClassA instance
│ Leaking: UNKNOWN
│ Library leak match: instance field ClassA#leak
│ ↓ ClassA.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersRootExclusion() {
hprofFile.dump {
"GcRoot" clazz {
staticField["leak"] = "Leaking" watchedInstance {}
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>(
referenceMatchers = listOf(
LibraryLeakReferenceMatcher(pattern = StaticFieldPattern("GcRoot", "leak"))
)
)
analysis rendersLibraryLeak """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ Library leak match: static field GcRoot#leak
│ ↓ static GcRoot.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersArray() {
hprofFile.dump {
"GcRoot" clazz {
staticField["array"] = objectArray("Leaking" watchedInstance {})
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>()
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.array
│ ~~~~~
├─ java.lang.Object[] array
│ Leaking: UNKNOWN
│ ↓ Object[0]
│ ~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun rendersThread() {
hprofFile.writeJavaLocalLeak(threadClass = "MyThread", threadName = "kroutine")
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>(
objectInspectors = ObjectInspectors.jdkDefaults
)
analysis renders """
┬───
│ GC Root: Thread object
│
├─ MyThread instance
│ Leaking: UNKNOWN
│ Thread name: 'kroutine'
│ ↓ MyThread<Java Local>
│ ~~~~~~~~~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
@Test fun renderFieldFromSuperClass() {
hprofFile.dump {
val leakingInstance = "Leaking" watchedInstance {}
val parentClassId =
clazz("com.ParentClass", fields = listOf("leak" to ReferenceHolder::class))
val childClassId = clazz("com.ChildClass", superclassId = parentClassId)
"GcRoot" clazz {
staticField["child"] = instance(childClassId, listOf(leakingInstance))
}
}
val analysis =
hprofFile.checkForLeaks<HeapAnalysisSuccess>()
analysis renders """
┬───
│ GC Root: System class
│
├─ GcRoot class
│ Leaking: UNKNOWN
│ ↓ static GcRoot.child
│ ~~~~~
├─ com.ChildClass instance
│ Leaking: UNKNOWN
│ ↓ ParentClass.leak
│ ~~~~
╰→ Leaking instance
Leaking: YES (ObjectWatcher was watching this because its lifecycle has ended)
key = 39efcc1a-67bf-2040-e7ab-3fc9f94731dc
watchDurationMillis = 25000
retainedDurationMillis = 10000
"""
}
private infix fun HeapAnalysisSuccess.renders(expectedString: String) {
assertThat(applicationLeaks[0].leakTraces.first().toString()).isEqualTo(
expectedString.trimIndent()
)
}
private infix fun HeapAnalysisSuccess.rendersLibraryLeak(expectedString: String) {
assertThat(libraryLeaks[0].leakTraces.first().toString()).isEqualTo(
expectedString.trimIndent()
)
}
}
| shark/src/test/java/shark/LeakTraceRenderingTest.kt | 453751266 |
package karballo.evaluation
import karballo.Board
import karballo.Color
import karballo.bitboard.AttacksInfo
import karballo.bitboard.BitboardAttacks
import karballo.util.StringUtils
abstract class Evaluator {
var bbAttacks: BitboardAttacks = BitboardAttacks.getInstance()
/**
* Board evaluator
*/
abstract fun evaluate(b: Board, ai: AttacksInfo): Int
fun formatOE(value: Int): String {
return StringUtils.padLeft(o(value).toString(), 8) + " " + StringUtils.padLeft(e(value).toString(), 8)
}
companion object {
val W = Color.W
val B = Color.B
val NO_VALUE = Short.MAX_VALUE.toInt()
val MATE = 30000
val KNOWN_WIN = 20000
val DRAW = 0
val PAWN_OPENING = 80
val PAWN = 100
val KNIGHT = 325
val BISHOP = 325
val ROOK = 500
val QUEEN = 975
val PIECE_VALUES = intArrayOf(0, PAWN, KNIGHT, BISHOP, ROOK, QUEEN)
val PIECE_VALUES_OE = intArrayOf(0, oe(PAWN_OPENING, PAWN), oe(KNIGHT, KNIGHT), oe(BISHOP, BISHOP), oe(ROOK, ROOK), oe(QUEEN, QUEEN))
val BISHOP_PAIR = oe(50, 50) // Bonus by having two bishops in different colors
val GAME_PHASE_MIDGAME = 1000
val GAME_PHASE_ENDGAME = 0
val NON_PAWN_MATERIAL_ENDGAME_MIN = QUEEN + ROOK
val NON_PAWN_MATERIAL_MIDGAME_MAX = 3 * KNIGHT + 3 * BISHOP + 4 * ROOK + 2 * QUEEN
/**
* Merges two short Opening - Ending values in one int
*/
fun oe(opening: Int, endgame: Int): Int {
return (opening shl 16) + endgame
}
/**
* Get the "Opening" part
*/
fun o(oe: Int): Int {
return oe + 0x8000 shr 16
}
/**
* Get the "Endgame" part
*/
fun e(oe: Int): Int {
return (oe and 0xffff).toShort().toInt()
}
/**
* Shift right each part by factor positions
*/
fun oeShr(factor: Int, oeValue: Int): Int {
return oe(o(oeValue) shr factor, e(oeValue) shr factor)
}
}
} | karballo-common/src/main/kotlin/karballo/evaluation/Evaluator.kt | 820129419 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.testGuiFramework.fixtures
import com.intellij.ide.actions.ViewNavigationBarAction
import com.intellij.openapi.actionSystem.ActionManager
import org.fest.swing.core.Robot
import javax.swing.JPanel
class NavigationBarFixture(private val myRobot: Robot, val myPanel: JPanel, private val myIdeFrame: IdeFrameFixture) :
ComponentFixture<NavigationBarFixture, JPanel>(NavigationBarFixture::class.java, myRobot, myPanel) {
private val VIEW_NAV_BAR_ACTION = "ViewNavigationBar"
fun show() {
if (!isShowing()) myIdeFrame.invokeMainMenu(VIEW_NAV_BAR_ACTION)
}
fun hide() {
if (isShowing()) myIdeFrame.invokeMainMenu(VIEW_NAV_BAR_ACTION)
}
fun isShowing(): Boolean {
val action = ActionManager.getInstance().getAction(VIEW_NAV_BAR_ACTION) as ViewNavigationBarAction
return action.isSelected(null)
}
companion object {
fun createNavigationBarFixture(robot: Robot, ideFrame: IdeFrameFixture): NavigationBarFixture {
val navBarPanel = robot.finder()
.find(ideFrame.target()) { component -> component is JPanel && isNavBar(component) } as JPanel
return NavigationBarFixture(robot, navBarPanel, ideFrame)
}
fun isNavBar(navBarPanel: JPanel): Boolean = navBarPanel.name == "navbar"
}
} | platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/NavigationBarFixture.kt | 4156479910 |
package net.yslibrary.monotweety.logout
import android.app.IntentService
import android.content.Context
import android.content.Intent
import net.yslibrary.monotweety.App
import net.yslibrary.monotweety.activity.main.MainActivity
import net.yslibrary.monotweety.login.domain.DoLogout
import javax.inject.Inject
import kotlin.properties.Delegates
class LogoutService : IntentService(NAME) {
@set:[Inject]
var doLogout by Delegates.notNull<DoLogout>()
val component: LogoutComponent by lazy {
DaggerLogoutComponent.builder()
.userComponent(App.userComponent(this))
.build()
}
override fun onCreate() {
super.onCreate()
component.inject(this)
}
override fun onHandleIntent(intent: Intent?) {
doLogout.execute().blockingAwait()
App.clearUserComponent(this)
val activityIntent = MainActivity.callingIntent(this)
activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(activityIntent)
}
companion object {
const val NAME = "LogoutService"
fun callingIntent(context: Context): Intent {
return Intent(context, LogoutService::class.java)
}
}
}
| app/src/main/java/net/yslibrary/monotweety/logout/LogoutService.kt | 2643654909 |
/**
* DO NOT EDIT THIS FILE.
*
* This source code was autogenerated from source code within the `app/src/gms` directory
* and is not intended for modifications. If any edits should be made, please do so in the
* corresponding file under the `app/src/gms` directory.
*/
/*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.kotlindemos
import android.os.Bundle
import android.os.Handler
import android.os.SystemClock
import android.view.View
import android.view.animation.OvershootInterpolator
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.google.android.libraries.maps.CameraUpdateFactory
import com.google.android.libraries.maps.GoogleMap
import com.google.android.libraries.maps.SupportMapFragment
import com.google.android.libraries.maps.model.LatLng
import com.google.android.libraries.maps.model.LatLngBounds
import com.google.android.libraries.maps.model.MarkerOptions
/**
* This shows how to use setPadding to allow overlays that obscure part of the map without
* obscuring the map UI or copyright notices.
*/
class VisibleRegionDemoActivity :
AppCompatActivity(),
OnMapAndViewReadyListener.OnGlobalLayoutAndMapReadyListener {
private val operaHouseLatLng = LatLng(-33.85704, 151.21522)
private val sfoLatLng = LatLng(37.614631, -122.385153)
private val australiaBounds = LatLngBounds(LatLng(-44.0, 113.0),
LatLng(-10.0, 154.0))
private lateinit var map: GoogleMap
private lateinit var messageView: TextView
private lateinit var normalButton: Button
private lateinit var morePaddedButton: Button
private lateinit var operaHouseButton: Button
private lateinit var sfoButton: Button
private lateinit var australiaButton: Button
/** Keep track of current values for padding, so we can animate from them. */
private var currentLeft = 150
private var currentTop = 0
private var currentRight = 0
private var currentBottom = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.visible_region_demo)
messageView = findViewById(R.id.message_text)
val mapFragment = supportFragmentManager.findFragmentById(R.id.map) as SupportMapFragment
OnMapAndViewReadyListener(mapFragment, this)
normalButton = findViewById(R.id.vr_normal_button)
morePaddedButton = findViewById(R.id.vr_more_padded_button)
operaHouseButton = findViewById(R.id.vr_soh_button)
sfoButton = findViewById(R.id.vr_sfo_button)
australiaButton = findViewById(R.id.vr_aus_button)
}
override fun onMapReady(googleMap: GoogleMap?) {
// exit early if the map was not initialised properly
map = googleMap ?: return
map.apply{
// Set padding for the current camera view
setPadding(currentLeft, currentTop, currentRight, currentBottom)
// Move to a place with indoor (sfoLatLng airport).
moveCamera(CameraUpdateFactory.newLatLngZoom(sfoLatLng, 18f))
// Add a marker to the Opera House.
addMarker(MarkerOptions().position(operaHouseLatLng).title("Sydney Opera House"))
// Add a camera idle listener that displays the current camera position in a TextView
setOnCameraIdleListener {
messageView.text = getString(R.string.camera_change_message,
[email protected])
}
}
normalButton.setOnClickListener {
animatePadding(150, 0, 0, 0)
}
// listener for when the 'more' padding button is clicked
// increases the amount of padding along the right and bottom of the map
morePaddedButton.setOnClickListener {
// get the view that contains the map
val mapView: View? = supportFragmentManager.findFragmentById(R.id.map)?.view
animatePadding(150, 0, (mapView?.width ?: 0) / 3,
(mapView?.height ?: 0)/ 4)
}
operaHouseButton.setOnClickListener {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(operaHouseLatLng, 16f))
}
sfoButton.setOnClickListener {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(sfoLatLng, 18f))
}
australiaButton.setOnClickListener {
map.moveCamera(CameraUpdateFactory.newLatLngBounds(australiaBounds, 0))
}
}
// this function smoothly changes the amount of padding over a period of time
private fun animatePadding(toLeft: Int, toTop: Int, toRight: Int, toBottom: Int) {
val handler = Handler()
val start = SystemClock.uptimeMillis()
val duration: Long = 1000
val interpolator = OvershootInterpolator()
val startLeft: Int = currentLeft
val startTop: Int = currentTop
val startRight: Int = currentRight
val startBottom: Int = currentBottom
currentLeft = toLeft
currentTop = toTop
currentRight = toRight
currentBottom = toBottom
handler.post(object : Runnable {
override fun run() {
val elapsed = SystemClock.uptimeMillis() - start
val t: Float = interpolator.getInterpolation(elapsed.toFloat() / duration)
val leftDiff = ((toLeft - startLeft) * t).toInt()
val topDiff = ((toTop - startTop) * t).toInt()
val rightDiff = ((toRight - startRight) * t).toInt()
val bottomDiff = ((toBottom - startBottom) * t).toInt()
val left = startLeft + leftDiff
val top = startTop + topDiff
val right = startRight + rightDiff
val bottom = startBottom + bottomDiff
map.setPadding(left, top, right, bottom)
// Post again 16ms later.
if (elapsed < duration) { handler.postDelayed(this, 16) }
}
})
}
}
| ApiDemos/kotlin/app/src/v3/java/com/example/kotlindemos/VisibleRegionDemoActivity.kt | 2691538630 |
package com.hosshan.android.salad.component.scene.repository
import android.content.Context
import android.content.Intent
import com.hosshan.android.salad.component.scene.SceneFragmentView
import com.hosshan.android.salad.component.scene.Presenter
import com.hosshan.android.salad.repository.github.entity.Repository
/**
* RepositoryConstants
*/
fun RepositoryActivity.Companion.createIntent(context: Context): Intent =
Intent(context, RepositoryActivity::class.java)
fun RepositoryFragment.Companion.createInstance(): RepositoryFragment =
RepositoryFragment()
internal interface RepositoryPresenter : Presenter<RepositoryView> {
}
internal interface RepositoryView : SceneFragmentView {
fun onCreateRepository(repository: Repository)
}
| app/src/main/kotlin/com/hosshan/android/salad/component/scene/repository/RepositoryConstants.kt | 3955847375 |
package com.bachhuberdesign.deckbuildergwent.inject.module
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
/**
* @author Eric Bachhuber
* @version 1.0.0
* @since 1.0.0
*/
@Module
class NetworkModule {
@Provides
@Singleton
fun provideGson(): Gson {
val gsonBuilder = GsonBuilder()
return gsonBuilder.create()
}
} | app/src/main/java/com/bachhuberdesign/deckbuildergwent/inject/module/NetworkModule.kt | 2785780386 |
package org.jetbrains
import org.gradle.api.DefaultTask
import org.gradle.api.GradleException
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.TaskAction
import org.gradle.kotlin.dsl.findByType
open class ValidatePublications : DefaultTask() {
init {
group = "verification"
project.tasks.named("check") {
dependsOn(this@ValidatePublications)
}
}
@TaskAction
fun validatePublicationConfiguration() {
project.subprojects.forEach { subProject ->
val publishing = subProject.extensions.findByType<PublishingExtension>() ?: return@forEach
publishing.publications
.filterIsInstance<MavenPublication>()
.filter { it.version == project.dokkaVersion }
.forEach { _ ->
checkProjectDependenciesArePublished(subProject)
subProject.assertPublicationVersion()
}
}
}
private fun checkProjectDependenciesArePublished(project: Project) {
val implementationDependencies = project.findDependenciesByName("implementation")
val apiDependencies = project.findDependenciesByName("api")
val allDependencies = implementationDependencies + apiDependencies
allDependencies
.filterIsInstance<ProjectDependency>()
.forEach { projectDependency ->
val publishing = projectDependency.dependencyProject.extensions.findByType<PublishingExtension>()
?: throw UnpublishedProjectDependencyException(
project = project, dependencyProject = projectDependency.dependencyProject
)
val isPublished = publishing.publications.filterIsInstance<MavenPublication>()
.any { it.version == project.dokkaVersion }
if (!isPublished) {
throw UnpublishedProjectDependencyException(project, projectDependency.dependencyProject)
}
}
}
private fun Project.findDependenciesByName(name: String): Set<Dependency> {
return configurations.findByName(name)?.allDependencies.orEmpty()
}
private fun Project.assertPublicationVersion() {
val versionTypeMatchesPublicationChannels = publicationChannels.all { publicationChannel ->
publicationChannel.acceptedDokkaVersionTypes.any { acceptedVersionType ->
acceptedVersionType == dokkaVersionType
}
}
if (!versionTypeMatchesPublicationChannels) {
throw AssertionError("Wrong version $dokkaVersion for configured publication channels $publicationChannels")
}
}
private class UnpublishedProjectDependencyException(
project: Project, dependencyProject: Project
): GradleException(
"Published project ${project.path} cannot depend on unpublished project ${dependencyProject.path}"
)
}
| buildSrc/src/main/kotlin/org/jetbrains/ValidatePublications.kt | 3903661938 |
package ii_collections
fun example9() {
val result = listOf(1, 2, 3, 4).fold(1, { partResult, element -> element * partResult })
result == 24
}
// The same as
fun whatFoldDoes(): Int {
var result = 1
listOf(1, 2, 3, 4).forEach { element -> result = element * result}
return result
}
fun Shop.getSetOfProductsOrderedByEveryCustomer(): Set<Product> {
// Return the set of products ordered by every customer
return customers.fold(allOrderedProducts, {
orderedByAll, customer -> orderedByAll.intersect(customer.orderedProducts)
})
}
| src/ii_collections/n22Fold.kt | 2449969135 |
/*
* Copyright 2021 Allan Wang
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.pitchedapps.frost.activities
import com.pitchedapps.frost.helper.activityRule
import dagger.hilt.android.testing.HiltAndroidRule
import dagger.hilt.android.testing.HiltAndroidTest
import org.junit.Rule
import org.junit.Test
@HiltAndroidTest
class LoginActivityTest {
@get:Rule(order = 0) val hildAndroidRule = HiltAndroidRule(this)
@get:Rule(order = 1) val activityRule = activityRule<LoginActivity>()
@Test
fun initializesSuccessfully() {
activityRule.scenario.use {
it.onActivity {
// Verify no crash
}
}
}
}
| app/src/androidTest/kotlin/com/pitchedapps/frost/activities/LoginActivityTest.kt | 781070940 |
/*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.article_viewer.article.list.usecase
import android.content.Context
import android.net.Uri
import io.mockk.MockKAnnotations
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.InjectMockKs
import io.mockk.impl.annotations.MockK
import io.mockk.just
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.article_viewer.article.list.ArticleListFragmentViewModel
import jp.toastkid.article_viewer.zip.ZipLoaderService
import org.junit.After
import org.junit.Before
import org.junit.Test
class UpdateUseCaseTest {
@InjectMockKs
private lateinit var updateUseCase: UpdateUseCase
@MockK
private lateinit var viewModel: ArticleListFragmentViewModel
@MockK
private lateinit var contextProvider: () -> Context?
@MockK
private lateinit var uri: Uri
@Before
fun setUp() {
MockKAnnotations.init(this)
every { viewModel.showProgress() }.just(Runs)
every { contextProvider.invoke() }.returns(mockk())
mockkObject(ZipLoaderService)
every { ZipLoaderService.start(any(), any()) }.just(Runs)
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testInvokeIfNeed() {
updateUseCase.invokeIfNeed(uri)
verify(exactly = 1) { viewModel.showProgress() }
verify(exactly = 1) { contextProvider.invoke() }
verify(exactly = 1) { ZipLoaderService.start(any(), any()) }
}
@Test
fun testInvokeIfNotNeed() {
updateUseCase.invokeIfNeed(null)
verify(exactly = 0) { viewModel.showProgress() }
verify(exactly = 0) { contextProvider.invoke() }
verify(exactly = 0) { ZipLoaderService.start(any(), any()) }
}
@Test
fun testInvokeIfNotNeedContextIsNull() {
every { contextProvider.invoke() }.returns(null)
updateUseCase.invokeIfNeed(uri)
verify(exactly = 1) { viewModel.showProgress() }
verify(exactly = 1) { contextProvider.invoke() }
verify(exactly = 0) { ZipLoaderService.start(any(), any()) }
}
} | article/src/test/java/jp/toastkid/article_viewer/article/list/usecase/UpdateUseCaseTest.kt | 256893927 |
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.vladsch.md.nav.actions.styling
import com.intellij.openapi.editor.LogicalPosition
import com.intellij.openapi.util.Condition
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.vladsch.md.nav.actions.handlers.util.CaretContextInfo
import com.vladsch.md.nav.actions.styling.util.DisabledConditionBuilder
import com.vladsch.md.nav.psi.element.MdBlockQuote
import com.vladsch.md.nav.psi.element.MdHeaderElement
import com.vladsch.md.nav.psi.util.BlockQuotePrefix
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.psi.util.MdTokenSets
import com.vladsch.md.nav.psi.util.MdTypes
import com.vladsch.plugin.util.psi.isTypeOf
import com.vladsch.plugin.util.toInt
import kotlin.math.max
class BlockQuoteAddAction : BlockQuoteItemAction() {
override fun getElementCondition(haveSelection: Boolean): Condition<PsiElement> {
//noinspection ReturnOfInnerClass
return Condition { element ->
element.node != null /*&& TokenTypeSets.BLOCK_ELEMENTS.contains(element.node.elementType)*/ && (
haveSelection || (
(element.node.elementType != MdTypes.PARAGRAPH_BLOCK || !MdPsiImplUtil.isFirstIndentedBlock(element, false))
&& !element.isTypeOf(MdTokenSets.LIST_BLOCK_ITEM_ELEMENT_TYPES)
)
)
}
}
override fun canPerformAction(element: PsiElement?, conditionBuilder: DisabledConditionBuilder?): Boolean {
var useElement = element
while (useElement?.node != null && !useElement.isTypeOf(MdTokenSets.BLOCK_ELEMENT_SET)) useElement = useElement.parent
val enabled = useElement?.node != null && useElement.isTypeOf(MdTokenSets.BLOCK_ELEMENT_SET)
conditionBuilder?.and(enabled, if (useElement?.node != null) "Not block element at caret" else "No element at caret")
return enabled
}
override fun performAction(element: PsiElement, editContext: CaretContextInfo, adjustCaret: Boolean) {
if (canPerformAction(element, null)) {
var useElement: PsiElement? = element
while (useElement?.node != null
&& !useElement.isTypeOf(MdTokenSets.BLOCK_ELEMENT_SET)) {
useElement = useElement.parent
}
if (useElement is PsiFile) return
// collapse to the innermost block quote that is a single child
while (useElement != null && useElement.children.size == 1
&& useElement is MdBlockQuote && useElement.lastChild is MdBlockQuote) {
useElement = useElement.lastChild
}
if (useElement == null) return
// append a quote level
val parentPrefixes = MdPsiImplUtil.getBlockPrefixes(useElement.parent, null, editContext)
val elementPrefixes = MdPsiImplUtil.getBlockPrefixes(useElement, parentPrefixes, editContext)
val blockQuotePrefix = BlockQuotePrefix.create(true, ">", ">")
val prefixes =
if (parentPrefixes.last() == elementPrefixes.last()) {
// append block quote at end of prefixes
parentPrefixes.append(blockQuotePrefix).finalizePrefixes(editContext)
} else {
// insert before the elementPrefix
parentPrefixes.append(blockQuotePrefix).append(elementPrefixes.last()).finalizePrefixes(editContext)
}
// only include tail blank line if it is part of the block quote already in existence
val includeTailBlankLine = useElement.node.elementType === MdTypes.BLOCK_QUOTE
val wrappingLines = editContext.lineAppendable
if (useElement.node.elementType == MdTypes.VERBATIM) {
wrappingLines.append(useElement.text)
wrappingLines.removeExtraBlankLines(1, 0)
MdPsiImplUtil.adjustLinePrefix(useElement, wrappingLines, editContext)
} else {
if (useElement is MdHeaderElement) {
wrappingLines.append(useElement.text)
MdPsiImplUtil.adjustLinePrefix(useElement, wrappingLines, editContext)
} else {
for (child in useElement.children) {
val textLines = MdPsiImplUtil.linesForWrapping(child, false, true, true, editContext)
wrappingLines.append(textLines, true)
}
}
}
// Fix: #320
if (wrappingLines.lineCount == 0) {
// no text just prefixes
wrappingLines.append(parentPrefixes.childPrefix)
}
wrappingLines.line()
val isFirstIndentedChild = MdPsiImplUtil.isFirstIndentedBlock(element, false)
val prefixedLines = wrappingLines.copyAppendable()
MdPsiImplUtil.addLinePrefix(prefixedLines, prefixes, isFirstIndentedChild, true)
var caretLine = editContext.caretLine - (editContext.offsetLineNumber(editContext.preEditOffset(useElement.node.startOffset)) ?: 0)
val postEditNodeStart = editContext.postEditNodeStart(useElement.node)
val startOffset = editContext.offsetLineStart(postEditNodeStart) ?: return
var endOffset = editContext.postEditNodeEnd(useElement.node)
if (!includeTailBlankLine) {
val lastLeafChild = MdPsiImplUtil.lastLeafChild(useElement.node)
if (lastLeafChild.elementType === MdTypes.BLANK_LINE) {
// remove the last line
endOffset = editContext.postEditNodeStart(lastLeafChild)
}
}
// FIX: this needs to take unterminated lines into account
if (caretLine >= wrappingLines.lineCountWithPending) {
caretLine = max(0, wrappingLines.lineCountWithPending - 1)
}
val originalPrefixLen = wrappingLines[caretLine].length - wrappingLines[caretLine].length
val finalPrefixLen = prefixedLines[caretLine].length - wrappingLines[caretLine].length
val logPos = editContext.editor.caretModel.primaryCaret.logicalPosition
val prefixedText = prefixedLines.toSequence(editContext.styleSettings.KEEP_BLANK_LINES, true)
editContext.document.replaceString(startOffset, endOffset, prefixedText)
if (adjustCaret) {
editContext.editor.caretModel.primaryCaret.moveToLogicalPosition(LogicalPosition(logPos.line, logPos.column + if (logPos.column >= originalPrefixLen) finalPrefixLen - originalPrefixLen else 0, logPos.leansForward))
if (editContext.editor.caretModel.primaryCaret.hasSelection() || useElement.isTypeOf(MdTokenSets.LIST_BLOCK_ELEMENT_TYPES)) {
val spaceDelta = (editContext.charSequence.safeCharAt(postEditNodeStart + 1) == ' ').toInt()
editContext.editor.caretModel.primaryCaret.setSelection(postEditNodeStart + 1 + spaceDelta, postEditNodeStart + prefixedText.length - (postEditNodeStart - startOffset))
}
}
}
}
}
| src/main/java/com/vladsch/md/nav/actions/styling/BlockQuoteAddAction.kt | 2514590212 |
package io.quarkus.it.panache.reactive.kotlin
import io.quarkus.runtime.annotations.RegisterForReflection
@RegisterForReflection
data class PersonName(val uniqueName: String?, val name: String?)
| integration-tests/hibernate-reactive-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/reactive/kotlin/PersonName.kt | 2329121139 |
package io.quarkus.hibernate.orm.panache.kotlin.runtime
import io.quarkus.gizmo.Gizmo
import io.quarkus.hibernate.orm.panache.kotlin.PanacheCompanionBase
import io.quarkus.hibernate.orm.panache.kotlin.PanacheEntityBase
import io.quarkus.hibernate.orm.panache.kotlin.PanacheQuery
import io.quarkus.hibernate.orm.panache.kotlin.PanacheRepository
import io.quarkus.panache.common.deployment.ByteCodeType
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassReader.SKIP_CODE
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import kotlin.reflect.KClass
import io.quarkus.hibernate.orm.panache.PanacheEntityBase as JavaPanacheEntityBase
import io.quarkus.hibernate.orm.panache.PanacheQuery as JavaPanacheQuery
import io.quarkus.hibernate.orm.panache.PanacheRepository as JavaPanacheRepository
val OBJECT = ByteCodeType(Object::class.java)
class TestAnalogs {
@Test
fun testPanacheQuery() {
compare(map(JavaPanacheQuery::class), map(PanacheQuery::class))
}
@Test
fun testPanacheRepository() {
compare(map(JavaPanacheRepository::class), map(PanacheRepository::class))
}
@Test
fun testPanacheRepositoryBase() {
compare(map(JavaPanacheRepository::class), map(PanacheRepository::class), listOf("findByIdOptional"))
}
@Test
fun testPanacheEntityBase() {
val javaMethods = map(JavaPanacheEntityBase::class).methods
val kotlinMethods = map(PanacheEntityBase::class).methods
val companionMethods = map(
PanacheCompanionBase::class,
ByteCodeType(PanacheEntityBase::class.java)
).methods
val implemented = mutableListOf<Method>()
javaMethods
.forEach {
if (!it.isStatic()) {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
} else {
if (it in companionMethods) {
companionMethods -= it
implemented += it
}
}
}
javaMethods.removeIf {
it.name.endsWith("Optional") || it in implemented
}
// methods("javaMethods", javaMethods)
// methods("kotlinMethods", kotlinMethods)
// methods("companionMethods", companionMethods)
assertTrue(javaMethods.isEmpty(), "New methods not implemented: \n${javaMethods.byLine()}")
assertTrue(kotlinMethods.isEmpty(), "Old methods not removed: \n${kotlinMethods.byLine()}")
assertTrue(companionMethods.isEmpty(), "Old methods not removed: \n${companionMethods.byLine()}")
}
private fun map(type: KClass<*>, erasedType: ByteCodeType? = null): AnalogVisitor {
return AnalogVisitor(erasedType).also { node ->
ClassReader(type.bytes()).accept(node, SKIP_CODE)
}
}
private fun KClass<*>.bytes() =
java.classLoader.getResourceAsStream(qualifiedName.toString().replace(".", "/") + ".class")
private fun compare(javaClass: AnalogVisitor, kotlinClass: AnalogVisitor, allowList: List<String> = listOf()) {
val javaMethods = javaClass.methods
val kotlinMethods = kotlinClass.methods
val implemented = mutableListOf<Method>()
javaMethods
.forEach {
if (it in kotlinMethods) {
kotlinMethods -= it
implemented += it
}
}
javaMethods.removeIf {
it.name.endsWith("Optional") ||
it.name in allowList ||
it in implemented
}
// methods("javaMethods", javaMethods)
// methods("kotlinMethods", kotlinMethods)
assertTrue(javaMethods.isEmpty(), "New methods not implemented: \n${javaMethods.byLine()}")
assertTrue(kotlinMethods.isEmpty(), "Old methods not removed: ${kotlinMethods.byLine()}")
}
@Suppress("unused")
private fun methods(label: String, methods: List<Method>) {
println("$label: ")
methods.toSortedSet(compareBy { it.toString() })
.forEach {
println(it)
}
}
}
private fun <E> List<E>.byLine(): String {
val map = map { it.toString() }
return map
.joinToString("\n")
}
class AnalogVisitor(val erasedType: ByteCodeType? = null) : ClassVisitor(Gizmo.ASM_API_VERSION) {
val methods = mutableListOf<Method>()
override fun visitMethod(
access: Int,
name: String,
descriptor: String,
signature: String?,
exceptions: Array<out String>?
): MethodVisitor? {
if (name != "<init>") {
val type = descriptor.substringAfterLast(")").trim()
var parameters = descriptor.substring(
descriptor.indexOf("("),
descriptor.lastIndexOf(")") + 1
)
erasedType?.let { type ->
parameters = parameters.replace(type.descriptor(), OBJECT.descriptor())
}
methods += Method(access, name, type, parameters)
}
return super.visitMethod(access, name, descriptor, signature, exceptions)
}
}
class Method(val access: Int, val name: String, val type: String, val parameters: String) {
fun isStatic() = access.matches(Opcodes.ACC_STATIC)
override fun toString(): String {
return (if (isStatic()) "static " else "") + "fun ${name}$parameters" +
(if (type.isNotBlank()) ": $type" else "") // +
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Method) return false
if (name != other.name) return false
if (parameters != other.parameters) return false
return true
}
override fun hashCode(): Int {
var result = name.hashCode()
result = 31 * result + type.hashCode()
result = 31 * result + parameters.hashCode()
return result
}
}
fun Int.matches(mask: Int) = (this and mask) == mask
fun Int.accDecode(): List<String> {
val decode: MutableList<String> = ArrayList()
val values: MutableMap<String, Int> = LinkedHashMap()
try {
for (f in Opcodes::class.java.declaredFields) {
if (f.name.startsWith("ACC_")) {
values[f.name] = f.getInt(Opcodes::class.java)
}
}
} catch (e: IllegalAccessException) {
throw RuntimeException(e.message, e)
}
for ((key, value) in values) {
if (this.matches(value)) {
decode.add(key)
}
}
return decode
}
| extensions/panache/hibernate-orm-panache-kotlin/runtime/src/test/kotlin/io/quarkus/hibernate/orm/panache/kotlin/runtime/TestAnalogs.kt | 1917035701 |
package com.booboot.vndbandroid.extensions
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView
import androidx.core.view.isVisible
import com.booboot.vndbandroid.R
import com.google.android.material.textfield.TextInputLayout
fun TextInputLayout.showCustomError(message: String, errorView: TextView) = apply {
error = " "
errorView.text = message
errorView.isVisible = true
}
fun TextInputLayout.hideCustomError(errorView: TextView) = apply {
error = null
errorView.isVisible = false
}
fun EditText.setTextChangedListener(onTextChanged: (String) -> Unit): TextWatcher {
val textWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
}
override fun beforeTextChanged(text: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) {
text?.let { onTextChanged(it.toString()) }
}
}
removeTextChangedListener()
setTag(R.id.tagTextWatcher, textWatcher)
addTextChangedListener(textWatcher)
return textWatcher
}
fun EditText.removeTextChangedListener() {
val oldTextWatcher = getTag(R.id.tagTextWatcher) as? TextWatcher
removeTextChangedListener(oldTextWatcher)
} | app/src/main/java/com/booboot/vndbandroid/extensions/EditText.kt | 2050314447 |
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* QKSMS is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.settings.about
import android.view.View
import com.jakewharton.rxbinding2.view.clicks
import com.moez.QKSMS.BuildConfig
import com.moez.QKSMS.R
import com.moez.QKSMS.common.base.QkController
import com.moez.QKSMS.common.widget.PreferenceView
import com.moez.QKSMS.injection.appComponent
import io.reactivex.Observable
import kotlinx.android.synthetic.main.about_controller.*
import javax.inject.Inject
class AboutController : QkController<AboutView, Unit, AboutPresenter>(), AboutView {
@Inject override lateinit var presenter: AboutPresenter
init {
appComponent.inject(this)
layoutRes = R.layout.about_controller
}
override fun onViewCreated() {
version.summary = BuildConfig.VERSION_NAME
}
override fun onAttach(view: View) {
super.onAttach(view)
presenter.bindIntents(this)
setTitle(R.string.about_title)
showBackButton(true)
}
override fun preferenceClicks(): Observable<PreferenceView> = (0 until preferences.childCount)
.map { index -> preferences.getChildAt(index) }
.mapNotNull { view -> view as? PreferenceView }
.map { preference -> preference.clicks().map { preference } }
.let { preferences -> Observable.merge(preferences) }
override fun render(state: Unit) {
// No special rendering required
}
} | presentation/src/main/java/com/moez/QKSMS/feature/settings/about/AboutController.kt | 1013404501 |
package eu.kanade.tachiyomi.data.database.models
class MangaCategory {
var id: Long? = null
var manga_id: Long = 0
var category_id: Int = 0
companion object {
fun create(manga: Manga, category: Category): MangaCategory {
val mc = MangaCategory()
mc.manga_id = manga.id!!
mc.category_id = category.id!!
return mc
}
}
}
| app/src/main/java/eu/kanade/tachiyomi/data/database/models/MangaCategory.kt | 1829834991 |
package com.data
data class Customer(val id: Long, val firstName: String, val lastName: String)
fun main(args: Array<String>) {
val customer = Customer(1L, "Mikolaj", "S")
println(customer)
} | relational-data-access-spring/src/main/kotlin/com/data/Customer.kt | 3881204634 |
package org.http4k.contract.openapi.v2
import org.http4k.contract.openapi.Render
import org.http4k.contract.openapi.RenderModes
import org.http4k.contract.openapi.SecurityRenderer
import org.http4k.contract.openapi.rendererFor
import org.http4k.contract.security.ApiKeySecurity
import org.http4k.contract.security.BasicAuthSecurity
import org.http4k.contract.security.ImplicitOAuthSecurity
/**
* Compose the supported Security models
*/
val OpenApi2SecurityRenderer = SecurityRenderer(ApiKeySecurity.renderer, BasicAuthSecurity.renderer, ImplicitOAuthSecurity.renderer)
val ApiKeySecurity.Companion.renderer
get() = rendererFor<ApiKeySecurity<*>> {
object : RenderModes {
override fun <NODE> full(): Render<NODE> = {
obj(it.name to obj(
"type" to string("apiKey"),
"in" to string(it.param.meta.location),
"name" to string(it.param.meta.name)
))
}
override fun <NODE> ref(): Render<NODE> = { obj(it.name to array(emptyList())) }
}
}
val BasicAuthSecurity.Companion.renderer
get() = rendererFor<BasicAuthSecurity> {
object : RenderModes {
override fun <NODE> full(): Render<NODE> = {
obj(it.name to obj(
"type" to string("basic")
))
}
override fun <NODE> ref(): Render<NODE> = { obj(it.name to array(emptyList())) }
}
}
val ImplicitOAuthSecurity.Companion.renderer
get() = rendererFor<ImplicitOAuthSecurity> {
object : RenderModes {
override fun <NODE> full(): Render<NODE> = {
obj(it.name to
obj(
listOfNotNull(
"type" to string("oauth2"),
"flow" to string("implicit"),
"authorizationUrl" to string(it.authorizationUrl.toString())
) + it.extraFields.map { it.key to string(it.value) }
)
)
}
override fun <NODE> ref(): Render<NODE> = { obj(it.name to array(emptyList())) }
}
}
| http4k-contract/src/main/kotlin/org/http4k/contract/openapi/v2/OpenApi2SecurityRenderer.kt | 1258524872 |
package org.http4k.security
data class State(val value: String)
| http4k-security/oauth/src/main/kotlin/org/http4k/security/state.kt | 1289912903 |
package org.http4k.format
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import org.http4k.events.Event
import java.lang.reflect.Type
import kotlin.reflect.KClass
/**
* Convenience class to create Moshi Adapter Factory
*/
open class SimpleMoshiAdapterFactory(vararg typesToAdapters: Pair<String, (Moshi) -> JsonAdapter<*>>) :
JsonAdapter.Factory {
private val mappings = typesToAdapters.toMap()
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi) =
mappings[Types.getRawType(type).typeName]?.let { it(moshi) }
}
/**
* Convenience function to create Moshi Adapter.
*/
inline fun <reified T : JsonAdapter<K>, reified K> adapter(noinline fn: (Moshi) -> T) = K::class.java.name to fn
/**
* Convenience function to create Moshi Adapter Factory for a simple Moshi Adapter
*/
inline fun <reified K> JsonAdapter<K>.asFactory() = SimpleMoshiAdapterFactory(K::class.java.name to { this })
/**
* Convenience function to add a custom adapter.
*/
inline fun <reified T : JsonAdapter<K>, reified K> Moshi.Builder.addTyped(fn: T): Moshi.Builder =
add(K::class.java, fn)
/**
* This adapter factory will capture ALL instances of a particular superclass/interface.
*/
abstract class IsAnInstanceOfAdapter<T : Any>(private val clazz: KClass<T>): JsonAdapter.Factory {
override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi) =
with(Types.getRawType(type)) {
when {
isA(clazz.java) -> moshi.adapter(clazz.java)
else -> null
}
}
private fun Class<*>?.isA(testCase: Class<*>): Boolean =
this?.let { testCase != this && testCase.isAssignableFrom(this) } ?: false
}
/**
* These adapters are the edge case adapters for dealing with Moshi
*/
object ThrowableAdapter : IsAnInstanceOfAdapter<Throwable>(Throwable::class)
object MapAdapter : IsAnInstanceOfAdapter<Map<*, *>>(Map::class)
object ListAdapter : IsAnInstanceOfAdapter<List<*>>(List::class)
object EventAdapter : JsonAdapter.Factory {
override fun create(p0: Type, p1: MutableSet<out Annotation>, p2: Moshi) =
if (p0.typeName == Event::class.java.typeName) p2.adapter(Any::class.java) else null
}
| http4k-format/moshi/src/main/kotlin/org/http4k/format/adapters.kt | 983860802 |
package guide.reference.clients
import org.apache.hc.client5.http.config.RequestConfig
import org.apache.hc.client5.http.cookie.StandardCookieSpec
import org.apache.hc.client5.http.impl.classic.HttpClients
import org.http4k.client.ApacheAsyncClient
import org.http4k.client.ApacheClient
import org.http4k.core.BodyMode
import org.http4k.core.Method.GET
import org.http4k.core.Request
import kotlin.concurrent.thread
fun main() {
// standard client
val client = ApacheClient()
val request = Request(GET, "http://httpbin.org/get").query("location", "John Doe")
val response = client(request)
println("SYNC")
println(response.status)
println(response.bodyString())
// streaming client
val streamingClient = ApacheClient(responseBodyMode = BodyMode.Stream)
val streamingRequest = Request(GET, "http://httpbin.org/stream/100")
println("STREAM")
println(streamingClient(streamingRequest).bodyString())
// async supporting clients can be passed a callback...
val asyncClient = ApacheAsyncClient()
asyncClient(Request(GET, "http://httpbin.org/stream/5")) {
println("ASYNC")
println(it.status)
println(it.bodyString())
}
// ... but must be closed
thread {
Thread.sleep(500)
asyncClient.close()
}
// custom configured client
val customClient = ApacheClient(
client = HttpClients.custom().setDefaultRequestConfig(
RequestConfig.custom()
.setRedirectsEnabled(false)
.setCookieSpec(StandardCookieSpec.IGNORE)
.build()
)
.build()
)
}
| src/docs/guide/reference/clients/example_http.kt | 3247020337 |
package com.otaliastudios.cameraview.demo
import android.animation.ValueAnimator
import android.content.Intent
import android.content.pm.PackageManager
import android.content.pm.PackageManager.PERMISSION_GRANTED
import android.graphics.*
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.otaliastudios.cameraview.*
import com.otaliastudios.cameraview.controls.Facing
import com.otaliastudios.cameraview.controls.Mode
import com.otaliastudios.cameraview.controls.Preview
import com.otaliastudios.cameraview.filter.Filters
import com.otaliastudios.cameraview.frame.Frame
import com.otaliastudios.cameraview.frame.FrameProcessor
import java.io.ByteArrayOutputStream
import java.io.File
import java.util.*
class CameraActivity : AppCompatActivity(), View.OnClickListener, OptionView.Callback {
companion object {
private val LOG = CameraLogger.create("DemoApp")
private const val USE_FRAME_PROCESSOR = false
private const val DECODE_BITMAP = false
}
private val camera: CameraView by lazy { findViewById(R.id.camera) }
private val controlPanel: ViewGroup by lazy { findViewById(R.id.controls) }
private var captureTime: Long = 0
private var currentFilter = 0
private val allFilters = Filters.values()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_camera)
CameraLogger.setLogLevel(CameraLogger.LEVEL_VERBOSE)
camera.setLifecycleOwner(this)
camera.addCameraListener(Listener())
if (USE_FRAME_PROCESSOR) {
camera.addFrameProcessor(object : FrameProcessor {
private var lastTime = System.currentTimeMillis()
override fun process(frame: Frame) {
val newTime = frame.time
val delay = newTime - lastTime
lastTime = newTime
LOG.v("Frame delayMillis:", delay, "FPS:", 1000 / delay)
if (DECODE_BITMAP) {
if (frame.format == ImageFormat.NV21
&& frame.dataClass == ByteArray::class.java) {
val data = frame.getData<ByteArray>()
val yuvImage = YuvImage(data,
frame.format,
frame.size.width,
frame.size.height,
null)
val jpegStream = ByteArrayOutputStream()
yuvImage.compressToJpeg(Rect(0, 0,
frame.size.width,
frame.size.height), 100, jpegStream)
val jpegByteArray = jpegStream.toByteArray()
val bitmap = BitmapFactory.decodeByteArray(jpegByteArray,
0, jpegByteArray.size)
bitmap.toString()
}
}
}
})
}
findViewById<View>(R.id.edit).setOnClickListener(this)
findViewById<View>(R.id.capturePicture).setOnClickListener(this)
findViewById<View>(R.id.capturePictureSnapshot).setOnClickListener(this)
findViewById<View>(R.id.captureVideo).setOnClickListener(this)
findViewById<View>(R.id.captureVideoSnapshot).setOnClickListener(this)
findViewById<View>(R.id.toggleCamera).setOnClickListener(this)
findViewById<View>(R.id.changeFilter).setOnClickListener(this)
val group = controlPanel.getChildAt(0) as ViewGroup
val watermark = findViewById<View>(R.id.watermark)
val options: List<Option<*>> = listOf(
// Layout
Option.Width(), Option.Height(),
// Engine and preview
Option.Mode(), Option.Engine(), Option.Preview(),
// Some controls
Option.Flash(), Option.WhiteBalance(), Option.Hdr(),
Option.PictureMetering(), Option.PictureSnapshotMetering(),
Option.PictureFormat(),
// Video recording
Option.PreviewFrameRate(), Option.VideoCodec(), Option.Audio(), Option.AudioCodec(),
// Gestures
Option.Pinch(), Option.HorizontalScroll(), Option.VerticalScroll(),
Option.Tap(), Option.LongTap(),
// Watermarks
Option.OverlayInPreview(watermark),
Option.OverlayInPictureSnapshot(watermark),
Option.OverlayInVideoSnapshot(watermark),
// Frame Processing
Option.FrameProcessingFormat(),
// Other
Option.Grid(), Option.GridColor(), Option.UseDeviceOrientation()
)
val dividers = listOf(
// Layout
false, true,
// Engine and preview
false, false, true,
// Some controls
false, false, false, false, false, true,
// Video recording
false, false, false, true,
// Gestures
false, false, false, false, true,
// Watermarks
false, false, true,
// Frame Processing
true,
// Other
false, false, true
)
for (i in options.indices) {
val view = OptionView<Any>(this)
view.setOption(options[i] as Option<Any>, this)
view.setHasDivider(dividers[i])
group.addView(view, MATCH_PARENT, WRAP_CONTENT)
}
controlPanel.viewTreeObserver.addOnGlobalLayoutListener {
BottomSheetBehavior.from(controlPanel).state = BottomSheetBehavior.STATE_HIDDEN
}
// Animate the watermark just to show we record the animation in video snapshots
val animator = ValueAnimator.ofFloat(1f, 0.8f)
animator.duration = 300
animator.repeatCount = ValueAnimator.INFINITE
animator.repeatMode = ValueAnimator.REVERSE
animator.addUpdateListener { animation ->
val scale = animation.animatedValue as Float
watermark.scaleX = scale
watermark.scaleY = scale
watermark.rotation = watermark.rotation + 2
}
animator.start()
}
private fun message(content: String, important: Boolean) {
if (important) {
LOG.w(content)
Toast.makeText(this, content, Toast.LENGTH_LONG).show()
} else {
LOG.i(content)
Toast.makeText(this, content, Toast.LENGTH_SHORT).show()
}
}
private inner class Listener : CameraListener() {
override fun onCameraOpened(options: CameraOptions) {
val group = controlPanel.getChildAt(0) as ViewGroup
for (i in 0 until group.childCount) {
val view = group.getChildAt(i) as OptionView<*>
view.onCameraOpened(camera, options)
}
}
override fun onCameraError(exception: CameraException) {
super.onCameraError(exception)
message("Got CameraException #" + exception.reason, true)
}
override fun onPictureTaken(result: PictureResult) {
super.onPictureTaken(result)
if (camera.isTakingVideo) {
message("Captured while taking video. Size=" + result.size, false)
return
}
// This can happen if picture was taken with a gesture.
val callbackTime = System.currentTimeMillis()
if (captureTime == 0L) captureTime = callbackTime - 300
LOG.w("onPictureTaken called! Launching activity. Delay:", callbackTime - captureTime)
PicturePreviewActivity.pictureResult = result
val intent = Intent(this@CameraActivity, PicturePreviewActivity::class.java)
intent.putExtra("delay", callbackTime - captureTime)
startActivity(intent)
captureTime = 0
LOG.w("onPictureTaken called! Launched activity.")
}
override fun onVideoTaken(result: VideoResult) {
super.onVideoTaken(result)
LOG.w("onVideoTaken called! Launching activity.")
VideoPreviewActivity.videoResult = result
val intent = Intent(this@CameraActivity, VideoPreviewActivity::class.java)
startActivity(intent)
LOG.w("onVideoTaken called! Launched activity.")
}
override fun onVideoRecordingStart() {
super.onVideoRecordingStart()
LOG.w("onVideoRecordingStart!")
}
override fun onVideoRecordingEnd() {
super.onVideoRecordingEnd()
message("Video taken. Processing...", false)
LOG.w("onVideoRecordingEnd!")
}
override fun onExposureCorrectionChanged(newValue: Float, bounds: FloatArray, fingers: Array<PointF>?) {
super.onExposureCorrectionChanged(newValue, bounds, fingers)
message("Exposure correction:$newValue", false)
}
override fun onZoomChanged(newValue: Float, bounds: FloatArray, fingers: Array<PointF>?) {
super.onZoomChanged(newValue, bounds, fingers)
message("Zoom:$newValue", false)
}
}
override fun onClick(view: View) {
when (view.id) {
R.id.edit -> edit()
R.id.capturePicture -> capturePicture()
R.id.capturePictureSnapshot -> capturePictureSnapshot()
R.id.captureVideo -> captureVideo()
R.id.captureVideoSnapshot -> captureVideoSnapshot()
R.id.toggleCamera -> toggleCamera()
R.id.changeFilter -> changeCurrentFilter()
}
}
override fun onBackPressed() {
val b = BottomSheetBehavior.from(controlPanel)
if (b.state != BottomSheetBehavior.STATE_HIDDEN) {
b.state = BottomSheetBehavior.STATE_HIDDEN
return
}
super.onBackPressed()
}
private fun edit() {
BottomSheetBehavior.from(controlPanel).state = BottomSheetBehavior.STATE_COLLAPSED
}
private fun capturePicture() {
if (camera.mode == Mode.VIDEO) return run {
message("Can't take HQ pictures while in VIDEO mode.", false)
}
if (camera.isTakingPicture) return
captureTime = System.currentTimeMillis()
message("Capturing picture...", false)
camera.takePicture()
}
private fun capturePictureSnapshot() {
if (camera.isTakingPicture) return
if (camera.preview != Preview.GL_SURFACE) return run {
message("Picture snapshots are only allowed with the GL_SURFACE preview.", true)
}
captureTime = System.currentTimeMillis()
message("Capturing picture snapshot...", false)
camera.takePictureSnapshot()
}
private fun captureVideo() {
if (camera.mode == Mode.PICTURE) return run {
message("Can't record HQ videos while in PICTURE mode.", false)
}
if (camera.isTakingPicture || camera.isTakingVideo) return
message("Recording for 5 seconds...", true)
camera.takeVideo(File(filesDir, "video.mp4"), 5000)
}
private fun captureVideoSnapshot() {
if (camera.isTakingVideo) return run {
message("Already taking video.", false)
}
if (camera.preview != Preview.GL_SURFACE) return run {
message("Video snapshots are only allowed with the GL_SURFACE preview.", true)
}
message("Recording snapshot for 5 seconds...", true)
camera.takeVideoSnapshot(File(filesDir, "video.mp4"), 5000)
}
private fun toggleCamera() {
if (camera.isTakingPicture || camera.isTakingVideo) return
when (camera.toggleFacing()) {
Facing.BACK -> message("Switched to back camera!", false)
Facing.FRONT -> message("Switched to front camera!", false)
}
}
private fun changeCurrentFilter() {
if (camera.preview != Preview.GL_SURFACE) return run {
message("Filters are supported only when preview is Preview.GL_SURFACE.", true)
}
if (currentFilter < allFilters.size - 1) {
currentFilter++
} else {
currentFilter = 0
}
val filter = allFilters[currentFilter]
message(filter.toString(), false)
// Normal behavior:
camera.filter = filter.newInstance()
// To test MultiFilter:
// DuotoneFilter duotone = new DuotoneFilter();
// duotone.setFirstColor(Color.RED);
// duotone.setSecondColor(Color.GREEN);
// camera.setFilter(new MultiFilter(duotone, filter.newInstance()));
}
override fun <T : Any> onValueChanged(option: Option<T>, value: T, name: String): Boolean {
if (option is Option.Width || option is Option.Height) {
val preview = camera.preview
val wrapContent = value as Int == WRAP_CONTENT
if (preview == Preview.SURFACE && !wrapContent) {
message("The SurfaceView preview does not support width or height changes. " +
"The view will act as WRAP_CONTENT by default.", true)
return false
}
}
option.set(camera, value)
BottomSheetBehavior.from(controlPanel).state = BottomSheetBehavior.STATE_HIDDEN
message("Changed " + option.name + " to " + name, false)
return true
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String?>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
val valid = grantResults.all { it == PERMISSION_GRANTED }
if (valid && !camera.isOpened) {
camera.open()
}
}
}
| demo/src/main/kotlin/com/otaliastudios/cameraview/demo/CameraActivity.kt | 1590210888 |
package org.asarkar.cache
import com.hazelcast.cache.impl.HazelcastServerCachingProvider
import com.hazelcast.client.cache.impl.HazelcastClientCachingProvider
import com.hazelcast.client.config.ClientConfig
import com.hazelcast.config.Config
import com.hazelcast.config.EvictionPolicy
import com.hazelcast.config.NearCacheConfig
import com.hazelcast.core.Hazelcast
import com.hazelcast.core.HazelcastInstance
import org.slf4j.LoggerFactory
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.Configuration
import javax.annotation.PreDestroy
import javax.cache.CacheManager
import javax.cache.configuration.FactoryBuilder
import javax.cache.configuration.MutableCacheEntryListenerConfiguration
import javax.cache.configuration.MutableConfiguration
import javax.cache.event.CacheEntryCreatedListener
import javax.cache.event.CacheEntryEvent
import javax.cache.expiry.AccessedExpiryPolicy
import javax.cache.expiry.Duration
@Configuration
@ComponentScan
class CacheConfiguration {
@Configuration
@ConditionalOnProperty("KUBERNETES_SERVICE_HOST")
class ClientCacheConfiguration {
private val logger = LoggerFactory.getLogger(ClientCacheConfiguration::class.java)
init {
logger.info("Hazelcast running in client mode")
}
@Bean
fun hazelcastClientConfig(): ClientConfig {
return ClientConfig().apply {
networkConfig.kubernetesConfig
.setEnabled(true)
.setProperty("service-dns", "hazelcast.default.svc.cluster.local")
val ncc = getNearCacheConfig(RandApp.RAND_CACHE) ?: NearCacheConfig(RandApp.RAND_CACHE)
// This is useful when the in-memory format of the Near Cache is different from the backing data structure.
// This setting has no meaning on Hazelcast clients, since they have no local entries.
ncc.isCacheLocalEntries = false
ncc.evictionConfig.evictionPolicy = EvictionPolicy.LRU
ncc.evictionConfig.size = 10
// When this setting is enabled, a Hazelcast instance with a Near Cache listens for cluster-wide changes
// on the entries of the backing data structure and invalidates its corresponding Near Cache entries.
// Changes done on the local Hazelcast instance always invalidate the Near Cache immediately.
ncc.isInvalidateOnChange = true
addNearCacheConfig(ncc)
setProperty("hazelcast.logging.type", "slf4j")
}
}
@Bean
fun jCacheManager(hazelcast: HazelcastInstance): CacheManager {
val cachingProvider = HazelcastClientCachingProvider.createCachingProvider(hazelcast)
return cachingProvider.cacheManager.apply {
createCache(RandApp.RAND_CACHE, cacheConfig(false))
}
}
}
@Configuration
@ConditionalOnProperty(name = ["KUBERNETES_SERVICE_HOST"], matchIfMissing = true)
class ServerCacheConfiguration {
private val logger = LoggerFactory.getLogger(ServerCacheConfiguration::class.java)
init {
logger.info("Hazelcast running in server mode")
}
@PreDestroy
fun shutdown() {
Hazelcast.shutdownAll();
}
@Bean
fun jCacheManager(hazelcast: HazelcastInstance): CacheManager {
val cachingProvider = HazelcastServerCachingProvider.createCachingProvider(hazelcast)
return cachingProvider.cacheManager.apply {
createCache(RandApp.RAND_CACHE, cacheConfig(true))
}
}
@Bean
fun hazelcastConfig(): Config {
return Config().apply {
setProperty("hazelcast.logging.type", "slf4j")
networkConfig.join.multicastConfig.isEnabled = true
networkConfig.join.kubernetesConfig.isEnabled = false
}
}
}
companion object {
fun cacheConfig(server: Boolean): MutableConfiguration<Any, Int> {
return MutableConfiguration<Any, Int>()
.setExpiryPolicyFactory(AccessedExpiryPolicy.factoryOf(Duration.ONE_MINUTE)).apply {
// Hazelcast Docker container doesn't have listener class on its classpath
if (server) {
addCacheEntryListenerConfiguration(
MutableCacheEntryListenerConfiguration(
FactoryBuilder.factoryOf(
RandCacheEntryCreatedListener()
), null, false, true
)
)
}
}
}
class RandCacheEntryCreatedListener : CacheEntryCreatedListener<Any, Int>, java.io.Serializable {
companion object {
private const val serialVersionUID: Long = 123
private val logger = LoggerFactory.getLogger(RandCacheEntryCreatedListener::class.java)
}
override fun onCreated(events: MutableIterable<CacheEntryEvent<out Any, out Int>>) {
events.forEach(this::logEvent)
}
private fun logEvent(e: CacheEntryEvent<out Any, out Int>) {
logger.info("Cache entry type: {}, key: {}, value: {}", e.eventType, e.key, e.value)
}
}
}
} | hazelcast-learning/src/main/kotlin/org/asarkar/cache/CacheConfiguration.kt | 2105598991 |
package com.github.czyzby.setup.data.templates.unofficial
import com.github.czyzby.setup.data.libs.unofficial.Noise4J
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.data.templates.Template
import com.github.czyzby.setup.views.ProjectTemplate
@ProjectTemplate
class Noise4JTemplate : Template {
override val id = "noise4jTemplate"
private lateinit var mainClass: String
override val width: String
get() = mainClass + ".SIZE * 2"
override val height: String
get() = mainClass + ".SIZE * 2"
override val description: String
get() = "Project template included simple launchers and an `ApplicationAdapter` extension that draws random maps created using [Noise4J](https://github.com/czyzby/noise4j)."
override fun apply(project: Project) {
mainClass = project.basic.mainClass
super.apply(project)
// Including noise4j dependency:
Noise4J().initiate(project)
}
override fun getApplicationListenerContent(project: Project): String = """package ${project.basic.rootPackage};
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Batch;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.github.czyzby.noise4j.map.Grid;
import com.github.czyzby.noise4j.map.generator.cellular.CellularAutomataGenerator;
import com.github.czyzby.noise4j.map.generator.noise.NoiseGenerator;
import com.github.czyzby.noise4j.map.generator.room.RoomType.DefaultRoomType;
import com.github.czyzby.noise4j.map.generator.room.dungeon.DungeonGenerator;
import com.github.czyzby.noise4j.map.generator.util.Generators;
/** {@link com.badlogic.gdx.ApplicationListener} implementation shared by all platforms. */
public class ${project.basic.mainClass} extends ApplicationAdapter {
/** Size of the generated maps. */
public static final int SIZE = 200;
private Grid grid = new Grid(SIZE);
private Batch batch;
private Texture texture;
private Pixmap pixmap;
@Override
public void create() {
pixmap = new Pixmap(SIZE, SIZE, Format.RGBA8888);
batch = new SpriteBatch();
// Adding event listener - recreating map on click:
Gdx.input.setInputProcessor(new InputAdapter() {
@Override
public boolean touchDown(int screenX, int screenY, int pointer, int button) {
rollMap();
return true;
}
});
// Creating a random map:
rollMap();
}
@Override
public void render() {
Gdx.gl.glClearColor(0f, 0f, 0f, 1f);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(texture, 0f, 0f, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
batch.end();
}
@Override
public void dispose() {
batch.dispose();
texture.dispose();
pixmap.dispose();
}
private void rollMap() {
// Clearing all grid values:
grid.set(0f);
// Choosing map generator:
float test = MathUtils.random();
if (test < 0.25f) {
createNoiseMap();
} else if (test < 0.50f) {
createCellularMap();
} else if (test < 0.75f) {
createSimpleDungeonMap();
} else {
createDungeonMap();
}
createTexture();
}
/** Uses NoiseGenerator to create a height map. */
private void createNoiseMap() {
NoiseGenerator noiseGenerator = new NoiseGenerator();
// The first value is the radius, the second is the modifier. Ensuring that the biggest regions have the highest
// modifier allows to generate interesting maps with smooth transitions between regions.
noiseStage(noiseGenerator, 32, 0.45f);
noiseStage(noiseGenerator, 16, 0.25f);
noiseStage(noiseGenerator, 8, 0.15f);
noiseStage(noiseGenerator, 4, 0.1f);
noiseStage(noiseGenerator, 2, 0.05f);
}
private void noiseStage(NoiseGenerator noiseGenerator, int radius, float modifier) {
noiseGenerator.setRadius(radius); // Radius of a single sector.
noiseGenerator.setModifier(modifier); // The max value added to a single cell.
// Seed ensures randomness, can be saved if you feel the need to generate the same map in the future.
noiseGenerator.setSeed(Generators.rollSeed());
noiseGenerator.generate(grid);
}
/** Uses CellularAutomataGenerator to create a cave-like map. */
private void createCellularMap() {
CellularAutomataGenerator cellularGenerator = new CellularAutomataGenerator();
cellularGenerator.setAliveChance(0.5f); // 50% of cells will start as filled.
cellularGenerator.setIterationsAmount(4); // The more iterations, the smoother the map.
cellularGenerator.generate(grid);
}
/** Uses DungeonGenerator to create a simple wall-corridor-room type of map. */
private void createSimpleDungeonMap() {
DungeonGenerator dungeonGenerator = new DungeonGenerator();
dungeonGenerator.setRoomGenerationAttempts(500); // The bigger it is, the more rooms are likely to appear.
dungeonGenerator.setMaxRoomSize(21); // Max room size, should be odd.
dungeonGenerator.setTolerance(5); // Max difference between width and height.
dungeonGenerator.setMinRoomSize(5); // Min room size, should be odd.
dungeonGenerator.generate(grid);
}
/** Uses DungeonGenerator to create a wall-corridor-room type of map with different room types. */
private void createDungeonMap() {
DungeonGenerator dungeonGenerator = new DungeonGenerator();
dungeonGenerator.setRoomGenerationAttempts(500); // The bigger it is, the more rooms are likely to appear.
dungeonGenerator.setMaxRoomSize(25); // Max room size, should be odd.
dungeonGenerator.setTolerance(5); // Max difference between width and height.
dungeonGenerator.setMinRoomSize(9); // Min room size, should be odd.
dungeonGenerator.addRoomTypes(DefaultRoomType.values()); // Adding different room types.
dungeonGenerator.generate(grid);
}
private void createTexture() {
// Destroying previous texture:
if (texture != null) {
texture.dispose();
}
// Drawing on pixmap according to grid's values:
Color color = new Color();
for (int x = 0; x < grid.getWidth(); x++) {
for (int y = 0; y < grid.getHeight(); y++) {
float cell = grid.get(x, y);
color.set(cell, cell, cell, 1f);
pixmap.drawPixel(x, y, Color.rgba8888(color));
}
} // Creating a new texture with the values from pixmap:
texture = new Texture(pixmap);
}
}"""
}
| src/main/kotlin/com/github/czyzby/setup/data/templates/unofficial/noise4j.kt | 2398602869 |
package glimpse
/**
* Two-dimensional angle.
*
* @property deg Angle measure in degrees.
* @property rad Angle measure in radians.
*/
data class Angle private constructor(val deg: Float, val rad: Float) : Comparable<Angle> {
companion object {
/**
* Null angle.
*/
val NULL = Angle(0f, 0f)
/**
* Full angle.
*/
val FULL = Angle(360f, (2.0 * Math.PI).toFloat())
/**
* Straight angle.
*/
val STRAIGHT = FULL / 2f
/**
* Right angle.
*/
val RIGHT = STRAIGHT / 2f
/**
* Creates [Angle] from degrees.
*/
fun fromDeg(deg: Float) = Angle(deg, (deg * Math.PI / 180.0).toFloat())
/**
* Creates [Angle] from radians.
*/
fun fromRad(rad: Float) = Angle((rad * 180.0 / Math.PI).toFloat(), rad)
}
/**
* Returns a string representation of the [Angle].
*/
override fun toString() = "%.1f\u00B0".format(deg)
/**
* Returns an angle opposite to this angle.
*/
operator fun unaryMinus() = Angle(-deg, -rad)
/**
* Returns a sum of this angle and the [other] angle.
*/
operator fun plus(other: Angle) = Angle(deg + other.deg, rad + other.rad)
/**
* Returns a difference of this angle and the [other] angle.
*/
operator fun minus(other: Angle) = Angle(deg - other.deg, rad - other.rad)
/**
* Returns a product of this angle and a [number].
*/
operator fun times(number: Float) = Angle(deg * number, rad * number)
/**
* Returns a quotient of this angle and a [number].
*/
operator fun div(number: Float) = Angle(deg / number, rad / number)
/**
* Returns a quotient of this angle and the [other] angle.
*/
operator fun div(other: Angle) = rad / other.rad
/**
* Returns a remainder of dividing this angle by the [other] angle.
*/
operator fun mod(other: Angle) = (deg % other.deg).degrees
/**
* Returns a range of angles.
*/
operator fun rangeTo(other: Angle) = AnglesRange(this, other)
/**
* Returns an angle coterminal to this angle, closest to [other] angle in clockwise direction.
*/
infix fun clockwiseFrom(other: Angle) =
other - (other - this) % FULL - if (other < this) FULL else NULL
/**
* Returns an angle coterminal to this angle, closest to [other] angle in counter-clockwise direction.
*/
infix fun counterClockwiseFrom(other: Angle) =
other + (this - other) % FULL + if (other > this) FULL else NULL
/**
* Compares this angle to the [other] angle.
*
* Returns zero if this angle is equal to the [other] angle,
* a negative number if it is less than [other],
* or a positive number if it is greater than [other].
*/
override operator fun compareTo(other: Angle) = rad.compareTo(other.rad)
}
| api/src/main/kotlin/glimpse/Angle.kt | 1774326394 |
package lt.vilnius.tvarkau.api
import com.google.gson.FieldNamingPolicy
import com.google.gson.GsonBuilder
import retrofit2.HttpException
import retrofit2.Response
import timber.log.Timber
import java.io.IOException
import java.nio.charset.Charset
class ApiError : RuntimeException {
val errorType: ErrorType
val retrofitResponse: Response<*>?
val validationErrors: List<ApiValidationError>
var responseCode: Int = BaseResponse.REPOSE_CODE_OK
private set
var response: BaseResponse? = null
private set
val httpStatusCode: Int
private var apiMessage: String? = null
constructor(cause: Throwable) : super(cause) {
errorType = ErrorType.SYSTEM
retrofitResponse = null
validationErrors = emptyList()
httpStatusCode = 500
}
constructor(httpException: HttpException) : super(httpException) {
errorType = ErrorType.SERVER
retrofitResponse = httpException.response()
validationErrors = emptyList()
parseApiResponse(httpException)
httpStatusCode = httpException.code()
}
constructor(response: BaseResponse) : super(response.message) {
this.response = response
validationErrors = response.errors
responseCode = response.code
apiMessage = response.message
retrofitResponse = null
errorType = when {
response.isValidationError -> ErrorType.VALIDATION
else -> ErrorType.API
}
this.httpStatusCode = 400
}
private fun parseApiResponse(httpException: HttpException) {
try {
response = extractBaseResponse(httpException)
responseCode = response!!.code
apiMessage = response!!.message
} catch (ignored: RuntimeException) {
val url = httpException.response().raw().request().url()
Timber.w("Failed parse response from url: $url")
}
}
val firstErrorMessage: String?
get() = validationErrors.firstOrNull()?.value ?: apiErrorMessage
val firstValidationErrorField: String
get() = validationErrors.firstOrNull()?.field ?: ""
/**
* @see ErrorType.VALIDATION
*/
val isValidationError: Boolean
get() = errorType == ErrorType.VALIDATION
/**
* @see ErrorType.API
*/
val isApiError: Boolean
get() = errorType == ErrorType.API
/**
* @see ErrorType.SERVER
*/
val isServerError: Boolean
get() = errorType == ErrorType.SERVER
/**
* @see ErrorType.SYSTEM
*/
val isSystemError: Boolean
get() = errorType == ErrorType.SYSTEM
val apiErrorMessage: String?
get() = apiMessage
enum class ErrorType {
/**
* Unexpected IO errors
*/
SYSTEM,
/**
* Unexpected server errors without response body (basically 5xx)
*/
SERVER,
/**
* Api errors (2xx - 4xx) with error body
*/
API,
/**
* Special case of validation Api error
*/
VALIDATION,
}
companion object {
fun extractBaseResponse(httpException: HttpException): BaseResponse {
val body = httpException.response().errorBody() ?: throw IOException("No body")
val source = body.source()
source.request(Long.MAX_VALUE)
val buffer = source.buffer()
val charset = body.contentType()?.charset(UTF_8) ?: UTF_8
val gson = GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create()
return gson.fromJson(buffer.clone().readString(charset), BaseResponse::class.java)
}
fun of(error: Throwable): ApiError {
return when (error) {
is ApiError -> error
is HttpException -> ApiError(error)
else -> ApiError(error)
}
}
val UTF_8: Charset = Charset.forName("UTF-8")
}
}
| app/src/main/java/lt/vilnius/tvarkau/api/ApiError.kt | 2468064214 |
package game.robotm.ecs.systems
import com.badlogic.ashley.core.ComponentMapper
import com.badlogic.ashley.core.Entity
import com.badlogic.ashley.core.Family
import com.badlogic.ashley.systems.IteratingSystem
import com.badlogic.gdx.graphics.Camera
import game.robotm.ecs.components.FollowCameraComponent
import game.robotm.ecs.components.PhysicsComponent
class FollowCameraSystem(val camera: Camera) : IteratingSystem(Family.all(PhysicsComponent::class.java, FollowCameraComponent::class.java).get()) {
val physicsM = ComponentMapper.getFor(PhysicsComponent::class.java)
val followCamM = ComponentMapper.getFor(FollowCameraComponent::class.java)
override fun processEntity(entity: Entity, delta: Float) {
val followCameraComponent = followCamM.get(entity)
val body = physicsM.get(entity).body
body.setTransform(camera.position.x + followCameraComponent.xDist, camera.position.y + followCameraComponent.yDist, 0f)
}
} | core/src/game/robotm/ecs/systems/FollowCameraSystem.kt | 1408704 |
package io.javalin.plugin.openapi.ui
import io.javalin.core.util.OptionalDependency
import io.javalin.core.util.Util
import io.javalin.http.Context
import io.javalin.http.Handler
import io.javalin.plugin.openapi.OpenApiOptions
import io.javalin.plugin.openapi.annotations.OpenApi
class ReDocOptions @JvmOverloads constructor(
path: String,
internal val optionsObject: RedocOptionsObject = RedocOptionsObject()
) : OpenApiUiOptions<ReDocOptions>(path) {
override val defaultTitle = "ReDoc"
}
internal class ReDocRenderer(private val openApiOptions: OpenApiOptions) : Handler {
@OpenApi(ignore = true)
override fun handle(ctx: Context) {
val reDocOptions = openApiOptions.reDoc!!
val docsPath = openApiOptions.getFullDocumentationUrl(ctx)
ctx.html(createReDocHtml(ctx, docsPath, reDocOptions))
}
}
private fun createReDocHtml(ctx: Context, docsPath: String, redocOptions: ReDocOptions): String {
val publicBasePath = Util.getWebjarPublicPath(ctx, OptionalDependency.REDOC)
val options = redocOptions.optionsObject
return """
|<!DOCTYPE html>
|<html>
| <head>
| <title>${redocOptions.createTitle()}</title>
| <!-- Needed for adaptive design -->
| <meta charset="utf-8"/>
| <meta name="viewport" content="width=device-width, initial-scale=1">
| <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
| <!-- ReDoc doesn't change outer page styles -->
| <style>body{margin:0;padding:0;}</style>
| </head>
| <body>
| <redoc id='redoc'></redoc>
| <script src="$publicBasePath/bundles/redoc.standalone.js"></script>
| <script>
| window.onload = () => {
| Redoc.init('$docsPath', ${options.json()}, document.getElementById('redoc'))
| }
| </script>
| </body>
|</html>
|""".trimMargin()
}
| javalin-openapi/src/main/java/io/javalin/plugin/openapi/ui/ReDocRenderer.kt | 4146367108 |
package com.wcaokaze.cac2er
import kunit.deepEquals
import org.junit.*
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.io.File
import java.io.Serializable
@RunWith(JUnit4::class)
class GcTest {
/**
* Cac2er caches the instances of [Cache]. So each test must use identified
* [File]s for [Cache]s.
*/
private companion object FileSupplier {
// do never specify 'test'.
val TEST_DIR = File(".cac2erTest/")
private var count = 0
fun supplyFile() = File(TEST_DIR, count++.toString())
}
private val garbage = IntRange(0, 256).toList()
@Before fun createTestDir() {
TEST_DIR.mkdir()
}
@After fun deleteTestDir() {
TEST_DIR.deleteRecursively()
}
@Test fun basic() {
val (file1, cache1) = cache(garbage)
val (file2, _ ) = cache(garbage)
cache1.recordAndSave()
val expectedLiveFiles = listOf(file1)
Cacher.gc(listOf(file1, file2), fileSizeFor(expectedLiveFiles))
assert(expectedLiveFiles isConsistentWith TEST_DIR)
}
@Test fun depend() {
class Foo(@Suppress("UNUSED") val cache: Cache<List<Int>>) : Serializable
val (file1, cache1) = cache(garbage)
val (file2, cache2) = cache(Foo(cache1))
val (file3, cache3) = cache(garbage)
cache2.recordAndSave(2.0f)
cache3.recordAndSave(1.0f)
/*
* cache3.importance > cache1.importance but cache1 will survive. Because
* cache1 is depended by cache2 and cache2.importance > cache3.importance.
*/
val expectedLiveFiles = listOf(file1, file2)
Cacher.gc(listOf(file1, file2, file3), fileSizeFor(expectedLiveFiles))
assert(expectedLiveFiles isConsistentWith TEST_DIR)
}
@Test fun deletingAllSameImportanceFiles() {
val files = IntRange(0, 127)
.map { cache("") }
.map { it.first }
Cacher.gc(files, fileSizeFor(files) / 2)
assert(TEST_DIR.listFiles().isEmpty())
}
@Test fun infinite() {
val (file1, cache1) = cache("wcaokaze")
val (file2, cache2) = cache("wcaokaze")
cache1.recordAndSave(114514.0f)
cache2.recordInfiniteAndSave()
val expectedLiveFiles = listOf(file2)
Cacher.gc(listOf(file1, file2), fileSizeFor(expectedLiveFiles))
assert(expectedLiveFiles isConsistentWith TEST_DIR)
}
@Test fun multiDepended() {
class Foo(@Suppress("UNUSED") val cache: Cache<String>) : Serializable
val (file1, cache1) = cache("wcaokaze")
val (file2, cache2) = cache(Foo(cache1))
val (file3, cache3) = cache(Foo(cache1))
cache2.recordAndSave(2.0f)
cache3.recordAndSave(3.0f)
val expectedLiveFiles = listOf(file1, file3)
Cacher.gc(listOf(file1, file2, file3), fileSizeFor(expectedLiveFiles))
assert(expectedLiveFiles isConsistentWith TEST_DIR)
}
@Test fun circularReference() {
class Foo(@Suppress("UNUSED") val cache: Cache<*>) : Serializable
/*
* +-----------------+
* | cache4 |
* | importance: 0.0 |
* +-----------------+
* |
* V
* +-----------------+ +-----------------+
* | cache2 | --> | cache3 |
* | importance: 0.0 | <-- | importance: 1.0 |
* +-----------------+ +-----------------+
* |
* V
* +-----------------+
* | cache1 |
* | "wcaokaze" |
* | importance: 0.0 |
* +-----------------+
*/
val (file1, cache1) = cache("wcaokaze")
val (file2, cache2) = cache<Any?>(null)
val (file3, cache3) = cache(Foo(cache2))
val (file4, _ ) = cache(Foo(cache2))
cache2.content = object : Serializable {
@Suppress ("UNUSED") val cache1 = cache1
@Suppress ("UNUSED") val cache3 = cache3
}
Cacher.save(cache2)
cache3.recordAndSave()
val expectedLiveFiles = listOf(file1, file2, file3)
Cacher.gc(listOf(file1, file2, file3, file4), fileSizeFor(expectedLiveFiles))
assert(expectedLiveFiles isConsistentWith TEST_DIR)
}
@Test fun removeUnaffectableRecords() {
val (file, cache) = cache("wcaokaze")
val currentPeriod = periodOf(System.currentTimeMillis())
with (cache.circulationRecord) {
record(startTimeOf(currentPeriod - 4), 2.5f) // importance: 0.42f
record(startTimeOf(currentPeriod - 3), 1.0f) // importance: 0.20f
record(startTimeOf(currentPeriod - 1), 1.0f) // importance: 0.33f
}
Cacher.saveCirculationRecord(cache)
Cacher.gc(listOf(file), fileSizeFor(listOf(file)))
val circulationRecord = cache.circulationRecord as CirculationRecordImpl
val survivedPeriods = circulationRecord.map { it.period }
assert(survivedPeriods deepEquals
listOf(currentPeriod - 4, currentPeriod - 1))
val savedCirculationRecord
= Cacher.load(file).second as CirculationRecordImpl
assert(savedCirculationRecord deepEquals circulationRecord)
}
private fun <T> cache(content: T): Pair<File, WritableCache<T>> {
val file = supplyFile()
val cache = WritableCache(file, content)
Cacher.save(cache)
return file to cache
}
private fun Cache<*>.recordAndSave(accessCount: Float = 1.0f) {
circulationRecord.record(accessCount = accessCount)
Cacher.saveCirculationRecord(this)
}
private fun Cache<*>.recordInfiniteAndSave() {
circulationRecord.recordInfinite()
Cacher.saveCirculationRecord(this)
}
private fun fileSizeFor(fileList: List<File>)
= fileList.map { it.length() }.sum() + 10L
private infix fun Iterable<File>.isConsistentWith(directory: File): Boolean {
val filesInDirectory = directory.listFiles()
return all { it in filesInDirectory } && filesInDirectory.all { it in this }
}
}
| src/test/kotlin/com/wcaokaze/cac2er/GcTest.kt | 1343803230 |
package de.westnordost.streetcomplete.quests.shop_type
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.meta.*
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.CITIZEN
class CheckShopType : OsmElementQuestType<ShopTypeAnswer> {
private val disusedShops by lazy { """
nodes, ways, relations with (
shop = vacant
or ${isKindOfShopExpression("disused")}
) and (
older today -1 years
or ${LAST_CHECK_DATE_KEYS.joinToString(" or ") { "$it < today -1 years" }}
)
""".toElementFilterExpression() }
/* elements tagged like "shop=ice_cream + disused:amenity=bank" should not appear as quests.
* This is arguably a tagging mistake, but that mistake should not lead to all the tags of
* this element being cleared when the quest is answered */
private val shops by lazy { """
nodes, ways, relations with ${isKindOfShopExpression()}
""".toElementFilterExpression() }
override val commitMessage = "Check if vacant shop is still vacant"
override val wikiLink = "Key:disused:"
override val icon = R.drawable.ic_quest_check_shop
override val questTypeAchievements = listOf(CITIZEN)
override fun getTitle(tags: Map<String, String>) = R.string.quest_shop_vacant_type_title
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> =
mapData.filter { isApplicableTo(it) }
override fun isApplicableTo(element: Element): Boolean =
disusedShops.matches(element) && !shops.matches(element)
override fun createForm() = ShopTypeForm()
override fun applyAnswerTo(answer: ShopTypeAnswer, changes: StringMapChangesBuilder) {
when (answer) {
is IsShopVacant -> {
changes.updateCheckDate()
}
is ShopType -> {
changes.deleteCheckDates()
if (!answer.tags.containsKey("shop")) {
changes.deleteIfExists("shop")
}
for ((key, _) in changes.getPreviousEntries()) {
// also deletes all "disused:" keys
val isOkToRemove =
KEYS_THAT_SHOULD_BE_REMOVED_WHEN_SHOP_IS_REPLACED.any { it.matches(key) }
if (isOkToRemove && !answer.tags.containsKey(key)) {
changes.delete(key)
}
}
for ((key, value) in answer.tags) {
changes.addOrModify(key, value)
}
}
}
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/shop_type/CheckShopType.kt | 3378857918 |
package quickbeer.android.domain.beerlist.repository
import javax.inject.Inject
import quickbeer.android.data.repository.repository.ItemListRepository
import quickbeer.android.domain.beer.Beer
import quickbeer.android.domain.beer.network.BeerJson
import quickbeer.android.domain.beerlist.network.BarcodeSearchFetcher
import quickbeer.android.domain.beerlist.store.BarcodeSearchStore
class BarcodeSearchRepository @Inject constructor(
override val store: BarcodeSearchStore,
fetcher: BarcodeSearchFetcher
) : ItemListRepository<String, Int, Beer, BeerJson>(store, fetcher)
| app/src/main/java/quickbeer/android/domain/beerlist/repository/BarcodeSearchRepository.kt | 3678212337 |
package gargoyle.ct.util.pref
import gargoyle.ct.util.prop.CTProperty
import java.text.MessageFormat
class CTPropertyChangeEvent<T : Any>(val property: CTProperty<T>, val name: String, val oldValue: T?, val newValue: T) {
override fun toString(): String {
return MessageFormat.format("CTPropertyChangeEvent'{'property={0}'}'", property)
}
}
| util/src/main/kotlin/gargoyle/ct/util/pref/CTPropertyChangeEvent.kt | 214204274 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.