content
stringlengths 0
3.9M
| path
stringlengths 4
242
| contentHash
stringlengths 1
10
|
---|---|---|
fun test() <selection>{
f()
g()
}</selection><caret> | plugins/kotlin/idea/tests/testData/wordSelection/RightBrace/1.kt | 86642638 |
package lib.threejs
@native("THREE.Raycaster")
class Raycaster {
@native fun set(origin : Vector3, direction: Vector3): Unit = noImpl
@native fun intersectObjects(objects : Array<Object3D>, recursive: Boolean): Array<dynamic> = noImpl
}
| client/src/lib/threejs/Raycaster.kt | 200673942 |
/*
* Copyright [2017] [NIRVANA PRIVATE LIMITED]
*
* 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.zwq65.unity.data.network.retrofit.interceptor
import android.util.Log
import com.zwq65.unity.utils.LogUtils
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import java.io.IOException
/**
* ================================================
* 自定义拦截器(log request and response data)
* <p>
* Created by NIRVANA on 2017/10/12
* Contact with <[email protected]>
* ================================================
*/
class MyInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val response = chain.proceed(chain.request())
LogUtils.d("request", "request:" + chain.request().url())
val body: ResponseBody
try {
body = response.peekBody((1024 * 1024).toLong())
} catch (e: IOException) {
e.printStackTrace()
throw e
}
val ss = body.string()
Log.d("retrofitResponse", ss)
return response
}
} | app/src/main/java/com/zwq65/unity/data/network/retrofit/interceptor/MyInterceptor.kt | 268100609 |
package kottage.core.router
import kottage.core.Request
import kottage.core.Response
/**
* Router implementation for Kottage.
* @author Michael Vaughan
*/
enum class HttpMethod {
GET, POST, PUT, DELETE
}
data class Route(val method: HttpMethod, val path: String, val regex: Regex, val pathParamMap: Map<Int, String>, val action: (Request) -> Response)
class Router {
private val routes: MutableMap<HttpMethod, MutableList<Route>> = mutableMapOf()
fun clear() {
routes.clear()
}
fun match(method: HttpMethod, path: String): Route? {
return routes[method]?.firstOrNull {it.regex.matches(path)}
}
fun get(path: String, f: (Request) -> Response) : Router {
addRoute(HttpMethod.GET, path, f)
return this
}
fun post(path: String, f: (Request) -> Response) : Router{
addRoute(HttpMethod.POST, path, f)
return this
}
fun put(path: String, f: (Request) -> Response) : Router {
addRoute(HttpMethod.PUT, path, f)
return this
}
fun delete(path: String, f: (Request) -> Response) : Router {
addRoute(HttpMethod.DELETE, path, f)
return this
}
private fun addRoute(method: HttpMethod, path: String, f: (Request) -> Response) {
val pathParamMap = mutableMapOf<Int, String>()
val splitPath = path.split("/")
val pathPattern = splitPath.mapIndexed { i, section ->
// If it is a path parameter, it will begin with a colon
if (section.startsWith(":")) {
// Update the path param map with the name of the path param and it's index in the path, removing the
// : prefix
pathParamMap.put(i, section.substring(1))
// Return a regex for matching this segment of the path
"[^/]+"
} else {
// Otherwise, replace the * with [^/]+ for regex
section.replace("*", "[^/]+")
}
}.joinToString("/")
routes.getOrPut(method, {mutableListOf()}).add(Route(method, path, Regex(pathPattern), pathParamMap, f))
}
}
| framework/src/main/kotlin/kottage/core/router/Router.kt | 1404376352 |
package ch.rmy.android.http_shortcuts.scripting.actions.types
import ch.rmy.android.framework.extensions.applyIfNotNull
import ch.rmy.android.framework.extensions.logException
import ch.rmy.android.http_shortcuts.R
import ch.rmy.android.http_shortcuts.exceptions.ActionException
import ch.rmy.android.http_shortcuts.scripting.ExecutionContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.eclipse.paho.client.mqttv3.MqttClient
import org.eclipse.paho.client.mqttv3.MqttConnectOptions
import org.eclipse.paho.client.mqttv3.MqttException
import org.eclipse.paho.client.mqttv3.MqttMessage
class SendMQTTMessagesAction(
private val serverUri: String,
private val username: String?,
private val password: String?,
private val messages: List<Message>,
) : BaseAction() {
override suspend fun execute(executionContext: ExecutionContext) {
withContext(Dispatchers.IO) {
try {
val client = MqttClient(serverUri, MqttClient.generateClientId(), null)
val options = MqttConnectOptions()
.apply {
isCleanSession = true
}
.applyIfNotNull(username) {
userName = it
}
.applyIfNotNull(password) {
password = it.toCharArray()
}
client.connect(options)
messages.forEach { message ->
client.publish(message.topic, MqttMessage(message.payload))
}
client.disconnect()
client.close()
} catch (e: MqttException) {
logException(e)
throw ActionException {
getString(R.string.error_failed_to_send_mqtt, e.message ?: e.toString())
}
}
}
}
data class Message(val topic: String, val payload: ByteArray)
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/scripting/actions/types/SendMQTTMessagesAction.kt | 1416825643 |
package ch.rmy.android.http_shortcuts.plugin
import android.content.Context
import javax.inject.Inject
class TaskerUtil
@Inject
constructor(
private val context: Context,
) {
fun isTaskerAvailable(): Boolean =
TaskerIntent.isTaskerInstalled(context)
}
| HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/plugin/TaskerUtil.kt | 2725175021 |
package com.github.h0tk3y.betterParse.benchmark
import com.github.h0tk3y.betterParse.grammar.parseToEnd
import kotlin.test.Ignore
import kotlin.test.Test
@Ignore
class Main {
val repeat = 1000_000_000
@Test
fun testNaive() {
NaiveJsonGrammar().parseToEnd(jsonSample1K)
}
@Test
fun testOptimized() {
repeat(repeat) {
OptimizedJsonGrammar().parseToEnd(jsonSample1K)
}
}
} | benchmarks/src/commonTest/kotlin/Main.kt | 2012888574 |
package com.archinamon.utils
import java.io.File
import javax.xml.bind.JAXBContext
import javax.xml.bind.annotation.*
internal fun findPackageNameIfAar(input: File): String {
if (!input.absolutePath.contains("build-cache")) return input.absolutePath
if (!input.exists()) return "[empty]"
var f: File? = input
do {
f = f?.parentFile
} while (f?.isDirectory!! && !f.listFiles().any(::findManifest))
val manifest = f.listFiles().find(::findManifest)
if (manifest != null) {
val xml = readXml(manifest, Manifest::class.java)
return xml.libPackage
}
return input.name
}
private fun findManifest(f: File): Boolean {
return f.name.equals("androidmanifest.xml", true)
}
private inline fun <reified T> readXml(file: File, clazz: Class<T>): T {
val jc = JAXBContext.newInstance(clazz)
val unmarshaller = jc.createUnmarshaller()
val data = unmarshaller.unmarshal(file) ?: error("Marshalling failed. Get null object")
return data as T
}
@XmlRootElement(name = "manifest")
@XmlAccessorType(XmlAccessType.FIELD)
internal class Manifest {
@XmlAttribute(name = "package")
lateinit var libPackage: String
} | src/main/kotlin/com/archinamon/utils/aar.kt | 429260226 |
/*
* Copyright 2019 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 nebula.plugin.bintray
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import net.jodah.failsafe.RetryPolicy
import okhttp3.Credentials
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.gradle.api.GradleException
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import java.io.IOException
import java.time.Duration
import net.jodah.failsafe.Failsafe
import org.slf4j.LoggerFactory
import java.util.concurrent.TimeUnit
class BintrayClient(var bintrayService: BintrayService, retryConfig: RetryConfig) {
var retryPolicy : RetryPolicy<Any>
val logger = LoggerFactory.getLogger(BintrayClient::class.java)
init {
this.retryPolicy = RetryPolicy<Any>()
.handle(IOException::class.java)
.withDelay(Duration.ofSeconds(retryConfig.retryDelayInSeconds))
.withMaxRetries(retryConfig.maxRetries)
.onFailedAttempt { e ->
logger.error(
"Trying to publish a new version to Bintray failed.",
e.lastFailure
)
}
.onRetry { _ -> logger.info("Retrying to publish a new version to Bintray.") }
}
data class Builder(
var user: String? = null,
var apiKey: String? = null,
var apiUrl: String? = null,
var maxRetries: Int = 3,
var retryDelayInSeconds: Long = 15,
var readTimeoutInSeconds: Long = 240,
var connectionTimeoutInSeconds: Long = 240) {
fun user(user: String) = apply { this.user = user }
fun apiKey(apiKey: String) = apply { this.apiKey = apiKey }
fun apiUrl(apiUrl: String) = apply { this.apiUrl = apiUrl }
fun maxRetries(maxRetries: Int) = apply { this.maxRetries = maxRetries }
fun retryDelayInSeconds(retryDelayInSeconds: Long) = apply { this.retryDelayInSeconds = retryDelayInSeconds }
fun readTimeoutInSeconds(readTimeoutInSeconds: Long) = apply { this.readTimeoutInSeconds = readTimeoutInSeconds }
fun connectionTimeoutInSeconds(connectionTimeoutInSeconds: Long) = apply { this.connectionTimeoutInSeconds = connectionTimeoutInSeconds }
fun build() = BintrayClient(bintray(apiUrl!!, user!!, apiKey!!, readTimeoutInSeconds, connectionTimeoutInSeconds), RetryConfig(this.maxRetries, this.retryDelayInSeconds))
}
data class RetryConfig(val maxRetries: Int, val retryDelayInSeconds: Long)
fun createOrUpdatePackage(subject: String, repo: String, pkg: String, packageRequest: PackageRequest) {
val getPackageResult = Failsafe.with(retryPolicy).get( { -> bintrayService.getPackage(subject, repo, pkg).execute() } )
if(getPackageResult.isSuccessful) {
return
}
if(getPackageResult.code() != 404) {
throw GradleException("Could not obtain information for package $repo/$subject/$pkg - ${getPackageResult.errorBody()?.string()}")
}
val createPackageResult = Failsafe.with(retryPolicy).get( { -> bintrayService.createPackage(subject, repo, packageRequest).execute() } )
if(!createPackageResult.isSuccessful) {
throw GradleException("Could not create or update information for package $repo/$subject/$pkg - ${getPackageResult.errorBody()?.string()}")
}
}
fun publishVersion(subject: String, repo: String, pkg: String, version: String, publishRequest: PublishRequest) {
val publishVersionResult = Failsafe.with(retryPolicy).get( { ->
bintrayService.publishVersion(subject, repo, pkg, version, publishRequest).execute() } )
if(!publishVersionResult.isSuccessful) {
throw GradleException("Could not publish $version version for package $repo/$subject/$pkg - ${publishVersionResult.errorBody()?.string()}")
}
}
fun syncVersionToMavenCentral(subject: String, repo: String, pkg: String, version: String, mavenCentralSyncRequest: MavenCentralSyncRequest) {
val syncVersionToMavenCentralResult = Failsafe.with(retryPolicy).get( { ->
bintrayService.syncVersionToMavenCentral(subject, repo, pkg, version, mavenCentralSyncRequest).execute() } )
if(!syncVersionToMavenCentralResult.isSuccessful) {
logger.error("Could not sync $version version for package $repo/$subject/$pkg to maven central - ${syncVersionToMavenCentralResult.errorBody()?.string()}")
}
}
fun gpgSignVersion(subject: String, repo: String, pkg: String, version: String, passphrase: String?) {
val headers = mutableMapOf<String, String>()
if(!passphrase.isNullOrEmpty()) {
headers.put("X-GPG-PASSPHRASE", passphrase)
}
val gppSignVersionResult = Failsafe.with(retryPolicy).get( { ->
bintrayService.gpgSign(subject, repo, pkg, version, headers).execute() } )
if(!gppSignVersionResult.isSuccessful) {
throw GradleException("Could not gpg sign $version version for package $repo/$subject/$pkg - ${gppSignVersionResult.errorBody()?.string()}")
}
}
}
fun bintray(apiUrl: String, user: String, apiKey: String, readTimeoutInSeconds: Long, connectionTimeoutInSeconds: Long): BintrayService = Retrofit.Builder()
.baseUrl(apiUrl)
.client(OkHttpClient.Builder()
.readTimeout(readTimeoutInSeconds, TimeUnit.SECONDS)
.connectTimeout(connectionTimeoutInSeconds, TimeUnit.SECONDS)
.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BASIC))
.addInterceptor({ chain ->
chain.proceed(chain.request().newBuilder()
.header("Authorization", Credentials.basic(user, apiKey))
.build())
})
.build())
.addConverterFactory(MoshiConverterFactory.create(Moshi.Builder().add(KotlinJsonAdapterFactory()).build()))
.build()
.create(BintrayService::class.java) | src/main/kotlin/nebula/plugin/bintray/BintrayClient.kt | 4000694398 |
/*
* Copyright 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.navigation.ui
import android.support.design.widget.BottomNavigationView
import androidx.navigation.NavController
/**
* Sets up a [BottomNavigationView] for use with a [NavController]. This will call
* [android.view.MenuItem.onNavDestinationSelected] when a menu item is selected.
*
* The selected item in the NavigationView will automatically be updated when the destination
* changes.
*/
fun BottomNavigationView.setupWithNavController(navController: NavController) {
NavigationUI.setupWithNavController(this, navController)
}
| navigation/ui/ktx/src/main/java/androidx/navigation/ui/BottomNavigationView.kt | 3364446577 |
/*
* Copyright 2016 Ross Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.payments.bukkit.notification
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.payments.bukkit.group.RPKPaymentGroup
/**
* Payment notification implementation.
*/
class RPKPaymentNotificationImpl(
override var id: Int = 0,
override val group: RPKPaymentGroup,
override val to: RPKCharacter,
override val character: RPKCharacter,
override val date: Long,
override val text: String
): RPKPaymentNotification
| bukkit/rpk-payments-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/notification/RPKPaymentNotificationImpl.kt | 976145617 |
package ktxc
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
suspend fun main() {
val launch = GlobalScope.launch {
val channel = Channel<Int>()
launch {
// 这里可能是消耗大量 CPU 运算的异步逻辑,我们将仅仅做 5 次整数的平方并发送
for (x in 1..5) channel.send(x * x)
}
// 这里我们打印了 5 次被接收的整数:
repeat(5) { println(channel.receive()) }
println("Done!")
}
launch.join()
} | JavaTest_Zone/src/ktxc/通道.kt | 4100509295 |
/*
* Copyright (C) 2017-2019 Hazuki
*
* 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 jp.hazuki.yuzubrowser.legacy.resblock.data
import android.content.Context
import android.webkit.WebResourceResponse
import com.squareup.moshi.JsonReader
import com.squareup.moshi.JsonWriter
import jp.hazuki.yuzubrowser.legacy.resblock.ResourceData
import java.io.IOException
import java.io.InputStream
class EmptyStringData : ResourceData {
constructor()
@Throws(IOException::class)
constructor(reader: JsonReader) {
//if(parser.nextToken() == JsonToken.VALUE_NULL) return;
}
override fun getTypeId(): Int {
return EMPTY_STRING_DATA
}
override fun getTitle(context: Context): String? {
return null
}
override fun getResource(context: Context): WebResourceResponse {
return WebResourceResponse("text/html", "UTF-8", sInputStream)
}
@Throws(IOException::class)
override fun write(writer: JsonWriter): Boolean {
writer.value(ResourceData.EMPTY_STRING_DATA.toLong())
return true
}
private class EmptyInputStream : InputStream() {
@Throws(IOException::class)
override fun read(): Int {
return -1
}
}
companion object {
private val sInputStream = EmptyInputStream()
}
}
| legacy/src/main/java/jp/hazuki/yuzubrowser/legacy/resblock/data/EmptyStringData.kt | 2844950040 |
package test.dom
import kotlinx.dom.*
import kotlin.*
import kotlin.test.*
import org.w3c.dom.*
import kotlinx.browser.*
import org.junit.Test as test
class DomTest {
@test fun addText() {
var doc = document
assertNotNull(doc, "Should have created a document")
val e = doc.createElement("foo")
e + "hello"
assertEquals("hello", e.textContent)
}
@test fun testCreateDocument() {
var doc = document
assertNotNull(doc, "Should have created a document")
val e = doc.createElement("foo")
assertCssClass(e, "")
// now lets update the cssClass property
e.classes = "foo"
assertCssClass(e, "foo")
// now using the attribute directly
e.setAttribute("class", "bar")
assertCssClass(e, "bar")
}
@test fun testAddClassMissing() {
val e = document.createElement("e")
assertNotNull(e)
e.classes = "class1"
e.addClass("class1", "class2")
assertEquals("class1 class2", e.classes)
}
@test fun testAddClassPresent() {
val e = document.createElement("e")
assertNotNull(e)
e.classes = "class2 class1"
e.addClass("class1", "class2")
assertEquals("class2 class1", e.classes)
}
@test fun testAddClassUndefinedClasses() {
val e = document.createElement("e")
e.addClass("class1")
assertEquals("class1", e.classes)
}
@test fun testRemoveClassMissing() {
val e = document.createElement("e")
assertNotNull(e)
e.classes = "class2 class1"
e.removeClass("class3")
assertEquals("class2 class1", e.classes)
}
@test fun testRemoveClassPresent1() {
val e = document.createElement("e")
assertNotNull(e)
e.classes = "class2 class1"
e.removeClass("class2")
assertEquals("class1", e.classes)
}
@test fun testRemoveClassPresent2() {
val e = document.createElement("e")
assertNotNull(e)
e.classes = "class2 class1"
e.removeClass("class1")
assertEquals("class2", e.classes)
}
@test fun testRemoveClassPresent3() {
val e = document.createElement("e")
assertNotNull(e)
e.classes = "class2 class1 class3"
e.removeClass("class1")
assertEquals("class2 class3", e.classes)
}
@test fun testRemoveClassUndefinedClasses() {
val e = document.createElement("e")
e.removeClass("class1")
assertEquals("", e.classes)
}
@test fun testRemoveFromParent() {
val doc = document
val parent = doc.createElement("pp")
val child = doc.createElement("cc")
parent.appendChild(child)
assertEquals(parent, child.parentNode)
assertEquals(listOf(child), parent.childNodes.asList())
child.removeFromParent()
assertNull(child.parentNode)
assertEquals(emptyList<Node>(), parent.childNodes.asList())
child.removeFromParent()
assertNull(child.parentNode)
}
@test fun testRemoveFromParentOrphanNode() {
val child = document.createElement("cc")
child.removeFromParent()
assertNull(child.parentNode)
}
@test fun testChildElements() {
val doc = document
val parent = doc.createElement("a")
val child1 = doc.createElement("b")
val child2 = doc.createElement("b")
val child3 = doc.createElement("c")
parent + child1
parent + child2
parent + child3
assertEquals(listOf(child1, child2, child3), parent.childElements())
assertEquals(listOf(child1, child2), parent.childElements("b"))
assertEquals(listOf(child3), parent.childElements("c"))
assertEquals(child1, parent.firstChildElement())
assertEquals(null, child1.firstChildElement())
assertEquals(null, null.firstChildElement())
assertEquals(child1, parent.firstChildElement("b"))
assertEquals(child3, parent.firstChildElement("c"))
assertEquals(null, parent.firstChildElement("d"))
assertEquals(null, null.firstChildElement("b"))
}
private fun assertCssClass(e: Element, value: String?): Unit {
val cl = e.classes
val cl2 = e.getAttribute("class") ?: ""
assertEquals(value, cl, "value of element.cssClass")
assertEquals(value, cl2, "value of element.getAttribute(\"class\")")
}
}
| src/test/kotlin/DomTest.kt | 2965540042 |
package io.frontierrobotics.i2c.driver
import io.frontierrobotics.i2c.I2CData
import io.frontierrobotics.i2c.I2CDevice
import io.frontierrobotics.i2c.api.Controller
import org.slf4j.Logger
import org.slf4j.LoggerFactory
class NoOpDriver : I2CDriver
{
val log: Logger = LoggerFactory.getLogger(Controller::class.java)
override fun send(device: I2CDevice, data: I2CData)
{
log.info("No-Op Send")
}
override fun receive(device: I2CDevice, size: Int): I2CData
{
log.info("No-Op Receive")
return I2CData("Empty")
}
} | src/main/kotlin/io/frontierrobotics/i2c/driver/NoOpDriver.kt | 4096100868 |
package org.evomaster.core.search.impact.impactinfocollection.value.numeric
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.numeric.IntegerGene
import org.evomaster.core.search.impact.impactinfocollection.GeneImpact
import org.evomaster.core.search.impact.impactinfocollection.SharedImpactInfo
import org.evomaster.core.search.impact.impactinfocollection.SpecificImpactInfo
/**
* created by manzh on 2019-09-09
*/
class IntegerGeneImpact (sharedImpactInfo: SharedImpactInfo, specificImpactInfo: SpecificImpactInfo) : GeneImpact(sharedImpactInfo, specificImpactInfo){
constructor(
id : String
) : this(SharedImpactInfo(id), SpecificImpactInfo())
override fun copy(): IntegerGeneImpact {
return IntegerGeneImpact(
shared.copy(),
specific.copy()
)
}
override fun clone(): IntegerGeneImpact {
return IntegerGeneImpact(
shared.clone(),
specific.clone()
)
}
override fun validate(gene: Gene): Boolean = gene is IntegerGene
} | core/src/main/kotlin/org/evomaster/core/search/impact/impactinfocollection/value/numeric/IntegerGeneImpact.kt | 1917121114 |
package com.herolynx.bouncer.users
import javax.persistence.*
typealias EMail = String
typealias Password = String
@Entity
data class UserInfo(
val firstName: String,
val lastName: String,
@Id
val eMail: EMail
)
@Entity
data class UserCredentials(
val password: Password,
@Id
val eMail: EMail
)
@Entity
data class UserSession(
@Id
val id: String
) | src/main/kotlin/com/herolynx/bouncer/users/users.kt | 1365403953 |
package me.proxer.library.internal.adapter
import com.squareup.moshi.FromJson
import com.squareup.moshi.JsonDataException
import com.squareup.moshi.ToJson
import me.proxer.library.entity.manga.Page
/**
* @author Ruben Gees
*/
internal class PageAdapter {
private companion object {
private const val FIELD_AMOUNT = 3
private const val NAME_FIELD_LOCATION = 0
private const val HEIGHT_FIELD_LOCATION = 1
private const val WIDTH_FIELD_LOCATION = 2
}
@FromJson
@Suppress("ThrowsCount")
fun fromJson(json: Array<Array<String>>): List<Page> {
return json.map { jsonPage ->
if (jsonPage.size != FIELD_AMOUNT) {
throw JsonDataException("Page array length is " + json.size + " instead of 3.")
}
val height = jsonPage[HEIGHT_FIELD_LOCATION].let {
it.toIntOrNull() ?: throw JsonDataException("Expected an Int for the height but was $it")
}
val width = jsonPage[WIDTH_FIELD_LOCATION].let {
it.toIntOrNull() ?: throw JsonDataException("Expected an Int for the width but was $it")
}
Page(jsonPage[NAME_FIELD_LOCATION], height, width)
}
}
@ToJson
fun toJson(value: Page): Array<String> {
return arrayOf(value.name, value.width.toString(), value.height.toString())
}
}
| library/src/main/kotlin/me/proxer/library/internal/adapter/PageAdapter.kt | 1124963274 |
package io.sonatalang.snc.backend.intrinsics.internal
import io.sonatalang.snc.backend.Backend
import io.sonatalang.snc.backend.intrinsics.Intrinsic
import io.sonatalang.snc.middleEnd.domain.node.BlockNode
import io.sonatalang.snc.middleEnd.domain.node.EmptyNode
import io.sonatalang.snc.middleEnd.domain.node.Node
object EmptyNodeIntrinsic: Intrinsic {
override fun canResolve(expression: Node) = expression is EmptyNode
override fun resolve(expression: Node, backend: Backend) = ""
} | backend/src/main/kotlin/io/sonatalang/snc/backend/intrinsics/internal/EmptyNodeIntrinsic.kt | 1125083718 |
package chat.rocket.android.chatdetails.presentation
import chat.rocket.android.chatdetails.domain.ChatDetails
import chat.rocket.android.chatroom.presentation.ChatRoomNavigator
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.server.domain.GetCurrentServerInteractor
import chat.rocket.android.server.infrastructure.ConnectionManagerFactory
import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.retryIO
import chat.rocket.common.RocketChatException
import chat.rocket.common.model.roomTypeOf
import chat.rocket.common.util.ifNull
import chat.rocket.core.internal.rest.favorite
import chat.rocket.core.internal.rest.getInfo
import chat.rocket.core.model.Room
import timber.log.Timber
import javax.inject.Inject
class ChatDetailsPresenter @Inject constructor(
private val view: ChatDetailsView,
private val navigator: ChatRoomNavigator,
private val strategy: CancelStrategy,
serverInteractor: GetCurrentServerInteractor,
factory: ConnectionManagerFactory
) {
private val currentServer = serverInteractor.get()!!
private val manager = factory.create(currentServer)
private val client = manager?.client
fun toggleFavoriteChatRoom(roomId: String, isFavorite: Boolean) {
launchUI(strategy) {
try {
// Note: If it is favorite then the user wants to remove the favorite - and vice versa.
retryIO("favorite($roomId, ${!isFavorite})") {
client?.favorite(roomId, !isFavorite)
}
view.showFavoriteIcon(!isFavorite)
} catch (e: RocketChatException) {
Timber.e(
e,
"Error while trying to favorite or removing the favorite of a chat room."
)
e.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
}
}
}
fun toVideoConference(roomId: String, chatRoomType: String) =
navigator.toVideoConference(roomId, chatRoomType)
fun getDetails(chatRoomId: String, chatRoomType: String) {
launchUI(strategy) {
try {
retryIO("getInfo($chatRoomId, null, $chatRoomType") {
client?.getInfo(chatRoomId, null, roomTypeOf(chatRoomType))?.let { room ->
view.displayDetails(roomToChatDetails(room))
}
}
} catch (exception: Exception) {
Timber.e(exception)
exception.message?.let {
view.showMessage(it)
}.ifNull {
view.showGenericErrorMessage()
}
}
}
}
fun toFiles(chatRoomId: String) {
navigator.toFileList(chatRoomId)
}
fun toMembers(chatRoomId: String) {
navigator.toMembersList(chatRoomId)
}
fun toMentions(chatRoomId: String) {
navigator.toMentions(chatRoomId)
}
fun toPinned(chatRoomId: String) {
navigator.toPinnedMessageList(chatRoomId)
}
fun toFavorites(chatRoomId: String) {
navigator.toFavoriteMessageList(chatRoomId)
}
private fun roomToChatDetails(room: Room): ChatDetails {
return with(room) {
ChatDetails(
name = name,
fullName = fullName,
type = type.toString(),
topic = topic,
description = description,
announcement = announcement
)
}
}
} | app/src/main/java/chat/rocket/android/chatdetails/presentation/ChatDetailsPresenter.kt | 780450958 |
/*
Copyright (C) 2013-2020 Expedia 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.hotels.styx.routing.handlers
import com.fasterxml.jackson.databind.JsonNode
import com.hotels.styx.RoutingObjectFactoryContext
import com.hotels.styx.api.HttpRequest
import com.hotels.styx.config.schema.SchemaValidationException
import com.hotels.styx.handle
import com.hotels.styx.infrastructure.configuration.yaml.YamlConfig
import com.hotels.styx.mockObject
import com.hotels.styx.ref
import com.hotels.styx.routeLookup
import com.hotels.styx.routing.config.Builtins.BUILTIN_HANDLER_SCHEMAS
import com.hotels.styx.routing.config.RoutingObjectFactory
import com.hotels.styx.routingObjectDef
import io.kotlintest.shouldBe
import io.kotlintest.shouldThrow
import io.kotlintest.specs.FeatureSpec
import io.mockk.verify
import reactor.core.publisher.toMono
import java.nio.charset.StandardCharsets.UTF_8
class PathPrefixRouterFactoryTest : FeatureSpec({
val context = RoutingObjectFactoryContext()
feature("PathPrefixRouterFactory") {
scenario("Builds a PathPrefixRouter instance") {
val routingDef = routingObjectDef("""
type: PathPrefixRouter
config:
routes:
- { prefix: /, destination: root }
- { prefix: /foo/, destination: foo }
""".trimIndent())
val context = RoutingObjectFactoryContext(
routeRefLookup = routeLookup {
ref("root" to mockObject("root"))
ref("foo" to mockObject("foo"))
}
)
val handler = PathPrefixRouter.Factory().build(listOf(), context.get(), routingDef);
handler.handle(HttpRequest.get("/x").build())
.toMono()
.block()!!.bodyAs(UTF_8) shouldBe "root"
handler.handle(HttpRequest.get("/foo/").build())
.toMono()
.block()!!.bodyAs(UTF_8) shouldBe "foo"
}
scenario("Supports inline routing object definitions") {
val routingDef = routingObjectDef("""
type: PathPrefixRouter
config:
routes:
- prefix: /foo
destination:
type: StaticResponseHandler
config:
status: 200
content: hello
""".trimIndent())
val handler = PathPrefixRouter.Factory().build(listOf(), context.get(), routingDef);
handler.handle(HttpRequest.get("/foo").build())
.toMono()
.block()!!.bodyAs(UTF_8) shouldBe "hello"
}
scenario("Missing routes attribute") {
val routingDef = routingObjectDef("""
type: PathPrefixRouter
config:
bar: 1
""".trimIndent())
val e = shouldThrow<IllegalArgumentException> {
PathPrefixRouter.Factory().build(listOf(), context.get(), routingDef);
}
e.message shouldBe "Routing object definition of type 'PathPrefixRouter', attribute='', is missing a mandatory 'routes' attribute."
}
}
feature("Schema validation") {
val EXTENSIONS = { key: String -> BUILTIN_HANDLER_SCHEMAS[key] }
scenario("Accepts inlined routing object definitions") {
val jsonNode = YamlConfig("""
routes:
- prefix: /foo
destination:
type: StaticResponseHandler
config:
status: 200
content: hello
- prefix: /bar
destination:
type: StaticResponseHandler
config:
status: 200
content: hello
""".trimIndent()).`as`(JsonNode::class.java)
PathPrefixRouter.SCHEMA.validate(listOf(), jsonNode, jsonNode, EXTENSIONS)
}
scenario("Accepts named routing object references") {
val jsonNode = YamlConfig("""
routes:
- prefix: /foo
destination: foo
- prefix: /bar
destination: bar
""".trimIndent()).`as`(JsonNode::class.java)
PathPrefixRouter.SCHEMA.validate(listOf(), jsonNode, jsonNode, EXTENSIONS)
}
scenario("Accepts a mix of routing object references and inline definitions") {
val jsonNode = YamlConfig("""
routes:
- prefix: /foo
destination: bar
- prefix: /bar
destination:
type: StaticResponseHandler
config:
status: 200
content: hello
""".trimIndent()).`as`(JsonNode::class.java)
PathPrefixRouter.SCHEMA.validate(listOf(), jsonNode, jsonNode, EXTENSIONS)
}
scenario("Accepts an empty routes list") {
val jsonNode = YamlConfig("""
routes: []
""".trimIndent()).`as`(JsonNode::class.java)
PathPrefixRouter.SCHEMA.validate(listOf(), jsonNode, jsonNode, EXTENSIONS)
}
scenario("Rejects unrelated attributes") {
val jsonNode = YamlConfig("""
routes: []
notAllowed: here
""".trimIndent()).`as`(JsonNode::class.java)
val e = shouldThrow<SchemaValidationException> {
PathPrefixRouter.SCHEMA.validate(listOf(), jsonNode, jsonNode, EXTENSIONS)
}
e.message shouldBe "Unexpected field: 'notAllowed'"
}
}
feature("Lifecycle management") {
scenario("Calls stop() for inlined handlers") {
val child1 = mockObject()
val child2 = mockObject()
val context = RoutingObjectFactoryContext(
objectFactories = mapOf(
"FirstTestHandler" to RoutingObjectFactory { _, _, _ -> child1 },
"SecondTestHandler" to RoutingObjectFactory { _, _, _ -> child2 }
)
)
val routingDef = routingObjectDef("""
type: PathPrefixRouter
config:
routes:
- prefix: /foo
destination:
type: FirstTestHandler
config:
na: na
- prefix: /bar
destination:
type: SecondTestHandler
config:
na: na
""".trimIndent())
PathPrefixRouter.Factory().build(listOf(), context.get(), routingDef)
.stop()
verify(exactly = 1) { child1.stop() }
verify(exactly = 1) { child2.stop() }
}
scenario("Does not call stop() referenced handlers") {
val child1 = mockObject()
val child2 = mockObject()
val context = RoutingObjectFactoryContext(
routeRefLookup = routeLookup {
ref("destinationNameOne" to child1)
ref("destinationNameTwo" to child2)
}
)
val routingDef = routingObjectDef("""
type: PathPrefixRouter
config:
routes:
- prefix: /foo
destination: destinationNameOne
- prefix: /bar
destination: destinationNameTwo
""".trimIndent())
PathPrefixRouter.Factory().build(listOf(), context.get(), routingDef)
.stop()
verify(exactly = 0) { child1.stop() }
verify(exactly = 0) { child2.stop() }
}
}
})
| components/proxy/src/test/kotlin/com/hotels/styx/routing/handlers/PathPrefixRouterFactoryTest.kt | 2426657449 |
package com.weidian.ihome.rx
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
import javax.inject.Scope
/**
* Created by binlly
*
*
* date: 2016/4/27 10:16
* desc: PerActivity
*/
@Scope
@Retention(RetentionPolicy.RUNTIME) annotation class PerActivity
| app/src/main/java/com/binlly/fastpeak/base/rx/PerActivity.kt | 4244459185 |
package com.reactnativenavigation.views.element
import android.animation.AnimatorSet
import android.view.View
import com.reactnativenavigation.parse.SharedElementTransitionOptions
import com.reactnativenavigation.viewcontrollers.ViewController
import com.reactnativenavigation.views.element.animators.*
class SharedElementTransition(appearing: ViewController<*>, private val options: SharedElementTransitionOptions) : Transition() {
val fromId: String = options.fromId.get()
val toId: String = options.toId.get()
lateinit var from: View
lateinit var to: View
override var viewController: ViewController<*> = appearing
override val view: View
get() = to
override val topInset: Int
get() = viewController.topInset
fun isValid(): Boolean = this::from.isInitialized
override fun createAnimators(): AnimatorSet {
val animators = animators()
.filter { it.shouldAnimateProperty() }
.map { it.create(options).apply {
duration = options.getDuration()
startDelay = options.getStartDelay()
interpolator = options.getInterpolator()
} }
val set = AnimatorSet()
set.playTogether(animators)
return set
}
private fun animators(): List<PropertyAnimatorCreator<*>> {
return listOf(
MatrixAnimator(from, to),
XAnimator(from, to),
YAnimator(from, to),
RotationAnimator(from, to),
ScaleXAnimator(from, to),
ScaleYAnimator(from, to),
BackgroundColorAnimator(from, to),
TextChangeAnimator(from, to)
)
}
} | lib/android/app/src/main/java/com/reactnativenavigation/views/element/SharedElementTransition.kt | 783915377 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.core
/**
* Marks a field within a service provider as injectable.
*
* @author Almas Baimagambetov ([email protected])
*/
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME)
annotation class Inject(
val value: String
) | fxgl-core/src/main/kotlin/com/almasb/fxgl/core/Inject.kt | 2966158476 |
/*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.core.util
import java.util.function.Supplier
/**
* A lazy value is only initialized when [get] is invoked.
* Subsequent calls to [get] returns the same value (instance).
*
* @author Almas Baimagambetov ([email protected])
*/
class LazyValue<T>(private val supplier: Supplier<T>) : Supplier<T> {
private var value: T? = null
override fun get(): T {
if (value == null)
value = supplier.get()
return value!!
}
} | fxgl-core/src/main/kotlin/com/almasb/fxgl/core/util/LazyValue.kt | 1531941555 |
package guru.benson.pinch
/**
* Knuth-Morris-Pratt Algorithm for Pattern Matching http://stackoverflow.com/questions/1507780/searching-for-a-sequence-of-bytes-in-a-binary-file-with-java
*/
/**
* Finds the first occurrence of the pattern in the text.
*/
internal fun indexOf(data: ByteArray, pattern: ByteArray): Int {
val failure = computeFailure(pattern)
var j = 0
if (data.isEmpty()) {
return -1
}
for (i in data.indices) {
while (j > 0 && pattern[j] != data[i]) {
j = failure[j - 1]
}
if (pattern[j] == data[i]) {
j++
}
if (j == pattern.size) {
return i - pattern.size + 1
}
}
return -1
}
/**
* Computes the failure function using a boot-strapping process, where the pattern is matched
* against itself.
*/
private fun computeFailure(pattern: ByteArray): IntArray {
val failure = IntArray(pattern.size)
var j = 0
for (i in 1 until pattern.size) {
while (j > 0 && pattern[j] != pattern[i]) {
j = failure[j - 1]
}
if (pattern[j] == pattern[i]) {
j++
}
failure[i] = j
}
return failure
}
| library/src/main/java/guru/benson/pinch/KMPMatch.kt | 3851438675 |
/*
* Copyright 2020 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.payments.bukkit.event.group
import com.rpkit.characters.bukkit.character.RPKCharacter
import com.rpkit.core.bukkit.event.RPKBukkitEvent
import com.rpkit.payments.bukkit.group.RPKPaymentGroup
import org.bukkit.event.Cancellable
import org.bukkit.event.HandlerList
class RPKBukkitPaymentGroupMemberRemoveEvent(
override val paymentGroup: RPKPaymentGroup,
override val character: RPKCharacter,
isAsync: Boolean
) : RPKBukkitEvent(isAsync), RPKPaymentGroupMemberRemoveEvent, Cancellable {
companion object {
@JvmStatic
val handlerList = HandlerList()
}
private var cancel: Boolean = false
override fun isCancelled(): Boolean {
return cancel
}
override fun setCancelled(cancel: Boolean) {
this.cancel = cancel
}
override fun getHandlers(): HandlerList {
return handlerList
}
} | bukkit/rpk-payment-lib-bukkit/src/main/kotlin/com/rpkit/payments/bukkit/event/group/RPKBukkitPaymentGroupMemberRemoveEvent.kt | 2704629622 |
package io.github.restioson.kettle
import com.badlogic.gdx.backends.lwjgl.LwjglApplication
import io.kotlintest.ProjectConfig
object TestConfig : ProjectConfig() {
private lateinit var app: LwjglApplication
override fun beforeAll() {
app = LwjglApplication(TestApplication())
}
override fun afterAll() {
app.exit()
}
} | core/src/test/kotlin/io/github/restioson/kettle/TestConfig.kt | 2881178765 |
package com.alexstyl.specialdates.upcoming
import com.alexstyl.specialdates.date.ContactEvent
import com.alexstyl.specialdates.date.Date
import com.alexstyl.specialdates.events.bankholidays.BankHoliday
import com.alexstyl.specialdates.events.namedays.NamesInADate
class UpcomingEventRowViewModelFactory(private val today: Date,
private val dateCreator: UpcomingDateStringCreator,
private val contactViewModelFactory: ContactViewModelFactory) {
fun createDateHeader(date: Date): UpcomingRowViewModel {
val label = dateCreator.createLabelFor(date)
return DateHeaderViewModel(label)
}
fun createViewModelFor(contactEvent: ContactEvent): UpcomingRowViewModel = contactViewModelFactory.createViewModelFor(today, contactEvent)
fun createViewModelFor(bankHoliday: BankHoliday): UpcomingRowViewModel = BankHolidayViewModel(bankHoliday.holidayName)
fun createViewModelFor(namedays: NamesInADate): UpcomingRowViewModel = NamedaysViewModel(namedays.names.joinToString(", "), namedays.date)
}
| android_mobile/src/main/java/com/alexstyl/specialdates/upcoming/UpcomingEventRowViewModelFactory.kt | 1195619917 |
package glNext.tut05
import com.jogamp.newt.event.KeyEvent
import com.jogamp.opengl.GL.*
import com.jogamp.opengl.GL2ES3.GL_COLOR
import com.jogamp.opengl.GL2ES3.GL_DEPTH
import com.jogamp.opengl.GL3
import com.jogamp.opengl.GL3.GL_DEPTH_CLAMP
import glNext.*
import glm.*
import main.framework.Framework
import uno.buffer.*
import uno.gl.gl3
import uno.glsl.programOf
import glm.vec._3.Vec3
/**
* Created by GBarbieri on 23.02.2017.
*/
fun main(args: Array<String>) {
DepthClamping_Next().setup("Tutorial 05 - Depth Clamping")
}
class DepthClamping_Next : Framework() {
object Buffer {
val VERTEX = 0
val INDEX = 1
val MAX = 2
}
var theProgram = 0
var offsetUniform = 0
var perspectiveMatrixUnif = 0
val numberOfVertices = 36
val perspectiveMatrix = FloatArray(16)
val frustumScale = 1.0f
val bufferObject = intBufferBig(Buffer.MAX)
val vao = intBufferBig(1)
var depthClampingActive = false
override fun init(gl: GL3) = with(gl) {
initializeProgram(gl)
initializeBuffers(gl)
initVertexArray(vao) {
val colorData = Vec3.SIZE * numberOfVertices
array(bufferObject[Buffer.VERTEX], glf.pos3_col4, 0, colorData)
element(bufferObject[Buffer.INDEX])
}
cullFace {
enable()
cullFace = back
frontFace = cw
}
depth {
test = true
mask = true
func = less
range = 0.0 .. 1.0
}
}
fun initializeProgram(gl: GL3) = with(gl) {
theProgram = programOf(gl, javaClass, "tut05", "standard.vert", "standard.frag")
withProgram(theProgram) {
offsetUniform = "offset".location
perspectiveMatrixUnif = "perspectiveMatrix".location
val zNear = 1.0f
val zFar = 3.0f
perspectiveMatrix[0] = frustumScale
perspectiveMatrix[5] = frustumScale
perspectiveMatrix[10] = (zFar + zNear) / (zNear - zFar)
perspectiveMatrix[14] = 2f * zFar * zNear / (zNear - zFar)
perspectiveMatrix[11] = -1.0f
use { glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix) }
}
}
fun initializeBuffers(gl: GL3) = with(gl) {
glGenBuffers(bufferObject)
withArrayBuffer(bufferObject[Buffer.VERTEX]) { data(vertexData, GL_STATIC_DRAW) }
withElementBuffer(bufferObject[Buffer.INDEX]) { data(indexData, GL_STATIC_DRAW) }
}
override fun display(gl: GL3) = with(gl) {
glClearBufferf(GL_COLOR, 0)
glClearBufferf(GL_DEPTH)
usingProgram(theProgram) {
withVertexArray(vao) {
glUniform3f(offsetUniform, 0.0f, 0.0f, 0.5f)
glDrawElements(indexData.size, GL_UNSIGNED_SHORT)
glUniform3f(offsetUniform, 0.0f, 0.0f, -1.0f)
glDrawElementsBaseVertex(indexData.size, GL_UNSIGNED_SHORT, 0, numberOfVertices / 2)
}
}
}
override fun reshape(gl: GL3, w: Int, h: Int) = with(gl) {
perspectiveMatrix[0] = frustumScale * (h / w.f)
perspectiveMatrix[5] = frustumScale
usingProgram(theProgram) { glUniformMatrix4f(perspectiveMatrixUnif, perspectiveMatrix) }
glViewport(w, h)
}
override fun end(gl: GL3) = with(gl) {
glDeleteProgram(theProgram)
glDeleteBuffers(bufferObject)
glDeleteVertexArray(vao)
destroyBuffers(vao, bufferObject, vertexData, indexData)
}
override fun keyPressed(keyEvent: KeyEvent) {
when (keyEvent.keyCode) {
KeyEvent.VK_ESCAPE -> quit()
KeyEvent.VK_SPACE -> window.gl3 {
if (depthClampingActive)
glDisable(GL_DEPTH_CLAMP)
else
glEnable(GL_DEPTH_CLAMP)
depthClampingActive = !depthClampingActive
}
}
}
val RIGHT_EXTENT = 0.8f
val LEFT_EXTENT = -RIGHT_EXTENT
val TOP_EXTENT = 0.20f
val MIDDLE_EXTENT = 0.0f
val BOTTOM_EXTENT = -TOP_EXTENT
val FRONT_EXTENT = -1.25f
val REAR_EXTENT = -1.75f
val GREEN_COLOR = floatArrayOf(0.75f, 0.75f, 1.0f, 1.0f)
val BLUE_COLOR = floatArrayOf(0.0f, 0.5f, 0.0f, 1.0f)
val RED_COLOR = floatArrayOf(1.0f, 0.0f, 0.0f, 1.0f)
val GREY_COLOR = floatArrayOf(0.8f, 0.8f, 0.8f, 1.0f)
val BROWN_COLOR = floatArrayOf(0.5f, 0.5f, 0.0f, 1.0f)
val vertexData = floatBufferOf(
//Object 1 positions
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
LEFT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, MIDDLE_EXTENT, FRONT_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
LEFT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, TOP_EXTENT, REAR_EXTENT,
RIGHT_EXTENT, BOTTOM_EXTENT, REAR_EXTENT,
//Object 2 positions
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, RIGHT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
MIDDLE_EXTENT, LEFT_EXTENT, FRONT_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, RIGHT_EXTENT, REAR_EXTENT,
TOP_EXTENT, LEFT_EXTENT, REAR_EXTENT,
BOTTOM_EXTENT, LEFT_EXTENT, REAR_EXTENT,
//Object 1 colors
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
//Object 2 colors
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*RED_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BROWN_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*BLUE_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREEN_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR,
*GREY_COLOR)
val indexData = shortBufferOf(
0, 2, 1,
3, 2, 0,
4, 5, 6,
6, 7, 4,
8, 9, 10,
11, 13, 12,
14, 16, 15,
17, 16, 14)
} | src/main/kotlin/glNext/tut05/depthClamping.kt | 2280402570 |
package nl.renedegroot.android.adbawake
import dagger.Module
import dagger.Provides
import nl.renedegroot.android.adbawake.providers.PowerManagerProvider
import nl.renedegroot.android.adbawake.providers.SharedPreferencesProvider
import nl.renedegroot.android.adbawake.providers.SystemTextProvider
import nl.renedegroot.android.adbawake.businessmodel.LockControl
import nl.renedegroot.android.adbawake.businessmodel.Preferences
import javax.inject.Singleton
@Module
class AppModule {
@Provides
fun systemTextProvider(): SystemTextProvider = SystemTextProvider()
@Provides
fun sharedPreferencesProvider(): SharedPreferencesProvider = SharedPreferencesProvider()
@Provides
fun powerManagerProvider(): PowerManagerProvider = PowerManagerProvider()
@Provides
fun preferences(): Preferences = Preferences()
@Provides
@Singleton
fun lockControl(): LockControl = LockControl()
} | studio/app/src/main/java/nl/renedegroot/android/adbawake/AppModule.kt | 2625627477 |
/*
Copyright 2015 Carlos
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.ybook.app.net
import java.net.InetAddress
/**
* Created by carlos on 11/12/14.
*/
val MSG_ERROR = 0
val MSG_SUCCESS = 1
val MSG_PASSWORD_WRONG = 2
val MSG_ONE_SEARCH_RESULT = 3
val oldUrl = "http://whitepanda.org:2333"//TODO add url
fun getMainUrl(): String? {
try {
val s = "http://" + InetAddress.getByName("www.ybook.me").getHostAddress() + ":2333"
return s
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
| app/src/main/kotlin/com/ybook/app/net/NetConfigure.kt | 3746109106 |
/*
* Copyright (C) 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 com.example.constraintlayout
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Button
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.layoutId
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstrainedLayoutReference
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.ConstraintLayoutBaseScope
import androidx.constraintlayout.compose.ConstraintSet
import androidx.constraintlayout.compose.Dimension
import androidx.constraintlayout.compose.FlowStyle
import androidx.constraintlayout.compose.LayoutReference
import androidx.constraintlayout.compose.Wrap
import java.util.Arrays
@Preview(group = "flow1")
@Composable
public fun FlowDslDemo1() {
// Currently, we still have problem with positioning the Flow Helper
// and/or setting the width/height properly.
ConstraintLayout(
ConstraintSet {
val a = createRefFor("1")
val b = createRefFor("2")
val c = createRefFor("3")
val d = createRefFor("4")
val g1 = createFlow(a, b, c, d)
constrain(g1) {
centerVerticallyTo(parent)
centerHorizontallyTo(parent)
}
},
modifier = Modifier.fillMaxSize()
) {
val numArray = arrayOf("1", "2", "3", "4")
for (num in numArray) {
Button(
modifier = Modifier.layoutId(num),
onClick = {},
) {
Text(text = num)
}
}
}
}
@Preview(group = "flow2")
@Composable
public fun FlowDslDemo2() {
ConstraintLayout(
ConstraintSet {
val a = createRefFor("1")
val b = createRefFor("2")
val c = createRefFor("3")
val d = createRefFor("4")
val g1 = createFlow(
a, b, c, d,
flowVertically = true
)
constrain(g1) {
centerVerticallyTo(parent)
centerHorizontallyTo(parent)
}
},
modifier = Modifier.fillMaxSize()
) {
val numArray = arrayOf("1", "2", "3", "4")
for (num in numArray) {
Button(
modifier = Modifier.layoutId(num),
onClick = {},
) {
Text(text = num)
}
}
}
}
@Preview(group = "flow3")
@Composable
public fun FlowDslDemo3() {
val numArray = arrayOf("1", "2", "3", "4", "5", "6", "7")
ConstraintLayout(
ConstraintSet {
val elem = arrayOfNulls<LayoutReference>(numArray.size)
for (i in numArray.indices) {
elem[i] = createRefFor(numArray[i])
}
val g1 = createFlow(
elements = *elem,
flowVertically = true,
padding = 30.dp,
wrapMode = Wrap.Chain,
verticalFlowBias = 0.1f,
horizontalFlowBias = 0.8f,
maxElement = 4,
)
constrain(g1) {
centerVerticallyTo(parent)
centerHorizontallyTo(parent)
}
},
modifier = Modifier.fillMaxSize()
) {
for (num in numArray) {
Button(
modifier = Modifier.layoutId(num),
onClick = {},
) {
Text(text = num)
}
}
}
}
@Preview(group = "flow4")
@Composable
public fun FlowDslDemo4() {
val chArray = arrayOf("a", "b", "c", "d", "e", "f", "g", "h")
ConstraintLayout(
ConstraintSet {
val elem = arrayOfNulls<LayoutReference>(chArray.size)
for (i in chArray.indices) {
elem[i] = createRefFor(chArray[i])
}
val g1 = createFlow(
elements = * elem,
wrapMode = Wrap.None,
verticalGap = 32.dp,
horizontalGap = 32.dp,
horizontalFlowBias = 0.8f,
maxElement = 4,
)
constrain(g1) {
centerVerticallyTo(parent)
centerHorizontallyTo(parent)
}
},
modifier = Modifier.fillMaxSize()
) {
for (ch in chArray) {
Button(
modifier = Modifier.layoutId(ch),
onClick = {},
) {
Text(text = ch)
}
}
}
}
@Preview(group = "flow5")
@Composable
public fun FlowDslDemo5() {
ConstraintLayout(
modifier = Modifier
.fillMaxSize()
) {
val (a, b, c, d) = createRefs()
val g1 = createFlow(a, b, c, d, horizontalGap = 20.dp)
constrain(g1) {
centerVerticallyTo(parent)
centerHorizontallyTo(parent)
}
Button(
modifier = Modifier.constrainAs(a) {},
onClick = {},
) {
Text(text = stringResource(id = R.string.log_in))
}
Button(
modifier = Modifier.constrainAs(b) {},
onClick = {},
) {
Text(text = stringResource(id = R.string.log_in))
}
Button(
modifier = Modifier.constrainAs(c) {},
onClick = {},
) {
Text(text = stringResource(id = R.string.log_in))
}
Button(
modifier = Modifier.constrainAs(d) {},
onClick = {},
) {
Text(text = stringResource(id = R.string.log_in))
}
}
}
// verticalStyle and horizontalStyle don't work properly
// Need to figure out the the reason.
@Preview(group = "flow-invalid")
@Composable
public fun FlowDslDemo6() {
val numArray = arrayOf("1", "2", "3", "4", "5", "6", "7")
ConstraintLayout(
ConstraintSet {
val elem = arrayOfNulls<LayoutReference>(numArray.size)
for (i in numArray.indices) {
elem[i] = createRefFor(numArray[i])
}
val g1 = createFlow(
elements = *elem,
flowVertically = true,
wrapMode = Wrap.Aligned,
verticalStyle = FlowStyle.Packed,
horizontalStyle = FlowStyle.Packed,
maxElement = 2,
)
constrain(g1) {
width = Dimension.matchParent
height = Dimension.matchParent
}
},
modifier = Modifier.fillMaxSize()
) {
for (num in numArray) {
Button(
modifier = Modifier.layoutId(num),
onClick = {},
) {
Text(text = num)
}
}
}
}
| projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/FlowDslDemo.kt | 1490158621 |
package org.rust.ide.template.postfix
class LetPostfixTemplateTest : PostfixTemplateTestCase(LetPostfixTemplate()) {
fun testNotApplicable() = doTestNotApplicable(
"""
fn foo() {
println!("test");.let/*caret*/
}
"""
)
fun testSimple() = doTest(
"""
fn foo() {
4.let/*caret*/;
}
"""
,
"""
fn foo() {
let /*caret*/i = 4;
}
"""
)
fun testSimpleParExpr() = doTest(
"""
fn foo() {
(1 + 2).let/*caret*/;
}
"""
,
"""
fn foo() {
let /*caret*/x = (1 + 2);
}
"""
)
fun testSimpleFoo() = doTest(
"""
fn foo() { }
fn main() {
foo().let/*caret*/
}
"""
,
"""
fn foo() { }
fn main() {
let /*caret*/foo = foo();
}
"""
)
fun testSimpleFooWithType() = doTest(
"""
fn foo() -> i32 { 42 }
fn main() {
foo().let/*caret*/
}
"""
,
"""
fn foo() -> i32 { 42 }
fn main() {
let /*caret*/i = foo();
}
"""
)
}
| src/test/kotlin/org/rust/ide/template/postfix/LetPostfixTemplateTest.kt | 2864754763 |
package net.perfectdreams.loritta.cinnamon.discord.utils
import dev.kord.common.entity.Snowflake
import dev.kord.core.Kord
import dev.kord.core.entity.Icon
fun DiscordUserAvatar(kord: Kord, id: Snowflake, discriminator: String, avatarHash: String?) = avatarHash?.let {
Icon.UserAvatar(id, it, kord)
} ?: Icon.DefaultUserAvatar(discriminator.toInt(), kord) | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/utils/DiscordUserAvatar.kt | 3412815575 |
package org.owntracks.android.ui.map
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageButton
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.commit
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import org.owntracks.android.R
import org.owntracks.android.databinding.MapLayerBottomSheetDialogBinding
class MapLayerBottomSheetDialog() : BottomSheetDialogFragment() {
protected val viewModel: MapViewModel by activityViewModels()
private lateinit var binding: MapLayerBottomSheetDialogBinding
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = MapLayerBottomSheetDialogBinding.inflate(inflater, container, false)
mapLayerSelectorButtonsToStyles.forEach {
binding.root.findViewById<AppCompatImageButton>(it.key).setOnClickListener { _ ->
val currentMapLayerStyle = viewModel.mapLayerStyle.value
val newMapLayerStyle = it.value
viewModel.setMapLayerStyle(it.value)
if (!(currentMapLayerStyle?.isSameProviderAs(newMapLayerStyle) ?: false)) {
// Replace the map fragment
val mapFragment =
parentFragmentManager.fragmentFactory.instantiate(
requireActivity().classLoader,
MapFragment::class.java.name
)
parentFragmentManager.commit(true) {
replace(R.id.mapFragment, mapFragment, "map")
}
}
dismiss()
}
}
return binding.root
}
}
| project/app/src/main/java/org/owntracks/android/ui/map/MapLayerBottomSheetDialog.kt | 2263230075 |
package net.perfectdreams.loritta.cinnamon.pudding.tables
import org.jetbrains.exposed.dao.id.LongIdTable
object BoostedCandyChannels : LongIdTable() {
val user = reference("user", Profiles)
val guildId = long("guild")
val channelId = long("channel")
val givenAt = long("given_at")
val expiresAt = long("expires_at")
} | pudding/client/src/main/kotlin/net/perfectdreams/loritta/cinnamon/pudding/tables/BoostedCandyChannels.kt | 3506336006 |
package net.perfectdreams.loritta.morenitta.commands.vanilla.images
import net.perfectdreams.loritta.morenitta.utils.extensions.drawStringWithOutline
import net.perfectdreams.loritta.common.commands.ArgumentType
import net.perfectdreams.loritta.common.utils.extensions.enableFontAntiAliasing
import net.perfectdreams.loritta.common.utils.image.JVMImage
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.commands.vanilla.images.base.ImageAbstractCommandBase
import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils
import java.awt.Color
import java.awt.Font
import java.awt.image.BufferedImage
import java.io.File
class TerminatorCommand(m: LorittaBot) : ImageAbstractCommandBase(
m,
listOf("terminator", "animeterminator", "terminatoranime")
) {
override fun command() = create {
localizedDescription("commands.command.terminator.description")
localizedExamples("commands.command.terminator.examples")
usage {
argument(ArgumentType.TEXT) {}
}
needsToUploadFiles = true
executes {
OutdatedCommandUtils.sendOutdatedCommandMessage(this, locale, "terminatoranime")
// TODO: Multiplatform
loritta as LorittaBot
val args = args.joinToString(" ")
val split = args.split("|")
if (2 > split.size) {
explain()
return@executes
}
val mppImage = validate(image(0))
mppImage as JVMImage
val mppTerminatorAnime = loritta.assets.loadImage("terminator_anime.png", loadFromCache = true)
val terminatorAnime = (mppTerminatorAnime as JVMImage).handle as BufferedImage
val input1 = split[0]
val input2 = split[1]
val graphics = terminatorAnime.createGraphics()
graphics.enableFontAntiAliasing()
val lato = Font.createFont(Font.TRUETYPE_FONT, File(LorittaBot.ASSETS, "fonts/Lato-Bold.ttf"))
val font = lato.deriveFont(24f)
graphics.color = Color(255, 251, 0)
graphics.font = font
fun drawTextCentralizedNewLines(text: String, startAtX: Int, startAtY: Int) {
var startAtX = startAtX
var startAtY = startAtY
val splitInput1 = text.split("((?<= )|(?= ))".toRegex()).dropLastWhile { it.isEmpty() }
var input1FitInLine = ""
for (split in splitInput1) {
val old = input1FitInLine
input1FitInLine += split
println("${startAtX - (graphics.getFontMetrics(font).stringWidth(old) / 2)}")
if (0 >= startAtX - (graphics.getFontMetrics(font).stringWidth(input1FitInLine) / 2) || startAtX + (graphics.getFontMetrics(font).stringWidth(input1FitInLine) / 2) >= terminatorAnime.width) {
println((graphics.getFontMetrics(font).stringWidth(old)))
val drawAtX = startAtX - (graphics.getFontMetrics(font).stringWidth(old) / 2)
graphics.drawStringWithOutline(old, drawAtX, startAtY, Color.BLACK, 2)
startAtY += 26
input1FitInLine = ""
input1FitInLine += split
}
}
val drawAtX = startAtX - (graphics.getFontMetrics(font).stringWidth(input1FitInLine) / 2)
graphics.drawStringWithOutline(input1FitInLine, drawAtX, startAtY, Color.BLACK, 2)
}
val centerInput1X = 98
val centerInput1Y = 138
val centerInput2X = 286
val centerInput2Y = 254
drawTextCentralizedNewLines(input1, centerInput1X, centerInput1Y)
drawTextCentralizedNewLines(input2, centerInput2X, centerInput2Y)
sendImage(JVMImage(terminatorAnime), "terminator_anime.png")
}
}
} | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/images/TerminatorCommand.kt | 966505761 |
package me.proxer.app.forum
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.ViewCompat
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.RecyclerView.LayoutManager
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.jakewharton.rxbinding3.view.clicks
import com.mikepenz.iconics.typeface.library.community.material.CommunityMaterial
import com.uber.autodispose.autoDisposable
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import kotterknife.bindView
import me.proxer.app.GlideRequests
import me.proxer.app.R
import me.proxer.app.base.AutoDisposeViewHolder
import me.proxer.app.base.BaseAdapter
import me.proxer.app.forum.PostAdapter.ViewHolder
import me.proxer.app.ui.view.bbcode.BBCodeView
import me.proxer.app.util.extension.distanceInWordsToNow
import me.proxer.app.util.extension.logErrors
import me.proxer.app.util.extension.mapBindingAdapterPosition
import me.proxer.app.util.extension.setIconicsImage
import me.proxer.library.util.ProxerUrls
import java.util.concurrent.ConcurrentHashMap
/**
* @author Ruben Gees
*/
class PostAdapter : BaseAdapter<ParsedPost, ViewHolder>() {
var glide: GlideRequests? = null
val profileClickSubject: PublishSubject<Pair<ImageView, ParsedPost>> = PublishSubject.create()
private val heightMap = ConcurrentHashMap<String, Int>()
private var layoutManager: LayoutManager? = null
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.item_post, parent, false))
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(data[position])
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
layoutManager = recyclerView.layoutManager
}
override fun onViewRecycled(holder: ViewHolder) {
glide?.clear(holder.image)
holder.post.destroyWithRetainingViews()
holder.signature.destroyWithRetainingViews()
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
layoutManager = null
glide = null
}
inner class ViewHolder(itemView: View) : AutoDisposeViewHolder(itemView) {
internal val userContainer by bindView<ViewGroup>(R.id.userContainer)
internal val image by bindView<ImageView>(R.id.image)
internal val user by bindView<TextView>(R.id.user)
internal val post by bindView<BBCodeView>(R.id.post)
internal val signatureDivider by bindView<View>(R.id.signatureDivider)
internal val signature by bindView<BBCodeView>(R.id.signature)
internal val date by bindView<TextView>(R.id.date)
internal val thankYouIcon by bindView<ImageView>(R.id.thankYouIcon)
internal val thankYou by bindView<TextView>(R.id.thankYou)
init {
post.glide = glide
post.enableEmotions = true
post.heightMap = heightMap
signature.glide = glide
signature.enableEmotions = true
signature.heightMap = heightMap
thankYouIcon.setIconicsImage(CommunityMaterial.Icon3.cmd_thumb_up, 32)
}
fun bind(item: ParsedPost) {
userContainer.clicks()
.mapBindingAdapterPosition({ bindingAdapterPosition }) { image to data[it] }
.autoDisposable(this)
.subscribe(profileClickSubject)
Observable.merge(post.heightChanges.map { post }, signature.heightChanges.map { signature })
.autoDisposable(this)
.subscribe {
it.requestLayout()
layoutManager?.requestSimpleAnimationsInNextLayout()
}
ViewCompat.setTransitionName(image, "post_${item.id}")
user.text = item.username
date.text = item.date.distanceInWordsToNow(date.context)
thankYou.text = item.thankYouAmount.toString()
post.userId = item.userId
post.tree = item.parsedMessage
item.signature.let {
signature.userId = item.userId
if (it == null) {
signatureDivider.isGone = true
signature.isGone = true
signature.tree = null
} else {
signatureDivider.isVisible = true
signature.isVisible = true
signature.tree = it
}
}
bindImage(item)
}
private fun bindImage(item: ParsedPost) {
if (item.image.isBlank()) {
image.setIconicsImage(CommunityMaterial.Icon.cmd_account, 32, 4, R.attr.colorSecondary)
} else {
glide?.load(ProxerUrls.userImage(item.image).toString())
?.transition(DrawableTransitionOptions.withCrossFade())
?.circleCrop()
?.logErrors()
?.into(image)
}
}
}
}
| src/main/kotlin/me/proxer/app/forum/PostAdapter.kt | 3681424216 |
package com.redsky.api
data class RedSkyProduct(
val availableToPromiseNetwork: AvailableToPromiseNetwork?,
val deepRedLabels: DeepRedLabels?,
val item: Item
)
| redsky-api/src/main/kotlin/com/redsky/api/RedSkyProduct.kt | 2479646602 |
package com.androidvip.hebf.adapters
import android.app.Activity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.CompoundButton
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.androidvip.hebf.R
import com.androidvip.hebf.models.App
class ForceStopAppsAdapter(private val activity: Activity, private val apps: List<App>) : RecyclerView.Adapter<ForceStopAppsAdapter.ViewHolder>() {
val selectedApps: MutableSet<App> = mutableSetOf()
class ViewHolder(v: View) : RecyclerView.ViewHolder(v) {
var label: TextView = v.findViewById(R.id.app_nome)
var icon: ImageView = v.findViewById(R.id.icon)
var checkBox: CheckBox = v.findViewById(R.id.force_stop_apps_check)
init {
setIsRecyclable(false)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val v = LayoutInflater.from(activity).inflate(R.layout.list_item_small_app, parent, false)
return ViewHolder(v).apply {
setIsRecyclable(false)
}
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val app = apps[holder.adapterPosition]
fun selectionChange(isChecked: Boolean) {
if (isChecked) {
selectedApps.add(app)
} else {
selectedApps.remove(app)
}
app.isChecked = isChecked
}
holder.checkBox.setOnCheckedChangeListener(null)
if (app.isChecked) {
holder.checkBox.isChecked = true
selectedApps.add(app)
} else {
holder.checkBox.isChecked = false
selectedApps.remove(app)
}
holder.checkBox.setOnCheckedChangeListener { _: CompoundButton?, isChecked: Boolean ->
selectionChange(isChecked)
}
holder.itemView.setOnClickListener {
selectionChange(!holder.checkBox.isChecked)
}
holder.label.text = app.label
holder.icon.setImageDrawable(app.icon)
}
override fun getItemCount(): Int {
return apps.size
}
} | app/src/main/java/com/androidvip/hebf/adapters/ForceStopAppsAdapter.kt | 2383032651 |
/*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hil.refactoring
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.intellij.plugins.hcl.terraform.config.refactoring.BaseIntroduceOperation
import org.intellij.plugins.hil.psi.ILExpression
class IntroduceOperation(project: Project, editor: Editor, file: PsiFile, name: String?) : BaseIntroduceOperation<ILExpression>(project, editor, file, name) | src/kotlin/org/intellij/plugins/hil/refactoring/IntroduceOperation.kt | 3858239727 |
package at.cpickl.gadsu.appointment.gcal
import at.cpickl.gadsu.appointment.gcal.sync.MatchClients
import at.cpickl.gadsu.appointment.gcal.sync.MatchClientsInDb
import at.cpickl.gadsu.client.Client
import at.cpickl.gadsu.client.ClientJdbcRepository
import at.cpickl.gadsu.testinfra.HsqldbTest
import at.cpickl.gadsu.testinfra.unsavedValidInstance
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.contains
import org.testng.annotations.BeforeMethod
import org.testng.annotations.Test
@Test(groups = arrayOf("hsqldb")) class MatchClientsInDbTest : HsqldbTest() {
private lateinit var testee: MatchClients
private lateinit var caroline: Client
private lateinit var carolina: Client
private lateinit var laura: Client
private lateinit var ingrid: Client
@BeforeMethod fun insertClients() {
testee = MatchClientsInDb(ClientJdbcRepository(jdbcx, idGenerator))
caroline = newClient("Caroline", "Caro", "Firefox")
carolina = newClient("Carolina", "Caro", "Safari")
laura = newClient("Laura", "", "Internet Chrome")
ingrid = newClient("Ingrid", "Haudegen", "Internet Explorer")
}
private fun findMatchingClientsProvider(): List<Pair<String, List<Client>>> = listOf(
// first name
testCase("caro", caroline, carolina),
testCase("caroline", caroline, carolina),
testCase("carolina", carolina, caroline),
// last name
testCase("chrome", laura),
testCase("inter", ingrid, laura),
// nick name
testCase("haudeg", ingrid)
)
// using a dataprovider does not really work here, as we need a client which is generated at runtime
fun `findMatchingClients by name _ should return clients _`() {
findMatchingClientsProvider().forEach {
assertThat("Search string: '${it.first}'", testee.findMatchingClients(it.first), contains(*it.second.toTypedArray()))
}
}
private fun newClient(firstName: String, nickName: String, lastName: String) =
insertClientViaRepo(Client.unsavedValidInstance().copy(firstName = firstName, nickNameInt = nickName, lastName = lastName))
private fun testCase(searchName: String, vararg expectedClients: Client): Pair<String, List<Client>> {
return Pair(searchName, expectedClients.toList())
}
}
| src/test/kotlin/at/cpickl/gadsu/appointment/gcal/matchclient.kt | 1565468833 |
package uk.co.appsbystudio.geoshare.authentication.login
interface LoginInteractor {
interface OnLoginFinishedListener {
fun onEmailError()
fun onPasswordError()
fun onSuccess()
fun onFailure(error: String)
}
fun login(email: String, password: String, listener: OnLoginFinishedListener)
} | mobile/src/main/java/uk/co/appsbystudio/geoshare/authentication/login/LoginInteractor.kt | 1321362890 |
package io.polymorphicpanda.kspec.context
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.present
import io.polymorphicpanda.kspec.Focus
import io.polymorphicpanda.kspec.focus
import io.polymorphicpanda.kspec.tag.SimpleTag
import org.junit.Test
/**
* @author Ranie Jade Ramiso
*/
class TaggingTest {
val focus = focus()
object TestTag: SimpleTag()
@Test
fun testTagExample() {
val tags = setOf(focus)
val example = Context.Example("example", Context.ExampleGroup("group", null), null, tags)
assertThat(example.contains(Focus::class), equalTo(true))
assertThat(example.contains(TestTag::class), equalTo(false))
}
@Test
fun testTagGroup() {
val parent = Context.ExampleGroup("group", null, setOf(focus))
val another = Context.ExampleGroup("another", parent)
val example = Context.Example("example", parent, null, setOf(TestTag))
assertThat(parent.contains(Focus::class), equalTo(true))
assertThat(another.contains(Focus::class), equalTo(true))
assertThat(example.contains(Focus::class), equalTo(true))
assertThat(example.contains(TestTag::class), equalTo(true))
}
@Test
fun testGetTagExample() {
val tags = setOf(focus)
val example = Context.Example("example", Context.ExampleGroup("group", null), null, tags)
assertThat(example.get<Focus>(), present(equalTo(focus)))
}
@Test
fun testGetTagGroup() {
val parent = Context.ExampleGroup("group", null, setOf(focus))
val another = Context.ExampleGroup("another", parent)
val example = Context.Example("example", parent, null, setOf(TestTag))
assertThat(parent.contains(Focus::class), equalTo(true))
assertThat(another.contains(Focus::class), equalTo(true))
assertThat(example.contains(Focus::class), equalTo(true))
assertThat(example.contains(TestTag::class), equalTo(true))
assertThat(parent.get<Focus>(), present(equalTo(focus)))
assertThat(another.get<Focus>(), present(equalTo(focus)))
assertThat(example.get<Focus>(), present(equalTo(focus)))
assertThat(example.get<TestTag>(), present(equalTo(TestTag)))
}
}
| kspec-core/src/test/kotlin/io/polymorphicpanda/kspec/context/TaggingTest.kt | 1655844096 |
package io.kotest.core.engine
import io.kotest.core.config.Project
import io.kotest.core.spec.Spec
import io.kotest.fp.Try
import kotlin.reflect.KClass
import kotlin.reflect.full.createInstance
/**
* Creates an instance of a [Spec] by delegating to constructor extensions, with
* a fallback to a reflection based zero-args constructor.
*/
fun <T : Spec> instantiateSpec(clazz: KClass<T>): Try<Spec> = Try {
val nullSpec: Spec? = null
Project.constructorExtensions()
.fold(nullSpec) { spec, ext -> spec ?: ext.instantiate(clazz) } ?: clazz.createInstance()
}
| kotest-core/src/jvmMain/kotlin/io/kotest/core/engine/instantiateSpec.kt | 3581345439 |
package io.kotest.matchers.equality
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.should
import io.kotest.matchers.shouldNot
import kotlin.reflect.KProperty
import kotlin.reflect.KVisibility
import kotlin.reflect.full.memberProperties
/**
* Asserts that this is equal to [other] using specific fields
*
* Verifies that [this] instance is equal to [other] using only some specific fields. This is useful for matching
* on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it
* doesn't matter for you, for example)
*
* Opposite of [shouldNotBeEqualToUsingFields]
*
* Example:
* ```
* data class Foo(val id: Int, val description: String)
*
* val firstFoo = Foo(1, "Bar!")
* val secondFoo = Foo(2, "Bar!")
*
* firstFoo.shouldBeEqualUsingFields(secondFoo, Foo::description) // Assertion passes
*
* firstFoo shouldBe secondFoo // Assertion fails, `equals` is false!
* ```
*
* Note:
* 1) Throws [IllegalArgumentException] in case [properties] parameter is not provided.
* 2) Throws [IllegalArgumentException] if [properties] contains any non public property
*
*/
fun <T : Any> T.shouldBeEqualToUsingFields(other: T, vararg properties: KProperty<*>) {
require(properties.isNotEmpty()) { "At-least one field is required to be mentioned for checking the equality" }
this should beEqualToUsingFields(other, *properties)
}
/**
* Asserts that this is NOT equal to [other] using specific fields
*
* Verifies that [this] instance is not equal to [other] using only some specific fields. This is useful for matching
* on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it
* doesn't matter for you, for example)
*
* Opposite of [shouldBeEqualToUsingFields]
*
* Example:
* ```
* data class Foo(val id: Int, val description: String)
*
* val firstFoo = Foo(1, "Bar!")
* val secondFoo = Foo(2, "BAT")
*
* firstFoo.shouldNotBeEqualToUsingFields(secondFoo, Foo::description) // Assertion passes
*
* ```
* Note:
* 1) Throws [IllegalArgumentException] in case [properties] parameter is not provided.
* 2) Throws [IllegalArgumentException] if [properties] contains any non public property
*
*
* @see [beEqualToUsingFields]
* @see [shouldNotBeEqualToIgnoringFields]
*
*/
fun <T : Any> T.shouldNotBeEqualToUsingFields(other: T, vararg properties: KProperty<*>) {
require(properties.isNotEmpty()) { "At-least one field is required to be mentioned for checking the equality" }
this shouldNot beEqualToUsingFields(other, *properties)
}
/**
* Matcher that compares values using specific fields
*
* Verifies that two instances not equal using only some specific fields. This is useful for matching
* on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it
* doesn't matter for you, for example)
*
*
* Example:
* ```
* data class Foo(val id: Int, val description: String)
*
* val firstFoo = Foo(1, "Bar!")
* val secondFoo = Foo(2, "Bar!")
*
* firstFoo should beEqualToUsingFields(secondFoo, Foo::description) // Assertion passes
*
* ```
*
* Note: Throws [IllegalArgumentException] if [fields] contains any non public property
*
* @see [shouldBeEqualToUsingFields]
* @see [shouldNotBeEqualToUsingFields]
* @see [beEqualToIgnoringFields]
*
*/
fun <T : Any> beEqualToUsingFields(other: T, vararg fields: KProperty<*>): Matcher<T> = object : Matcher<T> {
override fun test(value: T): MatcherResult {
val nonPublicFields = fields.filterNot { it.visibility == KVisibility.PUBLIC }
if(nonPublicFields.isNotEmpty()) {
throw IllegalArgumentException("Fields of only public visibility are allowed to be use for used for checking equality")
}
val failed = checkEqualityOfFields(fields.toList(), value, other)
val fieldsString = fields.joinToString(", ", "[", "]") { it.name }
return MatcherResult(
failed.isEmpty(),
"$value should be equal to $other using fields $fieldsString; Failed for $failed",
"$value should not be equal to $other using fields $fieldsString"
)
}
}
/**
* Asserts that this is equal to [other] without using specific fields
*
* Verifies that [this] instance is equal to [other] without using some specific fields. This is useful for matching
* on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it
* doesn't matter for you, for example)
*
* Opposite of [shouldNotBeEqualToIgnoringFields]
*
* Example:
* ```
* data class Foo(val id: Int, val description: String)
*
* val firstFoo = Foo(1, "Bar!")
* val secondFoo = Foo(2, "Bar!")
*
* firstFoo.shouldBeEqualToIgnoringFields(secondFoo, Foo::id) // Assertion passes
*
* firstFoo shouldBe secondFoo // Assertion fails, `equals` is false!
* ```
*
* Note: Throws [IllegalArgumentException] in case [properties] parameter is not provided.
*/
fun <T : Any> T.shouldBeEqualToIgnoringFields(other: T, vararg properties: KProperty<*>) {
require(properties.isNotEmpty()) { "At-least one field is required to be mentioned to be ignore for checking the equality" }
this should beEqualToIgnoringFields(other, *properties)
}
/**
* Asserts that this is not equal to [other] without using specific fields
*
* Verifies that [this] instance is not equal to [other] without using some specific fields. This is useful for matching
* on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it
* doesn't matter for you, for example)
*
* Opposite of [shouldBeEqualToIgnoringFields]
*
* Example:
* ```
* data class Foo(val id: Int, val description: String)
*
* val firstFoo = Foo(1, "Bar!")
* val secondFoo = Foo(2, "BAT!")
*
* firstFoo.shouldNotBeEqualToIgnoringFields(secondFoo, Foo::id) // Assertion passes
* ```
*
*/
fun <T : Any> T.shouldNotBeEqualToIgnoringFields(other: T, vararg properties: KProperty<*>) =
this shouldNot beEqualToIgnoringFields(other, *properties)
/**
* Matcher that compares values without using specific fields
*
* Verifies that two instances are equal by not using only some specific fields. This is useful for matching
* on objects that contain unknown values, such as a database Entity that contains an ID (you don't know this ID, and it
* doesn't matter for you, for example)
*
*
* Example:
* ```
* data class Foo(val id: Int, val description: String)
*
* val firstFoo = Foo(1, "Bar!")
* val secondFoo = Foo(2, "Bar!")
*
* firstFoo should beEqualToIgnoringFields(secondFoo, Foo::id) // Assertion passes
*
* ```
*
* @see [beEqualToUsingFields]
* @see [shouldBeEqualToIgnoringFields]
* @see [shouldNotBeEqualToIgnoringFields]
*
*/
fun <T : Any> beEqualToIgnoringFields(
other: T,
vararg fields: KProperty<*>
): Matcher<T> = object : Matcher<T> {
override fun test(value: T): MatcherResult {
val fieldNames = fields.map { it.name }
val fieldsToBeConsidered: List<KProperty<*>> = value::class.memberProperties
.filterNot { fieldNames.contains(it.name) }
.filter { it.visibility == KVisibility.PUBLIC }
val failed = checkEqualityOfFields(fieldsToBeConsidered, value, other)
val fieldsString = fields.joinToString(", ", "[", "]") { it.name }
return MatcherResult(
failed.isEmpty(),
"$value should be equal to $other ignoring fields $fieldsString; Failed for $failed",
"$value should not be equal to $other ignoring fields $fieldsString"
)
}
}
private fun <T> checkEqualityOfFields(fields: List<KProperty<*>>, value: T, other: T): List<String> {
return fields.mapNotNull {
val actual = it.getter.call(value)
val expected = it.getter.call(other)
if (actual == expected) null else {
"${it.name}: $actual != $expected"
}
}
}
| kotest-assertions/src/jvmMain/kotlin/io/kotest/matchers/equality/reflection.kt | 3095533181 |
package mil.nga.giat.mage.location
import android.content.Context
import android.content.SharedPreferences
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.os.Bundle
import android.util.Log
import androidx.lifecycle.LiveData
import dagger.hilt.android.qualifiers.ApplicationContext
import mil.nga.giat.mage.R
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class LocationProvider @Inject
constructor(@ApplicationContext val context: Context, val preferences: SharedPreferences) : LiveData<Location>(), SharedPreferences.OnSharedPreferenceChangeListener {
companion object {
private val LOG_NAME = LocationProvider::class.java.simpleName
}
private var locationManager: LocationManager? = null
private var locationListener: LiveDataLocationListener? = null
private var minimumDistanceChangeForUpdates: Long = 0
override fun onActive() {
super.onActive()
preferences.registerOnSharedPreferenceChangeListener(this)
locationManager = context.getSystemService(Context.LOCATION_SERVICE) as LocationManager
minimumDistanceChangeForUpdates = getMinimumDistanceChangeForUpdates()
requestLocationUpdates()
try {
var location: Location? = locationManager?.getLastKnownLocation(LocationManager.GPS_PROVIDER)
if (location == null) {
location = locationManager?.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)
}
location?.let { setValue(it) }
} catch (e: SecurityException) {
Log.i(LOG_NAME, "Error requesting location updates")
}
}
override fun onInactive() {
super.onInactive()
removeLocationUpdates()
preferences.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) {
if (key.equals(context.getString(R.string.gpsSensitivityKey), ignoreCase = true)) {
Log.d(LOG_NAME, "GPS sensitivity changed, distance in meters for change: $minimumDistanceChangeForUpdates")
minimumDistanceChangeForUpdates = getMinimumDistanceChangeForUpdates()
// bounce location updates so new distance sensitivity takes effect
removeLocationUpdates()
requestLocationUpdates()
}
}
private fun requestLocationUpdates() {
Log.v(LOG_NAME, "request location updates")
locationListener = LiveDataLocationListener().apply {
try {
locationManager?.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, minimumDistanceChangeForUpdates.toFloat(), this)
} catch (ex: java.lang.SecurityException) {
Log.i(LOG_NAME, "Error requesting location updates", ex)
} catch (ex: IllegalArgumentException) {
Log.d(LOG_NAME, "LocationManager.NETWORK_PROVIDER does not exist, " + ex.message)
}
try {
locationManager?.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, minimumDistanceChangeForUpdates.toFloat(), this)
} catch (ex: SecurityException) {
Log.i(LOG_NAME, "Error requesting location updates", ex)
} catch (ex: IllegalArgumentException) {
Log.d(LOG_NAME, "LocationManager.GPS_PROVIDER does not exist, " + ex.message)
}
}
}
private fun removeLocationUpdates() {
Log.v(LOG_NAME, "Removing location updates.")
locationListener?.let {
locationManager?.removeUpdates(it)
locationListener = null
}
}
private fun getMinimumDistanceChangeForUpdates(): Long {
return preferences.getInt(context.getString(R.string.gpsSensitivityKey), context.resources.getInteger(R.integer.gpsSensitivityDefaultValue)).toLong()
}
private inner class LiveDataLocationListener : LocationListener {
override fun onLocationChanged(location: Location) { setValue(location) }
override fun onProviderDisabled(provider: String) {}
override fun onProviderEnabled(provider: String) {}
override fun onStatusChanged(provider: String, status: Int, extras: Bundle) {}
}
}
| mage/src/main/java/mil/nga/giat/mage/location/LocationProvider.kt | 2283536292 |
package com.cout970.magneticraft.systems.computer.exception
import com.cout970.magneticraft.api.computer.ICPU
/**
* Created by cout970 on 03/06/2016.
*/
class NullPointerException : ICPU.IInterruption {
override fun getCode(): Int {
return 6
}
override fun getDescription(): String {
return "Attempt to jump to an invalid location (addr == 0)"
}
override fun getName(): String {
return "NULL POINTER EXCEPTION"
}
}
| src/main/kotlin/com/cout970/magneticraft/systems/computer/exception/NullPointerException.kt | 1714952693 |
package com.projctr.protostorage.writer
import com.google.protobuf.GeneratedMessage
import com.projctr.protostorage.configuration.StorageObjectConfiguration
import org.skife.jdbi.v2.DBI
internal class StorageWriter<in T: GeneratedMessage>(private val objectConfiguration: StorageObjectConfiguration, private val dbi: DBI) {
fun insert(obj: T) {
val builder: StringBuilder = StringBuilder()
with(objectConfiguration) {
val pkColumnNames = primaryKeyFields.map { "id_${it.name}" }.joinToString()
val valueNames = mutableListOf(pkColumnNames)
if (indexedColumns.size > 0) {
val indexedColumnNames = indexedColumns.map { it.name }.joinToString()
valueNames.add(indexedColumnNames)
}
val valuePlaceholders = valueNames.map { ":$it" }
val pkValues = primaryKeyFields.map { obj.getField(it) }
val indexedValues = indexedColumns.map { obj.getField(it) }
builder.append("insert into $tableName (${valueNames.joinToString()}, data) values (${valuePlaceholders.joinToString()}, :data)")
dbi.open().use {
val query = it.createStatement(builder.toString())
var i = 0
for (pkValue in pkValues) {
query.bind(i++, pkValue)
}
for (indexedValue in indexedValues) {
query.bind(i++, indexedValue)
}
query.bind(i, obj.toByteArray())
query.execute()
}
}
}
fun update(obj: T) {
// TODO
}
} | src/main/kotlin/com/projctr/protostorage/writer/StorageWriter.kt | 3944175726 |
/*
* 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.precompile
import org.gradle.internal.hash.Hashing
import org.gradle.kotlin.dsl.resolver.KotlinBuildScriptDependencies
import java.util.concurrent.Future
import kotlin.script.dependencies.Environment
import kotlin.script.dependencies.KotlinScriptExternalDependencies
import kotlin.script.dependencies.PseudoFuture
import kotlin.script.dependencies.ScriptContents
import kotlin.script.dependencies.ScriptDependenciesResolver
class PrecompiledScriptDependenciesResolver : ScriptDependenciesResolver {
companion object {
fun hashOf(charSequence: CharSequence?) = Hashing.hashString(charSequence).toString()
}
object EnvironmentProperties {
const val kotlinDslImplicitImports = "kotlinDslImplicitImports"
}
override fun resolve(
script: ScriptContents,
environment: Environment?,
report: (ScriptDependenciesResolver.ReportSeverity, String, ScriptContents.Position?) -> Unit,
previousDependencies: KotlinScriptExternalDependencies?
): Future<KotlinScriptExternalDependencies?> =
PseudoFuture(
KotlinBuildScriptDependencies(
imports = implicitImportsFrom(environment) + precompiledScriptPluginImportsFrom(environment, script),
classpath = emptyList(),
sources = emptyList()
)
)
private
fun implicitImportsFrom(environment: Environment?) =
environment.stringList(EnvironmentProperties.kotlinDslImplicitImports)
private
fun precompiledScriptPluginImportsFrom(environment: Environment?, script: ScriptContents): List<String> =
environment.stringList(hashOf(script.text))
private
fun Environment?.stringList(key: String) =
string(key)?.split(':')
?: emptyList()
private
fun Environment?.string(key: String) =
this?.get(key) as? String
}
| subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/precompile/PrecompiledScriptDependenciesResolver.kt | 2664715324 |
package com.idapgroup.android.mvp.impl.v2
import android.app.Activity
import android.app.Application.ActivityLifecycleCallbacks
import android.content.Context
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentManager.FragmentLifecycleCallbacks
import android.view.View
fun ActivityLifecycleCallbacks.filter(activity: Activity): ActivityLifecycleCallbacks {
return filter { it === activity }
}
fun ActivityLifecycleCallbacks.filter(predicate: (Activity) -> Boolean): ActivityLifecycleCallbacks {
val delegate = this
return object : ActivityLifecycleCallbacks {
override fun onActivityCreated(a: Activity, savedInstanceState: Bundle?) {
if(predicate(a)) delegate.onActivityCreated(a, savedInstanceState)
}
override fun onActivitySaveInstanceState(a: Activity, outState: Bundle) {
if(predicate(a)) delegate.onActivitySaveInstanceState(a, outState)
}
override fun onActivityStarted(a: Activity) {
if(predicate(a)) delegate.onActivityStarted(a)
}
override fun onActivityResumed(a: Activity) {
if(predicate(a)) delegate.onActivityResumed(a)
}
override fun onActivityPaused(a: Activity) {
if(predicate(a)) delegate.onActivityPaused(a)
}
override fun onActivityStopped(a: Activity) {
if(predicate(a)) delegate.onActivityStopped(a)
}
override fun onActivityDestroyed(a: Activity) {
if(predicate(a)) delegate.onActivityDestroyed(a)
}
}
}
fun FragmentLifecycleCallbacks.filter(fragment: Fragment): FragmentLifecycleCallbacks {
return filter { it === fragment }
}
fun FragmentLifecycleCallbacks.filter(predicate: (Fragment) -> Boolean): FragmentLifecycleCallbacks {
val delegate = this
return object : FragmentLifecycleCallbacks() {
override fun onFragmentPreAttached(fm: FragmentManager?, f: Fragment, context: Context?) {
if(predicate(f)) delegate.onFragmentPreAttached(fm, f, context)
}
override fun onFragmentAttached(fm: FragmentManager?, f: Fragment, context: Context?) {
if(predicate(f)) delegate.onFragmentAttached(fm, f, context)
}
override fun onFragmentActivityCreated(fm: FragmentManager?, f: Fragment, savedInstanceState: Bundle?) {
if(predicate(f)) delegate.onFragmentActivityCreated(fm, f, savedInstanceState)
}
override fun onFragmentCreated(fm: FragmentManager?, f: Fragment, savedInstanceState: Bundle?) {
if(predicate(f)) delegate.onFragmentCreated(fm, f, savedInstanceState)
}
override fun onFragmentSaveInstanceState(fm: FragmentManager, f: Fragment, outState: Bundle) {
if(predicate(f)) delegate.onFragmentSaveInstanceState(fm, f, outState)
}
override fun onFragmentViewCreated(fm: FragmentManager, f: Fragment, v: View?, savedInstanceState: Bundle?) {
if(predicate(f)) delegate.onFragmentViewCreated(fm, f, v, savedInstanceState)
}
override fun onFragmentStarted(fm: FragmentManager, f: Fragment) {
if(predicate(f)) delegate.onFragmentStarted(fm, f)
}
override fun onFragmentResumed(fm: FragmentManager, f: Fragment) {
if(predicate(f)) delegate.onFragmentResumed(fm, f)
}
override fun onFragmentPaused(fm: FragmentManager, f: Fragment) {
if(predicate(f)) delegate.onFragmentPaused(fm, f)
}
override fun onFragmentStopped(fm: FragmentManager, f: Fragment) {
if(predicate(f)) delegate.onFragmentStopped(fm, f)
}
override fun onFragmentViewDestroyed(fm: FragmentManager, f: Fragment) {
if(predicate(f)) delegate.onFragmentViewDestroyed(fm, f)
}
override fun onFragmentDestroyed(fm: FragmentManager?, f: Fragment) {
if(predicate(f)) delegate.onFragmentDestroyed(fm, f)
}
override fun onFragmentDetached(fm: FragmentManager?, f: Fragment) {
if(predicate(f)) delegate.onFragmentDetached(fm, f)
}
}
} | mvp/src/main/java/com/idapgroup/android/mvp/impl/v2/LifecycleCallbacks.kt | 4061723693 |
package com.github.simonpercic.oklogexample.ui
import com.github.simonpercic.oklogexample.AppComponent
import com.github.simonpercic.oklogexample.ui.base.scope.PerActivity
import dagger.Component
/**
* Main Activity's Dagger component.
* @author Simon Percic [https://github.com/simonpercic](https://github.com/simonpercic)
*/
@PerActivity
@Component(dependencies = arrayOf(AppComponent::class), modules = arrayOf(MainModule::class))
interface MainComponent {
fun inject(activity: MainActivity)
}
| example/src/main/kotlin/com/github/simonpercic/oklogexample/ui/MainComponent.kt | 2097758995 |
package io.flutter.plugins.deviceinfoexample.example
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity()
| packages/device_info_plus/device_info_plus/example/android/app/src/main/kotlin/io/flutter/plugins/deviceinfoexample/example/MainActivity.kt | 2239402408 |
/**
* Pokemon Go Bot Copyright (C) 2016 PokemonGoBot-authors (see authors.md for more information)
* This program comes with ABSOLUTELY NO WARRANTY;
* This is free software, and you are welcome to redistribute it under certain conditions.
*
* For more information, refer to the LICENSE file in this repositories root directory
*/
package ink.abb.pogo.scraper.controllers
import POGOProtos.Data.PokedexEntryOuterClass
import POGOProtos.Enums.PokemonIdOuterClass
import POGOProtos.Inventory.Item.ItemIdOuterClass
import com.pokegoapi.api.inventory.Item
import com.pokegoapi.api.inventory.ItemBag
import com.pokegoapi.api.map.pokemon.EvolutionResult
import com.pokegoapi.api.player.PlayerProfile
import com.pokegoapi.api.pokemon.Pokemon
import com.pokegoapi.google.common.geometry.S2LatLng
import ink.abb.pogo.scraper.Context
import ink.abb.pogo.scraper.Settings
import ink.abb.pogo.scraper.services.BotService
import ink.abb.pogo.scraper.util.ApiAuthProvider
import ink.abb.pogo.scraper.util.Log
import ink.abb.pogo.scraper.util.credentials.GoogleAutoCredentials
import ink.abb.pogo.scraper.util.data.*
import ink.abb.pogo.scraper.util.pokemon.getStatsFormatted
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.*
import javax.servlet.http.HttpServletResponse
@RestController
@CrossOrigin
@RequestMapping("/api")
class BotController {
@Autowired
lateinit var service: BotService
@Autowired
lateinit var authProvider: ApiAuthProvider
@RequestMapping("/bots")
fun bots(): List<Settings> {
return service.getAllBotSettings()
}
@RequestMapping(value = "/bot/{name}/auth", method = arrayOf(RequestMethod.POST))
fun auth(
@PathVariable name: String,
@RequestBody pass: String,
httpResponse: HttpServletResponse
): String {
val ctx = service.getBotContext(name)
if (ctx.restApiPassword.equals("")) {
Log.red("REST API: There is no REST API password set in the configuration for bot $name, generating one now...")
authProvider.generateRestPassword(name)
return "REST API password generated for bot $name, check your console output!"
}
authProvider.generateAuthToken(name)
if (!pass.equals(ctx.restApiPassword))
{
httpResponse.status = HttpServletResponse.SC_UNAUTHORIZED
return "Your authentication request ($pass) does not match the REST API password from the bot $name configuration!"
}
return ctx.restApiToken
}
@RequestMapping(value = "/bot/{name}/load", method = arrayOf(RequestMethod.POST))
fun loadBot(@PathVariable name: String): Settings {
Log.magenta("REST API: Load bot $name")
return service.submitBot(name)
}
@RequestMapping(value = "/bot/{name}/unload", method = arrayOf(RequestMethod.POST))
fun unloadBot(@PathVariable name: String): String {
Log.magenta("REST API: Unload bot $name")
return service.doWithBot(name) {
it.stop()
service.removeBot(it)
}.toString()
}
@RequestMapping(value = "/bot/{name}/reload", method = arrayOf(RequestMethod.POST))
fun reloadBot(@PathVariable name: String): Settings {
Log.magenta("REST API: Reload bot $name")
if (unloadBot(name).equals("false")) // return default settings
return Settings(
credentials = GoogleAutoCredentials(),
latitude = 0.0,
longitude = 0.0
)
return loadBot(name)
}
@RequestMapping(value = "/bot/{name}/start", method = arrayOf(RequestMethod.POST))
fun startBot(@PathVariable name: String): String {
Log.magenta("REST API: Starting bot $name")
return service.doWithBot(name) { it.start() }.toString()
}
@RequestMapping(value = "/bot/{name}/stop", method = arrayOf(RequestMethod.POST))
fun stopBot(@PathVariable name: String): String {
Log.magenta("REST API: Stopping bot $name")
return service.doWithBot(name) { it.stop() }.toString()
}
@RequestMapping(value = "/bot/{name}/pokemons", method = arrayOf(RequestMethod.GET))
fun listPokemons(@PathVariable name: String): List<PokemonData> {
service.getBotContext(name).api.inventories.updateInventories(true)
val pokemons = mutableListOf<PokemonData>()
for (pokemon in service.getBotContext(name).api.inventories.pokebank.pokemons) {
pokemons.add(PokemonData().buildFromPokemon(pokemon))
}
return pokemons
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/transfer", method = arrayOf(RequestMethod.POST))
fun transferPokemon(
@PathVariable name: String,
@PathVariable id: Long
): String {
val result: String
val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id)
result = pokemon!!.transferPokemon().toString()
Log.magenta("REST API: Transferring pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp})")
// Update GUI
service.getBotContext(name).server.sendPokebank()
return result
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/evolve", method = arrayOf(RequestMethod.POST))
fun evolvePokemon(
@PathVariable name: String,
@PathVariable id: Long,
httpResponse: HttpServletResponse
): String {
val result: String
val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id)
if (pokemon!!.candiesToEvolve > pokemon.candy) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
result = "Not enough candies to evolve: ${pokemon.candy}/${pokemon.candiesToEvolve}"
} else {
val evolutionResult: EvolutionResult
val evolved: Pokemon
evolutionResult = pokemon.evolve()
evolved = evolutionResult.evolvedPokemon
Log.magenta("REST API: Evolved pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp})"
+ " to pokemon ${evolved.pokemonId.name} with stats (${evolved.getStatsFormatted()} CP: ${evolved.cp})")
result = evolutionResult.result.toString()
}
// Update GUI
service.getBotContext(name).server.sendPokebank()
return result
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/powerup", method = arrayOf(RequestMethod.POST))
fun powerUpPokemon(
@PathVariable name: String,
@PathVariable id: Long,
httpResponse: HttpServletResponse
): String {
val result: String
val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id)
if (pokemon!!.candyCostsForPowerup > pokemon.candy) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
result = "Not enough candies to powerup: ${pokemon.candy}/${pokemon.candyCostsForPowerup}"
} else if (pokemon.stardustCostsForPowerup > service.getBotContext(name).api.playerProfile.currencies.get(PlayerProfile.Currency.STARDUST)!!.toInt()) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
result = "Not enough stardust to powerup: ${service.getBotContext(name).api.playerProfile.currencies.get(PlayerProfile.Currency.STARDUST)}/${pokemon.stardustCostsForPowerup}"
} else {
Log.magenta("REST API: Powering up pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp})")
result = pokemon.powerUp().toString()
Log.magenta("REST API: Pokemon new CP ${pokemon.cp}")
}
// Update GUI
service.getBotContext(name).server.sendPokebank()
return result
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/favorite", method = arrayOf(RequestMethod.POST))
fun togglePokemonFavorite(
@PathVariable name: String,
@PathVariable id: Long
): String {
val result: String
val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id)
result = pokemon!!.setFavoritePokemon(!pokemon.isFavorite).toString()
when (pokemon.isFavorite) {
true -> Log.magenta("REST API: Pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp}) is favorited")
false -> Log.magenta("REST API: Pokemon ${pokemon.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp}) is now unfavorited")
}
// Update GUI
service.getBotContext(name).server.sendPokebank()
return result
}
@RequestMapping(value = "/bot/{name}/pokemon/{id}/rename", method = arrayOf(RequestMethod.POST))
fun renamePokemon(
@PathVariable name: String,
@PathVariable id: Long,
@RequestBody newName: String
): String {
val pokemon: Pokemon? = getPokemonById(service.getBotContext(name), id)
Log.magenta("REST API: Renamed pokemon ${pokemon!!.pokemonId.name} with stats (${pokemon.getStatsFormatted()} CP: ${pokemon.cp}) to $newName")
return pokemon!!.renamePokemon(newName).toString()
}
@RequestMapping("/bot/{name}/items")
fun listItems(@PathVariable name: String): List<ItemData> {
service.getBotContext(name).api.inventories.updateInventories(true)
val items = mutableListOf<ItemData>()
for (item in service.getBotContext(name).api.inventories.itemBag.items) {
items.add(ItemData().buildFromItem(item))
}
return items
}
@RequestMapping(value = "/bot/{name}/item/{id}/drop/{quantity}", method = arrayOf(RequestMethod.DELETE))
fun dropItem(
@PathVariable name: String,
@PathVariable id: Int,
@PathVariable quantity: Int,
httpResponse: HttpServletResponse
): String {
val itemBag: ItemBag = service.getBotContext(name).api.inventories.itemBag
val item: Item? = itemBag.items.find { it.itemId.number == id }
if (quantity > item!!.count) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
return "Not enough items to drop ${item.count}"
} else {
Log.magenta("REST API: Dropping ${quantity} ${item.itemId.name}")
return itemBag.removeItem(item.itemId, quantity).toString()
}
}
@RequestMapping(value = "/bot/{name}/useIncense", method = arrayOf(RequestMethod.POST))
fun useIncense(
@PathVariable name: String,
httpResponse: HttpServletResponse
): String {
val itemBag = service.getBotContext(name).api.inventories.itemBag
val count = itemBag.items.find { it.itemId == ItemIdOuterClass.ItemId.ITEM_INCENSE_ORDINARY }?.count
if (count == 0) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
return "Not enough incenses"
} else {
itemBag.useIncense()
Log.magenta("REST API: Used incense")
return "SUCCESS"
}
}
@RequestMapping(value = "/bot/{name}/useLuckyEgg", method = arrayOf(RequestMethod.POST))
fun useLuckyEgg(
@PathVariable name: String,
httpResponse: HttpServletResponse
): String {
val itemBag = service.getBotContext(name).api.inventories.itemBag
val count = itemBag.items.find { it.itemId == ItemIdOuterClass.ItemId.ITEM_LUCKY_EGG }?.count
if (count == 0) {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
return "Not enough lucky eggs"
} else {
Log.magenta("REST API: Used lucky egg")
return itemBag.useLuckyEgg().result.toString()
}
}
@RequestMapping(value = "/bot/{name}/location", method = arrayOf(RequestMethod.GET))
fun getLocation(@PathVariable name: String): LocationData {
return LocationData(
service.getBotContext(name).api.latitude,
service.getBotContext(name).api.longitude
)
}
@RequestMapping(value = "/bot/{name}/location/{latitude}/{longitude}", method = arrayOf(RequestMethod.POST))
fun changeLocation(
@PathVariable name: String,
@PathVariable latitude: Double,
@PathVariable longitude: Double,
httpResponse: HttpServletResponse
): String {
val ctx: Context = service.getBotContext(name)
if (!latitude.isNaN() && !longitude.isNaN()) {
ctx.server.coordinatesToGoTo.add(S2LatLng.fromDegrees(latitude, longitude))
Log.magenta("REST API: Added ToGoTo coordinates $latitude $longitude")
return "SUCCESS"
} else {
httpResponse.status = HttpServletResponse.SC_BAD_REQUEST
return "FAIL"
}
}
@RequestMapping(value = "/bot/{name}/profile", method = arrayOf(RequestMethod.GET))
fun getProfile(@PathVariable name: String): ProfileData {
return ProfileData().buildFromApi(service.getBotContext(name).api)
}
@RequestMapping(value = "/bot/{name}/pokedex", method = arrayOf(RequestMethod.GET))
fun getPokedex(@PathVariable name: String): List<PokedexEntry> {
val pokedex = mutableListOf<PokedexEntry>()
val api = service.getBotContext(name).api
for (i in 0..151) {
val entry: PokedexEntryOuterClass.PokedexEntry? = api.inventories.pokedex.getPokedexEntry(PokemonIdOuterClass.PokemonId.forNumber(i))
entry ?: continue
pokedex.add(PokedexEntry().buildFromEntry(entry))
}
return pokedex
}
@RequestMapping(value = "/bot/{name}/eggs", method = arrayOf(RequestMethod.GET))
fun getEggs(@PathVariable name: String): List<EggData> {
service.getBotContext(name).api.inventories.updateInventories(true)
val eggs = mutableListOf<EggData>()
for (egg in service.getBotContext(name).api.inventories.hatchery.eggs) {
eggs.add(EggData().buildFromEggPokemon(egg))
}
return eggs
}
// FIXME! currently, the IDs returned by the API are not unique. It seems that only the last 6 digits change so we remove them
fun getPokemonById(ctx: Context, id: Long): Pokemon? {
return ctx.api.inventories.pokebank.pokemons.find {
(("" + id).substring(0, ("" + id).length - 6)).equals(("" + it.id).substring(0, ("" + it.id).length - 6))
}
}
}
| src/main/kotlin/ink/abb/pogo/scraper/controllers/BotController.kt | 12833048 |
package com.thornbirds.frameworkext.component.route
import com.thornbirds.component.IParams
/**
* @author YangLi [email protected]
*/
interface IRouterController
interface IPageRouter<T : IRouterController> : IRouter<T>
interface IPageParams : IParams
interface IPageEntry<T : IRouterController> {
fun matchController(controller: IRouterController): Boolean
fun performCreate(parentController: T)
fun performStart()
fun performStop()
fun performDestroy()
fun performBackPress(): Boolean
}
interface IPageCreator<T : IPageEntry<*>> {
fun create(params: IPageParams?): T
} | framework/src/main/java/com/thornbirds/frameworkext/component/route/IPageRouter.kt | 1631653973 |
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.networks.db
import com.google.android.horologist.networks.ExperimentalHorologistNetworksApi
import com.google.android.horologist.networks.data.DataRequest
import com.google.android.horologist.networks.data.DataRequestRepository
import com.google.android.horologist.networks.data.DataUsageReport
import com.google.android.horologist.networks.data.NetworkType
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import java.time.Instant
import java.time.LocalDate
import java.time.ZoneOffset
@ExperimentalHorologistNetworksApi
public class DBDataRequestRepository(
public val networkUsageDao: NetworkUsageDao,
public val coroutineScope: CoroutineScope
) : DataRequestRepository {
public val today: LocalDate = LocalDate.now()
// TODO update on day roll
public val day: Int = today.let { it.year * 1000 + it.dayOfYear }
public val from: Instant = today.atStartOfDay().toInstant(ZoneOffset.UTC)
public val to: Instant = today.plusDays(1).atStartOfDay().toInstant(ZoneOffset.UTC)
override fun storeRequest(dataRequest: DataRequest) {
val bytes = dataRequest.dataBytes
coroutineScope.launch {
var rows = networkUsageDao.updateBytes(day, bytes)
if (rows == 0) {
rows =
networkUsageDao.insert(DataUsage(dataRequest.networkInfo.type.name, bytes, day))
.toInt()
if (rows == -1) {
networkUsageDao.updateBytes(day, bytes)
}
}
}
}
override fun currentPeriodUsage(): Flow<DataUsageReport> {
return networkUsageDao.getRecords(day).map { list ->
var ble = 0L
var cell = 0L
var wifi = 0L
var unknown = 0L
list.forEach {
when (it.networkType) {
"ble" -> ble += it.bytesTotal
"cell" -> cell += it.bytesTotal
"wifi" -> wifi += it.bytesTotal
"unknown" -> unknown += it.bytesTotal
}
}
DataUsageReport(
dataByType = mapOf(
NetworkType.BT to ble,
NetworkType.Cell to cell,
NetworkType.Wifi to wifi,
NetworkType.Unknown to unknown
),
from = from,
to = to
)
}
}
}
| network-awareness/src/main/java/com/google/android/horologist/networks/db/DBDataRequestRepository.kt | 2530777949 |
package meh.watchdoge.request;
import android.os.Message;
open class Command(command: Int): Builder {
protected val _command = command;
override fun build(msg: Message) {
msg.arg1 = msg.arg1 or (_command shl 8);
}
}
open class CommandWithId(id: Int, command: Int): Command(command) {
protected val _id = id;
override fun build(msg: Message) {
super.build(msg);
msg.arg2 = _id;
}
}
open class Family(family: Int): Builder {
protected val _family = family;
protected lateinit var _command: Command;
override fun build(msg: Message) {
msg.arg1 = msg.arg1 or _family;
_command.build(msg);
}
}
| src/main/java/meh/watchdoge/request/util.kt | 1197841656 |
package org.wordpress.android.fluxc.model.order
import com.google.gson.annotations.SerializedName
/**
* Represents a tax line
*/
class TaxLine {
@SerializedName("id")
val id: Long? = null
@SerializedName("rate_id")
val rateId: Long? = null
@SerializedName("rate_code")
val rateCode: String? = null
@SerializedName("rate_percent")
val ratePercent: Float? = null
@SerializedName("label")
val label: String? = null
@SerializedName("compound")
val compound: Boolean? = null
@SerializedName("tax_total")
val taxTotal: String? = null
@SerializedName("shipping_tax_total")
val shippingTaxTotal: String? = null
}
| plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/model/order/TaxLine.kt | 3619760984 |
package org.koin.dsl
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.koin.Simple
import org.koin.test.getBeanDefinition
class BeanOptionsTest {
@Test
fun `definition created at start`() {
val app = koinApplication {
modules(
module {
single(createdAtStart = true) { Simple.ComponentA() }
single { Simple.ComponentB(get()) }
}
)
}
val defA = app.getBeanDefinition(Simple.ComponentA::class) ?: error("no definition found")
assertTrue(defA.options.isCreatedAtStart)
val defB = app.getBeanDefinition(Simple.ComponentB::class) ?: error("no definition found")
assertFalse(defB.options.isCreatedAtStart)
}
@Test
fun `definition override`() {
val app = koinApplication {
modules(
module {
single { Simple.ComponentA() }
single(override = true) { Simple.ComponentB(get()) }
}
)
}
val defA = app.getBeanDefinition(Simple.ComponentA::class) ?: error("no definition found")
assertFalse(defA.options.override)
val defB = app.getBeanDefinition(Simple.ComponentB::class) ?: error("no definition found")
assertTrue(defB.options.override)
}
} | koin-projects/koin-core/src/test/java/org/koin/dsl/BeanOptionsTest.kt | 2150403744 |
package be.vergauwen.simon.androidretaindata.core.di
import be.vergauwen.simon.androidretaindata.core.data.RxDataRepository
import be.vergauwen.simon.androidretaindata.core.rx.Transformers
import dagger.Component
@ApplicationScope
@Component(modules = arrayOf(ApplicationModule::class,ServiceModule::class))
interface ApplicationComponent {
val transfomers : Transformers
val dataRepository : RxDataRepository
} | sample/app/src/main/kotlin/be/vergauwen/simon/androidretaindata/core/di/ApplicationComponent.kt | 1124883183 |
package it.sephiroth.android.library.bottomnavigation
import android.content.Context
import android.util.AttributeSet
import android.view.View
import androidx.annotation.IntDef
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.core.view.ViewCompat
import java.lang.annotation.Retention
import java.lang.annotation.RetentionPolicy
/**
* Created by alessandro on 4/2/16.
*/
abstract class VerticalScrollingBehavior<V : View>(context: Context, attrs: AttributeSet) :
CoordinatorLayout.Behavior<V>(context, attrs) {
private var mTotalDyUnconsumed = 0
private var mTotalDy = 0
/*
@return Over scroll direction: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN, SCROLL_NONE
*/
@ScrollDirection
@get:ScrollDirection
var overScrollDirection = ScrollDirection.SCROLL_NONE
private set
/**
* @return Scroll direction: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN, SCROLL_NONE
*/
@ScrollDirection
@get:ScrollDirection
var scrollDirection = ScrollDirection.SCROLL_NONE
private set
@Suppress("DEPRECATED_JAVA_ANNOTATION")
@Retention(RetentionPolicy.SOURCE)
@IntDef(ScrollDirection.SCROLL_DIRECTION_UP, ScrollDirection.SCROLL_DIRECTION_DOWN)
annotation class ScrollDirection {
companion object {
const val SCROLL_DIRECTION_UP = 1
const val SCROLL_DIRECTION_DOWN = -1
const val SCROLL_NONE = 0
}
}
/**
* @param coordinatorLayout
* @param child
* @param direction Direction of the over scroll: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN
* @param currentOverScroll Unconsumed value, negative or positive based on the direction;
* @param totalOverScroll Cumulative value for current direction
*/
abstract fun onNestedVerticalOverScroll(
coordinatorLayout: CoordinatorLayout, child: V, @ScrollDirection direction: Int, currentOverScroll: Int,
totalOverScroll: Int)
/**
* @param scrollDirection Direction of the over scroll: SCROLL_DIRECTION_UP, SCROLL_DIRECTION_DOWN
*/
abstract fun onDirectionNestedPreScroll(
coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int, consumed: IntArray,
@ScrollDirection scrollDirection: Int)
override fun onStartNestedScroll(
coordinatorLayout: CoordinatorLayout, child: V, directTargetChild: View, target: View, nestedScrollAxes: Int,
@ViewCompat.NestedScrollType type: Int): Boolean {
return nestedScrollAxes and ViewCompat.SCROLL_AXIS_VERTICAL != 0
}
override fun onNestedScroll(
coordinatorLayout: CoordinatorLayout, child: V, target: View, dxConsumed: Int, dyConsumed: Int, dxUnconsumed: Int,
dyUnconsumed: Int, @ViewCompat.NestedScrollType type: Int) {
super.onNestedScroll(coordinatorLayout, child, target, dxConsumed, dyConsumed, dxUnconsumed, dyUnconsumed, type)
if (dyUnconsumed > 0 && mTotalDyUnconsumed < 0) {
mTotalDyUnconsumed = 0
overScrollDirection = ScrollDirection.SCROLL_DIRECTION_UP
} else if (dyUnconsumed < 0 && mTotalDyUnconsumed > 0) {
mTotalDyUnconsumed = 0
overScrollDirection = ScrollDirection.SCROLL_DIRECTION_DOWN
}
mTotalDyUnconsumed += dyUnconsumed
onNestedVerticalOverScroll(coordinatorLayout, child, overScrollDirection, dyConsumed, mTotalDyUnconsumed)
}
override fun onNestedPreScroll(coordinatorLayout: CoordinatorLayout, child: V, target: View, dx: Int, dy: Int,
consumed: IntArray, @ViewCompat.NestedScrollType type: Int) {
super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, type)
if (dy > 0 && mTotalDy < 0) {
mTotalDy = 0
scrollDirection = ScrollDirection.SCROLL_DIRECTION_UP
} else if (dy < 0 && mTotalDy > 0) {
mTotalDy = 0
scrollDirection = ScrollDirection.SCROLL_DIRECTION_DOWN
}
mTotalDy += dy
onDirectionNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed, scrollDirection)
}
override fun onNestedFling(
coordinatorLayout: CoordinatorLayout, child: V, target: View, velocityX: Float, velocityY: Float,
consumed: Boolean): Boolean {
super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed)
scrollDirection = if (velocityY > 0) ScrollDirection.SCROLL_DIRECTION_UP else ScrollDirection.SCROLL_DIRECTION_DOWN
return onNestedDirectionFling(coordinatorLayout, child, target, velocityX, velocityY, scrollDirection)
}
protected abstract fun onNestedDirectionFling(
coordinatorLayout: CoordinatorLayout, child: V, target: View, velocityX: Float, velocityY: Float,
@ScrollDirection scrollDirection: Int): Boolean
} | bottom-navigation/src/main/java/it/sephiroth/android/library/bottomnavigation/VerticalScrollingBehavior.kt | 3855988805 |
package us.mikeandwan.photos.utils
import android.content.Context
import android.content.res.Resources
import android.util.TypedValue
import us.mikeandwan.photos.R
fun Context.getTextColor(isActive: Boolean): Int {
val colorAttribute = if(isActive) R.attr.colorPrimary else R.attr.colorOnSurface
return getColorFromAttribute(colorAttribute)
}
fun Context.getColorFromAttribute(colorAttribute: Int): Int {
val typedValue = TypedValue()
val theme: Resources.Theme = this.theme
theme.resolveAttribute(colorAttribute, typedValue, true)
return typedValue.data
} | MaWPhotos/src/main/java/us/mikeandwan/photos/utils/ContextExtensions.kt | 2373728397 |
/*
* Copyright 2019 Andrey Tolpeev
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.vase4kin.teamcityapp.base.presenter
/**
* Base presenter
*/
interface BasePresenter {
/**
* handle activity onCreate callback
*/
fun onCreate()
/**
* handle activity onDestroy callback
*/
fun onDestroy()
}
| app/src/main/java/com/github/vase4kin/teamcityapp/base/presenter/BasePresenter.kt | 2175009685 |
package com.example
class KotlinConsts {
companion object {
const val ACTION = "REPLACE"
const val ACTION2 = "REPLACE"
}
}
| integration-tests/src/test/resources/kotlin-consts-in-java/workload/src/main/java/com/example/KotlinConsts.kt | 4206572684 |
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.tivi.domain.observers
import androidx.paging.ExperimentalPagingApi
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import app.tivi.data.daos.TrendingDao
import app.tivi.data.resultentities.TrendingEntryWithShow
import app.tivi.domain.PaginatedEntryRemoteMediator
import app.tivi.domain.PagingInteractor
import app.tivi.domain.interactors.UpdateTrendingShows
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
@OptIn(ExperimentalPagingApi::class)
class ObservePagedTrendingShows @Inject constructor(
private val trendingShowsDao: TrendingDao,
private val updateTrendingShows: UpdateTrendingShows
) : PagingInteractor<ObservePagedTrendingShows.Params, TrendingEntryWithShow>() {
override fun createObservable(
params: Params
): Flow<PagingData<TrendingEntryWithShow>> {
return Pager(
config = params.pagingConfig,
remoteMediator = PaginatedEntryRemoteMediator { page ->
updateTrendingShows.executeSync(
UpdateTrendingShows.Params(page = page, forceRefresh = true)
)
},
pagingSourceFactory = trendingShowsDao::entriesPagingSource
).flow
}
data class Params(
override val pagingConfig: PagingConfig
) : Parameters<TrendingEntryWithShow>
}
| domain/src/main/java/app/tivi/domain/observers/ObservePagedTrendingShows.kt | 3468607726 |
package com.jiangKlijna.web.websocket
import com.jiangKlijna.web.app.ContextWrapper
import com.jiangKlijna.web.bean.Message
import com.jiangKlijna.web.bean.User
import com.jiangKlijna.web.dao.MessageMapper
import com.jiangKlijna.web.service.UserService
import org.springframework.data.redis.connection.MessageListener
import org.springframework.data.redis.core.RedisTemplate
import org.springframework.stereotype.Component
import org.springframework.web.socket.CloseStatus
import org.springframework.web.socket.TextMessage
import org.springframework.web.socket.WebSocketSession
import org.springframework.web.socket.handler.TextWebSocketHandler
import java.io.ByteArrayInputStream
import java.io.ObjectInputStream
import java.util.concurrent.CopyOnWriteArrayList
import javax.annotation.Resource
/**
* Created by leil7 on 2017/6/6.
*/
@Component("ChatWebSocketHandler")
class ChatWebSocketHandler : TextWebSocketHandler() {
@Resource
val rt: RedisTemplate<String, Message>? = null
@Resource
val us: UserService? = null
@Resource
val mm: MessageMapper? = null
//接收文本消息
//只接受login信息,否则断开连接
override fun handleTextMessage(session: WebSocketSession, message: TextMessage) {
try {
val username = message.payload
if (username == null || username.isEmpty()) throw RuntimeException("null")
val re = us!!.get(username)
if (!re.isSucess()) throw RuntimeException("unknown username")
session.attributes["userid"] = (re.data as User).id
} catch (e: Exception) {
handleTransportError(session, e)
}
}
//0.连接建立后处理
override fun afterConnectionEstablished(session: WebSocketSession) {
sessions.add(session)
// session.sendMessage(TextMessage("Server:connected OK!"))
}
//1.连接关闭后处理
override fun afterConnectionClosed(session: WebSocketSession, closeStatus: CloseStatus?) {
sessions.remove(session)
}
//2.抛出异常时处理
override fun handleTransportError(session: WebSocketSession, exception: Throwable?) {
if (session.isOpen) session.close()
if (session in sessions) sessions.remove(session)
}
companion object {
private val sessions = CopyOnWriteArrayList<WebSocketSession>()
private fun <T : java.io.Serializable> ByteArray.toObject(): T =
ObjectInputStream(ByteArrayInputStream(this)).readObject() as T
private val updateMessage = TextMessage("update")
}
/**
* msg.body为com.jiangKlijna.web.bean.Message
* rt.convertAndSend(String, Message)
*/
class RedisMessageListener : MessageListener {
@Throws
override fun onMessage(msg: org.springframework.data.redis.connection.Message, p1: ByteArray?) {
val m = msg.body.toObject<Message>()
// 遍历所有session
for (session in sessions) {
if ("userid" !in session.attributes) continue
if (m.touser != session.attributes["userid"]) continue
session.sendMessage(updateMessage)
}
}
}
//@message 推送
fun publish(flag: Int, fromuser: Int, tousers: Collection<Int>, isSubThread: Boolean = true) {
if (tousers.isEmpty()) return
val core = fun() {
for (touser in tousers) {
val msg = Message(fromuser = fromuser, touser = touser, flag = flag)
mm!!.insert(msg)
rt!!.convertAndSend(Message::class.java.simpleName, msg)
}
}
if (isSubThread)
ContextWrapper.execute(Runnable { core() })
else core()
}
} | src/main/java/com/jiangKlijna/web/websocket/ChatWebSocketHandler.kt | 3747992498 |
package mil.nga.giat.mage.sdk
import android.content.Context
import androidx.preference.PreferenceManager
class Compatibility {
data class Server(val major: Int, val minor: Int)
companion object {
val servers = listOf(
Server(5, 4),
Server(6, 0)
)
fun isCompatibleWith(major: Int, minor: Int): Boolean {
for (server: Server in servers) {
if (server.major == major && server.minor <= minor) {
return true
}
}
return false;
}
fun isServerVersion5(applicationContext: Context): Boolean {
val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(applicationContext)
val majorVersion: Int = sharedPreferences.getInt(applicationContext.getString(R.string.serverVersionMajorKey), 0)
return majorVersion == 5
}
}
} | sdk/src/main/java/mil/nga/giat/mage/sdk/Compatibility.kt | 410374778 |
/*
* Copyright (C) 2017. Uber Technologies
*
* 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.uber.rib.core
import com.uber.rib.core.lifecycle.ActivityCallbackEvent
import com.uber.rib.core.lifecycle.ActivityLifecycleEvent
import io.reactivex.Observable
/** Interface for reactive activities. */
interface RxActivityEvents {
/** @return an observable of this activity's lifecycle events. */
fun lifecycle(): Observable<ActivityLifecycleEvent>
/** @return an observable of this activity's lifecycle events. */
fun callbacks(): Observable<ActivityCallbackEvent>
/**
* @param <T> The type of [ActivityLifecycleEvent] subclass you want.
* @param clazz The [ActivityLifecycleEvent] subclass you want.
* @return an observable of this activity's lifecycle events.
*/
@JvmDefault
fun <T : ActivityLifecycleEvent> lifecycle(clazz: Class<T>): Observable<T> {
return lifecycle()
.filter { activityEvent -> clazz.isAssignableFrom(activityEvent.javaClass) }
.cast(clazz)
}
/**
* @param <T> The type of [ActivityCallbackEvent] subclass you want.
* @param clazz The [ActivityCallbackEvent] subclass you want.
* @return an observable of this activity's callbacks events.
*/
@JvmDefault
fun <T : ActivityCallbackEvent> callbacks(clazz: Class<T>): Observable<T> {
return callbacks()
.filter { activityEvent -> clazz.isAssignableFrom(activityEvent.javaClass) }
.cast(clazz)
}
}
| android/libraries/rib-android/src/main/kotlin/com/uber/rib/core/RxActivityEvents.kt | 2295213763 |
/*
* Copyright (C) 2017. Uber Technologies
*
* 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.uber.rib.core
import org.junit.After
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoInteractions
class RibRefWatcherTest {
private val referenceWatcher: RibRefWatcher.ReferenceWatcher = mock()
private val ribRefWatcher = RibRefWatcher()
@After
fun tearDown() {
ribRefWatcher.disableLeakCanary()
ribRefWatcher.disableULeakLifecycleTracking()
}
@Test
fun watchDeletedObject_whenObjectIsNull_shouldDoNothing() {
ribRefWatcher.enableLeakCanary()
ribRefWatcher.setReferenceWatcher(referenceWatcher)
ribRefWatcher.watchDeletedObject(null)
verifyNoInteractions(referenceWatcher)
}
@Test
fun watchDeletedObject_whenReferenceWatcherIsNull_shouldDoNothing() {
ribRefWatcher.enableLeakCanary()
ribRefWatcher.watchDeletedObject(Any())
verifyNoInteractions(referenceWatcher)
}
@Test
fun watchDeletedObject_whenReferenceObjectIsNotNull_shouldTellReferenceWatcher() {
ribRefWatcher.enableLeakCanary()
val obj = Any()
ribRefWatcher.setReferenceWatcher(referenceWatcher)
ribRefWatcher.watchDeletedObject(obj)
verify(referenceWatcher).watch(obj)
}
@Test
fun watchDeletedObject_whenNonNullRefWithDisabledLeakCanary_shouldDoNothing() {
val obj = Any()
ribRefWatcher.setReferenceWatcher(referenceWatcher)
ribRefWatcher.watchDeletedObject(obj)
verify(referenceWatcher, never()).watch(obj)
}
@Test
fun watchDeletedObject_whenObjectIsNullWithULeak_shouldDoNothing() {
ribRefWatcher.enableULeakLifecycleTracking()
ribRefWatcher.setReferenceWatcher(referenceWatcher)
ribRefWatcher.watchDeletedObject(null)
verifyNoInteractions(referenceWatcher)
}
@Test
fun watchDeletedObject_whenReferenceWatcherIsNullULeakEnabled_shouldDoNothing() {
ribRefWatcher.enableULeakLifecycleTracking()
ribRefWatcher.watchDeletedObject(Any())
verifyNoInteractions(referenceWatcher)
}
@Test
fun watchDeletedObject_whenReferenceObjectIsNotNullULeak_shouldTellReferenceWatcher() {
ribRefWatcher.enableULeakLifecycleTracking()
val obj = Any()
ribRefWatcher.setReferenceWatcher(referenceWatcher)
ribRefWatcher.watchDeletedObject(obj)
verify(referenceWatcher).watch(obj)
}
@Test
fun watchDeletedObject_whenNonNullRefULeakDisabled_shouldDoNothing() {
val obj = Any()
ribRefWatcher.setReferenceWatcher(referenceWatcher)
ribRefWatcher.watchDeletedObject(obj)
verify(referenceWatcher, never()).watch(obj)
}
}
| android/libraries/rib-base/src/test/kotlin/com/uber/rib/core/RibRefWatcherTest.kt | 1134323723 |
package org.ooverkommelig.examples.ooverkommelig.cycles
fun main() {
val inputReader = System.`in`.bufferedReader()
CyclesOgd().Graph().use { graph ->
var currentStep: Step? = graph.mainMenu()
while (currentStep != null) {
currentStep.showInstructions()
currentStep = currentStep.handleInput(inputReader.readLine())
}
}
}
| examples/src/main/kotlin/org/ooverkommelig/examples/ooverkommelig/cycles/CyclesApp.kt | 1108688255 |
package com.goav.netty.Impl
import io.netty.channel.ChannelPipeline
import io.netty.channel.socket.SocketChannel
/**
* Copyright (c) 2017.
* [email protected]
*/
interface ChannelConnectImpl {
fun addChannelHandler(pipeline: ChannelPipeline): ChannelPipeline
fun onConnectCallBack(sc: SocketChannel?)
object DEFAULT : ChannelConnectImpl {
override fun onConnectCallBack(sc: SocketChannel?) {
// throw UnsupportedOperationException()
}
override fun addChannelHandler(pipeline: ChannelPipeline): ChannelPipeline = pipeline
}
}
| netty-android/src/main/java/com/goav/netty/Impl/ChannelConnectImpl.kt | 2077170371 |
package com.wisnia.videooo.authentication.presentation
import com.wisnia.videooo.authentication.view.LoginView
import com.wisnia.videooo.data.authentication.Token
import com.wisnia.videooo.mvp.BasePresenter
import com.wisnia.videooo.repository.authentication.LoginRepository
import com.wisnia.videooo.repository.authentication.TokenRepository
import io.reactivex.Scheduler
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
class LoginPresenter @Inject constructor(private val tokenRepository: TokenRepository,
private val loginRepository: LoginRepository,
private val mainThreadScheduler: Scheduler) : BasePresenter<LoginView>() {
fun signIn(username: String, password: String) {
loginRepository.signIn(username, password)
.subscribeOn(Schedulers.io())
.observeOn(mainThreadScheduler)
.subscribe({ onSignIn() }, { onError(it) })
}
fun signInAsGuest() {
loginRepository.signInAsGuest
.subscribeOn(Schedulers.io())
.observeOn(mainThreadScheduler)
.subscribe({ onSignIn() }, { onError(it) })
}
private fun onSignIn() {
view?.get()?.onSignedIn()
}
fun signInWebsite() {
tokenRepository.token
.subscribeOn(Schedulers.io())
.observeOn(mainThreadScheduler)
.subscribe({ onWebsiteTokenReceived(it) }, { onError(it) })
}
private fun onWebsiteTokenReceived(token: Token) {
view?.get()?.onWebsiteTokenReceived(token)
}
private fun onError(error: Throwable) {
view?.get()?.showError(error)
}
}
| core/src/main/kotlin/com/wisnia/videooo/authentication/presentation/LoginPresenter.kt | 856193392 |
/*
* Copyright (c) 2020 David Allison <[email protected]>
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation; either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.ichi2.anki.noteeditor
import android.content.Context
import android.os.Bundle
import android.util.SparseArray
import android.view.View
import com.ichi2.anki.FieldEditLine
import com.ichi2.anki.NoteEditor
import com.ichi2.anki.R
import com.ichi2.libanki.Model
import com.ichi2.libanki.Models
import com.ichi2.utils.KotlinCleanup
import com.ichi2.utils.MapUtil.getKeyByValue
import org.json.JSONObject
import java.util.*
/** Responsible for recreating EditFieldLines after NoteEditor operations
* This primarily exists so we can use saved instance state to repopulate the dynamically created FieldEditLine
*/
class FieldState private constructor(private val editor: NoteEditor) {
private var mSavedFieldData: List<View.BaseSavedState>? = null
fun loadFieldEditLines(type: FieldChangeType): List<FieldEditLine> {
val fieldEditLines: List<FieldEditLine>
if (type.type == Type.INIT && mSavedFieldData != null) {
fieldEditLines = recreateFieldsFromState()
mSavedFieldData = null
} else {
fieldEditLines = createFields(type)
}
for (l in fieldEditLines) {
l.id = View.generateViewId()
}
if (type.type == Type.CLEAR_KEEP_STICKY) {
// we use the UI values here as the model will post-processing steps (newline -> br).
val currentFieldStrings = editor.currentFieldStrings
val flds = editor.currentFields
for (fldIdx in 0 until flds.length()) {
if (flds.getJSONObject(fldIdx).getBoolean("sticky")) {
fieldEditLines[fldIdx].setContent(currentFieldStrings[fldIdx], type.replaceNewlines)
}
}
}
if (type.type == Type.CHANGE_FIELD_COUNT) {
val currentFieldStrings = editor.currentFieldStrings
for (i in 0 until Math.min(currentFieldStrings.size, fieldEditLines.size)) {
fieldEditLines[i].setContent(currentFieldStrings[i], type.replaceNewlines)
}
}
return fieldEditLines
}
private fun recreateFieldsFromState(): List<FieldEditLine> {
val editLines: MutableList<FieldEditLine> = ArrayList(mSavedFieldData!!.size)
for (state in mSavedFieldData!!) {
val edit_line_view = FieldEditLine(editor)
if (edit_line_view.id == 0) {
edit_line_view.id = View.generateViewId()
}
edit_line_view.loadState(state)
editLines.add(edit_line_view)
}
return editLines
}
protected fun createFields(type: FieldChangeType): List<FieldEditLine> {
val fields = getFields(type)
val editLines: MutableList<FieldEditLine> = ArrayList(fields.size)
for (i in fields.indices) {
val edit_line_view = FieldEditLine(editor)
editLines.add(edit_line_view)
edit_line_view.name = fields[i][0]
edit_line_view.setContent(fields[i][1], type.replaceNewlines)
edit_line_view.setOrd(i)
}
return editLines
}
private fun getFields(type: FieldChangeType): Array<Array<String>> {
if (type.type == Type.REFRESH_WITH_MAP) {
val items = editor.fieldsFromSelectedNote
val fMapNew = Models.fieldMap(type.newModel!!)
return fromFieldMap(editor, items, fMapNew, type.modelChangeFieldMap)
}
return editor.fieldsFromSelectedNote
}
@Suppress("deprecation") // get
fun setInstanceState(savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
return
}
if (!savedInstanceState.containsKey("customViewIds") || !savedInstanceState.containsKey("android:viewHierarchyState")) {
return
}
val customViewIds = savedInstanceState.getIntegerArrayList("customViewIds")
val viewHierarchyState = savedInstanceState.getBundle("android:viewHierarchyState")
if (customViewIds == null || viewHierarchyState == null) {
return
}
val views = viewHierarchyState["android:views"] as SparseArray<*>? ?: return
val important: MutableList<View.BaseSavedState> = ArrayList(customViewIds.size)
for (i in customViewIds) {
important.add(views[i!!] as View.BaseSavedState)
}
mSavedFieldData = important
}
/** How fields should be changed when the UI is rebuilt */
class FieldChangeType(val type: Type, val replaceNewlines: Boolean) {
var modelChangeFieldMap: Map<Int, Int>? = null
var newModel: Model? = null
companion object {
fun refreshWithMap(newModel: Model?, modelChangeFieldMap: Map<Int, Int>?, replaceNewlines: Boolean): FieldChangeType {
val typeClass = FieldChangeType(Type.REFRESH_WITH_MAP, replaceNewlines)
typeClass.newModel = newModel
typeClass.modelChangeFieldMap = modelChangeFieldMap
return typeClass
}
fun refresh(replaceNewlines: Boolean): FieldChangeType {
return fromType(Type.REFRESH, replaceNewlines)
}
fun refreshWithStickyFields(replaceNewlines: Boolean): FieldChangeType {
return fromType(Type.CLEAR_KEEP_STICKY, replaceNewlines)
}
fun changeFieldCount(replaceNewlines: Boolean): FieldChangeType {
return fromType(Type.CHANGE_FIELD_COUNT, replaceNewlines)
}
fun onActivityCreation(replaceNewlines: Boolean): FieldChangeType {
return fromType(Type.INIT, replaceNewlines)
}
private fun fromType(type: Type, replaceNewlines: Boolean): FieldChangeType {
return FieldChangeType(type, replaceNewlines)
}
}
}
enum class Type {
INIT, CLEAR_KEEP_STICKY, CHANGE_FIELD_COUNT, REFRESH, REFRESH_WITH_MAP
}
companion object {
private fun allowFieldRemapping(oldFields: Array<Array<String>>): Boolean {
return oldFields.size > 2
}
fun fromEditor(editor: NoteEditor): FieldState {
return FieldState(editor)
}
@KotlinCleanup("speed - no need for arrayOfNulls")
private fun fromFieldMap(context: Context, oldFields: Array<Array<String>>, fMapNew: Map<String, Pair<Int, JSONObject>>, modelChangeFieldMap: Map<Int, Int>?): Array<Array<String>> {
// Build array of label/values to provide to field EditText views
val fields = Array(fMapNew.size) { arrayOfNulls<String>(2) }
for (fname in fMapNew.keys) {
val fieldPair = fMapNew[fname] ?: continue
// Field index of new note type
val i = fieldPair.first
// Add values from old note type if they exist in map, otherwise make the new field empty
if (modelChangeFieldMap!!.containsValue(i)) {
// Get index of field from old note type given the field index of new note type
val j = getKeyByValue(modelChangeFieldMap, i) ?: continue
// Set the new field label text
if (allowFieldRemapping(oldFields)) {
// Show the content of old field if remapping is enabled
fields[i][0] = String.format(context.resources.getString(R.string.field_remapping), fname, oldFields[j][0])
} else {
fields[i][0] = fname
}
// Set the new field label value
fields[i][1] = oldFields[j][1]
} else {
// No values from old note type exist in the mapping
fields[i][0] = fname
fields[i][1] = ""
}
}
return fields.map { it.requireNoNulls() }.toTypedArray()
}
}
}
| AnkiDroid/src/main/java/com/ichi2/anki/noteeditor/FieldState.kt | 4257117137 |
package io.envoyproxy.envoymobile.helloenvoykotlin
import android.app.Activity
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import io.envoyproxy.envoymobile.AndroidEngineBuilder
import io.envoyproxy.envoymobile.Element
import io.envoyproxy.envoymobile.Engine
import io.envoyproxy.envoymobile.LogLevel
import io.envoyproxy.envoymobile.RequestHeadersBuilder
import io.envoyproxy.envoymobile.RequestMethod
import io.envoyproxy.envoymobile.UpstreamHttpProtocol
import io.envoyproxy.envoymobile.shared.Failure
import io.envoyproxy.envoymobile.shared.ResponseRecyclerViewAdapter
import io.envoyproxy.envoymobile.shared.Success
import java.io.IOException
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
private const val REQUEST_HANDLER_THREAD_NAME = "hello_envoy_kt"
private const val REQUEST_AUTHORITY = "api.lyft.com"
private const val REQUEST_PATH = "/ping"
private const val REQUEST_SCHEME = "https"
private val FILTERED_HEADERS = setOf(
"server",
"filter-demo",
"buffer-filter-demo",
"async-filter-demo",
"x-envoy-upstream-service-time"
)
/**
* The main activity of the app.
*/
class MainActivity : Activity() {
private val thread = HandlerThread(REQUEST_HANDLER_THREAD_NAME)
private lateinit var recyclerView: RecyclerView
private lateinit var viewAdapter: ResponseRecyclerViewAdapter
private lateinit var engine: Engine
@Suppress("MaxLineLength")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
engine = AndroidEngineBuilder(application)
.addLogLevel(LogLevel.DEBUG)
.enableProxying(true)
.addPlatformFilter(::DemoFilter)
.addPlatformFilter(::BufferDemoFilter)
.addPlatformFilter(::AsyncDemoFilter)
.addNativeFilter("envoy.filters.http.buffer", "{\"@type\":\"type.googleapis.com/envoy.extensions.filters.http.buffer.v3.Buffer\",\"max_request_bytes\":5242880}")
.addStringAccessor("demo-accessor", { "PlatformString" })
.setOnEngineRunning { Log.d("MainActivity", "Envoy async internal setup completed") }
.setEventTracker({
for (entry in it.entries) {
Log.d("MainActivity", "Event emitted: ${entry.key}, ${entry.value}")
}
})
.setLogger {
Log.d("MainActivity", it)
}
.build()
recyclerView = findViewById(R.id.recycler_view) as RecyclerView
recyclerView.layoutManager = LinearLayoutManager(this)
viewAdapter = ResponseRecyclerViewAdapter()
recyclerView.adapter = viewAdapter
val dividerItemDecoration = DividerItemDecoration(
recyclerView.context, DividerItemDecoration.VERTICAL
)
recyclerView.addItemDecoration(dividerItemDecoration)
thread.start()
val handler = Handler(thread.looper)
// Run a request loop and record stats until the application exits.
handler.postDelayed(
object : Runnable {
override fun run() {
try {
makeRequest()
recordStats()
} catch (e: IOException) {
Log.d("MainActivity", "exception making request or recording stats", e)
}
// Make a call and report stats again
handler.postDelayed(this, TimeUnit.SECONDS.toMillis(1))
}
},
TimeUnit.SECONDS.toMillis(1)
)
}
override fun onDestroy() {
super.onDestroy()
thread.quit()
}
private fun makeRequest() {
// Note: this request will use an h2 stream for the upstream request.
// The Java example uses http/1.1. This is done on purpose to test both paths in end-to-end
// tests in CI.
val requestHeaders = RequestHeadersBuilder(
RequestMethod.GET, REQUEST_SCHEME, REQUEST_AUTHORITY, REQUEST_PATH
)
.addUpstreamHttpProtocol(UpstreamHttpProtocol.HTTP2)
.build()
engine
.streamClient()
.newStreamPrototype()
.setOnResponseHeaders { responseHeaders, _, _ ->
val status = responseHeaders.httpStatus ?: 0L
val message = "received headers with status $status"
val sb = StringBuilder()
for ((name, value) in responseHeaders.caseSensitiveHeaders()) {
if (name in FILTERED_HEADERS) {
sb.append(name).append(": ").append(value.joinToString()).append("\n")
}
}
val headerText = sb.toString()
Log.d("MainActivity", message)
responseHeaders.value("filter-demo")?.first()?.let { filterDemoValue ->
Log.d("MainActivity", "filter-demo: $filterDemoValue")
}
if (status == 200) {
recyclerView.post { viewAdapter.add(Success(message, headerText)) }
} else {
recyclerView.post { viewAdapter.add(Failure(message)) }
}
}
.setOnError { error, _ ->
val attemptCount = error.attemptCount ?: -1
val message = "failed with error after $attemptCount attempts: ${error.message}"
Log.d("MainActivity", message)
recyclerView.post { viewAdapter.add(Failure(message)) }
}
.start(Executors.newSingleThreadExecutor())
.sendHeaders(requestHeaders, true)
}
private fun recordStats() {
val counter = engine.pulseClient().counter(Element("foo"), Element("bar"), Element("counter"))
val gauge = engine.pulseClient().gauge(Element("foo"), Element("bar"), Element("gauge"))
val timer = engine.pulseClient().timer(Element("foo"), Element("bar"), Element("timer"))
val distribution =
engine.pulseClient().distribution(Element("foo"), Element("bar"), Element("distribution"))
counter.increment()
counter.increment(5)
gauge.set(5)
gauge.add(10)
gauge.sub(1)
timer.recordDuration(15)
distribution.recordValue(15)
}
}
| mobile/examples/kotlin/hello_world/MainActivity.kt | 2870225051 |
/*
* 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.data.query
/**
* Can store part of a SQL selection statement, used to filter results in database queries.
*
* @see Filters
* @see Query
*/
data class Filter(var sqlStatement: String) {
init {
// Surround the SQL command in parenthesis to avoid mix ups when combined with other
// filters.
sqlStatement = "($sqlStatement)"
}
}
| app/src/main/java/co/timetableapp/data/query/Filter.kt | 1563600034 |
package de.westnordost.streetcomplete.quests.tactile_paving
import de.westnordost.streetcomplete.data.osm.mapdata.MapDataWithGeometry
import de.westnordost.streetcomplete.R
import de.westnordost.streetcomplete.data.elementfilter.toElementFilterExpression
import de.westnordost.streetcomplete.data.osm.osmquests.OsmElementQuestType
import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder
import de.westnordost.streetcomplete.data.meta.updateWithCheckDate
import de.westnordost.streetcomplete.data.osm.mapdata.Element
import de.westnordost.streetcomplete.data.osm.mapdata.Node
import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BLIND
import de.westnordost.streetcomplete.ktx.toYesNo
import de.westnordost.streetcomplete.quests.kerb_height.couldBeAKerb
import de.westnordost.streetcomplete.quests.kerb_height.findAllKerbNodes
class AddTactilePavingKerb : OsmElementQuestType<Boolean> {
private val eligibleKerbsFilter by lazy { """
nodes with
!tactile_paving
or tactile_paving = unknown
or tactile_paving = no and tactile_paving older today -4 years
or tactile_paving = yes and tactile_paving older today -8 years
""".toElementFilterExpression() }
override val commitMessage = "Add tactile paving on kerbs"
override val wikiLink = "Key:tactile_paving"
override val icon = R.drawable.ic_quest_kerb_tactile_paving
override val enabledInCountries = COUNTRIES_WHERE_TACTILE_PAVING_IS_COMMON
override val questTypeAchievements = listOf(BLIND)
override fun getTitle(tags: Map<String, String>) = R.string.quest_tactile_paving_kerb_title
override fun createForm() = TactilePavingForm()
override fun getApplicableElements(mapData: MapDataWithGeometry): Iterable<Element> =
mapData.findAllKerbNodes().filter { eligibleKerbsFilter.matches(it) }
override fun isApplicableTo(element: Element): Boolean? =
if (!eligibleKerbsFilter.matches(element) || element !is Node || !element.couldBeAKerb()) false
else null
override fun applyAnswerTo(answer: Boolean, changes: StringMapChangesBuilder) {
changes.updateWithCheckDate("tactile_paving", answer.toYesNo())
changes.addOrModify("barrier", "kerb")
}
}
| app/src/main/java/de/westnordost/streetcomplete/quests/tactile_paving/AddTactilePavingKerb.kt | 2403683767 |
package com.recurly.androidsdk.domain
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.core.content.ContextCompat
import com.recurly.androidsdk.R
import com.recurly.androidsdk.data.model.CreditCardsParameters
internal object RecurlyDataFormatter {
/**
* @param number credit card number
* @param validInput is recognized from a credit card pattern
* @return Returns the credit card number as Long if it is correct, return 0 if the Card Number is invalid or if it don´t belongs to a credit card type
*/
internal fun getCardNumber(number: String, validInput: Boolean): Long {
val cardNumber =
number.replace(" ", "")
return if (cardNumber.isNotEmpty() && validInput)
cardNumber.toLong()
else
0
}
/**
* @param expiration expiration date as string
* @param validInput if it is a valid expiration date
* @return Returns the month as an Int
*/
internal fun getExpirationMonth(expiration: String, validInput: Boolean): Int {
val expirationDate =
expiration.split("/")
return if (expirationDate.size == 2 && validInput) {
if (expirationDate[0].isNotEmpty())
expirationDate[0].toInt()
else
0
} else
0
}
/**
* @param expiration expiration date as string
* @param validInput if it is a valid expiration date
* @return Returns the year as an Int
*/
internal fun getExpirationYear(expiration: String, validInput: Boolean): Int {
val expirationDate =
expiration.split("/")
return if (expirationDate.size == 2 && validInput) {
if (expirationDate[1].isNotEmpty())
expirationDate[1].toInt()
else
0
} else
0
}
/**
* @param cvv cvv code
* @param validInput if it is a valid cvv code
* @return Returns the cvv code as an Int
*/
internal fun getCvvCode(cvv: String, validInput: Boolean): Int {
return if (cvv.isNotEmpty() && validInput)
cvv.toInt()
else
0
}
/**
* This fun get as a parameter the card type from CreditCardData to change the credit card icon
* @param context Context
* @param cardType the card type according to CreditCardsParameters
* @return Returns the icon of the credit card
*/
internal fun changeCardIcon(context: Context, cardType: String): Drawable {
when (cardType) {
CreditCardsParameters.HIPERCARD.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_hipercard_card)!!
CreditCardsParameters.AMERICAN_EXPRESS.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_amex_card)!!
CreditCardsParameters.DINERS_CLUB.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_diners_club_card)!!
CreditCardsParameters.DISCOVER.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_discover_card)!!
CreditCardsParameters.ELO.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_elo_card)!!
CreditCardsParameters.JCB.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_jcb_card)!!
CreditCardsParameters.MASTER.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_mastercard_card)!!
CreditCardsParameters.TARJETA_NARANJA.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_tarjeta_naranja_card)!!
CreditCardsParameters.UNION_PAY.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_union_pay_card)!!
CreditCardsParameters.VISA.cardType ->
return ContextCompat.getDrawable(context, R.drawable.ic_visa_card)!!
else ->
return ContextCompat.getDrawable(context, R.drawable.ic_generic_valid_card)!!
}
}
} | AndroidSdk/src/main/java/com/recurly/androidsdk/domain/RecurlyDataFormatter.kt | 2130797943 |
package com.fracturedskies.render.common.shaders.standard
import com.fracturedskies.render.common.shaders.ShaderProgram
class StandardShaderProgram: ShaderProgram(this::class.java.getResource("standard.vert").readText(), this::class.java.getResource("standard.frag").readText()) {
companion object {
const val MODEL_LOCATION = 0
const val VIEW_LOCATION = 1
const val PROJECTION_LOCATION = 2
const val ALBEDO_LOCATION = 3
}
}
| src/main/kotlin/com/fracturedskies/render/common/shaders/standard/StandardShaderProgram.kt | 2812428786 |
package jeb
import java.io.IOException
class JebExecException(
val cmd: String,
val stdout: String,
val stderr: String,
val returnCode: Int,
cause: Throwable? = null) : IOException("Could not execute $cmd", cause) {
override fun toString(): String {
return """
|Jeb error
|Command: $cmd
|Return code: $returnCode
|Standard Out:
|$stdout
| ====
|Standard Error:
|$stderr
| ====
""".trimMargin()
}
}
| src/main/kotlin/jeb/JebExecException.kt | 2262279523 |
package dev.pellet.integration
import dev.pellet.logging.pelletLogger
import dev.pellet.server.PelletBuilder.pelletServer
import dev.pellet.server.PelletConnector
import dev.pellet.server.routing.http.HTTPRouteResponse
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.delay
import kotlinx.coroutines.future.await
import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.yield
import okhttp3.Call
import okhttp3.Callback
import okhttp3.ConnectionPool
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.time.Duration
import java.time.Instant
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicInteger
import kotlin.test.Test
class NoContentBenchmarkTest {
private val logger = pelletLogger<NoContentBenchmarkTest>()
private val numberOfRequests = System.getProperty("benchmark.requests.total")?.toIntOrNull() ?: 1_000_000
@Test
fun `benchmark no content response`() = runBlocking {
val counter = AtomicInteger(numberOfRequests)
val pellet = pelletServer {
logRequests = false
httpConnector {
endpoint = PelletConnector.Endpoint(
"127.0.0.1",
9001
)
router {
get("/") {
counter.decrementAndGet()
HTTPRouteResponse.Builder()
.noContent()
.build()
}
}
}
}
val job = pellet.start()
val client = OkHttpClient().newBuilder()
.connectionPool(ConnectionPool(30, 1L, TimeUnit.MINUTES))
.build()
client.dispatcher.maxRequestsPerHost = 30
client.connectionPool.connectionCount()
logger.info { "sending ${counter.get()} requests..." }
val dispatcher = Dispatchers.Default
val channel = Channel<Request>()
val supervisor = SupervisorJob()
val scope = CoroutineScope(dispatcher + supervisor)
scope.launch {
numberOfRequests.downTo(0).map {
val request = Request.Builder()
.url("http://127.0.0.1:9001")
.get()
.build()
channel.send(request)
}
}
val processorCount = Runtime.getRuntime().availableProcessors()
val startTime = Instant.now()
processorCount.downTo(0).map {
scope.async {
sendRequests(client, channel)
}
}
scope.async {
while (this.isActive) {
val count = counter.get()
if (count <= 0) {
supervisor.cancel()
return@async
}
logger.info { "left to complete: $count" }
delay(1000L)
}
}.join()
job.cancel()
val endTime = Instant.now()
val timeElapsedMs = Duration.between(startTime, endTime).toMillis()
val rps = (numberOfRequests / timeElapsedMs.toDouble()) * 1000L
logger.info { "completed rps: $rps" }
}
private suspend fun CoroutineScope.sendRequests(
client: OkHttpClient,
channel: Channel<Request>
) {
while (this.isActive) {
val request = channel.receive()
val future = CompletableFuture<Response>()
client.newCall(request).enqueue(toCallback(future))
val response = future.await()
assert(response.code == 204)
yield()
}
}
private fun toCallback(future: CompletableFuture<Response>): Callback {
return object : Callback {
override fun onFailure(call: Call, e: IOException) {
future.completeExceptionally(e)
}
override fun onResponse(call: Call, response: Response) {
future.complete(response)
}
}
}
}
| server/src/integrationTest/kotlin/dev/pellet/integration/NoContentBenchmarkTest.kt | 2942514120 |
/*
* Copyright 2017-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.serialization.json.internal
import kotlinx.serialization.*
import kotlinx.serialization.descriptors.*
import kotlinx.serialization.encoding.*
import kotlinx.serialization.encoding.CompositeDecoder.Companion.DECODE_DONE
import kotlinx.serialization.encoding.CompositeDecoder.Companion.UNKNOWN_NAME
import kotlinx.serialization.internal.*
import kotlinx.serialization.json.*
import kotlinx.serialization.modules.*
import kotlin.jvm.*
/**
* [JsonDecoder] which reads given JSON from [AbstractJsonLexer] field by field.
*/
@OptIn(ExperimentalSerializationApi::class)
internal open class StreamingJsonDecoder(
final override val json: Json,
private val mode: WriteMode,
@JvmField internal val lexer: AbstractJsonLexer,
descriptor: SerialDescriptor,
discriminatorHolder: DiscriminatorHolder?
) : JsonDecoder, AbstractDecoder() {
// A mutable reference to the discriminator that have to be skipped when in optimistic phase
// of polymorphic serialization, see `decodeSerializableValue`
internal class DiscriminatorHolder(@JvmField var discriminatorToSkip: String?)
private fun DiscriminatorHolder?.trySkip(unknownKey: String): Boolean {
if (this == null) return false
if (discriminatorToSkip == unknownKey) {
discriminatorToSkip = null
return true
}
return false
}
override val serializersModule: SerializersModule = json.serializersModule
private var currentIndex = -1
private var discriminatorHolder: DiscriminatorHolder? = discriminatorHolder
private val configuration = json.configuration
private val elementMarker: JsonElementMarker? = if (configuration.explicitNulls) null else JsonElementMarker(descriptor)
override fun decodeJsonElement(): JsonElement = JsonTreeReader(json.configuration, lexer).read()
@Suppress("INVISIBLE_MEMBER", "INVISIBLE_REFERENCE")
override fun <T> decodeSerializableValue(deserializer: DeserializationStrategy<T>): T {
try {
/*
* This is an optimized path over decodeSerializableValuePolymorphic(deserializer):
* dSVP reads the very next JSON tree into a memory as JsonElement and then runs TreeJsonDecoder over it
* in order to deal with an arbitrary order of keys, but with the price of additional memory pressure
* and CPU consumption.
* We would like to provide the best possible performance for data produced by kotlinx.serialization
* itself, for that we do the following optimistic optimization:
*
* 0) Remember current position in the string
* 1) Read the very next key of JSON structure
* 2) If it matches* the discriminator key, read the value, remember current position
* 3) Return the value, recover an initial position
* (*) -- if it doesn't match, fallback to dSVP method.
*/
if (deserializer !is AbstractPolymorphicSerializer<*> || json.configuration.useArrayPolymorphism) {
return deserializer.deserialize(this)
}
val discriminator = deserializer.descriptor.classDiscriminator(json)
val type = lexer.consumeLeadingMatchingValue(discriminator, configuration.isLenient)
var actualSerializer: DeserializationStrategy<out Any>? = null
if (type != null) {
actualSerializer = deserializer.findPolymorphicSerializerOrNull(this, type)
}
if (actualSerializer == null) {
// Fallback if we haven't found discriminator or serializer
return decodeSerializableValuePolymorphic<T>(deserializer as DeserializationStrategy<T>)
}
discriminatorHolder = DiscriminatorHolder(discriminator)
@Suppress("UNCHECKED_CAST")
val result = actualSerializer.deserialize(this) as T
return result
} catch (e: MissingFieldException) {
throw MissingFieldException(e.missingFields, e.message + " at path: " + lexer.path.getPath(), e)
}
}
override fun beginStructure(descriptor: SerialDescriptor): CompositeDecoder {
val newMode = json.switchMode(descriptor)
lexer.path.pushDescriptor(descriptor)
lexer.consumeNextToken(newMode.begin)
checkLeadingComma()
return when (newMode) {
// In fact resets current index that these modes rely on
WriteMode.LIST, WriteMode.MAP, WriteMode.POLY_OBJ -> StreamingJsonDecoder(
json,
newMode,
lexer,
descriptor,
discriminatorHolder
)
else -> if (mode == newMode && json.configuration.explicitNulls) {
this
} else {
StreamingJsonDecoder(json, newMode, lexer, descriptor, discriminatorHolder)
}
}
}
override fun endStructure(descriptor: SerialDescriptor) {
// If we're ignoring unknown keys, we have to skip all un-decoded elements,
// e.g. for object serialization. It can be the case when the descriptor does
// not have any elements and decodeElementIndex is not invoked at all
if (json.configuration.ignoreUnknownKeys && descriptor.elementsCount == 0) {
skipLeftoverElements(descriptor)
}
// First consume the object so we know it's correct
lexer.consumeNextToken(mode.end)
// Then cleanup the path
lexer.path.popDescriptor()
}
private fun skipLeftoverElements(descriptor: SerialDescriptor) {
while (decodeElementIndex(descriptor) != DECODE_DONE) {
// Skip elements
}
}
override fun decodeNotNullMark(): Boolean {
return !(elementMarker?.isUnmarkedNull ?: false) && lexer.tryConsumeNotNull()
}
override fun decodeNull(): Nothing? {
// Do nothing, null was consumed by `decodeNotNullMark`
return null
}
private fun checkLeadingComma() {
if (lexer.peekNextToken() == TC_COMMA) {
lexer.fail("Unexpected leading comma")
}
}
override fun <T> decodeSerializableElement(
descriptor: SerialDescriptor,
index: Int,
deserializer: DeserializationStrategy<T>,
previousValue: T?
): T {
val isMapKey = mode == WriteMode.MAP && index and 1 == 0
// Reset previous key
if (isMapKey) {
lexer.path.resetCurrentMapKey()
}
// Deserialize the key
val value = super.decodeSerializableElement(descriptor, index, deserializer, previousValue)
// Put the key to the path
if (isMapKey) {
lexer.path.updateCurrentMapKey(value)
}
return value
}
override fun decodeElementIndex(descriptor: SerialDescriptor): Int {
val index = when (mode) {
WriteMode.OBJ -> decodeObjectIndex(descriptor)
WriteMode.MAP -> decodeMapIndex()
else -> decodeListIndex() // Both for LIST and default polymorphic
}
// The element of the next index that will be decoded
if (mode != WriteMode.MAP) {
lexer.path.updateDescriptorIndex(index)
}
return index
}
private fun decodeMapIndex(): Int {
var hasComma = false
val decodingKey = currentIndex % 2 != 0
if (decodingKey) {
if (currentIndex != -1) {
hasComma = lexer.tryConsumeComma()
}
} else {
lexer.consumeNextToken(COLON)
}
return if (lexer.canConsumeValue()) {
if (decodingKey) {
if (currentIndex == -1) lexer.require(!hasComma) { "Unexpected trailing comma" }
else lexer.require(hasComma) { "Expected comma after the key-value pair" }
}
++currentIndex
} else {
if (hasComma) lexer.fail("Expected '}', but had ',' instead")
CompositeDecoder.DECODE_DONE
}
}
/*
* Checks whether JSON has `null` value for non-null property or unknown enum value for enum property
*/
private fun coerceInputValue(descriptor: SerialDescriptor, index: Int): Boolean = json.tryCoerceValue(
descriptor.getElementDescriptor(index),
{ !lexer.tryConsumeNotNull() },
{ lexer.peekString(configuration.isLenient) },
{ lexer.consumeString() /* skip unknown enum string*/ }
)
private fun decodeObjectIndex(descriptor: SerialDescriptor): Int {
// hasComma checks are required to properly react on trailing commas
var hasComma = lexer.tryConsumeComma()
while (lexer.canConsumeValue()) { // TODO: consider merging comma consumption and this check
hasComma = false
val key = decodeStringKey()
lexer.consumeNextToken(COLON)
val index = descriptor.getJsonNameIndex(json, key)
val isUnknown = if (index != UNKNOWN_NAME) {
if (configuration.coerceInputValues && coerceInputValue(descriptor, index)) {
hasComma = lexer.tryConsumeComma()
false // Known element, but coerced
} else {
elementMarker?.mark(index)
return index // Known element without coercing, return it
}
} else {
true // unknown element
}
if (isUnknown) { // slow-path for unknown keys handling
hasComma = handleUnknown(key)
}
}
if (hasComma) lexer.fail("Unexpected trailing comma")
return elementMarker?.nextUnmarkedIndex() ?: CompositeDecoder.DECODE_DONE
}
private fun handleUnknown(key: String): Boolean {
if (configuration.ignoreUnknownKeys || discriminatorHolder.trySkip(key)) {
lexer.skipElement(configuration.isLenient)
} else {
// Here we cannot properly update json path indices
// as we do not have a proper SerialDescriptor in our hands
lexer.failOnUnknownKey(key)
}
return lexer.tryConsumeComma()
}
private fun decodeListIndex(): Int {
// Prohibit leading comma
val hasComma = lexer.tryConsumeComma()
return if (lexer.canConsumeValue()) {
if (currentIndex != -1 && !hasComma) lexer.fail("Expected end of the array or comma")
++currentIndex
} else {
if (hasComma) lexer.fail("Unexpected trailing comma")
CompositeDecoder.DECODE_DONE
}
}
override fun decodeBoolean(): Boolean {
/*
* We prohibit any boolean literal that is not strictly 'true' or 'false' as it is considered way too
* error-prone, but allow quoted literal in relaxed mode for booleans.
*/
return if (configuration.isLenient) {
lexer.consumeBooleanLenient()
} else {
lexer.consumeBoolean()
}
}
/*
* The rest of the primitives are allowed to be quoted and unquoted
* to simplify integrations with third-party API.
*/
override fun decodeByte(): Byte {
val value = lexer.consumeNumericLiteral()
// Check for overflow
if (value != value.toByte().toLong()) lexer.fail("Failed to parse byte for input '$value'")
return value.toByte()
}
override fun decodeShort(): Short {
val value = lexer.consumeNumericLiteral()
// Check for overflow
if (value != value.toShort().toLong()) lexer.fail("Failed to parse short for input '$value'")
return value.toShort()
}
override fun decodeInt(): Int {
val value = lexer.consumeNumericLiteral()
// Check for overflow
if (value != value.toInt().toLong()) lexer.fail("Failed to parse int for input '$value'")
return value.toInt()
}
override fun decodeLong(): Long {
return lexer.consumeNumericLiteral()
}
override fun decodeFloat(): Float {
val result = lexer.parseString("float") { toFloat() }
val specialFp = json.configuration.allowSpecialFloatingPointValues
if (specialFp || result.isFinite()) return result
lexer.throwInvalidFloatingPointDecoded(result)
}
override fun decodeDouble(): Double {
val result = lexer.parseString("double") { toDouble() }
val specialFp = json.configuration.allowSpecialFloatingPointValues
if (specialFp || result.isFinite()) return result
lexer.throwInvalidFloatingPointDecoded(result)
}
override fun decodeChar(): Char {
val string = lexer.consumeStringLenient()
if (string.length != 1) lexer.fail("Expected single char, but got '$string'")
return string[0]
}
private fun decodeStringKey(): String {
return if (configuration.isLenient) {
lexer.consumeStringLenientNotNull()
} else {
lexer.consumeKeyString()
}
}
override fun decodeString(): String {
return if (configuration.isLenient) {
lexer.consumeStringLenientNotNull()
} else {
lexer.consumeString()
}
}
override fun decodeInline(descriptor: SerialDescriptor): Decoder =
if (descriptor.isUnsignedNumber) JsonDecoderForUnsignedTypes(lexer, json)
else super.decodeInline(descriptor)
override fun decodeEnum(enumDescriptor: SerialDescriptor): Int {
return enumDescriptor.getJsonNameIndexOrThrow(json, decodeString(), " at path " + lexer.path.getPath())
}
}
@InternalSerializationApi
public fun <T> Json.decodeStringToJsonTree(
deserializer: DeserializationStrategy<T>,
source: String
): JsonElement {
val lexer = StringJsonLexer(source)
val input = StreamingJsonDecoder(this, WriteMode.OBJ, lexer, deserializer.descriptor, null)
val tree = input.decodeJsonElement()
lexer.expectEof()
return tree
}
@OptIn(ExperimentalSerializationApi::class)
internal class JsonDecoderForUnsignedTypes(
private val lexer: AbstractJsonLexer,
json: Json
) : AbstractDecoder() {
override val serializersModule: SerializersModule = json.serializersModule
override fun decodeElementIndex(descriptor: SerialDescriptor): Int = error("unsupported")
override fun decodeInt(): Int = lexer.parseString("UInt") { toUInt().toInt() }
override fun decodeLong(): Long = lexer.parseString("ULong") { toULong().toLong() }
override fun decodeByte(): Byte = lexer.parseString("UByte") { toUByte().toByte() }
override fun decodeShort(): Short = lexer.parseString("UShort") { toUShort().toShort() }
}
private inline fun <T> AbstractJsonLexer.parseString(expectedType: String, block: String.() -> T): T {
val input = consumeStringLenient()
try {
return input.block()
} catch (e: IllegalArgumentException) {
fail("Failed to parse type '$expectedType' for input '$input'")
}
}
| formats/json/commonMain/src/kotlinx/serialization/json/internal/StreamingJsonDecoder.kt | 2180538245 |
import com.intellij.codeInsight.*
import com.intellij.find.*
import com.intellij.find.impl.*
import com.intellij.testFramework.fixtures.*
import org.hamcrest.core.IsNull.*
import org.junit.Assert.*
class MakefileFindUsagesTest : BasePlatformTestCase() {
fun testSimple() {
val usages = myFixture.testFindUsages("$basePath/${getTestName(true)}.mk")
assertEquals(2, usages.size)
}
fun testPhony() = notSearchableForUsages()
fun testForce() = notSearchableForUsages()
fun notSearchableForUsages() {
myFixture.configureByFiles("$basePath/${getTestName(true)}.mk")
val targetElement = TargetElementUtil.findTargetElement(myFixture.editor, TargetElementUtil.ELEMENT_NAME_ACCEPTED or TargetElementUtil.REFERENCED_ELEMENT_ACCEPTED)
val handler = (FindManager.getInstance(project) as FindManagerImpl).findUsagesManager.getFindUsagesHandler(targetElement!!, false)
assertThat(handler, nullValue())
}
override fun getTestDataPath() = "testData"
override fun getBasePath() = "findUsages"
} | src/test/kotlin/MakefileFindUsagesTest.kt | 4258858309 |
package runtimemodels.chazm.api.entity
import runtimemodels.chazm.api.id.Identifiable
import runtimemodels.chazm.api.organization.Organization
/**
* The [Attribute] interface defines an attribute entity of an [Organization].
*
* @author Christopher Zhong
* @since 5.0
*/
interface Attribute : Identifiable<Attribute, AttributeId> {
/**
* The [Type] enumerates the various types of an [Attribute].
*
* @author Christopher Zhong
* @since 5.0
*/
enum class Type {
/**
* Indicates a quantity-type [Attribute] (whose range is from `0.0` to `+infinity`), and
* that higher values are better.
*/
POSITIVE_QUANTITY,
/**
* Indicates a quantity-type [Attribute] (whose range is from `0.0` to `+infinity`), and
* that lower values are better.
*/
NEGATIVE_QUANTITY,
/**
* Indicates a quantity-type [Attribute] (whose range is from `0.0` to `1.0`), and
* that higher values are better.
*/
POSITIVE_QUALITY,
/**
* Indicates a quantity-type [Attribute] (whose range is from `0.0` to `1.0`), and that
* lower values are better.
*/
NEGATIVE_QUALITY,
/**
* Indicates an unbounded-type [Attribute] (whose range is from `-infinity` to `+infinity`), and
* that higher values are better.
*/
POSITIVE_UNBOUNDED,
/**
* Indicates an unbounded-type [Attribute] (whose range is from `-infinity` to `+infinity`), and
* that lower values are better.
*/
NEGATIVE_UNBOUNDED
}
/**
* The [Type] of this [Attribute].
*/
val type: Type
}
| chazm-api/src/main/kotlin/runtimemodels/chazm/api/entity/Attribute.kt | 996985779 |
/*
* Copyright 2019 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.google.api.kotlin.generator
import com.google.api.kotlin.BaseClientGeneratorTest
import com.google.api.kotlin.ClientPluginOptions
import com.google.api.kotlin.GeneratedArtifact
import com.google.api.kotlin.asNormalizedString
import com.google.api.kotlin.config.FlattenedMethod
import com.google.api.kotlin.config.LongRunningResponse
import com.google.api.kotlin.config.MethodOptions
import com.google.api.kotlin.config.PagedResponse
import com.google.api.kotlin.config.ServiceOptions
import com.google.api.kotlin.config.asPropertyPath
import com.google.api.kotlin.props
import com.google.api.kotlin.sources
import com.google.api.kotlin.types.GrpcTypes
import com.google.common.truth.Truth.assertThat
import com.squareup.kotlinpoet.ClassName
import kotlin.test.Test
/**
* Tests for the [GRPCGenerator] using the primary test proto
* `proto/google/example/test.proto` in the test resources directory.
*/
internal class GRPCGeneratorTest : BaseClientGeneratorTest("test", "TestServiceClient") {
@Test
fun `Generates with class documentation`() {
val opts = ServiceOptions(methods = listOf())
assertThat(generate(opts).testServiceClient().kdoc.toString()).isNotEmpty()
}
@Test
fun `Generates with prepare`() {
val opts = ServiceOptions(methods = listOf())
val methods = generate(opts).testServiceClient().funSpecs
val method = methods.first { it.name == "prepare" }
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
|* Prepare for an API call by setting any desired options. For example:
|*
|* ```
|* val client = TestServiceClient.create()
|* val response = client.prepare {
|* withMetadata("my-custom-header", listOf("some", "thing"))
|* }.test(request)
|* ```
|*
|* You may save the client returned by this call and reuse it if you
|* plan to make multiple requests with the same settings.
|*/
|fun prepare(
| init: com.google.api.kgax.grpc.ClientCallOptions.Builder.() -> kotlin.Unit
|): google.example.TestServiceClient {
| val optionsBuilder = com.google.api.kgax.grpc.ClientCallOptions.Builder(options)
| optionsBuilder.init()
| return google.example.TestServiceClient(channel, optionsBuilder.build())
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates with required static imports`() {
val opts = ServiceOptions(methods = listOf())
val imports = generate(opts).sources().first().imports
assertThat(imports).containsExactly(
ClassName(GrpcTypes.Support.SUPPORT_LIB_GRPC_PACKAGE, "pager"),
ClassName(GrpcTypes.Support.SUPPORT_LIB_GRPC_PACKAGE, "prepare"),
ClassName("kotlinx.coroutines", "coroutineScope"),
ClassName("kotlinx.coroutines", "async")
)
}
@Test
fun `Generates the test method`() {
val opts = ServiceOptions(methods = listOf(MethodOptions(name = "Test")))
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "test" }
assertThat(methods).hasSize(1)
assertThat(methods.first().toString().asNormalizedString()).isEqualTo(
"""
|/**
|* This is the test method
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.test(
|* testRequest {
|* }
|* )
|* ```
|*
|* @param request the request object for the API call
|*/
|suspend fun test(
| request: google.example.TestRequest
|): google.example.TestResponse = stubs.api.execute(context = "test") {
| it.test(request)
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates the LRO method`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "OperationTest",
longRunningResponse = LongRunningResponse(
responseType = ".google.example.SomeResponse",
metadataType = ".google.example.SomeMetadata"
)
)
)
)
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "operationTest" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.operationTest(
|* testRequest {
|* }
|* )
|* ```
|*
|* @param request the request object for the API call
|*/
|suspend fun operationTest(
| request: google.example.TestRequest
|): com.google.api.kgax.grpc.LongRunningCall<google.example.SomeResponse> = coroutineScope {
| com.google.api.kgax.grpc.LongRunningCall<google.example.SomeResponse>(
| stubs.operation,
| async { stubs.api.execute(context = "operationTest") { it.operationTest(request) } },
| google.example.SomeResponse::class.java
| )
|}
""".asNormalizedString()
)
}
@Test
fun `Generates the streamTest method`() {
val opts = ServiceOptions(methods = listOf(MethodOptions(name = "StreamTest")))
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "streamTest" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = TestServiceClient.create()
| * val result = client.streamTest(
| * testRequest {
| * }
| * )
| * ```
| */
|fun streamTest(): com.google.api.kgax.grpc.StreamingCall<google.example.TestRequest, google.example.TestResponse> =
| stubs.api.executeStreaming(context = "streamTest") { it::streamTest }
""".asNormalizedString()
)
}
@Test
fun `Generates the streamTest method with flattening`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "StreamTest",
flattenedMethods = listOf(
FlattenedMethod(props("query")),
FlattenedMethod(props("query", "main_detail"))
),
keepOriginalMethod = false
)
)
)
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "streamTest" }
assertThat(methods).hasSize(2)
val oneParamMethod = methods.first { it.parameters.size == 1 }
assertThat(oneParamMethod.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.streamTest(
|* query
|* )
|* ```
|*
|* @param query the query
|*/
|fun streamTest(
| query: kotlin.String
|): com.google.api.kgax.grpc.StreamingCall<google.example.TestRequest, google.example.TestResponse> =
| stubs.api.prepare {
| withInitialRequest(
| google.example.testRequest {
| this.query = query
| }
| )
| }.executeStreaming(context = "streamTest") { it::streamTest }
|""".asNormalizedString()
)
val twoParamMethod = methods.first { it.parameters.size == 2 }
assertThat(twoParamMethod.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.streamTest(
|* query,
|* detail {
|* this.mainDetail = mainDetail
|* }
|* )
|* ```
|*
|* @param query the query
|*
|* @param mainDetail
|*/
|fun streamTest(
| query: kotlin.String,
| mainDetail: google.example.Detail
|): com.google.api.kgax.grpc.StreamingCall<google.example.TestRequest, google.example.TestResponse> =
| stubs.api.prepare {
| withInitialRequest(
| google.example.testRequest {
| this.query = query
| this.mainDetail = mainDetail
| }
| )
}.executeStreaming(context = "streamTest") { it::streamTest }
|""".asNormalizedString()
)
}
@Test
fun `Generates the streamClientTest method`() {
val opts = ServiceOptions(methods = listOf(MethodOptions(name = "StreamClientTest")))
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "streamClientTest" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.streamClientTest(
|* testRequest {
|* }
|* )
|* ```
|*/
|fun streamClientTest(): com.google.api.kgax.grpc.ClientStreamingCall<google.example.TestRequest, google.example.TestResponse> =
| stubs.api.executeClientStreaming(context = "streamClientTest") {
| it::streamClientTest
| }
|""".asNormalizedString()
)
}
@Test
fun `Generates the streamClientTest method with flattening`() {
val opts = ServiceOptions(methods = listOf(MethodOptions(name = "StreamClientTest")))
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "streamClientTest" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.streamClientTest(
|* testRequest {
|* }
|* )
|* ```
|*/
|fun streamClientTest(): com.google.api.kgax.grpc.ClientStreamingCall<google.example.TestRequest, google.example.TestResponse> =
| stubs.api.executeClientStreaming(context = "streamClientTest") {
| it::streamClientTest
| }
|""".asNormalizedString()
)
}
@Test
fun `Generates the streamServerTest method`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "StreamServerTest",
flattenedMethods = listOf(
FlattenedMethod(props("main_detail.even_more"))
),
keepOriginalMethod = false
)
)
)
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "streamServerTest" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.streamServerTest(
|* moreDetail {
|* this.evenMore = evenMore
|* }
|*)
|* ```
|*/
|fun streamServerTest(
| evenMore: google.example.MoreDetail
|): com.google.api.kgax.grpc.ServerStreamingCall<google.example.TestResponse> =
| stubs.api.executeServerStreaming(context = "streamServerTest") { stub, observer ->
| stub.streamServerTest(
| google.example.testRequest {
| this.mainDetail = google.example.detail {
| this.evenMore = evenMore
| }
| },
| observer
| )
| }
|""".asNormalizedString()
)
}
@Test
fun `Generates the streamServerTest method with flattening`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "StreamServerTest",
flattenedMethods = listOf(
FlattenedMethod(props("main_detail.even_more"))
),
keepOriginalMethod = false
)
)
)
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "streamServerTest" }
assertThat(methods).hasSize(1)
assertThat(methods.first().toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.streamServerTest(
|* moreDetail {
|* this.evenMore = evenMore
|* }
|* )
|* ```
|*/
|fun streamServerTest(
| evenMore: google.example.MoreDetail
|): com.google.api.kgax.grpc.ServerStreamingCall<google.example.TestResponse> = stubs.api.executeServerStreaming(context = "streamServerTest") { stub, observer ->
| stub.streamServerTest(google.example.testRequest {
| this.mainDetail = google.example.detail {
| this.evenMore = evenMore
| }
| },
| observer)
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates the testFlat methods`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "TestFlat",
flattenedMethods = listOf(
FlattenedMethod(props("query")),
FlattenedMethod(props("query", "main_detail"))
),
keepOriginalMethod = true
)
)
)
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "testFlat" }
assertThat(methods).hasSize(3)
val original =
methods.first { it.parameters.size == 1 && it.parameters[0].name == "request" }
assertThat(original.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.testFlat(
|* testRequest {
|* }
|* )
|* ```
|*
|* @param request the request object for the API call
|*/
|suspend fun testFlat(
| request: google.example.TestRequest
|): google.example.TestResponse = stubs.api.execute(context = "testFlat") {
| it.testFlat(request)
|}
|""".asNormalizedString()
)
val oneArg = methods.first { it.parameters.size == 1 && it.parameters[0].name != "request" }
assertThat(oneArg.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.testFlat(
|* query
|* )
|* ```
|*
|* @param query the query
|*/
|suspend fun testFlat(
| query: kotlin.String
|): google.example.TestResponse = stubs.api.execute(context = "testFlat") {
| it.testFlat(google.example.testRequest {
| this.query = query
| })
|}
|""".asNormalizedString()
)
val twoArg = methods.first { it.parameters.size == 2 }
assertThat(twoArg.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.testFlat(
|* query,
|* detail {
|* this.mainDetail = mainDetail
|* }
|* )
|* ```
|*
|* @param query the query
|*
|* @param mainDetail
|*/
|suspend fun testFlat(
| query: kotlin.String,
| mainDetail: google.example.Detail
|): google.example.TestResponse = stubs.api.execute(context = "testFlat") {
| it.testFlat(google.example.testRequest {
| this.query = query
| this.mainDetail = mainDetail
| })
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates the TestFlatWithoutOriginal methods`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "TestFlatWithoutOriginal",
flattenedMethods = listOf(
FlattenedMethod(props("main_detail"))
),
keepOriginalMethod = false
)
)
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == "testFlatWithoutOriginal" }
assertThat(methods).hasSize(1)
val oneArg = methods.first { it.parameters.size == 1 }
assertThat(oneArg.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.testFlatWithoutOriginal(
|* detail {
|* this.mainDetail = mainDetail
|* }
|* )
|* ```
|*
|* @param mainDetail
|*/
|suspend fun testFlatWithoutOriginal(
| mainDetail: google.example.Detail
|): google.example.TestResponse = stubs.api.execute(context = "testFlatWithoutOriginal") {
| it.testFlatWithoutOriginal(
| google.example.testRequest {
| this.mainDetail = mainDetail
| }
| )
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates the NestedFlat methods`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "NestedFlat",
flattenedMethods = listOf(
FlattenedMethod(props("main_detail.even_more"))
),
keepOriginalMethod = false
)
)
)
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "nestedFlat" }
assertThat(methods).hasSize(1)
assertThat(methods.first().toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.nestedFlat(
|* moreDetail {
|* this.evenMore = evenMore
|* }
|* )
|* ```
|*/
|suspend fun nestedFlat(
| evenMore: google.example.MoreDetail
|): google.example.TestResponse = stubs.api.execute(context = "nestedFlat") {
| it.nestedFlat(google.example.testRequest {
| this.mainDetail = google.example.detail {
| this.evenMore = evenMore
| }
| })
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates the NestedFlat methods with repeated fields`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "NestedFlat",
flattenedMethods = listOf(
FlattenedMethod(props("more_details"))
),
keepOriginalMethod = false
)
)
)
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "nestedFlat" }
assertThat(methods).hasSize(1)
assertThat(methods.first().toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.nestedFlat(
|* detail {
|* this.moreDetails = moreDetails
|* }
|* )
|* ```
|*
|* @param moreDetails
|*/
|suspend fun nestedFlat(
| moreDetails: kotlin.collections.List<google.example.Detail>
|): google.example.TestResponse = stubs.api.execute(context = "nestedFlat") {
| it.nestedFlat(
| google.example.testRequest {
| this.moreDetails = moreDetails
| }
| )
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates the NestedFlat methods with repeated nested fields`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "NestedFlat",
flattenedMethods = listOf(
FlattenedMethod(props("more_details[0].even_more"))
),
keepOriginalMethod = false
)
)
)
val methods = generate(opts).testServiceClient().funSpecs.filter { it.name == "nestedFlat" }
assertThat(methods).hasSize(1)
assertThat(methods.first().toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = TestServiceClient.create()
| * val result = client.nestedFlat(
| * moreDetail {
| * this.evenMore = evenMore
| * }
| *)
| * ```
| */
|suspend fun nestedFlat(
| evenMore: google.example.MoreDetail
|): google.example.TestResponse = stubs.api.execute(context = "nestedFlat") {
| it.nestedFlat(google.example.testRequest {
| this.moreDetails(google.example.detail {
| this.evenMore = evenMore
| })})
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates the NestedFlatPrimitive methods`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "NestedFlatPrimitive",
flattenedMethods = listOf(
FlattenedMethod(props("main_detail.useful"))
),
keepOriginalMethod = false
)
)
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == "nestedFlatPrimitive" }
assertThat(methods).hasSize(1)
val method = methods.first { it.parameters.size == 1 }
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
|*
|*
|* For example:
|* ```
|* val client = TestServiceClient.create()
|* val result = client.nestedFlatPrimitive(
|* mainDetail.useful
|* )
|* ```
|*/
|suspend fun nestedFlatPrimitive(
| useful: kotlin.Boolean
|): google.example.TestResponse = stubs.api.execute(context = "nestedFlatPrimitive") {
| it.nestedFlatPrimitive(google.example.testRequest {
| this.mainDetail = google.example.detail {
| this.useful = useful
| }
| })
|}
|""".asNormalizedString()
)
}
@Test
fun `Generates the PagedTest methods`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "PagedTest",
pagedResponse = PagedResponse(
pageSize = "page_size",
responseList = "responses",
requestPageToken = "page_token",
responsePageToken = "next_page_token"
)
)
)
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == "pagedTest" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = TestServiceClient.create()
| * val pager = client.pagedTest(
| * pagedRequest {
| * }
| *)
| * val page = pager.next()
| * ```
| *
| * @param request the request object for the API call
| */
|suspend fun pagedTest(
| request: google.example.PagedRequest
|): kotlinx.coroutines.channels.ReceiveChannel<com.google.api.kgax.Page<kotlin.Int>> =
| pager(
| method = {
| request -> stubs.api.execute(context = "pagedTest") {
| it.pagedTest(request)
| }
| },
| initialRequest = { request },
| nextRequest = { request, token -> request.toBuilder().setPageToken(token).build() },
| nextPage = { response: google.example.PagedResponse ->
| com.google.api.kgax.Page<kotlin.Int>(response.responsesList, response.nextPageToken)
| }
| )
|""".asNormalizedString()
)
}
@Test
fun `Generates the PagedTest methods with flattened page parameter`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "PagedTest",
pagedResponse = PagedResponse(
pageSize = "page_size",
responseList = "responses",
requestPageToken = "page_token",
responsePageToken = "next_page_token"
),
keepOriginalMethod = false,
flattenedMethods = listOf(
FlattenedMethod(
listOf(
"flag".asPropertyPath(),
"page_size".asPropertyPath()
)
)
)
)
)
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == "pagedTest" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = TestServiceClient.create()
| * val pager = client.pagedTest(
| * flag,
| * pageSize
| *)
| * val page = pager.next()
| * ```
| *
| * @param flag
| *
| * @param pageSize
| */
|suspend fun pagedTest(
| flag: kotlin.Boolean,
| pageSize: kotlin.Int
|): kotlinx.coroutines.channels.ReceiveChannel<com.google.api.kgax.Page<kotlin.Int>> = pager(
| method = { request ->
| stubs.api.execute(context = "pagedTest") { it.pagedTest(request) }
| },
| initialRequest = {
| google.example.pagedRequest {
| this.flag = flag
| this.pageSize = pageSize
| }
| },
| nextRequest = { request, token -> request.toBuilder().setPageToken(token).build() },
| nextPage = { response: google.example.PagedResponse ->
| com.google.api.kgax.Page<kotlin.Int>(response.responsesList, response.nextPageToken)
| }
|)
|""".trimIndent().asNormalizedString()
)
}
@Test
fun `Generates the PagedTest methods without paging`() {
val opts = ServiceOptions(
methods = listOf(MethodOptions(name = "PagedTest"))
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == "pagedTest" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = TestServiceClient.create()
| * val result = client.pagedTest(
| * pagedRequest {
| * }
| *)
| * ```
| *
| * @param request the request object for the API call
| */
|suspend fun pagedTest(request: google.example.PagedRequest): google.example.PagedResponse =
| stubs.api.execute(context = "pagedTest") { it.pagedTest(request) }
|""".asNormalizedString()
)
}
@Test
fun `skips the badly paged NotPagedTest method`() = skipsBadlyPagedMethod("NotPagedTest")
@Test
fun `skips the badly paged StillNotPagedTest method`() =
skipsBadlyPagedMethod("StillNotPagedTest")
@Test
fun `skips the badly paged NotPagedTest2 method`() = skipsBadlyPagedMethod("NotPagedTest2")
private fun skipsBadlyPagedMethod(methodName: String) {
val opts = ServiceOptions(
methods = listOf(MethodOptions(name = methodName))
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == methodName }
assertThat(methods).isEmpty()
}
@Test
fun `generates an empty method`() {
val opts = ServiceOptions(
methods = listOf(MethodOptions(name = "Empty"))
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == "empty" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = TestServiceClient.create()
| * val result = client.empty(
| * testRequest {
| * }
| *)
| * ```
| *
| * @param request the request object for the API call
| */
|suspend fun empty(request: google.example.TestRequest) {
| stubs.api.execute(context = "empty") { it.empty(request) }
|}""".asNormalizedString()
)
}
@Test
fun `generates another empty method`() {
val opts = ServiceOptions(
methods = listOf(MethodOptions(name = "StillEmpty"))
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == "stillEmpty" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = TestServiceClient.create()
| * val result = client.stillEmpty()
| * ```
| *
| * @param request the request object for the API call
| */
|suspend fun stillEmpty(): google.example.TestResponse =
| stubs.api.execute(context = "stillEmpty") { it.stillEmpty(com.google.protobuf.Empty.getDefaultInstance()) }
|""".asNormalizedString()
)
}
@Test
fun `generates a really empty method`() {
val opts = ServiceOptions(
methods = listOf(MethodOptions(name = "ReallyEmpty"))
)
val methods =
generate(opts).testServiceClient().funSpecs.filter { it.name == "reallyEmpty" }
assertThat(methods).hasSize(1)
val method = methods.first()
assertThat(method.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = TestServiceClient.create()
| * val result = client.reallyEmpty()
| * ```
| *
| * @param request the request object for the API call
| */
|suspend fun reallyEmpty() {
| stubs.api.execute(context = "reallyEmpty") { it.reallyEmpty(com.google.protobuf.Empty.getDefaultInstance()) }
|}""".asNormalizedString()
)
}
}
// Additional tests for non-standard naming patterns
internal class GRPCGeneratorNameTest : BaseClientGeneratorTest(
protoFileName = "test_names",
clientClassName = "SomeServiceClient",
protoDirectory = "names",
namespace = "names"
) {
@Test
fun `generates the GetUser method`() {
val opts = ServiceOptions(
methods = listOf(
MethodOptions(
name = "GetUser",
keepOriginalMethod = false,
flattenedMethods = listOf(
FlattenedMethod(
listOf(
"_user.n_a_m_e".asPropertyPath()
)
),
FlattenedMethod(
listOf(
"an_int".asPropertyPath(),
"aString".asPropertyPath(),
"a_bool".asPropertyPath(),
"_user".asPropertyPath()
)
)
)
)
)
)
val methods =
generate(opts).someServiceClient().funSpecs.filter { it.name == "getUser" }
assertThat(methods).hasSize(2)
val firstMethod = methods.find { it.parameters.size == 1 }
assertThat(firstMethod.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = SomeServiceClient.create()
| * val result = client.getUser(
| * user.name
| *)
| * ```
| *
| * @param name
| */
|suspend fun getUser(name: kotlin.String): names.User = stubs.api.execute(context = "getUser") {
| it.getUser(names.thing {
| this.user = names.user { this.name = name }
| })
|}
""".asNormalizedString()
)
val secondMethod = methods.find { it.parameters.size == 4 }
assertThat(secondMethod.toString().asNormalizedString()).isEqualTo(
"""
|/**
| *
| *
| * For example:
| * ```
| * val client = SomeServiceClient.create()
| * val result = client.getUser(
| * anInt,
| * aString,
| * aBool,
| * user {
| * this.user = user
| * }
| *)
| * ```
| *
| * @param anInt
| *
| * @param aString
| *
| * @param aBool
| *
| * @param user
|*/
|suspend fun getUser(anInt: kotlin.Int, aString: kotlin.String, aBool: kotlin.Boolean, user: names.User): names.User =
| stubs.api.execute(context = "getUser") {
| it.getUser(names.thing {
| this.anInt = anInt
| this.aString = aString
| this.aBool = aBool
| this.user = user
| })
| }
""".asNormalizedString()
)
}
}
// The lite/normal code is almost identical.
// This base class is used to isolate the difference.
internal abstract class StubsImplTestContent(
invocationOptions: ClientPluginOptions,
private val marshallerClassName: String
) : BaseClientGeneratorTest("test", "TestServiceClient", invocationOptions = invocationOptions) {
private val opts = ServiceOptions(methods = listOf(MethodOptions(name = "Test")))
@Test
fun `is annotated`() {
val stub = generate(opts).testServiceClientStub()
assertThat(stub.annotationSpecs.first().toString()).isEqualTo(
"@javax.annotation.Generated(\"com.google.api.kotlin.generator.GRPCGenerator\")"
)
}
@Test
fun `has a unary testDescriptor`() {
val stub = generate(opts).testServiceClientStub()
val descriptor = stub.propertySpecs.first { it.name == "testDescriptor" }
assertThat(descriptor.toString().asNormalizedString()).isEqualTo(
"""
|private val testDescriptor: io.grpc.MethodDescriptor<google.example.TestRequest, google.example.TestResponse> by lazy {
| io.grpc.MethodDescriptor.newBuilder<google.example.TestRequest, google.example.TestResponse>()
| .setType(io.grpc.MethodDescriptor.MethodType.UNARY)
| .setFullMethodName(generateFullMethodName("google.example.TestService", "Test"))
| .setSampledToLocalTracing(true)
| .setRequestMarshaller($marshallerClassName.marshaller(
| google.example.TestRequest.getDefaultInstance()))
| .setResponseMarshaller($marshallerClassName.marshaller(
| google.example.TestResponse.getDefaultInstance()))
| .build()
| }
""".asNormalizedString()
)
}
@Test
fun `has a unary test method`() {
val stub = generate(opts).testServiceClientStub()
val descriptor = stub.funSpecs.first { it.name == "test" }
assertThat(descriptor.toString().asNormalizedString()).isEqualTo(
"""
|fun test(
| request: google.example.TestRequest
|): com.google.common.util.concurrent.ListenableFuture<google.example.TestResponse> =
| futureUnaryCall(channel.newCall(testDescriptor, callOptions), request)
""".asNormalizedString()
)
}
@Test
fun `has a streaming streamTestDescriptor`() {
val stub = generate(opts).testServiceClientStub()
val descriptor = stub.propertySpecs.first { it.name == "streamTestDescriptor" }
assertThat(descriptor.toString().asNormalizedString()).isEqualTo(
"""
|private val streamTestDescriptor: io.grpc.MethodDescriptor<google.example.TestRequest, google.example.TestResponse> by lazy {
| io.grpc.MethodDescriptor.newBuilder<google.example.TestRequest, google.example.TestResponse>()
| .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING)
| .setFullMethodName(generateFullMethodName("google.example.TestService", "StreamTest"))
| .setSampledToLocalTracing(true)
| .setRequestMarshaller($marshallerClassName.marshaller(
| google.example.TestRequest.getDefaultInstance()
| ))
| .setResponseMarshaller($marshallerClassName.marshaller(
| google.example.TestResponse.getDefaultInstance()
| ))
| .build()
| }
""".asNormalizedString()
)
}
@Test
fun `has a streaming streamTest method`() {
val stub = generate(opts).testServiceClientStub()
val descriptor = stub.funSpecs.first { it.name == "streamTest" }
assertThat(descriptor.toString().asNormalizedString()).isEqualTo(
"""
|fun streamTest(
| responseObserver: io.grpc.stub.StreamObserver<google.example.TestResponse>
|): io.grpc.stub.StreamObserver<google.example.TestRequest> =
| asyncBidiStreamingCall(channel.newCall(streamTestDescriptor, callOptions), responseObserver)
""".asNormalizedString()
)
}
@Test
fun `has a streaming streamClientTestDescriptor`() {
val stub = generate(opts).testServiceClientStub()
val descriptor = stub.propertySpecs.first { it.name == "streamClientTestDescriptor" }
assertThat(descriptor.toString().asNormalizedString()).isEqualTo(
"""
|private val streamClientTestDescriptor: io.grpc.MethodDescriptor<google.example.TestRequest, google.example.TestResponse> by lazy {
| io.grpc.MethodDescriptor.newBuilder<google.example.TestRequest, google.example.TestResponse>()
| .setType(io.grpc.MethodDescriptor.MethodType.CLIENT_STREAMING)
| .setFullMethodName(generateFullMethodName("google.example.TestService", "StreamClientTest"))
| .setSampledToLocalTracing(true)
| .setRequestMarshaller($marshallerClassName.marshaller(
| google.example.TestRequest.getDefaultInstance()
| ))
| .setResponseMarshaller($marshallerClassName.marshaller(
| google.example.TestResponse.getDefaultInstance()
| ))
| .build()
| }
""".asNormalizedString()
)
}
@Test
fun `has a streaming streamClientTest method`() {
val stub = generate(opts).testServiceClientStub()
val descriptor = stub.funSpecs.first { it.name == "streamClientTest" }
assertThat(descriptor.toString().asNormalizedString()).isEqualTo(
"""
|fun streamClientTest(
| responseObserver: io.grpc.stub.StreamObserver<google.example.TestResponse>
|): io.grpc.stub.StreamObserver<google.example.TestRequest> =
| asyncClientStreamingCall(channel.newCall(streamClientTestDescriptor, callOptions), responseObserver)
""".asNormalizedString()
)
}
@Test
fun `has a streaming streamServerTestDescriptor`() {
val stub = generate(opts).testServiceClientStub()
val descriptor = stub.propertySpecs.first { it.name == "streamServerTestDescriptor" }
assertThat(descriptor.toString().asNormalizedString()).isEqualTo(
"""
|private val streamServerTestDescriptor: io.grpc.MethodDescriptor<google.example.TestRequest, google.example.TestResponse> by lazy {
| io.grpc.MethodDescriptor.newBuilder<google.example.TestRequest, google.example.TestResponse>()
| .setType(io.grpc.MethodDescriptor.MethodType.SERVER_STREAMING)
| .setFullMethodName(generateFullMethodName("google.example.TestService", "StreamServerTest"))
| .setSampledToLocalTracing(true)
| .setRequestMarshaller($marshallerClassName.marshaller(
| google.example.TestRequest.getDefaultInstance()
| ))
| .setResponseMarshaller($marshallerClassName.marshaller(
| google.example.TestResponse.getDefaultInstance()
| ))
| .build()
| }
""".asNormalizedString()
)
}
@Test
fun `has a streaming streamServerTest method`() {
val stub = generate(opts).testServiceClientStub()
val descriptor = stub.funSpecs.first { it.name == "streamServerTest" }
assertThat(descriptor.toString().asNormalizedString()).isEqualTo(
"""
|fun streamServerTest(
| request: google.example.TestRequest,
| responseObserver: io.grpc.stub.StreamObserver<google.example.TestResponse>
|) = asyncServerStreamingCall(channel.newCall(streamServerTestDescriptor, callOptions), request, responseObserver)
""".asNormalizedString()
)
}
}
internal class FullStubsImplTest :
StubsImplTestContent(ClientPluginOptions(), "io.grpc.protobuf.ProtoUtils")
internal class LiteStubsImplTest :
StubsImplTestContent(ClientPluginOptions(lite = true), "io.grpc.protobuf.lite.ProtoLiteUtils")
private fun List<GeneratedArtifact>.testServiceClient() = findSource("TestServiceClient")
private fun List<GeneratedArtifact>.testServiceClientStub() = findSource("TestServiceClientStub")
private fun List<GeneratedArtifact>.someServiceClient() = findSource("SomeServiceClient")
private fun List<GeneratedArtifact>.findSource(name: String) =
this.sources().firstOrNull { it.name == name }?.types?.first()
?: throw RuntimeException("Could not find $name in candidates: ${this.sources().map { it.name }}") | generator/src/test/kotlin/com/google/api/kotlin/generator/GRPCGeneratorTest.kt | 3100390065 |
package mediathek.javafx.filterpanel
import ca.odell.glazedlists.BasicEventList
import ca.odell.glazedlists.EventList
import ca.odell.glazedlists.TransformedList
import ca.odell.glazedlists.event.ListEvent
import mediathek.tool.GermanStringSorter
/**
* The base model object for all available senders that the client can process.
*/
object SenderListBoxModel {
private val providedSenderList: EventList<String> = BasicEventList()
@JvmStatic
val readOnlySenderList = ReadOnlySenderListBoxModel()
class ReadOnlySenderListBoxModel : TransformedList<String, String>(providedSenderList) {
override fun isWritable(): Boolean {
return false
}
override fun listChanged(listChanges: ListEvent<String>?) {
}
}
init {
providedSenderList.add("3Sat")
providedSenderList.add("ARD")
providedSenderList.add("ARTE.DE")
providedSenderList.add("ARTE.EN")
providedSenderList.add("ARTE.ES")
providedSenderList.add("ARTE.FR")
providedSenderList.add("ARTE.IT")
providedSenderList.add("ARTE.PL")
providedSenderList.add("BR")
providedSenderList.add("DW")
providedSenderList.add("Funk.net")
providedSenderList.add("HR")
providedSenderList.add("KiKA")
providedSenderList.add("MDR")
providedSenderList.add("NDR")
providedSenderList.add("ORF")
providedSenderList.add("PHOENIX")
providedSenderList.add("Radio Bremen TV")
providedSenderList.add("RBB")
providedSenderList.add("SR")
providedSenderList.add("SRF")
providedSenderList.add("SRF.Podcast")
providedSenderList.add("SWR")
providedSenderList.add("WDR")
providedSenderList.add("ZDF")
providedSenderList.add("ZDF-tivi")
providedSenderList.sortWith(GermanStringSorter.getInstance())
}
} | src/main/java/mediathek/javafx/filterpanel/SenderListBoxModel.kt | 2123612651 |
// Copyright 2020 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.api
enum class Version(val string: String) {
VERSION_UNSPECIFIED(""),
V2_ALPHA("v2alpha");
override fun toString(): String = string
companion object {
fun fromString(string: String): Version {
return values().find { it.string == string } ?: VERSION_UNSPECIFIED
}
}
}
| src/main/kotlin/org/wfanet/measurement/api/Version.kt | 4040421670 |
package com.makeevapps.simpletodolist.viewmodel
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.makeevapps.simpletodolist.App
import com.makeevapps.simpletodolist.datasource.db.table.Task
import com.makeevapps.simpletodolist.datasource.preferences.PreferenceManager
import com.makeevapps.simpletodolist.repository.TaskRepository
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Inject
class TodayViewModel : ViewModel() {
@Inject
lateinit var preferenceManager: PreferenceManager
@Inject
lateinit var taskRepository: TaskRepository
private val tasksResponse = MutableLiveData<List<Task>>()
private val compositeDisposable = CompositeDisposable()
init {
App.component.inject(this)
compositeDisposable.add(taskRepository.getTodayTasks().subscribe({ result -> tasksResponse.value = result }))
}
fun is24HoursFormat(): Boolean = preferenceManager.is24HourFormat()
fun insertOrUpdateTask(task: Task) {
compositeDisposable.add(taskRepository.insertOrUpdateTask(task).subscribe())
}
fun removeTask(task: Task) {
compositeDisposable.add(taskRepository.deleteTask(task).subscribe())
}
fun getTasksResponse(): MutableLiveData<List<Task>> = tasksResponse
override fun onCleared() {
compositeDisposable.clear()
}
} | app/src/main/java/com/makeevapps/simpletodolist/viewmodel/TodayViewModel.kt | 1035087007 |
package nl.hannahsten.texifyidea.lang.commands
import nl.hannahsten.texifyidea.lang.LatexPackage
import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.AMSSYMB
import nl.hannahsten.texifyidea.lang.LatexPackage.Companion.STMARYRD
/**
* @author Hannah Schellekens
*/
enum class LatexOperatorCommand(
override val command: String,
override vararg val arguments: Argument = emptyArray(),
override val dependency: LatexPackage = LatexPackage.DEFAULT,
override val display: String? = null,
override val isMathMode: Boolean = true,
val collapse: Boolean = false
) : LatexCommand {
FOR_ALL("forall", display = "∀", collapse = true),
PARTIAL("partial", display = "∂", collapse = true),
EXISTS("exists", display = "∃", collapse = true),
NOT_EXISTS("nexists", dependency = AMSSYMB, display = "∄", collapse = true),
EMPTY_SET("emptyset", display = "∅", collapse = true),
NOTHING("varnothing", dependency = AMSSYMB, display = "∅", collapse = true),
NABLA("nabla", display = "∇", collapse = true),
ELEMENT_OF("in", display = "∈", collapse = true),
NOT_ELEMENT_OF("notin", display = "∉", collapse = true),
CONTAIN_AS_MEMBER("ni", display = "∋", collapse = true),
COMPLEMENT("complement", dependency = AMSSYMB, display = "∁"),
N_ARY_PRODUCT("prod", display = "∏", collapse = true),
N_ARY_COPRODUCT("coprod", display = "∐", collapse = true),
SUM("sum", display = "∑", collapse = true),
MINUS_PLUS("mp", display = "∓", collapse = true),
PLUS_MINUS("pm", display = "±", collapse = true),
SET_MINUS("setminus", display = "∖", collapse = true),
SMALL_SET_MINUS("smallsetminus", dependency = AMSSYMB, display = "∖", collapse = true),
ASTERISK("ast", display = "∗"),
STAR("star", display = "⋆", collapse = true),
DOT_PLUS("dotplus", dependency = AMSSYMB, display = "∔"),
CIRCLE("circ", display = "∘"),
BULLET("bullet", display = "∙"),
PROPORTIONAL_TO("propto", display = "∝", collapse = true),
PROPORTIONAL_TO_SYMBOL("varpropto", dependency = AMSSYMB, display = "∝", collapse = true),
INFINITY("infty", display = "∞", collapse = true),
ANGLE("angle", display = "∠", collapse = true),
MEASURED_ANGLE("measuredangle", dependency = AMSSYMB, display = "∡", collapse = true),
SPHERICAL_ANGLE("sphericalangle", dependency = AMSSYMB, display = "∢", collapse = true),
MID("mid", display = "∣", collapse = true),
MID_SHORT("shortmid", dependency = AMSSYMB, display = "∣", collapse = true),
NOT_MID_SHORT("nshortmid", dependency = AMSSYMB),
PARALLEL("parallel", display = "∥", collapse = true),
NOT_PARALLEL("nparallel", dependency = AMSSYMB, display = "∦", collapse = true),
PARALLEL_SHORT("shortparallel", display = "∥", collapse = true),
NOT_PARALLEL_SHORT("nshortparallel", dependency = AMSSYMB, display = "∦", collapse = true),
LOGICAL_AND("land", display = "∧", collapse = true),
LOGICAL_OR("lor", display = "∨", collapse = true),
INTERSECTION("cap", display = "∩", collapse = true),
UNION("cup", display = "∪", collapse = true),
DOUBLE_UNION("Cup", dependency = AMSSYMB, display = "⋓", collapse = true),
DOUBLE_INTERSECTION("Cap", dependency = AMSSYMB, display = "⋒", collapse = true),
INTEGRAL("int", display = "∫", collapse = true),
DOUBLE_INTEGRAL("iint", dependency = LatexPackage.AMSMATH, display = "∬", collapse = true),
TRIPLE_INTEGRAL("iiint", dependency = LatexPackage.AMSMATH, display = "∭", collapse = true),
QUADRUPLE_INTEGRAL("iiiint", dependency = LatexPackage.AMSMATH, display = "⨌", collapse = true),
DOTS_INTEGRAL("idotsint", display = "∫⋯∫", collapse = true),
CONTOUR_INTEGRAL("oint", display = "∮", collapse = true),
THEREFORE("therefore", dependency = AMSSYMB, display = "∴", collapse = true),
BECAUSE("because", dependency = AMSSYMB, display = "∵", collapse = true),
TILDE_OPERATOR("sim", display = "∼", collapse = true),
WREATH_PRODUCT("wr", display = "≀", collapse = true),
APPROX("approx", display = "≈", collapse = true),
NOT_EQUAL("neq", display = "≠", collapse = true),
EQUIVALENT("equiv", display = "≡", collapse = true),
LESS_THAN_EQUAL("leq", display = "≤", collapse = true),
LESS_THAN_NOT_EQUAL("lneq", dependency = AMSSYMB, display = "⪇", collapse = true),
LESS_THAN_EQUALL("leqq", dependency = AMSSYMB, display = "≦", collapse = true),
GREATER_THAN_EQUAL("geq", display = "≥", collapse = true),
GREATER_THAN_NOT_EQUAL("gneq", dependency = AMSSYMB, display = "⪈", collapse = true),
GREATER_THAN_EQUALL("geqq", dependency = AMSSYMB, display = "≧", collapse = true),
NOT_LESS_THAN("nless", dependency = AMSSYMB, display = "≮", collapse = true),
NOT_GREATER_THAN("ngtr", dependency = AMSSYMB, display = "≯", collapse = true),
NOT_LESS_THAN_EQUAL("nleq", dependency = AMSSYMB, display = "≰", collapse = true),
NOT_LESS_THAN_EQUALL("nleqq", dependency = AMSSYMB, display = "≦\u200D\u0338"),
NOT_GREATER_THAN_EQUAL("ngeq", dependency = AMSSYMB, display = "≱", collapse = true),
NOT_GREATER_THAN_EQUALL("ngeqq", dependency = AMSSYMB, display = "≧\u200D\u0338"),
DOUBLE_LESS_THAN("ll", dependency = AMSSYMB, display = "≪", collapse = true),
LESS_LESS_LESS("lll", dependency = AMSSYMB, display = "⋘", collapse = true),
LESS_NOT_EQUAL("lneqq", dependency = AMSSYMB, display = "≨", collapse = true),
GREATER_NOT_EQUAL("gneqq", dependency = AMSSYMB, display = "≩", collapse = true),
DOUBLE_GREATER_THAN("gg", dependency = AMSSYMB, display = "≫", collapse = true),
GREATER_GREATER_GREATER("ggg", dependency = AMSSYMB, display = "⋙", collapse = true),
SUBSET("subset", display = "⊂", collapse = true),
SUPERSET("supset", display = "⊃", collapse = true),
SUBSET_EQUALS("subseteq", display = "⊆", collapse = true),
SUBSET_EQUALSS("subseteqq", dependency = AMSSYMB, display = "⊆", collapse = true),
SUPERSET_EQUALS("supseteq", display = "⊇", collapse = true),
SUPERSET_EQUALSS("supseteqq", dependency = AMSSYMB, display = "⊇", collapse = true),
NOT_SUBSET_EQUALS("nsubseteq", dependency = AMSSYMB, display = "⊈", collapse = true),
NOT_SUBSET_EQUALSS("nsubseteqq", dependency = AMSSYMB, display = "⊈", collapse = true),
NOT_SUPERSET_EQUALS("nsupseteq", dependency = AMSSYMB, display = "⊉", collapse = true),
NOT_SUPERSET_EQUALSS("nsupseteqq", dependency = AMSSYMB, display = "⊉", collapse = true),
SQUARE_SUBSET("sqsubset", dependency = AMSSYMB, display = "⊏", collapse = true),
SQUARE_SUPERSET("sqsupset", dependency = AMSSYMB, display = "⊐", collapse = true),
SQUARE_SUBSET_EQUALS("sqsubseteq", dependency = AMSSYMB, display = "⊑", collapse = true),
SQUARE_SUPERSET_EQUALS("sqsupseteq", dependency = AMSSYMB, display = "⊒", collapse = true),
SQUARE_CAP("sqcap", display = "⊓", collapse = true),
SQUARE_CUP("sqcup", display = "⊔", collapse = true),
CIRCLED_PLUS("oplus", display = "⊕", collapse = true),
CIRCLED_MINUS("ominus", display = "⊖", collapse = true),
CIRCLED_TIMES("otimes", display = "⊗", collapse = true),
CIRCLED_SLASH("oslash", display = "⊘", collapse = true),
CIRCLED_DOT("odot", display = "⊙", collapse = true),
BOXED_PLUS("boxplus", dependency = AMSSYMB, display = "⊞", collapse = true),
BOXED_MINUS("boxminus", dependency = AMSSYMB, display = "⊟", collapse = true),
BOXED_TIMES("boxtimes", dependency = AMSSYMB, display = "⊠", collapse = true),
BOXED_DOT("boxdot", dependency = AMSSYMB, display = "⊡", collapse = true),
BOWTIE("bowtie", display = "⋈", collapse = true),
JOIN("Join", dependency = AMSSYMB, display = "⨝", collapse = true),
TRIANGLE_RIGHT("triangleright", dependency = AMSSYMB, display = "▷", collapse = true),
TRIANGLE_LEFT("triangleleft", dependency = AMSSYMB, display = "◁", collapse = true),
LHD("lhd", dependency = AMSSYMB, display = "◁", collapse = true),
RHD("rhd", dependency = AMSSYMB, display = "▷", collapse = true),
UN_LHD("unlhd", dependency = AMSSYMB, display = "⊴", collapse = true),
UN_RHD("unrhd", dependency = AMSSYMB, display = "⊵", collapse = true),
TRIANGLELEFTEQ("tranglelefteq", dependency = AMSSYMB, display = "⊴", collapse = true),
TRIANGLERIGHTEQ("trianglerighteq", dependency = AMSSYMB, display = "⊵", collapse = true),
LTIMES("ltimes", dependency = AMSSYMB, display = "⋉", collapse = true),
RTIMES("rtimes", dependency = AMSSYMB, display = "⋊", collapse = true),
TIMES("times", display = "×", collapse = true),
LEFT_THREE_TIMES("leftthreetimes", dependency = AMSSYMB, display = "⋋", collapse = true),
RIGHT_THREE_TIMES("rightthreetimes", dependency = AMSSYMB, display = "⋌", collapse = true),
CIRCLED_CIRCLE("circledcirc", dependency = AMSSYMB, display = "⊚", collapse = true),
CIRCLED_DASH("circleddash", dependency = AMSSYMB, display = "⊝", collapse = true),
CIRCLED_ASTERISK("circledast", dependency = AMSSYMB, display = "⊛", collapse = true),
MULTISET_UNION("uplus", display = "⊎", collapse = true),
WEDGE_BAR("barwedge", dependency = AMSSYMB, display = "⊼", collapse = true),
VEE_BAR("veebar", dependency = AMSSYMB, display = "⊻", collapse = true),
DOUBLE_BAR_WEDGE("doublebarwedge", dependency = AMSSYMB, display = "⌆", collapse = true),
CURLY_WEDGE("curlywedge", dependency = AMSSYMB, display = "⋏", collapse = true),
CURLY_VEE("curlyvee", dependency = AMSSYMB, display = "⋎", collapse = true),
INTERCALATE("intercal", dependency = AMSSYMB, display = "⊺", collapse = true),
PITCHFORK("pitchfork", dependency = AMSSYMB, display = "⋔", collapse = true),
NOT_SIM("nsim", dependency = AMSSYMB),
SIM_EQUALS("simeq", display = "≃", collapse = true),
BACKWARDS_SIM_EQUALS("backsimeq", dependency = AMSSYMB, display = "⋍", collapse = true),
APPROX_EQUALS("approxeq", dependency = AMSSYMB, display = "≊", collapse = true),
CONG_SYMBOL("cong", dependency = AMSSYMB, display = "≅", collapse = true),
NOT_CONG("ncong", dependency = AMSSYMB, display = "≇", collapse = true),
SMILE("smile", dependency = AMSSYMB, display = "\u2323", collapse = true),
FROWN("frown", dependency = AMSSYMB, display = "\u2322", collapse = true),
SMALL_SMILE("smallsmile", dependency = AMSSYMB, display = "\u2323", collapse = true),
SMALL_FROWN("smallfrown", dependency = AMSSYMB, display = "\u2322", collapse = true),
BETWEEN("between", dependency = AMSSYMB, display = "≬", collapse = true),
PRECEDES("prec", display = "≺", collapse = true),
SUCCEEDS("succ", display = "≻", collapse = true),
NOT_PRECEEDS("nprec", dependency = AMSSYMB, display = "⊀", collapse = true),
NOT_SUCCEEDS("nsucc", dependency = AMSSYMB, display = "⊁", collapse = true),
PRECEDES_OR_EQUAL("preceq", dependency = AMSSYMB, display = "⪯", collapse = true),
SUCCEEDS_OR_EQUALS("succeq", dependency = AMSSYMB, display = "⪰", collapse = true),
NOT_PRECEDES_OR_EQUALS("npreceq", dependency = AMSSYMB, display = "⋠", collapse = true),
NOT_SUCCEEDS_OR_EQUALS("nsucceq", dependency = AMSSYMB, display = "⋡", collapse = true),
CURLY_PRECEDES_OR_EQUALS("preccurlyeq", dependency = AMSSYMB, display = "≼", collapse = true),
CURLY_SUCCEEDS_OR_EQUALS("succcurlyeq", dependency = AMSSYMB, display = "≽", collapse = true),
CURLY_EQUALS_PRECEDES("curlyeqprec", dependency = AMSSYMB, display = "⋞", collapse = true),
CURLY_EQUALS_SUCCEEDS("curlyeqsucc", dependency = AMSSYMB, display = "⋟", collapse = true),
PRECEDES_SIM("precsim", dependency = AMSSYMB, display = "≾", collapse = true),
SUCCEEDS_SIM("succsim", dependency = AMSSYMB, display = "≿", collapse = true),
PRECEDES_NOT_SIM("precnsim", dependency = AMSSYMB, display = "⋨", collapse = true),
SUCCEEDS_NOT_SIM("succnsim", dependency = AMSSYMB, display = "⋩", collapse = true),
PRECEDES_APPROX("precapprox", dependency = AMSSYMB, display = "⪷", collapse = true),
SUCCEEDS_APPROX("succapprox", dependency = AMSSYMB, display = "⪸", collapse = true),
PRECEDES_NOT_APPROX("precnapprox", dependency = AMSSYMB, display = "⪹", collapse = true),
SUCCEEDS_NOT_APPROX("succnapprox", dependency = AMSSYMB, display = "⪺", collapse = true),
PERPENDICULAR("perp", display = "⟂", collapse = true),
RIGHT_TACK("vdash", display = "⊢", collapse = true),
NOT_RIGHT_TACK("nvdash", dependency = AMSSYMB, display = "⊬", collapse = true),
FORCES("Vdash", dependency = AMSSYMB, display = "⊩", collapse = true),
TRIPLE_RIGHT_TACK("Vvdash", dependency = AMSSYMB, display = "⊪", collapse = true),
MODELS("models", display = "⊧", collapse = true),
VERTICAL_DOUBLE_DASH_RIGHT("vDash", dependency = AMSSYMB, display = "⊨", collapse = true),
NOT_VERTICAL_DOUBLE_DASH_RIGHT("nvDash", dependency = AMSSYMB, display = "⊭", collapse = true),
NOT_DOUBLE_VERTICAL_DOUBLE_DASH_RIGHT("nVDash", dependency = AMSSYMB, display = "⊯", collapse = true),
NOT_MID("nmid", dependency = AMSSYMB, display = "∤", collapse = true),
LESS_THAN_DOT("lessdot", dependency = AMSSYMB, display = "⋖", collapse = true),
GREATER_THAN_DOT("gtrdot", dependency = AMSSYMB, display = "⋗", collapse = true),
LESS_THAN_VERTICAL_NOT_EQUALS("lvertneqq", dependency = AMSSYMB),
GREATER_THAN_VERTICAL_NOT_EQUALS("gvertneqq", dependency = AMSSYMB),
LESS_THAN_EQUALS_SLANT("leqslant", dependency = AMSSYMB, display = "⩽", collapse = true),
GREATER_THAN_EQUALS_SLANT("geqslant", dependency = AMSSYMB, display = "⩾", collapse = true),
NOT_LESS_THAN_EQUALS_SLANT("nleqslant", dependency = AMSSYMB),
NOT_GREATER_THAN_EQUALS_SLANT("ngeqslant", dependency = AMSSYMB),
EQUALS_SLANT_LESS_THAN("eqslantless", dependency = AMSSYMB, display = "⪕", collapse = true),
EQUALS_SLANT_GREATER_THAN("eqslantgtr", dependency = AMSSYMB, display = "⪖", collapse = true),
LESS_GREATER("lessgtr", dependency = AMSSYMB, display = "≶", collapse = true),
GREATER_LESS("gtrless", dependency = AMSSYMB, display = "≷", collapse = true),
LESS_EQUALS_GREATER("lesseqgtr", dependency = AMSSYMB, display = "⋚", collapse = true),
GREATER_EQUALS_LESSER("gtreqless", dependency = AMSSYMB, display = "⋛", collapse = true),
LESS_EQUALSS_GREATER("lesseqqgtr", dependency = AMSSYMB, display = "⪋", collapse = true),
GREATER_EQUALSS_LESSER("gtreqqless", dependency = AMSSYMB, display = "⪌", collapse = true),
LESS_SIM("lesssim", dependency = AMSSYMB, display = "≲", collapse = true),
GREATER_SIM("gtrsim", dependency = AMSSYMB, display = "≳", collapse = true),
LESS_NOT_SIM("lnsim", dependency = AMSSYMB, display = "⋦", collapse = true),
GREATER_NOT_SIM("gnsim", dependency = AMSSYMB, display = "⋧", collapse = true),
LESS_APPROX("lessapprox", dependency = AMSSYMB, display = "⪅", collapse = true),
GREATER_APPROX("gtrapprox", dependency = AMSSYMB, display = "⪆", collapse = true),
LESS_NOT_APPROX("lnapprox", dependency = AMSSYMB, display = "⪉", collapse = true),
GREATER_NOT_APPROX("gnapprox", dependency = AMSSYMB, display = "⪊", collapse = true),
TRIANGLE_RIGHT_VARIATION("vartriangleright", dependency = AMSSYMB, display = "⊳", collapse = true),
TRIANGLE_LEFT_VARIATION("vartriangleleft", dependency = AMSSYMB, display = "⊲", collapse = true),
NOT_TRIANGLE_LEFT("ntriangleleft", dependency = AMSSYMB, display = "⋪", collapse = true),
NOT_TRIANGLE_RIGHT("ntriangleright", dependency = AMSSYMB, display = "⋫", collapse = true),
TRIANGLE_LEFT_EQUALS("trianglelefteq", dependency = AMSSYMB, display = "⊴", collapse = true),
TRIANGLE_RIGHT_EQUALS("trianglerighteq", dependency = AMSSYMB, display = "⊵", collapse = true),
TRIANGLE_LEFT_EQUALS_SLANT("trianglelefteqslant", dependency = STMARYRD),
TRIANGLE_RIGHT_EQUALS_SLANT("trianglerighteqslant", dependency = STMARYRD),
NOT_TRIANGLE_LEFT_EQUALS("ntrianglelefteq", dependency = AMSSYMB, display = "⋬", collapse = true),
NOT_TRIANGLE_RIGHT_EQUALS("ntrianglerighteq", dependency = AMSSYMB, display = "⋭", collapse = true),
NOT_TRIANGLE_LEFT_EQUALS_SLANT("ntrianglelefteqslant", dependency = STMARYRD),
NOT_TRIANGLE_RIGHT_SLANT("ntrianglerighteqslant", dependency = STMARYRD),
BLACK_TRIANGLE_LEFT("blacktriangleleft", dependency = AMSSYMB, display = "◂", collapse = true),
BLACK_TRIANGLE_RIGHT("blacktriangleright", dependency = AMSSYMB, display = "▸", collapse = true),
SUBSET_NOT_EQUALS("subsetneq", dependency = AMSSYMB, display = "⊊", collapse = true),
SUPERSET_NOT_EQUALS("supsetneq", dependency = AMSSYMB, display = "⊋", collapse = true),
SUBSET_NOT_EQUALS_VARIATION("varsubsetneq", dependency = AMSSYMB),
SUPERSET_NOT_EQUALS_VARIATION("varsupsetneq", dependency = AMSSYMB),
SUBSET_NOT_EQUALSS("subsetneqq", dependency = AMSSYMB, display = "⫋", collapse = true),
SUPERSET_NOT_EQUALSS("supsetneqq", dependency = AMSSYMB, display = "⫌", collapse = true),
REVERSED_EPSILON("backepsilon", dependency = AMSSYMB, display = "϶", collapse = true),
DOUBLE_SUBSET("Subset", dependency = AMSSYMB, display = "⋐", collapse = true),
DOUBLE_SUPERSET("Supset", dependency = AMSSYMB, display = "⋑", collapse = true),
CIRCLE_EQUALS("circeq", dependency = AMSSYMB, display = "≗", collapse = true),
TRIANGLE_EQUALS("triangleq", dependency = AMSSYMB, display = "≜", collapse = true),
EQUALS_CIRCLE("eqcirc", dependency = AMSSYMB),
BUMP_EQUALS("bumpeq", dependency = AMSSYMB),
DOUBLE_BUMP_EQUALS("Bumpeq", dependency = AMSSYMB, display = "", collapse = true),
DOT_EQUALS_DOT("doteqdot", dependency = AMSSYMB, display = "≑", collapse = true),
RISING_DOTS_EQUALS("risingdotseq", dependency = AMSSYMB, display = "≓", collapse = true),
FALLING_DOTS_EQUALS("fallingdotseq", dependency = AMSSYMB, display = "≒", collapse = true),
DOT_EQUALS("doteq", dependency = AMSSYMB),
SUBSET_PLUS("subsetplus", dependency = STMARYRD),
SUBSET_PLUS_EQUALS("subsetpluseq", dependency = STMARYRD),
SUPERSET_PLUS("supsetplus", dependency = STMARYRD),
SUPERSET_PLUS_EQUALS("supsetpluseq", dependency = STMARYRD),
IN_PLUS("inplus", dependency = STMARYRD),
REVERSED_IN_PLUS("niplus", dependency = STMARYRD),
;
override val identifier: String
get() = name
} | src/nl/hannahsten/texifyidea/lang/commands/LatexOperatorCommand.kt | 3065990565 |
package com.github.ykrank.androidtools.widget.track.talkingdata
import android.app.Activity
import android.content.Context
import com.github.ykrank.androidtools.data.TrackUser
import com.github.ykrank.androidtools.widget.track.TrackAgent
import com.tendcloud.tenddata.TCAgent
/**
* Created by ykrank on 2016/12/28.
* Agent for talking data proxy
*/
class TalkingDataAgent : TrackAgent {
override fun init(context: Context) {
TCAgent.LOG_ON = false
TCAgent.init(context)
TCAgent.setReportUncaughtExceptions(false)
}
override fun setUser(user: TrackUser) {
TCAgent.setGlobalKV("UserName", user.name)
TCAgent.setGlobalKV("Uid", user.uid)
TCAgent.setGlobalKV("Permission", user.permission.toString())
user.extras?.forEach { TCAgent.setGlobalKV(it.key, it.value) }
}
override fun onResume(activity: Activity) {
TCAgent.onPageStart(activity, activity.localClassName)
}
override fun onPause(activity: Activity) {
TCAgent.onPageEnd(activity, activity.localClassName)
}
override fun onPageStart(context: Context, string: String) {
TCAgent.onPageStart(context, string)
}
override fun onPageEnd(context: Context, string: String) {
TCAgent.onPageEnd(context, string)
}
override fun onEvent(context: Context, name: String, label: String, data: Map<String, String?>) {
TCAgent.onEvent(context, name, label, data)
}
}
| library/src/main/java/com/github/ykrank/androidtools/widget/track/talkingdata/TalkingDataAgent.kt | 1181841526 |
package com.jamieadkins.gwent.decktracker
import com.xwray.groupie.kotlinandroidextensions.Item
import com.xwray.groupie.kotlinandroidextensions.ViewHolder
import kotlinx.android.synthetic.main.view_beta_notice.*
data class BetaNoticeItem(
val onFeedbackClick: () -> Unit
) : Item() {
override fun getLayout(): Int = R.layout.view_beta_notice
override fun bind(viewHolder: ViewHolder, position: Int) {
viewHolder.btnFeedback.setOnClickListener { onFeedbackClick.invoke() }
}
} | decktracker/src/main/java/com/jamieadkins/gwent/decktracker/BetaNoticeItem.kt | 1396934217 |
package com.quickblox.sample.conference.kotlin.presentation.screens.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
/*
* Created by Injoit in 2021-09-30.
* Copyright © 2021 Quickblox. All rights reserved.
*/
abstract class BaseFragment<VB : ViewBinding> : Fragment() {
var binding: VB? = null
private set
abstract fun getViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
binding = getViewBinding(inflater, container)
return binding?.root
}
override fun onDestroyView() {
binding = null
super.onDestroyView()
}
} | sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/base/BaseFragment.kt | 3893062434 |
/*
* Copyright 2022, TeamDev. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Redistribution and use in source and/or binary forms, with or without
* modification, must retain the above copyright notice and the following
* disclaimer.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package io.spine.internal.gradle.github.pages
import java.io.File
import org.gradle.api.Project
import org.gradle.api.provider.Property
import org.gradle.api.provider.SetProperty
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.getByType
import org.gradle.kotlin.dsl.property
/**
* Configures the `updateGitHubPages` extension.
*/
@Suppress("unused")
fun Project.updateGitHubPages(excludeInternalDocletVersion: String,
action: UpdateGitHubPagesExtension.() -> Unit) {
apply<UpdateGitHubPages>()
val extension = extensions.getByType(UpdateGitHubPagesExtension::class)
extension.excludeInternalDocletVersion = excludeInternalDocletVersion
extension.action()
}
/**
* The extension for configuring the [UpdateGitHubPages] plugin.
*/
class UpdateGitHubPagesExtension
private constructor(
/**
* Tells whether the types marked `@Internal` should be included into
* the doc generation.
*/
val allowInternalJavadoc: Property<Boolean>,
/**
* The root folder of the repository to which the updated `Project` belongs.
*/
var rootFolder: Property<File>,
/**
* The external inputs, which output should be included into
* the GitHub Pages update.
*
* The values are interpreted according to
* [org.gradle.api.tasks.Copy.from] specification.
*
* This property is optional.
*/
var includeInputs: SetProperty<Any>
) {
/**
* The version of the
* [ExcludeInternalDoclet][io.spine.internal.gradle.javadoc.ExcludeInternalDoclet]
* used when updating documentation at GitHub Pages.
*
* This value is used when adding dependency on the doclet when the plugin tasks
* are registered. Since the doclet dependency is required, its value passed as
* a parameter for the extension, rather than a property.
*/
internal lateinit var excludeInternalDocletVersion: String
internal companion object {
/** The name of the extension. */
const val name = "updateGitHubPages"
/** Creates a new extension and adds it to the passed project. */
fun createIn(project: Project): UpdateGitHubPagesExtension {
val factory = project.objects
val result = UpdateGitHubPagesExtension(
allowInternalJavadoc = factory.property(Boolean::class),
rootFolder = factory.property(File::class),
includeInputs = factory.setProperty(Any::class.java)
)
project.extensions.add(result.javaClass, name, result)
return result
}
}
/**
* Returns `true` if the `@Internal`-annotated code should be included into the
* generated documentation, `false` otherwise.
*/
fun allowInternalJavadoc(): Boolean {
return allowInternalJavadoc.get()
}
/**
* Returns the local root folder of the repository, to which the handled Gradle
* Project belongs.
*/
fun rootFolder(): File {
return rootFolder.get()
}
/**
* Returns the external inputs, which results should be included into the
* GitHub Pages update.
*/
fun includedInputs(): Set<Any> {
return includeInputs.get()
}
}
| buildSrc/src/main/kotlin/io/spine/internal/gradle/github/pages/UpdateGitHubPagesExtension.kt | 2016842938 |
package com.jereksel.libresubstratum.activities.detailed
import com.jereksel.libresubstratumlib.Type1Extension
import com.jereksel.libresubstratumlib.Type2Extension
import com.jereksel.libresubstratumlib.Type3Extension
sealed class DetailedResult {
data class ListLoaded(
val themeAppId: String,
val themeName: String,
val themes: List<Theme>,
val type3: Type3?
): DetailedResult() {
data class Theme(
val appId: String,
val name: String,
val type1a: Type1?,
val type1b: Type1?,
val type1c: Type1?,
val type2: Type2?
)
data class Type1(
val data: List<Type1Extension>
)
data class Type2(
val data: List<Type2Extension>
)
data class Type3(
val data: List<Type3Extension>
)
}
sealed class ChangeSpinnerSelection: DetailedResult() {
abstract val listPosition: Int
abstract val position: Int
data class ChangeType1aSpinnerSelection(override val listPosition: Int, override val position: Int): ChangeSpinnerSelection()
data class ChangeType1bSpinnerSelection(override val listPosition: Int, override val position: Int): ChangeSpinnerSelection()
data class ChangeType1cSpinnerSelection(override val listPosition: Int, override val position: Int): ChangeSpinnerSelection()
data class ChangeType2SpinnerSelection(override val listPosition: Int, override val position: Int): ChangeSpinnerSelection()
}
class ChangeType3SpinnerSelection(val position: Int): DetailedResult()
sealed class InstalledStateResult: DetailedResult() {
data class Result(
val targetApp: String,
val targetOverlayId: String,
val installedResult: DetailedViewState.InstalledState,
val enabledState: DetailedViewState.EnabledState
): InstalledStateResult()
data class PositionResult(
var position: Int
): InstalledStateResult()
data class AppIdResult(
val appId: String
): InstalledStateResult()
}
sealed class CompilationStatusResult: DetailedResult() {
abstract val appId: String
data class StartFlow(override val appId: String): CompilationStatusResult()
data class StartCompilation(override val appId: String): CompilationStatusResult()
data class StartInstallation(override val appId: String): CompilationStatusResult()
data class FailedCompilation(override val appId: String, val error: Throwable): CompilationStatusResult()
data class CleanError(override val appId: String): CompilationStatusResult()
data class EndFlow(override val appId: String): CompilationStatusResult()
}
class SelectAllResult: DetailedResult()
class DeselectAllResult: DetailedResult()
data class ToggleCheckbox(val position: Int, val state: Boolean): DetailedResult()
data class LongClickBasicResult(val position: Int, val compileMode: DetailedAction.CompileMode) : DetailedResult()
data class CompileSelectedResult(val compileMode: DetailedAction.CompileMode): DetailedResult()
data class ShowErrorResult(val message: String): DetailedResult()
} | app/src/main/kotlin/com/jereksel/libresubstratum/activities/detailed/DetailedResult.kt | 2734843377 |
package com.example.alexeyglushkov.cachemanager.disk.serializer
import com.example.alexeyglushkov.cachemanager.disk.DiskStorageMetadata
import com.example.alexeyglushkov.streamlib.data_readers_and_writers.InputStreamDataReader
import com.example.alexeyglushkov.streamlib.progress.ProgressUpdater
import com.example.alexeyglushkov.tools.ExceptionTools
import com.fasterxml.jackson.core.Version
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import java.io.BufferedInputStream
import java.io.IOException
import java.io.InputStream
/**
* Created by alexeyglushkov on 11.09.16.
*/
class DiskMetadataReader : InputStreamDataReader<DiskStorageMetadata?> {
private var stream: InputStream? = null
override fun beginRead(stream: InputStream) {
ExceptionTools.throwIfNull(stream, "DiskMetadataReader.beginRead: stream is null")
this.stream = BufferedInputStream(stream)
}
@Throws(Exception::class)
override fun closeRead() {
ExceptionTools.throwIfNull(stream, "DiskMetadataReader.close: stream is null")
stream!!.close()
}
@Throws(IOException::class)
override fun read(): DiskStorageMetadata? {
ExceptionTools.throwIfNull(stream, "DiskMetadataReader.read: stream is null")
var result: DiskStorageMetadata? = null
val md = SimpleModule("DiskMetadataModule", Version(1, 0, 0, null, null, null))
md.addDeserializer(DiskStorageMetadata::class.java, DiskMetadataDeserializer(DiskStorageMetadata::class.java))
val mapper = ObjectMapper()
mapper.registerModule(md)
result = mapper.readValue(stream, DiskStorageMetadata::class.java)
return result
}
override fun setProgressUpdater(progressUpdater: ProgressUpdater) {}
} | storagemanager/src/main/java/com/example/alexeyglushkov/cachemanager/disk/serializer/DiskMetadataReader.kt | 2085088496 |
package com.jforex.dzjforex.login.test
import arrow.effects.fix
import com.jforex.dzjforex.login.LoginApi.logout
import com.jforex.dzjforex.mock.test.getContextDependenciesForTest_IO
import com.jforex.dzjforex.mock.test.getPluginDependenciesForTest_IO
import com.jforex.dzjforex.zorro.LOGOUT_OK
import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.verify
private val pluginApi = getPluginDependenciesForTest_IO()
private val contextApi = getContextDependenciesForTest_IO()
class LoginTest : StringSpec() {
val username = "John_Doe"
val password = "123456"
val accountName = "JohnAccount42"
init {
/*"Login is OK when client is already connected" {
val accountType = demoLoginType
every { pluginApi.client.isConnected } returns (false)
every { contextApi.account.accountId } returns (accountName)
val loginResult = pluginApi
.brokerLogin(username = username, password = password, accountType = accountType)
.fix()
.unsafeRunSync()
verify(exactly = 1) { pluginApi.client.isConnected }
loginResult.returnCode shouldBe LOGIN_OK
loginResult.accountName shouldBe accountName
//confirmVerified(pluginApi.client)
}*/
/*"Login is called with correct parameters" {
val username = "John_Doe"
val password = "123456"
val accountType = demoLoginType
every { pluginApi.client.disconnect() } just Runs
val loginResult = pluginApi
.brokerLogin(username = username, password = password, accountType = accountType)
.fix()
.unsafeRunSync()
verify(exactly = 1) {
pluginApi.client.login(
match {
it.password == password && it.username == username
},
eq(LoginType.DEMO),
IO.monadDefer()
)
}
// logoutResult.shouldBe(LOGOUT_OK)
}*/
}
}
class LogoutTest : StringSpec() {
init {
"Disconnect is called on client instance" {
every { pluginApi.client.disconnect() } just Runs
val logoutResult = pluginApi
.logout()
.fix()
.unsafeRunSync()
verify(exactly = 1) { pluginApi.client.disconnect() }
logoutResult.shouldBe(LOGOUT_OK)
}
}
}
| java/dzjforex/src/test/kotlin/com/jforex/dzjforex/login/test/LoginTest.kt | 3278407015 |
package io.github.binout.soccer.infrastructure.persistence.mongo
import io.github.binout.soccer.domain.date.MatchDate
import io.github.binout.soccer.domain.player.Player
import io.github.binout.soccer.domain.player.PlayerName
import io.github.binout.soccer.domain.player.values
import io.github.binout.soccer.infrastructure.persistence.MongoConfiguration
import io.github.binout.soccer.infrastructure.persistence.MongoFriendlyMatchDateRepository
import io.github.binout.soccer.infrastructure.persistence.MongoPlayerRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.Month
class MongoFriendlyMatchDateRepositoryTest {
private lateinit var repository: MongoFriendlyMatchDateRepository
private lateinit var playerRepository: MongoPlayerRepository
@BeforeEach
fun initRepository() {
playerRepository = MongoPlayerRepository(MongoConfiguration("").database())
repository = MongoFriendlyMatchDateRepository(MongoConfiguration("").database())
}
@Test
fun should_persist_date_without_player() {
repository.replace(MatchDate.newDateForFriendly(2016, Month.APRIL, 1))
val matchDate = repository.byDate(2016, Month.APRIL, 1)
assertThat(matchDate).isNotNull
assertThat(matchDate!!.date).isEqualTo(LocalDate.of(2016, Month.APRIL, 1))
assertThat(matchDate.presents().count()).isZero()
}
@Test
fun should_persist_date_with_player() {
val benoit = Player(PlayerName("benoit"))
playerRepository.add(benoit)
val date = MatchDate.newDateForFriendly(2016, Month.APRIL, 1)
date.present(benoit)
repository.replace(date)
val matchDate = repository.byDate(2016, Month.APRIL, 1)
assertThat(matchDate).isNotNull
assertThat(matchDate!!.date).isEqualTo(LocalDate.of(2016, Month.APRIL, 1))
assertThat(matchDate.presents().values()).containsOnly("benoit")
}
} | src/test/kotlin/io/github/binout/soccer/infrastructure/persistence/mongo/MongoFriendlyMatchDateRepositoryTest.kt | 336630660 |
/*
* This file is part of BOINC.
* http://boinc.berkeley.edu
* Copyright (C) 2020 University of California
*
* BOINC is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation,
* either version 3 of the License, or (at your option) any later version.
*
* BOINC is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with BOINC. If not, see <http://www.gnu.org/licenses/>.
*/
package edu.berkeley.boinc.rpc
import android.os.Parcel
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class WorkUnitParcelableTest {
@Test
fun `Test Creator createFromParcel()`() {
val expected = WorkUnit()
val parcel = Parcel.obtain()
expected.writeToParcel(parcel, expected.describeContents())
// Reset parcel for reading.
parcel.setDataPosition(0)
val actual = WorkUnit.CREATOR.createFromParcel(parcel)
Assert.assertEquals(expected, actual)
}
@Test
fun `Test Creator newArray()`() {
val array = WorkUnit.CREATOR.newArray(2)
Assert.assertNotNull(array)
Assert.assertEquals(2, array.size)
}
}
| android/BOINC/app/src/test/java/edu/berkeley/boinc/rpc/WorkUnitParcelableTest.kt | 2581729230 |
package com.shareyourproxy.api.rx
import android.content.Context
import com.shareyourproxy.api.RestClient.getUserChannelService
import com.shareyourproxy.api.RestClient.getUserGroupService
import com.shareyourproxy.api.domain.factory.UserFactory.addUserChannel
import com.shareyourproxy.api.domain.factory.UserFactory.deleteUserChannel
import com.shareyourproxy.api.domain.model.Channel
import com.shareyourproxy.api.domain.model.User
import com.shareyourproxy.api.rx.command.eventcallback.EventCallback
import com.shareyourproxy.api.rx.command.eventcallback.UserChannelAddedEventCallback
import com.shareyourproxy.api.rx.command.eventcallback.UserChannelDeletedEventCallback
import rx.Observable
import rx.functions.Func1
/**
* Sync newChannel operations.
*/
object RxUserChannelSync {
fun saveUserChannel(
context: Context, oldUser: User, oldChannel: Channel?, newChannel: Channel): UserChannelAddedEventCallback {
return Observable.just(oldUser)
.map(putUserChannel(newChannel))
.map(addRealmUser(context))
.map(saveChannelToFirebase(context, newChannel))
.map(userChannelAddedEventCallback(oldChannel, newChannel))
.toBlocking().single()
}
fun deleteChannel(
context: Context, oldUser: User, channel: Channel, position: Int): EventCallback {
return Observable.just(oldUser).map(removeUserChannel(channel)).map(addRealmUser(context)).map(deleteChannelFromFirebase(context, channel)).map(userChannelDeletedEventCallback(channel, position)).toBlocking().single()
}
private fun addRealmUser(context: Context): Func1<User, User> {
return Func1 { user ->
RxHelper.updateRealmUser(context, user)
user
}
}
/**
* Add the new channel to the users channel list and all groups.
* @param newChannel
* @return
*/
private fun putUserChannel(newChannel: Channel): Func1<User, User> {
return Func1 { oldUser ->
val newUser = addUserChannel(oldUser, newChannel)
newUser
}
}
private fun saveChannelToFirebase(
context: Context, channel: Channel): Func1<User, User> {
return Func1 { user ->
val userId = user.id()
val channelId = channel.id()
getUserChannelService(context).addUserChannel(userId, channelId, channel).subscribe()
getUserGroupService(context).updateUserGroups(userId, user.groups()).subscribe()
user
}
}
private fun userChannelAddedEventCallback(
oldChannel: Channel?, newChannel: Channel): Func1<User, UserChannelAddedEventCallback> {
return Func1 { user -> UserChannelAddedEventCallback(user, oldChannel, newChannel) }
}
private fun removeUserChannel(channel: Channel): Func1<User, User> {
return Func1 { oldUser ->
val newUser = deleteUserChannel(oldUser, channel)
newUser
}
}
private fun deleteChannelFromFirebase(
context: Context, channel: Channel): Func1<User, User> {
return Func1 { user ->
val userId = user.id()
val channelId = channel.id()
getUserChannelService(context).deleteUserChannel(userId, channelId).subscribe()
getUserGroupService(context).updateUserGroups(userId, user.groups()).subscribe()
user
}
}
private fun userChannelDeletedEventCallback(
channel: Channel, position: Int): Func1<User, EventCallback> {
return Func1 { user -> UserChannelDeletedEventCallback(user, channel, position) }
}
}
| Application/src/main/kotlin/com/shareyourproxy/api/rx/RxUserChannelSync.kt | 4145106889 |
package io.mockk.impl.verify
import io.mockk.MockKGateway
import io.mockk.MockKGateway.VerificationParameters
import io.mockk.MockKGateway.VerificationResult
import io.mockk.RecordedCall
import io.mockk.impl.log.SafeToString
import io.mockk.impl.stub.StubRepository
import io.mockk.impl.verify.VerificationHelpers.allInvocations
import io.mockk.impl.verify.VerificationHelpers.reportCalls
class SequenceCallVerifier(
val stubRepo: StubRepository,
val safeToString: SafeToString
) : MockKGateway.CallVerifier {
private val captureBlocks = mutableListOf<() -> Unit>()
override fun verify(
verificationSequence: List<RecordedCall>,
params: VerificationParameters
): VerificationResult {
val allCalls = verificationSequence.allInvocations(stubRepo)
if (allCalls.size != verificationSequence.size) {
return VerificationResult.Failure(safeToString.exec {
"number of calls happened not matching exact number of verification sequence" + reportCalls(
verificationSequence,
allCalls
)
})
}
for ((i, call) in allCalls.withIndex()) {
val matcher = verificationSequence[i].matcher
if (!matcher.match(call)) {
return VerificationResult.Failure(safeToString.exec {
"calls are not exactly matching verification sequence" + reportCalls(verificationSequence,
allCalls)
})
}
captureBlocks.add { matcher.captureAnswer(call) }
}
return VerificationResult.OK(allCalls)
}
override fun captureArguments() {
captureBlocks.forEach { it() }
}
} | modules/mockk/src/commonMain/kotlin/io/mockk/impl/verify/SequenceCallVerifier.kt | 2006035559 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.