content
stringlengths 0
13M
| path
stringlengths 4
263
| contentHash
stringlengths 1
10
|
---|---|---|
package net.pterodactylus.sone.web.ajax
import net.pterodactylus.sone.utils.parameters
import net.pterodactylus.sone.web.WebInterface
import net.pterodactylus.sone.web.page.*
import javax.inject.Inject
/**
* Lets the user [unlock][net.pterodactylus.sone.core.Core.unlockSone] a [Sone][net.pterodactylus.sone.data.Sone].
*/
@ToadletPath("unlockSone.ajax")
class UnlockSoneAjaxPage @Inject constructor(webInterface: WebInterface) : JsonPage(webInterface) {
override val requiresLogin = false
override fun createJsonObject(request: FreenetRequest) =
request.parameters["sone"]
?.let(core::getLocalSone)
?.also(core::unlockSone)
?.also { core.touchConfiguration() }
?.let { createSuccessJsonObject() }
?: createErrorJsonObject("invalid-sone-id")
}
| src/main/kotlin/net/pterodactylus/sone/web/ajax/UnlockSoneAjaxPage.kt | 1522412615 |
package net.pterodactylus.sone.web.pages
import com.google.common.base.*
import com.google.common.base.Optional.*
import net.pterodactylus.sone.data.*
import net.pterodactylus.sone.test.*
import net.pterodactylus.sone.utils.*
import net.pterodactylus.sone.web.*
import net.pterodactylus.sone.web.page.*
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.*
import java.util.concurrent.*
import java.util.concurrent.atomic.*
/**
* Unit test for [SearchPage].
*/
class SearchPageTest : WebPageTest({ webInterface, loaders, templateRenderer -> SearchPage(webInterface, loaders, templateRenderer, ticker) }) {
companion object {
val ticker = mock<Ticker>()
}
@Test
fun `page returns correct path`() {
assertThat(page.path, equalTo("search.html"))
}
@Test
fun `page does not require login`() {
assertThat(page.requiresLogin(), equalTo(false))
}
@Test
fun `page returns correct title`() {
addTranslation("Page.Search.Title", "search page title")
assertThat(page.getPageTitle(soneRequest), equalTo("search page title"))
}
@Test
fun `empty query redirects to index page`() {
verifyRedirect("index.html")
}
@Test
fun `empty search phrases redirect to index page`() {
addHttpRequestParameter("query", "\"\"")
verifyRedirect("index.html")
}
@Test
fun `invalid search phrases redirect to index page`() {
addHttpRequestParameter("query", "\"")
verifyRedirect("index.html")
}
@Test
fun `searching for sone link redirects to view sone page`() {
addSone("Sone-ID", mock())
addHttpRequestParameter("query", "sone://Sone-ID")
verifyRedirect("viewSone.html?sone=Sone-ID")
}
@Test
fun `searching for sone link without prefix redirects to view sone page`() {
addSone("sone-id", mock())
addHttpRequestParameter("query", "sone-id")
verifyRedirect("viewSone.html?sone=sone-id")
}
@Test
fun `searching for a post link redirects to post page`() {
addPost("Post-id", mock())
addHttpRequestParameter("query", "post://Post-id")
verifyRedirect("viewPost.html?post=Post-id")
}
@Test
fun `searching for a post ID without prefix redirects to post page`() {
addPost("post-id", mock())
addHttpRequestParameter("query", "post-id")
verifyRedirect("viewPost.html?post=post-id")
}
@Test
fun `searching for a reply link redirects to the post page`() {
val postReply = mock<PostReply>().apply { whenever(postId).thenReturn("post-id") }
addPostReply("Reply-id", postReply)
addHttpRequestParameter("query", "reply://Reply-id")
verifyRedirect("viewPost.html?post=post-id")
}
@Test
fun `searching for a reply ID redirects to the post page`() {
val postReply = mock<PostReply>().apply { whenever(postId).thenReturn("post-id") }
addPostReply("reply-id", postReply)
addHttpRequestParameter("query", "reply-id")
verifyRedirect("viewPost.html?post=post-id")
}
@Test
fun `searching for an album link redirects to the image browser`() {
addAlbum("album-id", mock())
addHttpRequestParameter("query", "album://album-id")
verifyRedirect("imageBrowser.html?album=album-id")
}
@Test
fun `searching for an album ID redirects to the image browser`() {
addAlbum("album-id", mock())
addHttpRequestParameter("query", "album-id")
verifyRedirect("imageBrowser.html?album=album-id")
}
@Test
fun `searching for an image link redirects to the image browser`() {
addImage("image-id", mock())
addHttpRequestParameter("query", "image://image-id")
verifyRedirect("imageBrowser.html?image=image-id")
}
@Test
fun `searching for an image ID redirects to the image browser`() {
addImage("image-id", mock())
addHttpRequestParameter("query", "image-id")
verifyRedirect("imageBrowser.html?image=image-id")
}
private fun createReply(text: String, postId: String? = null, sone: Sone? = null) = mock<PostReply>().apply {
whenever(this.text).thenReturn(text)
postId?.run { whenever([email protected]).thenReturn(postId) }
sone?.run { whenever([email protected]).thenReturn(sone) }
}
private fun createPost(id: String, text: String) = mock<Post>().apply {
whenever(this.id).thenReturn(id)
whenever(recipient).thenReturn(absent())
whenever(this.text).thenReturn(text)
}
private fun createSoneWithPost(post: Post, sone: Sone? = null) = sone?.apply {
whenever(posts).thenReturn(listOf(post))
} ?: mock<Sone>().apply {
whenever(posts).thenReturn(listOf(post))
whenever(profile).thenReturn(Profile(this))
}
@Test
fun `searching for a single word finds the post`() {
val postWithMatch = createPost("post-with-match", "the word here")
val postWithoutMatch = createPost("post-without-match", "no match here")
val soneWithMatch = createSoneWithPost(postWithMatch)
val soneWithoutMatch = createSoneWithPost(postWithoutMatch)
addSone("sone-with-match", soneWithMatch)
addSone("sone-without-match", soneWithoutMatch)
addHttpRequestParameter("query", "word")
verifyNoRedirect {
assertThat(this["postHits"], contains<Post>(postWithMatch))
}
}
@Test
fun `searching for a single word locates word in reply`() {
val postWithMatch = createPost("post-with-match", "no match here")
val postWithoutMatch = createPost("post-without-match", "no match here")
val soneWithMatch = createSoneWithPost(postWithMatch)
val soneWithoutMatch = createSoneWithPost(postWithoutMatch)
val replyWithMatch = createReply("the word here", "post-with-match", soneWithMatch)
val replyWithoutMatch = createReply("no match here", "post-without-match", soneWithoutMatch)
addPostReply("reply-with-match", replyWithMatch)
addPostReply("reply-without-match", replyWithoutMatch)
addSone("sone-with-match", soneWithMatch)
addSone("sone-without-match", soneWithoutMatch)
addHttpRequestParameter("query", "word")
verifyNoRedirect {
assertThat(this["postHits"], contains<Post>(postWithMatch))
}
}
private fun createSoneWithPost(idPostfix: String, text: String, recipient: Sone? = null, sender: Sone? = null) =
createPost("post-$idPostfix", text, recipient).apply {
addSone("sone-$idPostfix", createSoneWithPost(this, sender))
}
@Test
fun `earlier matches score higher than later matches`() {
val postWithEarlyMatch = createSoneWithPost("with-early-match", "optional match")
val postWithLaterMatch = createSoneWithPost("with-later-match", "match that is optional")
addHttpRequestParameter("query", "optional ")
verifyNoRedirect {
assertThat(this["postHits"], contains<Post>(postWithEarlyMatch, postWithLaterMatch))
}
}
@Test
fun `searching for required word does not return posts without that word`() {
val postWithRequiredMatch = createSoneWithPost("with-required-match", "required match")
createPost("without-required-match", "not a match")
addHttpRequestParameter("query", "+required ")
verifyNoRedirect {
assertThat(this["postHits"], contains<Post>(postWithRequiredMatch))
}
}
@Test
fun `searching for forbidden word does not return posts with that word`() {
createSoneWithPost("with-forbidden-match", "forbidden match")
val postWithoutForbiddenMatch = createSoneWithPost("without-forbidden-match", "not a match")
addHttpRequestParameter("query", "match -forbidden")
verifyNoRedirect {
assertThat(this["postHits"], contains<Post>(postWithoutForbiddenMatch))
}
}
@Test
fun `searching for a plus sign searches for optional plus sign`() {
val postWithMatch = createSoneWithPost("with-match", "with + match")
createSoneWithPost("without-match", "without match")
addHttpRequestParameter("query", "+")
verifyNoRedirect {
assertThat(this["postHits"], contains<Post>(postWithMatch))
}
}
@Test
fun `searching for a minus sign searches for optional minus sign`() {
val postWithMatch = createSoneWithPost("with-match", "with - match")
createSoneWithPost("without-match", "without match")
addHttpRequestParameter("query", "-")
verifyNoRedirect {
assertThat(this["postHits"], contains<Post>(postWithMatch))
}
}
private fun createPost(id: String, text: String, recipient: Sone?) = mock<Post>().apply {
whenever(this.id).thenReturn(id)
val recipientId = recipient?.id
whenever(this.recipientId).thenReturn(recipientId.asOptional())
whenever(this.recipient).thenReturn(recipient.asOptional())
whenever(this.text).thenReturn(text)
}
private fun createSone(id: String, firstName: String? = null, middleName: String? = null, lastName: String? = null) = mock<Sone>().apply {
whenever(this.id).thenReturn(id)
whenever(this.name).thenReturn(id)
whenever(this.profile).thenReturn(Profile(this).apply {
this.firstName = firstName
this.middleName = middleName
this.lastName = lastName
})
}
@Test
fun `searching for a recipient finds the correct post`() {
val recipient = createSone("recipient", "reci", "pi", "ent")
val postWithMatch = createSoneWithPost("with-match", "test", recipient)
createSoneWithPost("without-match", "no match")
addHttpRequestParameter("query", "recipient")
verifyNoRedirect {
assertThat(this["postHits"], contains<Post>(postWithMatch))
}
}
@Test
fun `searching for a field value finds the correct sone`() {
val soneWithProfileField = createSone("sone", "s", "o", "ne")
soneWithProfileField.profile.addField("field").value = "value"
createSoneWithPost("with-match", "test", sender = soneWithProfileField)
createSoneWithPost("without-match", "no match")
addHttpRequestParameter("query", "value")
verifyNoRedirect {
assertThat(this["soneHits"], contains(soneWithProfileField))
}
}
@Test
fun `sone hits are paginated correctly`() {
core.preferences.newPostsPerPage = 2
val sones = listOf(createSone("1Sone"), createSone("Other1"), createSone("22Sone"), createSone("333Sone"), createSone("Other2"))
.onEach { addSone(it.id, it) }
addHttpRequestParameter("query", "sone")
verifyNoRedirect {
assertThat(this["sonePagination"], isOnPage(0).hasPages(2))
assertThat(this["soneHits"], contains(sones[0], sones[2]))
}
}
@Test
fun `sone hits page 2 is shown correctly`() {
core.preferences.newPostsPerPage = 2
val sones = listOf(createSone("1Sone"), createSone("Other1"), createSone("22Sone"), createSone("333Sone"), createSone("Other2"))
.onEach { addSone(it.id, it) }
addHttpRequestParameter("query", "sone")
addHttpRequestParameter("sonePage", "1")
verifyNoRedirect {
assertThat(this["sonePagination"], isOnPage(1).hasPages(2))
assertThat(this["soneHits"], contains(sones[3]))
}
}
@Test
fun `post hits are paginated correctly`() {
core.preferences.newPostsPerPage = 2
val sones = listOf(createSoneWithPost("match1", "1Sone"), createSoneWithPost("no-match1", "Other1"), createSoneWithPost("match2", "22Sone"), createSoneWithPost("match3", "333Sone"), createSoneWithPost("no-match2", "Other2"))
addHttpRequestParameter("query", "sone")
verifyNoRedirect {
assertThat(this["postPagination"], isOnPage(0).hasPages(2))
assertThat(this["postHits"], contains(sones[0], sones[2]))
}
}
@Test
fun `post hits page 2 is shown correctly`() {
core.preferences.newPostsPerPage = 2
val sones = listOf(createSoneWithPost("match1", "1Sone"), createSoneWithPost("no-match1", "Other1"), createSoneWithPost("match2", "22Sone"), createSoneWithPost("match3", "333Sone"), createSoneWithPost("no-match2", "Other2"))
addHttpRequestParameter("query", "sone")
addHttpRequestParameter("postPage", "1")
verifyNoRedirect {
assertThat(this["postPagination"], isOnPage(1).hasPages(2))
assertThat(this["postHits"], contains(sones[3]))
}
}
@Test
fun `post search results are cached`() {
val post = createPost("with-match", "text")
val callCounter = AtomicInteger()
whenever(post.text).thenAnswer { callCounter.incrementAndGet(); "text" }
val sone = createSoneWithPost(post)
addSone("sone", sone)
addHttpRequestParameter("query", "text")
verifyNoRedirect {
assertThat(this["postHits"], contains(post))
}
verifyNoRedirect {
assertThat(callCounter.get(), equalTo(1))
}
}
@Test
fun `post search results are cached for five minutes`() {
val post = createPost("with-match", "text")
val callCounter = AtomicInteger()
whenever(post.text).thenAnswer { callCounter.incrementAndGet(); "text" }
val sone = createSoneWithPost(post)
addSone("sone", sone)
addHttpRequestParameter("query", "text")
verifyNoRedirect {
assertThat(this["postHits"], contains(post))
}
whenever(ticker.read()).thenReturn(TimeUnit.MINUTES.toNanos(5) + 1)
verifyNoRedirect {
assertThat(callCounter.get(), equalTo(2))
}
}
@Suppress("UNCHECKED_CAST")
private operator fun <T> get(key: String): T? = templateContext[key] as? T
@Test
fun `page can be created by dependency injection`() {
assertThat(baseInjector.getInstance<SearchPage>(), notNullValue())
}
@Test
fun `page is annotated with correct template path`() {
assertThat(page.templatePath, equalTo("/templates/search.html"))
}
}
| src/test/kotlin/net/pterodactylus/sone/web/pages/SearchPageTest.kt | 1577827546 |
package com.efficios.jabberwocky.trace
import com.efficios.jabberwocky.trace.event.TraceEvent
import com.google.common.collect.Iterators
abstract class Trace<out E : TraceEvent> {
abstract val name: String
/* Lazy-load the start time by reading the timestamp of the first event. */
val startTime: Long by lazy {
var startTime: Long = 0L
iterator().use { iter ->
if (iter.hasNext()) {
startTime = iter.next().timestamp
}
}
startTime
}
val endTime: Long by lazy {
var endTime: Long = 0L
iterator().use {
if (it.hasNext()) {
endTime = Iterators.getLast(it).timestamp
}
}
endTime
}
abstract fun iterator(): TraceIterator<E>
}
| jabberwocky-core/src/main/kotlin/com/efficios/jabberwocky/trace/Trace.kt | 3712762486 |
/*
* Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.jabberwockd
import com.efficios.jabberwocky.utils.using
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import java.io.File
import java.net.HttpURLConnection
import java.net.URL
import java.net.URLConnection
import java.nio.file.Files
class TraceUploadTest {
companion object {
private const val SERVER_URL = "http://localhost:$LISTENING_PORT/test"
private val UTF8 = Charsets.UTF_8
private const val CRLF = "\r\n" // Line separator required by multipart/form-data.
}
@Test
@Disabled("NYI")
fun testTraceUpload() {
val param = "value"
val textFile = File("/path/to/file.txt")
val binaryFile = File("/path/to/file.bin")
val boundary = System.currentTimeMillis().toString(16) // Just generate some unique random value.
val connection = URL(SERVER_URL).openConnection()
connection.doOutput = true
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=$boundary")
using {
val output = connection.getOutputStream().autoClose()
val writer = output.bufferedWriter().autoClose()
with(writer) {
// Send normal param.
append("--$boundary").append(CRLF)
append("Content-Disposition: form-data; name=\"param\"").append(CRLF)
append("Content-Type: text/plain; charset=" + UTF8).append(CRLF)
append(CRLF).append(param).append(CRLF).flush()
// Send text file.
append("--$boundary").append(CRLF)
append("Content-Disposition: form-data; name=\"textFile\"; filename=\"${textFile.name}\"").append(CRLF)
append("Content-Type: text/plain; charset=" + UTF8).append(CRLF) // Text file itself must be saved in this charset!
append(CRLF).flush()
Files.copy(textFile.toPath(), output)
output.flush()
append(CRLF).flush()
// Send binary file.
append("--$boundary").append(CRLF)
append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"${binaryFile.name}\"").append(CRLF)
append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.name)).append(CRLF)
append("Content-Transfer-Encoding: binary").append(CRLF)
append(CRLF).flush()
Files.copy(binaryFile.toPath(), output)
output.flush()
append(CRLF).flush()
// End of multipart/form-data.
append("--$boundary--").append(CRLF).flush()
}
}
// Request is lazily fired whenever you need to obtain information about response.
val responseCode = (connection as HttpURLConnection).responseCode
System.out.println(responseCode) // Should be 200
}
} | jabberwockd/src/test/kotlin/com/efficios/jabberwocky/jabberwockd/TraceUploadTest.kt | 2518668055 |
/*
* Copyright 2016 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
*
* 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.gradle.kotlin.dsl
import org.gradle.api.NamedDomainObjectContainer
import org.gradle.api.NamedDomainObjectProvider
import org.gradle.api.artifacts.Configuration
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.DependencyConstraint
import org.gradle.api.artifacts.ExternalModuleDependency
import org.gradle.api.artifacts.ModuleDependency
import org.gradle.api.artifacts.dsl.DependencyConstraintHandler
import org.gradle.api.artifacts.dsl.DependencyHandler
import org.gradle.api.initialization.dsl.ScriptHandler
import org.gradle.api.initialization.dsl.ScriptHandler.CLASSPATH_CONFIGURATION
import org.gradle.kotlin.dsl.support.delegates.ScriptHandlerDelegate
import org.gradle.kotlin.dsl.support.unsafeLazy
/**
* Receiver for the `buildscript` block.
*/
class ScriptHandlerScope
private constructor(
override val delegate: ScriptHandler
) : ScriptHandlerDelegate() {
companion object {
fun of(scriptHandler: ScriptHandler) =
ScriptHandlerScope(scriptHandler)
}
/**
* The dependencies of the script.
*/
val dependencies by unsafeLazy { DependencyHandlerScope.of(delegate.dependencies) }
/**
* The script classpath configuration.
*/
val NamedDomainObjectContainer<Configuration>.classpath: NamedDomainObjectProvider<Configuration>
get() = named(CLASSPATH_CONFIGURATION)
/**
* Adds a dependency to the script classpath.
*
* @param dependencyNotation notation for the dependency to be added.
* @return The dependency.
*
* @see [DependencyHandler.add]
*/
fun DependencyHandler.classpath(dependencyNotation: Any): Dependency? =
add(CLASSPATH_CONFIGURATION, dependencyNotation)
/**
* Adds a dependency to the script classpath.
*
* @param dependencyNotation notation for the dependency to be added.
* @param dependencyConfiguration expression to use to configure the dependency.
* @return The dependency.
*
* @see [DependencyHandler.add]
*/
inline fun DependencyHandler.classpath(
dependencyNotation: String,
dependencyConfiguration: ExternalModuleDependency.() -> Unit
): ExternalModuleDependency = add(CLASSPATH_CONFIGURATION, dependencyNotation, dependencyConfiguration)
/**
* Adds a dependency to the script classpath.
*
* @param group the group of the module to be added as a dependency.
* @param name the name of the module to be added as a dependency.
* @param version the optional version of the module to be added as a dependency.
* @param configuration the optional configuration of the module to be added as a dependency.
* @param classifier the optional classifier of the module artifact to be added as a dependency.
* @param ext the optional extension of the module artifact to be added as a dependency.
* @return The dependency.
*
* @see [DependencyHandler.add]
*/
fun DependencyHandler.classpath(
group: String,
name: String,
version: String? = null,
configuration: String? = null,
classifier: String? = null,
ext: String? = null
): ExternalModuleDependency = create(group, name, version, configuration, classifier, ext).also {
add(CLASSPATH_CONFIGURATION, it)
}
/**
* Adds a dependency to the script classpath.
*
* @param group the group of the module to be added as a dependency.
* @param name the name of the module to be added as a dependency.
* @param version the optional version of the module to be added as a dependency.
* @param configuration the optional configuration of the module to be added as a dependency.
* @param classifier the optional classifier of the module artifact to be added as a dependency.
* @param ext the optional extension of the module artifact to be added as a dependency.
* @param dependencyConfiguration expression to use to configure the dependency.
* @return The dependency.
*
* @see [DependencyHandler.create]
* @see [DependencyHandler.add]
*/
inline fun DependencyHandler.classpath(
group: String,
name: String,
version: String? = null,
configuration: String? = null,
classifier: String? = null,
ext: String? = null,
dependencyConfiguration: ExternalModuleDependency.() -> Unit
): ExternalModuleDependency = create(group, name, version, configuration, classifier, ext).also {
add(CLASSPATH_CONFIGURATION, it, dependencyConfiguration)
}
/**
* Adds a dependency to the script classpath.
*
* @param dependency dependency to be added.
* @param dependencyConfiguration expression to use to configure the dependency.
* @return The dependency.
*
* @see [DependencyHandler.add]
*/
inline fun <T : ModuleDependency> DependencyHandler.classpath(
dependency: T,
dependencyConfiguration: T.() -> Unit
): T = add(CLASSPATH_CONFIGURATION, dependency, dependencyConfiguration)
/**
* Adds a dependency constraint to the script classpath configuration.
*
* @param dependencyConstraintNotation the dependency constraint notation
*
* @return the added dependency constraint
*
* @see [DependencyConstraintHandler.add]
* @since 5.0
*/
fun DependencyConstraintHandler.classpath(dependencyConstraintNotation: Any): DependencyConstraint? =
add(CLASSPATH_CONFIGURATION, dependencyConstraintNotation)
/**
* Adds a dependency constraint to the script classpath configuration.
*
* @param dependencyConstraintNotation the dependency constraint notation
* @param configuration the block to use to configure the dependency constraint
*
* @return the added dependency constraint
*
* @see [DependencyConstraintHandler.add]
* @since 5.0
*/
fun DependencyConstraintHandler.classpath(dependencyConstraintNotation: Any, configuration: DependencyConstraint.() -> Unit): DependencyConstraint? =
add(CLASSPATH_CONFIGURATION, dependencyConstraintNotation, configuration)
}
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ScriptHandlerScope.kt | 1394427567 |
package de.ph1b.audiobook.common
import android.os.Build
val DARK_THEME_SETTABLE = Build.VERSION.SDK_INT < Build.VERSION_CODES.Q
| common/src/main/kotlin/de/ph1b/audiobook/common/DarkThemeSettable.kt | 1195362772 |
/*
* Copyright 2018 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
*
* 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.gradle.kotlin.dsl
import org.gradle.api.Action
import org.gradle.caching.BuildCacheServiceFactory
import org.gradle.caching.configuration.BuildCacheConfiguration
import org.gradle.caching.http.HttpBuildCache
import org.gradle.caching.local.DirectoryBuildCache
import org.gradle.caching.local.internal.DirectoryBuildCacheServiceFactory
import com.nhaarman.mockito_kotlin.any
import com.nhaarman.mockito_kotlin.doNothing
import com.nhaarman.mockito_kotlin.doReturn
import com.nhaarman.mockito_kotlin.inOrder
import com.nhaarman.mockito_kotlin.mock
import org.junit.Test
class BuildCacheConfigurationExtensionsTest {
@Test
fun registerBuildCacheService() {
val buildCache = mock<BuildCacheConfiguration>()
doNothing().`when`(buildCache).registerBuildCacheService(any<Class<DirectoryBuildCache>>(), any<Class<BuildCacheServiceFactory<DirectoryBuildCache>>>())
buildCache.registerBuildCacheService(DirectoryBuildCacheServiceFactory::class)
inOrder(buildCache) {
verify(buildCache).registerBuildCacheService(any<Class<DirectoryBuildCache>>(), any<Class<BuildCacheServiceFactory<DirectoryBuildCache>>>())
verifyNoMoreInteractions()
}
}
@Test
fun local() {
val buildCache = mock<BuildCacheConfiguration> {
on { local(any<Class<DirectoryBuildCache>>()) } doReturn mock<DirectoryBuildCache>()
on { local(any<Class<DirectoryBuildCache>>(), any<Action<DirectoryBuildCache>>()) } doReturn mock<DirectoryBuildCache>()
}
buildCache.local<DirectoryBuildCache>()
inOrder(buildCache) {
verify(buildCache).local(DirectoryBuildCache::class.java)
verifyNoMoreInteractions()
}
buildCache.local<DirectoryBuildCache> {}
inOrder(buildCache) {
verify(buildCache).local(any<Class<DirectoryBuildCache>>(), any<Action<DirectoryBuildCache>>())
verifyNoMoreInteractions()
}
}
@Test
fun remote() {
val buildCache = mock<BuildCacheConfiguration> {
on { remote(any<Class<HttpBuildCache>>()) } doReturn mock<HttpBuildCache>()
on { remote(any<Class<HttpBuildCache>>(), any<Action<HttpBuildCache>>()) } doReturn mock<HttpBuildCache>()
}
buildCache.remote<HttpBuildCache>()
inOrder(buildCache) {
verify(buildCache).remote(HttpBuildCache::class.java)
verifyNoMoreInteractions()
}
buildCache.remote<HttpBuildCache> {}
inOrder(buildCache) {
verify(buildCache).remote(any<Class<HttpBuildCache>>(), any<Action<HttpBuildCache>>())
verifyNoMoreInteractions()
}
}
}
| subprojects/kotlin-dsl/src/test/kotlin/org/gradle/kotlin/dsl/BuildCacheConfigurationExtensionsTest.kt | 239210609 |
package io.kotlintest.provided
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.arch.core.executor.TaskExecutor
import io.kotest.core.config.AbstractProjectConfig
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.test.TestCoroutineDispatcher
import kotlinx.coroutines.test.resetMain
import kotlinx.coroutines.test.setMain
object ProjectConfig : AbstractProjectConfig() {
override fun parallelism(): Int = 2
override fun beforeAll() {
super.beforeAll()
ArchTaskExecutor.getInstance().setDelegate(object : TaskExecutor() {
override fun executeOnDiskIO(runnable: Runnable) {
runnable.run()
}
override fun postToMainThread(runnable: Runnable) {
runnable.run()
}
override fun isMainThread(): Boolean {
return true
}
})
Dispatchers.setMain(testDispatcher)
}
val testDispatcher = TestCoroutineDispatcher()
override fun afterAll() {
super.afterAll()
ArchTaskExecutor.getInstance().setDelegate(null)
Dispatchers.resetMain()
}
} | app/src/test/java/io/kotlintest/provided/ProjectConfig.kt | 4138880149 |
/*
* 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.lithography.components
import com.facebook.litho.ComponentScope
import com.facebook.litho.KComponent
import com.facebook.litho.Row
import com.facebook.litho.Style
import com.facebook.litho.core.height
import com.facebook.litho.core.margin
import com.facebook.litho.core.padding
import com.facebook.litho.dp
import com.facebook.litho.drawableColor
import com.facebook.litho.flexbox.flex
import com.facebook.litho.kotlin.widget.Text
import com.facebook.litho.px
import com.facebook.litho.sp
import com.facebook.litho.view.background
import com.facebook.samples.litho.kotlin.lithography.data.Decade
import com.facebook.yoga.YogaAlign.CENTER
class DecadeSeparator(val decade: Decade) : KComponent() {
override fun ComponentScope.render() =
Row(alignItems = CENTER, style = Style.padding(16.dp).background(drawableColor(0xFFFAFAFA))) {
child(Row(style = Style.height(1.px).flex(grow = 1f).background(drawableColor(0xFFAAAAAA))))
child(
Text(
text = "${decade.year}",
textSize = 14.sp,
textColor = 0xFFAAAAAA.toInt(),
style = Style.margin(horizontal = 10.dp).flex(shrink = 0f)))
child(Row(style = Style.height(1.px).flex(grow = 1f).background(drawableColor(0xFFAAAAAA))))
}
}
| sample/src/main/java/com/facebook/samples/litho/kotlin/lithography/components/DecadeSeparator.kt | 594683695 |
package rcgonzalezf.org.weather.common.analytics
interface AnalyticsDataCatalog {
interface WeatherListActivity {
companion object {
const val NO_NETWORK_SEARCH = "NO_NETWORK_SEARCH"
const val MANUAL_SEARCH = "MANUAL_SEARCH"
const val LOCATION_SEARCH = "LOCATION_SEARCH"
const val SEARCH_COMPLETED = "SEARCH_COMPLETED"
}
}
interface SettingsActivity {
companion object {
const val TEMP_UNITS_TOGGLE = "TEMP_UNITS_TOGGLE"
const val ON_NAME = "ON_NAME"
const val ON_LOAD = "ON_LOAD"
}
}
}
| weather-app/src/main/java/rcgonzalezf/org/weather/common/analytics/AnalyticsDataCatalog.kt | 1249549112 |
package me.camsteffen.polite.di
import dagger.Component
import dagger.android.AndroidInjectionModule
import dagger.android.AndroidInjector
import me.camsteffen.polite.Polite
import javax.inject.Singleton
@Singleton
@Component(
modules = [
AndroidInjectionModule::class,
AppModule::class
]
)
interface AppComponent : AndroidInjector<Polite> {
@Component.Factory
interface Factory : AndroidInjector.Factory<Polite>
}
| src/main/java/me/camsteffen/polite/di/AppComponent.kt | 3521860162 |
package me.camsteffen.polite.model
import android.content.Context
import me.camsteffen.polite.R
import me.camsteffen.polite.rule.ScheduleRuleSchedule
import org.threeten.bp.DayOfWeek
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class DefaultRules
@Inject constructor(val context: Context) {
fun calendar() = CalendarRule(
id = Rule.NEW_ID,
name = context.getString(R.string.rule_default_name),
enabled = RuleDefaults.enabled,
vibrate = RuleDefaults.vibrate,
busyOnly = false,
calendarIds = emptySet(),
matchBy = CalendarEventMatchBy.ALL,
inverseMatch = false,
keywords = emptySet()
)
fun schedule() = ScheduleRule(
id = Rule.NEW_ID,
name = context.getString(R.string.rule_default_name),
enabled = RuleDefaults.enabled,
vibrate = RuleDefaults.vibrate,
schedule = ScheduleRuleSchedule(
12, 0,
13, 0,
DayOfWeek.MONDAY,
DayOfWeek.TUESDAY,
DayOfWeek.WEDNESDAY,
DayOfWeek.THURSDAY,
DayOfWeek.FRIDAY
)
)
}
private object RuleDefaults {
const val enabled = true
const val vibrate = false
}
| src/main/java/me/camsteffen/polite/model/DefaultRules.kt | 57439866 |
package chat.willow.warren.handler.rpl.isupport
import chat.willow.kale.IMetadataStore
import chat.willow.kale.KaleHandler
import chat.willow.kale.irc.message.rfc1459.rpl.Rpl005Message
import chat.willow.warren.extension.monitor.MonitorState
import chat.willow.warren.helper.loggerFor
import chat.willow.warren.state.ParsingState
class Rpl005Handler(val state: ParsingState,
val monitorState: MonitorState,
val prefixHandler: IRpl005PrefixHandler,
val channelModesHandler: IRpl005ChanModesHandler,
val channelTypesHandler: IRpl005ChanTypesHandler,
val caseMappingHandler: IRpl005CaseMappingHandler,
val monitorHandler: IRpl005MonitorHandler) : KaleHandler<Rpl005Message.Message>(Rpl005Message.Message.Parser) {
private val LOGGER = loggerFor<Rpl005Handler>()
override fun handle(message: Rpl005Message.Message, metadata: IMetadataStore) {
LOGGER.debug("got isupport additions: ${message.tokens}")
for ((key, value) in message.tokens) {
if (value == null) {
continue
}
when (key) {
"PREFIX" -> prefixHandler.handle(value, state.userPrefixes)
"CHANMODES" -> channelModesHandler.handle(value, state.channelModes)
"CHANTYPES" -> channelTypesHandler.handle(value, state.channelTypes)
"CASEMAPPING" -> caseMappingHandler.handle(value, state.caseMapping)
"MONITOR" -> monitorHandler.handle(value, monitorState)
}
}
}
} | src/main/kotlin/chat/willow/warren/handler/rpl/isupport/Rpl005Handler.kt | 482695963 |
/*
* Copyright (C) 2020 Jakub Ksiezniak
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.github.jksiezni.xpra.config
import android.content.Intent
import android.os.Bundle
import android.text.TextUtils
import android.util.Patterns
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.widget.Toast
import androidx.preference.EditTextPreference
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.Preference.SummaryProvider
import androidx.preference.PreferenceFragmentCompat
import com.github.jksiezni.xpra.R
import java.util.regex.Pattern
class ServerDetailsFragment : PreferenceFragmentCompat() {
private lateinit var dataStore: ServerDetailsDataStore
init {
setHasOptionsMenu(true)
}
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
val serverDetails = requireArguments().getSerializable(KEY_SERVER_DETAILS) as ServerDetails
val dao = ConfigDatabase.getInstance().configs
dataStore = ServerDetailsDataStore(serverDetails, dao)
preferenceManager.preferenceDataStore = dataStore
addPreferencesFromResource(R.xml.server_details_preference)
setupPreferences()
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.server_details_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.action_save -> if (save()) {
parentFragmentManager.popBackStack()
}
android.R.id.home -> parentFragmentManager.popBackStack()
}
return super.onOptionsItemSelected(item)
}
private fun setupPreferences() {
findPreference<Preference>(ServerDetailsDataStore.PREF_NAME)?.summaryProvider = EditTextSummaryProvider(getString(R.string.enter_unique_name))
findPreference<Preference>(ServerDetailsDataStore.PREF_HOST)?.summaryProvider = EditTextSummaryProvider(getString(R.string.enter_unique_name))
findPreference<Preference>(ServerDetailsDataStore.PREF_USERNAME)?.summaryProvider = EditTextSummaryProvider(getString(R.string.enter_unique_name))
findPreference<Preference>(ServerDetailsDataStore.PREF_DISPLAY_ID)?.summaryProvider = DisplayIdSummaryProvider(getString(R.string.automatic))
findPreference<ListPreference>(ServerDetailsDataStore.PREF_CONNECTION_TYPE)?.let {
it.setOnPreferenceChangeListener { _, newValue ->
setSshPreferencesEnabled(ConnectionType.SSH.name == newValue)
true
}
setSshPreferencesEnabled(ConnectionType.SSH.name == it.value)
}
findPreference<Preference>(ServerDetailsDataStore.PREF_PRIVATE_KEY)?.setOnPreferenceClickListener {
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "application/x-pem-file" // https://pki-tutorial.readthedocs.io/en/latest/mime.html
}
startActivity(intent)
true
}
}
private fun save(): Boolean {
return if (validate(dataStore.serverDetails)) {
dataStore.save()
true
} else {
false
}
}
private fun setSshPreferencesEnabled(enabled: Boolean) {
val portPref = findPreference<EditTextPreference>(ServerDetailsDataStore.PREF_PORT)
if (enabled) {
if ("10000" == portPref?.text) {
portPref.text = "22"
}
} else {
if ("22" == portPref?.text) {
portPref.text = "10000"
}
}
findPreference<Preference>(ServerDetailsDataStore.PREF_USERNAME)?.isEnabled = enabled
findPreference<Preference>(ServerDetailsDataStore.PREF_PRIVATE_KEY)?.isEnabled = enabled
}
private fun validateName(name: String?): Boolean {
if (name == null || name.isEmpty()) {
Toast.makeText(activity, "The connection name must not be empty.", Toast.LENGTH_LONG).show()
return false
}
// else if (!connectionDao.queryForEq("name", name).isEmpty()) {
// Toast.makeText(getActivity(), "The connection with that name exists already.", Toast.LENGTH_LONG).show();
// return false;
// }
return true
}
private fun validateHostname(host: String?): Boolean {
if (host == null || host.isEmpty()) {
Toast.makeText(activity, "The hostname must not be empty.", Toast.LENGTH_LONG).show()
return false
} else if (!HOSTNAME_PATTERN.matcher(host).matches()) {
val matcher = Patterns.IP_ADDRESS.matcher(host)
if (!matcher.matches()) {
Toast.makeText(activity, "Invalid hostname: $host", Toast.LENGTH_LONG).show()
return false
}
}
return true
}
private fun validate(serverDetails: ServerDetails): Boolean {
return validateName(serverDetails.name) && validateHostname(serverDetails.host)
}
companion object {
private const val KEY_SERVER_DETAILS = "server_details"
private val HOSTNAME_PATTERN = Pattern.compile("^[0-9a-zA-Z_\\-.]*$")
fun create(serverDetails: ServerDetails): ServerDetailsFragment {
return ServerDetailsFragment().apply {
arguments = Bundle().apply {
putSerializable(KEY_SERVER_DETAILS, serverDetails)
}
}
}
}
}
class EditTextSummaryProvider(private val emptySummary: String) : SummaryProvider<EditTextPreference> {
override fun provideSummary(preference: EditTextPreference): CharSequence {
return if (TextUtils.isEmpty(preference.text)) {
emptySummary
} else {
preference.text
}
}
}
class DisplayIdSummaryProvider(private val emptySummary: String) : SummaryProvider<EditTextPreference> {
override fun provideSummary(preference: EditTextPreference): CharSequence {
val text = preference.text
return if (TextUtils.isEmpty(text) || "-1" == text) {
emptySummary
} else {
text
}
}
}
| xpra-client-android/src/main/java/com/github/jksiezni/xpra/config/ServerDetailsFragment.kt | 2674168596 |
/*
* 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 androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.SupportMapFragment
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.maps.model.MarkerOptions
/**
* This shows how to create a simple activity with a map and a marker on the map.
*/
class BasicMapDemoActivity : AppCompatActivity(), OnMapReadyCallback {
val SYDNEY = LatLng(-33.862, 151.21)
val ZOOM_LEVEL = 13f
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_basic_map_demo)
val mapFragment : SupportMapFragment? =
supportFragmentManager.findFragmentById(R.id.map) as? SupportMapFragment
mapFragment?.getMapAsync(this)
}
/**
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just move the camera to Sydney and add a marker in Sydney.
*/
override fun onMapReady(googleMap: GoogleMap) {
with(googleMap) {
moveCamera(CameraUpdateFactory.newLatLngZoom(SYDNEY, ZOOM_LEVEL))
addMarker(MarkerOptions().position(SYDNEY))
}
}
}
| ApiDemos/kotlin/app/src/gms/java/com/example/kotlindemos/BasicMapDemoActivity.kt | 810625100 |
package com.nonnulldev.underling.injection.module
import com.nonnulldev.underling.data.local.PlayerRepo
import com.nonnulldev.underling.data.local.RealmPlayerRepo
import dagger.Binds
import dagger.Module
@Module
abstract class DataModule {
@Binds
abstract fun bindPlayerRepo(playerRepo: RealmPlayerRepo) : PlayerRepo
}
| app/src/main/kotlin/com/nonnulldev/underling/injection/module/DataModule.kt | 3606939468 |
package no.tornado.tornadofx.idea.facet
import com.intellij.facet.FacetConfiguration
import com.intellij.facet.ui.FacetEditorContext
import com.intellij.facet.ui.FacetValidatorsManager
import com.intellij.openapi.Disposable
import org.jdom.Element
class TornadoFXFacetConfiguration : FacetConfiguration, Disposable {
override fun createEditorTabs(editorContext: FacetEditorContext, validatorsManager: FacetValidatorsManager) =
arrayOf(TornadoFXFacetEditorTab(editorContext))
override fun readExternal(element: Element?) {
}
override fun writeExternal(element: Element?) {
}
override fun dispose() {
}
} | src/main/kotlin/no/tornado/tornadofx/idea/facet/TornadoFXFacetConfiguration.kt | 1427548334 |
package com.wcaokaze.japanecraft
class RomajiConverter(romajiMap: Map<String, Output>) {
private val romajiTable = romajiMap.toTrie()
operator fun invoke(romajiStr: String): String {
val romajiBuffer = StringBuffer(romajiStr)
fun StringBuffer.parseHeadRomaji(): String {
val strBuffer = this
fun loop(strIdx: Int, prevNode: Trie<Output>): String {
val node = prevNode[strBuffer[strIdx]]
fun confirm(strIdx: Int, node: Trie<Output>): String {
val output = node.value
val jpStr = output?.jpChar ?: strBuffer.substring(0..strIdx)
strBuffer.delete(0, strIdx + 1)
if (output != null) strBuffer.insert(0, output.nextInput)
return jpStr
}
return when {
node == null -> confirm(strIdx - 1, prevNode)
node.childCount == 0 -> confirm(strIdx, node)
strIdx == strBuffer.lastIndex -> confirm(strIdx, node)
else -> return loop(strIdx + 1, node)
}
}
val trieNode = romajiTable[romajiBuffer.first()]
if (trieNode != null) {
return loop(0, romajiTable)
} else {
val char = romajiBuffer.first()
romajiBuffer.deleteCharAt(0)
return String(charArrayOf(char))
}
}
return buildString {
while (romajiBuffer.isNotEmpty()) {
append(romajiBuffer.parseHeadRomaji())
}
}
}
class Output(val jpChar: String, val nextInput: String)
}
| src/main/kotlin/com/wcaokaze/japanecraft/RomajiConverter.kt | 1914172149 |
/*
* Copyright (C) 2018 Yaroslav Mytkalyk
*
* 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.doctoror.fuckoffmusicplayer.presentation.recentactivity
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.doctoror.fuckoffmusicplayer.R
import com.doctoror.fuckoffmusicplayer.databinding.FragmentRecentActivityBinding
import com.doctoror.fuckoffmusicplayer.presentation.base.BaseFragment
import com.doctoror.fuckoffmusicplayer.presentation.util.ViewUtils
import com.doctoror.fuckoffmusicplayer.presentation.widget.SpacesItemDecoration
import dagger.android.support.AndroidSupportInjection
import javax.inject.Inject
class RecentActivityFragment : BaseFragment() {
@Inject
lateinit var presenter: RecentActivityPresenter
@Inject
lateinit var viewModel: RecentActivityViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AndroidSupportInjection.inject(this)
setHasOptionsMenu(true)
if (savedInstanceState != null) {
presenter.restoreInstanceState(savedInstanceState)
}
lifecycle.addObserver(presenter)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
presenter.onSaveInstanceState(outState)
}
override fun onDestroy() {
super.onDestroy()
lifecycle.removeObserver(presenter)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View {
val binding = DataBindingUtil.inflate<FragmentRecentActivityBinding>(inflater,
R.layout.fragment_recent_activity, container, false)
setupRecyclerView(binding.recyclerView)
binding.model = viewModel
binding.root.findViewById<View>(R.id.btnRequest).setOnClickListener {
presenter.requestPermission()
}
val adapter = RecentActivityRecyclerAdapter(requireContext())
adapter.setOnAlbumClickListener { position, id, album ->
presenter.onAlbumClick(id, album) {
ViewUtils.getItemView(binding.recyclerView, position)
}
}
viewModel.recyclerAdapter.set(adapter)
return binding.root
}
private fun setupRecyclerView(recyclerView: RecyclerView) {
val columns = resources.getInteger(R.integer.recent_activity_grid_columns)
val lm = GridLayoutManager(activity, columns)
lm.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
val adapter = recyclerView.adapter ?: return 1
return when (adapter.getItemViewType(position)) {
RecentActivityRecyclerAdapter.VIEW_TYPE_HEADER -> columns
else -> 1
}
}
}
recyclerView.layoutManager = lm
recyclerView.addItemDecoration(SpacesItemDecoration(
resources.getDimensionPixelSize(R.dimen.recent_activity_grid_spacing)))
}
}
| presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/recentactivity/RecentActivityFragment.kt | 2739001382 |
// 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.psi.element
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiElement
import com.vladsch.flexmark.util.sequence.LineAppendable
import com.vladsch.md.nav.actions.handlers.util.PsiEditContext
import com.vladsch.md.nav.psi.util.MdPsiBundle
import com.vladsch.md.nav.psi.util.MdPsiImplUtil
import com.vladsch.md.nav.settings.MdApplicationSettings
import com.vladsch.md.nav.util.format.CharLinePrefixMatcher
import com.vladsch.md.nav.util.format.LinePrefixMatcher
import icons.MdIcons
import javax.swing.Icon
class MdAsideBlockImpl(node: ASTNode) : MdIndentingCompositeImpl(node), MdAsideBlock, MdStructureViewPresentableElement, MdStructureViewPresentableItem, MdBreadcrumbElement {
companion object {
@JvmField
val INDENT_PREFIX = "| "
private val INDENT_PREFIX_MATCHER = CharLinePrefixMatcher('|')
}
override fun isTextStart(node: ASTNode): Boolean {
return node !== node.firstChildNode
}
override fun getPrefixMatcher(editContext: PsiEditContext): LinePrefixMatcher {
return INDENT_PREFIX_MATCHER
}
override fun removeLinePrefix(lines: LineAppendable, indentColumns: IntArray, isFirstChild: Boolean, editContext: PsiEditContext) {
removeLinePrefix(lines, indentColumns, false, editContext, INDENT_PREFIX_MATCHER, 0)
}
override fun getIcon(flags: Int): Icon? {
return MdIcons.Element.ASIDE_BLOCK
}
override fun getPresentableText(): String? {
return MdPsiBundle.message("aside-block")
}
override fun getLocationString(): String? {
return null
}
override fun getStructureViewPresentation(): ItemPresentation {
return MdPsiImplUtil.getPresentation(this)
}
fun getBlockQuoteNesting(): Int {
var nesting = 1
var parent = parent
while (parent is MdAsideBlock) {
nesting++
parent = parent.parent
}
return nesting
}
override fun getBreadcrumbInfo(): String {
// val message = PsiBundle.message("block-quote")
// val nesting = getBlockQuoteNesting()
// return if (nesting > 1) "$message ×$nesting" else message
val settings = MdApplicationSettings.instance.documentSettings
if (settings.showBreadcrumbText) {
return "|"
}
return MdPsiBundle.message("aside-block")
}
override fun getBreadcrumbTooltip(): String? {
return null
}
override fun getBreadcrumbTextElement(): PsiElement? {
return null
}
}
| src/main/java/com/vladsch/md/nav/psi/element/MdAsideBlockImpl.kt | 2525113304 |
/*
* Copyright 2020 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spinnaker.kork.plugins
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import strikt.api.expectThat
import strikt.assertions.isEqualTo
import strikt.assertions.isFalse
import strikt.assertions.isTrue
class SpinnakerServiceVersionManagerTest : JUnit5Minutests {
fun tests() = rootContext<Fixture> {
fixture {
Fixture()
}
test("Service version satisfies plugin requirement constraint") {
val satisfiedConstraint = subject.checkVersionConstraint(
"0.0.9",
"$serviceName<=1.0.0"
)
expectThat(satisfiedConstraint).isTrue()
}
test("Service version does not satisfies plugin requirement constraint with upper limit") {
val satisfiedConstraint = subject.checkVersionConstraint(
"1.0.1",
"$serviceName<=1.0.0"
)
expectThat(satisfiedConstraint).isFalse()
}
test("Service version does not satisfy plugin requirement constraint with lower limit") {
val satisfiedConstraint = subject.checkVersionConstraint(
"0.0.9",
"$serviceName>=1.0.0"
)
expectThat(satisfiedConstraint).isFalse()
}
test("Service version satisfy plugin requirement constraint") {
val satisfiedConstraint = subject.checkVersionConstraint(
"1.0.0",
"$serviceName>=1.0.0"
)
expectThat(satisfiedConstraint).isTrue()
}
test("Service version satisfy plugin requirement constraint range") {
val satisfiedConstraint = subject.checkVersionConstraint(
"1.0.5",
"$serviceName>=1.0.0 & <1.1.0"
)
expectThat(satisfiedConstraint).isTrue()
}
test("Service version does not satisfy plugin requirement constraint range with upper limit") {
val satisfiedConstraint = subject.checkVersionConstraint(
"1.1.0",
"$serviceName>=1.0.0 & <1.1.0"
)
expectThat(satisfiedConstraint).isFalse()
}
test("Service version does not satisfy plugin requirement constraint range with lower limit") {
val satisfiedConstraint = subject.checkVersionConstraint(
"0.0.9",
"$serviceName>=1.0.0 & <1.1.0"
)
expectThat(satisfiedConstraint).isFalse()
}
test("Plugin version X is less than plugin version Y by -1") {
val x = "2.9.8"
val y = "2.9.9"
val comparisonResult = subject.compareVersions(x, y)
expectThat(comparisonResult).isEqualTo(-1)
}
test("Plugin version X is greater than plugin version Y by 1") {
val x = "3.0.0"
val y = "2.0.0"
val comparisonResult = subject.compareVersions(x, y)
expectThat(comparisonResult).isEqualTo(1)
}
test("Empty requires is allowed") {
val satisfiedConstraint = subject.checkVersionConstraint("0.0.9", "")
expectThat(satisfiedConstraint).isTrue()
}
}
private class Fixture {
val serviceName = "orca"
val subject = SpinnakerServiceVersionManager(serviceName)
}
}
| kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/SpinnakerServiceVersionManagerTest.kt | 372372153 |
package com.natpryce.krouton
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import dev.minutest.experimental.randomTest
import dev.minutest.junit.JUnit5Minutests
import dev.minutest.rootContext
import org.junit.platform.commons.annotation.Testable
@Testable
fun `encoding and decoding`() = rootContext {
val examples = listOf(
listOf("hits", "zz top") to "/hits/zz%20top",
listOf("hits", "ac/dc") to "/hits/ac%2Fdc",
listOf("hits", "? and the mysterians") to "/hits/%3F%20and%20the%20mysterians",
listOf("hits", "operation: cliff clavin") to "/hits/operation%3A%20cliff%20clavin",
listOf("hits", "!!!") to "/hits/%21%21%21",
listOf("hits", "x+y") to "/hits/x%2By"
)
examples.forEach { (elements, encoded) ->
test("$elements <-> $encoded") {
assertThat("encoding", joinPath(elements, ::encodePathElement), equalTo(encoded))
assertThat("decoding", splitPath(encoded), equalTo(elements))
}
}
test("can decode a plus if it receives one") {
// Testing this as a special case because we call through to the UrlDecoder after making the text not
// actually x-www-url-form-encoded format.
assertThat("decoding", splitPath("/hits/x+y"), equalTo(listOf("hits", "x+y")))
}
randomTest("fuzzing") { random, _ ->
repeat(100) { _ ->
val original = random.nextBytes(16).toString(Charsets.UTF_8)
val encoded = encodePathElement(original)
val decoded = decodePathElement(encoded)
assertThat(decoded, equalTo(original))
}
}
}
| src/test/kotlin/com/natpryce/krouton/EncodingAndDecodingTests.kt | 1126644475 |
package com.garpr.android.features.splash
import androidx.annotation.AnyThread
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.garpr.android.data.models.FavoritePlayer
import com.garpr.android.data.models.Region
import com.garpr.android.features.common.viewModels.BaseViewModel
import com.garpr.android.misc.Schedulers
import com.garpr.android.misc.Timber
import com.garpr.android.preferences.GeneralPreferenceStore
import com.garpr.android.repositories.IdentityRepository
import com.garpr.android.repositories.RegionRepository
class SplashScreenViewModel(
private val generalPreferenceStore: GeneralPreferenceStore,
private val identityRepository: IdentityRepository,
private val regionRepository: RegionRepository,
private val schedulers: Schedulers,
private val timber: Timber
) : BaseViewModel() {
private val _stateLiveData = MutableLiveData<State>()
val stateLiveData: LiveData<State> = _stateLiveData
private var state: State = State(
isSplashScreenComplete = generalPreferenceStore.hajimeteKimasu.get() == false,
region = regionRepository.region
)
set(value) {
field = value
_stateLiveData.postValue(value)
}
companion object {
private const val TAG = "SplashScreenViewModel"
}
init {
initListeners()
}
private fun initListeners() {
disposables.add(generalPreferenceStore.hajimeteKimasu.observable
.subscribeOn(schedulers.background)
.observeOn(schedulers.background)
.subscribe { hajimeteKimasu ->
refreshIsSplashScreenComplete(hajimeteKimasu.orElse(false))
})
disposables.add(identityRepository.identityObservable
.subscribeOn(schedulers.background)
.observeOn(schedulers.background)
.subscribe { identity ->
refreshIdentity(identity.orNull())
})
disposables.add(regionRepository.observable
.subscribeOn(schedulers.background)
.observeOn(schedulers.background)
.subscribe { region ->
refreshRegion(region)
})
}
@AnyThread
private fun refreshIsSplashScreenComplete(hajimeteKimasu: Boolean) {
state = state.copy(isSplashScreenComplete = !hajimeteKimasu)
}
@AnyThread
private fun refreshIdentity(identity: FavoritePlayer?) {
state = state.copy(identity = identity)
}
@AnyThread
private fun refreshRegion(region: Region) {
state = state.copy(region = region)
}
fun removeIdentity() {
identityRepository.removeIdentity()
}
fun setSplashScreenComplete() {
timber.d(TAG, "splash screen has been completed")
generalPreferenceStore.hajimeteKimasu.set(false)
}
data class State(
val isSplashScreenComplete: Boolean,
val identity: FavoritePlayer? = null,
val region: Region
)
}
| smash-ranks-android/app/src/main/java/com/garpr/android/features/splash/SplashScreenViewModel.kt | 1467522707 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.psi.util.PsiTreeUtil
import org.rust.lang.core.psi.RsTypeReference
val RsTypeReference.typeElement: RsTypeElement?
get() = PsiTreeUtil.getStubChildOfType(this, RsTypeElement::class.java)
| src/main/kotlin/org/rust/lang/core/psi/ext/RsTypeReference.kt | 4166753763 |
/*
* Copyright (C) 2019. OpenLattice, Inc.
*
* 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/>.
*
* You can contact the owner of the copyright at [email protected]
*
*
*/
package com.openlattice.hazelcast.serializers
import com.hazelcast.nio.ObjectDataInput
import com.hazelcast.nio.ObjectDataOutput
import com.kryptnostic.rhizome.hazelcast.serializers.UUIDStreamSerializerUtils
import com.kryptnostic.rhizome.pods.hazelcast.SelfRegisteringStreamSerializer
import com.openlattice.assembler.AssemblerConnectionManager
import com.openlattice.assembler.AssemblerConnectionManagerDependent
import com.openlattice.assembler.processors.UpdateMaterializedEntitySetProcessor
import com.openlattice.hazelcast.StreamSerializerTypeIds
import org.springframework.stereotype.Component
@Component
class UpdateMaterializedEntitySetProcessorStreamSerializer
: SelfRegisteringStreamSerializer<UpdateMaterializedEntitySetProcessor>, AssemblerConnectionManagerDependent<Void?> {
private lateinit var acm: AssemblerConnectionManager
override fun getTypeId(): Int {
return StreamSerializerTypeIds.UPDATE_MATERIALIZED_ENTITY_SET_PROCESSOR.ordinal
}
override fun getClazz(): Class<out UpdateMaterializedEntitySetProcessor> {
return UpdateMaterializedEntitySetProcessor::class.java
}
override fun write(output: ObjectDataOutput, obj: UpdateMaterializedEntitySetProcessor) {
EntitySetStreamSerializer.serialize(output, obj.entitySet)
output.writeInt(obj.materializablePropertyTypes.size)
obj.materializablePropertyTypes.forEach { (propertyTypeId, propertyType) ->
UUIDStreamSerializerUtils.serialize(output, propertyTypeId)
PropertyTypeStreamSerializer.serialize(output, propertyType)
}
}
override fun read(input: ObjectDataInput): UpdateMaterializedEntitySetProcessor {
val entitySet = EntitySetStreamSerializer.deserialize(input)
val size = input.readInt()
val materializablePropertyTypes = ((0 until size).map {
UUIDStreamSerializerUtils.deserialize(input) to PropertyTypeStreamSerializer.deserialize(input)
}.toMap())
return UpdateMaterializedEntitySetProcessor(
entitySet, materializablePropertyTypes
).init(acm)
}
override fun init(acm: AssemblerConnectionManager): Void? {
this.acm = acm
return null
}
} | src/main/kotlin/com/openlattice/hazelcast/serializers/UpdateMaterializedEntitySetProcessorStreamSerializer.kt | 3860547830 |
package com.takusemba.spotlight.shape
import android.animation.TimeInterpolator
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.PointF
import android.view.animation.DecelerateInterpolator
import java.util.concurrent.TimeUnit
/**
* [Shape] of Circle with customizable radius.
*/
class Circle @JvmOverloads constructor(
private val radius: Float,
override val duration: Long = DEFAULT_DURATION,
override val interpolator: TimeInterpolator = DEFAULT_INTERPOLATOR
) : Shape {
override fun draw(canvas: Canvas, point: PointF, value: Float, paint: Paint) {
canvas.drawCircle(point.x, point.y, value * radius, paint)
}
companion object {
val DEFAULT_DURATION = TimeUnit.MILLISECONDS.toMillis(500)
val DEFAULT_INTERPOLATOR = DecelerateInterpolator(2f)
}
}
| spotlight/src/main/java/com/takusemba/spotlight/shape/Circle.kt | 1934925555 |
package com.hackerrank
import java.util.*
fun main(args: Array<String>) {
val scan = Scanner(System.`in`)
val n = scan.nextInt()
val scores = Stack<Int>()
for (i in 0..n - 1) {
val score = scan.nextInt()
if (i == 0 || scores.peek() != score) {
scores.push(score)
}
}
val m = scan.nextInt()
for (i in 0..m - 1) {
val alice = scan.nextInt()
while (!scores.empty() && scores.peek() <= alice) {
scores.pop()
}
println(if (scores.isEmpty()) "1" else scores.size + 1)
}
} | src/main/kotlin/com/hackerrank/ClimbingTheLeaderboard.kt | 3084794042 |
package org.http4k.routing.inspect
import org.http4k.routing.RouterDescription
import org.http4k.routing.RouterMatch
import org.http4k.routing.RouterMatch.MatchedWithoutHandler
import org.http4k.routing.RouterMatch.MatchingHandler
import org.http4k.routing.RouterMatch.MethodNotMatched
import org.http4k.routing.RouterMatch.Unmatched
import org.http4k.routing.inspect.EscapeMode.Ansi
fun RouterDescription.prettify(depth: Int = 0, escape: EscapeMode = Ansi) = PrettyNode(this).prettify(depth, escape)
fun RouterMatch.prettify(depth: Int = 0, escape: EscapeMode = Ansi) = PrettyNode(this).prettify(depth, escape)
private data class PrettyNode(val name: String, val textStyle: TextStyle, val groupStyle: TextStyle, val children: List<PrettyNode>) {
constructor(description: RouterDescription) : this(
description.description,
TextStyle(ForegroundColour.Cyan),
TextStyle(),
description.children.map { PrettyNode(it) }
)
constructor(match: RouterMatch) : this(
match.description.description,
match.resolveStyle(),
match.resolveStyle(),
match.subMatches.map { PrettyNode(it) }
)
fun prettify(depth: Int = 0, escapeMode: EscapeMode = Ansi) = when (name) {
"or" -> orRendering(depth, escapeMode)
"and" -> andRenderer(depth, escapeMode)
else -> name.styled(textStyle, escapeMode)
}
private fun orRendering(depth: Int, escapeMode: EscapeMode): String =
if (children.isEmpty()) {
name.styled(textStyle, escapeMode)
} else {
val nIndent = (" ".repeat(depth * 2)).let{"\n$it"}
val prefix = if(depth == 0 /*no leading newline*/) "" else nIndent
prefix +
"(".styled(groupStyle, escapeMode) +
children.joinToString("$nIndent ${name.styled(groupStyle, escapeMode)} ") { it.prettify(depth + 1, escapeMode) } +
")".styled(groupStyle, escapeMode)
}
private fun andRenderer(depth: Int, escapeMode: EscapeMode): String =
if (children.isEmpty()) {
name.styled(textStyle, escapeMode)
} else {
"(".styled(groupStyle, escapeMode) +
children.joinToString(" ${name.styled(groupStyle, escapeMode)} ") { it.prettify(depth + 1, escapeMode) } +
")".styled(groupStyle, escapeMode)
}
}
private fun RouterMatch.resolveStyle(): TextStyle = when (this) {
is MatchingHandler, is MatchedWithoutHandler -> TextStyle(ForegroundColour.Green)
is MethodNotMatched, is Unmatched -> TextStyle(ForegroundColour.Red, variation = Variation.Strikethrough)
}
| http4k-core/src/main/kotlin/org/http4k/routing/inspect/inspection.kt | 3144971492 |
package org.http4k.server
import io.undertow.server.HttpServerExchange
import io.undertow.util.HttpString
import org.http4k.core.HttpHandler
import org.http4k.core.Method
import org.http4k.core.Request
import org.http4k.core.RequestSource
import org.http4k.core.Response
import org.http4k.core.Uri
import org.http4k.core.safeLong
import org.http4k.core.then
import org.http4k.core.toParametersMap
import org.http4k.filter.ServerFilters
/**
* Exposed to allow for insertion into a customised Undertow server instance
*/
class Http4kUndertowHttpHandler(handler: HttpHandler) : io.undertow.server.HttpHandler {
private val safeHandler = ServerFilters.CatchAll().then(handler)
private fun Response.into(exchange: HttpServerExchange) {
exchange.statusCode = status.code
headers.toParametersMap().forEach { (name, values) ->
exchange.responseHeaders.putAll(HttpString(name), values.toList())
}
body.stream.use { it.copyTo(exchange.outputStream) }
}
private fun HttpServerExchange.asRequest(): Request =
Request(Method.valueOf(requestMethod.toString()), Uri.of("$relativePath?$queryString"))
.headers(requestHeaders
.flatMap { header -> header.map { header.headerName.toString() to it } })
.body(inputStream, requestHeaders.getFirst("Content-Length").safeLong())
.source(RequestSource(sourceAddress.hostString, sourceAddress.port, requestScheme))
override fun handleRequest(exchange: HttpServerExchange) = safeHandler(exchange.asRequest()).into(exchange)
}
| http4k-server/undertow/src/main/kotlin/org/http4k/server/Http4kUndertowHttpHandler.kt | 3486529324 |
/*
* Copyright (c) 2016. Michael Buhot [email protected]
*/
package mbuhot.eskotlin.query.fulltext
import mbuhot.eskotlin.query.should_render_as
import org.junit.Test
class MultiMatchTest {
@Test
fun `test multi_match`() {
val query = multi_match {
query = "this is a test"
fields = listOf("subject", "message")
}
query should_render_as """
{
"multi_match": {
"query": "this is a test",
"fields": ["message^1.0", "subject^1.0"],
"type": "best_fields",
"operator": "OR",
"slop": 0,
"prefix_length": 0,
"max_expansions": 50,
"zero_terms_query": "NONE",
"auto_generate_synonyms_phrase_query": true,
"fuzzy_transpositions": true,
"boost": 1.0
}
}
"""
}
@Test
fun `test multi_match with best_fields type`() {
val query = multi_match {
query = "brown fox"
type = "best_fields"
fields = listOf("subject", "message")
tie_breaker = 0.3f
}
query should_render_as """
{
"multi_match": {
"query": "brown fox",
"fields": ["message^1.0", "subject^1.0"],
"type": "best_fields",
"operator": "OR",
"slop": 0,
"prefix_length": 0,
"max_expansions": 50,
"tie_breaker": 0.3,
"zero_terms_query": "NONE",
"auto_generate_synonyms_phrase_query": true,
"fuzzy_transpositions": true,
"boost": 1.0
}
}
"""
}
@Test
fun `test multi_match with operator`() {
val query = multi_match {
query = "Will Smith"
type = "cross_fields"
fields = listOf("first_name", "last_name")
operator = "and"
}
query should_render_as """
{
"multi_match": {
"query": "Will Smith",
"fields": ["first_name^1.0", "last_name^1.0"],
"type": "cross_fields",
"operator": "AND",
"slop": 0,
"prefix_length": 0,
"max_expansions": 50,
"zero_terms_query": "NONE",
"auto_generate_synonyms_phrase_query": true,
"fuzzy_transpositions": true,
"boost": 1.0
}
}
"""
}
@Test
fun `test multi_match with analyzer`() {
val query = multi_match {
query = "Jon"
type = "cross_fields"
analyzer = "standard"
fields = listOf("first", "last", "*.edge")
}
query should_render_as """
{
"multi_match": {
"query": "Jon",
"fields": ["*.edge^1.0", "first^1.0", "last^1.0"],
"type": "cross_fields",
"operator": "OR",
"analyzer": "standard",
"slop": 0,
"prefix_length": 0,
"max_expansions": 50,
"zero_terms_query": "NONE",
"auto_generate_synonyms_phrase_query": true,
"fuzzy_transpositions": true,
"boost": 1.0
}
}
"""
}
@Test
fun `test multi_match with boost`() {
val query = multi_match {
query = "this is a test"
fields = listOf("subject","message^2.0")
}
query should_render_as """
{
"multi_match": {
"query": "this is a test",
"fields": ["message^2.0", "subject^1.0"],
"type": "best_fields",
"operator": "OR",
"slop": 0,
"prefix_length": 0,
"max_expansions": 50,
"zero_terms_query": "NONE",
"auto_generate_synonyms_phrase_query": true,
"fuzzy_transpositions": true,
"boost": 1.0
}
}
"""
}
} | src/test/kotlin/mbuhot/eskotlin/query/fulltext/MultiMatchTest.kt | 993536570 |
package org.http4k.cloudnative.env
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import org.http4k.cloudnative.env.Environment.Companion.EMPTY
import org.http4k.cloudnative.env.Environment.Companion.from
import org.http4k.cloudnative.env.EnvironmentKey.k8s.HEALTH_PORT
import org.http4k.cloudnative.env.EnvironmentKey.k8s.SERVICE_PORT
import org.http4k.cloudnative.env.EnvironmentKey.k8s.serviceUriFor
import org.http4k.core.Uri
import org.http4k.core.with
import org.http4k.lens.LensFailure
import org.http4k.lens.composite
import org.http4k.lens.int
import org.http4k.lens.of
import org.http4k.lens.long
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import java.util.Properties
class EnvironmentKeyTest {
private val env = EMPTY
@Test
fun `custom key roundtrip`() {
val lens = EnvironmentKey.int().required("some-value")
assertThrows<LensFailure> { lens(env) }
val withInjectedValue = env.with(lens of 80)
assertThat(lens(withInjectedValue), equalTo(80))
assertThat(withInjectedValue["SOME_VALUE"], equalTo("80"))
assertThat(EnvironmentKey.int().required("SOME_VALUE")(withInjectedValue), equalTo(80))
}
@Test
fun `custom multi key roundtrip`() {
val lens = EnvironmentKey.int().multi.required("some-value")
assertThrows<LensFailure> { lens(env) }
val withInjectedValue = env.with(lens of listOf(80, 81))
assertThat(withInjectedValue["SOME_VALUE"], equalTo("80,81"))
assertThat(EnvironmentKey.int().multi.required("SOME_VALUE")(withInjectedValue), equalTo(listOf(80, 81)))
assertThat(EnvironmentKey.int().multi.required("SOME_VALUE")(from("SOME_VALUE" to "80 , 81 ")), equalTo(listOf(80, 81)))
}
@Test
fun `custom multi key roundtrip with non-standard separator`() {
val customEnv = MapEnvironment.from(Properties(), separator = ";")
val lens = EnvironmentKey.int().multi.required("some-value")
assertThrows<LensFailure> { lens(customEnv) }
val withInjectedValue = customEnv.with(lens of listOf(80, 81))
assertThat(withInjectedValue["SOME_VALUE"], equalTo("80;81"))
assertThat(EnvironmentKey.int().multi.required("SOME_VALUE")(withInjectedValue), equalTo(listOf(80, 81)))
assertThat(EnvironmentKey.int().multi.required("SOME_VALUE")(MapEnvironment.from(listOf("SOME_VALUE" to "80 ; 81 ").toMap().toProperties(), separator = ";")), equalTo(listOf(80, 81)))
}
@Test
fun `value replaced`() {
val single = EnvironmentKey.int().required("value")
val original = env.with(HEALTH_PORT of 81)
assertThat(single(single(2, single(1, original))), equalTo(2))
val multi = EnvironmentKey.int().multi.required("value")
assertThat(
multi(multi(listOf(3, 4), multi(listOf(1, 2), original))),
equalTo(listOf(3, 4))
)
}
@Test
fun `using property method`() {
val MY_GREAT_ENV_VARIABLE by EnvironmentKey.long().of().required()
assertThat(MY_GREAT_ENV_VARIABLE(from("MY_GREAT_ENV_VARIABLE" to "123")), equalTo(123))
}
@Test
fun `can get ports from env`() {
val withPorts = env.with(SERVICE_PORT of 80, HEALTH_PORT of 81)
assertThat(SERVICE_PORT(withPorts), equalTo(80))
assertThat(HEALTH_PORT(withPorts), equalTo(81))
}
@Test
fun `get uri for a service`() {
assertThat(serviceUriFor("myservice")(
from("MYSERVICE_SERVICE_PORT" to "8000")),
equalTo(Uri.of("http://myservice:8000/")))
assertThat(serviceUriFor("myservice")(
from("MYSERVICE_SERVICE_PORT" to "80")),
equalTo(Uri.of("http://myservice/")))
assertThat(serviceUriFor("myservice", true)(
from("MYSERVICE_SERVICE_PORT" to "80")),
equalTo(Uri.of("https://myservice/")))
assertThat(serviceUriFor("myservice")(
from("MYSERVICE_SERVICE_PORT" to "443")),
equalTo(Uri.of("http://myservice/")))
assertThat(serviceUriFor("myservice", true)(
from("MYSERVICE_SERVICE_PORT" to "443")),
equalTo(Uri.of("https://myservice/")))
}
@Test
fun `falls back to value when using environment key`() {
val finalEnv = EMPTY overrides from("FOO" to "bill")
val key = EnvironmentKey.required("FOO")
assertThat(finalEnv[key], equalTo("bill"))
assertThat(key(finalEnv), equalTo("bill"))
}
@Test
fun `composite can use a mixture of overridden and non overridden values`() {
data class Target(val foo: String, val bar: Int, var foobar: Int?)
val finalEnv = from("bar" to "123") overrides from("FOO" to "bill")
val key = EnvironmentKey.composite {
Target(
required("FOO")(it),
int().required("BAR")(it),
int().optional("FOOBAR")(it)
)
}
assertThat(key(finalEnv), equalTo(Target("bill", 123, null)))
}
}
| http4k-cloudnative/src/test/kotlin/org/http4k/cloudnative/env/EnvironmentKeyTest.kt | 1017980295 |
package kodando.rxjs.operators
import kodando.rxjs.JsFunction
import kodando.rxjs.Observable
import kodando.rxjs.fromModule
import kodando.rxjs.import
private val debounceTime_: JsFunction =
fromModule("rxjs/operators") import "debounceTime"
fun <T> Observable<T>.debounceTime(timeInMilliseconds: Int): Observable<T> {
return pipe(debounceTime_.call(this, timeInMilliseconds))
}
| kodando-rxjs/src/main/kotlin/kodando/rxjs/operators/DebounceTime.kt | 3032846817 |
package org.mapdb.benchmark
import java.io.*
import java.util.*
/**
* Benchmark utilities
*/
object Bench{
val propFile = File("target/benchmark.properties")
fun bench(benchName:String=callerName(), body:()->Long){
val many = testScale()>0;
val metric =
if(!many) {
body()
}else{
//run many times and do average
var t=0L;
for(i in 0 until 100)
t += body()
t/100
}
var formatedMetrics = String.format("%12s", String.format("%,d", metric))
println("BENCH: $formatedMetrics - $benchName ")
//load, update and save property file with results
val props = object : Properties(){
//save keys in sorted order
override fun keys(): Enumeration<Any>? {
return Collections.enumeration(TreeSet(keys));
}
}
if(propFile.exists())
props.load(propFile.inputStream().buffered())
props.put(benchName, metric.toString())
val out = propFile.outputStream()
val out2 = out.buffered()
props.store(out2,"mapdb benchmark")
out2.flush()
out.close()
//remove all temp dirs
tempDirs.forEach { tempDeleteRecur(it) }
tempDirs.clear()
}
fun stopwatch(body:()->Unit):Long{
val start = System.currentTimeMillis()
body()
return System.currentTimeMillis() - start
}
/** returns class name and method name of caller from previous stack trace frame */
inline fun callerName():String{
val t = Thread.currentThread().stackTrace
val t0 = t[2]
return t0.className+"."+t0.methodName
}
@JvmStatic fun testScale(): Int {
val prop = System.getProperty("testLong")?:"0"
try {
return Integer.valueOf(prop);
} catch(e:NumberFormatException) {
return 0;
}
}
private val tempDir = System.getProperty("java.io.tmpdir");
private val tempDirs = HashSet<File>()
/*
* Create temporary directory in temp folder.
*/
@JvmStatic fun tempDir(): File {
try {
val stackTrace = Thread.currentThread().stackTrace;
val elem = stackTrace[2];
val prefix = "mapdbTest_"+elem.className+"#"+elem.methodName+":"+elem.lineNumber+"_"
while(true){
val dir = File(tempDir+"/"+prefix+System.currentTimeMillis()+"_"+Math.random());
if(dir.exists())
continue
dir.mkdirs()
tempDirs+=dir
return dir
}
} catch (e: IOException) {
throw IOError(e)
}
}
@JvmStatic fun tempFile(): File {
return File(tempDir(), "benchFile")
}
@JvmStatic fun tempDelete(file: File){
val name = file.getName()
for (f2 in file.getParentFile().listFiles()!!) {
if (f2.name.startsWith(name))
tempDeleteRecur(f2)
}
tempDeleteRecur(file)
}
@JvmStatic fun tempDeleteRecur(file: File) {
if(file.isDirectory){
for(child in file.listFiles())
tempDeleteRecur(child)
}
file.delete()
}
}
| src/test/java/org/mapdb/benchmark/Bench.kt | 4223644473 |
package com.keylesspalace.tusky.util
import android.content.SharedPreferences
fun SharedPreferences.getNonNullString(key: String, defValue: String): String {
return this.getString(key, defValue) ?: defValue
}
| app/src/main/java/com/keylesspalace/tusky/util/SharedPreferencesExtensions.kt | 573294662 |
package components.progressBar
import components.Component
import javax.swing.JComponent
/**
* Created by vicboma on 05/12/16.
*/
interface Panel : Component<JComponent> {
val progressBar : ProgressBar?
val textArea : TextArea?
} | 09-start-async-radiobutton-application/src/main/kotlin/components/panel/Panel.kt | 4158551169 |
package com.github.kgtkr.mhxxSwitchCIS
import org.apache.commons.io.FileUtils
import org.apache.commons.io.FilenameUtils
import java.awt.Color
import java.awt.image.BufferedImage
import java.io.ByteArrayInputStream
import java.io.File
import java.util.*
import javax.imageio.ImageIO
typealias BitImages=List<Pair<String,BitImage>>
private fun readImage(name:String):List<Pair<String,BufferedImage>> {
val data = FileUtils.readFileToString(File("./data/${name}"), "utf8")
return data.split("\n")
.map { s -> s.split(",") }
.map { s -> Pair(s[0], s[1]) }
.map { data -> Pair(data.first, Base64.getDecoder().decode(data.second)) }
.map { data -> Pair(data.first, ImageIO.read(ByteArrayInputStream(data.second))) }
}
private fun readBitImage(name:String):BitImages{
return readImage(name)
.map{x-> Pair(x.first,x.second.toBitImage(IC.COLOR,IC.THRESHOLD)) }
}
private fun Triple<BufferedImage, BufferedImage, BufferedImage>.getVal(values:Triple<BitImages,BitImages,BitImages>):Int{
val val0=this.first.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(values.first)
val val1=when(val0){
""->this.second.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(values.second)
else->"1"
}
val val2=when(val1){
"1"->this.third.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(values.third.filter { x->x.first=="0"||x.first=="1"||x.first=="2"||x.first=="3" })
else->this.third.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(values.third.filter { x->x.first!="0"})
}
return (val0+val1+val2).toInt()
}
private fun BufferedImage.getSlot():Int{
val slot1Color= Color(this.getRGB(IC.SLOT1_COLOR_X,IC.SLOT_COLOR_Y))
val slot2Color= Color(this.getRGB(IC.SLOT2_COLOR_X,IC.SLOT_COLOR_Y))
val slot3Color= Color(this.getRGB(IC.SLOT3_COLOR_X,IC.SLOT_COLOR_Y))
return if(slot3Color.deff(IC.SLOT_COLOR)>IC.SLOT_THRESHOLD){
3
}else if(slot2Color.deff(IC.SLOT_COLOR)>IC.SLOT_THRESHOLD){
2
}else if(slot1Color.deff(IC.SLOT_COLOR)>IC.SLOT_THRESHOLD){
1
}else{
0
}
}
private fun BufferedImage.getGoseki(gosekis:List<Pair<String,Color>>):String{
return this.deffMinIndex(IC.GOSEKI_COLOR_X,IC.GOSEKI_COLOR_Y,gosekis)
}
private fun BufferedImage.getSkillName(skills:BitImages):String{
return this.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(skills)
}
fun analysisCmd(){
//データ読み込み
val skills=readBitImage("skill")
val values=Triple(readBitImage("value0"),readBitImage("value1"),readBitImage("value2"))
val gosekis=readImage("goseki")
.map{x->Pair(x.first,Color(x.second.getRGB(IC.GOSEKI_COLOR_X,IC.GOSEKI_COLOR_Y)))}
val csv=readImages("./input")
.map{row->
val skill1Name=row.oneSkillName.getSkillName(skills.filter { s->s.first.isNotEmpty() })
if(skill1Name!="(無)") {
val goseki = row.goseki.getGoseki(gosekis)
val skill1 = Pair(skill1Name, row.oneSkillValue.getVal(values.copy(first = values.first.filter { s->s.first!="-" },second = values.second.filter { s->s.first!="-" })))
val skill2Name = row.twoSkillName.getSkillName(skills.filter { s -> s.first != "(無)" })
val skill2 = when (skill2Name) {
"" -> null
else -> Pair(skill2Name, row.twoSkillValue.getVal(values))
}
val slot = row.slot.getSlot()
Goseki(goseki, skill1, skill2, slot)
}else{
null
}
}
.filterNotNull()
.map{g->
if(g.skill2!=null){
"${g.goseki},${g.slot},${g.skill1.first},${g.skill1.second},${g.skill2.first},${g.skill2.second}"
}else{
"${g.goseki},${g.slot},${g.skill1.first},${g.skill1.second}"
}
}
.joinToString("\n")
val header="#護石名,スロット,第一スキル名,第一スキルポイント,第ニスキル名,第ニスキルポイント\n"
FileUtils.write(File("./CHARM.csv"),header+csv,"sjis")
}
| src/main/kotlin/Analysis.kt | 275962018 |
package com.retronicgames.lis.visual.buildings
import com.retronicgames.lis.visual.DataVisual
import com.retronicgames.utils.IntVector2
object DataVisualBuildingLandingZone : DataVisual {
override val offset = IntVector2.ZERO
}
object DataVisualBuildingLivingBlock : DataVisual {
override val offset = IntVector2.ZERO
}
object DataVisualBuildingDigSite: DataVisual {
override val offset = IntVector2.ZERO
}
object DataVisualBuildingPowerBlock: DataVisual {
override val offset = IntVector2.ZERO
}
object DataVisualBuildingSolarPanels: DataVisual {
override val offset = IntVector2.ZERO
}
object DataVisualBuildingLaboratory: DataVisual {
override val offset = IntVector2.ZERO
} | core/src/main/kotlin/com/retronicgames/lis/visual/buildings/DataVisualBuildings.kt | 3775329250 |
/*
* Copyright 2017 Farbod Salamat-Zadeh
*
* 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 co.timetableapp.util
import android.app.Activity
import android.content.Context
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.os.Build
import android.support.annotation.ColorRes
import android.support.annotation.DrawableRes
import android.support.annotation.IdRes
import android.support.annotation.StringRes
import android.support.graphics.drawable.VectorDrawableCompat
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.view.LayoutInflater
import android.view.Menu
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import co.timetableapp.R
import co.timetableapp.model.Color
object UiUtils {
@JvmStatic
fun setBarColors(color: Color, activity: Activity, vararg views: View) {
for (view in views) {
view.setBackgroundColor(ContextCompat.getColor(
activity, color.getPrimaryColorResId(activity)))
}
if (Build.VERSION.SDK_INT >= 21) {
activity.window.statusBarColor =
ContextCompat.getColor(activity, color.getPrimaryDarkColorResId(activity))
}
}
@JvmStatic
fun tintMenuIcons(context: Context, menu: Menu, vararg @IdRes menuItems: Int) {
menuItems.forEach {
val icon = menu.findItem(it).icon
icon?.let {
tintMenuDrawableWhite(context, icon)
}
}
}
@JvmOverloads
@JvmStatic
fun tintDrawable(context: Context, @DrawableRes drawableRes: Int,
@ColorRes colorRes: Int = R.color.mdu_white): Drawable {
val vectorDrawableCompat = VectorDrawableCompat.create(context.resources, drawableRes, null)
val drawable = DrawableCompat.wrap(vectorDrawableCompat!!.current)
DrawableCompat.setTint(drawable, ContextCompat.getColor(context, colorRes))
return drawable
}
private fun tintMenuDrawableWhite(context: Context, d: Drawable): Drawable {
val drawable = DrawableCompat.wrap(d)
DrawableCompat.setTint(drawable, ContextCompat.getColor(context, R.color.mdu_white))
return drawable
}
@JvmOverloads
@JvmStatic
fun makePlaceholderView(context: Context,
@DrawableRes drawableRes: Int,
@StringRes titleRes: Int,
@ColorRes backgroundColorRes: Int = R.color.mdu_grey_50,
@ColorRes drawableColorRes: Int = R.color.mdu_grey_700,
@ColorRes textColorRes: Int = R.color.mdu_text_black_secondary,
largeIcon: Boolean = false,
@StringRes subtitleRes: Int? = null): View {
val placeholderView = LayoutInflater.from(context).inflate(R.layout.placeholder, null)
val background = placeholderView.findViewById(R.id.background)
background.setBackgroundColor(ContextCompat.getColor(context, backgroundColorRes))
val image = placeholderView.findViewById(R.id.imageView) as ImageView
image.setImageDrawable(tintDrawable(context, drawableRes, drawableColorRes))
if (largeIcon) {
image.layoutParams.width = dpToPixels(context, 108)
image.layoutParams.height = dpToPixels(context, 108)
}
val title = placeholderView.findViewById(R.id.title) as TextView
title.setText(titleRes)
title.setTextColor(ContextCompat.getColor(context, textColorRes))
val subtitle = placeholderView.findViewById(R.id.subtitle) as TextView
if (subtitleRes == null) {
subtitle.visibility = View.GONE
} else {
subtitle.setText(subtitleRes)
subtitle.setTextColor(ContextCompat.getColor(context, textColorRes))
}
return placeholderView
}
/**
* Formats the appearance of a TextView displaying item notes. For example, assignment notes or
* exam notes.
*
* If there are no notes to display (i.e. [notes] is blank), then a placeholder text will be
* shown instead with a lighter font color.
*/
@JvmStatic
fun formatNotesTextView(context: Context, textView: TextView, notes: String) {
with(textView) {
if (notes.isBlank()) {
text = context.getString(R.string.placeholder_notes_empty)
setTypeface(null, Typeface.ITALIC)
setTextColor(ContextCompat.getColor(context, R.color.mdu_text_black_secondary))
} else {
text = notes
setTypeface(null, android.graphics.Typeface.NORMAL)
setTextColor(ContextCompat.getColor(context, R.color.mdu_text_black))
}
}
}
@JvmStatic
fun dpToPixels(context: Context, dps: Int): Int {
val density = context.resources.displayMetrics.density
val dpAsPixels = (dps * density + 0.5f).toInt()
return dpAsPixels
}
@JvmStatic
fun isApi21() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP
}
| app/src/main/java/co/timetableapp/util/UiUtils.kt | 1018694965 |
package io.gitlab.arturbosch.detekt.cli.baseline
data class Baseline(val blacklist: Blacklist, val whitelist: Whitelist)
const val SMELL_BASELINE = "SmellBaseline"
const val BLACKLIST = "Blacklist"
const val WHITELIST = "Whitelist"
const val ID = "ID"
| detekt-cli/src/main/kotlin/io/gitlab/arturbosch/detekt/cli/baseline/Baseline.kt | 3427147021 |
package com.ch3d.android.utils
import android.content.Context
import android.util.TypedValue
class StringUtils {
companion object {
fun dpToPx(context: Context, i: Float): Float {
val displayMetrics = context.resources.displayMetrics
return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, displayMetrics)
}
val EMPTY_STRING = ""
val DASH = "-"
val SPACE = " "
val UNDERSCORE = "_"
val NEXT_STRING = "\n"
/**
* Safely checks whether two strings are equal or not
* @return true - if strings are equal, false - otherwise
*/
fun hasChanges(newValue: String, oldValue: String): Boolean {
if (StringUtils.isEmpty(newValue) && StringUtils.isEmpty(oldValue)) {
return false
} else if (StringUtils.isEmpty(newValue) && !StringUtils.isEmpty(oldValue)) {
return true
} else
return !StringUtils.isEmpty(newValue) && StringUtils.isEmpty(
oldValue) || newValue.trim { it <= ' ' } != oldValue.trim { it <= ' ' }
}
/**
* Returns true if the string is null or 0-length.
* @param str the string to be examined
* *
* @return true if str is null or zero length
*/
fun hasNoEmptyValue(vararg str: CharSequence) = str.all { seq -> !isEmpty(seq) }
fun isEmpty(str: CharSequence?) = str == null || str.length == 0
}
}
| app/src/main/kotlin/com/ch3d/android/utils/StringUtils.kt | 3820681018 |
package io.envoyproxy.envoymobile
/**
* Base builder class used to construct `Headers` instances.
* See `{Request|Response}HeadersBuilder` for usage.
*/
open class HeadersBuilder {
protected val container: HeadersContainer
/**
* Instantiate a new builder, only used by child classes.
*
* @param container: The headers container to start with.
*/
internal constructor(container: HeadersContainer) {
this.container = container
}
/**
* Append a value to the header name.
*
* @param name: The header name.
* @param value: The value associated to the header name.
*
* @return HeadersBuilder, This builder.
*/
open fun add(name: String, value: String): HeadersBuilder {
if (isRestrictedHeader(name)) {
return this
}
container.add(name, value)
return this
}
/**
* Replace all values at the provided name with a new set of header values.
*
* @param name: The header name.
* @param value: The value associated to the header name.
*
* @return HeadersBuilder, This builder.
*/
open fun set(name: String, value: MutableList<String>): HeadersBuilder {
if (isRestrictedHeader(name)) {
return this
}
container.set(name, value)
return this
}
/**
* Remove all headers with this name.
*
* @param name: The header name to remove.
*
* @return HeadersBuilder, This builder.
*/
open fun remove(name: String): HeadersBuilder {
if (isRestrictedHeader(name)) {
return this
}
container.remove(name)
return this
}
/**
* Allows for setting headers that are not publicly mutable (i.e., restricted headers).
*
* @param name: The header name.
* @param value: The value associated to the header name.
*
* @return HeadersBuilder, This builder.
*/
internal open fun internalSet(name: String, value: MutableList<String>): HeadersBuilder {
container.set(name, value)
return this
}
private fun isRestrictedHeader(name: String) = name.startsWith(":") ||
name.startsWith("x-envoy-mobile", ignoreCase = true) || name.equals("host", ignoreCase = true)
}
| mobile/library/kotlin/io/envoyproxy/envoymobile/HeadersBuilder.kt | 2559516786 |
/*
Copyright (c) 2021 Tarek Mohamed Abdalla <[email protected]>
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation; either version 3 of the License, or (at your option) any later
version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.dialogs.tags
import com.ichi2.testutils.assertFalse
import org.junit.Assert.*
import org.junit.Before
import org.junit.Ignore
import org.junit.Test
import org.mockito.ArgumentMatchers
import org.mockito.Mockito
import java.util.*
class TagsListTest {
lateinit var tagsList: TagsList
lateinit var tagsListWithIndeterminate: TagsList
@Before
@Throws(Exception::class)
fun setUp() {
tagsList = TagsList(TAGS, CHECKED_TAGS)
tagsListWithIndeterminate = TagsList(TAGS, CHECKED_TAGS, UNCHECKED_TAGS)
}
@Test
fun test_constructor_will_remove_dups() {
val allTags = listOf("a", "b", "a")
val checkedTags = listOf("b", "b", "b")
val list = TagsList(
allTags,
checkedTags
)
assertEquals(
"All tags list should not contain any duplicates",
listOf("a", "b"), list.copyOfAllTagList()
)
assertEquals(
"Checked tags list should not contain any duplicates",
listOf("b"), list.copyOfCheckedTagList()
)
}
@Test
fun test_constructor_will_remove_dups_unchecked() {
val allTags = listOf("a", "b", "a", "c", "c", "d")
val checkedTags = listOf("b", "b", "b")
val uncheckedTags = listOf("c", "c", "d")
val list = TagsList(
allTags,
checkedTags,
uncheckedTags
)
assertEquals(
"All tags list should not contain any duplicates",
listOf("a", "b", "c", "d"), list.copyOfAllTagList()
)
assertEquals(
"Checked tags list should not contain any duplicates",
listOf("b"), list.copyOfCheckedTagList()
)
assertEquals(
"indeterminate tags list should be empty",
listOf<Any>(), list.copyOfIndeterminateTagList()
)
}
@Test
fun test_constructor_will_ignore_casing() {
val allTags = listOf("aA", "bb", "aa")
val checkedTags = listOf("bb", "Bb", "bB")
val list = TagsList(
allTags,
checkedTags
)
assertEquals(
"All tags list should not contain any duplicates (case insensitive)",
listOf("aA", "bb"), list.copyOfAllTagList()
)
assertEquals(
"Checked tags list should not contain any duplicates (case insensitive)",
listOf("bb"), list.copyOfCheckedTagList()
)
}
@Test
fun test_constructor_will_ignore_casing_unchecked() {
val allTags = listOf("aA", "bb", "aa", "cc", "dd")
val checkedTags = listOf("bb", "Bb", "bB", "dd", "ff")
val uncheckedTags = listOf("BB", "cC", "cC", "dD", "CC")
val list = TagsList(
allTags,
checkedTags,
uncheckedTags
)
assertEquals(
"All tags list should not contain any duplicates (case insensitive)",
listOf("aA", "bb", "cc", "dd", "ff"), list.copyOfAllTagList()
)
assertEquals(
"Checked tags list should not contain any duplicates (case insensitive)",
listOf("ff"), list.copyOfCheckedTagList()
)
assertEquals(
"Checked tags list should not contain any duplicates (case insensitive)\n" +
"and IndeterminateTagList is correct".trimIndent(),
listOf("bb", "dd"), list.copyOfIndeterminateTagList()
)
}
@Test
fun test_constructor_will_add_checked_to_all() {
val allTags = listOf("aA", "bb", "aa")
val checkedTags = listOf("bb", "Bb", "bB", "cc")
val list = TagsList(
allTags,
checkedTags
)
assertEquals(
"Extra tags in checked not found in all tags, must be added to all tags list",
listOf("aA", "bb", "cc"), list.copyOfAllTagList()
)
assertEquals(
"Extra tags in checked not found in all tags, must be found when retrieving checked tag list",
listOf("bb", "cc"), list.copyOfCheckedTagList()
)
}
@Test
fun test_constructor_will_add_checked_and_unchecked_to_all() {
val allTags = listOf("aA", "bb", "aa")
val checkedTags = listOf("bb", "Bb", "bB", "Cc", "zz")
val uncheckedTags = listOf("BB", "cC", "cC", "dD", "CC")
val list = TagsList(
allTags,
checkedTags,
uncheckedTags
)
assertEquals(
"Extra tags in checked not found in all tags, must be added to all tags list",
listOf("aA", "bb", "Cc", "zz", "dD"), list.copyOfAllTagList()
)
assertEquals(
"Extra tags in checked not found in all tags, must be found when retrieving checked tag list",
listOf("zz"), list.copyOfCheckedTagList()
)
assertEquals(listOf("bb", "Cc"), list.copyOfIndeterminateTagList())
}
@Test
fun test_constructor_will_complete_hierarchy_for_all_tags() {
val allTags = listOf("cat1", "cat2::aa", "cat3::aa::bb::cc::dd")
val checkedTags = listOf("cat1::aa", "cat1::bb", "cat2::bb::aa", "cat2::bb::bb")
val list = TagsList(
allTags,
checkedTags
)
list.sort()
assertEquals(
listOf(
"cat1", "cat1::aa", "cat1::bb", "cat2", "cat2::aa", "cat2::bb", "cat2::bb::aa",
"cat2::bb::bb", "cat3", "cat3::aa", "cat3::aa::bb", "cat3::aa::bb::cc",
"cat3::aa::bb::cc::dd"
),
list.copyOfAllTagList()
)
assertEquals(listOf("cat1::aa", "cat1::bb", "cat2::bb::aa", "cat2::bb::bb"), list.copyOfCheckedTagList())
assertEquals(
"Ancestors of checked tags should be marked as indeterminate",
listOf("cat1", "cat2", "cat2::bb"), list.copyOfIndeterminateTagList()
)
}
@Test
fun test_isChecked_index() {
assertTrue("Tag at index 0 should be checked", tagsList.isChecked(0))
assertTrue("Tag at index 3 should be checked", tagsList.isChecked(3))
assertFalse("Tag at index 1 should be unchecked", tagsList.isChecked(1))
assertFalse("Tag at index 6 should be unchecked", tagsList.isChecked(6))
// indeterminate tags
assertFalse("Tag at index 0 should be unchecked", tagsListWithIndeterminate.isChecked(0))
assertFalse("Tag at index 3 should be unchecked", tagsListWithIndeterminate.isChecked(3))
}
@Test
fun test_isChecked_object() {
assertTrue("'programming' tag should be checked", tagsList.isChecked("programming"))
assertTrue("'faces' tag should be checked", tagsList.isChecked("faces"))
assertFalse("'cars' tag should be unchecked", tagsList.isChecked("cars"))
assertFalse("'flags' tag should be unchecked", tagsList.isChecked("flags"))
// indeterminate tags
assertFalse("Tag at index 'programming' should be unchecked", tagsListWithIndeterminate.isChecked("programming"))
assertFalse("Tag at index 'faces' should be unchecked", tagsListWithIndeterminate.isChecked("faces"))
}
@Test
fun test_isIndeterminate_index() {
assertFalse("Tag at index 0 should be checked (not indeterminate)", tagsList.isIndeterminate(0))
assertFalse("Tag at index 3 should be checked (not indeterminate)", tagsList.isIndeterminate(3))
assertFalse("Tag at index 1 should be unchecked (not indeterminate)", tagsList.isIndeterminate(1))
assertFalse("Tag at index 6 should be unchecked (not indeterminate)", tagsList.isIndeterminate(6))
assertTrue("Tag at index 0 should be indeterminate", tagsListWithIndeterminate.isIndeterminate(0))
assertTrue("Tag at index 3 should be indeterminate", tagsListWithIndeterminate.isIndeterminate(3))
assertFalse("Tag at index 1 should be unchecked (not indeterminate)", tagsListWithIndeterminate.isIndeterminate(1))
assertFalse("Tag at index 6 should be unchecked (not indeterminate)", tagsListWithIndeterminate.isIndeterminate(6))
assertFalse("Tag at index 6 should be unchecked (not indeterminate)", tagsListWithIndeterminate.isIndeterminate(5))
}
@Test
fun test_isIndeterminate_object() {
assertFalse("'programming' tag should be checked (not indeterminate)", tagsList.isIndeterminate("programming"))
assertFalse("'faces' tag should be checked (not indeterminate)", tagsList.isIndeterminate("faces"))
assertFalse("'cars' tag should be unchecked (not indeterminate)", tagsList.isIndeterminate("cars"))
assertFalse("'flags' tag should be unchecked (not indeterminate)", tagsList.isIndeterminate("flags"))
assertTrue("Tag 'programming' should be indeterminate", tagsListWithIndeterminate.isIndeterminate("programming"))
assertTrue("Tag 'faces' should be indeterminate", tagsListWithIndeterminate.isIndeterminate("faces"))
assertFalse("Tag 'cars' should be unchecked (not indeterminate)", tagsListWithIndeterminate.isIndeterminate("cars"))
assertFalse("Tag 'flags' should be unchecked (not indeterminate)", tagsListWithIndeterminate.isIndeterminate("flags"))
}
@Test
fun test_add() {
assertTrue(
"Adding 'anki' tag should return true, as the 'anki' is a new tag",
tagsList.add("anki")
)
assertFalse(
"Adding 'colors' tag should return false, as the 'colors' is a already existing tag",
tagsList.add("colors")
)
assertEquals(
"The newly added 'anki' tag should be found when retrieving all tags list",
join(TAGS, "anki"), tagsList.copyOfAllTagList()
)
assertSameElementsIgnoreOrder(
"Adding operations should have nothing to do with the checked status of tags",
CHECKED_TAGS, tagsList.copyOfCheckedTagList()
)
}
@Test
fun test_add_hierarchy_tag() {
assertTrue(
"Adding 'language::english' tag should return true",
tagsList.add("language::english")
)
assertTrue(
"Adding 'language::other::java' tag should return true",
tagsList.add("language::other::java")
)
assertTrue(
"Adding 'language::other::kotlin' tag should return true",
tagsList.add("language::other::kotlin")
)
assertFalse(
"Repeatedly adding 'language::english' tag should return false",
tagsList.add("language::english")
)
assertFalse(
"Adding 'language::other' tag should return false, for it should have been auto created.",
tagsList.add("language::other")
)
assertTrue(tagsList.check("language::other::java"))
assertTrue(
"Intermediate tags should marked as indeterminate",
tagsList.copyOfIndeterminateTagList().contains("language::other")
)
assertTrue(tagsList.add("object::electronic"))
assertTrue(tagsList.check("object::electronic"))
assertTrue(tagsList.add("object::electronic::computer"))
assertTrue(tagsList.check("object::electronic::computer"))
assertFalse(
"Should not mark checked intermediate tags as indeterminate",
tagsList.copyOfIndeterminateTagList().contains("object::electronic")
)
}
@Test
fun test_check() {
assertFalse(
"Attempting to check tag 'anki' should return false, as 'anki' is not found in all tags list",
tagsList.check("anki")
) // not in the list
assertFalse(
"Attempting to check tag 'colors' should return false, as 'colors' is already checked",
tagsList.check("colors")
) // already checked
assertTrue(
"Attempting to check tag 'flags' should return true, as 'flags' is found in all tags and is not already checked",
tagsList.check("flags")
)
assertEquals(
"Changing the status of tags to be checked should have noting to do with all tag list",
TAGS, tagsList.copyOfAllTagList()
) // no change
assertSameElementsIgnoreOrder(
"The checked 'flags' tag should be found when retrieving list of checked tag",
join(CHECKED_TAGS, "flags"), tagsList.copyOfCheckedTagList()
)
}
@Test
fun test_check_with_indeterminate_tags_list() {
assertTrue(
"Attempting to check tag 'faces' should return true, as 'faces' is found in all tags and it have indeterminate state",
tagsListWithIndeterminate.check("faces")
)
assertEquals(
"Changing the status of tags to be checked should have noting to do with all tag list",
TAGS, tagsListWithIndeterminate.copyOfAllTagList()
)
assertTrue(
"The checked 'faces' tag should be found when retrieving list of checked tag",
tagsListWithIndeterminate.copyOfCheckedTagList().contains("faces")
)
assertFalse(
"The checked 'faces' tag should not be found when retrieving list of indeterminate tags",
tagsListWithIndeterminate.copyOfIndeterminateTagList().contains("faces")
)
}
@Test
fun test_uncheck() {
assertFalse(
"Attempting to uncheck tag 'anki' should return false, as 'anki' is not found in all tags list",
tagsList.uncheck("anki")
) // not in the list
assertFalse(
"Attempting to uncheck tag 'flags' should return false, as 'flags' is already unchecked",
tagsList.uncheck("flags")
) // already unchecked
assertTrue(
"Attempting to uncheck tag 'colors' should return true, as 'colors' is found in all tags and is checked",
tagsList.uncheck("colors")
)
assertEquals(
"Changing the status of tags to be unchecked should have noting to do with all tag list",
TAGS, tagsList.copyOfAllTagList()
) // no change
assertSameElementsIgnoreOrder(
"The unchecked 'colors' tag should be not be found when retrieving list of checked tag",
minus(CHECKED_TAGS, "colors"), tagsList.copyOfCheckedTagList()
)
}
@Test
fun test_uncheck_indeterminate_tags_list() {
assertTrue(
"Attempting to uncheck tag 'programming' should return true, as 'programming' is found in all tags and it have indeterminate state",
tagsListWithIndeterminate.uncheck("programming")
)
assertEquals(
"Changing the status of tags to be checked should have noting to do with all tag list",
TAGS, tagsListWithIndeterminate.copyOfAllTagList()
)
assertFalse(
"Changing from indeterminate to unchecked should not affect checked tags",
tagsListWithIndeterminate.copyOfCheckedTagList().contains("programming")
)
assertFalse(
"The checked 'programming' tag should not be found when retrieving list of indeterminate tags",
tagsListWithIndeterminate.copyOfIndeterminateTagList().contains("programming")
)
}
@Test
fun test_toggleAllCheckedStatuses() {
assertEquals(TAGS, tagsList.copyOfAllTagList())
assertSameElementsIgnoreOrder(CHECKED_TAGS, tagsList.copyOfCheckedTagList())
assertTrue(tagsList.toggleAllCheckedStatuses())
assertEquals(TAGS, tagsList.copyOfAllTagList())
assertSameElementsIgnoreOrder(TAGS, tagsList.copyOfCheckedTagList())
assertTrue(tagsList.toggleAllCheckedStatuses())
assertEquals(TAGS, tagsList.copyOfAllTagList())
assertSameElementsIgnoreOrder(ArrayList(), tagsList.copyOfCheckedTagList())
}
@Test
fun test_toggleAllCheckedStatuses_indeterminate() {
assertEquals(TAGS, tagsListWithIndeterminate.copyOfAllTagList())
assertSameElementsIgnoreOrder(
minus(CHECKED_TAGS, INDETERMINATE_TAGS),
tagsListWithIndeterminate.copyOfCheckedTagList()
)
assertNotEquals(emptyList<Any>(), tagsListWithIndeterminate.copyOfIndeterminateTagList())
assertTrue(tagsListWithIndeterminate.toggleAllCheckedStatuses())
assertEquals(TAGS, tagsListWithIndeterminate.copyOfAllTagList())
assertSameElementsIgnoreOrder(TAGS, tagsListWithIndeterminate.copyOfCheckedTagList())
assertEquals(emptyList<Any>(), tagsListWithIndeterminate.copyOfIndeterminateTagList())
assertTrue(tagsListWithIndeterminate.toggleAllCheckedStatuses())
assertEquals(TAGS, tagsListWithIndeterminate.copyOfAllTagList())
assertSameElementsIgnoreOrder(ArrayList(), tagsListWithIndeterminate.copyOfCheckedTagList())
assertEquals(emptyList<Any>(), tagsListWithIndeterminate.copyOfIndeterminateTagList())
}
@Test
fun test_size_if_checked_have_no_extra_items_not_found_in_allTags() {
assertEquals(TAGS.size, tagsList.size())
assertEquals(TAGS.size, tagsListWithIndeterminate.size())
}
@Test
fun test_size_if_checked_have_extra_items_not_found_in_allTags() {
tagsList = TagsList(TAGS, join(CHECKED_TAGS, "NEW"))
assertEquals((TAGS.size + 1), tagsList.size())
}
@Test
fun test_size_if_unchecked_and_checked_have_extra_items_not_found_in_allTags() {
tagsList = TagsList(TAGS, join(CHECKED_TAGS, "NEW"), join(UNCHECKED_TAGS, "ALSO_NEW"))
assertEquals((TAGS.size + 2), tagsList.size())
}
@Test
fun test_sort() {
assertEquals(TAGS, tagsList.copyOfAllTagList())
tagsList.sort()
assertEquals(
"Calling #sort on TagsList should result on sorting all tags",
SORTED_TAGS, tagsList.copyOfAllTagList()
)
}
@Test
fun test_sort_with_indeterminate_tags() {
assertEquals(TAGS, tagsListWithIndeterminate.copyOfAllTagList())
tagsListWithIndeterminate.sort()
assertEquals(
"Calling #sort on TagsList should result on sorting all tags",
SORTED_TAGS, tagsListWithIndeterminate.copyOfAllTagList()
)
}
@Test // #8807
@Ignore(
"Collections.singletonList() triggers infinite recursion. " +
"Need solution to only mock the sort() method."
)
fun test_sort_will_not_call_collectionsSort() {
Mockito.mockStatic(Collections::class.java).use { MockCollection ->
assertEquals(TAGS, tagsList.copyOfAllTagList())
tagsList.sort()
assertEquals(
"Calling #sort on TagsList should result on sorting all tags",
SORTED_TAGS, tagsList.copyOfAllTagList()
)
MockCollection.verify({ Collections.sort(ArgumentMatchers.any(), ArgumentMatchers.any<Comparator<in Any>>()) }, Mockito.never())
}
}
companion object {
val SORTED_TAGS = listOf(
"colors",
"faces",
"programming",
"cars",
"electrical",
"flags",
"learn",
"meat",
"names",
"playground"
)
val TAGS = listOf(
"programming",
"learn",
"names",
"faces",
"cars",
"colors",
"flags",
"meat",
"playground",
"electrical"
)
val CHECKED_TAGS = listOf(
"programming",
"faces",
"colors"
)
val UNCHECKED_TAGS = listOf(
"electrical",
"meat",
"programming",
"faces"
)
val INDETERMINATE_TAGS = listOf(
"programming",
"faces"
)
private fun <E> join(l1: List<E>, l2: List<E>): List<E> {
val joined: MutableList<E> = ArrayList()
joined.addAll(l1)
joined.addAll(l2)
return joined
}
private fun <E> join(l1: List<E>, e: E): List<E> {
val joined: MutableList<E> = ArrayList(l1)
joined.add(e)
return joined
}
private fun <E> minus(l1: List<E>, e: E): List<E> {
val res: MutableList<E> = ArrayList(l1)
res.remove(e)
return res
}
private fun <E> minus(l1: List<E>, el: List<E>): List<E> {
val res: MutableList<E> = ArrayList(l1)
for (e in el) {
res.remove(e)
}
return res
}
private fun <E> assertSameElementsIgnoreOrder(l1: Collection<E>, l2: Collection<E>) {
assertSameElementsIgnoreOrder(null, l1, l2)
}
private fun <E> assertSameElementsIgnoreOrder(message: String?, l1: Collection<E>, l2: Collection<E>) {
assertEquals(message, l1.size, l2.size)
assertTrue(message, l1.containsAll(l2))
}
}
}
| AnkiDroid/src/test/java/com/ichi2/anki/dialogs/tags/TagsListTest.kt | 94354656 |
/*
* Copyright (c) 2019.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine.test.loanOrigination.systems
import kotlinx.serialization.Serializable
import nl.adaptivity.process.engine.test.loanOrigination.auth.AuthToken
import nl.adaptivity.process.engine.test.loanOrigination.auth.LoanPermissions
import nl.adaptivity.process.engine.test.loanOrigination.auth.ServiceImpl
class SigningService(authService: AuthService): ServiceImpl(authService, "SigningService") {
override fun getServiceState(): String = ""
fun <V> signDocument(authInfo: AuthToken, document: V): SignedDocument<V> {
logMe(document)
validateAuthInfo(authInfo, LoanPermissions.SIGN)
return SignedDocument(authInfo.principal.name, authInfo.nodeInstanceHandle.handleValue, document)
}
}
@Serializable
data class SignedDocument<V>(val signedBy: String, val nodeInstanceHandle: Long, val document: V)
| ProcessEngine/core/src/jvmTest/kotlin/nl/adaptivity/process/engine/test/loanOrigination/systems/SigningService.kt | 3524185191 |
package quickbeer.android.data.room.converter
import androidx.room.TypeConverter
private const val SEPARATOR = ","
class IntListConverter {
@TypeConverter
fun fromString(value: String): List<Int> {
return value.split(SEPARATOR)
.filter(String::isNotEmpty)
.map(String::toInt)
}
@TypeConverter
fun toString(list: List<Int>): String {
return list.joinToString(SEPARATOR)
}
}
| app/src/main/java/quickbeer/android/data/room/converter/IntListConverter.kt | 2895271897 |
package com.octaldata.datastore
import com.octaldata.domain.DeploymentId
import com.octaldata.domain.query.View
import com.octaldata.domain.query.ViewId
import com.octaldata.domain.query.ViewName
import io.kotest.core.extensions.install
import io.kotest.core.spec.style.FunSpec
import io.kotest.extensions.testcontainers.JdbcTestContainerExtension
import io.kotest.matchers.nulls.shouldBeNull
import io.kotest.matchers.shouldBe
import org.flywaydb.core.Flyway
import org.testcontainers.containers.MySQLContainer
class ViewDatastoreTest : FunSpec({
val mysql = MySQLContainer<Nothing>("mysql:8.0.26").apply {
startupAttempts = 1
withUrlParam("connectionTimeZone", "Z")
withUrlParam("zeroDateTimeBehavior", "convertToNull")
}
val ds = install(JdbcTestContainerExtension(mysql)) {
poolName = "myconnectionpool"
maximumPoolSize = 8
idleTimeout = 10000
}
Class.forName(com.mysql.jdbc.Driver::class.java.name)
Flyway
.configure()
.dataSource(ds)
.locations("classpath:changesets")
.load()
.migrate()
val datastore = ViewDatastore(ds)
test("insert happy path") {
datastore.insert(
View(
ViewId("a"),
DeploymentId("kafka1"),
"select * from foo",
ViewName("wibble"),
)
).getOrThrow()
datastore.insert(
View(
ViewId("b"),
DeploymentId("pulsar1"),
"select * from bar",
ViewName("wobble"),
)
).getOrThrow()
datastore.findAll().getOrThrow().shouldBe(
listOf(
View(
ViewId("a"),
DeploymentId("kafka1"),
"select * from foo",
ViewName("wibble"),
),
View(
ViewId("b"),
DeploymentId("pulsar1"),
"select * from bar",
ViewName("wobble"),
)
)
)
}
test("get by id") {
datastore.getById(ViewId("a")).getOrThrow().shouldBe(
View(
ViewId("a"),
DeploymentId("kafka1"),
"select * from foo",
ViewName("wibble"),
),
)
}
test("get by id for non existing id") {
datastore.getById(ViewId("qwerty")).getOrThrow().shouldBeNull()
}
test("delete") {
datastore.delete(ViewId("b")).getOrThrow()
datastore.findAll().getOrThrow().shouldBe(
listOf(
View(
ViewId("a"),
DeploymentId("kafka1"),
"select * from foo",
ViewName("wibble"),
),
)
)
}
})
| streamops-datastore/src/test/kotlin/com/octaldata/datastore/ViewDatastoreTest.kt | 1937883984 |
package com.boardgamegeek.livedata
import android.content.Context
import android.content.SharedPreferences
import androidx.lifecycle.MutableLiveData
import com.boardgamegeek.extensions.preferences
@Suppress("UNCHECKED_CAST")
class LiveSharedPreference<T>(context: Context, preferenceKey: String, sharedPreferencesName: String? = null) : MutableLiveData<T>() {
private val listener: SharedPreferences.OnSharedPreferenceChangeListener =
SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
if (key == preferenceKey) {
value = sharedPreferences.all[key] as T
}
}
private val sharedPreferences: SharedPreferences = context.preferences(sharedPreferencesName)
init {
value = sharedPreferences.all[preferenceKey] as T
}
override fun onActive() {
super.onActive()
sharedPreferences.registerOnSharedPreferenceChangeListener(listener)
}
override fun onInactive() {
super.onInactive()
sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener)
}
}
| app/src/main/java/com/boardgamegeek/livedata/LiveSharedPreference.kt | 3256615698 |
// Copyright 2021 [email protected]
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cfig.io
import cfig.io.Struct3.ByteArrayExt.Companion.toCString
import cfig.io.Struct3.ByteArrayExt.Companion.toInt
import cfig.io.Struct3.ByteArrayExt.Companion.toLong
import cfig.io.Struct3.ByteArrayExt.Companion.toShort
import cfig.io.Struct3.ByteArrayExt.Companion.toUInt
import cfig.io.Struct3.ByteArrayExt.Companion.toULong
import cfig.io.Struct3.ByteArrayExt.Companion.toUShort
import cfig.io.Struct3.ByteBufferExt.Companion.appendByteArray
import cfig.io.Struct3.ByteBufferExt.Companion.appendPadding
import cfig.io.Struct3.ByteBufferExt.Companion.appendUByteArray
import cfig.io.Struct3.InputStreamExt.Companion.getByteArray
import cfig.io.Struct3.InputStreamExt.Companion.getCString
import cfig.io.Struct3.InputStreamExt.Companion.getChar
import cfig.io.Struct3.InputStreamExt.Companion.getInt
import cfig.io.Struct3.InputStreamExt.Companion.getLong
import cfig.io.Struct3.InputStreamExt.Companion.getPadding
import cfig.io.Struct3.InputStreamExt.Companion.getShort
import cfig.io.Struct3.InputStreamExt.Companion.getUByteArray
import cfig.io.Struct3.InputStreamExt.Companion.getUInt
import cfig.io.Struct3.InputStreamExt.Companion.getULong
import cfig.io.Struct3.InputStreamExt.Companion.getUShort
import org.slf4j.LoggerFactory
import java.io.IOException
import java.io.InputStream
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.charset.StandardCharsets
import java.util.*
import java.util.regex.Pattern
import kotlin.random.Random
class Struct3 {
private val formatString: String
private var byteOrder = ByteOrder.LITTLE_ENDIAN
private val formats = ArrayList<Array<Any?>>()
constructor(inFormatString: String) {
assert(inFormatString.isNotEmpty()) { "FORMAT_STRING must not be empty" }
formatString = inFormatString
val m = Pattern.compile("(\\d*)([a-zA-Z])").matcher(formatString)
when (formatString[0]) {
'>', '!' -> this.byteOrder = ByteOrder.BIG_ENDIAN
'@', '=' -> this.byteOrder = ByteOrder.nativeOrder()
else -> this.byteOrder = ByteOrder.LITTLE_ENDIAN
}
while (m.find()) {
//item[0]: Type, item[1]: multiple
// if need to expand format items, explode it
// eg: "4L" will be exploded to "1L 1L 1L 1L", so it's treated as primitive
// eg: "10x" won't be exploded, it's still "10x", so it's treated as non-primitive
val typeName: Any = when (m.group(2)) {
//primitive types
"x" -> Random //byte 1 (exploded)
"b" -> Byte //byte 1 (exploded)
"B" -> UByte //UByte 1 (exploded)
"s" -> String //string (exploded)
//zippable types, which need to be exploded with multiple=1
"c" -> Char
"h" -> Short //2
"H" -> UShort //2
"i", "l" -> Int //4
"I", "L" -> UInt //4
"q" -> Long //8
"Q" -> ULong //8
else -> throw IllegalArgumentException("type [" + m.group(2) + "] not supported")
}
val bPrimitive = m.group(2) in listOf("x", "b", "B", "s")
val multiple = if (m.group(1).isEmpty()) 1 else Integer.decode(m.group(1))
if (bPrimitive) {
formats.add(arrayOf<Any?>(typeName, multiple))
} else {
for (i in 0 until multiple) {
formats.add(arrayOf<Any?>(typeName, 1))
}
}
}
}
private fun getFormatInfo(inCursor: Int): String {
return ("type=" + formats.get(inCursor)[0] + ", value=" + formats.get(inCursor)[1])
}
override fun toString(): String {
val formatStr = mutableListOf<String>()
formats.forEach {
val fs = StringBuilder()
when (it[0]) {
Random -> fs.append("x")
Byte -> fs.append("b")
UByte -> fs.append("B")
String -> fs.append("s")
Char -> fs.append("c")
Short -> fs.append("h")
UShort -> fs.append("H")
Int -> fs.append("i")
UInt -> fs.append("I")
Long -> fs.append("q")
ULong -> fs.append("Q")
else -> throw IllegalArgumentException("type [" + it[0] + "] not supported")
}
fs.append(":" + it[1])
formatStr.add(fs.toString())
}
return "Struct3(formatString='$formatString', byteOrder=$byteOrder, formats=$formatStr)"
}
fun calcSize(): Int {
var ret = 0
for (format in formats) {
ret += when (val formatType = format[0]) {
Random, Byte, UByte, Char, String -> format[1] as Int
Short, UShort -> 2 * format[1] as Int
Int, UInt -> 4 * format[1] as Int
Long, ULong -> 8 * format[1] as Int
else -> throw IllegalArgumentException("Class [$formatType] not supported")
}
}
return ret
}
@Throws(IllegalArgumentException::class)
fun pack(vararg args: Any?): ByteArray {
if (args.size != this.formats.size) {
throw IllegalArgumentException("argument size " + args.size + " doesn't match format size " + this.formats.size)
}
val bf = ByteBuffer.allocate(this.calcSize())
bf.order(this.byteOrder)
for (i in args.indices) {
val arg = args[i]
val typeName = formats[i][0]
val multiple = formats[i][1] as Int
if (typeName !in arrayOf(Random, Byte, String, UByte)) {
assert(1 == multiple)
}
//x: padding:
if (Random == typeName) {
when (arg) {
null -> bf.appendPadding(0, multiple)
is Byte -> bf.appendPadding(arg, multiple)
is Int -> bf.appendPadding(arg.toByte(), multiple)
else -> throw IllegalArgumentException("Index[" + i + "] Unsupported arg [" + arg + "] with type [" + formats[i][0] + "]")
}
continue
}
//c: character
if (Char == typeName) {
assert(arg is Char) { "[$arg](${arg!!::class.java}) is NOT Char" }
if ((arg as Char) !in '\u0000'..'\u00ff') {
throw IllegalArgumentException("arg[${arg.code}] exceeds 8-bit bound")
}
bf.put(arg.code.toByte())
continue
}
//b: byte array
if (Byte == typeName) {
when (arg) {
is IntArray -> bf.appendByteArray(arg, multiple)
is ByteArray -> bf.appendByteArray(arg, multiple)
else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT ByteArray/IntArray")
}
continue
}
//B: UByte array
if (UByte == typeName) {
when (arg) {
is ByteArray -> bf.appendByteArray(arg, multiple)
is UByteArray -> bf.appendUByteArray(arg, multiple)
is IntArray -> bf.appendUByteArray(arg, multiple)
else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT ByteArray/IntArray")
}
continue
}
//s: String
if (String == typeName) {
assert(arg != null) { "arg can not be NULL for String, formatString=$formatString, ${getFormatInfo(i)}" }
assert(arg is String) { "[$arg](${arg!!::class.java}) is NOT String, ${getFormatInfo(i)}" }
bf.appendByteArray((arg as String).toByteArray(), multiple)
continue
}
//h: Short
if (Short == typeName) {
when (arg) {
is Int -> {
assert(arg in Short.MIN_VALUE..Short.MAX_VALUE) { "[$arg] is truncated as type Short.class" }
bf.putShort(arg.toShort())
}
is Short -> bf.putShort(arg) //instance Short
else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT Short/Int")
}
continue
}
//H: UShort
if (UShort == typeName) {
assert(arg is UShort || arg is UInt || arg is Int) { "[$arg](${arg!!::class.java}) is NOT UShort/UInt/Int" }
when (arg) {
is Int -> {
assert(arg >= UShort.MIN_VALUE.toInt() && arg <= UShort.MAX_VALUE.toInt()) { "[$arg] is truncated as type UShort" }
bf.putShort(arg.toShort())
}
is UInt -> {
assert(arg >= UShort.MIN_VALUE && arg <= UShort.MAX_VALUE) { "[$arg] is truncated as type UShort" }
bf.putShort(arg.toShort())
}
is UShort -> bf.putShort(arg.toShort())
}
continue
}
//i, l: Int
if (Int == typeName) {
assert(arg is Int) { "[$arg](${arg!!::class.java}) is NOT Int" }
bf.putInt(arg as Int)
continue
}
//I, L: UInt
if (UInt == typeName) {
when (arg) {
is Int -> {
assert(arg >= 0) { "[$arg] is invalid as type UInt" }
bf.putInt(arg)
}
is UInt -> bf.putInt(arg.toInt())
is Long -> {
assert(arg >= 0) { "[$arg] is invalid as type UInt" }
bf.putInt(arg.toInt())
}
else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT UInt/Int/Long")
}
continue
}
//q: Long
if (Long == typeName) {
when (arg) {
is Long -> bf.putLong(arg)
is Int -> bf.putLong(arg.toLong())
else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT Long/Int")
}
continue
}
//Q: ULong
if (ULong == typeName) {
when (arg) {
is Int -> {
assert(arg >= 0) { "[$arg] is invalid as type ULong" }
bf.putLong(arg.toLong())
}
is Long -> {
assert(arg >= 0) { "[$arg] is invalid as type ULong" }
bf.putLong(arg)
}
is ULong -> bf.putLong(arg.toLong())
else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT Int/Long/ULong")
}
continue
}
throw IllegalArgumentException("unrecognized format $typeName")
}
return bf.array()
}
@Throws(IOException::class, IllegalArgumentException::class)
fun unpack(iS: InputStream): List<*> {
val ret = ArrayList<Any>()
for (format in this.formats) {
when (format[0]) {
Random -> ret.add(iS.getPadding(format[1] as Int)) //return padding byte
Byte -> ret.add(iS.getByteArray(format[1] as Int)) //b: byte array
UByte -> ret.add(iS.getUByteArray(format[1] as Int)) //B: ubyte array
Char -> ret.add(iS.getChar()) //char: 1
String -> ret.add(iS.getCString(format[1] as Int)) //c string
Short -> ret.add(iS.getShort(this.byteOrder)) //h: short
UShort -> ret.add(iS.getUShort(this.byteOrder)) //H: UShort
Int -> ret.add(iS.getInt(this.byteOrder)) //i, l: Int
UInt -> ret.add(iS.getUInt(this.byteOrder)) //I, L: UInt
Long -> ret.add(iS.getLong(this.byteOrder)) //q: Long
ULong -> ret.add(iS.getULong(this.byteOrder)) //Q: ULong
else -> throw IllegalArgumentException("Class [" + format[0] + "] not supported")
}//end-of-when
}//end-of-for
return ret
}
class ByteBufferExt {
companion object {
private val log = LoggerFactory.getLogger(ByteBufferExt::class.java)
@Throws(IllegalArgumentException::class)
fun ByteBuffer.appendPadding(b: Byte, bufSize: Int) {
when {
bufSize == 0 -> {
log.debug("paddingSize is zero, perfect match")
return
}
bufSize < 0 -> {
throw IllegalArgumentException("illegal padding size: $bufSize")
}
else -> {
log.debug("paddingSize $bufSize")
}
}
val padding = ByteArray(bufSize)
Arrays.fill(padding, b)
this.put(padding)
}
fun ByteBuffer.appendByteArray(inIntArray: IntArray, bufSize: Int) {
val arg2 = mutableListOf<Byte>()
inIntArray.toMutableList().mapTo(arg2) {
if (it in Byte.MIN_VALUE..Byte.MAX_VALUE) {
it.toByte()
} else {
throw IllegalArgumentException("$it is not valid Byte")
}
}
appendByteArray(arg2.toByteArray(), bufSize)
}
@Throws(IllegalArgumentException::class)
fun ByteBuffer.appendByteArray(inByteArray: ByteArray, bufSize: Int) {
val paddingSize = bufSize - inByteArray.size
if (paddingSize < 0) throw IllegalArgumentException("arg length [${inByteArray.size}] exceeds limit: $bufSize")
//data
this.put(inByteArray)
//padding
this.appendPadding(0.toByte(), paddingSize)
log.debug("paddingSize $paddingSize")
}
fun ByteBuffer.appendUByteArray(inIntArray: IntArray, bufSize: Int) {
val arg2 = mutableListOf<UByte>()
inIntArray.toMutableList().mapTo(arg2) {
if (it in UByte.MIN_VALUE.toInt()..UByte.MAX_VALUE.toInt())
it.toUByte()
else {
throw IllegalArgumentException("$it is not valid Byte")
}
}
appendUByteArray(arg2.toUByteArray(), bufSize)
}
fun ByteBuffer.appendUByteArray(inUByteArray: UByteArray, bufSize: Int) {
val bl = mutableListOf<Byte>()
inUByteArray.toMutableList().mapTo(bl) { it.toByte() }
this.appendByteArray(bl.toByteArray(), bufSize)
}
}
}
class InputStreamExt {
companion object {
fun InputStream.getChar(): Char {
val data = ByteArray(Byte.SIZE_BYTES)
assert(Byte.SIZE_BYTES == this.read(data))
return data[0].toInt().toChar()
}
fun InputStream.getShort(inByteOrder: ByteOrder): Short {
val data = ByteArray(Short.SIZE_BYTES)
assert(Short.SIZE_BYTES == this.read(data))
return data.toShort(inByteOrder)
}
fun InputStream.getInt(inByteOrder: ByteOrder): Int {
val data = ByteArray(Int.SIZE_BYTES)
assert(Int.SIZE_BYTES == this.read(data))
return data.toInt(inByteOrder)
}
fun InputStream.getLong(inByteOrder: ByteOrder): Long {
val data = ByteArray(Long.SIZE_BYTES)
assert(Long.SIZE_BYTES == this.read(data))
return data.toLong(inByteOrder)
}
fun InputStream.getUShort(inByteOrder: ByteOrder): UShort {
val data = ByteArray(UShort.SIZE_BYTES)
assert(UShort.SIZE_BYTES == this.read(data))
return data.toUShort(inByteOrder)
}
fun InputStream.getUInt(inByteOrder: ByteOrder): UInt {
val data = ByteArray(UInt.SIZE_BYTES)
assert(UInt.SIZE_BYTES == this.read(data))
return data.toUInt(inByteOrder)
}
fun InputStream.getULong(inByteOrder: ByteOrder): ULong {
val data = ByteArray(ULong.SIZE_BYTES)
assert(ULong.SIZE_BYTES == this.read(data))
return data.toULong(inByteOrder)
}
fun InputStream.getByteArray(inSize: Int): ByteArray {
val data = ByteArray(inSize)
assert(inSize == this.read(data))
return data
}
fun InputStream.getUByteArray(inSize: Int): UByteArray {
val data = ByteArray(inSize)
assert(inSize == this.read(data))
val innerData2 = mutableListOf<UByte>()
data.toMutableList().mapTo(innerData2) { it.toUByte() }
return innerData2.toUByteArray()
}
fun InputStream.getCString(inSize: Int): String {
val data = ByteArray(inSize)
assert(inSize == this.read(data))
return data.toCString()
}
fun InputStream.getPadding(inSize: Int): Byte {
val data = ByteArray(Byte.SIZE_BYTES)
assert(Byte.SIZE_BYTES == this.read(data)) //sample the 1st byte
val skipped = this.skip(inSize.toLong() - Byte.SIZE_BYTES)//skip remaining to save memory
assert(inSize.toLong() - Byte.SIZE_BYTES == skipped)
return data[0]
}
}
}
class ByteArrayExt {
companion object {
fun ByteArray.toShort(inByteOrder: ByteOrder): Short {
val typeSize = Short.SIZE_BYTES / Byte.SIZE_BYTES
assert(typeSize == this.size) { "Short must have $typeSize bytes" }
return ByteBuffer.allocate(this.size).let {
it.order(inByteOrder)
it.put(this)
it.flip()
it.getShort()
}
}
fun ByteArray.toInt(inByteOrder: ByteOrder): Int {
val typeSize = Int.SIZE_BYTES / Byte.SIZE_BYTES
assert(typeSize == this.size) { "Int must have $typeSize bytes" }
return ByteBuffer.allocate(this.size).let {
it.order(inByteOrder)
it.put(this)
it.flip()
it.getInt()
}
}
fun ByteArray.toLong(inByteOrder: ByteOrder): Long {
val typeSize = Long.SIZE_BYTES / Byte.SIZE_BYTES
assert(typeSize == this.size) { "Long must have $typeSize bytes" }
return ByteBuffer.allocate(this.size).let {
it.order(inByteOrder)
it.put(this)
it.flip()
it.getLong()
}
}
fun ByteArray.toUShort(inByteOrder: ByteOrder): UShort {
val typeSize = UShort.SIZE_BYTES / Byte.SIZE_BYTES
assert(typeSize == this.size) { "UShort must have $typeSize bytes" }
return ByteBuffer.allocate(this.size).let {
it.order(inByteOrder)
it.put(this)
it.flip()
it.getShort().toUShort()
}
}
fun ByteArray.toUInt(inByteOrder: ByteOrder): UInt {
val typeSize = UInt.SIZE_BYTES / Byte.SIZE_BYTES
assert(typeSize == this.size) { "UInt must have $typeSize bytes" }
return ByteBuffer.allocate(this.size).let {
it.order(inByteOrder)
it.put(this)
it.flip()
it.getInt().toUInt()
}
}
fun ByteArray.toULong(inByteOrder: ByteOrder): ULong {
val typeSize = ULong.SIZE_BYTES / Byte.SIZE_BYTES
assert(typeSize == this.size) { "ULong must have $typeSize bytes" }
return ByteBuffer.allocate(this.size).let {
it.order(inByteOrder)
it.put(this)
it.flip()
it.getLong().toULong()
}
}
//similar to this.toString(StandardCharsets.UTF_8).replace("${Character.MIN_VALUE}", "")
// not Deprecated for now, "1.3.41 experimental api: ByteArray.decodeToString()") is a little different
fun ByteArray.toCString(): String {
return this.toString(StandardCharsets.UTF_8).let { str ->
str.indexOf(Character.MIN_VALUE).let { nullPos ->
if (nullPos >= 0) str.substring(0, nullPos) else str
}
}
}
}//end-of-Companion
}//end-of-ByteArrayExt
}
| helper/src/main/kotlin/cfig/io/Struct3.kt | 1967103751 |
/*
* Lantern
*
* Copyright (c) LanternPowered <https://www.lanternpowered.org>
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* This work is licensed under the terms of the MIT License (MIT). For
* a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>.
*/
package org.lanternpowered.server.network.vanilla.packet.codec.play
import org.lanternpowered.server.network.buffer.ByteBuffer
import org.lanternpowered.server.network.packet.PacketDecoder
import org.lanternpowered.server.network.packet.CodecContext
import org.lanternpowered.server.network.vanilla.packet.type.play.GenerateJigsawStructurePacket
object GenerateJigsawStructureDecoder : PacketDecoder<GenerateJigsawStructurePacket> {
override fun decode(ctx: CodecContext, buf: ByteBuffer): GenerateJigsawStructurePacket {
return buf.run {
val position = readBlockPosition()
val levels = readInt()
GenerateJigsawStructurePacket(position, levels)
}
}
}
| src/main/kotlin/org/lanternpowered/server/network/vanilla/packet/codec/play/GenerateJigsawStructureDecoder.kt | 4273206292 |
// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.integration.deploy.gcloud
import java.time.Clock
import org.wfanet.measurement.common.identity.RandomIdGenerator
import org.wfanet.measurement.gcloud.spanner.testing.SpannerEmulatorDatabaseRule
import org.wfanet.measurement.integration.common.InProcessKingdom
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.SpannerDataServices
import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.testing.Schemata
private const val REDIRECT_URI = "https://localhost:2048"
private const val ALLOW_MPC_PROTOCOLS_FOR_SINGLE_DATA_PROVIDER = true
fun buildKingdomSpannerEmulatorDatabaseRule(): SpannerEmulatorDatabaseRule {
return SpannerEmulatorDatabaseRule(Schemata.KINGDOM_CHANGELOG_PATH)
}
fun buildSpannerInProcessKingdom(
databaseRule: SpannerEmulatorDatabaseRule,
clock: Clock = Clock.systemUTC(),
verboseGrpcLogging: Boolean = false
): InProcessKingdom {
return InProcessKingdom(
dataServicesProvider = {
SpannerDataServices(clock, RandomIdGenerator(clock), databaseRule.databaseClient)
},
verboseGrpcLogging = verboseGrpcLogging,
REDIRECT_URI,
ALLOW_MPC_PROTOCOLS_FOR_SINGLE_DATA_PROVIDER
)
}
| src/main/kotlin/org/wfanet/measurement/integration/deploy/gcloud/InProcessKingdom.kt | 50542853 |
package ch.difty.scipamato.core.sync.houskeeping
import ch.difty.scipamato.publ.db.tables.records.CodeRecord
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.amshove.kluent.shouldBeEqualTo
import org.jooq.DeleteConditionStep
import org.junit.jupiter.api.Test
import org.springframework.batch.core.StepContribution
import org.springframework.batch.core.scope.context.ChunkContext
import org.springframework.batch.repeat.RepeatStatus
internal class PseudoForeignKeyConstraintEnforcerTest {
private val stepMock = mockk<DeleteConditionStep<CodeRecord>>(relaxed = true)
private val contributionMock = mockk<StepContribution>()
private val chunkContextMock = mockk<ChunkContext>()
private var enforcer = PseudoForeignKeyConstraintEnforcer(stepMock, "code", "s")
@Test
fun executing_withNullStep_doesNotThrow() {
enforcer = PseudoForeignKeyConstraintEnforcer(null, "code", "s")
enforcer.execute(contributionMock, chunkContextMock) shouldBeEqualTo RepeatStatus.FINISHED
}
@Test
fun executing_returnsFinishedStatus() {
enforcer.execute(contributionMock, chunkContextMock) shouldBeEqualTo RepeatStatus.FINISHED
verify { stepMock.execute() }
}
@Test
fun executing_withNoExplicitPlural_returnsFinishedStatus_asIfPluralWereS() {
enforcer = PseudoForeignKeyConstraintEnforcer(stepMock, "code")
enforcer.execute(contributionMock, chunkContextMock) shouldBeEqualTo RepeatStatus.FINISHED
verify { stepMock.execute() }
}
@Test
fun executing_withSingleModifications_logs() {
every { stepMock.execute() } returns 1
enforcer.execute(contributionMock, chunkContextMock)
verify { stepMock.execute() }
// log un-asserted, log format different from the one in the next test (visual assertion)
}
@Test
fun executing_withMultipleModifications_logs() {
every { stepMock.execute() } returns 2
enforcer.execute(contributionMock, chunkContextMock)
verify { stepMock.execute() }
// log un-asserted, log format different form that in the previous test (visual assertion)
}
@Test
fun executing_withoutModifications_skipsLog() {
every { stepMock.execute() } returns 0
enforcer.execute(contributionMock, chunkContextMock)
verify { stepMock.execute() }
// missing log un-asserted (visual assertion)
}
@Test
fun executing_ignoresContributionMock() {
enforcer.execute(contributionMock, chunkContextMock)
confirmVerified(contributionMock)
}
@Test
fun executing_ignoresChunkContextMock() {
enforcer.execute(contributionMock, chunkContextMock)
confirmVerified(chunkContextMock)
}
}
| core/core-sync/src/test/kotlin/ch/difty/scipamato/core/sync/houskeeping/PseudoForeignKeyConstraintEnforcerTest.kt | 1457065467 |
package me.giorgirokhadze.hello.jmx.jetty
class CounterSingleton private constructor() {
var counter: Int = 0
private set
init {
counter = 0
}
@Synchronized fun increment() {
counter++
}
@Synchronized fun reset() {
counter = 0
}
companion object {
val instance = CounterSingleton()
}
}
| JMX/src/main/java/me/giorgirokhadze/hello/jmx/jetty/CounterSingleton.kt | 422061666 |
/*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.api.entity
import com.squareup.moshi.Json
import net.simonvt.cathode.api.enumeration.Gender
data class Profile(
val username: String,
@Json(name = "private") val isPrivate: Boolean? = null,
val name: String? = null,
val vip: Boolean? = null,
val vip_ep: Boolean? = null,
val vip_og: Boolean? = null,
val vip_years: Int? = null,
val joined_at: IsoTime? = null,
val location: String? = null,
val about: String? = null,
val gender: Gender? = null,
val age: Int? = null,
val images: Images? = null
)
| trakt-api/src/main/java/net/simonvt/cathode/api/entity/Profile.kt | 4197830826 |
/*
* Copyright (C) 2013 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.actions.user
import android.content.ContentProviderOperation
import android.content.ContentValues
import android.content.Context
import net.simonvt.cathode.actions.CallAction
import net.simonvt.cathode.api.entity.Movie
import net.simonvt.cathode.api.enumeration.Extended
import net.simonvt.cathode.api.service.RecommendationsService
import net.simonvt.cathode.common.database.forEach
import net.simonvt.cathode.common.database.getLong
import net.simonvt.cathode.provider.DatabaseContract.MovieColumns
import net.simonvt.cathode.provider.ProviderSchematic.Movies
import net.simonvt.cathode.provider.batch
import net.simonvt.cathode.provider.helper.MovieDatabaseHelper
import net.simonvt.cathode.provider.query
import net.simonvt.cathode.settings.SuggestionsTimestamps
import retrofit2.Call
import javax.inject.Inject
class SyncMovieRecommendations @Inject constructor(
private val context: Context,
private val movieHelper: MovieDatabaseHelper,
private val recommendationsService: RecommendationsService
) : CallAction<Unit, List<Movie>>() {
override fun key(params: Unit): String = "SyncMovieRecommendations"
override fun getCall(params: Unit): Call<List<Movie>> =
recommendationsService.movies(LIMIT, Extended.FULL)
override suspend fun handleResponse(params: Unit, response: List<Movie>) {
val ops = arrayListOf<ContentProviderOperation>()
val movieIds = mutableListOf<Long>()
val localMovies = context.contentResolver.query(Movies.RECOMMENDED)
localMovies.forEach { cursor -> movieIds.add(cursor.getLong(MovieColumns.ID)) }
localMovies.close()
response.forEachIndexed { index, movie ->
val movieId = movieHelper.partialUpdate(movie)
movieIds.remove(movieId)
val values = ContentValues()
values.put(MovieColumns.RECOMMENDATION_INDEX, index)
val op = ContentProviderOperation.newUpdate(Movies.withId(movieId)).withValues(values).build()
ops.add(op)
}
for (id in movieIds) {
val op = ContentProviderOperation.newUpdate(Movies.withId(id))
.withValue(MovieColumns.RECOMMENDATION_INDEX, -1)
.build()
ops.add(op)
}
context.contentResolver.batch(ops)
SuggestionsTimestamps.get(context)
.edit()
.putLong(SuggestionsTimestamps.MOVIES_RECOMMENDED, System.currentTimeMillis())
.apply()
}
companion object {
private const val LIMIT = 50
}
}
| cathode-sync/src/main/java/net/simonvt/cathode/actions/user/SyncMovieRecommendations.kt | 285152114 |
/*
* Copyright 2016 Burke Choi All rights reserved.
* http://www.sarangnamu.net
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.sarangnamu.common.arch.viewmodel
import android.arch.lifecycle.ViewModel
import android.databinding.ObservableArrayList
import android.databinding.ObservableField
import net.sarangnamu.common.arch.adapter.BkAdapter
/**
* Created by <a href="mailto:[email protected]">Burke Choi</a> on 2018. 5. 11.. <p/>
*/
open class RecyclerViewModel<T> : ViewModel() {
val items = ObservableArrayList<T>()
val adapter = ObservableField<BkAdapter<T>>()
open fun initAdapter(id: String) {
val adapter = BkAdapter<T>(id)
adapter.items = this.items
adapter.vmodel = this
this.adapter.set(adapter)
}
open fun initAdapter(ids: Array<String>) {
val adapter = BkAdapter<T>(ids)
adapter.items = this.items
adapter.vmodel = this
this.adapter.set(adapter)
}
fun clearItems(items: ArrayList<T>) {
this.items.clear()
this.items.addAll(items)
}
} | library/src/main/java/net/sarangnamu/common/arch/viewmodel/RecyclerViewModel.kt | 575108578 |
/*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.simonvt.cathode.api.body
class RateItems private constructor(val movies: List<RatingMovie>, val shows: List<RatingShow>) {
class Builder {
val movies = mutableListOf<RatingMovie>()
val shows = mutableListOf<RatingShow>()
fun movie(traktId: Long, rating: Int, ratedAt: String): Builder {
val movie = movies.firstOrNull { it.ids.trakt == traktId }
if (movie != null) {
throw IllegalArgumentException("Movie $traktId already rated in this request")
}
movies.add(RatingMovie(TraktId(traktId), rating, ratedAt))
return this
}
fun show(traktId: Long, rating: Int, ratedAt: String): Builder {
val show = shows.firstOrNull { it.ids.trakt == traktId }
if (show?.rating != null) {
throw IllegalArgumentException("Show $traktId already rated in this request")
}
shows.add(RatingShow(TraktId(traktId), rating, ratedAt))
return this
}
fun season(showTraktId: Long, season: Int, rating: Int, ratedAt: String): Builder {
var show: RatingShow? = shows.firstOrNull { it.ids.trakt == showTraktId }
if (show == null) {
show = RatingShow(TraktId(showTraktId))
shows.add(show)
}
val ratingSeason = show.seasons.firstOrNull { it.number == season }
if (ratingSeason?.rating != null) {
throw IllegalArgumentException("Season $showTraktId-$season already rated in this request")
}
show.seasons.add(RatingSeason(season, rating, ratedAt))
return this
}
fun episode(
showTraktId: Long,
season: Int,
episode: Int,
rating: Int,
ratedAt: String
): Builder {
var show: RatingShow? = shows.firstOrNull { it.ids.trakt == showTraktId }
if (show == null) {
show = RatingShow(TraktId(showTraktId))
shows.add(show)
}
var ratingSeason = show.seasons.firstOrNull { it.number == season }
if (ratingSeason == null) {
ratingSeason = RatingSeason(season)
show.seasons.add(ratingSeason)
}
val ratingEpisode = ratingSeason.episodes.firstOrNull { it.number == episode }
if (ratingEpisode == null) {
ratingSeason.episodes.add(RatingEpisode(episode, rating, ratedAt))
} else {
throw IllegalArgumentException("Episode $showTraktId-$season-$episode already rated in this request")
}
return this
}
fun build(): RateItems {
return RateItems(movies, shows)
}
}
}
class RatingMovie internal constructor(val ids: TraktId, val rating: Int, val rated_at: String)
class RatingShow internal constructor(
val ids: TraktId,
val rating: Int? = null,
val rated_at: String? = null,
val seasons: MutableList<RatingSeason> = mutableListOf()
)
class RatingSeason(
val number: Int,
val rating: Int? = null,
val rated_at: String? = null,
val episodes: MutableList<RatingEpisode> = mutableListOf()
)
class RatingEpisode(val number: Int, val rating: Int, val rated_at: String)
| trakt-api/src/main/java/net/simonvt/cathode/api/body/RateItems.kt | 1136837162 |
/*
Copyright 2017 Google Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package com.google.androidstudiopoet.generators.android_modules
import com.google.androidstudiopoet.models.ActivityBlueprint
interface ActivityGenerator {
fun generate(blueprint: ActivityBlueprint)
}
| aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/android_modules/ActivityGenerator.kt | 2328043968 |
package org.rliz.cfm.recorder.playback.data
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import javax.persistence.Column
import javax.persistence.ElementCollection
import javax.persistence.Entity
import javax.persistence.FetchType
import javax.persistence.GeneratedValue
import javax.persistence.Id
import javax.validation.constraints.NotNull
import javax.validation.constraints.Size
@Entity
class RawPlaybackData {
@Id
@GeneratedValue
var oid: Long? = null
@NotNull
@ElementCollection(fetch = FetchType.LAZY)
@Size(min = 1)
@Fetch(FetchMode.SUBSELECT)
var artists: List<String>? = null
@NotNull
@Size(min = 1, max = 1024)
@Column(length = 1024)
var artistJson: String? = null
@NotNull
@Size(min = 1)
var recordingTitle: String? = null
@NotNull
@Size(min = 1)
var releaseTitle: String? = null
var length: Long? = null
var discNumber: Int? = null
var trackNumber: Int? = null
constructor()
constructor(
artists: List<String>?,
artistJson: String?,
recordingTitle: String?,
releaseTitle: String?,
length: Long? = null,
discNumber: Int? = null,
trackNumber: Int? = null
) : this() {
this.artists = artists
this.artistJson = artistJson
this.recordingTitle = recordingTitle
this.releaseTitle = releaseTitle
this.length = length
this.discNumber = discNumber
this.trackNumber = trackNumber
}
}
| server/recorder/src/main/kotlin/org/rliz/cfm/recorder/playback/data/RawPlaybackData.kt | 2807075628 |
/**
* Created by njasm on 02/07/2017.
*/
package com.github.njasm.kotwave
import com.github.kittinunf.fuel.core.Request
import java.util.*
internal class Auth(internal var token: Token) {
internal var dataDate: Calendar = Calendar.getInstance()
val accessToken
get() = this.token.access_token
val tokenScope
get() = this.token.scope
val refreshToken
get() = this.token.refresh_token
fun addOauthHeader(req: Request) {
if (tokenIsNotEmpty()
&& !req.headers.containsKey("Authorization")
&& !isTokenExpired()
) {
req.header("Authorization" to "OAuth " + this.accessToken.trim())
}
}
fun isTokenExpired(): Boolean {
when (this.getExpiresIn()) {
null -> return false
else -> {
dataDate.add(Calendar.SECOND, getExpiresIn()!!)
return dataDate.compareTo(Calendar.getInstance()) <= 0
}
}
}
private fun getExpiresIn(): Int? = this.token.expires_in
private fun tokenIsNotEmpty(): Boolean = this.accessToken.isNotEmpty()
}
internal data class Token(
val access_token: String = "",
val scope: String = "",
val expires_in: Int? = null,
val refresh_token: String? = null
)
| src/main/kotlin/com/github/njasm/kotwave/Auth.kt | 2829077251 |
package com.jamieadkins.gwent.data.update.repository
import com.f2prateek.rx.preferences2.RxSharedPreferences
import com.jamieadkins.gwent.data.update.CardUpdate
import com.jamieadkins.gwent.data.update.CategoryUpdate
import com.jamieadkins.gwent.data.update.KeywordUpdate
import com.jamieadkins.gwent.data.update.NotificationsUpdate
import com.jamieadkins.gwent.database.GwentDatabase
import com.jamieadkins.gwent.domain.update.model.UpdateResult
import com.jamieadkins.gwent.domain.update.repository.UpdateRepository
import io.reactivex.Completable
import io.reactivex.Observable
import io.reactivex.functions.Function3
import io.reactivex.functions.Function4
import java.io.File
import javax.inject.Inject
import javax.inject.Named
class UpdateRepositoryImpl @Inject constructor(
@Named("files") filesDirectory: File,
preferences: RxSharedPreferences,
@NotificationsUpdate private val notificationsRepository: UpdateRepository,
@CardUpdate private val cardUpdateRepository: UpdateRepository,
@KeywordUpdate private val keywordUpdateRepository: UpdateRepository,
@CategoryUpdate private val categoryUpdateRepository: UpdateRepository
) : BaseUpdateRepository(filesDirectory, preferences) {
// Unused.
override val FILE_NAME = ""
override fun isUpdateAvailable(): Observable<Boolean> {
return Observable.combineLatest(
cardUpdateRepository.isUpdateAvailable(),
keywordUpdateRepository.isUpdateAvailable(),
categoryUpdateRepository.isUpdateAvailable(),
Function3 { card: Boolean, keyword: Boolean, category: Boolean ->
card || keyword || category
})
.onErrorReturnItem(false)
.distinctUntilChanged()
}
override fun internalPerformUpdate(): Completable {
return cardUpdateRepository.performUpdate()
.andThen(keywordUpdateRepository.performUpdate())
.andThen(categoryUpdateRepository.performUpdate())
}
override fun hasDoneFirstTimeSetup(): Observable<Boolean> {
return Observable.combineLatest(
notificationsRepository.hasDoneFirstTimeSetup(),
cardUpdateRepository.hasDoneFirstTimeSetup(),
keywordUpdateRepository.hasDoneFirstTimeSetup(),
categoryUpdateRepository.hasDoneFirstTimeSetup(),
Function4 { notifications: Boolean, card: Boolean, keyword: Boolean, category: Boolean ->
notifications && card && keyword && category
})
.distinctUntilChanged()
}
override fun internalPerformFirstTimeSetup(): Completable {
return notificationsRepository.performFirstTimeSetup()
.andThen(cardUpdateRepository.performFirstTimeSetup())
.andThen(keywordUpdateRepository.performFirstTimeSetup())
.andThen(categoryUpdateRepository.performFirstTimeSetup())
}
} | data/src/main/java/com/jamieadkins/gwent/data/update/repository/UpdateRepositoryImpl.kt | 1660358742 |
package org.jetbrains.settingsRepository.test
import com.intellij.openapi.vcs.merge.MergeSession
import com.intellij.testFramework.ProjectRule
import org.eclipse.jgit.api.Git
import org.eclipse.jgit.lib.Repository
import org.jetbrains.settingsRepository.CannotResolveConflictInTestMode
import org.jetbrains.settingsRepository.SyncType
import org.jetbrains.settingsRepository.conflictResolver
import org.jetbrains.settingsRepository.git.GitRepositoryManager
import org.jetbrains.settingsRepository.git.commit
import org.jetbrains.settingsRepository.git.resetHard
import org.junit.ClassRule
import java.nio.file.FileSystem
import java.util.*
import kotlin.properties.Delegates
internal abstract class GitTestCase : IcsTestCase() {
companion object {
@JvmField
@ClassRule val projectRule = ProjectRule()
}
protected val repositoryManager: GitRepositoryManager
get() = icsManager.repositoryManager as GitRepositoryManager
protected val repository: Repository
get() = repositoryManager.repository
protected var remoteRepository: Repository by Delegates.notNull()
init {
conflictResolver = { files, mergeProvider ->
val mergeSession = mergeProvider.createMergeSession(files)
for (file in files) {
val mergeData = mergeProvider.loadRevisions(file)
if (Arrays.equals(mergeData.CURRENT, MARKER_ACCEPT_MY) || Arrays.equals(mergeData.LAST, MARKER_ACCEPT_THEIRS)) {
mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedYours)
}
else if (Arrays.equals(mergeData.CURRENT, MARKER_ACCEPT_THEIRS) || Arrays.equals(mergeData.LAST, MARKER_ACCEPT_MY)) {
mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedTheirs)
}
else if (Arrays.equals(mergeData.LAST, MARKER_ACCEPT_MY)) {
file.setBinaryContent(mergeData.LAST)
mergeProvider.conflictResolvedForFile(file)
}
else {
throw CannotResolveConflictInTestMode()
}
}
}
}
class FileInfo(val name: String, val data: ByteArray)
protected fun addAndCommit(path: String): FileInfo {
val data = """<file path="$path" />""".toByteArray()
provider.write(path, data)
repositoryManager.commit()
return FileInfo(path, data)
}
protected fun createRemoteRepository(branchName: String? = null, initialCommit: Boolean = false) {
val repository = tempDirManager.createRepository("upstream")
if (initialCommit) {
repository
.add(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT)
.commit("")
}
if (branchName != null) {
if (!initialCommit) {
// jgit cannot checkout&create branch if no HEAD (no commits in our empty repository), so we create initial empty commit
repository.commit("")
}
Git(repository).checkout().setCreateBranch(true).setName(branchName).call()
}
remoteRepository = repository
}
protected fun restoreRemoteAfterPush() {
/** we must not push to non-bare repository - but we do it in test (our sync merge equals to "pull&push"),
"
By default, updating the current branch in a non-bare repository
is denied, because it will make the index and work tree inconsistent
with what you pushed, and will require 'git reset --hard' to match the work tree to HEAD.
"
so, we do "git reset --hard"
*/
remoteRepository.resetHard()
}
protected fun sync(syncType: SyncType) {
icsManager.sync(syncType)
}
protected fun createLocalAndRemoteRepositories(remoteBranchName: String? = null, initialCommit: Boolean = false) {
createRemoteRepository(remoteBranchName, true)
configureLocalRepository(remoteBranchName)
if (initialCommit) {
addAndCommit("local.xml")
}
}
protected fun configureLocalRepository(remoteBranchName: String? = null) {
repositoryManager.setUpstream(remoteRepository.workTree.absolutePath, remoteBranchName)
}
protected fun FileSystem.compare(): FileSystem {
val root = getPath("/")!!
compareFiles(root, repository.workTreePath)
compareFiles(root, remoteRepository.workTreePath)
return this
}
} | plugins/settings-repository/testSrc/GitTestCase.kt | 953140575 |
package com.hartwig.hmftools.cider
import htsjdk.samtools.SAMRecord
import org.eclipse.collections.api.factory.Lists
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class VjReadLayoutAdaptorTest
{
@Test
fun testReadCandidateToLayoutReadPosStrand()
{
val layoutAdaptor = VJReadLayoutAdaptor(0)
val seq = "AAGACACGGC" // 10 bases long
// test V read
var anchorOffsetStart = 2
var anchorOffsetEnd = 6
var readCandidate = createReadCandidate(seq, false,
false, VJ.V, anchorOffsetStart, anchorOffsetEnd)
var layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("GACACGGC", layoutRead.sequence) // remove the bases before anchor
assertEquals(3, layoutRead.alignedPosition) // aligned at last base of anchor
// now test J read
anchorOffsetStart = 5
anchorOffsetEnd = 8
readCandidate = createReadCandidate(seq, false,
false, VJ.J, anchorOffsetStart, anchorOffsetEnd)
layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("AAGACACG", layoutRead.sequence) // remove the bases after anchor
assertEquals(5, layoutRead.alignedPosition) // aligned at first base of anchor
}
@Test
fun testReadCandidateToLayoutReadNegStrand()
{
val layoutAdaptor = VJReadLayoutAdaptor(0)
val seq = "GCCGTGTCTT" // 10 bases long, reverse comp of AAGACACGGC
// test V read
var anchorOffsetStart = 2
var anchorOffsetEnd = 6
var readCandidate = createReadCandidate(seq, false,
true, VJ.V, anchorOffsetStart, anchorOffsetEnd)
var layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("GACACGGC", layoutRead.sequence) // remove the bases before anchor
assertEquals(3, layoutRead.alignedPosition) // aligned at last base of anchor
// now test J read
anchorOffsetStart = 5
anchorOffsetEnd = 8
readCandidate = createReadCandidate(seq, false,
true, VJ.J, anchorOffsetStart, anchorOffsetEnd)
layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("AAGACACG", layoutRead.sequence) // remove the bases after anchor
assertEquals(5, layoutRead.alignedPosition) // aligned at first base of anchor
}
@Test
fun testReadCandidateToLayoutReadPolyG()
{
val layoutAdaptor = VJReadLayoutAdaptor(0)
val seq = "AAGACACGGC" + "GTACT" + "G".repeat(8) // 10 bases long + 5 bases + 8 Gs
// test V read
var anchorOffsetStart = 2
var anchorOffsetEnd = 6
var readCandidate = createReadCandidate(seq, false,
false, VJ.V, anchorOffsetStart, anchorOffsetEnd)
var layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("GACACGGC", layoutRead.sequence) // remove the bases before anchor
assertEquals(3, layoutRead.alignedPosition) // aligned at last base of anchor
// now test J read
anchorOffsetStart = 5
anchorOffsetEnd = 8
readCandidate = createReadCandidate(seq, false,
false, VJ.J, anchorOffsetStart, anchorOffsetEnd)
layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("AAGACACG", layoutRead.sequence) // remove the bases after anchor
assertEquals(5, layoutRead.alignedPosition) // aligned at first base of anchor
}
@Test
fun testReadCandidateToLayoutReadPolyC()
{
val layoutAdaptor = VJReadLayoutAdaptor(0)
val seq = "C".repeat(8) + "GTACT" + "AAGACACGGC" // 8 Cs + 5 bases + 10 bases long
// test V read
var anchorOffsetStart = 2 + 13 // 8 Cs + 5 bases
var anchorOffsetEnd = 6 + 13
var readCandidate = createReadCandidate(seq, true,
false, VJ.V, anchorOffsetStart, anchorOffsetEnd)
var layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("GACACGGC", layoutRead.sequence) // remove the bases before anchor
assertEquals(3, layoutRead.alignedPosition) // aligned at last base of anchor
// now test J read
anchorOffsetStart = 5 + 13
anchorOffsetEnd = 8 + 13
readCandidate = createReadCandidate(seq, true,
false, VJ.J, anchorOffsetStart, anchorOffsetEnd)
layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("AAGACACG", layoutRead.sequence) // remove the bases after anchor
assertEquals(5, layoutRead.alignedPosition) // aligned at first base of anchor
}
@Test
fun testReadCandidateToLayoutReadTrimBasesPolyG()
{
val layoutAdaptor = VJReadLayoutAdaptor(1)
var seq = "AAGACACGGC" + "GTACT" + "G".repeat(8) // 10 bases long + 5 bases + 8 Gs
// add 1 base around for trim
seq = "T" + seq + "A"
// test V read
var anchorOffsetStart = 2 + 1
var anchorOffsetEnd = 6 + 1
var readCandidate = createReadCandidate(seq, false,
false, VJ.V, anchorOffsetStart, anchorOffsetEnd)
var layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("GACACGGC", layoutRead.sequence) // remove the bases before anchor
assertEquals(3, layoutRead.alignedPosition) // aligned at last base of anchor
// now test J read
anchorOffsetStart = 5 + 1
anchorOffsetEnd = 8 + 1
readCandidate = createReadCandidate(seq, false,
false, VJ.J, anchorOffsetStart, anchorOffsetEnd)
layoutRead = layoutAdaptor.readCandidateToLayoutRead(readCandidate)
assertNotNull(layoutRead)
assertEquals("AAGACACG", layoutRead.sequence) // remove the bases after anchor
assertEquals(5, layoutRead.alignedPosition) // aligned at first base of anchor
}
@Test
fun testReadCandidateToLayoutReadTrimBasesPolyC()
{
}
fun createReadCandidate(seq: String, isReadNegativeStrand: Boolean, useReverseComplement: Boolean, vj: VJ,
anchorOffsetStart: Int, anchorOffsetEnd: Int) : VJReadCandidate
{
val record = SAMRecord(null)
record.readName = "read"
record.readPairedFlag = true
record.firstOfPairFlag = true
record.readNegativeStrandFlag = isReadNegativeStrand
record.readString = seq
record.baseQualityString = "F".repeat(seq.length)
val vjGeneType = if (vj == VJ.V) VJGeneType.TRAV else VJGeneType.TRAJ
return VJReadCandidate(record, Lists.immutable.empty(), vjGeneType,
"CACGTG", VJReadCandidate.MatchMethod.ALIGN,
useReverseComplement, anchorOffsetStart, anchorOffsetEnd,
0, 0)
}
} | cider/src/test/java/com/hartwig/hmftools/cider/VjReadLayoutAdaptorTest.kt | 3602464082 |
package com.quickblox.sample.conference.kotlin.presentation.screens.main
import android.os.Bundle
import com.quickblox.chat.model.QBChatDialog
import com.quickblox.sample.conference.kotlin.R
import com.quickblox.sample.conference.kotlin.domain.DomainCallback
import com.quickblox.sample.conference.kotlin.domain.chat.ChatManager
import com.quickblox.sample.conference.kotlin.domain.chat.ConnectionChatListener
import com.quickblox.sample.conference.kotlin.domain.chat.DialogListener
import com.quickblox.sample.conference.kotlin.domain.push.PushManager
import com.quickblox.sample.conference.kotlin.domain.repositories.connection.ConnectionRepository
import com.quickblox.sample.conference.kotlin.domain.repositories.connection.ConnectivityChangedListener
import com.quickblox.sample.conference.kotlin.domain.user.UserManager
import com.quickblox.sample.conference.kotlin.presentation.LiveData
import com.quickblox.sample.conference.kotlin.presentation.resources.ResourcesManager
import com.quickblox.sample.conference.kotlin.presentation.screens.base.BaseViewModel
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.ERROR
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.LIST_DIALOGS_UPDATED
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.MOVE_TO_FIRST_DIALOG
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.PROGRESS
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_CHAT_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_CREATE_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_DIALOGS
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_LOGIN_SCREEN
import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.USER_ERROR
import com.quickblox.users.model.QBUser
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
const val DIALOGS_LIMIT = 100
const val EXTRA_TOTAL_ENTRIES = "total_entries"
const val EXTRA_SKIP = "skip"
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
@HiltViewModel
class MainViewModel @Inject constructor(private val userManager: UserManager, private val chatManager: ChatManager,
private val resourcesManager: ResourcesManager, private val pushManager: PushManager,
private val connectionRepository: ConnectionRepository) : BaseViewModel() {
private val TAG: String = MainViewModel::class.java.simpleName
private var selectedDialogId: String? = null
private val connectionListener = ConnectionListener(TAG)
private val dialogListener = DialogListenerImpl(TAG)
val liveData = LiveData<Pair<Int, Any?>>()
var user: QBUser? = null
private set
private val connectivityChangedListener = ConnectivityChangedListenerImpl(TAG)
init {
user = userManager.getCurrentUser()
}
fun getDialogs(): ArrayList<QBChatDialog> {
return chatManager.getDialogs()
}
private fun loginToChat(user: QBUser?) {
if (user == null) {
liveData.setValue(Pair(USER_ERROR, null))
} else {
chatManager.loginToChat(user, object : DomainCallback<Unit, Exception> {
override fun onSuccess(result: Unit, bundle: Bundle?) {
subscribeChatListener()
loadDialogs(refresh = true, reJoin = true)
}
override fun onError(error: Exception) {
liveData.setValue(Pair(ERROR, error.message))
}
})
}
}
fun singOut() {
if (!connectionRepository.isInternetAvailable()) {
liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.no_internet)))
return
}
liveData.setValue(Pair(PROGRESS, null))
if (pushManager.isSubscribed()) {
pushManager.unSubscribe {
userManager.signOut(object : DomainCallback<Unit?, Exception> {
override fun onSuccess(result: Unit?, bundle: Bundle?) {
chatManager.clearDialogs()
chatManager.unsubscribeDialogListener(dialogListener)
chatManager.unSubscribeConnectionChatListener(connectionListener)
chatManager.destroyChat()
liveData.setValue(Pair(SHOW_LOGIN_SCREEN, null))
}
override fun onError(error: Exception) {
liveData.setValue(Pair(ERROR, error.message))
}
})
}
} else {
userManager.signOut(object : DomainCallback<Unit?, Exception> {
override fun onSuccess(result: Unit?, bundle: Bundle?) {
chatManager.clearDialogs()
chatManager.unsubscribeDialogListener(dialogListener)
chatManager.unSubscribeConnectionChatListener(connectionListener)
chatManager.destroyChat()
liveData.setValue(Pair(SHOW_LOGIN_SCREEN, null))
}
override fun onError(error: Exception) {
liveData.setValue(Pair(ERROR, error.message))
}
})
}
}
fun loadDialogs(refresh: Boolean, reJoin: Boolean) {
liveData.setValue(Pair(PROGRESS, null))
chatManager.loadDialogs(refresh, reJoin, object : DomainCallback<ArrayList<QBChatDialog>, Exception> {
override fun onSuccess(result: ArrayList<QBChatDialog>, bundle: Bundle?) {
liveData.setValue(Pair(SHOW_DIALOGS, chatManager.getDialogs()))
}
override fun onError(error: Exception) {
liveData.setValue(Pair(ERROR, error.message))
}
})
}
fun deleteDialogs(dialogs: ArrayList<QBChatDialog>) {
liveData.setValue(Pair(PROGRESS, null))
user?.let {
chatManager.deleteDialogs(dialogs, it, object : DomainCallback<List<QBChatDialog>, Exception> {
override fun onSuccess(notDeletedDialogs: List<QBChatDialog>, bundle: Bundle?) {
if (notDeletedDialogs.isNotEmpty()) {
liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.not_deleted_dialogs, notDeletedDialogs.size)))
return
}
liveData.setValue(Pair(LIST_DIALOGS_UPDATED, null))
}
override fun onError(error: Exception) {
// Empty
}
})
}
}
private fun subscribeChatListener() {
chatManager.subscribeDialogListener(dialogListener)
chatManager.subscribeConnectionChatListener(connectionListener)
}
override fun onResumeView() {
connectionRepository.addListener(connectivityChangedListener)
if (chatManager.isLoggedInChat()) {
subscribeChatListener()
loadDialogs(refresh = true, reJoin = true)
} else {
loginToChat(user)
}
}
override fun onStopView() {
connectionRepository.removeListener(connectivityChangedListener)
chatManager.unsubscribeDialogListener(dialogListener)
chatManager.unSubscribeConnectionChatListener(connectionListener)
}
override fun onStopApp() {
chatManager.destroyChat()
}
fun onDialogClicked(dialog: QBChatDialog) {
if (!connectionRepository.isInternetAvailable()) {
liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.no_internet)))
return
}
selectedDialogId = dialog.dialogId
liveData.setValue(Pair(SHOW_CHAT_SCREEN, dialog))
}
fun showCreateScreen() {
if (!connectionRepository.isInternetAvailable()) {
liveData.setValue(Pair(ERROR, Exception(resourcesManager.get().getString(R.string.no_internet))))
return
}
liveData.setValue(Pair(SHOW_CREATE_SCREEN, null))
}
private inner class ConnectionListener(val tag: String) : ConnectionChatListener {
override fun onConnectedChat() {
liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.connected)))
}
override fun onError(exception: Exception) {
liveData.setValue(Pair(ERROR, exception.message))
}
override fun reconnectionFailed(exception: Exception) {
liveData.setValue(Pair(ERROR, exception.message))
loginToChat(user)
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is ConnectionListener) {
return false
}
return tag == other.tag
}
override fun hashCode(): Int {
var hash = 1
hash = 31 * hash + tag.hashCode()
return hash
}
}
private inner class DialogListenerImpl(val tag: String) : DialogListener {
override fun onUpdatedDialog(dialog: QBChatDialog) {
if (chatManager.getDialogs().isEmpty()) {
loadDialogs(refresh = true, reJoin = false)
} else {
liveData.setValue(Pair(MOVE_TO_FIRST_DIALOG, dialog))
}
}
override fun onError(exception: Exception) {
liveData.setValue(Pair(ERROR, exception.message))
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is DialogListenerImpl) {
return false
}
return tag == other.tag
}
override fun hashCode(): Int {
var hash = 1
hash = 31 * hash + tag.hashCode()
return hash
}
}
private inner class ConnectivityChangedListenerImpl(val tag: String) : ConnectivityChangedListener {
override fun onAvailable() {
if (!chatManager.isLoggedInChat()) {
liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.internet_restored)))
loginToChat(user)
}
}
override fun onLost() {
liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.no_internet)))
}
override fun equals(other: Any?): Boolean {
if (this === other) {
return true
}
if (other !is ConnectivityChangedListenerImpl) {
return false
}
return tag == other.tag
}
override fun hashCode(): Int {
var hash = 1
hash = 31 * hash + tag.hashCode()
return hash
}
}
} | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/main/MainViewModel.kt | 1052437052 |
package net.milosvasic.pussycat.android.application
import net.milosvasic.pussycat.application.APPLICATION_TYPE
import net.milosvasic.pussycat.application.PUSSYCAT_MODE
class ApplicationTestTerminalFilesystemParams4 : ApplicationTestAbstract() {
init {
expectedType = APPLICATION_TYPE.CLI
expectedMode = PUSSYCAT_MODE.FILESYSTEM
}
override fun testApplication() {
params = arrayOf("--terminal", "--filesystem=${localSample.absolutePath}")
super.testApplication()
}
} | Android/src/test/kotlin/net/milosvasic/pussycat/android/application/ApplicationTestTerminalFilesystemParams4.kt | 4101346608 |
package org.embulk.test
import com.google.common.base.CaseFormat.UPPER_CAMEL
import com.google.common.base.CaseFormat.LOWER_UNDERSCORE
import org.embulk.config.DataSource
import kotlin.reflect.KClass
fun ExtendedTestingEmbulk.Builder.registerPlugin(
impl: KClass<*>, name: String? = null, iface: KClass<*>? = null): ExtendedTestingEmbulk.Builder {
return registerPlugin(impl.java, name ?: guessName(impl.java), iface?.java ?: guessInterface(impl.java))
}
fun ExtendedTestingEmbulk.Builder.registerPlugins(vararg impls: KClass<*>): ExtendedTestingEmbulk.Builder {
impls.forEach { registerPlugin(it.java) }
return this
}
fun <T : DataSource> T.set(vararg keyValues: Pair<String, Any>): T {
keyValues.forEach { this.set(it.first, it.second) }
return this
}
fun String.toSnakeCase(): String = UPPER_CAMEL.to(LOWER_UNDERSCORE, this)
| src/main/kotlin/org/embulk/test/extensions.kt | 297125948 |
package cc.aoeiuv020.reader.simple
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import cc.aoeiuv020.reader.*
import kotlinx.android.synthetic.main.simple.view.*
/**
*
* Created by AoEiuV020 on 2017.12.01-02:14:20.
*/
internal class SimpleReader(override var ctx: Context, novel: String, private val parent: ViewGroup, requester: TextRequester, override var config: ReaderConfig)
: BaseNovelReader(novel, requester), ConfigChangedListener {
private val layoutInflater = LayoutInflater.from(ctx)
private val contentView: View = layoutInflater.inflate(R.layout.simple, parent, true)
private val viewPager: androidx.viewpager.widget.ViewPager = contentView.viewPager
private val background: ImageView = contentView.ivBackground
private val dtfRoot: DispatchTouchFrameLayout = contentView.dtfRoot
private val ntpAdapter: NovelTextPagerAdapter
override var chapterList: List<String>
get() = super.chapterList
set(value) {
super.chapterList = value
ntpAdapter.notifyDataSetChanged()
}
override var textProgress: Int
get() = ntpAdapter.getCurrentTextProgress() ?: 0
set(value) {
ntpAdapter.setCurrentTextProgress(value)
}
override val maxTextProgress: Int
get() = ntpAdapter.getCurrentTextCount() ?: 0
override var currentChapter: Int
get() = viewPager.currentItem
set(value) {
viewPager.currentItem = value
}
init {
config.listeners.add(this)
viewPager.addOnPageChangeListener(object : androidx.viewpager.widget.ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) {
menuListener?.hide()
}
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
}
override fun onPageSelected(position: Int) {
if (position != currentChapter) {
currentChapter = position
readingListener?.onReading(position, 0)
}
}
})
dtfRoot.reader = this
ntpAdapter = NovelTextPagerAdapter(this)
viewPager.adapter = ntpAdapter
background.setBackgroundColor(config.backgroundColor)
background.setImageURI(config.backgroundImage)
}
override fun destroy() {
// 清空viewPager,自动调用destroyItem切断presenter,
viewPager.adapter = null
parent.removeView(contentView)
}
override fun refreshCurrentChapter() {
ntpAdapter.refreshCurrentChapter()
}
override fun onConfigChanged(name: ReaderConfigName) {
when (name) {
ReaderConfigName.TextSize -> ntpAdapter.notifyAllItemDataSetChanged()
ReaderConfigName.Font -> ntpAdapter.notifyAllItemDataSetChanged()
ReaderConfigName.TextColor -> ntpAdapter.notifyAllItemDataSetChanged()
ReaderConfigName.LineSpacing -> ntpAdapter.notifyAllItemDataSetChanged()
ReaderConfigName.ParagraphSpacing -> ntpAdapter.notifyAllItemDataSetChanged()
ReaderConfigName.ContentMargins -> ntpAdapter.notifyAllItemContentSpacingChanged()
ReaderConfigName.BackgroundColor -> background.setBackgroundColor(config.backgroundColor)
ReaderConfigName.BackgroundImage -> background.setImageURI(config.backgroundImage)
else -> {
}
}
}
}
| reader/src/main/java/cc/aoeiuv020/reader/simple/SimpleReader.kt | 2088443104 |
package cc.aoeiuv020.panovel.backup
/**
* Created by AoEiuV020 on 2018.05.11-19:32:55.
*/
enum class BackupOption {
Bookshelf,
BookList,
Progress,
Settings,
} | app/src/main/java/cc/aoeiuv020/panovel/backup/BackupOption.kt | 2292997186 |
package com.didichuxing.doraemonkit.widget.brvah.animation
import android.animation.Animator
import android.animation.ObjectAnimator
import android.view.View
import android.view.animation.LinearInterpolator
/**
* https://github.com/CymChad/BaseRecyclerViewAdapterHelper
*/
class AlphaInAnimation @JvmOverloads constructor(private val mFrom: Float = DEFAULT_ALPHA_FROM) : BaseAnimation {
override fun animators(view: View): Array<Animator> {
val animator = ObjectAnimator.ofFloat(view, "alpha", mFrom, 1f)
animator.duration = 300L
animator.interpolator = LinearInterpolator()
return arrayOf(animator)
}
companion object {
private const val DEFAULT_ALPHA_FROM = 0f
}
} | Android/dokit/src/main/java/com/didichuxing/doraemonkit/widget/brvah/animation/AlphaInAnimation.kt | 1869063061 |
package com.icetea09.vivid.camera
import android.content.Context
import android.content.Intent
import com.icetea09.vivid.imagepicker.Configuration
interface CameraModule {
fun getCameraIntent(context: Context, config: Configuration): Intent?
fun getImage(context: Context, intent: Intent?, imageReadyListener: OnImageReadyListener?)
}
| library/src/main/java/com/icetea09/vivid/camera/CameraModule.kt | 4012322043 |
package info.demmonic.kinject
/**
* Represents a simplified facade for loading [Transformer]s.
*
* @author Demmonic
*/
interface TransformerDeserializer {
/**
* Deserializes a [List] of [Transformer]s
*
* @return A [List] of deserialized [Transformer]s
*/
fun getInjectors(): List<Transformer>
} | src/main/java/info/demmonic/kinject/TransformerDeserializer.kt | 1666278234 |
/*
* ******************************************************************************
* Copyright 2014-2017 Spectra Logic Corporation. 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. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file.
* This file 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.spectralogic.ds3autogen.go.models.response
import com.google.common.collect.ImmutableList
import com.google.common.collect.ImmutableSet
data class Response(
val name: String,
val payloadStruct: String, //The struct definition for the response payload
val expectedCodes: String,
val parseResponseMethod: String, //Contains the Go code for the parse method if one is needed, else empty
val responseCodes: ImmutableList<ResponseCode>)
| ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/models/response/Response.kt | 2973154953 |
/*
* Copyright 2021 Brackeys IDE contributors.
*
* 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.brackeys.ui.language.markdown.provider
import com.brackeys.ui.language.base.model.Suggestion
import com.brackeys.ui.language.base.provider.SuggestionProvider
import com.brackeys.ui.language.base.utils.WordsManager
class MarkdownProvider private constructor() : SuggestionProvider {
companion object {
private var markdownProvider: MarkdownProvider? = null
fun getInstance(): MarkdownProvider {
return markdownProvider ?: MarkdownProvider().also {
markdownProvider = it
}
}
}
private val wordsManager = WordsManager()
override fun getAll(): Set<Suggestion> {
return wordsManager.getWords()
}
override fun processLine(lineNumber: Int, text: String) {
wordsManager.processLine(lineNumber, text)
}
override fun deleteLine(lineNumber: Int) {
wordsManager.deleteLine(lineNumber)
}
override fun clearLines() {
wordsManager.clearLines()
}
} | languages/language-markdown/src/main/kotlin/com/brackeys/ui/language/markdown/provider/MarkdownProvider.kt | 4125364241 |
package net.nemerosa.ontrack.kdsl.acceptance.tests.github.system
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import com.fasterxml.jackson.databind.JsonNode
import net.nemerosa.ontrack.json.parse
import net.nemerosa.ontrack.kdsl.acceptance.tests.ACCProperties
import net.nemerosa.ontrack.kdsl.acceptance.tests.github.gitHubClient
import net.nemerosa.ontrack.kdsl.acceptance.tests.support.uid
import net.nemerosa.ontrack.kdsl.acceptance.tests.support.waitUntil
import net.nemerosa.ontrack.kdsl.spec.Branch
import net.nemerosa.ontrack.kdsl.spec.Ontrack
import net.nemerosa.ontrack.kdsl.spec.Project
import net.nemerosa.ontrack.kdsl.spec.extension.git.GitBranchConfigurationProperty
import net.nemerosa.ontrack.kdsl.spec.extension.git.gitBranchConfigurationProperty
import net.nemerosa.ontrack.kdsl.spec.extension.github.GitHubConfiguration
import net.nemerosa.ontrack.kdsl.spec.extension.github.GitHubProjectConfigurationProperty
import net.nemerosa.ontrack.kdsl.spec.extension.github.gitHub
import net.nemerosa.ontrack.kdsl.spec.extension.github.gitHubConfigurationProperty
import org.apache.commons.codec.binary.Base64
import org.springframework.web.client.HttpClientErrorException
import org.springframework.web.client.HttpClientErrorException.NotFound
import org.springframework.web.client.RestClientException
import java.util.*
import kotlin.test.assertTrue
import kotlin.test.fail
fun withTestGitHubRepository(
autoMerge: Boolean = false,
code: GitHubRepositoryContext.() -> Unit,
) {
// Unique name for the repository
val uuid = UUID.randomUUID().toString()
val repo = "ontrack-auto-versioning-test-$uuid"
// Creates the repository
gitHubClient.postForObject(
"/orgs/${ACCProperties.GitHub.organization}/repos",
mapOf(
"name" to repo,
"description" to "Test repository for auto versioning - can be deleted at any time",
"private" to false,
"has_issues" to false,
"has_projects" to false,
"has_wiki" to false
),
Unit::class.java
)
try {
// Context
val context = GitHubRepositoryContext(repo)
// Running the code
context.code()
} finally {
// Deleting the repository
try {
gitHubClient.delete("/repos/${ACCProperties.GitHub.organization}/$repo")
} catch (ignored: RestClientException) {
// Ignoring errors at deletion
}
}
}
class GitHubRepositoryContext(
val repository: String,
) {
fun repositoryFile(
path: String,
branch: String = "main",
content: () -> String,
) {
createBranchIfNotExisting(branch)
val existingFile = getRawFile(path, branch)
val body = mutableMapOf(
"message" to "Creating $path",
"content" to Base64.encodeBase64String(content().toByteArray()),
"branch" to branch,
)
if (existingFile != null) {
body["sha"] = existingFile.sha
}
waitUntil(task = "Setting file content on branch $branch at path $path") {
try {
gitHubClient.put(
"/repos/${ACCProperties.GitHub.organization}/${repository}/contents/$path",
body
)
// Assuming it's OK
true
} catch (_: NotFound) {
// We need to retry
false
}
}
}
private fun createBranchIfNotExisting(branch: String, base: String = "main") {
if (branch != base) {
// Checks if the branch exists
val gitHubBranch = getBranch(branch)
if (gitHubBranch == null) {
// Gets the last commit of the base branch
val baseBranch = getBranch(base) ?: throw IllegalStateException("Cannot find base branch $base")
val baseCommit = baseBranch.commit.sha
// Creates the branch
gitHubClient.postForObject(
"/repos/${ACCProperties.GitHub.organization}/${repository}/git/refs",
mapOf(
"ref" to "refs/heads/$branch",
"sha" to baseCommit
),
JsonNode::class.java
)
}
}
}
fun createGitHubConfiguration(ontrack: Ontrack): String {
val name = uid("gh")
ontrack.gitHub.createConfig(
GitHubConfiguration(
name = name,
url = "https://github.com",
oauth2Token = ACCProperties.GitHub.token,
autoMergeToken = ACCProperties.GitHub.autoMergeToken,
)
)
return name
}
fun Project.configuredForGitHub(ontrack: Ontrack): String {
val config = createGitHubConfiguration(ontrack)
gitHubConfigurationProperty = GitHubProjectConfigurationProperty(
configuration = config,
repository = "${ACCProperties.GitHub.organization}/$repository",
)
return config
}
fun Branch.configuredForGitHubRepository(
ontrack: Ontrack,
scmBranch: String = "main",
): String {
val configName = project.configuredForGitHub(ontrack)
gitBranchConfigurationProperty = GitBranchConfigurationProperty(branch = scmBranch)
return configName
}
fun assertThatGitHubRepository(
code: AssertionContext.() -> Unit,
) {
val context = AssertionContext()
context.code()
}
private fun getPR(from: String?, to: String?): GitHubPR? {
var url = "/repos/${ACCProperties.GitHub.organization}/$repository/pulls?state=all"
if (from != null) {
url += "&head=$from"
}
if (to != null) {
url += "&base=$to"
}
return gitHubClient.getForObject(
url,
JsonNode::class.java
)?.firstOrNull()?.parse()
}
private fun getPRReviews(pr: GitHubPR): List<GitHubPRReview> =
gitHubClient.getForObject(
"/repos/${ACCProperties.GitHub.organization}/$repository/pulls/${pr.number}/reviews",
JsonNode::class.java
)?.map {
it.parse<GitHubPRReview>()
} ?: emptyList()
private fun getFile(path: String, branch: String): List<String> =
getRawFile(path, branch)?.content?.run { String(Base64.decodeBase64(this)) }?.lines()
?.filter { it.isNotBlank() }
?: emptyList()
private fun getRawFile(path: String, branch: String): GitHubContentsResponse? =
try {
gitHubClient.getForObject(
"/repos/${ACCProperties.GitHub.organization}/$repository/contents/$path?ref=$branch",
GitHubContentsResponse::class.java
)
} catch (ex: NotFound) {
null
}
private fun getBranch(branch: String) =
try {
gitHubClient.getForObject(
"/repos/${ACCProperties.GitHub.organization}/$repository/branches/$branch",
GitHubBranch::class.java
)
} catch (ex: HttpClientErrorException.NotFound) {
null
}
inner class AssertionContext {
fun hasNoBranch(branch: String) {
val gitHubBranch = getBranch(branch)
if (gitHubBranch != null) {
fail("Branch $branch exists when it was expected not to.")
}
}
private fun checkPR(from: String?, to: String?, checkPR: (GitHubPR?) -> Boolean): GitHubPR? {
var pr: GitHubPR? = null
waitUntil(
task = "Checking the PR from $from to $to",
timeout = 120_000L,
interval = 20_000L,
) {
pr = getPR(from, to)
checkPR(pr)
}
return pr
}
fun hasPR(from: String, to: String): GitHubPR =
checkPR(from = from, to = to) {
it != null
} ?: error("PR cannot be null after the check")
fun hasNoPR(to: String) {
checkPR(from = null, to = to) {
it == null
}
}
fun checkPRIsNotApproved(pr: GitHubPR) {
val reviews = getPRReviews(pr)
assertTrue(
reviews.none { it.state == "APPROVED" },
"No review was approved"
)
}
fun fileContains(
path: String,
branch: String = "main",
timeout: Long = 60_000L,
content: () -> String,
) {
val expectedContent = content()
var actualContent: String?
waitUntil(
timeout = timeout,
task = "Waiting for file $path on branch $branch to have a given content.",
onTimeout = {
actualContent = getFile(path, branch).joinToString("\n")
fail(
"""
Expected the following content for the $path file on the $branch branch:
$expectedContent
but got:
$actualContent
""".trimIndent()
)
}
) {
actualContent = getFile(path, branch).joinToString("\n")
actualContent?.contains(expectedContent) ?: false
}
}
}
}
@JsonIgnoreProperties(ignoreUnknown = true)
class GitHubPR(
val number: Int,
val state: String,
)
@JsonIgnoreProperties(ignoreUnknown = true)
class GitHubPRReview(
val user: GitHubUser,
val state: String,
)
@JsonIgnoreProperties(ignoreUnknown = true)
private class GitHubContentsResponse(
val content: String,
val sha: String,
)
@JsonIgnoreProperties(ignoreUnknown = true)
class GitHubBranch(
val name: String,
val commit: GitHubCommit,
)
@JsonIgnoreProperties(ignoreUnknown = true)
class GitHubCommit(
val sha: String,
)
@JsonIgnoreProperties(ignoreUnknown = true)
class GitHubUser(
val login: String,
)
| ontrack-kdsl-acceptance/src/test/java/net/nemerosa/ontrack/kdsl/acceptance/tests/github/system/GitHubTestRepository.kt | 2812916613 |
package net.nemerosa.ontrack.graphql.support
import graphql.Scalars.GraphQLInt
import graphql.Scalars.GraphQLString
import graphql.schema.DataFetchingEnvironment
import graphql.schema.GraphQLArgument
import java.util.*
/**
* Creates a `String` GraphQL argument.
*
* @param name Name of the argument
* @param description Description of the argument
*/
fun stringArgument(
name: String,
description: String
): GraphQLArgument = GraphQLArgument.newArgument()
.name(name)
.description(description)
.type(GraphQLString)
.build()
/**
* Creates a `Int` GraphQL argument.
*
* @param name Name of the argument
* @param description Description of the argument
*/
fun intArgument(
name: String,
description: String,
nullable: Boolean = true,
): GraphQLArgument = GraphQLArgument.newArgument()
.name(name)
.description(description)
.type(nullableInputType(GraphQLInt, nullable))
.build()
/**
* Creates a date/time GraphQL argument.
*
* @param name Name of the argument
* @param description Description of the argument
*/
fun dateTimeArgument(
name: String,
description: String
): GraphQLArgument = GraphQLArgument.newArgument()
.name(name)
.description(description)
.type(GQLScalarLocalDateTime.INSTANCE)
.build()
/**
* Checks list of arguments
*/
fun checkArgList(environment: DataFetchingEnvironment, vararg args: String) {
val actualArgs: Set<String> = environment.arguments.filterValues { it != null }.keys
val expectedArgs: Set<String> = args.toSet()
check(actualArgs == expectedArgs) {
"Expected this list of arguments: $expectedArgs, but was: $actualArgs"
}
}
| ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/support/GQLArgumentUtils.kt | 2757163917 |
package org.tvheadend.data.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Index
import androidx.room.PrimaryKey
data class Connection(
var id: Int = 0,
var name: String? = "",
var hostname: String? = "",
var port: Int = 9982,
var username: String? = "*",
var password: String? = "*",
var isActive: Boolean = false,
var streamingPort: Int = 9981,
var isWolEnabled: Boolean = false,
var wolMacAddress: String? = "",
var wolPort: Int = 9,
var isWolUseBroadcast: Boolean = false,
var lastUpdate: Long = 0,
var isSyncRequired: Boolean = true,
var serverUrl: String? = "",
var streamingUrl: String? = ""
)
@Entity(tableName = "connections", indices = [Index(value = ["id"], unique = true)])
internal data class ConnectionEntity(
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
var name: String? = "",
var hostname: String? = "",
var port: Int = 9982,
var username: String? = "",
var password: String? = "",
@ColumnInfo(name = "active")
var isActive: Boolean = false,
@ColumnInfo(name = "streaming_port")
var streamingPort: Int = 9981,
@ColumnInfo(name = "wol_enabled")
var isWolEnabled: Boolean = false,
@ColumnInfo(name = "wol_hostname")
var wolMacAddress: String? = "",
@ColumnInfo(name = "wol_port")
var wolPort: Int = 9,
@ColumnInfo(name = "wol_use_broadcast")
var isWolUseBroadcast: Boolean = false,
@ColumnInfo(name = "last_update")
var lastUpdate: Long = 0,
@ColumnInfo(name = "sync_required")
var isSyncRequired: Boolean = true,
@ColumnInfo(name = "server_url")
var serverUrl: String? = "",
@ColumnInfo(name = "streaming_url")
var streamingUrl: String? = ""
) {
companion object {
fun from(connection: Connection): ConnectionEntity {
return ConnectionEntity(
connection.id,
connection.name,
connection.hostname,
connection.port,
connection.username,
connection.password,
connection.isActive,
connection.streamingPort,
connection.isWolEnabled,
connection.wolMacAddress,
connection.wolPort,
connection.isWolUseBroadcast,
connection.lastUpdate,
connection.isSyncRequired,
connection.serverUrl,
connection.streamingUrl)
}
}
fun toConnection(): Connection {
return Connection(id, name, hostname, port, username, password, isActive, streamingPort, isWolEnabled, wolMacAddress, wolPort, isWolUseBroadcast, lastUpdate, isSyncRequired, serverUrl, streamingUrl)
}
}
| data/src/main/java/org/tvheadend/data/entity/Connection.kt | 2854924854 |
/*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.designer.psi.tset
import com.intellij.extapi.psi.PsiFileBase
import com.intellij.lang.Language
import com.intellij.openapi.fileTypes.FileType
import com.intellij.psi.FileViewProvider
/**
* Created by thoma on 12/07/2016.
*/
class TsetFile : PsiFileBase {
companion object Data {
var fileProvider: FileViewProvider? = null
var fileLanguage: Language? = null
var fileTy: TsetFileType? = null
}
constructor(fileViewProvider: FileViewProvider, language: Language) : super(fileViewProvider, language) {
fileProvider = fileViewProvider
fileLanguage = language
}
override fun getFileType(): FileType {
fileTy = TsetFileType()
return fileTy as FileType
}
} | neuroph-plugin/src/com/thomas/needham/neurophidea/designer/psi/tset/TsetFile.kt | 1727166079 |
/*
The MIT License (MIT)
Copyright (c) 2016 Tom Needham
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package com.thomas.needham.neurophidea.actions
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.thomas.needham.neurophidea.forms.export.ExportNetworkForm
/**
* Created by Thomas Needham on 28/05/2016.
*/
class ShowExportNetworkFormAction : AnAction() {
var form: ExportNetworkForm? = null
var itr: Long = 0L
companion object ProjectInfo {
var project: Project? = null
var projectDirectory: String? = ""
var isOpen: Boolean? = false
}
override fun actionPerformed(e: AnActionEvent) {
InitialisationAction.project = e.project
InitialisationAction.projectDirectory = InitialisationAction.project?.basePath
InitialisationAction.isOpen = InitialisationAction.project?.isOpen
form = ExportNetworkForm()
}
override fun update(e: AnActionEvent) {
super.update(e)
if (form != null) {
form?.repaint(itr, 0, 0, form?.width!!, form?.height!!)
itr++
}
e.presentation.isEnabledAndVisible = true
}
}
| neuroph-plugin/src/com/thomas/needham/neurophidea/actions/ShowExportNetworkFormAction.kt | 3761555285 |
package treehou.se.habit.dagger
import dagger.Module
import dagger.Provides
import treehou.se.habit.dagger.scopes.ActivityScope
@Module
abstract class ViewModule<out T>(protected val view: T) {
@Provides
@ActivityScope
fun provideActivity(): T {
return view
}
} | mobile/src/main/java/treehou/se/habit/dagger/ViewModule.kt | 2541648668 |
package com.xiaojinzi.component.impl
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import androidx.annotation.Keep
import androidx.annotation.UiContext
import androidx.annotation.UiThread
import androidx.fragment.app.Fragment
import com.xiaojinzi.component.Component.requiredConfig
import com.xiaojinzi.component.ComponentActivityStack
import com.xiaojinzi.component.anno.support.CheckClassNameAnno
import com.xiaojinzi.component.support.*
import java.util.*
interface IRouterRequestBuilder<T : IRouterRequestBuilder<T>> :
IURIBuilder<T>,
IBundleBuilder<T> {
val options: Bundle?
val intentFlags: List<Int>
val intentCategories: List<String>
val context: Context?
val fragment: Fragment?
/**
* 是否是跳转拿 [com.xiaojinzi.component.bean.ActivityResult] 的
*/
val isForResult: Boolean
/**
* 是否是为了目标 Intent
*/
val isForTargetIntent: Boolean
val requestCode: Int?
val intentConsumer: Consumer<Intent>?
val beforeAction: (() -> Unit)?
val beforeStartAction: (() -> Unit)?
val afterStartAction: (() -> Unit)?
val afterAction: (() -> Unit)?
val afterErrorAction: (() -> Unit)?
val afterEventAction: (() -> Unit)?
fun context(context: Context?): T
fun fragment(fragment: Fragment?): T
fun isForResult(isForResult: Boolean): T
fun isForTargetIntent(isForTargetIntent: Boolean): T
fun requestCode(requestCode: Int?): T
fun beforeAction(@UiThread action: Action?): T
fun beforeAction(@UiThread action: (() -> Unit)?): T
fun beforeStartAction(@UiThread action: Action?): T
fun beforeStartAction(@UiThread action: (() -> Unit)?): T
fun afterStartAction(@UiThread action: Action?): T
fun afterStartAction(@UiThread action: (() -> Unit)?): T
fun afterAction(@UiThread action: Action?): T
fun afterAction(@UiThread action: (() -> Unit)?): T
fun afterErrorAction(@UiThread action: Action?): T
fun afterErrorAction(@UiThread action: (() -> Unit)?): T
fun afterEventAction(@UiThread action: Action?): T
fun afterEventAction(@UiThread action: (() -> Unit)?): T
fun intentConsumer(@UiThread intentConsumer: Consumer<Intent>?): T
fun addIntentFlags(vararg flags: Int): T
fun addIntentCategories(vararg categories: String): T
fun options(options: Bundle?): T
fun build(): RouterRequest
}
class RouterRequestBuilderImpl<T : IRouterRequestBuilder<T>>(
context: Context? = null,
fragment: Fragment? = null,
private val uriBuilder: IURIBuilder<T> = IURIBuilderImpl(),
private val bundleBuilder: IBundleBuilder<T> = IBundleBuilderImpl(),
private val targetDelegateImplCallable: DelegateImplCallable<T> = DelegateImplCallableImpl()
) : IRouterRequestBuilder<T>,
IURIBuilder<T> by uriBuilder,
IBundleBuilder<T> by bundleBuilder,
DelegateImplCallable<T> by targetDelegateImplCallable {
override var options: Bundle? = null
/**
* Intent 的 flag,允许修改的
*/
override val intentFlags: MutableList<Int> = mutableListOf()
/**
* Intent 的 类别,允许修改的
*/
override val intentCategories: MutableList<String> = mutableListOf()
override var context: Context? = null
override var fragment: Fragment? = null
override var requestCode: Int? = null
override var isForResult = false
override var isForTargetIntent = false
override var intentConsumer: Consumer<Intent>? = null
/**
* 路由开始之前
*/
override var beforeAction: (() -> Unit)? = null
/**
* 执行 [Activity.startActivity] 之前
*/
override var beforeStartAction: (() -> Unit)? = null
/**
* 执行 [Activity.startActivity] 之后
*/
override var afterStartAction: (() -> Unit)? = null
/**
* 跳转成功之后的 Callback
* 此时的跳转成功仅代表目标界面启动成功, 不代表跳转拿数据的回调被回调了
* 假如你是跳转拿数据的, 当你跳转到 A 界面, 此回调就会回调了,
* 当你拿到 Intent 的回调了, 和此回调已经没关系了
*/
override var afterAction: (() -> Unit)? = null
/**
* 跳转失败之后的 Callback
*/
override var afterErrorAction: (() -> Unit)? = null
/**
* 跳转成功和失败之后的 Callback
*/
override var afterEventAction: (() -> Unit)? = null
override var delegateImplCallable: () -> T
get() = targetDelegateImplCallable.delegateImplCallable
set(value) {
uriBuilder.delegateImplCallable = value
bundleBuilder.delegateImplCallable = value
targetDelegateImplCallable.delegateImplCallable = value
}
private fun getRealDelegateImpl(): T {
return delegateImplCallable.invoke()
}
override fun context(context: Context?): T {
this.context = context
return getRealDelegateImpl()
}
override fun fragment(fragment: Fragment?): T {
this.fragment = fragment
return getRealDelegateImpl()
}
override fun isForResult(isForResult: Boolean): T {
this.isForResult = isForResult
return getRealDelegateImpl()
}
override fun isForTargetIntent(isForTargetIntent: Boolean): T {
this.isForTargetIntent = isForTargetIntent
return getRealDelegateImpl()
}
override fun requestCode(requestCode: Int?): T {
this.requestCode = requestCode
return getRealDelegateImpl()
}
override fun beforeAction(@UiThread action: Action?): T {
return beforeAction(action = {
action?.run()
})
}
override fun beforeAction(@UiThread action: (() -> Unit)?): T {
beforeAction = action
return getRealDelegateImpl()
}
override fun beforeStartAction(@UiThread action: Action?): T {
return beforeStartAction(action = {
action?.run()
})
}
override fun beforeStartAction(@UiThread action: (() -> Unit)?): T {
beforeStartAction = action
return getRealDelegateImpl()
}
override fun afterStartAction(@UiThread action: Action?): T {
return afterStartAction(action = {
action?.run()
})
}
override fun afterStartAction(@UiThread action: (() -> Unit)?): T {
afterStartAction = action
return getRealDelegateImpl()
}
override fun afterAction(@UiThread action: Action?): T {
return afterAction(action = {
action?.run()
})
}
override fun afterAction(@UiThread action: (() -> Unit)?): T {
afterAction = action
return getRealDelegateImpl()
}
override fun afterErrorAction(@UiThread action: Action?): T {
return afterErrorAction(action = {
action?.run()
})
}
override fun afterErrorAction(@UiThread action: (() -> Unit)?): T {
afterErrorAction = action
return getRealDelegateImpl()
}
override fun afterEventAction(@UiThread action: Action?): T {
return afterEventAction(action = {
action?.run()
})
}
override fun afterEventAction(@UiThread action: (() -> Unit)?): T {
afterEventAction = action
return getRealDelegateImpl()
}
/**
* 当不是自定义跳转的时候, Intent 由框架生成,所以可以回调这个接口
* 当自定义跳转,这个回调不会回调的,这是需要注意的点
*
*
* 其实目标界面可以完全的自定义路由,这个功能实际上没有存在的必要,因为你可以为同一个界面添加上多个 [com.xiaojinzi.component.anno.RouterAnno]
* 然后每一个 [com.xiaojinzi.component.anno.RouterAnno] 都可以有不同的行为.是可以完全的代替 [RouterRequest.intentConsumer] 方法的
*
* @param intentConsumer Intent 是框架自动构建完成的,里面有跳转需要的所有参数和数据,这里就是给用户一个
* 更改的机会,最好别更改内部的参数等的信息,这里提供出来其实主要是可以让你调用Intent
* 的 [Intent.addFlags] 等方法,并不是给你修改内部的 bundle 的
*/
override fun intentConsumer(@UiThread intentConsumer: Consumer<Intent>?): T {
this.intentConsumer = intentConsumer
return getRealDelegateImpl()
}
override fun addIntentFlags(vararg flags: Int): T {
intentFlags.addAll(flags.toList())
return getRealDelegateImpl()
}
override fun addIntentCategories(vararg categories: String): T {
intentCategories.addAll(listOf(*categories))
return getRealDelegateImpl()
}
/**
* 用于 API >= 16 的时候,调用 [Activity.startActivity]
*/
override fun options(options: Bundle?): T {
this.options = options
return getRealDelegateImpl()
}
/**
* 构建请求对象,这个构建是必须的,不能错误的,如果出错了,直接崩溃掉,因为连最基本的信息都不全没法进行下一步的操作
*
* @return 可能会抛出一个运行时异常, 由于您的参数在构建 uri 的时候出现的异常
*/
override fun build(): RouterRequest {
val builder = this
return RouterRequest(
context = builder.context,
fragment = builder.fragment,
uri = builder.buildURI(),
requestCode = builder.requestCode,
isForResult = builder.isForResult,
isForTargetIntent = builder.isForTargetIntent,
options = builder.options,
intentFlags = Collections.unmodifiableList(builder.intentFlags),
intentCategories = Collections.unmodifiableList(builder.intentCategories),
bundle = Bundle().apply {
this.putAll(builder.bundle)
},
intentConsumer = builder.intentConsumer,
beforeAction = builder.beforeAction,
beforeStartAction = builder.beforeStartAction,
afterStartAction = builder.afterStartAction,
afterAction = builder.afterAction,
afterErrorAction = builder.afterErrorAction,
afterEventAction = builder.afterEventAction,
)
}
init {
this.context = context
this.fragment = fragment
delegateImplCallable = targetDelegateImplCallable.delegateImplCallable
}
}
/**
* 构建一个路由请求对象 [RouterRequest] 对象的 Builder
*
* @author xiaojinzi
*/
class RouterRequestBuilder(
private val routerRequestBuilder: IRouterRequestBuilder<RouterRequestBuilder> = RouterRequestBuilderImpl(),
) : IRouterRequestBuilder<RouterRequestBuilder> by routerRequestBuilder {
init {
delegateImplCallable = {
this
}
}
}
/**
* 表示路由的一个请求类,构建时候如果参数不对是有异常会发生的,使用的时候注意这一点
* 但是在拦截器 [RouterInterceptor] 中构建是不用关心错误的,
* 因为拦截器的 [RouterInterceptor.intercept] 方法
* 允许抛出异常
*
*
* time : 2018/11/29
*
* @author xiaojinzi
*/
@Keep
@CheckClassNameAnno
data class RouterRequest(
val context: Context?,
val fragment: Fragment?,
/**
* 这是一个很重要的参数, 一定不可以为空,如果这个为空了,一定不能继续下去,因为很多地方直接使用这个参数的,不做空判断的
* 而且这个参数不可以为空的
*/
val uri: Uri,
/**
* 请求码
*/
val requestCode: Int? = null,
/**
* 框架是否帮助用户跳转拿 [com.xiaojinzi.component.bean.ActivityResult]
* 有 requestCode 只能说明用户使用了某一个 requestCode,
* 会调用 [Activity.startActivityForResult].
* 但是不代表需要框架去帮你获取到 [com.xiaojinzi.component.bean.ActivityResult].
* 所以这个值就是标记是否需要框架帮助您去获取 [com.xiaojinzi.component.bean.ActivityResult]
*/
val isForResult: Boolean,
/**
* 是否是为了目标 Intent 来的
*/
val isForTargetIntent: Boolean,
/**
* 跳转的时候 options 参数
*/
val options: Bundle?,
/**
* Intent 的 flag, 集合不可更改
*/
val intentFlags: List<Int>,
/**
* Intent 的 类别, 集合不可更改
*/
val intentCategories: List<String>,
/**
* 携带的数据
*/
val bundle: Bundle,
/**
* Intent 的回调, 可以让你做一些事情
*/
val intentConsumer: Consumer<Intent>?,
/**
* 这个 [Action] 是在路由开始的时候调用的.
* 和 [Activity.startActivity] 不是连着执行的.
* 中间 post 到主线程的操作
*/
val beforeAction: (() -> Unit)?,
/**
* 这个 [Action] 是在 [Activity.startActivity] 之前调用的.
* 和 [Activity.startActivity] 是连着执行的.
*/
val beforeStartAction: (() -> Unit)?,
/**
* 这个 [Action] 是在 [Activity.startActivity] 之后调用的.
* 和 [Activity.startActivity] 是连着执行的.
*/
val afterStartAction: (() -> Unit)?,
/**
* 这个 [Action] 是在结束之后调用的.
* 和 [Activity.startActivity] 不是连着执行的.
* 是在 [RouterInterceptor.Callback.onSuccess]
* 方法中 post 到主线程完成的
*/
val afterAction: (() -> Unit)?,
/**
* 这个 [Action] 是在结束之后调用的.
* 和 [Activity.startActivity] 不是连着执行的.
* 是在 [RouterInterceptor.Callback.onError]
* 方法中 post 到主线程完成的
*/
val afterErrorAction: (() -> Unit)?,
/**
* 这个 [Action] 是在结束之后调用的.
* 和 [Activity.startActivity] 不是连着执行的.
* 是在 [RouterInterceptor.Callback.onSuccess] 或者
* [RouterInterceptor.Callback.onError]
* 方法中 post 到主线程完成的
*/
val afterEventAction: (() -> Unit)?,
) // 占位
{
companion object {
const val KEY_SYNC_URI = "_componentSyncUri"
}
/**
* 同步 Query 到 Bundle 中
*/
fun syncUriToBundle() {
// 如果 URI 没有变化就不同步了
if (bundle.getInt(KEY_SYNC_URI) == uri.hashCode()) {
return
}
ParameterSupport.syncUriToBundle(uri = uri, bundle = bundle)
// 更新新的 hashCode
bundle.putInt(KEY_SYNC_URI, uri.hashCode())
}
/**
* 从 [Fragment] 和 [Context] 中获取上下文
*
*
* 参数中的 [RouterRequest.context] 可能是一个 [android.app.Application] 或者是一个
* [android.content.ContextWrapper] 或者是一个 [Activity]
* 无论参数的类型是哪种, 此方法的返回值就只有两种类型:
* 1. [android.app.Application]
* 2. [Activity]
*
*
* 如果返回的是 [Activity] 的 [Context],
* 当 [Activity] 销毁了就会返回 null
* 另外就是返回 [android.app.Application]
*
* @return [Context], 可能为 null, null 就只有一种情况就是界面销毁了.
* 构建 [RouterRequest] 的时候已经保证了
*/
val rawContext: Context?
get() {
var rawContext: Context? = null
if (context != null) {
rawContext = context
} else if (fragment != null) {
rawContext = fragment.context
}
val rawAct = Utils.getActivityFromContext(rawContext)
// 如果不是 Activity 可能是 Application,所以直接返回
return if (rawAct == null) {
rawContext
} else {
// 如果是 Activity 并且已经销毁了返回 null
if (Utils.isActivityDestoryed(rawAct)) {
null
} else {
rawContext
}
}
}
/**
* 从 [Context] 中获取 [Activity], [Context] 可能是 [android.content.ContextWrapper]
*
* @return 如果 Activity 销毁了就会返回 null
*/
val activity: Activity?
get() {
if (context == null) {
return null
}
val realActivity = Utils.getActivityFromContext(context)
?: return null
return if (Utils.isActivityDestoryed(realActivity)) {
null
} else realActivity
}
/**
* 从参数 [Fragment] 和 [Context] 获取 Activity,
*
* @return 如果 activity 已经销毁并且 fragment 销毁了就会返回 null
*/
val rawActivity: Activity?
get() {
var rawActivity = activity
if (rawActivity == null) {
if (fragment != null) {
rawActivity = fragment.activity
}
}
if (rawActivity == null) {
return null
}
return if (Utils.isActivityDestoryed(rawActivity)) {
null
} else {
// 如果不是为空返回的, 那么必定不是销毁的
rawActivity
}
}
/**
* 首先调用 [.getRawActivity] 尝试获取此次用户传入的 Context 中是否有关联的 Activity
* 如果为空, 则尝试获取运行中的所有 Activity 中顶层的那个
*/
val rawOrTopActivity: Activity?
get() {
var result = rawActivity
if (result == null) {
// 如果不是为空返回的, 那么必定不是销毁的
result = ComponentActivityStack.topAliveActivity
}
return result
}
/**
* 这里转化的对象会比 [RouterRequestBuilder] 对象中的参数少一个 [RouterRequestBuilder.url]
* 因为 uri 转化为了 scheme,host,path,queryMap 那么这时候就不需要 url 了
*/
fun toBuilder(): RouterRequestBuilder {
val builder = RouterRequestBuilder()
// 有关界面的两个
builder.context(context = context)
builder.fragment(fragment = fragment)
// 还原一个 Uri 为各个零散的参数
builder.scheme(scheme = uri.scheme!!)
builder.userInfo(userInfo = uri.userInfo)
builder.host(host = uri.host)
builder.path(path = uri.path)
val queryParameterNames = uri.queryParameterNames
if (queryParameterNames != null) {
for (queryParameterName in queryParameterNames) {
builder.query(queryName = queryParameterName, queryValue = uri.getQueryParameter(queryParameterName)!!)
}
}
// 不能拆分每个参数, 因为可能 url 中可能没有 path 参数
// builder.url(url = uri.toString())
builder.bundle.putAll(bundle)
builder.requestCode(requestCode = requestCode)
builder.isForResult(isForResult = isForResult)
builder.isForTargetIntent(isForTargetIntent = isForTargetIntent)
builder.options(options = options)
// 这里需要新创建一个是因为不可修改的集合不可以给别人
builder.addIntentCategories(*intentCategories.toTypedArray())
builder.addIntentFlags(*intentFlags.toIntArray())
builder.intentConsumer(intentConsumer = intentConsumer)
builder.beforeAction(action = beforeAction)
builder.beforeStartAction(action = beforeStartAction)
builder.afterStartAction(action = afterStartAction)
builder.afterAction(action = afterAction)
builder.afterErrorAction(action = afterErrorAction)
builder.afterEventAction(action = afterEventAction)
return builder
}
} | ComponentImpl/src/main/java/com/xiaojinzi/component/impl/RouterRequest.kt | 468880615 |
package com.nilhcem.henripotier.network
import com.nilhcem.henripotier.BuildConfig
import com.nilhcem.henripotier.network.api.BookStoreApi
import retrofit.RestAdapter
object RestApi {
val bookStoreApi: BookStoreApi
init {
val restAdapter = RestAdapter.Builder().setEndpoint(BuildConfig.WS_ENDPOINT).build()
bookStoreApi = restAdapter.create(javaClass<BookStoreApi>())
}
}
| app/src/main/kotlin/com/nilhcem/henripotier/network/RestApi.kt | 3024475044 |
package io.mockk.impl.log
import io.mockk.proxy.MockKAgentLogger
import kotlin.reflect.KClass
object JvmLogging {
fun slf4jOrJulLogging(): (KClass<*>) -> Logger {
return try {
Class.forName("org.slf4j.Logger");
Class.forName("org.slf4j.impl.StaticLoggerBinder");
{ cls: KClass<*> -> Slf4jLogger(cls) }
} catch (ex: ClassNotFoundException) {
{ cls: KClass<*> -> JULLogger(cls) }
}
}
fun Logger.adaptor(): MockKAgentLogger {
return object : MockKAgentLogger {
override fun debug(msg: String) {
[email protected] { msg }
}
override fun trace(msg: String) {
[email protected] { msg }
}
override fun trace(ex: Throwable, msg: String) {
[email protected](ex) { msg }
}
override fun warn(msg: String) {
[email protected] { msg }
}
override fun warn(ex: Throwable, msg: String) {
[email protected](ex) { msg }
}
}
}
} | modules/mockk/src/jvmMain/kotlin/io/mockk/impl/log/JvmLogging.kt | 1900977874 |
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2021 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.creator.exception
class ProjectCreatorException(message: String, cause: Throwable) : Exception(message, cause)
| src/main/kotlin/creator/exception/ProjectCreatorException.kt | 1248232672 |
package com.pushtorefresh.storio3.contentresolver.annotations.processor.introspection
import com.pushtorefresh.storio3.common.annotations.processor.introspection.StorIOTypeMeta
import com.pushtorefresh.storio3.contentresolver.annotations.StorIOContentResolverType
import com.squareup.javapoet.ClassName
class StorIOContentResolverTypeMeta(
simpleName: String,
packageName: String,
storIOType: StorIOContentResolverType,
needsCreator: Boolean,
nonNullAnnotationClass: ClassName
) : StorIOTypeMeta<StorIOContentResolverType, StorIOContentResolverColumnMeta>(
simpleName,
packageName,
storIOType,
needsCreator,
nonNullAnnotationClass
) {
override val generateTableClass: Boolean
get() = false
} | storio-content-resolver-annotations-processor/src/main/kotlin/com/pushtorefresh/storio3/contentresolver/annotations/processor/introspection/StorIOContentResolverTypeMeta.kt | 3380104557 |
package io.gitlab.arturbosch.tinbo.api.plugins
/**
* Plugin helpers are objects which exist within Tinbo and provide interfaces to
* common data which can be evaluated/used by plugins.
*
* All plugin helpers get loaded into the {@see SpringContext} class through spring auto wiring
* and can be used through a {@see TinboPlugin}'s context() method.
*
*
*
* @author Artur Bosch
*/
interface PluginHelper
| tinbo-plugin-api/src/main/kotlin/io/gitlab/arturbosch/tinbo/api/plugins/PluginHelper.kt | 1975354867 |
/*
* Jicofo, the Jitsi Conference Focus.
*
* Copyright @ 2020 - present 8x8, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jitsi.jicofo.xmpp
import org.apache.commons.lang3.StringUtils
import org.jitsi.impl.protocol.xmpp.XmppProvider
import org.jitsi.jicofo.ConferenceStore
import org.jitsi.jicofo.FocusManager
import org.jitsi.jicofo.auth.AbstractAuthAuthority
import org.jitsi.jicofo.jigasi.JigasiConfig
import org.jitsi.jicofo.jigasi.JigasiDetector
import org.jitsi.utils.OrderedJsonObject
import org.jitsi.utils.logging2.createLogger
class XmppServices(
xmppProviderFactory: XmppProviderFactory,
conferenceStore: ConferenceStore,
authenticationAuthority: AbstractAuthAuthority?,
focusManager: FocusManager
) {
private val logger = createLogger()
val clientConnection: XmppProvider = xmppProviderFactory.createXmppProvider(XmppConfig.client, logger).apply {
start()
}
val serviceConnection: XmppProvider = if (XmppConfig.service.enabled) {
logger.info("Using a dedicated Service XMPP connection.")
xmppProviderFactory.createXmppProvider(XmppConfig.service, logger).apply {
start()
}
} else {
logger.info("No dedicated Service XMPP connection configured, re-using the client XMPP connection.")
clientConnection
}
fun getXmppConnectionByName(name: XmppConnectionEnum) = when (name) {
XmppConnectionEnum.Client -> clientConnection
XmppConnectionEnum.Service -> serviceConnection
}
val jigasiDetector = JigasiConfig.config.breweryJid?.let { breweryJid ->
JigasiDetector(
getXmppConnectionByName(JigasiConfig.config.xmppConnectionName),
breweryJid
).apply { init() }
} ?: run {
logger.info("No Jigasi detector configured.")
null
}
private val jibriIqHandler = JibriIqHandler(
setOf(clientConnection.xmppConnection, serviceConnection.xmppConnection),
conferenceStore
)
private val jigasiIqHandler = if (jigasiDetector != null) {
JigasiIqHandler(
setOf(clientConnection.xmppConnection, serviceConnection.xmppConnection),
conferenceStore,
jigasiDetector
)
} else null
val jigasiStats: OrderedJsonObject
get() = jigasiIqHandler?.statsJson ?: OrderedJsonObject()
private val avModerationHandler = AvModerationHandler(clientConnection, conferenceStore)
private val audioMuteHandler = AudioMuteIqHandler(setOf(clientConnection.xmppConnection), conferenceStore)
private val videoMuteHandler = VideoMuteIqHandler(setOf(clientConnection.xmppConnection), conferenceStore)
private val conferenceIqHandler = ConferenceIqHandler(
xmppProvider = clientConnection,
focusManager = focusManager,
focusAuthJid = "${XmppConfig.client.username}@${XmppConfig.client.domain}",
isFocusAnonymous = StringUtils.isBlank(XmppConfig.client.password),
authAuthority = authenticationAuthority,
jigasiEnabled = jigasiDetector != null
).apply {
clientConnection.xmppConnection.registerIQRequestHandler(this)
}
private val authenticationIqHandler: AuthenticationIqHandler? = if (authenticationAuthority == null) null else {
AuthenticationIqHandler(authenticationAuthority).also {
clientConnection.xmppConnection.registerIQRequestHandler(it.loginUrlIqHandler)
clientConnection.xmppConnection.registerIQRequestHandler(it.logoutIqHandler)
}
}
fun shutdown() {
clientConnection.shutdown()
if (serviceConnection != clientConnection) {
serviceConnection.shutdown()
}
jigasiDetector?.shutdown()
jibriIqHandler.shutdown()
jigasiIqHandler?.shutdown()
audioMuteHandler.shutdown()
videoMuteHandler.shutdown()
avModerationHandler.shutdown()
clientConnection.xmppConnection.unregisterIQRequestHandler(conferenceIqHandler)
authenticationIqHandler?.let {
clientConnection.xmppConnection.unregisterIQRequestHandler(it.loginUrlIqHandler)
clientConnection.xmppConnection.unregisterIQRequestHandler(it.logoutIqHandler)
}
}
}
| jicofo/src/main/kotlin/org/jitsi/jicofo/xmpp/XmppServices.kt | 4031554697 |
package com.icapps.niddler.lib.utils
import java.net.InetAddress
/**
* @author nicolaverbeeck
*/
enum class Platform {
UNKNOWN, LINUX, WINDOWS, DARWIN
}
fun currentPlatform(): Platform {
val os = System.getProperty("os.name")
return when {
os.startsWith("Mac OS", ignoreCase = true) -> Platform.DARWIN
os.startsWith("Windows", ignoreCase = true) -> Platform.WINDOWS
os.startsWith("Linux", ignoreCase = true) -> Platform.LINUX
else -> Platform.UNKNOWN
}
}
fun localName(): String? {
try {
return when (currentPlatform()) {
Platform.UNKNOWN,
Platform.DARWIN,
Platform.LINUX -> System.getenv("HOSTNAME") ?: InetAddress.getLocalHost().hostName
Platform.WINDOWS -> System.getenv("COMPUTERNAME")
}
} catch (e: Throwable) {
logger<Platform>().debug("Failed to get host name", e)
return null
}
} | client-lib/src/main/kotlin/com/icapps/niddler/lib/utils/Platform.kt | 3574623524 |
package com.tamsiree.rxfeature.activity
import android.graphics.Color
import android.os.Bundle
import android.view.View
import com.tamsiree.rxfeature.R
import com.tamsiree.rxfeature.tool.RxBarCode
import com.tamsiree.rxfeature.tool.RxQRCode
import com.tamsiree.rxkit.*
import com.tamsiree.rxkit.view.RxToast
import com.tamsiree.rxui.activity.ActivityBase
import com.tamsiree.rxui.view.ticker.RxTickerUtils
import kotlinx.android.synthetic.main.activity_code_tool.*
/**
* @author tamsiree
*/
class ActivityCodeTool : ActivityBase() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
RxBarTool.noTitle(this)
RxBarTool.setTransparentStatusBar(this)
setContentView(R.layout.activity_code_tool)
RxDeviceTool.setPortrait(this)
}
override fun onResume() {
super.onResume()
updateScanCodeCount()
}
override fun initView() {
ticker_scan_count.setCharacterList(NUMBER_LIST)
ticker_made_count.setCharacterList(NUMBER_LIST)
updateMadeCodeCount()
}
override fun initData() {
initEvent()
}
private fun updateScanCodeCount() {
ticker_scan_count!!.setText(RxDataTool.stringToInt(RxSPTool.getContent(mContext.baseContext!!, RxConstants.SP_SCAN_CODE)).toString() + "", true)
}
private fun updateMadeCodeCount() {
ticker_made_count.setText(RxDataTool.stringToInt(RxSPTool.getContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE)).toString() + "", true)
}
private fun initEvent() {
rx_title.setLeftIconVisibility(true)
rx_title.setTitleColor(Color.WHITE)
rx_title.setTitleSize(RxImageTool.dp2px(20f))
rx_title.setLeftFinish(mContext)
ticker_scan_count!!.animationDuration = 500
iv_create_qr_code.setOnClickListener {
val str = et_qr_code.text.toString()
if (RxDataTool.isNullString(str)) {
RxToast.error("二维码文字内容不能为空!")
} else {
ll_code!!.visibility = View.VISIBLE
//二维码生成方式一 推荐此方法
RxQRCode.builder(str).backColor(-0x1).codeColor(-0x1000000).codeSide(600).codeLogo(resources.getDrawable(R.drawable.faviconhandsome)).codeBorder(1).into(iv_qr_code)
//二维码生成方式二 默认宽和高都为800 背景为白色 二维码为黑色
// RxQRCode.createQRCode(str,iv_qr_code);
iv_qr_code!!.visibility = View.VISIBLE
RxToast.success("二维码已生成!")
RxSPTool.putContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE, (RxDataTool.stringToInt(RxSPTool.getContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE)) + 1).toString())
updateMadeCodeCount()
nestedScrollView!!.computeScroll()
}
}
iv_create_bar_code!!.setOnClickListener {
val str1 = et_bar_code!!.text.toString()
if (RxDataTool.isNullString(str1)) {
RxToast.error("条形码文字内容不能为空!")
} else {
ll_bar_code!!.visibility = View.VISIBLE
//条形码生成方式一 推荐此方法
RxBarCode.builder(str1).backColor(0x00000000).codeColor(-0x1000000).codeWidth(1000).codeHeight(300).into(iv_bar_code)
//条形码生成方式二 默认宽为1000 高为300 背景为白色 二维码为黑色
//iv_bar_code.setImageBitmap(RxBarCode.createBarCode(str1, 1000, 300));
iv_bar_code!!.visibility = View.VISIBLE
RxToast.success("条形码已生成!")
RxSPTool.putContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE, (RxDataTool.stringToInt(RxSPTool.getContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE)) + 1).toString())
updateMadeCodeCount()
}
}
ll_scaner!!.setOnClickListener { RxActivityTool.skipActivity(mContext, ActivityScanerCode::class.java) }
ll_qr!!.setOnClickListener {
ll_qr_root!!.visibility = View.VISIBLE
ll_bar_root!!.visibility = View.GONE
}
ll_bar!!.setOnClickListener {
ll_bar_root!!.visibility = View.VISIBLE
ll_qr_root!!.visibility = View.GONE
}
}
companion object {
private val NUMBER_LIST = RxTickerUtils.defaultNumberList
}
} | RxFeature/src/main/java/com/tamsiree/rxfeature/activity/ActivityCodeTool.kt | 1404214708 |
package org.lrs.kmodernlrs.domain
import java.io.Serializable
data class ContextActivities(
var parent: List<XapiObject>? = null,
var grouping: List<XapiObject>? = null,
var category: List<XapiObject>? = null,
var other: List<XapiObject>? = null
) : Serializable {
companion object {
private val serialVersionUID:Long = 1
}
} | src/main/org/lrs/kmodernlrs/domain/ContextActivities.kt | 4201268344 |
package ffc.app.location
import ffc.api.ApiErrorException
import ffc.api.FfcCentral
import ffc.app.mockRepository
import ffc.app.person.mockPerson
import ffc.app.util.RepoCallback
import ffc.app.util.TaskCallback
import ffc.entity.Organization
import ffc.entity.Person
import ffc.entity.place.House
import me.piruin.geok.geometry.Point
import retrofit2.dsl.enqueue
interface Houses {
fun house(id: String, callbackDsl: RepoCallback<House>.() -> Unit)
fun houseNoLocation(callbackDsl: RepoCallback<List<House>>.() -> Unit)
}
interface HouseManipulator {
fun update(callbackDsl: TaskCallback<House>.() -> Unit)
}
fun housesOf(org: Organization): Houses = if (mockRepository) DummyHouses() else ApiHouses(org)
private class ApiHouses(val org: Organization) : Houses {
val api = FfcCentral().service<PlaceService>()
override fun house(id: String, callbackDsl: RepoCallback<House>.() -> Unit) {
val callback = RepoCallback<House>().apply(callbackDsl)
api.get(org.id, id).enqueue {
onSuccess {
callback.onFound!!.invoke(body()!!)
}
onError {
callback.onFail!!.invoke(ApiErrorException(this))
}
onFailure {
callback.onFail!!.invoke(it)
}
}
}
override fun houseNoLocation(callbackDsl: RepoCallback<List<House>>.() -> Unit) {
val callback = RepoCallback<List<House>>().apply(callbackDsl)
api.listHouseNoLocation(org.id).enqueue {
onSuccess {
callback.onFound!!.invoke(body()!!)
}
onError {
if (code() == 404)
callback.onNotFound!!.invoke()
else
callback.onFail!!.invoke(ApiErrorException(this))
}
onFailure {
callback.onFail!!.invoke(it)
}
}
}
}
private class ApiHouseManipulator(val org: Organization, val house: House) : HouseManipulator {
val api = FfcCentral().service<PlaceService>()
override fun update(callbackDsl: TaskCallback<House>.() -> Unit) {
val callback = TaskCallback<House>().apply(callbackDsl)
api.updateHouse(org.id, house).enqueue {
onSuccess {
callback.result(body()!!)
}
onError {
callback.expception!!.invoke(ApiErrorException(this))
}
onFailure {
callback.expception!!.invoke(it)
}
}
}
}
private class DummyHouses(val house: House? = null) : Houses, HouseManipulator {
override fun houseNoLocation(callbackDsl: RepoCallback<List<House>>.() -> Unit) {
val callback = RepoCallback<List<House>>().apply(callbackDsl)
val houses = mutableListOf<House>()
for (i in 1..100) {
houses.add(House().apply { no = "100/$i" })
}
callback.onFound!!.invoke(houses)
}
override fun update(callbackDsl: TaskCallback<House>.() -> Unit) {
val callback = TaskCallback<House>().apply(callbackDsl)
callback.result(house!!)
}
override fun house(id: String, callbackDsl: RepoCallback<House>.() -> Unit) {
val callback = RepoCallback<House>().apply(callbackDsl)
callback.onFound!!.invoke(House().apply {
no = "112 อุทธยานวิทยาศาสตร์"
location = Point(13.0, 102.0)
})
}
}
internal fun House.resident(orgId: String, callbackDsl: RepoCallback<List<Person>>.() -> Unit) {
val callback = RepoCallback<List<Person>>().apply(callbackDsl)
if (mockRepository) {
callback.onFound!!.invoke(listOf(mockPerson))
} else {
FfcCentral().service<HouseApi>().personInHouse(orgId, this.id).enqueue {
onSuccess { callback.onFound!!.invoke(body()!!) }
onClientError { callback.onNotFound!!.invoke() }
onServerError { callback.onFail!!.invoke(ApiErrorException(this)) }
onFailure { callback.onFail!!.invoke(it) }
}
}
}
fun House.manipulator(org: Organization): HouseManipulator {
return if (mockRepository) DummyHouses(this) else ApiHouseManipulator(org, this)
}
internal fun House.pushTo(org: Organization, callbackDsl: TaskCallback<House>.() -> Unit) {
manipulator(org).update(callbackDsl)
}
| ffc/src/main/kotlin/ffc/app/location/Houses.kt | 3513167382 |
package com.icapps.niddler.lib.utils
import java.net.URL
import java.net.URLDecoder
import java.util.LinkedList
import kotlin.collections.LinkedHashMap
/**
* @author Nicola Verbeeck
* @date 09/11/2017.
*/
class UrlUtil(private val fullUrl: String?) {
private val internalUrl = if (fullUrl != null) URL(fullUrl) else null
val queryString: String?
get() {
return internalUrl?.query
}
val url: String?
get() {
if (internalUrl?.query == null)
return fullUrl
return fullUrl?.substring(0, fullUrl.indexOf('?')) + '?' + queryString
}
val query: Map<String, List<String>>
get() {
val query = internalUrl?.query ?: return emptyMap()
val params = LinkedHashMap<String, MutableList<String>>()
val pairs = query.split("&")
for (pair in pairs) {
val idx = pair.indexOf("=")
val key = if (idx > 0) URLDecoder.decode(pair.substring(0, idx), "UTF-8") else pair
if (!params.containsKey(key)) {
params.put(key, LinkedList<String>())
}
val value = if (idx > 0 && pair.length > idx + 1) URLDecoder.decode(pair.substring(idx + 1), "UTF-8") else null
if (value != null)
params[key]?.add(value)
}
return params
}
}
| client-lib/src/main/kotlin/com/icapps/niddler/lib/utils/UrlUtil.kt | 1122028384 |
package chat.rocket.android.server.presentation
import chat.rocket.android.analytics.AnalyticsManager
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.infrastructure.LocalRepository
import chat.rocket.android.server.domain.GetAccountInteractor
import chat.rocket.android.server.domain.GetAccountsInteractor
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.domain.SaveCurrentServerInteractor
import chat.rocket.android.server.domain.SettingsRepository
import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.infrastructure.ConnectionManagerFactory
import chat.rocket.android.util.extension.launchUI
import chat.rocket.common.util.ifNull
import javax.inject.Inject
class ChangeServerPresenter @Inject constructor(
private val view: ChangeServerView,
private val navigator: ChangeServerNavigator,
private val strategy: CancelStrategy,
private val saveCurrentServerInteractor: SaveCurrentServerInteractor,
private val getCurrentServerInteractor: GetCurrentServerInteractor,
private val getAccountInteractor: GetAccountInteractor,
private val getAccountsInteractor: GetAccountsInteractor,
private val analyticsManager: AnalyticsManager,
private val settingsRepository: SettingsRepository,
private val tokenRepository: TokenRepository,
private val localRepository: LocalRepository,
private val connectionManager: ConnectionManagerFactory
) {
fun loadServer(newUrl: String?, chatRoomId: String? = null) {
launchUI(strategy) {
view.showProgress()
var url = newUrl
val accounts = getAccountsInteractor.get()
if (url == null) {
// Try to load next server on the list...
url = accounts.firstOrNull()?.serverUrl
}
url?.let { serverUrl ->
val token = tokenRepository.get(serverUrl)
if (token == null) {
view.showInvalidCredentials()
view.hideProgress()
navigator.toServerScreen()
return@launchUI
}
val settings = settingsRepository.get(serverUrl)
if (settings == null) {
// TODO - reload settings...
}
// Call disconnect on the old url if any...
getCurrentServerInteractor.get()?.let { url ->
connectionManager.get(url)?.disconnect()
}
// Save the current username.
getAccountInteractor.get(serverUrl)?.let { account ->
localRepository.save(LocalRepository.CURRENT_USERNAME_KEY, account.userName)
}
saveCurrentServerInteractor.save(serverUrl)
view.hideProgress()
analyticsManager.logServerSwitch()
navigator.toChatRooms(chatRoomId)
}.ifNull {
view.hideProgress()
navigator.toServerScreen()
}
}
}
} | app/src/main/java/chat/rocket/android/server/presentation/ChangeServerPresenter.kt | 880614482 |
package com.tamsiree.rxui.view.loadingview.animation.interpolator
import android.graphics.Path
import android.view.animation.Interpolator
/**
* @author tamsiree
* Base implementation for path interpolator compatibility.
*/
internal object PathInterpolatorCompatBase {
fun create(path: Path?): Interpolator {
return PathInterpolatorDonut(path)
}
fun create(controlX: Float, controlY: Float): Interpolator {
return PathInterpolatorDonut(controlX, controlY)
}
fun create(controlX1: Float, controlY1: Float,
controlX2: Float, controlY2: Float): Interpolator {
return PathInterpolatorDonut(controlX1, controlY1, controlX2, controlY2)
}
} | RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/animation/interpolator/PathInterpolatorCompatBase.kt | 2652098050 |
package dolvic.gw2.jackson.mechanics
import com.fasterxml.jackson.annotation.JsonAlias
internal abstract class TrainingTrackMixin {
@JsonAlias("skill_id", "trait_id")
val id = 0
}
| jackson/src/main/kotlin/dolvic/gw2/jackson/mechanics/TrainingTrackMixin.kt | 2625716011 |
package ru.molkov.collapsarserver.config
import org.springframework.web.WebApplicationInitializer
import org.springframework.web.context.ContextLoaderListener
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext
import org.springframework.web.servlet.DispatcherServlet
import javax.servlet.ServletContext
import javax.servlet.ServletException
class WebAppInitializer : WebApplicationInitializer {
companion object {
private val DISPATCHER = "dispatcher"
private val DISPATCHER_SERVLET_MAPPING = "/"
}
@Throws(ServletException::class)
override fun onStartup(servletContext: ServletContext) {
val webApplicationContext = AnnotationConfigWebApplicationContext().apply {
register(WebMvcConfig::class.java)
}
servletContext.addListener(ContextLoaderListener(webApplicationContext))
servletContext.addServlet(DISPATCHER, DispatcherServlet(webApplicationContext)).apply {
addMapping(DISPATCHER_SERVLET_MAPPING)
}
}
}
| src/main/kotlin/ru/molkov/collapsarserver/config/WebAppInitializer.kt | 1012731515 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.build.lint
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@RunWith(JUnit4::class)
class MissingJvmDefaultWithCompatibilityDetectorTest : AbstractLintDetectorTest(
useDetector = MissingJvmDefaultWithCompatibilityDetector(),
useIssues = listOf(MissingJvmDefaultWithCompatibilityDetector.ISSUE),
) {
@Test
fun `Test lint for interface with stable default method`() {
val input = arrayOf(
kotlin("""
package java.androidx
interface InterfaceWithDefaultMethod {
fun methodWithoutDefaultImplementation(foo: Int): String
fun methodWithDefaultImplementation(): Int = 3
}
""")
)
/* ktlint-disable max-line-length */
val expected = """
src/java/androidx/InterfaceWithDefaultMethod.kt:4: Error: This interface must be annotated with @JvmDefaultWithCompatibility because it has a stable method with a default implementation [MissingJvmDefaultWithCompatibility]
interface InterfaceWithDefaultMethod {
^
1 errors, 0 warnings
"""
val expectedFixDiffs = """
Autofix for src/java/androidx/InterfaceWithDefaultMethod.kt line 4: Annotate with @JvmDefaultWithCompatibility:
@@ -4 +4
+ @JvmDefaultWithCompatibility
"""
/* ktlint-enable max-line-length */
check(*input)
.expect(expected)
.expectFixDiffs(expectedFixDiffs)
}
@Test
fun `Test lint for interface with stable method with default parameter`() {
val input = arrayOf(
kotlin("""
package java.androidx
interface InterfaceWithMethodWithDefaultParameterValue {
fun methodWithDefaultParameterValue(foo: Int = 3): Int
}
""")
)
/* ktlint-disable max-line-length */
val expected = """
src/java/androidx/InterfaceWithMethodWithDefaultParameterValue.kt:4: Error: This interface must be annotated with @JvmDefaultWithCompatibility because it has a stable method with a parameter with a default value [MissingJvmDefaultWithCompatibility]
interface InterfaceWithMethodWithDefaultParameterValue {
^
1 errors, 0 warnings
"""
val expectedFixDiffs = """
Autofix for src/java/androidx/InterfaceWithMethodWithDefaultParameterValue.kt line 4: Annotate with @JvmDefaultWithCompatibility:
@@ -4 +4
+ @JvmDefaultWithCompatibility
"""
/* ktlint-enable max-line-length */
check(*input)
.expect(expected)
.expectFixDiffs(expectedFixDiffs)
}
@Test
fun `Test lint for interface implementing @JvmDefaultWithCompatibility interface`() {
val input = arrayOf(
kotlin("""
package java.androidx
import kotlin.jvm.JvmDefaultWithCompatibility
@JvmDefaultWithCompatibility
interface InterfaceWithAnnotation {
fun foo(bar: Int = 3): Int
}
"""),
kotlin("""
package java.androidx
interface InterfaceWithoutAnnotation: InterfaceWithAnnotation {
fun baz(): Int
}
"""),
Stubs.JvmDefaultWithCompatibility
)
/* ktlint-disable max-line-length */
val expected = """
src/java/androidx/InterfaceWithoutAnnotation.kt:4: Error: This interface must be annotated with @JvmDefaultWithCompatibility because it implements an interface which uses this annotation [MissingJvmDefaultWithCompatibility]
interface InterfaceWithoutAnnotation: InterfaceWithAnnotation {
^
1 errors, 0 warnings
"""
val expectedFixDiffs = """
Autofix for src/java/androidx/InterfaceWithoutAnnotation.kt line 4: Annotate with @JvmDefaultWithCompatibility:
@@ -4 +4
+ @JvmDefaultWithCompatibility
""".trimIndent()
/* ktlint-enable max-line-length */
check(*input)
.expect(expected)
.expectFixDiffs(expectedFixDiffs)
}
@Test
fun `Test lint does not apply to interface implementing @JvmDefaultWithCompatibility`() {
val input = arrayOf(
kotlin("""
package java.androidx
import kotlin.jvm.JvmDefaultWithCompatibility
@JvmDefaultWithCompatibility
interface InterfaceWithAnnotation {
fun foo(bar: Int = 3): Int = 4
}
"""),
Stubs.JvmDefaultWithCompatibility
)
check(*input)
.expectClean()
}
@Test
fun `Test lint does not apply to unstable interface`() {
val input = arrayOf(
kotlin("""
package java.androidx
@RequiresOptIn
interface UnstableInterface {
fun foo(bar: Int = 3): Int = 4
}
"""),
Stubs.OptIn
)
check(*input)
.expectClean()
}
@Test
fun `Test lint does not apply to interface with no stable methods`() {
val input = arrayOf(
kotlin("""
package java.androidx
interface InterfaceWithoutStableMethods {
@RequiresOptIn
fun unstableMethod(foo: Int = 3): Int = 4
}
"""),
Stubs.OptIn
)
check(*input)
.expectClean()
}
@Test
fun `Test lint does apply to interface with one unstable method and one stable method`() {
val input = arrayOf(
kotlin("""
package java.androidx
interface InterfaceWithStableAndUnstableMethods {
@RequiresOptIn
fun unstableMethod(foo: Int = 3): Int = 4
fun stableMethod(foo: Int = 3): Int = 4
}
"""),
Stubs.OptIn
)
/* ktlint-disable max-line-length */
val expected = """
src/java/androidx/InterfaceWithStableAndUnstableMethods.kt:4: Error: This interface must be annotated with @JvmDefaultWithCompatibility because it has a stable method with a default implementation [MissingJvmDefaultWithCompatibility]
interface InterfaceWithStableAndUnstableMethods {
^
1 errors, 0 warnings
"""
val expectedFixDiffs = """
Autofix for src/java/androidx/InterfaceWithStableAndUnstableMethods.kt line 4: Annotate with @JvmDefaultWithCompatibility:
@@ -4 +4
+ @JvmDefaultWithCompatibility
""".trimIndent()
/* ktlint-enable max-line-length */
check(*input)
.expect(expected)
.expectFixDiffs(expectedFixDiffs)
}
@Test
fun `Test lint does not apply to interface with no default methods`() {
val input = arrayOf(
kotlin("""
package java.androidx
interface InterfaceWithoutDefaults {
fun methodWithoutDefaults(foo: Int): Int
}
""")
)
check(*input)
.expectClean()
}
@Test
fun `Test lint does not apply to Java file`() {
val input = arrayOf(
java("""
package java.androidx;
interface JavaInterface {
static int staticMethodInInterface() {
return 3;
}
}
""")
)
check(*input)
.expectClean()
}
} | lint-checks/src/test/java/androidx/build/lint/MissingJvmDefaultWithCompatibilityDetectorTest.kt | 1838019663 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.focus
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.modifier.ModifierLocalConsumer
import androidx.compose.ui.modifier.ModifierLocalProvider
import androidx.compose.ui.modifier.ModifierLocalReadScope
import androidx.compose.ui.modifier.modifierLocalOf
import androidx.compose.ui.platform.InspectorInfo
import androidx.compose.ui.platform.InspectorValueInfo
import androidx.compose.ui.platform.debugInspectorInfo
/**
* A Modifier local that stores [FocusProperties] for a sub-hierarchy.
*
* @see [focusProperties]
*/
internal val ModifierLocalFocusProperties =
modifierLocalOf<FocusPropertiesModifier?> { null }
/**
* Properties that are applied to [focusTarget]s that can read the [ModifierLocalFocusProperties]
* Modifier Local.
*
* @see [focusProperties]
*/
interface FocusProperties {
/**
* When set to false, indicates that the [focusTarget] that this is applied to can no longer
* take focus. If the [focusTarget] is currently focused, setting this property to false will
* end up clearing focus.
*/
var canFocus: Boolean
/**
* A custom item to be used when the user requests the focus to move to the "next" item.
*
* @sample androidx.compose.ui.samples.CustomFocusOrderSample
*/
var next: FocusRequester
get() = FocusRequester.Default
set(_) {}
/**
* A custom item to be used when the user requests the focus to move to the "previous" item.
*
* @sample androidx.compose.ui.samples.CustomFocusOrderSample
*/
var previous: FocusRequester
get() = FocusRequester.Default
set(_) {}
/**
* A custom item to be used when the user moves focus "up".
*
* @sample androidx.compose.ui.samples.CustomFocusOrderSample
*/
var up: FocusRequester
get() = FocusRequester.Default
set(_) {}
/**
* A custom item to be used when the user moves focus "down".
*
* @sample androidx.compose.ui.samples.CustomFocusOrderSample
*/
var down: FocusRequester
get() = FocusRequester.Default
set(_) {}
/**
* A custom item to be used when the user requests a focus moves to the "left" item.
*
* @sample androidx.compose.ui.samples.CustomFocusOrderSample
*/
var left: FocusRequester
get() = FocusRequester.Default
set(_) {}
/**
* A custom item to be used when the user requests a focus moves to the "right" item.
*
* @sample androidx.compose.ui.samples.CustomFocusOrderSample
*/
var right: FocusRequester
get() = FocusRequester.Default
set(_) {}
/**
* A custom item to be used when the user requests a focus moves to the "left" in LTR mode and
* "right" in RTL mode.
*
* @sample androidx.compose.ui.samples.CustomFocusOrderSample
*/
var start: FocusRequester
get() = FocusRequester.Default
set(_) {}
/**
* A custom item to be used when the user requests a focus moves to the "right" in LTR mode
* and "left" in RTL mode.
*
* @sample androidx.compose.ui.samples.CustomFocusOrderSample
*/
var end: FocusRequester
get() = FocusRequester.Default
set(_) {}
/**
* A custom item to be used when the user requests focus to move focus in
* ([FocusDirection.Enter]). An automatic [Enter][FocusDirection.Enter]"
* can be triggered when we move focus to a focus group that is not itself focusable. In this
* case, users can use the the focus direction that triggered the move in to determine the
* next item to be focused on.
*
* When you set the [enter] property, provide a lambda that takes the FocusDirection that
* triggered the enter as an input, and provides a [FocusRequester] as an output. You can
* return a custom destination by providing a [FocusRequester] attached to that destination,
* a [Cancel][FocusRequester.Cancel] to cancel the focus enter or
* [Default][FocusRequester.Default] to use the default focus enter behavior.
*
* @sample androidx.compose.ui.samples.CustomFocusEnterSample
*/
@Suppress("OPT_IN_MARKER_ON_WRONG_TARGET")
@get:ExperimentalComposeUiApi
@set:ExperimentalComposeUiApi
@ExperimentalComposeUiApi
var enter: (FocusDirection) -> FocusRequester
get() = { FocusRequester.Default }
set(_) {}
/**
* A custom item to be used when the user requests focus to move out ([FocusDirection.Exit]).
* An automatic [Exit][FocusDirection.Exit] can be triggered when we move focus outside the edge
* of a parent. In this case, users can use the the focus direction that triggered the move out
* to determine the next focus destination.
*
* When you set the [exit] property, provide a lambda that takes the FocusDirection that
* triggered the exit as an input, and provides a [FocusRequester] as an output. You can
* return a custom destination by providing a [FocusRequester] attached to that destination,
* a [Cancel][FocusRequester.Cancel] to cancel the focus exit or
* [Default][FocusRequester.Default] to use the default focus exit behavior.
*
* @sample androidx.compose.ui.samples.CustomFocusExitSample
*/
@Suppress("OPT_IN_MARKER_ON_WRONG_TARGET")
@get:ExperimentalComposeUiApi
@set:ExperimentalComposeUiApi
@ExperimentalComposeUiApi
var exit: (FocusDirection) -> FocusRequester
get() = { FocusRequester.Default }
set(_) {}
}
/**
* This modifier allows you to specify properties that are accessible to [focusTarget]s further
* down the modifier chain or on child layout nodes.
*
* @sample androidx.compose.ui.samples.FocusPropertiesSample
*/
fun Modifier.focusProperties(scope: FocusProperties.() -> Unit): Modifier = this.then(
FocusPropertiesModifier(
focusPropertiesScope = scope,
inspectorInfo = debugInspectorInfo {
name = "focusProperties"
properties["scope"] = scope
}
)
)
@Stable
internal class FocusPropertiesModifier(
val focusPropertiesScope: FocusProperties.() -> Unit,
inspectorInfo: InspectorInfo.() -> Unit
) : ModifierLocalConsumer,
ModifierLocalProvider<FocusPropertiesModifier?>,
InspectorValueInfo(inspectorInfo) {
private var parent: FocusPropertiesModifier? by mutableStateOf(null)
override fun onModifierLocalsUpdated(scope: ModifierLocalReadScope) {
parent = scope.run { ModifierLocalFocusProperties.current }
}
override val key = ModifierLocalFocusProperties
override val value: FocusPropertiesModifier
get() = this
override fun equals(other: Any?) =
other is FocusPropertiesModifier && focusPropertiesScope == other.focusPropertiesScope
override fun hashCode() = focusPropertiesScope.hashCode()
fun calculateProperties(focusProperties: FocusProperties) {
// Populate with the specified focus properties.
focusProperties.apply(focusPropertiesScope)
// Parent can override any values set by this
parent?.calculateProperties(focusProperties)
}
}
internal fun FocusModifier.setUpdatedProperties(properties: FocusProperties) {
if (properties.canFocus) activateNode() else deactivateNode()
}
internal class FocusPropertiesImpl : FocusProperties {
override var canFocus: Boolean = true
override var next: FocusRequester = FocusRequester.Default
override var previous: FocusRequester = FocusRequester.Default
override var up: FocusRequester = FocusRequester.Default
override var down: FocusRequester = FocusRequester.Default
override var left: FocusRequester = FocusRequester.Default
override var right: FocusRequester = FocusRequester.Default
override var start: FocusRequester = FocusRequester.Default
override var end: FocusRequester = FocusRequester.Default
@OptIn(ExperimentalComposeUiApi::class)
override var enter: (FocusDirection) -> FocusRequester = { FocusRequester.Default }
@OptIn(ExperimentalComposeUiApi::class)
override var exit: (FocusDirection) -> FocusRequester = { FocusRequester.Default }
}
internal fun FocusProperties.clear() {
canFocus = true
next = FocusRequester.Default
previous = FocusRequester.Default
up = FocusRequester.Default
down = FocusRequester.Default
left = FocusRequester.Default
right = FocusRequester.Default
start = FocusRequester.Default
end = FocusRequester.Default
@OptIn(ExperimentalComposeUiApi::class)
enter = { FocusRequester.Default }
@OptIn(ExperimentalComposeUiApi::class)
exit = { FocusRequester.Default }
}
internal fun FocusModifier.refreshFocusProperties() {
val coordinator = coordinator ?: return
focusProperties.clear()
coordinator.layoutNode.owner?.snapshotObserver?.observeReads(this,
FocusModifier.RefreshFocusProperties
) {
focusPropertiesModifier?.calculateProperties(focusProperties)
}
setUpdatedProperties(focusProperties)
} | compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/focus/FocusProperties.kt | 538942950 |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.core
import android.os.Handler
import androidx.annotation.RequiresApi
import java.util.concurrent.Executor
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
/**
* This collection pre-configured executors, dispatchers, and scopes that are used throughout this
* library.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
class Threads(
val globalScope: CoroutineScope,
val blockingExecutor: Executor,
val blockingDispatcher: CoroutineDispatcher,
val backgroundExecutor: Executor,
val backgroundDispatcher: CoroutineDispatcher,
val lightweightExecutor: Executor,
val lightweightDispatcher: CoroutineDispatcher,
camera2Handler: () -> Handler,
camera2Executor: () -> Executor
) {
private val _camera2Handler = lazy { camera2Handler() }
private val _camera2Executor = lazy { camera2Executor() }
val camera2Handler: Handler
get() = _camera2Handler.value
val camera2Executor: Executor
get() = _camera2Executor.value
} | camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/core/Threads.kt | 1738465523 |
import android.database.Cursor
import androidx.room.EntityInsertionAdapter
import androidx.room.RoomDatabase
import androidx.room.RoomSQLiteQuery
import androidx.room.RoomSQLiteQuery.Companion.acquire
import androidx.room.util.getColumnIndexOrThrow
import androidx.room.util.query
import androidx.sqlite.db.SupportSQLiteStatement
import java.lang.Class
import javax.`annotation`.processing.Generated
import kotlin.Int
import kotlin.String
import kotlin.Suppress
import kotlin.Unit
import kotlin.collections.List
import kotlin.jvm.JvmStatic
@Generated(value = ["androidx.room.RoomProcessor"])
@Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"])
public class MyDao_Impl(
__db: RoomDatabase,
) : MyDao {
private val __db: RoomDatabase
private val __insertionAdapterOfMyEntity: EntityInsertionAdapter<MyEntity>
init {
this.__db = __db
this.__insertionAdapterOfMyEntity = object : EntityInsertionAdapter<MyEntity>(__db) {
public override fun createQuery(): String =
"INSERT OR ABORT INTO `MyEntity` (`pk`,`bar`) VALUES (?,?)"
public override fun bind(statement: SupportSQLiteStatement, entity: MyEntity): Unit {
statement.bindLong(1, entity.pk.toLong())
val _tmp: Foo = FooBarConverter.toFoo(entity.bar)
val _tmp_1: String = FooBarConverter.toString(_tmp)
statement.bindString(2, _tmp_1)
}
}
}
public override fun addEntity(item: MyEntity): Unit {
__db.assertNotSuspendingTransaction()
__db.beginTransaction()
try {
__insertionAdapterOfMyEntity.insert(item)
__db.setTransactionSuccessful()
} finally {
__db.endTransaction()
}
}
public override fun getEntity(): MyEntity {
val _sql: String = "SELECT * FROM MyEntity"
val _statement: RoomSQLiteQuery = acquire(_sql, 0)
__db.assertNotSuspendingTransaction()
val _cursor: Cursor = query(__db, _statement, false, null)
try {
val _cursorIndexOfPk: Int = getColumnIndexOrThrow(_cursor, "pk")
val _cursorIndexOfBar: Int = getColumnIndexOrThrow(_cursor, "bar")
val _result: MyEntity
if (_cursor.moveToFirst()) {
val _tmpPk: Int
_tmpPk = _cursor.getInt(_cursorIndexOfPk)
val _tmpBar: Bar
val _tmp: String
_tmp = _cursor.getString(_cursorIndexOfBar)
val _tmp_1: Foo = FooBarConverter.fromString(_tmp)
_tmpBar = FooBarConverter.fromFoo(_tmp_1)
_result = MyEntity(_tmpPk,_tmpBar)
} else {
error("Cursor was empty, but expected a single item.")
}
return _result
} finally {
_cursor.close()
_statement.release()
}
}
public companion object {
@JvmStatic
public fun getRequiredConverters(): List<Class<*>> = emptyList()
}
} | room/room-compiler/src/test/test-data/kotlinCodeGen/pojoRowAdapter_customTypeConverter_composite.kt | 251577649 |
package com.riaektiv.akka.spices
import akka.actor.ActorRef
import akka.actor.ActorSystem
import akka.actor.Props
import org.openjdk.jmh.annotations.*
import scala.concurrent.duration.FiniteDuration
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
/**
* Coding With Passion Since 1991
* Created: 12/25/2016, 12:22 PM Eastern Time
* @author Sergey Chuykov
*/
@State(Scope.Thread)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Fork(jvmArgsAppend = arrayOf("-Xmx4g"))
@Warmup(iterations = 8, time = 3)
@Measurement(iterations = 8, time = 3)
open class OneToThreePipelineAkkaBenchmark {
val ONE_MINUTE = FiniteDuration(1, TimeUnit.MINUTES)
companion object {
const val EVENTS_TO_CONSUME = 1 * 1000 * 1000
}
lateinit var system: ActorSystem
lateinit var driver: ActorRef
lateinit var journalingActor: ActorRef
lateinit var replicationActor: ActorRef
lateinit var exitActor: ActorRef
lateinit var ticket: OneToThreePipelineTicket
@Setup
fun setup() {
system = ActorSystem.create();
driver = system.actorOf(Props.create(LongEventProducerUntypedActor::class.java))
journalingActor = system.actorOf(Props.create(LongEventJournalingActor::class.java))
replicationActor = system.actorOf(Props.create(LongEventReplicationActor::class.java))
exitActor = system.actorOf(Props.create(LongEventExitActor::class.java))
}
@Benchmark
@OperationsPerInvocation(LongEventBatchSpiceBenchmark.EVENTS_TO_CONSUME)
fun execute() {
ticket = OneToThreePipelineTicket(EVENTS_TO_CONSUME, CountDownLatch(1),
driver, journalingActor, replicationActor, exitActor)
driver.tell(ticket, ActorRef.noSender())
ticket.latch.await(1, TimeUnit.MINUTES)
}
@TearDown
fun tearDown() {
system.terminate()
system.awaitTermination(ONE_MINUTE)
}
} | incubator-events-benchmarks/src/main/java/com/riaektiv/akka/spices/OneToThreePipelineAkkaBenchmark.kt | 1526373826 |
package com.twilio.video.examples.common
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.ImageDecoder
import android.graphics.ImageFormat
import android.graphics.Matrix
import android.graphics.Rect
import android.graphics.YuvImage
import android.os.Build
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.nio.ByteBuffer
import tvi.webrtc.VideoFrame
import tvi.webrtc.YuvConverter
/**
* Converts a [tvi.webrtc.VideoFrame] to a Bitmap. This method must be called from a thread with a
* valid EGL context when the frame buffer is a [VideoFrame.TextureBuffer].
*/
fun VideoFrame.toBitmap(): Bitmap? {
// Construct yuv image from image data
val yuvImage = if (buffer is VideoFrame.TextureBuffer) {
val yuvConverter = YuvConverter()
val i420Buffer = yuvConverter.convert(buffer as VideoFrame.TextureBuffer)
yuvConverter.release()
i420ToYuvImage(i420Buffer, i420Buffer.width, i420Buffer.height)
} else {
val i420Buffer = buffer.toI420()
val returnImage = i420ToYuvImage(i420Buffer, i420Buffer.width, i420Buffer.height)
i420Buffer.release()
returnImage
}
val stream = ByteArrayOutputStream()
val rect = Rect(0, 0, yuvImage.width, yuvImage.height)
// Compress YuvImage to jpeg
yuvImage.compressToJpeg(rect, 100, stream)
// Convert jpeg to Bitmap
val imageBytes = stream.toByteArray()
var bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
val buffer = ByteBuffer.wrap(imageBytes)
val src =
ImageDecoder.createSource(buffer)
try {
ImageDecoder.decodeBitmap(src)
} catch (e: IOException) {
e.printStackTrace()
return null
}
} else {
BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size)
}
val matrix = Matrix()
// Apply any needed rotation
matrix.postRotate(rotation.toFloat())
bitmap = Bitmap.createBitmap(
bitmap!!, 0, 0, bitmap.width, bitmap.height, matrix, true
)
return bitmap
}
private fun i420ToYuvImage(i420Buffer: VideoFrame.I420Buffer, width: Int, height: Int): YuvImage {
val yuvPlanes = arrayOf(
i420Buffer.dataY, i420Buffer.dataU, i420Buffer.dataV
)
val yuvStrides = intArrayOf(
i420Buffer.strideY, i420Buffer.strideU, i420Buffer.strideV
)
if (yuvStrides[0] != width) {
return fastI420ToYuvImage(yuvPlanes, yuvStrides, width, height)
}
if (yuvStrides[1] != width / 2) {
return fastI420ToYuvImage(yuvPlanes, yuvStrides, width, height)
}
if (yuvStrides[2] != width / 2) {
return fastI420ToYuvImage(yuvPlanes, yuvStrides, width, height)
}
val bytes = ByteArray(
yuvStrides[0] * height + yuvStrides[1] * height / 2 + yuvStrides[2] * height / 2
)
var tmp = ByteBuffer.wrap(bytes, 0, width * height)
copyPlane(yuvPlanes[0], tmp)
val tmpBytes = ByteArray(width / 2 * height / 2)
tmp = ByteBuffer.wrap(tmpBytes, 0, width / 2 * height / 2)
copyPlane(yuvPlanes[2], tmp)
for (row in 0 until height / 2) {
for (col in 0 until width / 2) {
bytes[width * height + row * width + col * 2] =
tmpBytes[row * width / 2 + col]
}
}
copyPlane(yuvPlanes[1], tmp)
for (row in 0 until height / 2) {
for (col in 0 until width / 2) {
bytes[width * height + row * width + col * 2 + 1] =
tmpBytes[row * width / 2 + col]
}
}
return YuvImage(bytes, ImageFormat.NV21, width, height, null)
}
private fun fastI420ToYuvImage(
yuvPlanes: Array<ByteBuffer>,
yuvStrides: IntArray,
width: Int,
height: Int
): YuvImage {
val bytes = ByteArray(width * height * 3 / 2)
var i = 0
for (row in 0 until height) {
for (col in 0 until width) {
bytes[i++] = yuvPlanes[0].get(col + row * yuvStrides[0])
}
}
for (row in 0 until height / 2) {
for (col in 0 until width / 2) {
bytes[i++] = yuvPlanes[2].get(col + row * yuvStrides[2])
bytes[i++] = yuvPlanes[1].get(col + row * yuvStrides[1])
}
}
return YuvImage(bytes, ImageFormat.NV21, width, height, null)
}
private fun copyPlane(src: ByteBuffer, dst: ByteBuffer) {
src.position(0).limit(src.capacity())
dst.put(src)
dst.position(0).limit(dst.capacity())
}
| common/src/main/java/com/twilio/video/examples/common/VideoFrameKtx.kt | 2370089263 |
/*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.lang.core.psi.ext
import com.intellij.lang.ASTNode
import com.intellij.psi.PsiElement
import com.intellij.psi.stubs.IStubElementType
import com.intellij.psi.stubs.StubBase
import org.rust.lang.core.macros.RsExpandedElement
import org.rust.lang.core.psi.*
/**
* Any type can be wrapped into parens, e.g. `let a: (i32) = 1;` Such type is parsed as [RsParenType].
* This method unwraps any number of parens around the type.
*/
tailrec fun RsTypeReference.skipParens(): RsTypeReference {
if (this !is RsParenType) return this
val typeReference = typeReference ?: return this
return typeReference.skipParens()
}
val RsTypeReference.owner: RsTypeReference
get() = ancestors
.filterNot { it is RsTypeArgumentList || it is RsPath }
.takeWhile { it is RsPathType || it is RsTupleType || it is RsRefLikeType || it is RsTypeReference }
.last() as RsTypeReference
abstract class RsTypeReferenceImplMixin : RsStubbedElementImpl<StubBase<*>>, RsTypeReference {
constructor(node: ASTNode) : super(node)
constructor(stub: StubBase<*>, nodeType: IStubElementType<*, *>) : super(stub, nodeType)
override fun getContext(): PsiElement? = RsExpandedElement.getContextImpl(this)
}
| src/main/kotlin/org/rust/lang/core/psi/ext/RsTypeReference.kt | 4109337757 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.