repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
angelolloqui/SwiftKotlin
Assets/Tests/KotlinTokenizer/lambdas.kt
1
628
userService.updateUser(picture = picture).always { this.hasPhoto = true } userService.autoLinkTenant(tenantId = tenant.id).then { _ -> this.startPayment(paymentMethod, true) }.catchError { _ -> val intent = this.coordinator.autoRegisterIntent(tenant = tenant, onComplete = { this.startPayment(paymentMethod, true) }) this.navigationManager.show(intent, animation = .push) } item.selectCallback = { option -> presenter.selectPaymentMethod(option) } item.selectCallback?.invoke(option) item.selectCallback!!.invoke(option) ints.map { if (it == 0) { return@map "zero" } "non zero" }
mit
1d50efccc80c16eb8cda2e20bc09045a
30.4
126
0.694268
3.609195
false
false
false
false
Waboodoo/HTTP-Shortcuts
HTTPShortcuts/app/src/main/kotlin/ch/rmy/android/http_shortcuts/utils/ExternalURLs.kt
1
1188
package ch.rmy.android.http_shortcuts.utils object ExternalURLs { const val SHORTCUTS_DOCUMENTATION = "https://http-shortcuts.rmy.ch/shortcuts" const val CATEGORIES_DOCUMENTATION = "https://http-shortcuts.rmy.ch/categories" const val VARIABLES_DOCUMENTATION = "https://http-shortcuts.rmy.ch/variables" const val SCRIPTING_DOCUMENTATION = "https://http-shortcuts.rmy.ch/scripting#scripting" const val IMPORT_EXPORT_DOCUMENTATION = "https://http-shortcuts.rmy.ch/import-export" const val PRIVACY_POLICY = "https://http-shortcuts.rmy.ch/privacy-policy" const val DOCUMENTATION_PAGE = "https://http-shortcuts.rmy.ch/documentation" const val DONATION_PAGE = "https://http-shortcuts.rmy.ch/support-me#donate" const val PLAY_STORE = "https://play.google.com/store/apps/details?id=ch.rmy.android.http_shortcuts" const val F_DROID = "https://f-droid.org/en/packages/ch.rmy.android.http_shortcuts/" const val GITHUB = "https://github.com/Waboodoo/HTTP-Shortcuts" const val TRANSLATION = "https://poeditor.com/join/project/8tHhwOTzVZ" fun getScriptingDocumentation(docRef: String) = "https://http-shortcuts.rmy.ch/scripting#$docRef" }
mit
ad4bedf69b812c9dbc0cc47a66187250
55.571429
104
0.742424
3.463557
false
false
false
false
aosp-mirror/platform_frameworks_support
room/integration-tests/kotlintestapp/src/androidTest/java/androidx/room/integration/kotlintestapp/vo/BookWithJavaEntity.kt
1
939
/* * Copyright (C) 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.room.integration.kotlintestapp.vo import androidx.room.Embedded import androidx.room.Relation class BookWithJavaEntity { @Embedded var book: Book? = null @Relation(parentColumn = "bookId", entityColumn = "bookId", entity=JavaEntity::class) var javaEntities: List<JavaEntity>? = null }
apache-2.0
d200d1f3ec3925928c8791da2cc34a0e
35.153846
89
0.743344
4.173333
false
false
false
false
koma-im/koma
src/main/kotlin/link/continuum/desktop/gui/list/user/dataStore.kt
1
2675
package link.continuum.desktop.gui.list.user import javafx.scene.paint.Color import koma.gui.element.icon.placeholder.generator.hashStringColorDark import koma.matrix.UserId import koma.network.media.MHUrl import koma.network.media.parseMxc import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.Flow import link.continuum.database.models.getLatestAvatar import link.continuum.database.models.getLatestNick import link.continuum.database.models.saveUserAvatar import link.continuum.database.models.saveUserNick import link.continuum.desktop.database.KDataStore import link.continuum.desktop.database.LatestFlowMap import link.continuum.desktop.gui.icon.avatar.AvatarView import link.continuum.desktop.gui.util.UiPool import mu.KotlinLogging import java.util.concurrent.ConcurrentHashMap private val logger = KotlinLogging.logger {} @ExperimentalCoroutinesApi class UserDataStore( val data: KDataStore ) { val avatarPool = UiPool { AvatarView(this) } val latestNames = LatestFlowMap( save = { userId: UserId, s: String?, l: Long -> s?.let { data.runOp { saveUserNick(this, userId, it, l) } } }, init = { data.runOp { getLatestNick(this, it) }?.let { it.since to it.nickname } ?: 0L to null }) suspend fun updateName(userId: UserId, name: String, time: Long) { latestNames.update(userId, name, time) } private val color = ConcurrentHashMap<UserId, Color>() fun getUserColor(userId: UserId): Color { return color.computeIfAbsent(userId) { hashStringColorDark(it.str) } } fun getNameUpdates(userId: UserId): Flow<String?> { return latestNames.receiveUpdates(userId) } val latestAvatarUrls = LatestFlowMap( save = { userId: UserId, url: MHUrl?, l: Long -> url?.let { data.runOp { saveUserAvatar(this, userId, it.toString(), l) } } }, init = { val n = data.runOp { getLatestAvatar(this, it) } val a = n?.avatar?.parseMxc() if (n != null && a != null) { n.since to a } else 0L to null }) suspend fun updateAvatarUrl(userId: UserId, avatarUrl: MHUrl, time: Long) { latestAvatarUrls.update(userId, avatarUrl, time) } fun getAvatarUrlUpdates(userId: UserId): Flow<MHUrl?> { return latestAvatarUrls.receiveUpdates(userId) } }
gpl-3.0
20385b361fb4b2791f4f7691a29e6ebf
35.643836
79
0.624299
4.436153
false
true
false
false
aosp-mirror/platform_frameworks_support
jetifier/jetifier/processor/src/main/kotlin/com/android/tools/build/jetifier/processor/transform/pom/PomDocument.kt
1
6605
/* * Copyright 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.build.jetifier.processor.transform.pom import com.android.tools.build.jetifier.core.pom.PomDependency import com.android.tools.build.jetifier.core.pom.PomRewriteRule import com.android.tools.build.jetifier.core.utils.Log import com.android.tools.build.jetifier.processor.archive.ArchiveFile import com.android.tools.build.jetifier.processor.transform.TransformationContext import org.jdom2.Document import org.jdom2.Element /** * Wraps a single POM XML [ArchiveFile] with parsed metadata about transformation related sections. */ class PomDocument(val file: ArchiveFile, private val document: Document) { companion object { private const val TAG = "Pom" fun loadFrom(file: ArchiveFile): PomDocument { val document = XmlUtils.createDocumentFromByteArray(file.data) val pomDoc = PomDocument(file, document) pomDoc.initialize() return pomDoc } } val dependencies: MutableSet<PomDependency> = mutableSetOf() private val properties: MutableMap<String, String> = mutableMapOf() private var dependenciesGroup: Element? = null private var hasChanged: Boolean = false private fun initialize() { val propertiesGroup = document.rootElement .getChild("properties", document.rootElement.namespace) if (propertiesGroup != null) { propertiesGroup.children .filterNot { it.value.isNullOrEmpty() } .forEach { properties[it.name] = it.value } } dependenciesGroup = document.rootElement .getChild("dependencies", document.rootElement.namespace) ?: return dependenciesGroup!!.children.mapTo(dependencies) { XmlUtils.createDependencyFrom(it, properties) } } /** * Validates that this document is consistent with the provided [rules]. * * Currently it checks that all the dependencies that are going to be rewritten by the given * rules satisfy the minimal version requirements defined by the rules. */ fun validate(rules: Set<PomRewriteRule>): Boolean { if (dependenciesGroup == null) { // Nothing to validate as this file has no dependencies section return true } return dependencies.all { dep -> rules.all { it.validateVersion(dep) } } } /** * Applies the given [rules] to rewrite the POM file. * * Changes are not saved back until requested. */ fun applyRules(context: TransformationContext) { tryRewriteOwnArtifactInfo(context) if (dependenciesGroup == null) { // Nothing to transform as this file has no dependencies section return } val newDependencies = mutableSetOf<PomDependency>() for (dependency in dependencies) { newDependencies.add(mapDependency(dependency, context)) } if (newDependencies.isEmpty()) { return } dependenciesGroup!!.children.clear() newDependencies.forEach { dependenciesGroup!!.addContent(it.toXmlElement(document)) } hasChanged = true } fun getAsPomDependency(): PomDependency { val groupIdNode = document.rootElement .getChild("groupId", document.rootElement.namespace) val artifactIdNode = document.rootElement .getChild("artifactId", document.rootElement.namespace) val version = document.rootElement .getChild("version", document.rootElement.namespace) return PomDependency(groupIdNode.text, artifactIdNode.text, version.text) } private fun tryRewriteOwnArtifactInfo(context: TransformationContext) { val groupIdNode = document.rootElement .getChild("groupId", document.rootElement.namespace) val artifactIdNode = document.rootElement .getChild("artifactId", document.rootElement.namespace) val version = document.rootElement .getChild("version", document.rootElement.namespace) if (groupIdNode == null || artifactIdNode == null || version == null) { return } val dependency = PomDependency(groupIdNode.text, artifactIdNode.text, version.text) val newDependency = mapDependency(dependency, context) if (newDependency != dependency) { groupIdNode.text = newDependency.groupId artifactIdNode.text = newDependency.artifactId version.text = newDependency.version hasChanged = true } } private fun mapDependency( dependency: PomDependency, context: TransformationContext ): PomDependency { val rule = context.config.pomRewriteRules.firstOrNull { it.matches(dependency) } if (rule != null) { // Replace with new dependencies return rule.to.rewrite(dependency, context.versions) } val matchesPrefix = context.config.restrictToPackagePrefixesWithDots.any { dependency.groupId!!.startsWith(it) } if (matchesPrefix) { context.reportNoPackageMappingFoundFailure( TAG, dependency.toStringNotation(), file.relativePath.toString()) } // No rule to rewrite => keep it return dependency } /** * Saves any current pending changes back to the file if needed. */ fun saveBackToFileIfNeeded() { if (!hasChanged) { return } file.setNewData(XmlUtils.convertDocumentToByteArray(document)) } /** * Logs the information about the current file using info level. */ fun logDocumentDetails() { Log.i(TAG, "POM file at: '%s'", file.relativePath) for ((groupId, artifactId, version) in dependencies) { Log.v(TAG, "- Dep: %s:%s:%s", groupId, artifactId, version) } } }
apache-2.0
7a2441918c09cc5e98f4aed1a7c806a8
34.708108
99
0.653899
4.899852
false
false
false
false
sisbell/oulipo
oulipo-machine-browser/src/main/java/org/oulipo/browser/api/BaseExtension.kt
1
3314
/******************************************************************************* * OulipoMachine licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. See the NOTICE file distributed with this work for * additional information regarding copyright ownership. */ package org.oulipo.browser.api import javafx.event.ActionEvent import javafx.event.EventHandler import javafx.scene.control.Menu import javafx.scene.control.MenuItem import javafx.scene.control.SeparatorMenuItem import org.oulipo.browser.api.MenuContext.Type abstract class BaseExtension : Extension { fun addMenu(ctx: BrowserContext, text: String, type: Type): Menu { val menu = Menu() menu.text = text if (Type.BOOKMARK == type) { ctx.menuContext.bookmarkMenu.items.add(menu) } else if (Type.FILE == type) { ctx.menuContext.fileMenu.items.add(menu) } else if (Type.HISTORY == type) { ctx.menuContext.historyMenu.items.add(menu) } else if (Type.MANAGER == type) { ctx.menuContext.managerMenu.items.add(menu) } else if (Type.PEOPLE == type) { ctx.menuContext.peopleMenu.items.add(menu) } else if (Type.TOOLS == type) { ctx.menuContext.toolsMenu.items.add(menu) } return menu } fun addMenuItem(ctx: BrowserContext, text: String, type: Type, e: EventHandler<ActionEvent>): MenuItem { val item = MenuItem() item.text = text item.onAction = e if (Type.BOOKMARK == type) { ctx.menuContext.bookmarkMenu.items.add(item) } else if (Type.FILE == type) { ctx.menuContext.fileMenu.items.add(item) } else if (Type.HISTORY == type) { ctx.menuContext.historyMenu.items.add(item) } else if (Type.MANAGER == type) { ctx.menuContext.managerMenu.items.add(item) } else if (Type.PEOPLE == type) { ctx.menuContext.peopleMenu.items.add(item) } else if (Type.TOOLS == type) { ctx.menuContext.toolsMenu.items.add(item) } return item } fun addSeparator(ctx: BrowserContext, type: Type) { val item = SeparatorMenuItem() if (Type.BOOKMARK == type) { ctx.menuContext.bookmarkMenu.items.add(item) } else if (Type.FILE == type) { ctx.menuContext.fileMenu.items.add(item) } else if (Type.HISTORY == type) { ctx.menuContext.historyMenu.items.add(item) } else if (Type.MANAGER == type) { ctx.menuContext.managerMenu.items.add(item) } else if (Type.PEOPLE == type) { ctx.menuContext.peopleMenu.items.add(item) } else if (Type.TOOLS == type) { ctx.menuContext.toolsMenu.items.add(item) } } }
apache-2.0
e80f4b005e3ad3ec962f6e6074f5bbc6
39.414634
108
0.624623
3.968862
false
false
false
false
square/sqldelight
sqldelight-compiler/src/test/kotlin/com/squareup/sqldelight/core/queries/SelectQueryFunctionTest.kt
1
49959
package com.squareup.sqldelight.core.queries import com.alecstrong.sql.psi.core.DialectPreset import com.google.common.truth.Truth.assertThat import com.squareup.burst.BurstJUnit4 import com.squareup.kotlinpoet.ParameterSpec import com.squareup.kotlinpoet.asTypeName import com.squareup.sqldelight.core.compiler.SelectQueryGenerator import com.squareup.sqldelight.core.dialects.intType import com.squareup.sqldelight.test.util.FixtureCompiler import org.junit.Assume.assumeTrue import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import org.junit.runner.RunWith @RunWith(BurstJUnit4::class) class SelectQueryFunctionTest { @get:Rule val tempFolder = TemporaryFolder() @Test fun `query function with default result type generates properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER NOT NULL, | value TEXT NOT NULL |); | |selectForId: |SELECT * |FROM data |WHERE id = ?; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun selectForId(id: kotlin.Long): com.squareup.sqldelight.Query<com.example.Data_> = selectForId(id) { id_, value -> | com.example.Data_( | id_, | value | ) |} |""".trimMargin() ) } @Test fun `infer type for between`() { val file = FixtureCompiler.parseSql( """ |import com.example.LocalDateTime; | |CREATE TABLE data ( | channelId TEXT NOT NULL, | startTime INTEGER AS LocalDateTime NOT NULL, | endTime INTEGER AS LocalDateTime NOT NULL |); | |selectByChannelId: |SELECT * |FROM data |WHERE channelId =? |AND ( | startTime BETWEEN :from AND :to | OR | endTime BETWEEN :from AND :to | OR | :from BETWEEN startTime AND endTime | OR | :to BETWEEN startTime AND endTime |); |""".trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun selectByChannelId( | channelId: kotlin.String, | from: com.example.LocalDateTime, | to: com.example.LocalDateTime |): com.squareup.sqldelight.Query<com.example.Data_> = selectByChannelId(channelId, from, to) { channelId_, startTime, endTime -> | com.example.Data_( | channelId_, | startTime, | endTime | ) |} |""".trimMargin() ) } @Test fun `query bind args appear in the correct order`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER NOT NULL, | value TEXT NOT NULL |); | |select: |SELECT * |FROM data |WHERE id = ?2 |AND value = ?1; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun select(value: kotlin.String, id: kotlin.Long): com.squareup.sqldelight.Query<com.example.Data_> = select(value, id) { id_, value_ -> | com.example.Data_( | id_, | value_ | ) |} |""".trimMargin() ) } @Test fun `query function with custom result type generates properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER NOT NULL, | value TEXT NOT NULL |); | |selectForId: |SELECT * |FROM data |WHERE id = ?; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectForId(id: kotlin.Long, mapper: (id: kotlin.Long, value: kotlin.String) -> T): com.squareup.sqldelight.Query<T> = SelectForIdQuery(id) { cursor -> | mapper( | cursor.getLong(0)!!, | cursor.getString(1)!! | ) |} | """.trimMargin() ) } @Test fun `custom result type query function uses adapter`() { val file = FixtureCompiler.parseSql( """ |import kotlin.collections.List; | |CREATE TABLE data ( | id INTEGER NOT NULL, | value TEXT AS List NOT NULL |); | |selectForId: |SELECT * |FROM data |WHERE id = ?; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectForId(id: kotlin.Long, mapper: (id: kotlin.Long, value: kotlin.collections.List) -> T): com.squareup.sqldelight.Query<T> = SelectForIdQuery(id) { cursor -> | mapper( | cursor.getLong(0)!!, | database.data_Adapter.valueAdapter.decode(cursor.getString(1)!!) | ) |} | """.trimMargin() ) } @Test fun `multiple values types are folded into proper result type`() { val file = FixtureCompiler.parseSql( """ |selectValues: |VALUES (1), ('sup'); """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.customResultTypeFunction().toString()).contains( """ |override fun selectValues(): com.squareup.sqldelight.Query<kotlin.String> """.trimMargin() ) } @Test fun `query with no parameters doesn't subclass Query`() { val file = FixtureCompiler.parseSql( """ |import kotlin.collections.List; | |CREATE TABLE data ( | id INTEGER NOT NULL, | value TEXT AS List NOT NULL |); | |selectForId: |SELECT * |FROM data; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectForId(mapper: (id: kotlin.Long, value: kotlin.collections.List) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, selectForId, driver, "Test.sq", "selectForId", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getLong(0)!!, | database.data_Adapter.valueAdapter.decode(cursor.getString(1)!!) | ) |} |""".trimMargin() ) } @Test fun `integer primary key is always exposed as non-null`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER PRIMARY KEY |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun selectData(): com.squareup.sqldelight.Query<kotlin.Long> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | cursor.getLong(0)!! |} | """.trimMargin() ) } @Test fun `bind parameter used in IN expression explodes into multiple query args`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER NOT NULL |); | |selectForId: |SELECT * |FROM data |WHERE id IN :good AND id NOT IN :bad; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.querySubtype().toString()).isEqualTo( """ |private inner class SelectForIdQuery<out T : kotlin.Any>( | @kotlin.jvm.JvmField | public val good: kotlin.collections.Collection<kotlin.Long>, | @kotlin.jvm.JvmField | public val bad: kotlin.collections.Collection<kotlin.Long>, | mapper: (com.squareup.sqldelight.db.SqlCursor) -> T |) : com.squareup.sqldelight.Query<T>(selectForId, mapper) { | public override fun execute(): com.squareup.sqldelight.db.SqlCursor { | val goodIndexes = createArguments(count = good.size) | val badIndexes = createArguments(count = bad.size) | return driver.executeQuery(null, ""${'"'} | |SELECT * | |FROM data | |WHERE id IN ${"$"}goodIndexes AND id NOT IN ${"$"}badIndexes | ""${'"'}.trimMargin(), good.size + bad.size) { | good.forEachIndexed { index, good_ -> | bindLong(index + 1, good_) | } | bad.forEachIndexed { index, bad_ -> | bindLong(index + good.size + 1, bad_) | } | } | } | | public override fun toString(): kotlin.String = "Test.sq:selectForId" |} | """.trimMargin() ) } @Test fun `limit and offset bind expressions gets proper types`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | some_column INTEGER NOT NULL, | some_column2 INTEGER NOT NULL |); | |someSelect: |SELECT * |FROM data |WHERE EXISTS (SELECT * FROM data LIMIT :minimum OFFSET :offset) |LIMIT :minimum; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun someSelect(minimum: kotlin.Long, offset: kotlin.Long): com.squareup.sqldelight.Query<com.example.Data_> = someSelect(minimum, offset) { some_column, some_column2 -> | com.example.Data_( | some_column, | some_column2 | ) |} |""".trimMargin() ) } @Test fun `boolean column mapper from result set properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | id INTEGER PRIMARY KEY, | value INTEGER AS Boolean |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectData(mapper: (id: kotlin.Long, value: kotlin.Boolean?) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getLong(0)!!, | cursor.getLong(1)?.let { it == 1L } | ) |} | """.trimMargin() ) } @Test fun `named bind arg can be reused`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE person ( | _id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | first_name TEXT NOT NULL, | last_name TEXT NOT NULL |); | |equivalentNamesNamed: |SELECT * |FROM person |WHERE first_name = :name AND last_name = :name; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.querySubtype().toString()).isEqualTo( """ |private inner class EquivalentNamesNamedQuery<out T : kotlin.Any>( | @kotlin.jvm.JvmField | public val name: kotlin.String, | mapper: (com.squareup.sqldelight.db.SqlCursor) -> T |) : com.squareup.sqldelight.Query<T>(equivalentNamesNamed, mapper) { | public override fun execute(): com.squareup.sqldelight.db.SqlCursor = driver.executeQuery(${query.id}, ""${'"'} | |SELECT * | |FROM person | |WHERE first_name = ? AND last_name = ? | ""${'"'}.trimMargin(), 2) { | bindString(1, name) | bindString(2, name) | } | | public override fun toString(): kotlin.String = "Test.sq:equivalentNamesNamed" |} | """.trimMargin() ) } @Test fun `real is exposed properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | value REAL NOT NULL |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun selectData(): com.squareup.sqldelight.Query<kotlin.Double> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | cursor.getDouble(0)!! |} | """.trimMargin() ) } @Test fun `blob is exposed properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | value BLOB NOT NULL |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun selectData(): com.squareup.sqldelight.Query<kotlin.ByteArray> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | cursor.getBytes(0)!! |} | """.trimMargin() ) } @Test fun `null is exposed properly`() { val file = FixtureCompiler.parseSql( """ |selectData: |SELECT NULL; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectData(mapper: (expr: java.lang.Void?) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", "SELECT NULL") { cursor -> | mapper( | null | ) |} | """.trimMargin() ) } @Test fun `types are exposed properly in HSQL`(dialect: DialectPreset) { assumeTrue(dialect == DialectPreset.HSQL) val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | boolean0 BOOLEAN NOT NULL, | boolean1 BOOLEAN, | boolean2 BOOLEAN AS kotlin.String NOT NULL, | boolean3 BOOLEAN AS kotlin.String, | tinyint0 TINYINT NOT NULL, | tinyint1 TINYINT, | tinyint2 TINYINT AS kotlin.String NOT NULL, | tinyint3 TINYINT AS kotlin.String, | smallint0 SMALLINT NOT NULL, | smallint1 SMALLINT, | smallint2 SMALLINT AS kotlin.String NOT NULL, | smallint3 SMALLINT AS kotlin.String, | int0 ${dialect.intType} NOT NULL, | int1 ${dialect.intType}, | int2 ${dialect.intType} AS kotlin.String NOT NULL, | int3 ${dialect.intType} AS kotlin.String, | bigint0 BIGINT NOT NULL, | bigint1 BIGINT, | bigint2 BIGINT AS kotlin.String NOT NULL, | bigint3 BIGINT AS kotlin.String |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder, dialectPreset = dialect ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectData(mapper: ( | boolean0: kotlin.Boolean, | boolean1: kotlin.Boolean?, | boolean2: kotlin.String, | boolean3: kotlin.String?, | tinyint0: kotlin.Byte, | tinyint1: kotlin.Byte?, | tinyint2: kotlin.String, | tinyint3: kotlin.String?, | smallint0: kotlin.Short, | smallint1: kotlin.Short?, | smallint2: kotlin.String, | smallint3: kotlin.String?, | int0: kotlin.Int, | int1: kotlin.Int?, | int2: kotlin.String, | int3: kotlin.String?, | bigint0: kotlin.Long, | bigint1: kotlin.Long?, | bigint2: kotlin.String, | bigint3: kotlin.String? |) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getLong(0)!! == 1L, | cursor.getLong(1)?.let { it == 1L }, | database.data_Adapter.boolean2Adapter.decode(cursor.getLong(2)!! == 1L), | cursor.getLong(3)?.let { database.data_Adapter.boolean3Adapter.decode(it == 1L) }, | cursor.getLong(4)!!.toByte(), | cursor.getLong(5)?.toByte(), | database.data_Adapter.tinyint2Adapter.decode(cursor.getLong(6)!!.toByte()), | cursor.getLong(7)?.let { database.data_Adapter.tinyint3Adapter.decode(it.toByte()) }, | cursor.getLong(8)!!.toShort(), | cursor.getLong(9)?.toShort(), | database.data_Adapter.smallint2Adapter.decode(cursor.getLong(10)!!.toShort()), | cursor.getLong(11)?.let { database.data_Adapter.smallint3Adapter.decode(it.toShort()) }, | cursor.getLong(12)!!.toInt(), | cursor.getLong(13)?.toInt(), | database.data_Adapter.int2Adapter.decode(cursor.getLong(14)!!.toInt()), | cursor.getLong(15)?.let { database.data_Adapter.int3Adapter.decode(it.toInt()) }, | cursor.getLong(16)!!, | cursor.getLong(17), | database.data_Adapter.bigint2Adapter.decode(cursor.getLong(18)!!), | cursor.getLong(19)?.let { database.data_Adapter.bigint3Adapter.decode(it) } | ) |} | """.trimMargin() ) } @Test fun `types are exposed properly in MySQL`(dialect: DialectPreset) { assumeTrue(dialect == DialectPreset.MYSQL) val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | boolean0 BOOLEAN NOT NULL, | boolean1 BOOLEAN, | boolean2 BOOLEAN AS kotlin.String NOT NULL, | boolean3 BOOLEAN AS kotlin.String, | bit0 BIT NOT NULL, | bit1 BIT, | bit2 BIT AS kotlin.String NOT NULL, | bit3 BIT AS kotlin.String, | tinyint0 TINYINT NOT NULL, | tinyint1 TINYINT, | tinyint2 TINYINT AS kotlin.String NOT NULL, | tinyint3 TINYINT AS kotlin.String, | smallint0 SMALLINT NOT NULL, | smallint1 SMALLINT, | smallint2 SMALLINT AS kotlin.String NOT NULL, | smallint3 SMALLINT AS kotlin.String, | int0 ${dialect.intType} NOT NULL, | int1 ${dialect.intType}, | int2 ${dialect.intType} AS kotlin.String NOT NULL, | int3 ${dialect.intType} AS kotlin.String, | bigint0 BIGINT NOT NULL, | bigint1 BIGINT, | bigint2 BIGINT AS kotlin.String NOT NULL, | bigint3 BIGINT AS kotlin.String |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder, dialectPreset = dialect ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectData(mapper: ( | boolean0: kotlin.Boolean, | boolean1: kotlin.Boolean?, | boolean2: kotlin.String, | boolean3: kotlin.String?, | bit0: kotlin.Boolean, | bit1: kotlin.Boolean?, | bit2: kotlin.String, | bit3: kotlin.String?, | tinyint0: kotlin.Byte, | tinyint1: kotlin.Byte?, | tinyint2: kotlin.String, | tinyint3: kotlin.String?, | smallint0: kotlin.Short, | smallint1: kotlin.Short?, | smallint2: kotlin.String, | smallint3: kotlin.String?, | int0: kotlin.Int, | int1: kotlin.Int?, | int2: kotlin.String, | int3: kotlin.String?, | bigint0: kotlin.Long, | bigint1: kotlin.Long?, | bigint2: kotlin.String, | bigint3: kotlin.String? |) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getLong(0)!! == 1L, | cursor.getLong(1)?.let { it == 1L }, | database.data_Adapter.boolean2Adapter.decode(cursor.getLong(2)!! == 1L), | cursor.getLong(3)?.let { database.data_Adapter.boolean3Adapter.decode(it == 1L) }, | cursor.getLong(4)!! == 1L, | cursor.getLong(5)?.let { it == 1L }, | database.data_Adapter.bit2Adapter.decode(cursor.getLong(6)!! == 1L), | cursor.getLong(7)?.let { database.data_Adapter.bit3Adapter.decode(it == 1L) }, | cursor.getLong(8)!!.toByte(), | cursor.getLong(9)?.toByte(), | database.data_Adapter.tinyint2Adapter.decode(cursor.getLong(10)!!.toByte()), | cursor.getLong(11)?.let { database.data_Adapter.tinyint3Adapter.decode(it.toByte()) }, | cursor.getLong(12)!!.toShort(), | cursor.getLong(13)?.toShort(), | database.data_Adapter.smallint2Adapter.decode(cursor.getLong(14)!!.toShort()), | cursor.getLong(15)?.let { database.data_Adapter.smallint3Adapter.decode(it.toShort()) }, | cursor.getLong(16)!!.toInt(), | cursor.getLong(17)?.toInt(), | database.data_Adapter.int2Adapter.decode(cursor.getLong(18)!!.toInt()), | cursor.getLong(19)?.let { database.data_Adapter.int3Adapter.decode(it.toInt()) }, | cursor.getLong(20)!!, | cursor.getLong(21), | database.data_Adapter.bigint2Adapter.decode(cursor.getLong(22)!!), | cursor.getLong(23)?.let { database.data_Adapter.bigint3Adapter.decode(it) } | ) |} | """.trimMargin() ) } @Test fun `types are exposed properly in PostgreSQL`(dialect: DialectPreset) { assumeTrue(dialect == DialectPreset.POSTGRESQL) val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | smallint0 SMALLINT NOT NULL, | smallint1 SMALLINT, | smallint2 SMALLINT AS kotlin.String NOT NULL, | smallint3 SMALLINT AS kotlin.String, | int0 ${dialect.intType} NOT NULL, | int1 ${dialect.intType}, | int2 ${dialect.intType} AS kotlin.String NOT NULL, | int3 ${dialect.intType} AS kotlin.String, | bigint0 BIGINT NOT NULL, | bigint1 BIGINT, | bigint2 BIGINT AS kotlin.String NOT NULL, | bigint3 BIGINT AS kotlin.String |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder, dialectPreset = dialect ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectData(mapper: ( | smallint0: kotlin.Short, | smallint1: kotlin.Short?, | smallint2: kotlin.String, | smallint3: kotlin.String?, | int0: kotlin.Int, | int1: kotlin.Int?, | int2: kotlin.String, | int3: kotlin.String?, | bigint0: kotlin.Long, | bigint1: kotlin.Long?, | bigint2: kotlin.String, | bigint3: kotlin.String? |) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getLong(0)!!.toShort(), | cursor.getLong(1)?.toShort(), | database.data_Adapter.smallint2Adapter.decode(cursor.getLong(2)!!.toShort()), | cursor.getLong(3)?.let { database.data_Adapter.smallint3Adapter.decode(it.toShort()) }, | cursor.getLong(4)!!.toInt(), | cursor.getLong(5)?.toInt(), | database.data_Adapter.int2Adapter.decode(cursor.getLong(6)!!.toInt()), | cursor.getLong(7)?.let { database.data_Adapter.int3Adapter.decode(it.toInt()) }, | cursor.getLong(8)!!, | cursor.getLong(9), | database.data_Adapter.bigint2Adapter.decode(cursor.getLong(10)!!), | cursor.getLong(11)?.let { database.data_Adapter.bigint3Adapter.decode(it) } | ) |} | """.trimMargin() ) } @Test fun `non null boolean is exposed properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | value INTEGER AS Boolean NOT NULL |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun selectData(): com.squareup.sqldelight.Query<kotlin.Boolean> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | cursor.getLong(0)!! == 1L |} | """.trimMargin() ) } @Test fun `nonnull int is computed properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | value INTEGER AS Int NOT NULL |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun selectData(): com.squareup.sqldelight.Query<kotlin.Int> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | cursor.getLong(0)!!.toInt() |} | """.trimMargin() ) } @Test fun `nullable int is computed properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | value INTEGER AS Int |); | |selectData: |SELECT * |FROM data; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectData(mapper: (value: kotlin.Int?) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, selectData, driver, "Test.sq", "selectData", ""${'"'} ||SELECT * ||FROM data |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getLong(0)?.toInt() | ) |} | """.trimMargin() ) } @Test fun `query returns custom query type`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE data ( | value INTEGER, | value2 INTEGER |); | |selectData: |SELECT coalesce(value, value2), value, value2 |FROM data; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun selectData(): com.squareup.sqldelight.Query<com.example.SelectData> = selectData { coalesce, value, value2 -> | com.example.SelectData( | coalesce, | value, | value2 | ) |} |""".trimMargin() ) } @Test fun `optional parameter with type inferred from case expression`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE a ( | name TEXT NOT NULL |); | |broken: |SELECT a.name |FROM a |WHERE | :input IS NULL | OR :input = | CASE name | WHEN 'a' THEN 'b' | ELSE name | END; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun broken(input: kotlin.String?): com.squareup.sqldelight.Query<kotlin.String> = BrokenQuery(input) { cursor -> | cursor.getString(0)!! |} | """.trimMargin() ) } @Test fun `projection with more columns than there are runtime Function types`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE bigTable ( | val1 INTEGER, | val2 INTEGER, | val3 INTEGER, | val4 INTEGER, | val5 INTEGER, | val6 INTEGER, | val7 INTEGER, | val8 INTEGER, | val9 INTEGER, | val10 INTEGER, | val11 INTEGER, | val12 INTEGER, | val13 INTEGER, | val14 INTEGER, | val15 INTEGER, | val16 INTEGER, | val17 INTEGER, | val18 INTEGER, | val19 INTEGER, | val20 INTEGER, | val21 INTEGER, | val22 INTEGER, | val23 INTEGER, | val24 INTEGER, | val25 INTEGER, | val26 INTEGER, | val27 INTEGER, | val28 INTEGER, | val29 INTEGER, | val30 INTEGER |); | |select: |SELECT * |FROM bigTable; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> select(mapper: ( | val1: kotlin.Long?, | val2: kotlin.Long?, | val3: kotlin.Long?, | val4: kotlin.Long?, | val5: kotlin.Long?, | val6: kotlin.Long?, | val7: kotlin.Long?, | val8: kotlin.Long?, | val9: kotlin.Long?, | val10: kotlin.Long?, | val11: kotlin.Long?, | val12: kotlin.Long?, | val13: kotlin.Long?, | val14: kotlin.Long?, | val15: kotlin.Long?, | val16: kotlin.Long?, | val17: kotlin.Long?, | val18: kotlin.Long?, | val19: kotlin.Long?, | val20: kotlin.Long?, | val21: kotlin.Long?, | val22: kotlin.Long?, | val23: kotlin.Long?, | val24: kotlin.Long?, | val25: kotlin.Long?, | val26: kotlin.Long?, | val27: kotlin.Long?, | val28: kotlin.Long?, | val29: kotlin.Long?, | val30: kotlin.Long? |) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, select, driver, "Test.sq", "select", ""${'"'} ||SELECT * ||FROM bigTable |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getLong(0), | cursor.getLong(1), | cursor.getLong(2), | cursor.getLong(3), | cursor.getLong(4), | cursor.getLong(5), | cursor.getLong(6), | cursor.getLong(7), | cursor.getLong(8), | cursor.getLong(9), | cursor.getLong(10), | cursor.getLong(11), | cursor.getLong(12), | cursor.getLong(13), | cursor.getLong(14), | cursor.getLong(15), | cursor.getLong(16), | cursor.getLong(17), | cursor.getLong(18), | cursor.getLong(19), | cursor.getLong(20), | cursor.getLong(21), | cursor.getLong(22), | cursor.getLong(23), | cursor.getLong(24), | cursor.getLong(25), | cursor.getLong(26), | cursor.getLong(27), | cursor.getLong(28), | cursor.getLong(29) | ) |} |""".trimMargin() ) } @Test fun `match expression on column in FTS table`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE item( | id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | packageName TEXT NOT NULL, | className TEXT NOT NULL, | deprecated INTEGER AS Boolean NOT NULL DEFAULT 0, | link TEXT NOT NULL, | | UNIQUE (packageName, className) |); | |CREATE VIRTUAL TABLE item_index USING fts4(content TEXT); | |queryTerm: |SELECT item.* |FROM item_index |JOIN item ON (docid = item.id) |WHERE content MATCH ?1 |ORDER BY | -- deprecated classes are always last | deprecated ASC, | CASE | -- exact match | WHEN className LIKE ?1 ESCAPE '\' THEN 1 | -- prefix match with no nested type | WHEN className LIKE ?1 || '%' ESCAPE '\' AND instr(className, '.') = 0 THEN 2 | -- exact match on nested type | WHEN className LIKE '%.' || ?1 ESCAPE '\' THEN 3 | -- prefix match (allowing nested types) | WHEN className LIKE ?1 || '%' ESCAPE '\' THEN 4 | -- prefix match on nested type | WHEN className LIKE '%.' || ?1 || '%' ESCAPE '\' THEN 5 | -- infix match | ELSE 6 | END ASC, | -- prefer "closer" matches based on length | length(className) ASC, | -- alphabetize to eliminate any remaining non-determinism | packageName ASC, | className ASC |LIMIT 50 |; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> queryTerm(content: kotlin.String, mapper: ( | id: kotlin.Long, | packageName: kotlin.String, | className: kotlin.String, | deprecated: kotlin.Boolean, | link: kotlin.String |) -> T): com.squareup.sqldelight.Query<T> = QueryTermQuery(content) { cursor -> | mapper( | cursor.getLong(0)!!, | cursor.getString(1)!!, | cursor.getString(2)!!, | cursor.getLong(3)!! == 1L, | cursor.getString(4)!! | ) |} | """.trimMargin() ) } @Test fun `match expression on FTS table name`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE place( | id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | name TEXT NOT NULL, | shortName TEXT NOT NULL, | category TEXT NOT NULL |); | |CREATE VIRTUAL TABLE place_fts USING fts4( | name TEXT NOT NULL, | shortName TEXT NOT NULL |); | |selectPlace: |SELECT place.* |FROM place_fts |JOIN place ON place_fts.rowid = place.id |WHERE place_fts MATCH ?1 |ORDER BY rank(matchinfo(place_fts)), place.name; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectPlace(place_fts: kotlin.String, mapper: ( | id: kotlin.Long, | name: kotlin.String, | shortName: kotlin.String, | category: kotlin.String |) -> T): com.squareup.sqldelight.Query<T> = SelectPlaceQuery(place_fts) { cursor -> | mapper( | cursor.getLong(0)!!, | cursor.getString(1)!!, | cursor.getString(2)!!, | cursor.getString(3)!! | ) |} | """.trimMargin() ) } @Test fun `adapted column in inner query exposed in projection`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE testA ( | id TEXT NOT NULL PRIMARY KEY, | status TEXT AS Test.Status, | attr TEXT |); | |someSelect: |SELECT * |FROM ( | SELECT *, 1 AS ordering | FROM testA | WHERE testA.attr IS NOT NULL | | UNION | | SELECT *, 2 AS ordering | FROM testA | WHERE testA.attr IS NULL |); """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> someSelect(mapper: ( | id: kotlin.String, | status: Test.Status?, | attr: kotlin.String?, | ordering: kotlin.Long |) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, someSelect, driver, "Test.sq", "someSelect", ""${'"'} ||SELECT * ||FROM ( || SELECT *, 1 AS ordering || FROM testA || WHERE testA.attr IS NOT NULL || || UNION || || SELECT *, 2 AS ordering || FROM testA || WHERE testA.attr IS NULL ||) |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getString(0)!!, | cursor.getString(1)?.let { database.testAAdapter.statusAdapter.decode(it) }, | cursor.getString(2), | cursor.getLong(3)!! | ) |} |""".trimMargin() ) } @Test fun `adapted column in foreign table exposed properly`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE testA ( | _id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | parent_id INTEGER NOT NULL, | child_id INTEGER NOT NULL, | FOREIGN KEY (parent_id) REFERENCES testB(_id), | FOREIGN KEY (child_id) REFERENCES testB(_id) |); | |CREATE TABLE testB( | _id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, | category TEXT AS java.util.List NOT NULL, | type TEXT AS java.util.List NOT NULL, | name TEXT NOT NULL |); | |exact_match: |SELECT * |FROM testA |JOIN testB AS parentJoined ON parent_id = parentJoined._id |JOIN testB AS childJoined ON child_id = childJoined._id |WHERE parent_id = ? AND child_id = ?; """.trimMargin(), tempFolder ) val generator = SelectQueryGenerator(file.namedQueries.first()) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> exact_match( | parent_id: kotlin.Long, | child_id: kotlin.Long, | mapper: ( | _id: kotlin.Long, | parent_id: kotlin.Long, | child_id: kotlin.Long, | _id_: kotlin.Long, | category: java.util.List, | type: java.util.List, | name: kotlin.String, | _id__: kotlin.Long, | category_: java.util.List, | type_: java.util.List, | name_: kotlin.String | ) -> T |): com.squareup.sqldelight.Query<T> = Exact_matchQuery(parent_id, child_id) { cursor -> | mapper( | cursor.getLong(0)!!, | cursor.getLong(1)!!, | cursor.getLong(2)!!, | cursor.getLong(3)!!, | database.testBAdapter.categoryAdapter.decode(cursor.getString(4)!!), | database.testBAdapter.typeAdapter.decode(cursor.getString(5)!!), | cursor.getString(6)!!, | cursor.getLong(7)!!, | database.testBAdapter.categoryAdapter.decode(cursor.getString(8)!!), | database.testBAdapter.typeAdapter.decode(cursor.getString(9)!!), | cursor.getString(10)!! | ) |} | """.trimMargin() ) } @Test fun `is not null has correct type`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE test ( | stuff INTEGER |); | |someSelect: |SELECT stuff |FROM test |WHERE stuff IS NOT NULL; |""".trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun someSelect(): com.squareup.sqldelight.Query<kotlin.Long> = com.squareup.sqldelight.Query(-602300915, someSelect, driver, "Test.sq", "someSelect", ""${'"'} ||SELECT stuff ||FROM test ||WHERE stuff IS NOT NULL |""${'"'}.trimMargin()) { cursor -> | cursor.getLong(0)!! |} |""".trimMargin() ) } @Test fun `division has correct type`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE test ( | stuff INTEGER NOT NULL |); | |someSelect: |SELECT SUM(stuff) / 3.0 |FROM test; |""".trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> someSelect(mapper: (expr: kotlin.Double?) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(-602300915, someSelect, driver, "Test.sq", "someSelect", ""${'"'} ||SELECT SUM(stuff) / 3.0 ||FROM test |""${'"'}.trimMargin()) { cursor -> | mapper( | cursor.getDouble(0) | ) |} |""".trimMargin() ) } @Test fun `type inference on boolean`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE exit ( | wingsuit INTEGER AS Boolean NOT NULL |); | |queryOne: |SELECT * FROM exit WHERE wingsuit = :wingsuit AND :wingsuit = 1; | |queryTwo: |SELECT * FROM exit WHERE :wingsuit = 1 AND wingsuit = :wingsuit; """.trimMargin(), tempFolder ) val queryOne = file.namedQueries.first() val generatorOne = SelectQueryGenerator(queryOne) val queryTwo = file.namedQueries.first() val generatorTwo = SelectQueryGenerator(queryTwo) val param = ParameterSpec.builder("wingsuit", Boolean::class.asTypeName()).build() assertThat(generatorOne.defaultResultTypeFunction().parameters).containsExactly(param) assertThat(generatorTwo.defaultResultTypeFunction().parameters).containsExactly(param) } @Test fun `instr second parameter is a string`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE `models` ( | `model_id` int(11) NOT NULL AUTO_INCREMENT, | `model_descriptor_id` int(11) NOT NULL, | `model_description` varchar(8) NOT NULL, | PRIMARY KEY (`model_id`) |) DEFAULT CHARSET=latin1; | |searchDescription: |SELECT model_id, model_description FROM models WHERE INSTR(model_description, ?) > 0; """.trimMargin(), tempFolder, dialectPreset = DialectPreset.MYSQL ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> searchDescription(value: kotlin.String, mapper: (model_id: kotlin.Int, model_description: kotlin.String) -> T): com.squareup.sqldelight.Query<T> = SearchDescriptionQuery(value) { cursor -> | mapper( | cursor.getLong(0)!!.toInt(), | cursor.getString(1)!! | ) |} |""".trimMargin() ) } @Test fun `type inference on instr`() { val file = FixtureCompiler.parseSql( """ |selectIfNull: |SELECT 1, 2 |WHERE IFNULL(:param, 1) > 0; """.trimMargin(), tempFolder ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) val param = ParameterSpec.builder( "param", Long::class.asTypeName() .copy(nullable = true) ) .build() assertThat(generator.defaultResultTypeFunction().parameters).containsExactly(param) } @Test fun `annotations on a type returned in a function`() { val file = FixtureCompiler.parseSql( """ |import java.lang.Deprecated; |import java.lang.String; | |CREATE TABLE category ( | accent_color TEXT AS @Deprecated String, | other_thing TEXT AS @Deprecated String |); | |selectAll: |SELECT * FROM category; """.trimMargin(), tempFolder, dialectPreset = DialectPreset.MYSQL ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun <T : kotlin.Any> selectAll(mapper: (accent_color: kotlin.String?, other_thing: kotlin.String?) -> T): com.squareup.sqldelight.Query<T> = com.squareup.sqldelight.Query(${query.id}, selectAll, driver, "Test.sq", "selectAll", "SELECT * FROM category") { cursor -> | mapper( | cursor.getString(0), | cursor.getString(1) | ) |} |""".trimMargin() ) } @Test fun `union of two views uses the view type`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE sup( | value TEXT |); | |CREATE VIEW supView AS |SELECT value AS value1, value AS value2 |FROM sup; | |unioned: |SELECT * |FROM supView | |UNION ALL | |SELECT * |FROM supView; """.trimMargin(), tempFolder, dialectPreset = DialectPreset.MYSQL ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun unioned(): com.squareup.sqldelight.Query<com.example.SupView> = unioned { value1, value2 -> | com.example.SupView( | value1, | value2 | ) |} |""".trimMargin() ) } @Test fun `union of two tables uses the function type`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE sup( | value TEXT |); | |CREATE TABLE sup2( | value TEXT |); | |unioned: |SELECT * |FROM sup | |UNION ALL | |SELECT * |FROM sup2; """.trimMargin(), tempFolder, dialectPreset = DialectPreset.MYSQL ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun unioned(): com.squareup.sqldelight.Query<com.example.Unioned> = unioned { value -> | com.example.Unioned( | value | ) |} |""".trimMargin() ) } @Test fun `union of a table with itself uses the table type`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE sup( | value TEXT |); | |unioned: |SELECT * |FROM sup | |UNION ALL | |SELECT * |FROM sup; """.trimMargin(), tempFolder, dialectPreset = DialectPreset.MYSQL ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun unioned(): com.squareup.sqldelight.Query<com.example.Sup> = unioned { value -> | com.example.Sup( | value | ) |} |""".trimMargin() ) } @Test fun `view that unions two types uses the view type for star projections`() { val file = FixtureCompiler.parseSql( """ |CREATE TABLE TestTable1( | id TEXT, | name TEXT |); | |CREATE TABLE TestTable2( | id TEXT, | name TEXT |); | |CREATE VIEW TestView AS |SELECT | id, | name |FROM TestTable1 |UNION ALL |SELECT | id, | name |FROM TestTable2; | |findAll: |SELECT * FROM TestView; """.trimMargin(), tempFolder, dialectPreset = DialectPreset.MYSQL ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.defaultResultTypeFunction().toString()).isEqualTo( """ |public override fun findAll(): com.squareup.sqldelight.Query<com.example.TestView> = findAll { id, name -> | com.example.TestView( | id, | name | ) |} |""".trimMargin() ) } @Test fun `if return type computes correctly`() { val file = FixtureCompiler.parseSql( """ |selectIf: |SELECT IF(1 == 1, 'yes', 'no'); """.trimMargin(), tempFolder, dialectPreset = DialectPreset.MYSQL ) val query = file.namedQueries.first() val generator = SelectQueryGenerator(query) assertThat(generator.customResultTypeFunction().toString()).isEqualTo( """ |public override fun selectIf(): com.squareup.sqldelight.Query<kotlin.String> = com.squareup.sqldelight.Query(${query.id}, selectIf, driver, "Test.sq", "selectIf", "SELECT IF(1 == 1, 'yes', 'no')") { cursor -> | cursor.getString(0)!! |} |""".trimMargin() ) } }
apache-2.0
ea08958f35e1a5fb119839aedf025660
29.481391
287
0.576913
3.949328
false
true
false
false
savoirfairelinux/ring-client-android
ring-android/libjamiclient/src/main/kotlin/net/jami/conversation/ConversationPresenter.kt
1
18189
/* * Copyright (C) 2004-2021 Savoir-faire Linux Inc. * * Author: Hadrien De Sousa <[email protected]> * Author: Adrien Béraud <[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, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ package net.jami.conversation import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Scheduler import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.schedulers.Schedulers import io.reactivex.rxjava3.subjects.BehaviorSubject import io.reactivex.rxjava3.subjects.Subject import net.jami.daemon.Blob import net.jami.services.ConversationFacade import net.jami.model.* import net.jami.model.Account.ComposingStatus import net.jami.model.Conversation.ElementStatus import net.jami.mvp.RootPresenter import net.jami.services.* import net.jami.utils.Log import net.jami.utils.VCardUtils import java.io.File import javax.inject.Inject import javax.inject.Named class ConversationPresenter @Inject constructor( private val contactService: ContactService, private val accountService: AccountService, private val hardwareService: HardwareService, private val conversationFacade: ConversationFacade, private val vCardService: VCardService, val deviceRuntimeService: DeviceRuntimeService, private val preferencesService: PreferencesService, @param:Named("UiScheduler") private val uiScheduler: Scheduler ) : RootPresenter<ConversationView>() { private var mConversation: Conversation? = null private var mConversationUri: Uri? = null private var mConversationDisposable: CompositeDisposable? = null private val mVisibilityDisposable = CompositeDisposable().apply { mCompositeDisposable.add(this) } private val mConversationSubject: Subject<Conversation> = BehaviorSubject.create() fun init(conversationUri: Uri, accountId: String) { if (conversationUri == mConversationUri) return Log.w(TAG, "init $conversationUri $accountId") val settings = preferencesService.settings view?.setSettings(settings.enableReadIndicator, settings.enableLinkPreviews) mConversationUri = conversationUri mCompositeDisposable.add(conversationFacade.getAccountSubject(accountId) .flatMap { a: Account -> conversationFacade.loadConversationHistory(a, conversationUri) .observeOn(uiScheduler) .doOnSuccess { c: Conversation -> setConversation(a, c) } } .observeOn(uiScheduler) .subscribe({}) { e: Throwable -> Log.e(TAG, "Error loading conversation", e) view?.goToHome() }) } override fun unbindView() { super.unbindView() mConversation = null mConversationUri = null mConversationDisposable?.let { conversationDisposable -> conversationDisposable.dispose() mConversationDisposable = null } } private fun setConversation(account: Account, conversation: Conversation) { Log.w(TAG, "setConversation " + conversation.aggregateHistory.size) if (mConversation == conversation) return mConversation = conversation mConversationSubject.onNext(conversation) view?.let { initView(account, conversation, it) } } fun pause() { mVisibilityDisposable.clear() mConversation?.isVisible = false } fun resume(isBubble: Boolean) { Log.w(TAG, "resume $mConversationUri") mVisibilityDisposable.clear() mVisibilityDisposable.add(mConversationSubject .subscribe({ conversation: Conversation -> conversation.isVisible = true updateOngoingCallView(conversation) accountService.getAccount(conversation.accountId)?.let { account -> conversationFacade.readMessages(account, conversation, !isBubble)} }) { e -> Log.e(TAG, "Error loading conversation", e) }) } private fun initContact( account: Account, conversation: Conversation, contacts: List<ContactViewModel>, mode: Conversation.Mode, view: ConversationView ) { if (account.isJami) { Log.w(TAG, "initContact " + conversation.uri + " mode: " + mode) if (mode === Conversation.Mode.Syncing) { view.switchToSyncingView() } else if (mode == Conversation.Mode.Request) { view.switchToIncomingTrustRequestView(contacts[0].displayName ?: conversation.uri.uri) } else if (conversation.isSwarm || account.isContact(conversation)) { //if (conversation.isEnded()) // conversation.s view.switchToConversationView() } else { val uri = conversation.uri val req = account.getRequest(uri) if (req == null) { view.switchToUnknownView(uri.rawUriString) } else { view.switchToIncomingTrustRequestView(req.displayName) } } } else { view.switchToConversationView() } view.displayContact(conversation, contacts) } private fun initView(account: Account, c: Conversation, view: ConversationView) { Log.w(TAG, "initView " + c.uri) val disposable = mConversationDisposable?.apply { clear() } ?: CompositeDisposable().apply { mConversationDisposable = this mCompositeDisposable.add(this) } view.hideNumberSpinner() disposable.add(c.mode .switchMapSingle { mode: Conversation.Mode -> contactService.getLoadedContact(c.accountId, c.contacts, true) .observeOn(uiScheduler) .doOnSuccess { contacts -> initContact(account, c, contacts, mode, this.view!!) } } .subscribe()) disposable.add(c.mode .switchMap { mode: Conversation.Mode -> if (mode === Conversation.Mode.Legacy || mode === Conversation.Mode.Request) c.contact!!.conversationUri else Observable.empty() } .observeOn(uiScheduler) .subscribe { uri: Uri -> init(uri, account.accountId) }) disposable.add(Observable.combineLatest(hardwareService.connectivityState, accountService.getObservableAccount(account)) { isConnected: Boolean, a: Account -> isConnected || a.isRegistered } .observeOn(uiScheduler) .subscribe { isOk: Boolean -> this.view?.let { v -> if (!isOk) v.displayNetworkErrorPanel() else if (!account.isEnabled) { v.displayAccountOfflineErrorPanel() } else { v.hideErrorPanel() } } }) disposable.add(c.sortedHistory .observeOn(uiScheduler) .subscribe({ conversation: List<Interaction> -> this.view?.refreshView(conversation) }) { e: Throwable -> Log.e(TAG, "Can't update element", e) }) disposable.add(c.cleared .observeOn(uiScheduler) .subscribe({ conversation: List<Interaction> -> this.view?.refreshView(conversation) }) { e: Throwable -> Log.e(TAG, "Can't update elements", e) }) disposable.add(c.contactUpdates .switchMap { contacts -> Observable.merge(contactService.observeLoadedContact(c.accountId, contacts, true)) } .observeOn(uiScheduler) .subscribe { contact: ContactViewModel -> this.view?.updateContact(contact) }) disposable.add(c.updatedElements .observeOn(uiScheduler) .subscribe({ elementTuple -> val v = this.view ?: return@subscribe when (elementTuple.second) { ElementStatus.ADD -> v.addElement(elementTuple.first) ElementStatus.UPDATE -> v.updateElement(elementTuple.first) ElementStatus.REMOVE -> v.removeElement(elementTuple.first) } }, { e: Throwable -> Log.e(TAG, "Can't update element", e) }) ) if (showTypingIndicator()) { disposable.add(c.composingStatus .observeOn(uiScheduler) .subscribe { composingStatus: ComposingStatus -> this.view?.setComposingStatus(composingStatus) }) } disposable.add(c.getLastDisplayed() .observeOn(uiScheduler) .subscribe { interaction: Interaction -> this.view?.setLastDisplayed(interaction) }) disposable.add(c.calls .observeOn(uiScheduler) .subscribe({ updateOngoingCallView(c) }) { e: Throwable -> Log.e(TAG, "Can't update call view", e) }) disposable.add(c.getColor() .observeOn(uiScheduler) .subscribe({ integer: Int -> this.view?.setConversationColor(integer) }) { e: Throwable -> Log.e(TAG, "Can't update conversation color", e) }) disposable.add(c.getSymbol() .observeOn(uiScheduler) .subscribe({ symbol: CharSequence -> this.view?.setConversationSymbol(symbol) }) { e: Throwable -> Log.e(TAG, "Can't update conversation color", e) }) disposable.add(account .getLocationUpdates(c.uri) .observeOn(uiScheduler) .subscribe { Log.e(TAG, "getLocationUpdates: update") this.view?.showMap(c.accountId, c.uri.uri, false) } ) } fun loadMore() { mConversationDisposable?.add(accountService.loadMore(mConversation!!).subscribe({}) {}) } fun openContact() { mConversation?.let { conversation -> view?.goToContactActivity(conversation.accountId, conversation.uri) } } fun sendTextMessage(message: String?) { val conversation = mConversation if (message == null || message.isEmpty() || conversation == null) { return } val conference = conversation.currentCall if (conversation.isSwarm || conference == null || !conference.isOnGoing) { conversationFacade.sendTextMessage(conversation, conversation.uri, message).subscribe() } else { conversationFacade.sendTextMessage(conversation, conference, message) } } fun selectFile() { view?.openFilePicker() } fun sendFile(file: File) { mCompositeDisposable.add(mConversationSubject.firstElement().subscribe({ conversation -> conversationFacade.sendFile(conversation, conversation.uri, file).subscribe() }) {e -> Log.e(TAG, "Can't send file", e)}) } /** * Gets the absolute path of the file dataTransfer and sends both the DataTransfer and the * found path to the ConversationView in order to start saving the file * * @param interaction an interaction representing a datat transfer */ fun saveFile(interaction: Interaction) { val transfer = interaction as DataTransfer val fileAbsolutePath = deviceRuntimeService.getConversationPath(transfer).absolutePath view?.startSaveFile(transfer, fileAbsolutePath) } fun shareFile(interaction: Interaction) { val file = interaction as DataTransfer val path = deviceRuntimeService.getConversationPath(file) view?.shareFile(path, file.displayName) } fun openFile(interaction: Interaction) { val file = interaction as DataTransfer val path = deviceRuntimeService.getConversationPath(file) view?.openFile(path, file.displayName) } fun acceptFile(transfer: DataTransfer) { view?.acceptFile(mConversation!!.accountId, mConversationUri!!, transfer) } fun refuseFile(transfer: DataTransfer) { view!!.refuseFile(mConversation!!.accountId, mConversationUri!!, transfer) } fun deleteConversationItem(element: Interaction) { conversationFacade.deleteConversationItem(mConversation!!, element) } fun cancelMessage(message: Interaction) { conversationFacade.cancelMessage(message) } private fun sendTrustRequest() { val conversation = mConversation ?: return val contact = conversation.contact ?: return contact.status = Contact.Status.REQUEST_SENT vCardService.loadSmallVCardWithDefault(conversation.accountId, VCardService.MAX_SIZE_REQUEST) .subscribeOn(Schedulers.computation()) .subscribe({ vCard -> accountService.sendTrustRequest(conversation, contact.uri, Blob.fromString(VCardUtils.vcardToString(vCard)))}) { accountService.sendTrustRequest(conversation, contact.uri, null) } } fun clickOnGoingPane() { val conf = mConversation?.currentCall if (conf != null) { view?.goToCallActivity(conf.id, conf.hasActiveVideo()) } else { view?.displayOnGoingCallPane(false) } } fun goToCall(withCamera: Boolean) { if (!withCamera && !hardwareService.hasMicrophone()) { view!!.displayErrorToast(Error.NO_MICROPHONE) return } mCompositeDisposable.add(mConversationSubject .firstElement() .subscribe { conversation: Conversation -> val view = view if (view != null) { val conf = conversation.currentCall if (conf != null && conf.participants.isNotEmpty() && conf.participants[0].callStatus !== Call.CallStatus.INACTIVE && conf.participants[0].callStatus !== Call.CallStatus.FAILURE) { view.goToCallActivity(conf.id, conf.hasActiveVideo()) } else { view.goToCallActivityWithResult(conversation.accountId, conversation.uri, conversation.contact!!.uri, withCamera) } } }) } private fun updateOngoingCallView(conversation: Conversation?) { val conf = conversation?.currentCall view?.displayOnGoingCallPane(conf != null && (conf.state === Call.CallStatus.CURRENT || conf.state === Call.CallStatus.HOLD || conf.state === Call.CallStatus.RINGING)) } fun onBlockIncomingContactRequest() { mConversation?.let { conversation -> conversationFacade.discardRequest(conversation.accountId, conversation.uri) accountService.removeContact(conversation.accountId, conversation.uri.host, true) } view?.goToHome() } fun onRefuseIncomingContactRequest() { mConversation?.let { conversation -> conversationFacade.discardRequest(conversation.accountId, conversation.uri) } view?.goToHome() } fun onAcceptIncomingContactRequest() { mConversation?.let { conversation -> if (conversation.mode.blockingFirst() == Conversation.Mode.Request) { conversation.loaded = null conversation.clearHistory(true) conversation.setMode(Conversation.Mode.Syncing) } conversationFacade.acceptRequest(conversation.accountId, conversation.uri) } view?.switchToConversationView() } fun onAddContact() { sendTrustRequest() view?.switchToConversationView() } fun noSpaceLeft() { Log.e(TAG, "configureForFileInfoTextMessage: no space left on device") view?.displayErrorToast(Error.NO_SPACE_LEFT) } fun setConversationColor(color: Int) { mCompositeDisposable.add(mConversationSubject .firstElement() .subscribe { conversation: Conversation -> conversation.setColor(color) }) } fun setConversationSymbol(symbol: CharSequence) { mCompositeDisposable.add(mConversationSubject.firstElement() .subscribe { conversation -> conversation.setSymbol(symbol) }) } fun cameraPermissionChanged(isGranted: Boolean) { if (isGranted && hardwareService.isVideoAvailable) { hardwareService.initVideo() .onErrorComplete() .subscribe() } } fun shareLocation() { mCompositeDisposable.add(mConversationSubject.firstElement() .subscribe { conversation -> view?.startShareLocation(conversation.accountId, conversation.uri.uri) }) } fun showPluginListHandlers() { view?.showPluginListHandlers(mConversation!!.accountId, mConversationUri!!.uri) } val path: Pair<String, String> get() = Pair(mConversation!!.accountId, mConversationUri!!.uri) fun onComposingChanged(hasMessage: Boolean) { if (showTypingIndicator()) { mConversation?.let { conversation -> conversationFacade.setIsComposing(conversation.accountId, conversation.uri, hasMessage) } } } private fun showTypingIndicator(): Boolean { return preferencesService.settings.enableTypingIndicator } private fun showReadIndicator(): Boolean { return preferencesService.settings.enableReadIndicator } companion object { private val TAG = ConversationPresenter::class.simpleName!! } }
gpl-3.0
6f2522c5351688d0d0ac974323c0541d
40.058691
175
0.635474
4.972116
false
false
false
false
udamken/PswGen
PswGenDroid/app/src/main/java/de/dknapps/pswgendroid/ui/DisplayPasswordFragment.kt
1
3099
/************************************************************************************ * PswGenDesktop - Manages your websites and repeatably generates passwords for them * PswGenDroid - Generates your passwords managed by PswGenDesktop on your mobile * * Copyright (C) 2005-2018 Uwe Damken * * 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 de.dknapps.pswgendroid.ui import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders import de.dknapps.pswgencore.model.ServiceInfo import de.dknapps.pswgendroid.R import de.dknapps.pswgendroid.model.ServiceMaintenanceViewModel import kotlinx.android.synthetic.main.display_password_fragment.* class DisplayPasswordFragment : androidx.fragment.app.Fragment() { companion object { fun newInstance() = DisplayPasswordFragment() } private lateinit var viewModel: ServiceMaintenanceViewModel override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.display_password_fragment, container, false) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) (requireActivity() as AppCompatActivity).supportActionBar!!.setDisplayHomeAsUpEnabled(true) viewModel = ViewModelProviders.of(requireActivity()).get(ServiceMaintenanceViewModel::class.java) } override fun onResume() { super.onResume() // When the screen gets locked services are unloaded. Therefore we return to previous fragment // if there is currently no service or no password available (probably because of screen lock). if (!viewModel.retrieveService() || viewModel.password == null) { requireActivity().supportFragmentManager.popBackStack() } else { putServiceToView(viewModel.currentServiceInfo) password.text = viewModel.password!! passwordExplanation.text = viewModel.passwordExplanation!! } } /** * Copy values to be displayed into UI (method name identical with PswGenDesktop). */ private fun putServiceToView(si: ServiceInfo) { serviceAbbreviation.text = si.serviceAbbreviation loginInfo.text = si.loginInfo password.text = si.additionalLoginInfo } }
apache-2.0
96b99c0dca97fb77d8c10e33570b3ca4
40.32
105
0.696031
4.903481
false
false
false
false
NLPIE/BioMedICUS
biomedicus-core/src/main/kotlin/edu/umn/biomedicus/parsing/Parsing.kt
1
6392
/* * Copyright (c) 2018 Regents of the University of Minnesota. * * 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 edu.umn.biomedicus.parsing import edu.umn.biomedicus.tokenization.ParseToken import edu.umn.nlpengine.* import java.util.* class ParsingModule : SystemModule() { override fun setup() { addEnumClass<UDRelation>() addLabelClass<DependencyParse>() addLabelClass<Dependency>() addLabelClass<ConstituencyParse>() } } @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class ConstituencyParse( override val startIndex: Int, override val endIndex: Int, val parseTree: String ) : Label() { constructor(textRange: TextRange, parseTree: String) : this(textRange.startIndex, textRange.endIndex, parseTree) } /** * The root of the dependency tree in a sentence. * * @property startIndex the start index of the word which is the root * @property endIndex the index after the word which is the root * @property root the span of the root */ @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class DependencyParse( override val startIndex: Int, override val endIndex: Int, val root: Span ) : Label() { constructor( textRange: TextRange, root: TextRange ) : this(textRange.startIndex, textRange.endIndex, root.toSpan()) } /** * A dependency relation in text. * * @property startIndex the index the dependant starts at * @property endIndex the index after the dependant * @property relation the relation between dependant and head * @property head the span of the head */ @LabelMetadata(classpath = "biomedicus.v2", distinct = true) data class Dependency( override val startIndex: Int, override val endIndex: Int, val dep: ParseToken, val relation: UDRelation?, val head: Dependency? ) : Label() { constructor( dep: ParseToken, relation: UDRelation?, head: Dependency? ) : this(dep.startIndex, dep.endIndex, dep, relation, head) fun selfAndParentIterator(): Iterator<Dependency> { return ancestorIterator(this) } fun parentIterator(): Iterator<Dependency> { return ancestorIterator(head) } private fun ancestorIterator(blah: Dependency?): Iterator<Dependency> { return object : Iterator<Dependency> { var ptr = blah override fun hasNext(): Boolean { return ptr != null } override fun next(): Dependency { val temp: Dependency = ptr ?: throw NoSuchElementException("No parent.") ptr = temp.head return temp } } } } /** * Finds the head of a phrase [dependencies] by finding the dependency that links outside of the * phrase. */ fun findHead(dependencies: Collection<Dependency>): Dependency { return dependencies.find { test -> dependencies.none { test.head?.locationEquals(it) ?: false } } ?: throw AssertionError("Could not find root of phrase") } /** * Returns the universal dependency relation enum represented by [string] */ fun getUniversalDependencyRelation(string: String) : UDRelation { return UDRelation.values().firstOrNull { string == it.lowercase } ?: throw AssertionError("Could not find dependency relation: $string") } /** * A merge of the universal dependency v1 and v2 relations. */ enum class UDRelation { /** * clausal modifier of noun (adjectival clause) */ ACL, /** * adverbial clause modifier */ ADVCL, /** * adverbial modifier */ ADVMOD, /** * adjectival modifier */ AMOD, /** * appositional modifier */ APPOS, /** * auxiliary */ AUX, /** * passive auxiliary */ AUXPASS, /** * case marking */ CASE, /** * coordinating conjunction */ CC, /** * clausal complement */ CCOMP, /** * classifier */ CLF, /** * compound */ COMPOUND, /** * conjunct */ CONJ, /** * copula */ COP, /** * clausal subject */ CSUBJ, /** * clausal passive subject */ CSUBJPASS, /** * unspecified dependency */ DEP, /** * determiner */ DET, /** * discourse element */ DISCOURSE, /** * dislocated elements */ DISLOCATED, /** * Direct object */ DOBJ, /** * expletive */ EXPL, /** * fixed multiword expression */ FIXED, /** * flat multiword expression */ FLAT, /** * goes with */ GOESWITH, /** * indirect object */ IOBJ, /** * list */ LIST, /** * marker */ MARK, /** * multi-word expression */ MWE, /** * name */ NAME, /** * negation modifier */ NEG, /** * nominal modifier */ NMOD, /** * nominal subject */ NSUBJ, /** * passive nominal subject */ NSUBJPASS, /** * numeric modifier */ NUMMOD, /** * object */ OBJ, /** * oblique nominal */ OBL, /** * orphan */ ORPHAN, /** * parataxis */ PARATAXIS, /** * punctuation */ PUNCT, /** * : overridden disfluency */ REPARANDUM, /** * remnant in ellipsis */ REMNANT, /** * ROOT */ ROOT, /** * vocative */ VOCATIVE, /** * open clausal complement */ XCOMP; val lowercase = name.toLowerCase() override fun toString() = lowercase }
apache-2.0
206753a93461cc2951204ba23f9a8510
19.227848
116
0.568992
4.238727
false
false
false
false
arcao/Geocaching4Locus
app/src/main/java/com/arcao/geocaching4locus/update/UpdateViewModel.kt
1
8678
package com.arcao.geocaching4locus.update import android.app.Application import android.content.Intent import com.arcao.geocaching4locus.R import com.arcao.geocaching4locus.authentication.util.isPremium import com.arcao.geocaching4locus.base.BaseViewModel import com.arcao.geocaching4locus.base.constants.AppConstants import com.arcao.geocaching4locus.base.coroutine.CoroutinesDispatcherProvider import com.arcao.geocaching4locus.base.usecase.GetGeocachingLogsUseCase import com.arcao.geocaching4locus.base.usecase.GetPointFromGeocacheCodeUseCase import com.arcao.geocaching4locus.base.util.AnalyticsManager import com.arcao.geocaching4locus.base.util.Command import com.arcao.geocaching4locus.base.util.invoke import com.arcao.geocaching4locus.data.account.AccountManager import com.arcao.geocaching4locus.error.handler.ExceptionHandler import com.arcao.geocaching4locus.settings.manager.DefaultPreferenceManager import kotlinx.coroutines.Job import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.toList import locus.api.android.utils.IntentHelper import locus.api.android.utils.LocusUtils import locus.api.manager.LocusMapManager import locus.api.mapper.PointMerger import locus.api.mapper.Util import locus.api.objects.geoData.Point import timber.log.Timber class UpdateViewModel( private val context: Application, private val accountManager: AccountManager, private val defaultPreferenceManager: DefaultPreferenceManager, private val getPointFromGeocacheCode: GetPointFromGeocacheCodeUseCase, private val getGeocachingLogs: GetGeocachingLogsUseCase, private val pointMerger: PointMerger, private val locusMapManager: LocusMapManager, private val exceptionHandler: ExceptionHandler, private val analyticsManager: AnalyticsManager, dispatcherProvider: CoroutinesDispatcherProvider ) : BaseViewModel(dispatcherProvider) { val action = Command<UpdateAction>() private var job: Job? = null fun processIntent(intent: Intent) { if (locusMapManager.isLocusMapNotInstalled) { action(UpdateAction.LocusMapNotInstalled) return } if (accountManager.account == null) { action(UpdateAction.SignIn) return } if (!accountManager.isPremium && isUpdateLogsIntent(intent)) { action(UpdateAction.PremiumMembershipRequired) return } if (job?.isActive == true) { job?.cancel() } job = mainLaunch { val downloadFullGeocacheOnShow = defaultPreferenceManager.downloadFullGeocacheOnShow try { showProgress(R.string.progress_update_geocache, maxProgress = 1) { val updateData = computationContext { val updateData = retrieveUpdateData(intent) ?: return@computationContext null val basicMember = !(accountManager.isPremium) var logsCount = defaultPreferenceManager.downloadingGeocacheLogsCount var lite = false if (basicMember) { logsCount = 0 lite = true } updateData.newPoint = getPointFromGeocacheCode(updateData.geocacheCode, lite, logsCount) if (updateData.downloadLogs) { var progress = updateData.newPoint.gcData?.logs?.count() ?: 0 logsCount = AppConstants.LOGS_TO_UPDATE_MAX updateProgress( R.string.progress_download_logs, progress = progress, maxProgress = logsCount ) val logs = getGeocachingLogs( updateData.geocacheCode, progress, logsCount ).map { progress += it.count() updateProgress(progress = progress, maxProgress = logsCount) it }.toList() updateData.newPoint.gcData?.logs?.apply { addAll(logs.flatten()) sortBy { it.date } } } if (updateData.downloadLogs && updateData.oldPoint != null && !defaultPreferenceManager.downloadLogsUpdateCache) { pointMerger.mergeGeocachingLogs( updateData.oldPoint, updateData.newPoint ) // only when this feature is enabled if (defaultPreferenceManager.disableDnfNmNaGeocaches) Util.applyUnavailabilityForGeocache( updateData.oldPoint, defaultPreferenceManager.disableDnfNmNaGeocachesThreshold ) updateData.newPoint = updateData.oldPoint } else { pointMerger.mergePoints(updateData.newPoint, updateData.oldPoint) if (downloadFullGeocacheOnShow) { updateData.newPoint.removeExtraOnDisplay() } } return@computationContext updateData } if (updateData == null) { action(UpdateAction.Cancel) return@showProgress } // if Point is already in DB we must update it manually if (updateData.oldPoint != null) { locusMapManager.updatePoint(updateData.newPoint) action(UpdateAction.Finish()) } else { action( UpdateAction.Finish( LocusUtils.prepareResultExtraOnDisplayIntent( updateData.newPoint, downloadFullGeocacheOnShow ) ) ) } } } catch (e: Exception) { action(UpdateAction.Error(exceptionHandler(e))) } } } private fun retrieveUpdateData(intent: Intent): UpdateData? { var cacheId: String? = null var oldPoint: Point? = null when { intent.hasExtra(UpdateActivity.PARAM_CACHE_ID) -> cacheId = intent.getStringExtra(UpdateActivity.PARAM_CACHE_ID) IntentHelper.isIntentPointTools(intent) -> try { val p = IntentHelper.getPointFromIntent(context, intent) if (p?.gcData != null) { cacheId = p.gcData?.cacheID oldPoint = p } } catch (t: Throwable) { Timber.e(t) } intent.hasExtra(UpdateActivity.PARAM_SIMPLE_CACHE_ID) -> { cacheId = intent.getStringExtra(UpdateActivity.PARAM_SIMPLE_CACHE_ID) if (!defaultPreferenceManager.downloadGeocacheOnShow) { Timber.d("Updating simple cache on displaying is not allowed!") cacheId = null } } } if (cacheId == null || !cacheId.uppercase().startsWith("GC")) { Timber.e("cacheId/simpleCacheId not found") return null } val downloadLogs = AppConstants.UPDATE_WITH_LOGS_COMPONENT == intent.component?.className analyticsManager.actionUpdate(oldPoint != null, downloadLogs, accountManager.isPremium) return UpdateData(cacheId, downloadLogs, oldPoint) } private fun isUpdateLogsIntent(intent: Intent) = AppConstants.UPDATE_WITH_LOGS_COMPONENT == intent.component?.className fun cancelProgress() { job?.cancel() } class UpdateData( val geocacheCode: String, val downloadLogs: Boolean, val oldPoint: Point? = null ) { lateinit var newPoint: Point } }
gpl-3.0
3009164dcc5a8b49eda693df8ac91070
38.266968
138
0.548974
5.762284
false
false
false
false
lijunzz/LongChuanGang
util/src/main/kotlin/net/junzz/app/util/ColorUtils.kt
1
594
package net.junzz.app.util import java.util.* /** * 颜色工具类 */ object ColorUtils { fun newRandomColor(): String { var r: String var g: String var b: String val random = Random() r = Integer.toHexString(random.nextInt(256)).toLowerCase() g = Integer.toHexString(random.nextInt(256)).toLowerCase() b = Integer.toHexString(random.nextInt(256)).toLowerCase() r = if (r.length == 1) "0$r" else r g = if (g.length == 1) "0$g" else g b = if (b.length == 1) "0$b" else b return "#$r$g$b" } }
gpl-3.0
b462786d78e5d92bce3c339368ef6452
23.333333
66
0.558219
3.395349
false
false
false
false
signed/intellij-community
platform/built-in-server/src/org/jetbrains/builtInWebServer/DefaultWebServerRootsProvider.kt
1
11248
/* * Copyright 2000-2014 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.jetbrains.builtInWebServer import com.intellij.openapi.application.runReadAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.* import com.intellij.openapi.roots.impl.DirectoryIndex import com.intellij.openapi.roots.impl.ModuleLibraryOrderEntryImpl import com.intellij.openapi.roots.libraries.LibraryTable import com.intellij.openapi.roots.libraries.LibraryTablesRegistrar import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.text.StringUtil import com.intellij.openapi.vfs.JarFileSystem import com.intellij.openapi.vfs.VfsUtilCore import com.intellij.openapi.vfs.VirtualFile import com.intellij.project.rootManager import com.intellij.util.PlatformUtils import com.intellij.util.containers.computeOrNull internal data class SuitableRoot(val file: VirtualFile, val moduleQualifier: String?) private class DefaultWebServerRootsProvider : WebServerRootsProvider() { override fun resolve(path: String, project: Project, pathQuery: PathQuery): PathInfo? { val pathToFileManager = WebServerPathToFileManager.getInstance(project) var effectivePath = path if (PlatformUtils.isIntelliJ()) { val index = effectivePath.indexOf('/') if (index > 0 && !effectivePath.regionMatches(0, project.name, 0, index, !SystemInfo.isFileSystemCaseSensitive)) { val moduleName = effectivePath.substring(0, index) val module = runReadAction { ModuleManager.getInstance(project).findModuleByName(moduleName) } if (module != null && !module.isDisposed) { effectivePath = effectivePath.substring(index + 1) val resolver = pathToFileManager.getResolver(effectivePath) val result = RootProvider.values().computeOrNull { findByRelativePath(effectivePath, it.getRoots(module.rootManager), resolver, moduleName, pathQuery) } ?: findInModuleLibraries(effectivePath, module, resolver, pathQuery) if (result != null) { return result } } } } val resolver = pathToFileManager.getResolver(effectivePath) val modules = runReadAction { ModuleManager.getInstance(project).modules } if (pathQuery.useVfs) { var oldestParent = path.indexOf("/").let { if (it > 0) path.substring(0, it) else null } if (oldestParent == null && !path.isEmpty() && !path.contains('.')) { // maybe it is top level directory? (in case of dart projects - web) oldestParent = path } if (oldestParent != null) { for (root in pathToFileManager.parentToSuitableRoot.get(oldestParent)) { root.file.findFileByRelativePath(path)?.let { return PathInfo(null, it, root.file, root.moduleQualifier) } } } } else { for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } findByRelativePath(path, rootProvider.getRoots(module.rootManager), resolver, null, pathQuery)?.let { it.moduleName = getModuleNameQualifier(project, module) return it } } } } if (!pathQuery.searchInLibs) { // yes, if !searchInLibs, config.json is also not checked return null } fun findByConfigJson(): PathInfo? { // https://youtrack.jetbrains.com/issue/WEB-24283 for (rootProvider in RootProvider.values()) { for (module in modules) { if (module.isDisposed) { continue } for (root in rootProvider.getRoots(module.rootManager)) { if (resolver.resolve("config.json", root, pathQuery = pathQuery) != null) { resolver.resolve("index.html", root, pathQuery = pathQuery)?.let { it.moduleName = getModuleNameQualifier(project, module) return it } } } } } return null } val exists = pathToFileManager.pathToExistShortTermCache.getIfPresent("config.json") if (exists == null || exists) { val result = findByConfigJson() pathToFileManager.pathToExistShortTermCache.put("config.json", result != null) if (result != null) { return result } } return findInLibraries(project, effectivePath, resolver, pathQuery) } override fun getPathInfo(file: VirtualFile, project: Project): PathInfo? { return runReadAction { val directoryIndex = DirectoryIndex.getInstance(project) val info = directoryIndex.getInfoForFile(file) // we serve excluded files if (!info.isExcluded && !info.isInProject) { // javadoc jars is "not under project", but actually is, so, let's check library or SDK if (file.fileSystem == JarFileSystem.getInstance()) getInfoForDocJar(file, project) else null } else { var root = info.sourceRoot val isRootNameOptionalInPath: Boolean val isLibrary: Boolean if (root == null) { isRootNameOptionalInPath = false root = info.contentRoot if (root == null) { root = info.libraryClassRoot isLibrary = true assert(root != null) { file.presentableUrl } } else { isLibrary = false } } else { isLibrary = info.isInLibrarySource isRootNameOptionalInPath = !isLibrary } var module = info.module if (isLibrary && module == null) { for (entry in directoryIndex.getOrderEntries(info)) { if (entry is ModuleLibraryOrderEntryImpl) { module = entry.ownerModule break } } } PathInfo(null, file, root!!, getModuleNameQualifier(project, module), isLibrary, isRootNameOptionalInPath = isRootNameOptionalInPath) } } } } internal enum class RootProvider { SOURCE { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.sourceRoots }, CONTENT { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.contentRoots }, EXCLUDED { override fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> = rootManager.excludeRoots }; abstract fun getRoots(rootManager: ModuleRootManager): Array<VirtualFile> } private val ORDER_ROOT_TYPES by lazy { val javaDocRootType = getJavadocOrderRootType() if (javaDocRootType == null) arrayOf(OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) else arrayOf(javaDocRootType, OrderRootType.DOCUMENTATION, OrderRootType.SOURCES, OrderRootType.CLASSES) } private fun getJavadocOrderRootType(): OrderRootType? { try { return JavadocOrderRootType.getInstance() } catch (e: Throwable) { return null } } private fun findInModuleLibraries(path: String, module: Module, resolver: FileResolver, pathQuery: PathQuery): PathInfo? { val index = path.indexOf('/') if (index <= 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return ORDER_ROOT_TYPES.computeOrNull { findInModuleLevelLibraries(module, it) { root, module -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true, pathQuery = pathQuery) else null } } } private fun findInLibraries(project: Project, path: String, resolver: FileResolver, pathQuery: PathQuery): PathInfo? { val index = path.indexOf('/') if (index < 0) { return null } val libraryFileName = path.substring(0, index) val relativePath = path.substring(index + 1) return findInLibrariesAndSdk(project, ORDER_ROOT_TYPES) { root, module -> if (StringUtil.equalsIgnoreCase(root.nameSequence, libraryFileName)) resolver.resolve(relativePath, root, isLibrary = true, pathQuery = pathQuery) else null } } private fun getInfoForDocJar(file: VirtualFile, project: Project): PathInfo? { val javaDocRootType = getJavadocOrderRootType() ?: return null return findInLibrariesAndSdk(project, arrayOf(javaDocRootType)) { root, module -> if (VfsUtilCore.isAncestor(root, file, false)) PathInfo(null, file, root, getModuleNameQualifier(project, module), true) else null } } internal fun getModuleNameQualifier(project: Project, module: Module?): String? { if (module != null && PlatformUtils.isIntelliJ() && !(module.name.equals(project.name, ignoreCase = true) || compareNameAndProjectBasePath(module.name, project))) { return module.name } return null } private fun findByRelativePath(path: String, roots: Array<VirtualFile>, resolver: FileResolver, moduleName: String?, pathQuery: PathQuery) = roots.computeOrNull { resolver.resolve(path, it, moduleName, pathQuery = pathQuery) } private fun findInLibrariesAndSdk(project: Project, rootTypes: Array<OrderRootType>, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { fun findInLibraryTable(table: LibraryTable, rootType: OrderRootType) = table.libraryIterator.computeOrNull { it.getFiles(rootType).computeOrNull { fileProcessor(it, null) } } fun findInProjectSdkOrInAll(rootType: OrderRootType): PathInfo? { val inSdkFinder = { sdk: Sdk -> sdk.rootProvider.getFiles(rootType).computeOrNull { fileProcessor(it, null) } } val projectSdk = ProjectRootManager.getInstance(project).projectSdk return projectSdk?.let(inSdkFinder) ?: ProjectJdkTable.getInstance().allJdks.computeOrNull { if (it === projectSdk) null else inSdkFinder(it) } } return rootTypes.computeOrNull { rootType -> runReadAction { findInLibraryTable(LibraryTablesRegistrar.getInstance().getLibraryTable(project), rootType) ?: findInProjectSdkOrInAll(rootType) ?: ModuleManager.getInstance(project).modules.computeOrNull { if (it.isDisposed) null else findInModuleLevelLibraries(it, rootType, fileProcessor) } ?: findInLibraryTable(LibraryTablesRegistrar.getInstance().libraryTable, rootType) } } } private fun findInModuleLevelLibraries(module: Module, rootType: OrderRootType, fileProcessor: (root: VirtualFile, module: Module?) -> PathInfo?): PathInfo? { return module.rootManager.orderEntries.computeOrNull { if (it is LibraryOrderEntry && it.isModuleLevel) it.getFiles(rootType).computeOrNull { fileProcessor(it, module) } else null } }
apache-2.0
5fb24fd95f2967a4680093dc53d0ce7b
39.464029
226
0.699769
4.776221
false
false
false
false
appnexus/mobile-sdk-android
tests/TrackerTestApp/app/src/androidTest/java/appnexus/com/trackertestapp/util/SizeMatcher.kt
1
776
package appnexus.com.trackertestapp.util import android.view.View import org.hamcrest.TypeSafeMatcher class SizeMatcher(private val expectedWith: Int, private val expectedHeight: Int) : TypeSafeMatcher<View?>(View::class.java) { override fun matchesSafely(target: View?): Boolean { val targetWidth: Int = target!!.getWidth() val targetHeight: Int = target!!.getHeight() return targetWidth >= expectedWith - 2 && targetWidth <= expectedWith + 2 && targetHeight >= expectedHeight - 2 && targetHeight <= expectedHeight + 2 } override fun describeTo(description: org.hamcrest.Description?) { description?.appendText("with SizeMatcher: ") description?.appendValue(expectedWith.toString() + "x" + expectedHeight) } }
apache-2.0
2611561147c08e357ee5889cce39d821
36
157
0.707474
4.646707
false
false
false
false
kmizu/kollection
src/main/kotlin/com/github/kmizu/kollection/KBatchedQueue.kt
1
992
package com.github.kmizu.kollection data class KBatchedQueue<T>(private val front: KList<T>, private val rear: KList<T>) : KQueue<T> { constructor() : this(KList.Nil, KList.Nil) private fun ensureFront(f: KList<T>, r: KList<T>): KBatchedQueue<T> = when { f.isEmpty -> KBatchedQueue(r.reverse(), KList.Nil) else -> KBatchedQueue(f, r) } override val isEmpty: Boolean get() = front.isEmpty override fun enqueue(newElement: T): KBatchedQueue<T> = ensureFront(front, newElement cons rear) override fun dequeue(): KBatchedQueue<T> = when { front.isEmpty -> throw IllegalArgumentException("com.github.kmizu.kollection.KBatchedQueue.isEmpty") else -> ensureFront(front.tl, rear) } override fun peek(): T = when { front.isEmpty -> throw IllegalArgumentException("com.github.kmizu.kollection.KBatchedQueue.isEmpty") else -> front.hd } override fun toList(): KList<T> = front concat rear.reverse() }
mit
5c94efb648da6369493c8f81d3178f36
37.153846
108
0.672379
3.771863
false
false
false
false
eugeis/ee
ee-design/src/main/kotlin/ee/design/gen/swagger/DesignSwaggerModel.kt
1
3793
package ee.design.gen.swagger import ee.common.ext.joinSurroundIfNotEmptyToString import ee.common.ext.then import ee.common.ext.toHyphenLowerCase import ee.design.* import ee.lang.* import ee.lang.gen.swagger.* fun <T : EntityI<*>> T.toSwaggerGet(c: GenerationContext, api: String = LangDerivedKind.API): String { val finders = findDownByType(FindByI::class.java) val counters = findDownByType(CountByI::class.java) val exists = findDownByType(ExistByI::class.java) val paramsMap = mutableMapOf<String, AttributeI<*>>() finders.forEach { it.params().forEach { paramsMap[it.name()] = it } } counters.forEach { it.params().forEach { paramsMap[it.name()] = it } } exists.forEach { it.params().forEach { paramsMap[it.name()] = it } } val params = paramsMap.values.sortedBy { it.name() } return if (finders.isNotEmpty() || counters.isNotEmpty() || exists.isNotEmpty()) { """ get:${toSwaggerDescription(" ")} parameters: - name: operationId in: query description: id of the operation, e.g. findByName required: false schema: type: string enum: ${finders.toSwaggerLiterals(" ")}${counters.toSwaggerLiterals( " ")}${exists.toSwaggerLiterals(" ")} - name: operationType in: query required: false schema: type: string enum: ${finders.isNotEmpty().then { """ - find""" }}${counters.isNotEmpty().then { """ - count""" }}${exists.isNotEmpty().then { """ - exists""" }}${params.joinSurroundIfNotEmptyToString("") { param -> """ - name: ${param.name()} in: query${param.toSwaggerDescription()} required: false schema:${param.toSwaggerTypeDef(c, api, " ")}""" }} responses: '200': description: fsdfsdf content: application/json: schema:${toSwagger(c, api, " ")}""" } else "" } fun <T : EntityI<*>> T.toSwaggerPost(): String { return """""" } fun <T : EntityI<*>> T.toSwaggerPut(): String { return """""" } fun <T : EntityI<*>> T.toSwaggerDelete(): String { return """""" } fun <T : CompI<*>> T.toSwagger(c: GenerationContext, derived: String = LangDerivedKind.IMPL, api: String = LangDerivedKind.API): String { val moduleAggregates = findDownByType( EntityI::class.java).filter { !it.isVirtual() && it.belongsToAggregate().isEMPTY() && it.derivedAsType().isEmpty() } .groupBy { it.findParentMust(ModuleI::class.java) } val moduleItems = findDownByType(DataTypeI::class.java).filter { it.derivedAsType().isEmpty() }.groupBy { it.findParentMust(ModuleI::class.java) } return """openapi: "3.0.0" info: title: ${fullName()}${doc().isNotEMPTY().then { """ description: ${doc().toDsl()}""" }} version: "1.0.0" paths:${moduleAggregates.joinSurroundIfNotEmptyToString("") { module, item -> if (item.findDownByType(FindByI::class.java).isNotEmpty()) { """ /${c.n(module, derived).toHyphenLowerCase()}${item.toSwaggerPath(c, derived)}:${item.toSwaggerGet(c, api)}${ item.toSwaggerPost()}${item.toSwaggerPut()}${item.toSwaggerDelete()}""" } else "" }} components: schemas:${moduleItems.joinSurroundIfNotEmptyToString("") { module, item -> if (item is EnumTypeI<*>) item.toSwaggerEnum(c, derived) else item.toSwaggerDefinition(c, derived) }}""" } /* responses: parameters: examples: requestBodies: headers: links: callbacks: securitySchemes: */
apache-2.0
accbaa79e599c66beaab55d8fd794f84
31.152542
124
0.581861
4.018008
false
false
false
false
simonorono/pradera_baja
farmacia/src/main/kotlin/pb/farmacia/controller/FormEvento.kt
1
2662
/* * Copyright 2016 Simón Oroñ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 pb.farmacia.controller import javafx.event.ActionEvent import javafx.fxml.FXML import javafx.scene.control.TextArea import javafx.scene.control.TextField import javafx.stage.Stage import pb.common.date.formatDateTime import pb.common.gui.Message import pb.farmacia.data.Articulo import pb.farmacia.data.DB import pb.farmacia.data.Evento import pb.farmacia.data.TipoEvento import java.time.LocalDateTime @Suppress("unused", "UNUSED_PARAMETER") class FormEvento(private var articulo: Articulo, private val tipo: TipoEvento) { @FXML lateinit private var fecha: TextField @FXML lateinit private var cantidad: TextField @FXML lateinit private var detalle: TextArea private val now = LocalDateTime.now() private fun close() = (fecha.scene.window as Stage).close() @FXML private fun initialize() { fecha.text = now.formatDateTime() } @FXML private fun aceptarOnAction(event: ActionEvent) { val cantidadReal: Int if (detalle.text.length == 0) { Message.error("Debe ingresar un detalle") return } if (cantidad.text.length == 0) { Message.error("Ingrese una cantidad") return } try { cantidadReal = cantidad.text.toInt() } catch (e: NumberFormatException) { Message.error("La cantidad debe ser un número entero") return } if (tipo == TipoEvento.SALIDA && cantidadReal > articulo.existencia) { Message.error("No puede satisfacerse la salida. Máximo ${articulo.existencia}.") return } val articuloId = articulo.id val detalle = detalle.text val evento = Evento(0, tipo, articuloId, detalle, cantidadReal, now) val mod = if (tipo == TipoEvento.ENTRADA) cantidadReal else -cantidadReal articulo.existencia += mod DB.crearEvento(evento) DB.updateArticulo(articulo) close() } @FXML private fun cancelarOnAction(event: ActionEvent) = close() }
apache-2.0
901ed72b1cb50de5fde8affdb3fab998
29.204545
92
0.676825
3.780939
false
false
false
false
simonorono/SRSM
src/main/kotlin/srsm/window/FormActividad.kt
1
1407
/* * Copyright 2016 Sociedad Religiosa Servidores de María * * 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 srsm.window import javafx.fxml.FXMLLoader import javafx.scene.Parent import javafx.scene.Scene import javafx.stage.Stage import srsm.controller.FormActividad import srsm.model.Actividad class FormActividad(actividad: Actividad? = null, editable: Boolean = true) { private val stage = Stage() init { stage.isResizable = false val loader = FXMLLoader(javaClass.classLoader.getResource("fxml/form_actividad.fxml")) val root: Parent = loader.load() val scene = Scene(root) val cont = loader.getController<FormActividad>() cont.actividad = actividad cont.editable = editable cont.init() stage.title = "Actividad" stage.scene = scene } fun showAndWait() = stage.showAndWait() }
apache-2.0
c1c6411d939f691042b63187f49ee3e0
29.565217
94
0.709815
4.017143
false
false
false
false
world-federation-of-advertisers/common-jvm
src/main/kotlin/org/wfanet/measurement/common/ByteStringOutputBuffer.kt
1
2122
// 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.common import com.google.protobuf.ByteString import java.nio.ByteBuffer import java.nio.channels.Channels import java.nio.channels.WritableByteChannel /** Fixed capacity [ByteString.Output] buffer for outputting [ByteString] instances. */ class ByteStringOutputBuffer(private val capacity: Int) : AutoCloseable { init { require(capacity > 0) } private val output = ByteString.newOutput(capacity) private val channel: WritableByteChannel = Channels.newChannel(output) /** Size of this buffer in bytes. */ val size: Int get() = output.size() /** Whether the buffer is full. */ val full: Boolean get() = size == capacity /** Clears all bytes from the buffer. */ fun clear() = output.reset() /** * Puts the remaining bytes from the source buffer into this buffer until either there are no more * remaining bytes in the source or this buffer is full. */ fun putUntilFull(source: ByteBuffer) { if (full) return val remainingCapacity = capacity - size if (source.remaining() > remainingCapacity) { val originalLimit = source.limit() source.limit(source.position() + remainingCapacity) channel.write(source) source.limit(originalLimit) } else { channel.write(source) } } /** @see ByteString.Output.toByteString() */ fun toByteString(): ByteString = output.toByteString() /** Closes the underlying [ByteString.Output]. */ override fun close() { channel.close() } }
apache-2.0
d42a00b6558a09ea12c2a159f31721cf
30.671642
100
0.713007
4.295547
false
true
false
false
charbgr/CliffHanger
cliffhanger/feature-movie-detail/src/main/kotlin/com/github/charbgr/cliffhanger/features/detail/arch/ViewModel.kt
1
457
package com.github.charbgr.cliffhanger.features.detail.arch import com.github.charbgr.cliffhanger.domain.FullMovie data class ViewModel( val showLoader: Boolean, val showMovie: Boolean, val showError: Boolean, val throwable: Throwable? = null, val movie: FullMovie? = null ) { companion object { fun Initial() = ViewModel( showLoader = false, showMovie = false, showError = false, movie = null ) } }
mit
9f26f2576351b203dbcdbcaef3d03f15
20.761905
59
0.673961
3.973913
false
false
false
false
ffgiraldez/rx-mvvm-android
app/src/main/java/es/ffgiraldez/comicsearch/query/base/ui/QueryScreenDelegate.kt
1
896
package es.ffgiraldez.comicsearch.query.base.ui import es.ffgiraldez.comicsearch.comics.domain.Volume import es.ffgiraldez.comicsearch.navigation.Navigator import es.ffgiraldez.comicsearch.navigation.Screen import es.ffgiraldez.comicsearch.query.search.presentation.SuspendSearchViewModel import es.ffgiraldez.comicsearch.query.sugestion.presentation.SuspendSuggestionViewModel class QueryScreenDelegate( val suggestions: SuspendSuggestionViewModel, val search: SuspendSearchViewModel, val adapter: QueryVolumeAdapter, private val navigator: Navigator ) { fun onVolumeSelected(volume: Volume): Unit = navigator.to(Screen.Detail(volume)) fun onQueryChange(new: String): Unit = with(suggestions) { query.value = new } fun onSuggestionSelected(suggestion: String): Unit = with(search) { query.value = suggestion } }
apache-2.0
aaa491d6b2ce3a9041cea82c62682ccd
38
88
0.760045
4.666667
false
false
false
false
anthologist/Simple-Gallery
app/src/main/kotlin/com/simplemobiletools/gallery/helpers/MediaSideScroll.kt
1
6704
package com.simplemobiletools.gallery.helpers import android.app.Activity import android.content.Context import android.media.AudioManager import android.os.Handler import android.provider.Settings import android.util.AttributeSet import android.view.MotionEvent import android.view.ViewGroup import android.widget.RelativeLayout import android.widget.TextView import com.simplemobiletools.gallery.R import com.simplemobiletools.gallery.activities.ViewPagerActivity import com.simplemobiletools.gallery.extensions.audioManager // allow horizontal swipes through the layout, else it can cause glitches at zoomed in images class MediaSideScroll(context: Context, attrs: AttributeSet) : RelativeLayout(context, attrs) { private val SLIDE_INFO_FADE_DELAY = 1000L private var mTouchDownX = 0f private var mTouchDownY = 0f private var mTouchDownTime = 0L private var mTouchDownValue = -1 private var mTempBrightness = 0 private var mLastTouchY = 0f private var mIsBrightnessScroll = false private var mPassTouches = false private var dragThreshold = DRAG_THRESHOLD * context.resources.displayMetrics.density private var mSlideInfoText = "" private var mSlideInfoFadeHandler = Handler() private var mParentView: ViewGroup? = null private lateinit var activity: Activity private lateinit var slideInfoView: TextView private lateinit var callback: (Float, Float) -> Unit fun initialize(activity: Activity, slideInfoView: TextView, isBrightness: Boolean, parentView: ViewGroup?, callback: (x: Float, y: Float) -> Unit) { this.activity = activity this.slideInfoView = slideInfoView this.callback = callback mParentView = parentView mIsBrightnessScroll = isBrightness mSlideInfoText = activity.getString(if (isBrightness) R.string.brightness else R.string.volume) } override fun dispatchTouchEvent(ev: MotionEvent): Boolean { if (mPassTouches) { if (ev.actionMasked == MotionEvent.ACTION_DOWN) { mPassTouches = false } return false } return super.dispatchTouchEvent(ev) } override fun onTouchEvent(event: MotionEvent): Boolean { if (mPassTouches) { return false } when (event.actionMasked) { MotionEvent.ACTION_DOWN -> { mTouchDownX = event.x mTouchDownY = event.y mLastTouchY = event.y mTouchDownTime = System.currentTimeMillis() if (mIsBrightnessScroll) { if (mTouchDownValue == -1) { mTouchDownValue = getCurrentBrightness() } } else { mTouchDownValue = getCurrentVolume() } } MotionEvent.ACTION_MOVE -> { val diffX = mTouchDownX - event.x val diffY = mTouchDownY - event.y if (Math.abs(diffY) > dragThreshold && Math.abs(diffY) > Math.abs(diffX)) { var percent = ((diffY / ViewPagerActivity.screenHeight) * 100).toInt() * 3 percent = Math.min(100, Math.max(-100, percent)) if ((percent == 100 && event.y > mLastTouchY) || (percent == -100 && event.y < mLastTouchY)) { mTouchDownY = event.y mTouchDownValue = if (mIsBrightnessScroll) mTempBrightness else getCurrentVolume() } percentChanged(percent) } else if (Math.abs(diffX) > dragThreshold || Math.abs(diffY) > dragThreshold) { if (!mPassTouches) { event.action = MotionEvent.ACTION_DOWN event.setLocation(event.rawX, event.y) mParentView?.dispatchTouchEvent(event) } mPassTouches = true mParentView?.dispatchTouchEvent(event) return false } mLastTouchY = event.y } MotionEvent.ACTION_UP -> { if (System.currentTimeMillis() - mTouchDownTime < CLICK_MAX_DURATION) { callback(event.rawX, event.rawY) } if (mIsBrightnessScroll) { mTouchDownValue = mTempBrightness } } } return true } private fun getCurrentVolume() = activity.audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) private fun getCurrentBrightness(): Int { return try { Settings.System.getInt(activity.contentResolver, Settings.System.SCREEN_BRIGHTNESS) } catch (e: Settings.SettingNotFoundException) { 70 } } private fun percentChanged(percent: Int) { if (mIsBrightnessScroll) { brightnessPercentChanged(percent) } else { volumePercentChanged(percent) } } private fun volumePercentChanged(percent: Int) { val stream = AudioManager.STREAM_MUSIC val maxVolume = activity.audioManager.getStreamMaxVolume(stream) val percentPerPoint = 100 / maxVolume val addPoints = percent / percentPerPoint val newVolume = Math.min(maxVolume, Math.max(0, mTouchDownValue + addPoints)) activity.audioManager.setStreamVolume(stream, newVolume, 0) val absolutePercent = ((newVolume / maxVolume.toFloat()) * 100).toInt() showValue(absolutePercent) mSlideInfoFadeHandler.removeCallbacksAndMessages(null) mSlideInfoFadeHandler.postDelayed({ slideInfoView.animate().alpha(0f) }, SLIDE_INFO_FADE_DELAY) } private fun brightnessPercentChanged(percent: Int) { val maxBrightness = 255f var newBrightness = (mTouchDownValue + 2.55 * percent).toFloat() newBrightness = Math.min(maxBrightness, Math.max(0f, newBrightness)) mTempBrightness = newBrightness.toInt() val absolutePercent = ((newBrightness / maxBrightness) * 100).toInt() showValue(absolutePercent) val attributes = activity.window.attributes attributes.screenBrightness = absolutePercent / 100f activity.window.attributes = attributes mSlideInfoFadeHandler.removeCallbacksAndMessages(null) mSlideInfoFadeHandler.postDelayed({ slideInfoView.animate().alpha(0f) }, SLIDE_INFO_FADE_DELAY) } private fun showValue(percent: Int) { slideInfoView.apply { text = "$mSlideInfoText:\n$percent%" alpha = 1f } } }
apache-2.0
ea2b48c47cc3884569ecfeb4017bb5c4
37.308571
152
0.621122
4.954915
false
false
false
false
google/horologist
audio-ui/src/debug/java/com/google/android/horologist/audio/ui/components/animated/AnimatedSetVolumeButtonPreview.kt
1
1937
/* * 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.audio.ui.components.animated import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.wear.compose.material.Stepper import com.google.android.horologist.audio.VolumeState import com.google.android.horologist.audio.ui.VolumeScreenDefaults.DecreaseIcon import com.google.android.horologist.audio.ui.VolumeScreenDefaults.IncreaseIcon import com.google.android.horologist.compose.tools.WearSmallRoundDevicePreview @WearSmallRoundDevicePreview @Composable fun AnimatedSetVolumeButtonPreview() { var volumeState by remember { mutableStateOf(VolumeState(3, 5)) } InteractivePreviewAware { Stepper( value = volumeState.current.toFloat(), onValueChange = { volumeState = volumeState.copy(current = it.toInt()) }, steps = volumeState.max - 1, valueRange = (0f..volumeState.max.toFloat()), increaseIcon = { IncreaseIcon() }, decreaseIcon = { DecreaseIcon() } ) { AnimatedSetVolumeButton(onVolumeClick = { }, volumeState = volumeState) } } }
apache-2.0
dc440fb044e1a215796fb93c91399a18
36.980392
85
0.721218
4.422374
false
false
false
false
epabst/kotlin-showcase
src/jsMain/kotlin/bootstrap/NavLink.kt
1
878
@file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS", "EXTERNAL_DELEGATION", "unused") @file:JsModule("react-bootstrap") package bootstrap import react.RProps external interface NavLinkProps : RProps { var active: Boolean? get() = definedExternally; set(value) = definedExternally var disabled: Boolean? get() = definedExternally; set(value) = definedExternally var role: String? get() = definedExternally; set(value) = definedExternally var href: String? get() = definedExternally; set(value) = definedExternally var onSelect: SelectCallback? get() = definedExternally; set(value) = definedExternally var eventKey: Any? get() = definedExternally; set(value) = definedExternally } abstract external class NavLink<As : React.ElementType> : BsPrefixComponent<As, NavLinkProps>
apache-2.0
428976881129e32a8aec161d8686d3f7
57.6
164
0.76082
4.346535
false
false
false
false
ptaylor/autograph
src/main/kotlin/org/pftylr/autograph/Autograph.kt
1
6131
/* * MIT License * * Copyright (c) 2017 ptaylor * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ package org.pftylr.autograph import org.pftylr.autograph.InputStreamDataSource import org.pftylr.autograph.Graph import javafx.application.Application import javafx.event.ActionEvent import javafx.event.EventHandler import javafx.scene.Scene import javafx.scene.Group import javafx.scene.control.Button import javafx.scene.layout.StackPane import javafx.stage.Stage import javafx.scene.canvas.Canvas import javafx.scene.paint.Color import javafx.scene.canvas.GraphicsContext import javafx.concurrent.Task import javafx.application.Platform import javafx.beans.value.ChangeListener import javafx.beans.value.ObservableValue import java.util.Properties class Autograph : Application() { fun run(args: Array<String>) { launch(*args) } override fun init() { } override fun stop() { System.exit(0) } override fun start(stage: Stage) { try { val options = Options() options.addProperties(processArgs()) options.addSystemProperties() options.addPropertiesFile("${System.getProperty("user.home")}/.autograph.properties") options.addPropertiesResource("org/pftylr/autograph/autograph.properties") val width = options.getDoubleValue("width") val height = options.getDoubleValue("height") val size = options.getIntValue("size") val bg_colour = Color.valueOf(options.getStringValue("bg_colour")) val title = options.getStringValue("title") val root = Group() val scene = Scene(root, width!!, height!!, bg_colour); stage.setTitle(title); stage.setScene(scene); stage.show(); val dataSource = InputStreamDataSource(System.`in`) val graph = Graph(root, dataSource, scene.width, scene.height, size!!, options) val changeListener = object : ChangeListener<Number?> { public override fun changed(observable: ObservableValue<out Number?>?, oldValue: Number?, newValue: Number?) { graph.resize(scene.width, scene.height) } } scene.widthProperty().addListener(changeListener) scene.heightProperty().addListener(changeListener) graph.run() } catch (e: Exception) { System.err.println("exception ${e}") } } private fun processArgs() : Properties { val p = Properties() val args = getParameters().getRaw() var skip : Boolean = false args.forEachIndexed { i, v -> if (skip) { skip = false } else { when (v) { "--title", "-t" -> { setStringArg(p, "title", v, args, i + 1) skip = true } "--width", "-w" -> { setStringArg(p, "width", v, args, i + 1) skip = true } "--height", "-h" -> { setStringArg(p, "height", v, args, i + 1) skip = true } "--size", "-s" -> { setStringArg(p, "size", v, args, i + 1) skip = true } "--minmax", "-m" -> { setBooleanArg(p, "minmax.enabled", v, args, i + 1) skip = true } else -> fatal("unknown argument: ${v}") } } } return p } private fun setStringArg(p: Properties, name: String, aname: String, args: List<String>, i: Int) { p.setProperty(name, getArgValue(aname, args, i)) } private fun setBooleanArg(p: Properties, name: String, aname: String, args: List<String>, i: Int) { val v = getArgValue(aname, args, i) when (v.toLowerCase()) { "true", "t", "yes", "on" -> p.setProperty(name, "true") else -> p.setProperty(name, "false") } } private fun getArgValue(aname: String, args: List<String>, i: Int) : String { try { return args.get(i) } catch (e: IndexOutOfBoundsException) { fatal("missing value for argument: ${aname}") return "" } } private fun fatal(s: String) { System.err.println("ERROR: ${s}") System.err.println(""" |usage: autograph | | --title|-t <TITLE> - set the window title to <TITLE>. | --width|-w <N> - set the window width to <N> | --height|-h <N> - set the window height to <N> | --size|-s <N> - set the max number of data elements to <N> | --minmax|-m <B> - if <B> is true display min/max lines | """.trimMargin()) Platform.exit() } }
mit
868672d0c9bb95a13139e500fe16e458
31.268421
126
0.56826
4.455669
false
false
false
false
Doctoror/FuckOffMusicPlayer
presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/recentactivity/RecentActivityFragmentModule.kt
2
2462
package com.doctoror.fuckoffmusicplayer.presentation.recentactivity import android.content.res.Resources import com.doctoror.commons.reactivex.SchedulersProvider import com.doctoror.fuckoffmusicplayer.RuntimePermissions import com.doctoror.fuckoffmusicplayer.di.scopes.FragmentScope import com.doctoror.fuckoffmusicplayer.domain.albums.AlbumsProvider import com.doctoror.fuckoffmusicplayer.domain.queue.QueueProviderAlbums import com.doctoror.fuckoffmusicplayer.presentation.library.LibraryPermissionsProvider import com.doctoror.fuckoffmusicplayer.presentation.library.albums.AlbumClickHandler import com.doctoror.fuckoffmusicplayer.presentation.rxpermissions.RxPermissionsProvider import dagger.Module import dagger.Provides @Module class RecentActivityFragmentModule { @Provides @FragmentScope fun provideAlbumItemsFactory() = AlbumItemsFactory() @Provides @FragmentScope fun provideAlbumClickHandler( fragment: RecentActivityFragment, queueProvider: QueueProviderAlbums) = AlbumClickHandler(fragment, queueProvider) @Provides @FragmentScope fun provideRecentActivityPresenter( albumClickHandler: AlbumClickHandler, albumItemsFactory: AlbumItemsFactory, albumsProvider: AlbumsProvider, libraryPermissionProvider: LibraryPermissionsProvider, resources: Resources, runtimePermissions: RuntimePermissions, schedulersProvider: SchedulersProvider, viewModel: RecentActivityViewModel ) = RecentActivityPresenter( albumClickHandler, albumItemsFactory, albumsProvider, libraryPermissionProvider, resources, runtimePermissions, schedulersProvider, viewModel) @Provides @FragmentScope fun provideRecentActivityViewModel() = RecentActivityViewModel() @Provides @FragmentScope fun provideRxPermissionsProvider(fragment: RecentActivityFragment) = RxPermissionsProvider(fragment.requireActivity()) @Provides @FragmentScope fun provideLibraryPermissionsProvider( fragment: RecentActivityFragment, runtimePermissions: RuntimePermissions, rxPermissionsProvider: RxPermissionsProvider ) = LibraryPermissionsProvider( fragment.requireContext(), runtimePermissions, rxPermissionsProvider) }
apache-2.0
2c0cb88cb3b360b5ba0888573d1b37f9
35.205882
92
0.745735
6.109181
false
false
false
false
TheFallOfRapture/Morph
src/main/kotlin/com/morph/engine/graphics/Texture.kt
2
5675
package com.morph.engine.graphics import com.morph.engine.util.IOUtils import org.lwjgl.BufferUtils import org.lwjgl.opengl.GL11.* import org.lwjgl.opengl.GL12.GL_CLAMP_TO_EDGE import org.lwjgl.opengl.GL13.GL_TEXTURE0 import org.lwjgl.opengl.GL13.glActiveTexture import org.lwjgl.stb.STBTTBakedChar import org.lwjgl.stb.STBTruetype import java.io.IOException import java.nio.ByteBuffer import java.util.* import javax.imageio.ImageIO class Texture { val filename: String private val resource: TextureResource? // TODO: Make non-nullable, an error in texture loading should return an empty Texture constructor(filename: String?) { this.filename = filename ?: "textures/solid.png" val oldResource = loadedTextures[this.filename] if (oldResource != null) { this.resource = oldResource resource.addReference() } else { resource = loadTexture(this.filename) loadedTextures[this.filename] = resource!! } } constructor(font: String?, size: Int, bitmapWidth: Int, bitmapHeight: Int) { this.filename = font ?: "C:/Windows/Fonts/arial.ttf" val oldResource = loadedTextures[this.filename + ":" + size] if (oldResource != null) { this.resource = oldResource resource.addReference() } else { resource = loadFont(this.filename, size, bitmapWidth, bitmapHeight) loadedTextures[this.filename] = resource } } constructor(id: String, width: Int, height: Int, pixels: ByteBuffer) { this.filename = id val oldResource = loadedTextures[this.filename] if (oldResource != null) { this.resource = oldResource resource.addReference() } else { resource = loadTextureFromByteBuffer(width, height, pixels) loadedTextures[this.filename] = resource } } private fun loadTextureFromByteBuffer(width: Int, height: Int, buffer: ByteBuffer): TextureResource { val id = glGenTextures() buffer.flip() glBindTexture(GL_TEXTURE_2D, id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glPixelStorei(GL_UNPACK_ALIGNMENT, 1) glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, width, height, 0, GL_ALPHA, GL_UNSIGNED_BYTE, buffer) return TextureResource(id) } private fun loadTexture(filename: String): TextureResource? { try { val image = ImageIO.read(Texture::class.java.classLoader.getResourceAsStream(filename)) val pixels = image.getRGB(0, 0, image.width, image.height, null, 0, image.width) val buffer = BufferUtils.createByteBuffer(image.width * image.height * 4) val hasAlpha = image.colorModel.hasAlpha() for (y in 0 until image.height) { for (x in 0 until image.width) { val color = pixels[x + y * image.width] buffer.put((color shr 16 and 0xff).toByte()) buffer.put((color shr 8 and 0xff).toByte()) buffer.put((color and 0xff).toByte()) if (hasAlpha) buffer.put((color shr 24 and 0xff).toByte()) else buffer.put(0xff.toByte()) } } buffer.flip() val id = glGenTextures() glBindTexture(GL_TEXTURE_2D, id) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.width, image.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer) return TextureResource(id) } catch (e: IOException) { e.printStackTrace() } return null } private fun loadFont(font: String, size: Int, bitmapWidth: Int, bitmapHeight: Int): TextureResource { val texture = glGenTextures() val chars = STBTTBakedChar.malloc(96) try { val fontBuffer = IOUtils.getFileAsByteBuffer(font, 160 * 1024) val bitmap = BufferUtils.createByteBuffer(bitmapWidth * bitmapHeight) STBTruetype.stbtt_BakeFontBitmap(fontBuffer, size.toFloat(), bitmap, bitmapWidth, bitmapHeight, 32, chars) glBindTexture(GL_TEXTURE_2D, texture) glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, bitmapWidth, bitmapHeight, 0, GL_ALPHA, GL_UNSIGNED_BYTE, bitmap) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR) } catch (e: IOException) { throw RuntimeException(e) } return TextureResource(texture) } fun destroy() { resource!!.removeReference() } fun bind() { glActiveTexture(GL_TEXTURE0) glBindTexture(GL_TEXTURE_2D, resource!!.id) } fun bind(i: Int) { glActiveTexture(GL_TEXTURE0 + i) glBindTexture(GL_TEXTURE_2D, resource!!.id) } fun unbind() { glBindTexture(GL_TEXTURE_2D, 0) } companion object { private val loadedTextures = HashMap<String, TextureResource>() } }
mit
8103939927d8d2e680eeb1cdcc5954dd
34.030864
129
0.621322
4.056469
false
false
false
false
msebire/intellij-community
python/src/com/jetbrains/python/inspections/PyThirdPartyInspectionExtension.kt
1
1699
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.inspections import com.intellij.util.containers.ContainerUtil import com.jetbrains.python.psi.PyElement import com.jetbrains.python.psi.PyExpression import com.jetbrains.python.psi.PyFunction import com.jetbrains.python.psi.PyUtil import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.QualifiedNameFinder import com.jetbrains.python.psi.types.TypeEvalContext class PyThirdPartyInspectionExtension : PyInspectionExtension() { override fun ignoreMethodParameters(function: PyFunction, context: TypeEvalContext): Boolean { val cls = function.containingClass if (cls != null) { // zope.interface.Interface inheritor could have any parameters val interfaceQName = "zope.interface.interface.Interface" if (cls.isSubclass(interfaceQName, context)) return true // Checking for subclassing above does not help while zope.interface.Interface is defined as target with call expression assigned val resolveContext = PyResolveContext.noImplicits().withTypeEvalContext(context) for (expression in cls.superClassExpressions) { if (resolvesTo(expression, interfaceQName, resolveContext)) return true } } return false } private fun resolvesTo(expression: PyExpression, qualifiedName: String, resolveContext: PyResolveContext): Boolean { return ContainerUtil.exists(PyUtil.multiResolveTopPriority(expression, resolveContext)) { it is PyElement && QualifiedNameFinder.getQualifiedName(it) == qualifiedName } } }
apache-2.0
f2a49b1e5115516bea06ccc5073faa41
44.945946
140
0.783991
4.785915
false
false
false
false
laurencegw/jenjin
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/async/Tasks.kt
1
1516
package com.binarymonks.jj.core.async import com.binarymonks.jj.core.api.TasksAPI import com.binarymonks.jj.core.pools.Poolable import com.binarymonks.jj.core.pools.new import com.binarymonks.jj.core.pools.recycle import kotlin.reflect.KFunction class Tasks : TasksAPI { internal var preloopTasks = TaskMaster() internal var postPhysicsTasks = TaskMaster() internal var prePhysicsTasks = TaskMaster() override fun addPreLoopTask(task: Task) { preloopTasks.addTask(task) } override fun addPostPhysicsTask(task: Task) { postPhysicsTasks.addTask(task) } override fun doOnceAfterPhysics(fn: () -> Unit) { postPhysicsTasks.addTask(new(OneTimeFunctionWrapper::class).set(fn)) } override fun doOnceAfterPhysicsCapture(function: KFunction<*>, build: (FunctionClosureBuilder.() -> Unit)?) { val functionCapture = capture(function, build) postPhysicsTasks.addTask(new(OneTimeFunctionWrapper::class).set(functionCapture::call)) } override fun addPrePhysicsTask(task: Task) { prePhysicsTasks.addTask(task) } } internal class OneTimeFunctionWrapper : OneTimeTask(), Poolable { var function: (() -> Unit)? = null fun set(fn: () -> Unit): OneTimeFunctionWrapper { function = fn return this } override fun doOnce() { function!!() } override fun reset() { function = null } override fun tearDown() { super.tearDown() recycle(this) } }
apache-2.0
a7c3ae8e2112157f0dd2822e7fbf57fb
25.137931
113
0.677441
4.153425
false
false
false
false
czyzby/gdx-setup
src/main/kotlin/com/github/czyzby/setup/data/templates/unofficial/autumnMvcVis.kt
2
22753
package com.github.czyzby.setup.data.templates.unofficial import com.github.czyzby.setup.data.files.CopiedFile import com.github.czyzby.setup.data.files.SourceFile import com.github.czyzby.setup.data.files.path import com.github.czyzby.setup.data.libs.unofficial.LMLVis import com.github.czyzby.setup.data.platforms.Assets import com.github.czyzby.setup.data.platforms.Core import com.github.czyzby.setup.data.project.Project import com.github.czyzby.setup.views.ProjectTemplate /** * A solid application base using Autumn MVC. * @author MJ */ @ProjectTemplate open class AutumnMvcVisTemplate : AutumnMvcBasicTemplate() { override val id = "autumnMvcVisTemplate" override val generateSkin = false override val description: String get() = "Project template included launchers with [Autumn](https://github.com/czyzby/gdx-lml/tree/master/autumn) class scanners and a basic [Autumn MVC](https://github.com/czyzby/gdx-lml/tree/master/mvc) application." override fun getReflectedClasses(project: Project): Array<String> = arrayOf("com.github.czyzby.autumn.mvc.component.preferences.dto.AbstractPreference") override fun getReflectedPackages(project: Project): Array<String> = arrayOf("${project.basic.rootPackage}.configuration", "${project.basic.rootPackage}.controller", "${project.basic.rootPackage}.service") override fun getApplicationListenerContent(project: Project): String = """package ${project.basic.rootPackage}; /** This class serves only as the application scanning root. Any classes in its package (or any of the sub-packages) * with proper Autumn MVC annotations will be found, scanned and initiated. */ public class ${project.basic.mainClass} { /** Default application size. */ public static final int WIDTH = 480, HEIGHT = 360; }""" override fun apply(project: Project) { super.apply(project) addResources(project) addSources(project) // Adding VisUI support: LMLVis().initiate(project) } protected open fun addResources(project: Project) { // Adding resources: project.files.add(CopiedFile(projectName = Assets.ID, path = path("images", "libgdx.png"), original = path("generator", "templates", "libgdx.png"))) project.files.add(CopiedFile(projectName = Assets.ID, path = path("music", "theme.ogg"), original = path("generator", "templates", "autumn", "theme.ogg"))) // Adding I18N bundle: arrayOf("", "_en", "_pl").forEach { val fileName = "bundle${it}.properties" project.files.add(CopiedFile(projectName = Assets.ID, path = path("i18n", fileName), original = path("generator", "templates", "autumn", fileName))) } } protected open fun addSources(project: Project) { project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.configuration", fileName = "Configuration.java", content = """package ${project.basic.rootPackage}.configuration; import com.badlogic.gdx.utils.viewport.FitViewport; import com.badlogic.gdx.utils.viewport.Viewport; import com.github.czyzby.autumn.annotation.Component; import com.github.czyzby.autumn.annotation.Initiate; import com.github.czyzby.autumn.mvc.component.ui.SkinService; import com.github.czyzby.autumn.mvc.stereotype.preference.AvailableLocales; import com.github.czyzby.autumn.mvc.stereotype.preference.I18nBundle; import com.github.czyzby.autumn.mvc.stereotype.preference.I18nLocale; import com.github.czyzby.autumn.mvc.stereotype.preference.LmlMacro; import com.github.czyzby.autumn.mvc.stereotype.preference.LmlParserSyntax; import com.github.czyzby.autumn.mvc.stereotype.preference.Preference; import com.github.czyzby.autumn.mvc.stereotype.preference.StageViewport; import com.github.czyzby.autumn.mvc.stereotype.preference.sfx.MusicEnabled; import com.github.czyzby.autumn.mvc.stereotype.preference.sfx.MusicVolume; import com.github.czyzby.autumn.mvc.stereotype.preference.sfx.SoundEnabled; import com.github.czyzby.autumn.mvc.stereotype.preference.sfx.SoundVolume; import com.github.czyzby.kiwi.util.gdx.asset.lazy.provider.ObjectProvider; import com.github.czyzby.lml.parser.LmlSyntax; import com.github.czyzby.lml.util.Lml; import com.github.czyzby.lml.vis.parser.impl.VisLmlSyntax; import com.kotcrab.vis.ui.VisUI; import ${project.basic.rootPackage}.${project.basic.mainClass}; import ${project.basic.rootPackage}.service.ScaleService; /** Thanks to the Component annotation, this class will be automatically found and processed. * * This is a utility class that configures application settings. */ @Component public class Configuration { /** Name of the application's preferences file. */ public static final String PREFERENCES = "${project.basic.name}"; /** Path to the internationalization bundle. */ @I18nBundle private final String bundlePath = "i18n/bundle"; /** Enabling VisUI usage. */ @LmlParserSyntax private final LmlSyntax syntax = new VisLmlSyntax(); /** Parsing macros available in all views. */ @LmlMacro private final String globalMacro = "ui/templates/macros/global.lml"; /** Using a custom viewport provider - Autumn MVC defaults to the ScreenViewport, as it is the only viewport that * doesn't need to know application's targeted screen size. This provider overrides that by using more sophisticated * FitViewport that works on virtual units rather than pixels. */ @StageViewport private final ObjectProvider<Viewport> viewportProvider = new ObjectProvider<Viewport>() { @Override public Viewport provide() { return new FitViewport(${project.basic.mainClass}.WIDTH, ${project.basic.mainClass}.HEIGHT); } }; /** These sound-related fields allow MusicService to store settings in preferences file. Sound preferences will be * automatically saved when the application closes and restored the next time it's turned on. Sound-related methods * methods will be automatically added to LML templates - see settings.lml template. */ @SoundVolume(preferences = PREFERENCES) private final String soundVolume = "soundVolume"; @SoundEnabled(preferences = PREFERENCES) private final String soundEnabled = "soundOn"; @MusicVolume(preferences = PREFERENCES) private final String musicVolume = "musicVolume"; @MusicEnabled(preferences = PREFERENCES) private final String musicEnabledPreference = "musicOn"; /** These i18n-related fields will allow LocaleService to save game's locale in preferences file. Locale changing * actions will be automatically added to LML templates - see settings.lml template. */ @I18nLocale(propertiesPath = PREFERENCES, defaultLocale = "en") private final String localePreference = "locale"; @AvailableLocales private final String[] availableLocales = new String[] { "en", "pl" }; /** Setting the default Preferences object path. */ @Preference private final String preferencesPath = PREFERENCES; /** Thanks to the Initiate annotation, this method will be automatically invoked during context building. All * method's parameters will be injected with values from the context. * * @param scaleService contains current GUI scale. * @param skinService contains GUI skin. */ @Initiate public void initiateConfiguration(final ScaleService scaleService, final SkinService skinService) { // Loading default VisUI skin with the selected scale: VisUI.load(scaleService.getScale()); // Registering VisUI skin with "default" name - this skin will be the default one for all LML widgets: skinService.addSkin("default", VisUI.getSkin()); // Thanks to this setting, only methods annotated with @LmlAction will be available in views, significantly // speeding up method look-up: Lml.EXTRACT_UNANNOTATED_METHODS = false; } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.configuration.preferences", fileName = "ScalePreference.java", content = """package ${project.basic.rootPackage}.configuration.preferences; import com.badlogic.gdx.scenes.scene2d.Actor; import com.github.czyzby.autumn.mvc.component.preferences.dto.AbstractPreference; import com.github.czyzby.autumn.mvc.stereotype.preference.Property; import com.github.czyzby.lml.util.LmlUtilities; import com.kotcrab.vis.ui.VisUI.SkinScale; /** Thanks to the Property annotation, this class will be automatically found and initiated. * * This class manages VisUI scale preference. */ @Property("Scale") public class ScalePreference extends AbstractPreference<SkinScale> { @Override public SkinScale getDefault() { return SkinScale.X2; } @Override public SkinScale extractFromActor(final Actor actor) { return convert(LmlUtilities.getActorId(actor)); } @Override protected SkinScale convert(final String rawPreference) { return SkinScale.valueOf(rawPreference); } @Override protected String serialize(final SkinScale preference) { return preference.name(); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller", fileName = "LoadingController.java", content = """package ${project.basic.rootPackage}.controller; import com.badlogic.gdx.scenes.scene2d.Stage; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.component.asset.AssetService; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewRenderer; import com.github.czyzby.autumn.mvc.stereotype.View; import com.github.czyzby.lml.annotation.LmlActor; import com.kotcrab.vis.ui.widget.VisProgressBar; /** Thanks to View annotation, this class will be automatically found and initiated. * * This is the first application's view, shown right after the application starts. It will hide after all assests are * loaded. */ @View(value = "ui/templates/loading.lml", first = true) public class LoadingController implements ViewRenderer { /** Will be injected automatically. Manages assets. Used to display loading progress. */ @Inject private AssetService assetService; /** This is a widget injected from the loading.lml template. "loadingBar" is its ID. */ @LmlActor("loadingBar") private VisProgressBar loadingBar; // Since this class implements ViewRenderer, it can modify the way its view is drawn. Additionally to drawing the // stage, this view also updates assets manager and reads its progress. @Override public void render(final Stage stage, final float delta) { assetService.update(); loadingBar.setValue(assetService.getLoadingProgress()); stage.act(delta); stage.draw(); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller", fileName = "MenuController.java", content = """package ${project.basic.rootPackage}.controller; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.scenes.scene2d.Stage; import com.github.czyzby.autumn.mvc.component.ui.controller.ViewRenderer; import com.github.czyzby.autumn.mvc.stereotype.Asset; import com.github.czyzby.autumn.mvc.stereotype.View; /** Thanks to View annotation, this class will be automatically found and initiated. * * This is application's main view, displaying a menu with several options. */ @View(id = "menu", value = "ui/templates/menu.lml", themes = "music/theme.ogg") public class MenuController implements ViewRenderer { /** Asset-annotated files will be found and automatically loaded by the AssetsService. */ @Asset("images/libgdx.png") private Texture logo; @Override public void render(final Stage stage, final float delta) { // As a proof of concept that you can pair custom logic with Autumn MVC views, this class implements // ViewRenderer and handles view rendering manually. It renders LibGDX logo before drawing the stage. stage.act(delta); final Batch batch = stage.getBatch(); batch.setColor(stage.getRoot().getColor()); // We want the logo to share color alpha with the stage. batch.begin(); batch.draw(logo, (int) (stage.getWidth() - logo.getWidth()) / 2, (int) (stage.getHeight() - logo.getHeight()) / 2); batch.end(); stage.draw(); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller.action", fileName = "Global.java", content = """package ${project.basic.rootPackage}.controller.action; import com.github.czyzby.autumn.mvc.stereotype.ViewActionContainer; import com.github.czyzby.lml.annotation.LmlAction; import com.github.czyzby.lml.parser.action.ActionContainer; /** Since this class implements ActionContainer and is annotated with ViewActionContainer, its methods will be reflected * and available in all LML templates. Note that this class is a component like any other, so it can inject any fields, * use Initiate-annotated methods, etc. */ @ViewActionContainer("global") public class Global implements ActionContainer { /** This is a mock-up method that does nothing. It will be available in LML templates through "close" (annotation * argument) and "noOp" (method name) IDs. */ @LmlAction("close") public void noOp() { } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.controller.dialog", fileName = "SettingsController.java", content = """package ${project.basic.rootPackage}.controller.dialog; import com.badlogic.gdx.scenes.scene2d.Actor; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.stereotype.ViewDialog; import com.github.czyzby.lml.annotation.LmlAction; import com.github.czyzby.lml.parser.action.ActionContainer; import com.kotcrab.vis.ui.VisUI.SkinScale; import ${project.basic.rootPackage}.service.ScaleService; /** This is a settings dialog, which can be shown in any view by using "show:settings" LML action or - in Java code - * through InterfaceService.showDialog(Class) method. Thanks to the fact that it implements ActionContainer, its methods * will be available in the LML template. */ @ViewDialog(id = "settings", value = "ui/templates/dialogs/settings.lml") public class SettingsController implements ActionContainer { // @Inject-annotated fields will be automatically filled with values from the context. @Inject private ScaleService scaleService; /** @return array of available GUI scales. */ @LmlAction("scales") public SkinScale[] getGuiScales() { return scaleService.getScales(); } /** @param actor requested scale change. Its ID represents a GUI scale. */ @LmlAction("changeScale") public void changeGuiScale(final Actor actor) { final SkinScale scale = scaleService.getPreference().extractFromActor(actor); scaleService.changeScale(scale); } }""")) project.files.add(SourceFile(projectName = Core.ID, packageName = "${project.basic.rootPackage}.service", fileName = "ScaleService.java", content = """package ${project.basic.rootPackage}.service; import com.github.czyzby.autumn.annotation.Component; import com.github.czyzby.autumn.annotation.Inject; import com.github.czyzby.autumn.mvc.component.ui.InterfaceService; import com.github.czyzby.autumn.mvc.component.ui.SkinService; import com.kotcrab.vis.ui.VisUI; import com.kotcrab.vis.ui.VisUI.SkinScale; import ${project.basic.rootPackage}.configuration.preferences.ScalePreference; /** Thanks to the ViewActionContainer annotation, this class will be automatically found and processed. * * This service handles GUI scale. */ @Component public class ScaleService { // @Inject-annotated fields will be automatically filled by the context initializer. @Inject private ScalePreference preference; @Inject private InterfaceService interfaceService; @Inject private SkinService skinService; /** @return current GUI scale. */ public SkinScale getScale() { return preference.get(); } /** @return all scales supported by the application. */ public SkinScale[] getScales() { return SkinScale.values(); } /** @return scale property, which is saved in application's preferences. */ public ScalePreference getPreference() { return preference; } /** @param scale the new application's scale. */ public void changeScale(final SkinScale scale) { if (preference.get() == scale) { return; // This is the current scale. } preference.set(scale); // Changing GUI skin, reloading all screens: interfaceService.reload(new Runnable() { @Override public void run() { // Removing previous skin resources: VisUI.dispose(); // Loading new skin: VisUI.load(scale); // Replacing the previously default skin: skinService.clear(); skinService.addSkin("default", VisUI.getSkin()); } }); } }""")) } override fun addViews(project: Project) { project.files.add(SourceFile(projectName = Assets.ID, sourceFolderPath = "ui", packageName = "templates", fileName = "loading.lml", content = """<!-- Going through LML tutorials is suggested before starting with Autumn MVC. If anything is unclear in the .lml files, you should go through LML resources first. --> <window title="@loadingTitle" titleAlign="center"> <!-- Thanks to "goto:menu" action, menu.lml will be shown after this bar is fully loaded. --> <progressBar id="loadingBar" animateDuration="0.4" onComplete="goto:menu"/> </window>""")) project.files.add(SourceFile(projectName = Assets.ID, sourceFolderPath = "ui", packageName = "templates", fileName = "menu.lml", content = """<table oneColumn="true" defaultPad="2" tableAlign="bottomRight" fillParent="true" defaultFillX="true"> <!-- "show:settings" will automatically show the settings.lml dialog when button is clicked. --> <textButton onChange="show:settings">@settings</textButton> <!-- "app:exit" will automatically try to exit the application when the button is clicked. --> <textButton onChange="app:exit">@exit</textButton> </table>""")) project.files.add(SourceFile(projectName = Assets.ID, sourceFolderPath = "ui", packageName = "templates", fileName = path("dialogs", "settings.lml"), content = """<dialog id="dialog" title="@settings" style="dialog"> <!-- Note that all values (like width and height) are in viewport units, not pixels. Its somewhat safe to use "magic" values. Values in {= } are equations; values proceeded with $ reference Java methods. --> <tabbedPane selected="0" width="{=200 * (${'$'}getScale - X)}" height="{=100 * (${'$'}getScale - X)}"> <!-- :setting macro is defined at global.lml. --> <:setting name="@music"> @musicVolume <!-- Music-related methods are added by MusicService. --> <slider value="${'$'}getMusicVolume" onChange="setMusicVolume" growX="true" /> <checkBox onChange="toggleMusic" checked="${'$'}musicOn">@toggleMusic</checkBox> </:setting> <:setting name="@sound"> @soundVolume <!-- Sound-related methods are added by MusicService. --> <slider value="${'$'}getSoundVolume" onChange="setSoundVolume" growX="true" /> <checkBox onChange="toggleSound" checked="${'$'}soundOn">@toggleSound</checkBox> </:setting> <:setting name="@locale"> <!-- {locales} and {currentLocale} are LML arguments automatically added by LocaleService. "locale:name" action changes current locale and reloads UI. For example, "locale:en" action would change current locale to English. --> <:each locale="{locales}"> <:if test="{locale} != {currentLocale}"> <textButton onChange="locale:{locale}">@{locale}</textButton> </:if> </:each> </:setting> <:setting name="@gui"> @scale <!-- Scale-related actions are registered by SettingsController and handled by our custom ScaleService. --> <:each scale="${'$'}scales"> <:if test="{scale} != ${'$'}getScale"> <textButton id="{scale}" onChange="changeScale">{scale}</textButton> </:if> </:each> </:setting> </tabbedPane> <!-- "close" action is defined in Global class. --> <textButton onResult="close">@exit</textButton> </dialog>""")) project.files.add(SourceFile(projectName = Assets.ID, sourceFolderPath = "ui", packageName = "templates", fileName = path("macros", "global.lml"), content = """<!-- This is a custom macro that displays a TabbedPane's tab. - name: becomes the title of the tab. Defaults to empty string. --> <:macro alias="setting" replace="content" name=""> <!-- "name" will be replaced with the value of the passed argument. --> <tab title="{name}" closeable="false" oneColumn="true" defaultPad="1" bg="dialogDim"> <!-- "content" will be replaced with the data between macro tags. --> {content} </tab> </:macro>""")) } }
unlicense
b96fa97507d66eb6c333941b35e22854
51.791183
225
0.672746
4.508223
false
false
false
false
alashow/music-android
modules/core-downloader/src/main/java/tm/alashow/datmusic/downloader/DownloaderMessages.kt
1
1050
/* * Copyright (C) 2021, Alashov Berkeli * All rights reserved. */ package tm.alashow.datmusic.downloader import com.tonyodev.fetch2.Status import tm.alashow.base.util.UiMessage val DownloadsFolderNotFound = UiMessage.Resource(R.string.downloader_enqueue_downloadsNotFound) val AudioDownloadErrorFileCreate = UiMessage.Resource(R.string.downloader_enqueue_audio_error_fileCreate) val AudioDownloadErrorInvalidUrl = UiMessage.Resource(R.string.downloader_enqueue_audio_error_invalidUrl) val AudioDownloadQueued = UiMessage.Resource(R.string.downloader_enqueue_audio_queued) val AudioDownloadResumingExisting = UiMessage.Resource(R.string.downloader_enqueue_audio_existing_resuming) val AudioDownloadAlreadyQueued = UiMessage.Resource(R.string.downloader_enqueue_audio_existing_alreadyQueued) val AudioDownloadAlreadyCompleted = UiMessage.Resource(R.string.downloader_enqueue_audio_existing_completed) fun audioDownloadExistingUnknownStatus(status: Status) = UiMessage.Resource(R.string.downloader_enqueue_audio_existing_unknown, listOf(status))
apache-2.0
9cdd4b33bc74e849cfb4da7c47d663f3
57.333333
143
0.846667
3.888889
false
false
false
false
BrianLusina/MovieReel
app/src/main/kotlin/com/moviereel/data/api/model/tv/TvLatestResponse.kt
1
2871
package com.moviereel.data.api.model.tv import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName import com.moviereel.data.api.model.Networks import com.moviereel.data.db.entities.ProductionCompany import com.moviereel.data.api.model.tv.Seasons import com.moviereel.data.db.entities.GenreEntity /** * @author lusinabrian on 10/04/17 * * This is the response we get back when we do a fetch for the latest tv show */ data class TvLatestResponse( @Expose @SerializedName("backdrop_path") var backdropPath: String, // @Expose // @SerializedName("created_by") // private List<> createdBy; @Expose @SerializedName("episode_run_time") var episodeRunTime: List<Int>, @Expose @SerializedName("first_air_date") var firstAirDate: String, @Expose @SerializedName("genres") var genres: List<GenreEntity>, @Expose @SerializedName("homepage") var homepage: String, @Expose @SerializedName("id") var id: Int = 0, @Expose @SerializedName("in_production") var isInProduction: Boolean = false, @Expose @SerializedName("languages") var languages: List<String>, @Expose @SerializedName("last_air_date") var lastAirDate: String, @Expose @SerializedName("name") var name: String, @Expose @SerializedName("networks") var networks: List<Networks>, @Expose @SerializedName("number_of_episodes") var numberOfEpisodes: Int = 0, @Expose @SerializedName("number_of_seasons") var numberOfSeasons: Int = 0, @Expose @SerializedName("origin_country") var originCountry: List<String>, @Expose @SerializedName("original_language") var originalLanguage: String, @Expose @SerializedName("original_name") var originalName: String, @Expose @SerializedName("overview") var overview: String, @Expose @SerializedName("popularity") var popularity: Int = 0, @Expose @SerializedName("poster_path") var posterPath: String, @Expose @SerializedName("production_companies") var productionCompanies: List<ProductionCompany>, @Expose @SerializedName("seasons") var seasons: List<Seasons>, @Expose @SerializedName("status") var status: String, @Expose @SerializedName("type") var type: String, @Expose @SerializedName("vote_average") var voteAverage: Int = 0, @Expose @SerializedName("vote_count") var voteCount: Int = 0 )
mit
4460326c04a1565b968b1881dacb5260
22.727273
79
0.596308
4.660714
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
example/src/test/java/org/wordpress/android/fluxc/store/dashboard/CardsStoreTest.kt
1
15176
package org.wordpress.android.fluxc.store.dashboard import com.nhaarman.mockitokotlin2.verify import com.nhaarman.mockitokotlin2.whenever import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.single import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mock import org.mockito.junit.MockitoJUnitRunner import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.dashboard.CardModel import org.wordpress.android.fluxc.model.dashboard.CardModel.PostsCardModel import org.wordpress.android.fluxc.model.dashboard.CardModel.PostsCardModel.PostCardModel import org.wordpress.android.fluxc.model.dashboard.CardModel.TodaysStatsCardModel import org.wordpress.android.fluxc.network.rest.wpcom.dashboard.CardsRestClient import org.wordpress.android.fluxc.network.rest.wpcom.dashboard.CardsRestClient.CardsResponse import org.wordpress.android.fluxc.network.rest.wpcom.dashboard.CardsRestClient.PostResponse import org.wordpress.android.fluxc.network.rest.wpcom.dashboard.CardsRestClient.PostsResponse import org.wordpress.android.fluxc.network.rest.wpcom.dashboard.CardsRestClient.TodaysStatsResponse import org.wordpress.android.fluxc.network.rest.wpcom.dashboard.CardsUtils import org.wordpress.android.fluxc.persistence.dashboard.CardsDao import org.wordpress.android.fluxc.persistence.dashboard.CardsDao.CardEntity import org.wordpress.android.fluxc.store.dashboard.CardsStore.CardsError import org.wordpress.android.fluxc.store.dashboard.CardsStore.CardsErrorType import org.wordpress.android.fluxc.store.dashboard.CardsStore.CardsPayload import org.wordpress.android.fluxc.store.dashboard.CardsStore.CardsResult import org.wordpress.android.fluxc.store.dashboard.CardsStore.PostCardError import org.wordpress.android.fluxc.store.dashboard.CardsStore.PostCardErrorType import org.wordpress.android.fluxc.store.dashboard.CardsStore.TodaysStatsCardError import org.wordpress.android.fluxc.store.dashboard.CardsStore.TodaysStatsCardErrorType import org.wordpress.android.fluxc.test import org.wordpress.android.fluxc.tools.initCoroutineEngine import kotlin.test.assertEquals import kotlin.test.assertNull /* SITE */ const val SITE_LOCAL_ID = 1 /* TODAY'S STATS */ const val TODAYS_STATS_VIEWS = 100 const val TODAYS_STATS_VISITORS = 30 const val TODAYS_STATS_LIKES = 50 const val TODAYS_STATS_COMMENTS = 10 /* POST */ const val POST_ID = 1 const val POST_TITLE = "title" const val POST_CONTENT = "content" const val POST_FEATURED_IMAGE = "featuredImage" const val POST_DATE = "2021-12-27 11:33:55" /* CARD TYPES */ private val CARD_TYPES = listOf(CardModel.Type.TODAYS_STATS, CardModel.Type.POSTS) /* RESPONSE */ private val TODAYS_STATS_RESPONSE = TodaysStatsResponse( views = TODAYS_STATS_VIEWS, visitors = TODAYS_STATS_VISITORS, likes = TODAYS_STATS_LIKES, comments = TODAYS_STATS_COMMENTS ) private val POST_RESPONSE = PostResponse( id = POST_ID, title = POST_TITLE, content = POST_CONTENT, featuredImage = POST_FEATURED_IMAGE, date = POST_DATE ) private val POSTS_RESPONSE = PostsResponse( hasPublished = false, draft = listOf(POST_RESPONSE), scheduled = listOf(POST_RESPONSE) ) private val CARDS_RESPONSE = CardsResponse( todaysStats = TODAYS_STATS_RESPONSE, posts = POSTS_RESPONSE ) /* MODEL */ private val TODAYS_STATS_MODEL = TodaysStatsCardModel( views = TODAYS_STATS_VIEWS, visitors = TODAYS_STATS_VISITORS, likes = TODAYS_STATS_LIKES, comments = TODAYS_STATS_COMMENTS ) private val TODAYS_STATS_WITH_ERROR_MODEL = TodaysStatsCardModel( error = TodaysStatsCardError(TodaysStatsCardErrorType.JETPACK_DISCONNECTED) ) private val POST_MODEL = PostCardModel( id = POST_ID, title = POST_TITLE, content = POST_CONTENT, featuredImage = POST_FEATURED_IMAGE, date = CardsUtils.fromDate(POST_DATE) ) private val POSTS_MODEL = PostsCardModel( hasPublished = false, draft = listOf(POST_MODEL), scheduled = listOf(POST_MODEL) ) private val POSTS_WITH_ERROR_MODEL = PostsCardModel( error = PostCardError(PostCardErrorType.UNAUTHORIZED) ) private val CARDS_MODEL = listOf( TODAYS_STATS_MODEL, POSTS_MODEL ) /* ENTITY */ private val TODAYS_STATS_ENTITY = CardEntity( siteLocalId = SITE_LOCAL_ID, type = CardModel.Type.TODAYS_STATS.name, date = CardsUtils.getInsertDate(), json = CardsUtils.GSON.toJson(TODAYS_STATS_MODEL) ) private val TODAY_STATS_WITH_ERROR_ENTITY = CardEntity( siteLocalId = SITE_LOCAL_ID, type = CardModel.Type.TODAYS_STATS.name, date = CardsUtils.getInsertDate(), json = CardsUtils.GSON.toJson(TODAYS_STATS_WITH_ERROR_MODEL) ) private val POSTS_ENTITY = CardEntity( siteLocalId = SITE_LOCAL_ID, type = CardModel.Type.POSTS.name, date = CardsUtils.getInsertDate(), json = CardsUtils.GSON.toJson(POSTS_MODEL) ) private val POSTS_WITH_ERROR_ENTITY = CardEntity( siteLocalId = SITE_LOCAL_ID, type = CardModel.Type.POSTS.name, date = CardsUtils.getInsertDate(), json = CardsUtils.GSON.toJson(POSTS_WITH_ERROR_MODEL) ) private val CARDS_ENTITY = listOf( TODAYS_STATS_ENTITY, POSTS_ENTITY ) @RunWith(MockitoJUnitRunner::class) class CardsStoreTest { @Mock private lateinit var siteModel: SiteModel @Mock private lateinit var restClient: CardsRestClient @Mock private lateinit var dao: CardsDao @Mock private lateinit var cardsRespone: CardsResponse private lateinit var cardsStore: CardsStore @Before fun setUp() { cardsStore = CardsStore( restClient, dao, initCoroutineEngine() ) setUpMocks() } private fun setUpMocks() { whenever(siteModel.id).thenReturn(SITE_LOCAL_ID) } @Test fun `given all card types, when fetch cards triggered, then all cards model is inserted into db`() = test { val payload = CardsPayload(CARDS_RESPONSE) whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(payload) cardsStore.fetchCards(siteModel, CARD_TYPES) verify(dao).insertWithDate(siteModel.id, CARDS_MODEL) } @Test fun `given todays stats type, when fetch cards triggered, then today's stats card model inserted into db`() = test { val payload = CardsPayload(CardsResponse(todaysStats = TODAYS_STATS_RESPONSE)) whenever(restClient.fetchCards(siteModel, listOf(CardModel.Type.TODAYS_STATS))).thenReturn(payload) cardsStore.fetchCards(siteModel, listOf(CardModel.Type.TODAYS_STATS)) verify(dao).insertWithDate(siteModel.id, listOf(TODAYS_STATS_MODEL)) } @Test fun `given posts type, when fetch cards triggered, then post card model inserted into db`() = test { val payload = CardsPayload(CardsResponse(posts = POSTS_RESPONSE)) whenever(restClient.fetchCards(siteModel, listOf(CardModel.Type.POSTS))).thenReturn(payload) cardsStore.fetchCards(siteModel, listOf(CardModel.Type.POSTS)) verify(dao).insertWithDate(siteModel.id, listOf(POSTS_MODEL)) } @Test fun `given cards response, when fetch cards gets triggered, then empty cards model is returned`() = test { val payload = CardsPayload(CARDS_RESPONSE) whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(payload) val result = cardsStore.fetchCards(siteModel, CARD_TYPES) assertThat(result.model).isNull() assertThat(result.error).isNull() } @Test fun `given card response with exception, when fetch cards gets triggered, then cards error is returned`() = test { val payload = CardsPayload(CARDS_RESPONSE) whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(payload) whenever(dao.insertWithDate(siteModel.id, CARDS_MODEL)).thenThrow(IllegalStateException("Error")) val result = cardsStore.fetchCards(siteModel, CARD_TYPES) assertThat(result.model).isNull() assertEquals(CardsErrorType.GENERIC_ERROR, result.error.type) assertNull(result.error.message) } @Test fun `given cards error, when fetch cards gets triggered, then cards error is returned`() = test { val errorType = CardsErrorType.API_ERROR val payload = CardsPayload<CardsResponse>(CardsError(errorType)) whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(payload) val result = cardsStore.fetchCards(siteModel, CARD_TYPES) assertThat(result.model).isNull() assertEquals(errorType, result.error.type) assertNull(result.error.message) } @Test fun `given authorization required, when fetch cards gets triggered, then db is cleared of cards model`() = test { val errorType = CardsErrorType.AUTHORIZATION_REQUIRED val payload = CardsPayload<CardsResponse>(CardsError(errorType)) whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(payload) cardsStore.fetchCards(siteModel, CARD_TYPES) verify(dao).clear() } @Test fun `given authorization required, when fetch cards gets triggered, then empty cards model is returned`() = test { val errorType = CardsErrorType.AUTHORIZATION_REQUIRED val payload = CardsPayload<CardsResponse>(CardsError(errorType)) whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(payload) val result = cardsStore.fetchCards(siteModel, CARD_TYPES) assertThat(result.model).isNull() assertThat(result.error).isNull() } @Test fun `given empty cards payload, when fetch cards gets triggered, then cards error is returned`() = test { val payload = CardsPayload<CardsResponse>() whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(payload) val result = cardsStore.fetchCards(siteModel, CARD_TYPES) assertThat(result.model).isNull() assertEquals(CardsErrorType.INVALID_RESPONSE, result.error.type) assertNull(result.error.message) } @Test fun `when get cards gets triggered, then a flow of cards model is returned`() = test { whenever(dao.get(SITE_LOCAL_ID, CARD_TYPES)).thenReturn(flowOf(CARDS_ENTITY)) val result = cardsStore.getCards(siteModel, CARD_TYPES).single() assertThat(result).isEqualTo(CardsResult(CARDS_MODEL)) } @Test fun `when get cards gets triggered for today's stats only, then a flow of today's stats card model is returned`() = test { whenever(dao.get(SITE_LOCAL_ID, listOf(CardModel.Type.TODAYS_STATS))) .thenReturn(flowOf(listOf(TODAYS_STATS_ENTITY))) val result = cardsStore.getCards(siteModel, listOf(CardModel.Type.TODAYS_STATS)).single() assertThat(result).isEqualTo(CardsResult(listOf(TODAYS_STATS_MODEL))) } @Test fun `when get cards gets triggered for posts only, then a flow of post card model is returned`() = test { whenever(dao.get(SITE_LOCAL_ID, listOf(CardModel.Type.POSTS))).thenReturn(flowOf(listOf(POSTS_ENTITY))) val result = cardsStore.getCards(siteModel, listOf(CardModel.Type.POSTS)).single() assertThat(result).isEqualTo(CardsResult(listOf(POSTS_MODEL))) } /* TODAYS STATS CARD WITH ERROR */ @Test fun `given todays stats card with error, when fetch cards triggered, then card with error inserted into db`() = test { whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(CardsPayload(cardsRespone)) whenever(cardsRespone.toCards()).thenReturn(listOf(TODAYS_STATS_WITH_ERROR_MODEL)) cardsStore.fetchCards(siteModel, CARD_TYPES) verify(dao).insertWithDate(siteModel.id, listOf(TODAYS_STATS_WITH_ERROR_MODEL)) } @Test fun `given today's stats jetpack disconn error, when get cards triggered, then error exists in the card`() = test { whenever(dao.get(SITE_LOCAL_ID, CARD_TYPES)) .thenReturn( flowOf(listOf(getTodaysStatsErrorCardEntity(TodaysStatsCardErrorType.JETPACK_DISCONNECTED))) ) val result = cardsStore.getCards(siteModel, CARD_TYPES).single() assertThat(result.findTodaysStatsCardError()?.type).isEqualTo(TodaysStatsCardErrorType.JETPACK_DISCONNECTED) } @Test fun `given today's stats jetpack disabled error, when get cards triggered, then error exists in the card`() = test { whenever(dao.get(SITE_LOCAL_ID, CARD_TYPES)) .thenReturn(flowOf(listOf(getTodaysStatsErrorCardEntity(TodaysStatsCardErrorType.JETPACK_DISABLED)))) val result = cardsStore.getCards(siteModel, CARD_TYPES).single() assertThat(result.findTodaysStatsCardError()?.type).isEqualTo(TodaysStatsCardErrorType.JETPACK_DISABLED) } @Test fun `given today's stats jetpack unauth error, when get cards triggered, then error exists in the card`() = test { whenever(dao.get(SITE_LOCAL_ID, CARD_TYPES)) .thenReturn(flowOf(listOf(getTodaysStatsErrorCardEntity(TodaysStatsCardErrorType.UNAUTHORIZED)))) val result = cardsStore.getCards(siteModel, CARD_TYPES).single() assertThat(result.findTodaysStatsCardError()?.type).isEqualTo(TodaysStatsCardErrorType.UNAUTHORIZED) } /* POSTS CARD WITH ERROR */ @Test fun `given posts card with error, when fetch cards triggered, then card with error inserted into db`() = test { whenever(restClient.fetchCards(siteModel, CARD_TYPES)).thenReturn(CardsPayload(cardsRespone)) whenever(cardsRespone.toCards()).thenReturn(listOf(POSTS_WITH_ERROR_MODEL)) cardsStore.fetchCards(siteModel, CARD_TYPES) verify(dao).insertWithDate(siteModel.id, listOf(POSTS_WITH_ERROR_MODEL)) } @Test fun `given posts card unauth error, when get cards triggered, then error exists in the card`() = test { whenever(dao.get(SITE_LOCAL_ID, CARD_TYPES)).thenReturn(flowOf(listOf(POSTS_WITH_ERROR_ENTITY))) val result = cardsStore.getCards(siteModel, CARD_TYPES).single() assertThat(result.findPostsCardError()?.type).isEqualTo(PostCardErrorType.UNAUTHORIZED) } private fun CardsResult<List<CardModel>>.findTodaysStatsCardError(): TodaysStatsCardError? = model?.filterIsInstance(TodaysStatsCardModel::class.java)?.firstOrNull()?.error private fun CardsResult<List<CardModel>>.findPostsCardError(): PostCardError? = model?.filterIsInstance(PostsCardModel::class.java)?.firstOrNull()?.error private fun getTodaysStatsErrorCardEntity(type: TodaysStatsCardErrorType) = TODAY_STATS_WITH_ERROR_ENTITY.copy( json = CardsUtils.GSON.toJson(TodaysStatsCardModel(error = TodaysStatsCardError(type))) ) }
gpl-2.0
a411d7b1a0a1a482cbe840087605223a
38.012853
120
0.714879
4.143052
false
true
false
false
songzhw/Hello-kotlin
Advanced_hm/src/main/kotlin/ca/six/kjdemo/architecture/ifelse/HashMap大法.kt
1
872
package ca.six.kjdemo.architecture.ifelse enum class Condition11 { ONE, TWO, THREE, FOUR } fun original11(condition: Condition11) { if (condition === Condition11.ONE) { println("001") } else if (condition === Condition11.TWO) { println("002") } else if (condition === Condition11.THREE) { println("003") } else { println("004") } } fun refactor11(condition: Condition11) { val actions = HashMap<Condition11, () -> Unit>() // actions.put(Condition11.ONE, ()->{ println("001"); }) //ERROR actions.put(Condition11.ONE, { println("001"); }) actions.put(Condition11.TWO, { println("002"); }) actions.put(Condition11.THREE, { println("003"); }) actions[condition]?.invoke() ?: println("new 004") } fun main() { original11(Condition11.FOUR) refactor11(Condition11.FOUR) }
apache-2.0
875cf17f5fa593437c02af5196383fb9
22.567568
68
0.611239
3.559184
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/cause/entity/damage/source/LanternBlockDamageSourceBuilder.kt
1
2150
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.cause.entity.damage.source import org.lanternpowered.api.world.Location import org.spongepowered.api.block.BlockSnapshot import org.spongepowered.api.event.cause.entity.damage.source.BlockDamageSource import org.spongepowered.api.event.cause.entity.damage.source.common.AbstractDamageSourceBuilder class LanternBlockDamageSourceBuilder : AbstractDamageSourceBuilder<BlockDamageSource, BlockDamageSource.Builder>(), BlockDamageSource.Builder { private var location: Location? = null private var blockSnapshot: BlockSnapshot? = null override fun block(location: Location): BlockDamageSource.Builder = apply { this.location = location } override fun block(blockSnapshot: BlockSnapshot): BlockDamageSource.Builder = apply { this.blockSnapshot = blockSnapshot } override fun reset(): BlockDamageSource.Builder = apply { super.reset() this.location = null this.blockSnapshot = null } override fun from(value: BlockDamageSource): BlockDamageSource.Builder = apply { super.from(value) this.location = value.location this.blockSnapshot = value.blockSnapshot } override fun build(): BlockDamageSource { var location: Location? = this.location var blockSnapshot: BlockSnapshot? = this.blockSnapshot if (location == null && blockSnapshot != null) { location = blockSnapshot.location.orElse(null) } else if (location != null && blockSnapshot == null) { blockSnapshot = location.createSnapshot() } val location0 = checkNotNull(location) { "The location must be set" } val blockSnapshot0 = checkNotNull(blockSnapshot) { "The block snapshot must be set" } return LanternBlockDamageSource(this, location0, blockSnapshot0) } }
mit
de7881ccf77b4da8fe32b7c36119b856
42
144
0.723256
4.469854
false
false
false
false
trydent-io/youth
youth-webapp/src/main/kotlin/io/youth/Main.kt
1
4755
package io.youth import com.typesafe.config.Config import io.youth.service.person.AddPerson import io.youth.service.person.EditPerson import io.youth.service.person.PersonModule import io.youth.service.person.RemovePerson import io.youth.service.person.personCommand import io.youth.service.person.personQuery import io.youth.service.person.profilePersons import org.jooby.Err import org.jooby.MediaType.json import org.jooby.Request import org.jooby.Results import org.jooby.Route import org.jooby.Status import org.jooby.Status.NOT_FOUND import org.jooby.Status.UNPROCESSABLE_ENTITY import org.jooby.flyway.Flywaydb import org.jooby.handlers.CorsHandler import org.jooby.json.Gzon import org.jooby.pac4j.Auth import org.jooby.pac4j.AuthStore import org.jooby.require import org.jooby.run import org.jooby.rx.Rx import org.jooby.rx.RxJdbc import org.pac4j.core.profile.CommonProfile import org.pac4j.http.client.direct.ParameterClient import org.pac4j.jwt.config.signature.SecretSignatureConfiguration import org.pac4j.jwt.config.signature.SignatureConfiguration import org.pac4j.jwt.credentials.authenticator.JwtAuthenticator import org.pac4j.jwt.profile.JwtGenerator import org.pac4j.oauth.client.FacebookClient import org.pac4j.oidc.client.OidcClient import org.pac4j.oidc.config.OidcConfiguration import org.pac4j.oidc.profile.OidcProfile import java.util.Objects.isNull private fun Request.uuid() = this.param("uuid").value() private fun Request.addPerson() = this.body().to(AddPerson::class.java) private fun Request.editPerson() = this.body().to(EditPerson::class.java) val getUserProfile: (req: Request) -> CommonProfile = { val id = it.ifGet<String>(Auth.ID).orElseGet { it.session().get(Auth.ID).value(null) } if (isNull(id)) throw Err(Status.UNAUTHORIZED) val store = it.require(AuthStore::class) store.get(id).get().apply { removeAttribute("sub") removeAttribute("iat") } } data class OpenIDProfile(val client: String, val profile: CommonProfile) data class Token(val token: String) val handler = Route.OneArgHandler { req -> val profile = getUserProfile(req) OpenIDProfile( client = profile::class.java.simpleName.replace("Profile", ""), profile = profile ) Results.redirect("/?logged") } class GoogleClient(conf: OidcConfiguration) : OidcClient<OidcProfile>(conf) fun main(args: Array<String>) { run(*args) { use("*", CorsHandler()) use(Gzon()) use(Flywaydb()) use(Rx()) use(RxJdbc()) use(PersonModule()) get("*") { req, _ -> req.session().get(Auth.ID).toOptional().ifPresent { req.set("logged", it) } } get("/auth/token") { req -> val profile = getUserProfile(req) val config = req.require(Config::class.java) val sign = SecretSignatureConfiguration(config.getString("jwt.salt")) val jwtGenerator = JwtGenerator<CommonProfile>(sign) val token = jwtGenerator.generate(profile) Token(token) } assets("/", "index.html") assets("/static/**") use(Auth() .client("/auth/facebook/**") { FacebookClient(it.getString("fb.key"), it.getString("fb.secret")).apply { scope = "public_profile" } } .client("/auth/google/**") { OidcConfiguration().apply { clientId = it.getString("oidc.clientID") secret = it.getString("oidc.secret") discoveryURI = it.getString("oidc.discoveryURI") addCustomParam("prompt", "consent") }.let { GoogleClient(it) } } .client("/auth/jwt/**") { conf -> SecretSignatureConfiguration(conf.getString("jwt.salt")) .let { arrayOf<SignatureConfiguration>(it).toMutableList() } .let { JwtAuthenticator(it) } .let { ParameterClient("token", it).apply { isSupportGetRequest = true isSupportPostRequest = false } } } ) get("/auth/profile", handler) get("/auth/google", handler) get("/auth/facebook", handler) get("/auth/jwt", handler) get("/auth/token", handler) use("/api/person") .get { -> "Person API by using HATEOAS is on the way" } .get("/fetch/all") { -> profilePersons().toList() } .get("/fetch/count") { -> profilePersons().count() } .get("/:uuid") { req -> personQuery().one(req.uuid()) ?: Results.with(NOT_FOUND) } .post { req -> personCommand().apply(req.addPerson()) ?: Results.with(UNPROCESSABLE_ENTITY) } .put { req -> personCommand().apply(req.editPerson()) ?: Results.with(UNPROCESSABLE_ENTITY) } .delete("/:uuid") { req -> personCommand().apply(RemovePerson(req.uuid())) ?: Results.with(UNPROCESSABLE_ENTITY) } .consumes(json) .produces(json) } }
gpl-3.0
f99354674a248dd906f5afb0e2eebc58
29.677419
120
0.679706
3.643678
false
true
false
false
danrien/projectBlueWater
projectBlueWater/src/test/java/com/lasthopesoftware/bluewater/client/connection/builder/GivenAnAccessCodeThatIsAValidServer/WithAPort/WhenScanningForUrls.kt
2
2101
package com.lasthopesoftware.bluewater.client.connection.builder.GivenAnAccessCodeThatIsAValidServer.WithAPort import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.connection.builder.PassThroughBase64Encoder import com.lasthopesoftware.bluewater.client.connection.builder.UrlScanner import com.lasthopesoftware.bluewater.client.connection.settings.ConnectionSettings import com.lasthopesoftware.bluewater.client.connection.settings.LookupConnectionSettings import com.lasthopesoftware.bluewater.client.connection.testing.TestConnections import com.lasthopesoftware.bluewater.client.connection.url.IUrlProvider import com.lasthopesoftware.bluewater.shared.promises.extensions.toFuture import com.lasthopesoftware.bluewater.shared.promises.extensions.toPromise import io.mockk.every import io.mockk.mockk import org.assertj.core.api.Assertions.assertThat import org.junit.BeforeClass import org.junit.Test class WhenScanningForUrls { companion object { private var urlProvider: IUrlProvider? = null @BeforeClass @JvmStatic fun before() { val connectionTester = mockk<TestConnections>() every { connectionTester.promiseIsConnectionPossible(any()) } returns false.toPromise() every { connectionTester.promiseIsConnectionPossible(match { a -> a.urlProvider.baseUrl.toString() == "http://gooPc:3504/MCWS/v1/" }) } returns true.toPromise() val connectionSettingsLookup = mockk<LookupConnectionSettings>() every { connectionSettingsLookup.lookupConnectionSettings(LibraryId(13)) } returns ConnectionSettings(accessCode = "http://gooPc:3504").toPromise() val urlScanner = UrlScanner( PassThroughBase64Encoder, connectionTester, mockk(), connectionSettingsLookup, mockk()) urlProvider = urlScanner.promiseBuiltUrlProvider(LibraryId(13)).toFuture().get() } } @Test fun thenTheUrlProviderIsReturned() { assertThat(urlProvider).isNotNull } @Test fun thenTheBaseUrlIsCorrect() { assertThat(urlProvider?.baseUrl?.toString()).isEqualTo("http://gooPc:3504/MCWS/v1/") } }
lgpl-3.0
7e891f6cdd8f7d7d146cbe68e7b956f0
38.641509
163
0.813422
4.358921
false
true
false
false
EMResearch/EMB
jdk_8_maven/cs/graphql/graphql-scs/src/main/kotlin/org/graphqlscs/type/Title.kt
1
1049
package org.graphqlscs.type import org.springframework.stereotype.Component import java.util.* @Component class Title { fun subject(sex: String, title: String): String { //CHECK PERSONAL TITLE CONSISTENT WITH SEX var sex = sex var title = title sex = sex.lowercase(Locale.getDefault()) title = title.lowercase(Locale.getDefault()) var result = -1 if ("male" == sex) { if ("mr" == title || "dr" == title || "sir" == title || "rev" == title || "rthon" == title || "prof" == title) { result = 1 } } else if ("female" == sex) { if ("mrs" == title || "miss" == title || "ms" == title || "dr" == title || "lady" == title || "rev" == title || "rthon" == title || "prof" == title) { result = 0 } } else if ("none" == sex) { if ("dr" == title || "rev" == title || "rthon" == title || "prof" == title) { result = 2 } } return "" + result } }
apache-2.0
8863bf5ecd55f01936b9582701744cd9
34
162
0.471878
3.787004
false
false
false
false
Zephyrrus/ubb
YEAR 3/SEM 1/MOBILE/native/PhotoApp/app/src/main/java/com/example/zephy/photoapp/activities/LessonActivity.kt
1
6202
package com.example.zephy.photoapp.activities import android.support.design.widget.TabLayout import android.support.v7.app.AppCompatActivity import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentPagerAdapter import android.os.Bundle import android.support.v7.widget.Toolbar import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import com.example.zephy.photoapp.R import com.example.zephy.photoapp.fragments.PageLessonFragment import com.example.zephy.photoapp.fragments.SubmissionsLessonFragment import kotlinx.android.synthetic.main.activity_lesson.* import kotlinx.android.synthetic.main.fragment_lesson.view.* class LessonActivity : AppCompatActivity() { private var lessonId = 0 /** * The [android.support.v4.view.PagerAdapter] that will provide * fragments for each of the sections. We use a * {@link FragmentPagerAdapter} derivative, which will keep every * loaded fragment in memory. If this becomes too memory intensive, it * may be best to switch to a * [android.support.v4.app.FragmentStatePagerAdapter]. */ private var mSectionsPagerAdapter: SectionsPagerAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_lesson) val extras = intent.extras if (extras != null) { lessonId = extras.getInt("lessonId") } else if (savedInstanceState != null){ lessonId = savedInstanceState.getInt("lessonId") } /*setSupportActionBar(toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true)*/ // toolbar val toolbar = findViewById<View>(R.id.toolbar) as Toolbar setSupportActionBar(toolbar) // add back arrow to toolbar if (supportActionBar != null) { supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setDisplayShowHomeEnabled(true) } // Create the adapter that will return a fragment for each of the three // primary sections of the activity. mSectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager, lessonId) // Set up the ViewPager with the sections adapter. container.adapter = mSectionsPagerAdapter container.addOnPageChangeListener(TabLayout.TabLayoutOnPageChangeListener(tabs)) tabs.addOnTabSelectedListener(TabLayout.ViewPagerOnTabSelectedListener(container)) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_lesson, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. val id = item.itemId if (id == R.id.action_settings) { return true } return super.onOptionsItemSelected(item) } public override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) // Save UI state changes to the savedInstanceState. // This bundle will be passed to onCreate if the process is // killed and restarted. savedInstanceState.putInt("lessonId", lessonId) // etc. } public override fun onRestoreInstanceState(savedInstanceState: Bundle) { super.onRestoreInstanceState(savedInstanceState) // Restore UI state from the savedInstanceState. // This bundle has also been passed to onCreate. lessonId = savedInstanceState.getInt("lessonId") } fun setActionBarTitle(title: String) { supportActionBar!!.title = title } /** * A [FragmentPagerAdapter] that returns a fragment corresponding to * one of the sections/tabs/pages. */ inner class SectionsPagerAdapter(fm: FragmentManager, lId: Int) : FragmentPagerAdapter(fm) { private val lessonId = lId override fun getItem(position: Int): Fragment { // getItem is called to instantiate the fragment for the given page. // Return a PlaceholderFragment (defined as a static inner class below). when (position) { 0 -> return PageLessonFragment.newInstance(lessonId) 1 -> return SubmissionsLessonFragment.newInstance(lessonId) } return PlaceholderFragment.newInstance( position + 1 ) } override fun getCount(): Int { // Show 3 total pages. return 3 } } /** * A placeholder fragment containing a simple view. */ class PlaceholderFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val rootView = inflater.inflate(R.layout.fragment_lesson, container, false) rootView.section_label.text = getString( R.string.section_format, arguments?.getInt( ARG_SECTION_NUMBER )) return rootView } companion object { /** * The fragment argument representing the section number for this * fragment. */ private val ARG_SECTION_NUMBER = "section_number" /** * Returns a new instance of this fragment for the given section * number. */ fun newInstance(sectionNumber: Int): PlaceholderFragment { val fragment = PlaceholderFragment() val args = Bundle() args.putInt(ARG_SECTION_NUMBER, sectionNumber) fragment.arguments = args return fragment } } } }
mit
fa6eefbb0bf48d56f8f26d3cd8183ec4
34.849711
96
0.656079
5.278298
false
false
false
false
tasks/tasks
app/src/main/java/com/todoroo/astrid/service/TaskCompleter.kt
1
3098
package com.todoroo.astrid.service import android.app.NotificationManager import android.app.NotificationManager.INTERRUPTION_FILTER_ALL import android.content.Context import android.media.RingtoneManager import com.todoroo.andlib.utility.DateUtilities import com.todoroo.astrid.dao.TaskDao import com.todoroo.astrid.data.Task import dagger.hilt.android.qualifiers.ApplicationContext import org.tasks.LocalBroadcastManager import org.tasks.data.GoogleTaskDao import org.tasks.jobs.WorkManager import org.tasks.preferences.Preferences import timber.log.Timber import javax.inject.Inject class TaskCompleter @Inject internal constructor( @ApplicationContext private val context: Context, private val taskDao: TaskDao, private val googleTaskDao: GoogleTaskDao, private val preferences: Preferences, private val notificationManager: NotificationManager, private val localBroadcastManager: LocalBroadcastManager, private val workManager: WorkManager, ) { suspend fun setComplete(taskId: Long) = taskDao .fetch(taskId) ?.let { setComplete(it, true) } ?: Timber.e("Could not find task $taskId") suspend fun setComplete(item: Task, completed: Boolean, includeChildren: Boolean = true) { val completionDate = if (completed) DateUtilities.now() else 0L ArrayList<Task?>() .apply { if (includeChildren) { addAll(googleTaskDao.getChildTasks(item.id)) addAll(taskDao.getChildren(item.id).let { taskDao.fetch(it) }) } if (!completed) { add(googleTaskDao.getParentTask(item.id)) addAll(taskDao.getParents(item.id).let { taskDao.fetch(it) }) } add(item) } .filterNotNull() .filter { it.isCompleted != completionDate > 0 } .let { setComplete(it, completionDate) if (completed && !item.isRecurring) { localBroadcastManager.broadcastTaskCompleted(ArrayList(it.map(Task::id))) } } } suspend fun setComplete(tasks: List<Task>, completionDate: Long) { if (tasks.isEmpty()) { return } val completed = completionDate > 0 taskDao.setCompletionDate(tasks.mapNotNull { it.remoteId }, completionDate) tasks.forEachIndexed { i, original -> if (i < tasks.size - 1) { original.suppressRefresh() } taskDao.saved(original) } tasks.forEach { if (completed && it.isRecurring) { workManager.scheduleRepeat(it) } } if (completed && notificationManager.currentInterruptionFilter == INTERRUPTION_FILTER_ALL) { preferences .completionSound ?.takeUnless { preferences.isCurrentlyQuietHours } ?.let { RingtoneManager.getRingtone(context, it).play() } } } }
gpl-3.0
767b1dc7485a395113697a00ff65ef55
37.259259
100
0.619432
4.940989
false
false
false
false
aglne/mycollab
mycollab-services-community/src/test/java/com/mycollab/module/page/service/PageServiceTest.kt
3
4820
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.module.page.service import com.mycollab.common.i18n.WikiI18nEnum import com.mycollab.module.page.domain.Page import com.mycollab.test.spring.IntegrationServiceTest import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.tuple import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.test.context.junit.jupiter.SpringExtension import javax.jcr.RepositoryException @ExtendWith(SpringExtension::class) class PageServiceTest : IntegrationServiceTest() { @Autowired private lateinit var pageService: PageService @BeforeEach fun setup() { val page = Page() page.createdUser = "[email protected]" page.category = "abc" page.path = "1/page/document_1" page.status = WikiI18nEnum.status_public.name page.subject = "Hello world" page.content = "My name is <b>Hai Nguyen</b>" pageService.savePage(page, "[email protected]") } @AfterEach fun tearDown() { pageService.removeResource("") } @Test fun testGetWikiPages() { val pages = pageService.getPages("1/page", "[email protected]") assertThat(pages.size).isEqualTo(1) assertThat(pages[0].category).isEqualTo("abc") } private fun savePage2() { val page = Page() page.createdUser = "[email protected]" page.category = "abc" page.path = "1/page/document_2" page.status = WikiI18nEnum.status_public.name page.subject = "Hello world 2" page.content = "My name is <b>Bao Han</b>" page.status = WikiI18nEnum.status_private.name pageService.savePage(page, "[email protected]") val expectedPage = pageService.getPage("1/page/document_2", "[email protected]") assertThat(expectedPage!!.subject).isEqualTo("Hello world 2") } @Test fun testGetResources() { savePage2() val pages = pageService.getPages("1/page", "[email protected]") assertThat(pages.size).isEqualTo(2) assertThat(pages).extracting("subject", "status").contains( tuple("Hello world", "status_public"), tuple("Hello world 2", "status_private")) } @Test @Throws(RepositoryException::class) fun testUpdatePage() { val page = Page() page.createdUser = "[email protected]" page.category = "abc" page.path = "1/page/document_1" page.status = WikiI18nEnum.status_public.name page.subject = "Hello world 2" page.content = "My name is <b>Bao Han</b>" pageService.savePage(page, "[email protected]") val pages = pageService.getPages("1/page", "[email protected]") assertThat(pages.size).isEqualTo(1) assertThat(pages[0].subject).isEqualTo("Hello world 2") } @Test fun testGetVersions() { var page = Page() page.createdUser = "[email protected]" page.category = "abc" page.path = "1/page/document_1" page.status = WikiI18nEnum.status_public.name page.subject = "Hello world 2" page.content = "My name is <b>Bao Han</b>" pageService.savePage(page, "[email protected]") page.subject = "Hello world 3" pageService.savePage(page, "[email protected]") val versions = pageService.getPageVersions("1/page/document_1") assertThat(versions.size).isEqualTo(2) page = pageService.getPageByVersion("1/page/document_1", "1.0") assertThat(page.subject).isEqualTo("Hello world 2") val restorePage = pageService.restorePage("1/page/document_1", "1.0") assertThat(restorePage.subject).isEqualTo("Hello world 2") val page2 = pageService.getPage("1/page/document_1", "[email protected]") assertThat(page2!!.subject).isEqualTo("Hello world 2") } }
agpl-3.0
7d710e199553013289e06541d6cafb0f
36.356589
93
0.674829
3.82157
false
true
false
false
Dominick1993/GD-lunch-Brno
src/main/kotlin/gdlunch/parser/ZlataLodParser.kt
1
1171
package gdlunch.parser import com.labuda.gdlunch.parser.AbstractRestaurantWebParser import com.labuda.gdlunch.parser.DailyParser import com.labuda.gdlunch.repository.entity.DailyMenu import com.labuda.gdlunch.repository.entity.MenuItem import com.labuda.gdlunch.repository.entity.Restaurant import mu.KotlinLogging import org.jsoup.Jsoup import java.time.LocalDate /** * Parses daily menu from Zlata Lod restaurant */ class ZlataLodParser(restaurant: Restaurant) : AbstractRestaurantWebParser(restaurant), DailyParser { val logger = KotlinLogging.logger { } override fun parse(): DailyMenu { val result = DailyMenu() result.restaurant = restaurant result.date = LocalDate.now() val document = Jsoup.connect(restaurant.parserUrl).get() val items = document.selectFirst(".menu-one-day").select("td") val names = items.filterIndexed { index, _ -> index % 2 == 0 }.map { it.text() } val prices = items.filterIndexed { index, _ -> index % 2 == 1 }.map { parsePrice(it.text()) } names.forEachIndexed { index, name -> result.menu.add(MenuItem(name, prices[index])) } return result } }
gpl-3.0
73d373aa73ca1affea795857521bb8eb
34.484848
101
0.710504
4.010274
false
false
false
false
candalo/rss-reader
app/src/main/java/com/github/rssreader/features/feed/domain/models/FeedChannel.kt
1
457
package com.github.rssreader.features.feed.domain.models data class FeedChannel( val title: String, val link: String, val description: String, val language: String = "", val managingEditorEmail: String = "", val pubDate: String = "", val lastBuildDate: String = "", val category: String = "", val image: FeedImage = FeedImage(), val items: ArrayList<FeedItem> = ArrayList() )
mit
f34315cb4bf32af2dc4eda9fb7990e78
29.533333
56
0.603939
4.524752
false
false
false
false
openHPI/android-app
app/src/main/java/de/xikolo/models/Document.kt
1
1395
package de.xikolo.models import com.squareup.moshi.Json import de.xikolo.models.base.RealmAdapter import io.realm.RealmList import io.realm.RealmObject import io.realm.annotations.PrimaryKey import moe.banana.jsonapi2.HasMany import moe.banana.jsonapi2.JsonApi import moe.banana.jsonapi2.Resource open class Document : RealmObject() { @PrimaryKey var id: String? = null var title: String? = null var description: String? = null var tags: RealmList<String> = RealmList() var isPublic: Boolean = false var courseIds: RealmList<String> = RealmList() @JsonApi(type = "documents") class JsonModel : Resource(), RealmAdapter<Document> { var title: String? = null var description: String? = null var tags: List<String>? = null @field:Json(name = "public") var isPublic: Boolean = false var courses: HasMany<Course.JsonModel>? = null var courseIds: List<String>? = null get() = courses?.map { it.id } override fun convertToRealmObject(): Document { val model = Document() model.id = id model.title = title model.description = description tags?.let { model.tags.addAll(it) } courseIds?.let { model.courseIds.addAll(it) } model.isPublic = isPublic return model } } }
bsd-3-clause
61d7e04f6806ca36169617d2e32847f7
23.473684
58
0.631541
4.214502
false
false
false
false
soywiz/korge
korge/src/commonMain/kotlin/com/soywiz/korge/ui/UISpacing.kt
1
425
package com.soywiz.korge.ui import com.soywiz.korge.view.* inline fun Container.uiSpacing( width: Double = UI_DEFAULT_WIDTH, height: Double = UI_DEFAULT_HEIGHT, block: @ViewDslMarker UISpacing.() -> Unit = {} ): UISpacing = UISpacing(width, height).addTo(this).apply(block) open class UISpacing( width: Double = UI_DEFAULT_WIDTH, height: Double = UI_DEFAULT_HEIGHT, ) : UIView(width, height), ViewLeaf
apache-2.0
072a72607416ecebe4f1be62427908f2
29.357143
64
0.705882
3.455285
false
false
false
false
synyx/calenope
modules/organizer/src/main/kotlin/de/synyx/calenope/organizer/component/Widgets.kt
1
3534
package de.synyx.calenope.organizer.component import android.support.design.widget.TextInputEditText import android.support.design.widget.TextInputLayout import android.text.InputType import android.view.Gravity import android.widget.ImageButton import android.widget.LinearLayout import de.synyx.calenope.organizer.R import trikita.anvil.BaseDSL.MATCH import trikita.anvil.BaseDSL.WRAP import trikita.anvil.BaseDSL.layoutGravity import trikita.anvil.BaseDSL.weight import trikita.anvil.DSL.backgroundResource import trikita.anvil.DSL.dip import trikita.anvil.DSL.imageButton import trikita.anvil.DSL.imageResource import trikita.anvil.DSL.inputType import trikita.anvil.DSL.linearLayout import trikita.anvil.DSL.margin import trikita.anvil.DSL.onClick import trikita.anvil.DSL.onEditorAction import trikita.anvil.DSL.onLongClick import trikita.anvil.DSL.orientation import trikita.anvil.DSL.size import trikita.anvil.DSL.text import trikita.anvil.design.DesignDSL.hint import trikita.anvil.design.DesignDSL.textInputEditText import trikita.anvil.design.DesignDSL.textInputLayout /** * @author clausen - [email protected] */ object Widgets { class Button ( private val resource : Int, private val button : Element<ImageButton>.() -> Unit = {} ) : Component () { override fun view () { imageButton { configure<ImageButton> { once += { size (dip (48), dip (48)) imageResource (resource) backgroundResource (R.color.primary) } always += { onClick {} onLongClick { false } } button (this) } } } } class Speechinput ( private val text : CharSequence? = "", private val hint : CharSequence? = "", private val input : Element<TextInputEditText>.() -> Unit = {}, private val button : Element<ImageButton>.() -> Unit = {} ) : Component () { override fun view () { linearLayout { size (MATCH, WRAP) orientation (LinearLayout.HORIZONTAL) margin (dip (20), dip (20), dip (20), 0) textInputLayout { configure<TextInputLayout> { once += { size (MATCH, WRAP) weight (1.0f) hint ([email protected]) } } textInputEditText { configure<TextInputEditText> { once += { size (MATCH, dip (40)) inputType (InputType.TYPE_CLASS_TEXT) } always += { text ([email protected]) onEditorAction { _, _, _ -> false } } input (this) } } } show { Button (R.drawable.ic_record) { once += { layoutGravity (Gravity.END) } button (this) } } } } } }
apache-2.0
eaf75fd8df960f7d9036d866fd078bd1
30.008772
73
0.499434
5.387195
false
false
false
false
cashapp/sqldelight
dialects/postgresql/src/main/kotlin/app/cash/sqldelight/dialects/postgresql/grammar/mixins/AlterTableRenameColumnMixin.kt
1
1970
package app.cash.sqldelight.dialects.postgresql.grammar.mixins import app.cash.sqldelight.dialects.postgresql.grammar.psi.PostgreSqlAlterTableRenameColumn import com.alecstrong.sql.psi.core.SqlAnnotationHolder import com.alecstrong.sql.psi.core.psi.AlterTableApplier import com.alecstrong.sql.psi.core.psi.LazyQuery import com.alecstrong.sql.psi.core.psi.QueryElement import com.alecstrong.sql.psi.core.psi.SqlColumnAlias import com.alecstrong.sql.psi.core.psi.SqlColumnName import com.alecstrong.sql.psi.core.psi.SqlCompositeElementImpl import com.alecstrong.sql.psi.core.psi.alterStmt import com.intellij.lang.ASTNode internal abstract class AlterTableRenameColumnMixin( node: ASTNode, ) : SqlCompositeElementImpl(node), PostgreSqlAlterTableRenameColumn, AlterTableApplier { private val columnName get() = children.filterIsInstance<SqlColumnName>().single() private val columnAlias get() = children.filterIsInstance<SqlColumnAlias>().single() override fun applyTo(lazyQuery: LazyQuery): LazyQuery { return LazyQuery( tableName = lazyQuery.tableName, query = { val columns = lazyQuery.query.columns val column = QueryElement.QueryColumn(element = columnAlias) val replace = columns.singleOrNull { (it.element as SqlColumnName).textMatches(columnName) } lazyQuery.query.copy( columns = lazyQuery.query.columns.map { if (it == replace) column else it }, ) }, ) } override fun annotate(annotationHolder: SqlAnnotationHolder) { super.annotate(annotationHolder) if (tablesAvailable(this) .filter { it.tableName.textMatches(alterStmt.tableName) } .flatMap { it.query.columns } .none { (it.element as? SqlColumnName)?.textMatches(columnName) == true } ) { annotationHolder.createErrorAnnotation( element = columnName, s = "No column found to modify with name ${columnName.text}", ) } } }
apache-2.0
f257fd332d1519be6dd818b367bfa371
34.818182
91
0.733503
4.156118
false
false
false
false
marcelgross90/Cineaste
app/src/main/kotlin/de/cineaste/android/entity/movie/Movie.kt
1
1080
package de.cineaste.android.entity.movie import com.google.gson.annotations.SerializedName import java.util.Date data class Movie( var id: Long = 0, @SerializedName("poster_path") var posterPath: String? = "", var title: String = "", var runtime: Int = 0, @SerializedName("vote_average") var voteAverage: Double = 0.toDouble(), @SerializedName("vote_count") var voteCount: Int = 0, @SerializedName("overview") var description: String = "", private var watched: Boolean = false, var watchedDate: Date? = null, @SerializedName("release_date") var releaseDate: Date? = null, var listPosition: Int = 0 ) : Comparable<Movie> { var isWatched: Boolean get() = watched set(watched) { this.watched = watched if (watched && this.watchedDate == null) { this.watchedDate = Date() } else { this.watchedDate = null } } override fun compareTo(other: Movie): Int { return this.id.compareTo(other.id) } }
gpl-3.0
823a817a562ca023beb696db81e333c6
26.025
54
0.599074
4.137931
false
false
false
false
exponent/exponent
packages/expo-dev-launcher/android/src/main/java/expo/modules/devlauncher/launcher/errors/DevLauncherUncaughtExceptionHandler.kt
2
3042
package expo.modules.devlauncher.launcher.errors import android.app.Activity import android.app.Application import android.os.Bundle import android.os.Process import android.util.Log import java.lang.ref.WeakReference import java.util.* import kotlin.concurrent.schedule import kotlin.system.exitProcess class DevLauncherUncaughtExceptionHandler( application: Application, private val defaultUncaughtHandler: Thread.UncaughtExceptionHandler? ) : Thread.UncaughtExceptionHandler { private val applicationHolder = WeakReference(application) private var exceptionWasReported = false private var timerTask: TimerTask? = null init { application.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) { if (exceptionWasReported && activity is DevLauncherErrorActivity) { timerTask?.cancel() timerTask = null exceptionWasReported = false return } } override fun onActivityStarted(activity: Activity) = Unit override fun onActivityResumed(activity: Activity) = Unit override fun onActivityPaused(activity: Activity) = Unit override fun onActivityStopped(activity: Activity) = Unit override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit override fun onActivityDestroyed(activity: Activity) = Unit }) } override fun uncaughtException(thread: Thread, exception: Throwable) { // The same exception can be reported multiple times. // We handle only the first one. if (exceptionWasReported) { return } exceptionWasReported = true Log.e("DevLauncher", "DevLauncher tries to handle uncaught exception.", exception) applicationHolder.get()?.let { DevLauncherErrorActivity.showFatalError( it, DevLauncherAppError(exception.message, exception) ) } // We don't know if the error screen will show up. // For instance, if the exception was thrown in `MainApplication.onCreate` method, // the erorr screen won't show up. // That's why we schedule a simple function which will check // if the error was handle properly or will fallback // to the default exception handler. timerTask = Timer().schedule(2000) { if (!exceptionWasReported) { // Exception was handle, we should suppress error here return@schedule } // The error screen didn't appear in time. // We fallback to the default exception handler. if (defaultUncaughtHandler != null) { defaultUncaughtHandler.uncaughtException(thread, exception) } else { // This scenario should never occur. It can only happen if there was no defaultUncaughtHandler when the handler was set up. Log.e("UNCAUGHT_EXCEPTION", "exception", exception) // print exception in 'Logcat' tab. Process.killProcess(Process.myPid()) exitProcess(0) } } } }
bsd-3-clause
63b309d2ba3e6cc42d421468ff82c6bb
33.965517
131
0.714333
5.07
false
false
false
false
TeamWizardry/LibrarianLib
modules/core/src/main/kotlin/com/teamwizardry/librarianlib/core/util/RegistryId.kt
1
2407
@file:JvmName("RegistryId") package com.teamwizardry.librarianlib.core.util import net.minecraft.block.Block import net.minecraft.enchantment.Enchantment import net.minecraft.entity.EntityType import net.minecraft.entity.attribute.EntityAttribute import net.minecraft.entity.effect.StatusEffect import net.minecraft.fluid.Fluid import net.minecraft.item.Item import net.minecraft.loot.condition.LootConditionType import net.minecraft.loot.entry.LootPoolEntryType import net.minecraft.loot.function.LootFunctionType import net.minecraft.potion.Potion import net.minecraft.recipe.RecipeSerializer import net.minecraft.recipe.RecipeType import net.minecraft.sound.SoundEvent import net.minecraft.stat.StatType import net.minecraft.util.Identifier import net.minecraft.util.registry.Registry public val SoundEvent.registryId: Identifier? @JvmName("of") get() = Registry.SOUND_EVENT.getId(this) public val Fluid.registryId: Identifier @JvmName("of") get() = Registry.FLUID.getId(this) public val StatusEffect.registryId: Identifier? @JvmName("of") get() = Registry.STATUS_EFFECT.getId(this) public val Block.registryId: Identifier @JvmName("of") get() = Registry.BLOCK.getId(this) public val Enchantment.registryId: Identifier? @JvmName("of") get() = Registry.ENCHANTMENT.getId(this) public val EntityType<*>.registryId: Identifier @JvmName("of") get() = Registry.ENTITY_TYPE.getId(this) public val Item.registryId: Identifier @JvmName("of") get() = Registry.ITEM.getId(this) public val Potion.registryId: Identifier @JvmName("of") get() = Registry.POTION.getId(this) public val RecipeType<*>.registryId: Identifier? @JvmName("of") get() = Registry.RECIPE_TYPE.getId(this) public val RecipeSerializer<*>.registryId: Identifier? @JvmName("of") get() = Registry.RECIPE_SERIALIZER.getId(this) public val EntityAttribute.registryId: Identifier? @JvmName("of") get() = Registry.ATTRIBUTE.getId(this) public val StatType<*>.registryId: Identifier? @JvmName("of") get() = Registry.STAT_TYPE.getId(this) public val LootPoolEntryType.registryId: Identifier? @JvmName("of") get() = Registry.LOOT_POOL_ENTRY_TYPE.getId(this) public val LootFunctionType.registryId: Identifier? @JvmName("of") get() = Registry.LOOT_FUNCTION_TYPE.getId(this) public val LootConditionType.registryId: Identifier? @JvmName("of") get() = Registry.LOOT_CONDITION_TYPE.getId(this)
lgpl-3.0
b60e60c6dabf37ea5fd9b653b13ba3de
42.763636
68
0.777732
3.760938
false
false
false
false
foreverigor/TumCampusApp
app/src/main/java/de/tum/in/tumcampusapp/utils/Const.kt
1
7096
package de.tum.`in`.tumcampusapp.utils /** * Contains different constants used by several classes. Allows a unified access. */ object Const { const val MENSA_FOR_FAVORITEDISH = "FavoriteDishCafeteriaID" const val ACCESS_TOKEN = "access_token" const val ACTION_EXTRA = "action" const val BACKGROUND_MODE = "background_mode" const val CAFETERIA_ID = "cafeteriasId" const val CAFETERIA_DATE = "cafeteriaDate" const val CAFETERIAS = "cafeterias" const val CALENDAR_WEEK_MODE = "calender_week_mode" const val EVENT_BOOKED_MODE = "event_booked_mode" const val COMPLETED = "completed" const val DATABASE_NAME = "tca.db" const val DATE = "date" const val DOWNLOAD_ALL_FROM_EXTERNAL = "download_all_from_external" const val ERROR = "error" const val MESSAGE = "message" const val FORCE_DOWNLOAD = "force_download" const val LRZ_ID = "lrz_id" const val NEWS = "news" const val EVENTS = "events" const val KINO = "kino" const val STUDY_ROOM_GROUP_ID = "study_room_group_id" const val ROLE = "card_role" const val SILENCE_ON = "silence_on" const val SILENCE_SERVICE = "silent_mode" const val SILENCE_OLD_STATE = "silence_old_state" const val TITLE_EXTRA = "title" const val API_HOSTNAME = "tumcabe.in.tum.de" const val API_HOSTNAME_NEW = "app.tum.de" const val STUDY_ROOMS_HOSTNAME = "www.devapp.it.tum.de" const val CURRENT_CHAT_ROOM = "current_chat_room" const val CHAT_ROOM_DISPLAY_NAME = "chat_room_display_name" const val CHAT_ROOM_NAME = "chat_room_name" const val PRIVATE_KEY = "chat_member_private_key" const val PUBLIC_KEY = "chat_member_public_key" const val PUBLIC_KEY_UPLOADED = "chat_member_public_key_uploaded" const val TUMO_PIDENT_NR = "pIdentNr" const val TUMO_STUDENT_ID = "tumoStudentNr" const val TUMO_EXTERNAL_ID = "tumoExternNr" const val TUMO_EMPLOYEE_ID = "tumoBediensteteNr" const val TUMO_DISABLED = "tumo_is_disabled" const val EMPLOYEE_MODE = "employee_mode" const val FCM_REG_ID = "gcm_registration_id" const val FCM_REG_ID_SENT_TO_SERVER = "gcm_registration_id_sent_to_server" const val FCM_REG_ID_LAST_TRANSMISSION = "gcm_registration_id_last_transmission" const val FCM_INSTANCE_ID = "gcm_instance_id" const val FCM_TOKEN_ID = "gcm_token_id" const val APP_LAUNCHES = "app_launches" const val SYNC_CALENDAR = "sync_calendar" const val PREFERENCE_SCREEN = "preference_screen" const val P_TOKEN = "pToken" const val SYNC_CALENDAR_IMPORT = "calendar_import" const val GROUP_CHAT_ENABLED = "group_chat_enabled" const val BUG_REPORTS = "bug_reports" const val DEFAULT_CAMPUS = "card_default_campus" const val AUTO_JOIN_NEW_ROOMS = "auto_join_new_rooms" const val CHAT_MEMBER = "chat_member" const val POSITION = "position" const val PREF_UNIQUE_ID = "PREF_UNIQUE_ID" const val URL_ROOM_FINDER_API = "/Api/roomfinder/room/" const val URL_DEFAULT_MAP_IMAGE = "https://$API_HOSTNAME${URL_ROOM_FINDER_API}defaultMap/" const val URL_MAP_IMAGE = "https://$API_HOSTNAME${URL_ROOM_FINDER_API}map/" const val ROOM_ID = "room_id" const val KEY_NOTIFICATION_ID = "notificationID" const val KEY_NOTIFICATION = "notification" const val NOTIFICATION_CHANNEL_DEFAULT = "general" const val NOTIFICATION_CHANNEL_CHAT = "chat" const val NOTIFICATION_CHANNEL_EDUROAM = "eduroam" const val NOTIFICATION_CHANNEL_CAFETERIA = "cafeteria" const val NOTIFICATION_CHANNEL_MVV = "mvv" const val NOTIFICATION_CHANNEL_EMERGENCY = "emergency" const val BACKGROUND_SERVICE_JOB_ID = 1000 const val SEND_MESSAGE_SERVICE_JOB_ID = 1001 const val SILENCE_SERVICE_JOB_ID = 1002 const val SEND_WIFI_SERVICE_JOB_ID = 1003 const val DOWNLOAD_SERVICE_JOB_ID = 1004 const val FILL_CACHE_SERVICE_JOB_ID = 1005 const val FEEDBACK_MESSAGE = "feedback_message" const val FEEDBACK_PIC_PATHS = "feedback_paths" const val FEEDBACK_INCL_EMAIL = "feedback_include_email" const val FEEDBACK_INCL_LOCATION = "feedback_incl_location" const val FEEDBACK_TOPIC = "feedback_topic" const val FEEDBACK_EMAIL = "feedback_reply_to" const val FEEDBACK_IMG_COMPRESSION_QUALITY = 50; const val FEEDBACK_TOPIC_GENERAL = "general" const val FEEDBACK_TOPIC_APP = "tca" const val EXTRA_FOREIGN_CONFIGURATION_EXISTS = "CONFIGURED_BY_OTHER_APP" const val GEOFENCING_SERVICE_JOB_ID = 1006 const val ADD_GEOFENCE_EXTRA = "AddGeofence" const val DISTANCE_IN_METER = 50 * 1000f const val MUNICH_GEOFENCE = "geofence_munich_id" const val TUM_ID_PATTERN = "^[a-z]{2}[0-9]{2}[a-z]{3}$" const val WIFI_SCANS_ALLOWED = "WIFI_SCANS_ALLOWED" const val WIFI_SCAN_MINIMUM_BATTERY_LEVEL = "WIFI_SCAN_MINIMUM_BATTERY_LEVEL" const val CARD_POSITION_PREFERENCE_SUFFIX = "_card_position" const val DISCARD_SETTINGS_START = "discard_settings_start" const val DISCARD_SETTINGS_PHONE = "discard_settings_phone" const val CALENDAR_ID_PARAM = "calendar_id" const val RAINBOW_MODE = "rainbow_enabled" const val REFRESH_CARDS = "refresh_cards" const val EDUROAM_SSID = "eduroam" const val LRZ = "lrz" const val FCM_CHAT = "fcmChat" const val CHAT_MESSAGE = "chatMessage" const val CHAT_BROADCAST_NAME = "chat-message-received" const val EVENT_EDIT = "pEdit" const val EVENT_TITLE = "pTitel" const val EVENT_COMMENT = "pAnmerkung" const val EVENT_START = "pVon" const val EVENT_END = "pBis" const val EVENT_NR = "pTerminNr" const val EVENT_TIME = "event_time" const val KINO_DATE = "kinoDate" const val CALENDAR_MONTHS_BEFORE = 2 const val CALENDAR_MONTHS_AFTER = 2 const val PDF_TITLE = "pdfTitle" const val PDF_PATH = "pdfPath" const val TOP_NEWS = "topNewsDownload" const val NEWS_ALERT_IMAGE = "newsAlertImageURL" const val NEWS_ALERT_LINK = "newsAlertLink" const val NEWS_ALERT_SHOW_UNTIL = "newsAlertShowUntil" const val CONTACTS_PERMISSION_REQUEST_CODE = 0 const val PERSON_SEARCH_TUM_REQUEST_KEY = "pSuche" const val TUM_CAMPUS_URL = "http://campus.tum.de" const val TUM_ONLINE_PROFILE_PICTURE_URL_FORMAT_STRING = "https://campus.tum.de/tumonline/visitenkarte.showImage?pPersonenGruppe=%s&pPersonenId=%s" const val CALENDAR_FILTER_CANCELED = "calendar_filter_canceled" const val CALENDAR_FILTER_HOUR_LIMIT_MIN = "calendar_filter_hour_limit_min" const val CALENDAR_FILTER_HOUR_LIMIT_MAX = "calendar_filter_hour_limit_max" const val CALENDAR_FILTER_HOUR_LIMIT_MIN_DEFAULT = "8" const val CALENDAR_FILTER_HOUR_LIMIT_MAX_DEFAULT = "20" const val STRIPE_API_PUBLISHABLE_KEY = "pk_live_bjSAhBM3WFUqeNI4cJn9upDW" const val KEY_EVENT = "event" const val KEY_EVENT_ID = "eventId" const val KEY_CARD_HOLDER = "cardholder" const val KEY_TICKET_PRICE = "ticketPrice" const val KEY_TICKET_HISTORY = "ticketHistory" const val SHOW_DRAWER = "showDrawer" const val KEY_NOTIFICATION_TYPE_ID = "type_id" }
gpl-3.0
210e2119cf48c1c9f6a86b48e5e83217
39.548571
151
0.699267
3.387112
false
false
false
false
charleskorn/batect
app/src/unitTest/kotlin/batect/execution/CancellationContextSpec.kt
1
3877
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.execution import batect.testutils.createForEachTest import batect.testutils.equalTo import batect.testutils.given import batect.testutils.on import com.natpryce.hamkrest.assertion.assertThat import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object CancellationContextSpec : Spek({ describe("a cancellation context") { val context by createForEachTest { CancellationContext() } given("a cancellation callback has been registered") { var callbackCount = 0 beforeEachTest { callbackCount = 0 context.addCancellationCallback { callbackCount++ } } on("before the context is cancelled") { it("does not call the registered callback") { assertThat(callbackCount, equalTo(0)) } } on("cancelling the context") { beforeEachTest { context.cancel() } it("calls the registered callback") { assertThat(callbackCount, equalTo(1)) } } on("cancelling the context multiple times") { beforeEachTest { context.cancel() context.cancel() } it("calls the registered callback only once") { assertThat(callbackCount, equalTo(1)) } } } given("a cancellation callback has been registered and removed") { var callbackCount = 0 beforeEachTest { callbackCount = 0 val closeable = context.addCancellationCallback { callbackCount++ } closeable.use {} } on("cancelling the context") { beforeEachTest { context.cancel() } it("does not call the callback") { assertThat(callbackCount, equalTo(0)) } } } given("multiple cancellation callbacks have been registered") { var callback1Count = 0 var callback2Count = 0 beforeEachTest { callback1Count = 0 callback2Count = 0 context.addCancellationCallback { callback1Count++ } context.addCancellationCallback { callback2Count++ } } on("cancelling the context") { beforeEachTest { context.cancel() } it("calls both registered callbacks") { assertThat(callback1Count, equalTo(1)) assertThat(callback2Count, equalTo(1)) } } } given("the cancellation context has been cancelled") { beforeEachTest { context.cancel() } on("registering a callback") { var callbackCount = 0 beforeEachTest { callbackCount = 0 context.addCancellationCallback { callbackCount++ }.use {} } it("immediately calls the callback") { assertThat(callbackCount, equalTo(1)) } } } } })
apache-2.0
3cf8183ce954469d12fc9111e248d6a7
30.778689
83
0.559195
5.718289
false
true
false
false
android/identity-samples
BlockStore/app/src/main/java/com/google/android/gms/identity/sample/blockstore/MainViewModel.kt
1
1342
package com.google.android.gms.identity.sample.blockstore import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject data class State( val bytes: String? = null ) val State.areBytesStored get() = bytes != null /** * ViewModel is used to access the Block Store Data and to observe changes to it. */ @HiltViewModel class MainViewModel @Inject constructor( private val blockStoreRepository: BlockStoreRepository ) : ViewModel() { private val _state = MutableStateFlow(State()) val state: StateFlow<State> = _state.asStateFlow() init { viewModelScope.launch { _state.value = State(bytes = blockStoreRepository.retrieveBytes()) } } fun storeBytes(inputString: String) { viewModelScope.launch { blockStoreRepository.storeBytes(inputString) _state.value = State(bytes = blockStoreRepository.retrieveBytes()) } } fun clearBytes() { viewModelScope.launch { blockStoreRepository.clearBytes() _state.value = State(bytes = null) } } }
apache-2.0
554bdcdc5e7377f70b46ca39ca15f51f
26.979167
81
0.708644
4.611684
false
false
false
false
MoonlightOwl/Yui
src/main/kotlin/totoro/yui/actions/NeverGonnaAction.kt
1
766
package totoro.yui.actions import totoro.yui.client.Command import totoro.yui.client.IRCClient import totoro.yui.util.Dict class NeverGonnaAction : SensitivityAction("never", "nevergonna") { private val promises = Dict.of( "... give you up", "... let you down", "... run around", "... desert you", "... make you cry", "... say goodbye", "... tell a lie", "... hurt you" ) override fun handle(client: IRCClient, command: Command): Boolean { if (command.name == "nevergonna" || (command.args.size == 1 && command.args[0] == "gonna")) { client.send(command.chan, promises()) return true } return false } }
mit
d62f02d0a5781de24252364f0f38364d
28.461538
101
0.537859
4.11828
false
false
false
false
google/ide-perf
src/main/java/com/google/idea/perf/tracer/TracerClassFileTransformer.kt
1
9140
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.perf.tracer import com.google.idea.perf.agent.TracerTrampoline import com.intellij.openapi.diagnostic.Logger import org.objectweb.asm.ClassReader import org.objectweb.asm.ClassReader.EXPAND_FRAMES import org.objectweb.asm.ClassVisitor import org.objectweb.asm.ClassWriter import org.objectweb.asm.ClassWriter.COMPUTE_MAXS import org.objectweb.asm.MethodVisitor import org.objectweb.asm.Opcodes import org.objectweb.asm.Opcodes.ASM9 import org.objectweb.asm.Type import org.objectweb.asm.commons.AdviceAdapter import org.objectweb.asm.commons.Method import java.lang.instrument.ClassFileTransformer import java.security.ProtectionDomain import kotlin.reflect.jvm.javaMethod private const val ASM_API = ASM9 /** * [TracerClassFileTransformer] inserts calls (in JVM byte code) to the tracer hooks. * It consults [TracerConfig] to figure out which classes to transform. */ class TracerClassFileTransformer : ClassFileTransformer { override fun transform( loader: ClassLoader?, classJvmName: String, classBeingRedefined: Class<*>?, protectionDomain: ProtectionDomain?, classfileBuffer: ByteArray, ): ByteArray? { try { val className = classJvmName.replace('/', '.') if (TracerConfig.shouldInstrumentClass(className)) { return tryTransform(className, classfileBuffer) } else { return null } } catch (e: Throwable) { Logger.getInstance(javaClass).error("Failed to instrument class $classJvmName", e) return null } } // Debugging tip: the JVM verifier will only give you good error messages if the VerifyError // happens during the *initial* class load (not during class retransformations). private fun tryTransform( clazz: String, classBytes: ByteArray ): ByteArray? { // Note: we avoid using COMPUTE_FRAMES because that causes ClassWriter to use // reflection. Reflection triggers class loading (undesirable) and can also fail outright // if it is using the wrong classloader. See ClassWriter.getCommonSuperClass(). val reader = ClassReader(classBytes) val writer = ClassWriter(reader, COMPUTE_MAXS) val classVisitor = TracerClassVisitor(clazz, writer) reader.accept(classVisitor, EXPAND_FRAMES) // EXPAND_FRAMES is required by AdviceAdapter. return when { classVisitor.transformedSomeMethods -> writer.toByteArray() else -> null } } } class TracerClassVisitor( private val clazz: String, writer: ClassVisitor, ) : ClassVisitor(ASM_API, writer) { var transformedSomeMethods = false override fun visitMethod( access: Int, method: String, desc: String, signature: String?, exceptions: Array<out String>?, ): MethodVisitor? { val methodWriter = super.visitMethod(access, method, desc, signature, exceptions) val methodFqName = MethodFqName(clazz, method, desc) val traceData = TracerConfig.getMethodTraceData(methodFqName) if (traceData != null && traceData.config.enabled) { transformedSomeMethods = true return TracerMethodVisitor(methodWriter, traceData, clazz, method, desc, access) } else { return methodWriter } } } class TracerMethodVisitor( methodWriter: MethodVisitor, private val traceData: MethodTraceData, private val clazz: String, private val method: String, private val desc: String, access: Int, ) : AdviceAdapter(ASM_API, methodWriter, access, method, desc) { companion object { private val LOG = Logger.getInstance(TracerMethodVisitor::class.java) private val OBJECT_TYPE = Type.getType(Any::class.java) private val THROWABLE_TYPE = Type.getType(Throwable::class.java) private val TRAMPOLINE_TYPE = Type.getType(TracerTrampoline::class.java) private val TRAMPOLINE_ENTER_METHOD = Method.getMethod(TracerTrampoline::enter.javaMethod) private val TRAMPOLINE_LEAVE_METHOD = Method.getMethod(TracerTrampoline::leave.javaMethod) } private val methodStart = newLabel() // For constructors with control flow prior to the super class constructor call, // AdviceAdapter will sometimes fail to call onMethodEnter(). In those cases it // is better to bail out completely than have incorrect tracer hooks. private var methodEntered = false override fun onMethodEnter() { // Note: AdviceAdapter has a comment, "For constructors... onMethodEnter() is // called after each super class constructor call, because the object // cannot be used before it is properly initialized." In particular, it // seems we cannot wrap the super class constructor call inside our // try-catch block because then the JVM complains about seeing // "uninitialized this" in the stack map. So, we have to live with a // compromise: traced constructors will exclude the time spent in their // super class constructor calls. This seems acceptable for now. push(traceData.methodId) loadTracedArgs() invokeStatic(TRAMPOLINE_TYPE, TRAMPOLINE_ENTER_METHOD) methodEntered = true mark(methodStart) } override fun onMethodExit(opcode: Int) { if (methodEntered && opcode != ATHROW) { invokeStatic(TRAMPOLINE_TYPE, TRAMPOLINE_LEAVE_METHOD) } } override fun visitMaxs(maxStack: Int, maxLocals: Int) { // Note: visitMaxs() is the first method called after visiting all instructions. if (methodEntered) { buildCatchBlock() } else { val fqName = "$clazz.$method$desc" LOG.warn("Unable to instrument $fqName because ASM failed to call onMethodEnter") } super.visitMaxs(maxStack, maxLocals) } // Surrounds the entire method body with a try-catch block to ensure that the // exit hook is called even if exceptions are thrown. private fun buildCatchBlock() { // Technically, ASM requires that visitTryCatchBlock() is called *before* its start // label is visited. However, we do not want to call visitTryCatchBlock() at the start // of the method because that would place the handler at the beginning of the exception // table, thus incorrectly taking priority over preexisting catch blocks. // For more details see https://gitlab.ow2.org/asm/asm/-/issues/317617. // // There are a few ways to work around this: // 1. Use the ASM tree API, which can directly mutate the exception table. // 2. Replace the method body with a single try-catch block surrounding // a call to a synthetic method containing the original body. // 3. Ignore what ASM says and just visit the labels out of order. // // Option 1 seems more complex than we want, and option 2 seems invasive. So we // choose option 3 for now, which---despite breaking the ASM verifier---seems to // work fine. In fact, option 3 is what everyone else seems to do, including the author // of AdviceAdapter (see the 2007 paper "Using the ASM framework to implement common // Java bytecode transformation patterns" from Eugene Kuleshov). catchException(methodStart, mark(), THROWABLE_TYPE) visitFrame(Opcodes.F_NEW, 0, emptyArray(), 1, arrayOf(THROWABLE_TYPE.internalName)) invokeStatic(TRAMPOLINE_TYPE, TRAMPOLINE_LEAVE_METHOD) throwException() // Rethrow. } private fun loadTracedArgs() { val rawTracedParams = traceData.config.tracedParams val tracedParams = rawTracedParams.filter(argumentTypes.indices::contains) if (tracedParams.size < rawTracedParams.size) { val fqName = "$clazz.$method$desc" LOG.warn("Some arg indices are out of bounds for method $fqName: $rawTracedParams") } if (tracedParams.isEmpty()) { visitInsn(ACONST_NULL) return } // See the similar code in GeneratorAdapter.loadArgArray(). push(tracedParams.size) newArray(OBJECT_TYPE) for ((storeIndex, paramIndex) in tracedParams.withIndex()) { dup() push(storeIndex) loadArg(paramIndex) box(argumentTypes[paramIndex]) arrayStore(OBJECT_TYPE) } } }
apache-2.0
c33fd8ceed0de0e1dd33d6c26d9c71ac
41.511628
98
0.681838
4.531482
false
false
false
false
wealthfront/magellan
magellan-test/src/main/java/com/wealthfront/magellan/test/FakeLinearNavigator.kt
1
2609
package com.wealthfront.magellan.test import android.content.Context import com.wealthfront.magellan.Direction import com.wealthfront.magellan.Direction.BACKWARD import com.wealthfront.magellan.Direction.FORWARD import com.wealthfront.magellan.core.Navigable import com.wealthfront.magellan.init.getDefaultTransition import com.wealthfront.magellan.navigation.LinearNavigator import com.wealthfront.magellan.navigation.NavigationEvent import com.wealthfront.magellan.transitions.MagellanTransition import java.util.ArrayDeque import java.util.Deque /** * An implementation of [LinearNavigator] suitable for tests. Avoids attaching child [Navigable]s to * the lifecycle, avoiding the need to satisfy their dependencies. Holds state; should be * re-instantiated, [destroy]ed, or [clear]ed between tests. */ public class FakeLinearNavigator : LinearNavigator { public override var backStack: List<NavigationEvent> = emptyList() /** * The [Navigable] that's currently on the top of the [backStack] */ public val currentNavigable: Navigable? get() = backStack.firstOrNull()?.navigable as? Navigable /** * Clear this navigator for the next test. [destroy] will do the same thing, and it's also safe to * leave this object to be garbage collected instead. */ public fun clear() { backStack = emptyList() } public override fun goTo(navigable: Navigable, overrideMagellanTransition: MagellanTransition?) { navigate(FORWARD) { backStack -> backStack.push( NavigationEvent( navigable, overrideMagellanTransition ?: getDefaultTransition() ) ) backStack.peek()!!.magellanTransition } } public override fun replace(navigable: Navigable, overrideMagellanTransition: MagellanTransition?) { navigate(FORWARD) { backStack -> backStack.pop() backStack.push( NavigationEvent( navigable, overrideMagellanTransition ?: getDefaultTransition() ) ) backStack.peek()!!.magellanTransition } } public override fun navigate( direction: Direction, backStackOperation: (Deque<NavigationEvent>) -> MagellanTransition ) { val tempBackStack: Deque<NavigationEvent> = ArrayDeque(backStack) backStackOperation(tempBackStack) backStack = tempBackStack.toList() } public override fun goBack(): Boolean { return if (backStack.size > 1) { navigate(BACKWARD) { backStack -> backStack.pop().magellanTransition } true } else { false } } public override fun destroy(context: Context) { clear() } }
apache-2.0
f0e88fa9662138a1b88ba893125cce28
30.059524
102
0.722499
4.717902
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/nbt/lang/NbttBraceMatcher.kt
1
1408
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.lang import com.demonwav.mcdev.nbt.lang.gen.psi.NbttByteArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttIntArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttLongArray import com.demonwav.mcdev.nbt.lang.gen.psi.NbttTypes import com.intellij.lang.BracePair import com.intellij.lang.PairedBraceMatcher import com.intellij.psi.PsiFile import com.intellij.psi.tree.IElementType class NbttBraceMatcher : PairedBraceMatcher { override fun getCodeConstructStart(file: PsiFile, openingBraceOffset: Int): Int { val element = file.findElementAt(openingBraceOffset) if (element == null || element is PsiFile) { return openingBraceOffset } val parent = element.parent if (parent is NbttByteArray || parent is NbttIntArray || parent is NbttLongArray) { return parent.textRange.startOffset } return openingBraceOffset } override fun getPairs() = arrayOf( BracePair(NbttTypes.LPAREN, NbttTypes.RPAREN, true), BracePair(NbttTypes.LBRACE, NbttTypes.RBRACE, true), BracePair(NbttTypes.LBRACKET, NbttTypes.RBRACKET, true) ) override fun isPairedBracesAllowedBeforeType(lbraceType: IElementType, contextType: IElementType?) = true }
mit
f11d7eed0aa1a3fadac40d4a40efccf5
30.288889
109
0.727273
4.253776
false
false
false
false
anlun/haskell-idea-plugin
plugin/src/org/jetbrains/haskell/parser/HaskellParserDefinition.kt
1
2305
package org.jetbrains.haskell.parser import com.intellij.lang.ASTNode import com.intellij.lang.ParserDefinition import com.intellij.lang.PsiBuilder import com.intellij.lang.PsiParser import com.intellij.lexer.Lexer import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.FileViewProvider import com.intellij.psi.tree.IElementType import com.intellij.psi.tree.TokenSet import com.intellij.psi.tree.IFileElementType import org.jetbrains.haskell.fileType.HaskellFile import org.jetbrains.haskell.HaskellLanguage import org.jetbrains.haskell.parser.lexer.HaskellLexer import com.intellij.lang.ParserDefinition.SpaceRequirements import org.jetbrains.haskell.parser.token.* import com.intellij.extapi.psi.ASTWrapperPsiElement import org.jetbrains.haskell.psi.Module import java.util.ArrayList import org.jetbrains.grammar.HaskellLexerTokens public class HaskellParserDefinition() : ParserDefinition { val HASKELL_FILE = IFileElementType(HaskellLanguage.INSTANCE) override fun createLexer(project: Project?): Lexer = HaskellLexer() override fun getFileNodeType(): IFileElementType = HASKELL_FILE override fun getWhitespaceTokens() = WHITESPACES override fun getCommentTokens(): TokenSet = COMMENTS override fun getStringLiteralElements(): TokenSet = TokenSet.create(HaskellLexerTokens.STRING) override fun createParser(project: Project?): PsiParser = object : PsiParser { override fun parse(root: IElementType?, builder: PsiBuilder?): ASTNode { return org.jetbrains.grammar.HaskellParser(builder!!).parse(root!!) } } override fun createFile(viewProvider: FileViewProvider?): PsiFile = HaskellFile(viewProvider!!) override fun spaceExistanceTypeBetweenTokens(left: ASTNode?, right: ASTNode?) = ParserDefinition.SpaceRequirements.MAY override fun createElement(node: ASTNode?): PsiElement { val elementType = node!!.getElementType() if (elementType is HaskellCompositeElementType) { val constructor = elementType.constructor if (constructor != null) { return constructor(node) } } return ASTWrapperPsiElement(node) } }
apache-2.0
438bfe54a7ddae5f9de5543aed759965
33.924242
98
0.754881
4.967672
false
false
false
false
collaction/freehkkai-android
app/src/main/java/hk/collaction/freehkkai/ui/settings/SettingsFragment.kt
1
5995
package hk.collaction.freehkkai.ui.settings import android.app.Activity import android.content.Intent import android.content.SharedPreferences import android.net.Uri import android.os.Build import android.os.Bundle import androidx.preference.Preference import androidx.preference.PreferenceFragmentCompat import androidx.preference.PreferenceManager import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.listItemsSingleChoice import hk.collaction.freehkkai.BuildConfig import hk.collaction.freehkkai.R import hk.collaction.freehkkai.util.Utils import hk.collaction.freehkkai.util.Utils.PREF_FONT_VERSION import hk.collaction.freehkkai.util.Utils.getCurrentFontName class SettingsFragment : PreferenceFragmentCompat() { private lateinit var sharedPreferences: SharedPreferences private var prefFontVersion: Preference? = null override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { addPreferencesFromResource(R.xml.pref_general) sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) /* Set version */ val prefVersion = findPreference<Preference>("pref_version") prefVersion!!.summary = Utils.getAppVersionName(context) findPreference<Preference>("pref_report")?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val intent = Intent(Intent.ACTION_SEND) var text = "Android Version: " + Build.VERSION.RELEASE + "\n" text += "SDK Level: " + Build.VERSION.SDK_INT.toString() + "\n" text += "Version: " + Utils.getAppVersionName(context) + "\n" text += "Brand: " + Build.BRAND + "\n" text += "Model: " + Build.MODEL + "\n\n\n" intent.type = "message/rfc822" intent.putExtra(Intent.EXTRA_EMAIL, arrayOf(BuildConfig.CONTACT_EMAIL)) intent.putExtra(Intent.EXTRA_SUBJECT, "自由香港楷書回報問題") intent.putExtra(Intent.EXTRA_TEXT, text) startActivity(intent) false } findPreference<Preference>("pref_rate")?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val uri = Uri.parse("market://details?id=" + context?.packageName) val intent = Intent(Intent.ACTION_VIEW, uri) startActivity(intent) false } findPreference<Preference>("pref_share")?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val intent = Intent() intent.action = Intent.ACTION_SEND intent.putExtra(Intent.EXTRA_TEXT, "下載「自由香港楷書」程式,就可以查詢支援超過 4700 個香港教育局楷書參考寫法,解決因為「電腦輸入法」而令學生 / 家長 / 教師混淆而寫錯字的問題。\n\n" + "https://play.google.com/store/apps/details?id=" + context?.packageName) intent.type = "text/plain" startActivity(Intent.createChooser(intent, "分享此程式")) false } findPreference<Preference>("pref_author")?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val uri = Uri.parse("market://search?q=pub:\"Collaction 小隊\"") val intent = Intent(Intent.ACTION_VIEW, uri) startActivity(intent) false } findPreference<Preference>("pref_collaction")?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val uri = Uri.parse("https://www.collaction.hk/s/collactionopensource") val intent = Intent(Intent.ACTION_VIEW, uri) startActivity(intent) false } findPreference<Preference>("pref_hkfreekai")?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val uri = Uri.parse("https://www.collaction.hk/s/freehkfonts") val intent = Intent(Intent.ACTION_VIEW, uri) startActivity(intent) false } findPreference<Preference>("pref_privacy")?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val uri = Uri.parse("https://www.collaction.hk/about/privacy") val intent = Intent(Intent.ACTION_VIEW, uri) startActivity(intent) false } prefFontVersion = findPreference("pref_font_version") prefFontVersion?.onPreferenceClickListener = Preference.OnPreferenceClickListener { val a = when (sharedPreferences.getString(PREF_FONT_VERSION, "4700")) { "7000" -> 1 else -> 0 } activity?.let { activity -> MaterialDialog(activity) .title(text = "切換字型檔案版本") .listItemsSingleChoice( R.array.font_version_array, initialSelection = a, waitForPositiveButton = false ) { dialog, index, _ -> when (index) { 0 -> sharedPreferences.edit().putString(PREF_FONT_VERSION, "4700").apply() 1 -> sharedPreferences.edit().putString(PREF_FONT_VERSION, "7000").apply() } setFontVersionSummary() dialog.dismiss() } .negativeButton(R.string.ui_cancel) .show() activity.setResult(Activity.RESULT_OK) } false } setFontVersionSummary() } private fun setFontVersionSummary() { context?.let { context -> prefFontVersion?.setSummary(getCurrentFontName(context)) } } companion object { fun newInstance(): SettingsFragment { return SettingsFragment() } } }
gpl-3.0
3fe8da8890e6f6bc0dfed2cfbf5104d6
45.544
204
0.620251
4.627685
false
false
false
false
austinv11/KotBot-IV
Core/src/main/kotlin/com/austinv11/kotbot/core/util/extensions.kt
1
4893
package com.austinv11.kotbot.core.util import com.austinv11.kotbot.core.LOGGER import com.austinv11.kotbot.core.OWNER import com.austinv11.kotbot.core.api.commands.Command import sx.blah.discord.api.events.Event import sx.blah.discord.handle.obj.IChannel import sx.blah.discord.handle.obj.IDiscordObject import sx.blah.discord.handle.obj.IMessage import sx.blah.discord.handle.obj.IUser import sx.blah.discord.modules.IModule import sx.blah.discord.util.EmbedBuilder import sx.blah.discord.util.RequestBuffer import java.awt.Color import java.util.* import kotlin.reflect.* import kotlin.reflect.full.* val KOTLIN_BLURPLE = Color(118, 108, 180) val KOTLIN_BLUE = Color(5, 148, 214) val KOTLIN_PINK = Color(185, 90, 165) val KOTLIN_ORANGE = Color(248, 138, 0) /** * This generates a random color from the kotlin logo. */ fun generateRandomKotlinColor(): Color { when(Random().nextInt(4)) { 0 -> return KOTLIN_BLURPLE 1 -> return KOTLIN_BLUE 2 -> return KOTLIN_PINK 3 -> return KOTLIN_ORANGE } return KOTLIN_ORANGE } /** * This checks of this [KType] is a subtype of another class. This also checks nullable types. */ fun KType.isNullableSubtypeOf(type: KType): Boolean { var type = type if (this.isMarkedNullable) type = type.withNullability(true) return this.isSubtypeOf(type) } /** * This creates a standardized embed builder. */ fun createEmbedBuilder() = EmbedBuilder() .setLenient(true) .withFooterText("Owned by ${OWNER.name}#${OWNER.discriminator}") .withFooterIcon(OWNER.avatarURL) .withColor(generateRandomKotlinColor()) /** * This will automatically scan a module for inner classes extending [ModuleDependentObject] and then register them. */ fun IModule.scanForModuleDependentObjects(): Unit { this::class.nestedClasses .filter { it.allSupertypes.contains(ModuleDependentObject::class.starProjectedType) } .map { it.primaryConstructor!!.call(this) as ModuleDependentObject } .forEach { register(it) } } /** * This coerces a string to a given length. * @param length The desired length. * @return The coerced string. */ fun String.coerce(length: Int): String { if (this.length <= length) return this return this.substring(0, length-3)+"..." } /** * This checks if a specified event has a field which has an object with the same id as the provided object. * @param obj The object to check for. * @param T The object type to search for. * @return True if an object with a matching id is found. */ inline fun <reified T: IDiscordObject<T>> Event.isObjectPresent(obj: T): Boolean { return isIDPresent<T>(obj.id) } /** * This checks if a specified event has a field which has an object with the same id as provided. * @param id The id to check for. * @param T The object type to search for. * @return True if an object with the provided id is found. */ inline fun <reified T: IDiscordObject<T>> Event.isIDPresent(id: String): Boolean { return (this::class.java.fields+this::class.java.declaredFields) .filter { T::class.java.isAssignableFrom(it.type) } .apply { this.firstOrNull()?.isAccessible = true } .firstOrNull { (it.get(this) as? T)?.id == id } ?.run { true } ?: false } /** * This is a simple function wrapper for RequestBuffer. */ fun buffer(block: () -> Unit) { buffer<Unit>(block) } /** * This is a simple function wrapper for RequestBuffer. */ fun <T> buffer(block: () -> T): T { return RequestBuffer.request(RequestBuffer.IRequest<T> { try { return@IRequest block() } catch (e: Throwable) { LOGGER.error("Error caught attempting to send a request!", e) throw e } }).get() } /** * This represents caller information. */ val Any.caller: Caller get() = Caller() internal val contextMap: MutableMap<Int, CommandContext> = mutableMapOf() /** * This represents a command's context. */ val Command.context: CommandContext get() { val callr = caller return contextMap[Objects.hash(callr.thread, callr.`class`)]!! } /** * This represents a caller context. */ data class Caller(val thread: Thread = Thread.currentThread(), val `class`: String = spoofManager.getCallerClassName(4)) private val spoofManager = SpoofSecurityManager() internal class SpoofSecurityManager : SecurityManager() { fun getCallerClassName(callStackDepth: Int): String { return classContext[callStackDepth].name } } /** * This represents the context for a command. */ data class CommandContext(val message: IMessage, val channel: IChannel = message.channel, val user: IUser = message.author, val content: String = message.content)
gpl-3.0
1a1d0b0576eee23a43bf48a98c964fc1
29.391304
116
0.675455
3.880254
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/views/subscriptions/SubscriptionDetailsView.kt
1
8912
package com.habitrpg.android.habitica.ui.views.subscriptions import android.content.Context import android.content.Intent import android.graphics.drawable.BitmapDrawable import android.net.Uri import android.util.AttributeSet import android.view.View import android.widget.LinearLayout import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.SubscriptionDetailsBinding import com.habitrpg.common.habitica.extensions.layoutInflater import com.habitrpg.android.habitica.models.user.SubscriptionPlan import com.habitrpg.android.habitica.ui.views.HabiticaIconsHelper import java.text.DateFormat import java.time.LocalDate import java.time.format.DateTimeFormatter import java.util.Date class SubscriptionDetailsView : LinearLayout { lateinit var binding: SubscriptionDetailsBinding private var plan: SubscriptionPlan? = null var onShowSubscriptionOptions: (() -> Unit)? = null var currentUserID: String? = null constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet) { setupView() } constructor(context: Context) : super(context) { setupView() } private fun setupView() { binding = SubscriptionDetailsBinding.inflate(context.layoutInflater, this, true) binding.changeSubscriptionButton.setOnClickListener { changeSubscriptionButtonTapped() } binding.heartIcon.setImageDrawable(BitmapDrawable(context.resources, HabiticaIconsHelper.imageOfHeartLightBg())) } fun setPlan(plan: SubscriptionPlan) { this.plan = plan updateSubscriptionStatusPill(plan) var duration: String? = null if (plan.planId != null && plan.dateTerminated == null) { if (plan.planId == SubscriptionPlan.PLANID_BASIC || plan.planId == SubscriptionPlan.PLANID_BASICEARNED) { duration = resources.getString(R.string.month) } else if (plan.planId == SubscriptionPlan.PLANID_BASIC3MONTH) { duration = resources.getString(R.string.three_months) } else if (plan.planId == SubscriptionPlan.PLANID_BASIC6MONTH || plan.planId == SubscriptionPlan.PLANID_GOOGLE6MONTH) { duration = resources.getString(R.string.six_months) } else if (plan.planId == SubscriptionPlan.PLANID_BASIC12MONTH) { duration = resources.getString(R.string.twelve_months) } } when { duration != null -> binding.subscriptionDurationTextView.text = resources.getString(R.string.subscription_duration, duration) plan.isGroupPlanSub -> binding.subscriptionDurationTextView.setText(R.string.member_group_plan) plan.dateTerminated != null -> binding.subscriptionDurationTextView.text = resources.getString(R.string.ending_on, DateFormat.getDateInstance().format(plan.dateTerminated ?: Date())) } if ((plan.extraMonths ?: 0) > 0) { binding.subscriptionCreditWrapper.visibility = View.VISIBLE if (plan.extraMonths == 1) { binding.subscriptionCreditTextView.text = resources.getString(R.string.one_month) } else { binding.subscriptionCreditTextView.text = resources.getString(R.string.x_months, plan.extraMonths) } } else { binding.subscriptionCreditWrapper.visibility = View.GONE } when (plan.paymentMethod) { "Amazon Payments" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_amazon) "Apple" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_apple) "Google" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_google) "PayPal" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_paypal) "Stripe" -> binding.paymentProcessorImageView.setImageResource(R.drawable.payment_stripe) else -> { if (plan.isGiftedSub) { binding.paymentProcessorImageView.setImageResource(R.drawable.payment_gift) binding.subscriptionPaymentMethodTextview.text = context.getString(R.string.gifted) } else { binding.paymentProcessorWrapper.visibility = View.GONE } } } if (plan.consecutive?.count == 1) { binding.monthsSubscribedTextView.text = resources.getString(R.string.one_month) } else { binding.monthsSubscribedTextView.text = resources.getString(R.string.x_months, plan.consecutive?.count ?: 0) } binding.gemCapTextView.text = plan.totalNumberOfGems.toString() plan.monthsUntilNextHourglass?.let { nextHourglass -> val nextHourglassMonth = LocalDate.now().plusMonths(nextHourglass.toLong()).format(DateTimeFormatter.ofPattern("MMMM")) nextHourglassMonth?.let { binding.nextHourglassTextview.text = it } } binding.changeSubscriptionButton.visibility = View.VISIBLE if (plan.paymentMethod != null) { binding.changeSubscriptionTitle.setText(R.string.cancel_subscription) if (plan.paymentMethod == "Google") { binding.changeSubscriptionDescription.setText(R.string.cancel_subscription_google_description) binding.changeSubscriptionButton.setText(R.string.open_in_store) } else { if (plan.isGroupPlanSub) { /*if (plan.ownerID == currentUserID) { binding.changeSubscriptionDescription.setText(R.string.cancel_subscription_group_plan_owner) } else {*/ binding.changeSubscriptionDescription.setText(R.string.cancel_subscription_group_plan) binding.changeSubscriptionButton.visibility = View.GONE // } } else { binding.changeSubscriptionDescription.setText(R.string.cancel_subscription_notgoogle_description) } binding.changeSubscriptionButton.setText(R.string.visit_habitica_website) } } if (plan.dateTerminated != null) { binding.changeSubscriptionTitle.setText(R.string.resubscribe) binding.changeSubscriptionDescription.setText(R.string.resubscribe_description) binding.changeSubscriptionButton.setText(R.string.renew_subscription) } } private fun updateSubscriptionStatusPill(plan: SubscriptionPlan) { if (plan.isActive) { if (plan.dateTerminated != null) { if (plan.isGiftedSub) { binding.subscriptionStatusNotRecurring.visibility = View.VISIBLE binding.subscriptionStatusCancelled.visibility = View.GONE } else { binding.subscriptionStatusNotRecurring.visibility = View.GONE binding.subscriptionStatusCancelled.visibility = View.VISIBLE } binding.subscriptionStatusActive.visibility = View.GONE binding.subscriptionStatusGroupPlan.visibility = View.GONE } else { if (plan.isGroupPlanSub) { binding.subscriptionStatusGroupPlan.visibility = View.VISIBLE binding.subscriptionStatusActive.visibility = View.GONE binding.subscriptionStatusNotRecurring.visibility = View.GONE } else { binding.subscriptionStatusActive.visibility = View.VISIBLE binding.subscriptionStatusNotRecurring.visibility = View.GONE binding.subscriptionStatusGroupPlan.visibility = View.GONE } } binding.subscriptionStatusInactive.visibility = View.GONE } else { binding.subscriptionStatusActive.visibility = View.GONE binding.subscriptionStatusInactive.visibility = View.VISIBLE binding.subscriptionStatusNotRecurring.visibility = View.GONE binding.subscriptionStatusGroupPlan.visibility = View.GONE } } private fun changeSubscriptionButtonTapped() { if (plan?.paymentMethod != null && plan?.dateTerminated == null) { val url = if (plan?.paymentMethod == "Google") { "https://play.google.com/store/account/subscriptions" } else { context.getString(R.string.base_url) + "/" } context.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(url))) } else if (plan?.dateTerminated != null) { onShowSubscriptionOptions?.invoke() } } }
gpl-3.0
bf4013a369d2cd0d476903f6633ae4f7
47.511111
194
0.646095
4.942873
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/cache/code_preference/CodePreferenceCacheDataSourceImpl.kt
2
1155
package org.stepik.android.cache.code_preference import io.reactivex.Completable import io.reactivex.Single import org.stepik.android.cache.code_preference.dao.CodePreferenceDao import org.stepik.android.cache.code_preference.model.CodePreference import org.stepik.android.data.code_preference.source.CodePreferenceCacheDataSource import javax.inject.Inject class CodePreferenceCacheDataSourceImpl @Inject constructor( private val codePreferenceDao: CodePreferenceDao ) : CodePreferenceCacheDataSource { companion object { private const val PREFIX = "[" private const val POSTFIX = "]" private const val SEPARATOR = "__,__" } override fun getCodePreference(languagesKey: Set<String>): Single<CodePreference> = codePreferenceDao.getCodePreferences(mapLanguagesKeyToString(languagesKey)) override fun saveCodePreference(codePreference: CodePreference): Completable = codePreferenceDao.saveCodePreference(codePreference) private fun mapLanguagesKeyToString(languagesKey: Set<String>): String = languagesKey.joinToString(separator = SEPARATOR, transform = { "$PREFIX$it$POSTFIX" }) }
apache-2.0
3f7116c8e1829bab0d78552fddae1c3f
40.285714
94
0.782684
4.8125
false
false
false
false
Cognifide/APM
app/aem/core/src/main/kotlin/com/cognifide/apm/core/grammar/ScriptExecutionException.kt
1
943
/* * ========================LICENSE_START================================= * AEM Permission Management * %% * Copyright (C) 2013 Wunderman Thompson Technology * %% * 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. * =========================LICENSE_END================================== */ package com.cognifide.apm.core.grammar class ScriptExecutionException(message: String) : RuntimeException(message)
apache-2.0
47b8b4894d57112e2a156f8a2dba2c67
39.086957
75
0.636267
4.835897
false
false
false
false
CarlosEsco/tachiyomi
app/src/main/java/eu/kanade/tachiyomi/data/track/model/TrackSearch.kt
1
1547
package eu.kanade.tachiyomi.data.track.model import eu.kanade.tachiyomi.data.database.models.Track class TrackSearch : Track { override var id: Long? = null override var manga_id: Long = 0 override var sync_id: Int = 0 override var media_id: Long = 0 override var library_id: Long? = null override lateinit var title: String override var last_chapter_read: Float = 0F override var total_chapters: Int = 0 override var score: Float = 0f override var status: Int = 0 override var started_reading_date: Long = 0 override var finished_reading_date: Long = 0 override lateinit var tracking_url: String var cover_url: String = "" var summary: String = "" var publishing_status: String = "" var publishing_type: String = "" var start_date: String = "" override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as TrackSearch if (manga_id != other.manga_id) return false if (sync_id != other.sync_id) return false if (media_id != other.media_id) return false return true } override fun hashCode(): Int { var result = manga_id.hashCode() result = 31 * result + sync_id result = 31 * result + media_id.hashCode() return result } companion object { fun create(serviceId: Long): TrackSearch = TrackSearch().apply { sync_id = serviceId.toInt() } } }
apache-2.0
f98b4e0bcfb17b9027e6c45a2b7328f6
21.75
72
0.621849
4.114362
false
false
false
false
itsmortoncornelius/example-wifi-direct
app/src/main/java/de/handler/mobile/wifivideo/WifiP2pConnectionManager.kt
1
4424
package de.handler.mobile.wifivideo import android.os.AsyncTask import android.util.Log import java.io.DataInputStream import java.io.DataOutputStream import java.io.IOException import java.io.InputStream import java.lang.ref.WeakReference import java.net.InetAddress import java.net.InetSocketAddress import java.net.ServerSocket import java.net.Socket class WifiP2pConnectionManager(private val listener: OnDataListener) { private var receiveDataTask: AsyncTask<Void, Void, Int?>? = null private var serverSocket: Socket? = null // send date to this socket private var clientSocket: Socket? = null // receive messages with this input stream private var inputStream: InputStream? = null interface OnDataListener { fun onServerBound(success: Boolean) fun onClientBound(success: Boolean) fun onDataSend(data: Int, success: Boolean) fun onDataReceived(data: Int) } fun bindServer(inetAddress: InetAddress?) { inetAddress?.let { BindServerTask(WeakReference(this), it).execute() } } fun sendData(message: Int) { SendDataTask(WeakReference(this)).execute(message) } fun bindClient() { BindClientTask(WeakReference(this)).execute() } fun receiveData(stop: Boolean = false) { if (receiveDataTask == null) { receiveDataTask = ReceiveDataTask(WeakReference(this)).execute() } else if (stop) { receiveDataTask!!.cancel(true) receiveDataTask = null } } class BindServerTask(private val manager: WeakReference<WifiP2pConnectionManager>, private val inetAddress: InetAddress) : AsyncTask<Void, Void, Boolean?>() { override fun doInBackground(vararg p0: Void): Boolean? { try { if (manager.get()?.serverSocket != null && manager.get()?.serverSocket!!.isBound) { return null } val socketAddress = InetSocketAddress(inetAddress, 8888) val socket = Socket() socket.bind(null) manager.get()?.serverSocket = socket manager.get()?.serverSocket!!.connect(socketAddress, 500) return true } catch (e: IOException) { Log.e("TAG_BIND_SERVER", e.message) return false } } override fun onPostExecute(result: Boolean?) { if (result != null) { manager.get()?.listener?.onServerBound(result) } } } class BindClientTask(private val manager: WeakReference<WifiP2pConnectionManager>) : AsyncTask<Void, Void, Boolean>() { override fun doInBackground(vararg p0: Void): Boolean { try { val serverSocket = ServerSocket(8888) manager.get()?.clientSocket = serverSocket.accept() // receive messages and log manager.get()?.inputStream = manager.get()?.clientSocket?.getInputStream() return true } catch (e: IOException) { Log.e("TAG_RECEIVE_DATA", e.message) return false } } override fun onPostExecute(result: Boolean) { manager.get()?.listener?.onClientBound(result) } } class SendDataTask(private val manager: WeakReference<WifiP2pConnectionManager>) : AsyncTask<Int, Void, Boolean>() { private var message: Int? = null override fun doInBackground(vararg p0: Int?): Boolean { if (p0[0] == null) { return false } else { message = p0[0] } try { val serverSocket = manager.get()?.serverSocket if (serverSocket == null || !serverSocket.isConnected) { return false } val outputStream = serverSocket.getOutputStream() ?: return false val dataOutputStream = DataOutputStream(outputStream) p0[0]?.let { dataOutputStream.writeInt(it) } return true } catch (e: IOException) { Log.e("TAG_SEND_DATA", e.message) return false } } override fun onPostExecute(result: Boolean?) { manager.get()?.listener?.onDataSend(message ?: 0, result ?: false) } } class ReceiveDataTask(private val manager: WeakReference<WifiP2pConnectionManager>) : AsyncTask<Void, Void, Int?>() { override fun doInBackground(vararg p0: Void): Int? { if (manager.get()?.inputStream != null) { val dataInputStream = DataInputStream(manager.get()?.inputStream) return dataInputStream.readInt() } return null } override fun onPostExecute(result: Int?) { if (result != null) { manager.get()?.listener?.onDataReceived(result) Log.d("TAG_RECEIVE_DATA", result.toString()) val wifiP2pConnectionManager = manager.get() ?: return wifiP2pConnectionManager.receiveDataTask = ReceiveDataTask(WeakReference(wifiP2pConnectionManager)) wifiP2pConnectionManager.receiveDataTask!!.execute() } } } }
apache-2.0
4e0d75973c8657c075278ef0766f37f0
29.102041
159
0.713608
3.659222
false
false
false
false
exponentjs/exponent
android/versioned-abis/expoview-abi44_0_0/src/main/java/abi44_0_0/expo/modules/notifications/service/delegates/SharedPreferencesNotificationsStore.kt
2
4464
package abi44_0_0.expo.modules.notifications.service.delegates import android.content.Context import android.content.SharedPreferences import expo.modules.notifications.notifications.model.NotificationRequest import java.io.IOException /** * A fairly straightforward [SharedPreferences] wrapper to be used by [NotificationSchedulingHelper]. * Saves and reads notifications (identifiers, requests and triggers) to and from the persistent storage. * * A notification request of identifier = 123abc, it will be persisted under key: * [SharedPreferencesNotificationsStore.NOTIFICATION_REQUEST_KEY_PREFIX]123abc */ class SharedPreferencesNotificationsStore(context: Context) { companion object { private const val SHARED_PREFERENCES_NAME = "expo.modules.notifications.SharedPreferencesNotificationsStore" private const val NOTIFICATION_REQUEST_KEY_PREFIX = "notification_request-" } private val sharedPreferences: SharedPreferences = context.getSharedPreferences(SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) /** * Fetches scheduled notification info for given identifier. * * @param identifier Identifier of the notification. * @return Notification information: request and trigger. * @throws JSONException Thrown if notification request could not have been interpreted as a JSON object. * @throws IOException Thrown if there is an error when fetching trigger from the storage. * @throws ClassNotFoundException Thrown if there is an error when interpreting trigger fetched from the storage. */ @Throws(IOException::class, ClassNotFoundException::class) fun getNotificationRequest(identifier: String) = sharedPreferences.getString( preferencesNotificationRequestKey(identifier), null )?.asBase64EncodedObject<NotificationRequest>() /** * Fetches all scheduled notifications, ignoring invalid ones. * * Goes through all the [SharedPreferences] entries, interpreting only the ones conforming * to the expected format. * * @return Map with identifiers as keys and notification info as values */ val allNotificationRequests: Collection<NotificationRequest> get() = sharedPreferences .all .filter { it.key.startsWith(NOTIFICATION_REQUEST_KEY_PREFIX) } .mapNotNull { (_, value) -> return@mapNotNull try { (value as String?)?.asBase64EncodedObject<NotificationRequest>() } catch (e: ClassNotFoundException) { // do nothing null } catch (e: IOException) { // do nothing null } } /** * Saves given notification in the persistent storage. * * @param notificationRequest Notification request * @throws IOException Thrown if there is an error while serializing trigger */ @Throws(IOException::class) fun saveNotificationRequest(notificationRequest: NotificationRequest) = sharedPreferences.edit() .putString( preferencesNotificationRequestKey(notificationRequest.identifier), notificationRequest.encodedInBase64() ) .apply() /** * Removes notification info for given identifier. * * @param identifier Notification identifier */ fun removeNotificationRequest(identifier: String) = removeNotificationRequest(sharedPreferences.edit(), identifier).apply() /** * Perform notification removal on provided [SharedPreferences.Editor] instance. Can be reused * to batch deletion. * * @param editor Editor to apply changes onto * @param identifier Notification identifier * @return Returns a reference to the same Editor object, so you can * chain put calls together. */ private fun removeNotificationRequest(editor: SharedPreferences.Editor, identifier: String) = editor.remove(preferencesNotificationRequestKey(identifier)) /** * Removes all notification infos, returning removed IDs. */ fun removeAllNotificationRequests(): Collection<String> = with(sharedPreferences.edit()) { allNotificationRequests.map { removeNotificationRequest(this, it.identifier) it.identifier }.let { this.apply() it } } /** * @param identifier Notification identifier * @return Key under which notification request will be persisted in the storage. */ private fun preferencesNotificationRequestKey(identifier: String) = NOTIFICATION_REQUEST_KEY_PREFIX + identifier }
bsd-3-clause
a208fd6838f521555ac06a5a5787e354
36.512605
128
0.729615
5.227166
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceNotNullAssertionWithElvisReturnInspection.kt
1
4365
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.inspections import com.intellij.codeInsight.intention.LowPriorityAction import com.intellij.codeInspection.LocalQuickFix import com.intellij.codeInspection.ProblemDescriptor import com.intellij.codeInspection.ProblemHighlightType import com.intellij.codeInspection.ProblemsHolder import com.intellij.openapi.project.Project import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.diagnostics.Errors import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.base.psi.replaced import org.jetbrains.kotlin.idea.intentions.getParentLambdaLabelName import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getParentOfTypes import org.jetbrains.kotlin.psi.psiUtil.getTopmostParentOfType import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode import org.jetbrains.kotlin.types.isNullable import org.jetbrains.kotlin.types.typeUtil.isUnit class ReplaceNotNullAssertionWithElvisReturnInspection : AbstractKotlinInspection() { override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = postfixExpressionVisitor(fun(postfix) { if (postfix.baseExpression == null) return val operationReference = postfix.operationReference if (operationReference.getReferencedNameElementType() != KtTokens.EXCLEXCL) return if ((postfix.getTopmostParentOfType<KtParenthesizedExpression>() ?: postfix).parent is KtReturnExpression) return val parent = postfix.getParentOfTypes(true, KtLambdaExpression::class.java, KtNamedFunction::class.java) if (parent !is KtNamedFunction && parent !is KtLambdaExpression) return val context = postfix.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS) val (isNullable, returnLabelName) = when (parent) { is KtNamedFunction -> { val returnType = parent.descriptor(context)?.returnType ?: return val isNullable = returnType.isNullable() if (!returnType.isUnit() && !isNullable) return isNullable to null } is KtLambdaExpression -> { val functionLiteral = parent.functionLiteral val returnType = functionLiteral.descriptor(context)?.returnType ?: return if (!returnType.isUnit()) return val lambdaLabelName = functionLiteral.bodyBlockExpression?.getParentLambdaLabelName() ?: return false to lambdaLabelName } else -> return } if (context.diagnostics.forElement(operationReference).any { it.factory == Errors.UNNECESSARY_NOT_NULL_ASSERTION }) return holder.registerProblem( postfix.operationReference, KotlinBundle.message("replace.with.return"), ProblemHighlightType.GENERIC_ERROR_OR_WARNING, ReplaceWithElvisReturnFix(isNullable, returnLabelName) ) }) private fun KtFunction.descriptor(context: BindingContext): FunctionDescriptor? { return context[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? FunctionDescriptor } private class ReplaceWithElvisReturnFix( private val returnNull: Boolean, private val returnLabelName: String? ) : LocalQuickFix, LowPriorityAction { override fun getName() = KotlinBundle.message("replace.with.elvis.return.fix.text", if (returnNull) " null" else "") override fun getFamilyName() = name override fun applyFix(project: Project, descriptor: ProblemDescriptor) { val postfix = descriptor.psiElement.parent as? KtPostfixExpression ?: return val base = postfix.baseExpression ?: return val psiFactory = KtPsiFactory(postfix) postfix.replaced( psiFactory.createExpressionByPattern( "$0 ?: return$1$2", base, returnLabelName?.let { "@$it" } ?: "", if (returnNull) " null" else "" ) ) } } }
apache-2.0
80e6cafb4fa59b294a911408e09f03a1
48.613636
158
0.708133
5.408922
false
false
false
false
Jumpaku/JumpakuOthello
api/src/main/kotlin/jumpaku/othello/api/Modules.kt
1
3836
package jumpaku.othello.api import com.github.salomonbrys.kotson.get import com.github.salomonbrys.kotson.string import io.ktor.application.Application import io.ktor.application.ApplicationCall import io.ktor.application.call import io.ktor.http.ContentType import io.ktor.http.HttpStatusCode import io.ktor.http.content.* import io.ktor.request.receiveText import io.ktor.response.respondRedirect import io.ktor.response.respondText import io.ktor.routing.get import io.ktor.routing.post import io.ktor.routing.route import io.ktor.routing.routing import jumpaku.commons.control.Failure import jumpaku.commons.control.Success import jumpaku.commons.json.parseJson fun Application.apiModules() = routing { get("/") { call.respondText(ContentType.Text.Plain, HttpStatusCode.OK) { "Jumpaku Othello\n" } } route("/v1/") { get("/") { call.respondRedirect("/v1/api/") } get("/api") { call.respondText(ContentType.Text.Plain, HttpStatusCode.OK) { "Jumpaku Othello API v1\n" } } post("/ai/move/") { call.selectMoveByAi() } post("/ai/moves/") { call.evaluateMovesByAi() } post("/games/") { when (call.request.queryParameters["action"]) { "make" -> call.makeNewGame() "get" -> call.getGameState() "move" -> call.selectMove() else -> call.respondBadRequestQueryParameter("action") } } } } private suspend fun ApplicationCall.selectMoveByAi() { when( val result = receiveText().parseJson() .tryFlatMap { selectorInput(it) } .tryFlatMap { input -> selectMoveByAi(input) }) { is Success -> respondText(ContentType.Application.Json, HttpStatusCode.OK) { result.value.toJson().toString() } is Failure -> respondBadRequest(result.error.message ?: "") } } private suspend fun ApplicationCall.evaluateMovesByAi() { println("OK") when( val result = receiveText().parseJson() .tryFlatMap { selectorInput(it) } .tryFlatMap { input -> evaluateMovesByAi(input) }) { is Success -> respondText(ContentType.Application.Json, HttpStatusCode.OK) { result.value.toJson().toString() } is Failure -> respondBadRequest(result.error.message ?: "") } } private suspend fun ApplicationCall.makeNewGame() { respondText(ContentType.Application.Json, HttpStatusCode.OK) { GameDatabase.make().toJson().toString() } } private suspend fun ApplicationCall.getGameState() { when ( val result = receiveText().parseJson() .tryMap { it["gameId"].string } .tryFlatMap { gameId -> GameDatabase[gameId] }) { is Success -> respondText(ContentType.Application.Json, HttpStatusCode.OK) { result.value.toJson().toString() } is Failure -> respondNotFound(result.error.message ?: "") } } private suspend fun ApplicationCall.selectMove() { when ( val result = receiveText().parseJson() .tryFlatMap { json -> updateData(json) } .tryFlatMap { (gameId, move) -> GameDatabase.update(gameId, move) }) { is Success -> respondText(ContentType.Application.Json, HttpStatusCode.OK) { result.value.toJson().toString() } is Failure -> respondNotFound(result.error.message ?: "") } } private suspend fun ApplicationCall.respondBadRequest(message: String) { respondText(ContentType.Application.Json, HttpStatusCode.BadRequest) { "{ \"message\": \"$message\" }" } } private suspend fun ApplicationCall.respondBadRequestQueryParameter(name: String) { respondBadRequest("invalid query parameter $name") } private suspend fun ApplicationCall.respondNotFound(message: String) { respondText(ContentType.Application.Json, HttpStatusCode.NotFound) { "{ \"message\": \"$message\" }" } }
bsd-2-clause
e5fd6d6b372a65733fee6492161e9e9d
37.37
119
0.674922
4.183206
false
false
false
false
ThoseGrapefruits/intellij-rust
src/main/kotlin/org/rust/cargo/util/Platform.kt
1
1318
package org.rust.cargo.util import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.process.CapturingProcessHandler import com.intellij.execution.process.ProcessListener import com.intellij.execution.process.ProcessOutput import com.intellij.openapi.util.SystemInfo object Platform { /** * Adjusts filename to become canonical executable one (adding 'exe' extension on Windows, for example) */ fun getCanonicalNativeExecutableName(fileName: String): String { return if (SystemInfo.isWindows) "$fileName.exe" else fileName } /** * Runs cargo-executable specified with the given path, supplying it with given parameters * and attaching to the running process the listener supplied * * @return process 'output' object (containing `stderr`/`stdout` streams, exit-code, etc.) */ fun runExecutableWith(cargoPath: String, params: List<String>, listener: ProcessListener? = null): ProcessOutput { val cmd = GeneralCommandLine() cmd.exePath = cargoPath cmd.addParameters(*params.toTypedArray()) val process = cmd.createProcess() val handler = CapturingProcessHandler(process) listener?.let { handler.addProcessListener(it) } return handler.runProcess() } }
mit
860ae25c534523bfcfc883eb7e430e1c
33.684211
118
0.723824
4.845588
false
false
false
false
DiUS/pact-jvm
provider/junit/src/main/kotlin/au/com/dius/pact/provider/junit/RunStateChanges.kt
1
2606
package au.com.dius.pact.provider.junit import au.com.dius.pact.core.model.ProviderState import au.com.dius.pact.provider.IProviderVerifier import au.com.dius.pact.provider.junitsupport.State import au.com.dius.pact.provider.junitsupport.StateChangeAction import mu.KLogging import org.junit.runners.model.FrameworkMethod import org.junit.runners.model.Statement import java.util.function.Supplier import kotlin.reflect.full.isSubclassOf data class StateChangeCallbackFailed( override val message: String, override val cause: Throwable ) : Exception(message, cause) class RunStateChanges( private val next: Statement, private val methods: List<Pair<FrameworkMethod, State>>, private val stateChangeHandlers: List<Supplier<out Any>>, private val providerState: ProviderState, private val testContext: MutableMap<String, Any>, private val verifier: IProviderVerifier ) : Statement() { override fun evaluate() { invokeStateChangeMethods(StateChangeAction.SETUP) try { next.evaluate() } finally { invokeStateChangeMethods(StateChangeAction.TEARDOWN) } } private fun invokeStateChangeMethods(action: StateChangeAction) { for (method in methods) { if (method.second.action == action) { logger.info { val name = method.second.value.joinToString(", ") if (method.second.comment.isNotEmpty()) { "Invoking state change method '$name':${method.second.action} (${method.second.comment})" } else { "Invoking state change method '$name':${method.second.action}" } } val target = stateChangeHandlers.map(Supplier<out Any>::get).find { it::class.isSubclassOf(method.first.declaringClass.kotlin) } val stateChangeValue = try { if (method.first.method.parameterCount == 1) { method.first.invokeExplosively(target, providerState.params) } else { method.first.invokeExplosively(target) } } catch (e: Throwable) { logger.error(e) { "State change method for \"${providerState.name}\" failed" } val callbackFailed = StateChangeCallbackFailed("State change method for \"${providerState.name}\" failed", e) verifier.reportStateChangeFailed(providerState, callbackFailed, action == StateChangeAction.SETUP) verifier.finaliseReports() throw callbackFailed } if (stateChangeValue is Map<*, *>) { testContext.putAll(stateChangeValue as Map<String, Any>) } } } } companion object : KLogging() }
apache-2.0
09629e8ac0b3f4c3f899f746756d1f48
35.194444
119
0.68726
4.336106
false
false
false
false
KotlinNLP/SimpleDNN
src/main/kotlin/com/kotlinnlp/simplednn/core/layers/StackedLayersParameters.kt
1
4531
/* Copyright 2016-present The KotlinNLP Authors. All Rights Reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, you can obtain one at http://mozilla.org/MPL/2.0/. * ------------------------------------------------------------------*/ package com.kotlinnlp.simplednn.core.layers import com.kotlinnlp.simplednn.core.functionalities.initializers.GlorotInitializer import com.kotlinnlp.simplednn.core.functionalities.initializers.Initializer import com.kotlinnlp.utils.Serializer import java.io.InputStream import java.io.OutputStream import java.io.Serializable /** * [StackedLayersParameters] contains all the parameters of the layers defined in [layersConfiguration], * grouped per layer. * * @property layersConfiguration a list of configurations, one per layer * @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot) * @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot) */ class StackedLayersParameters( val layersConfiguration: List<LayerInterface>, weightsInitializer: Initializer? = GlorotInitializer(), biasesInitializer: Initializer? = GlorotInitializer() ) : Serializable { companion object { /** * Private val used to serialize the class (needed by Serializable). */ @Suppress("unused") private const val serialVersionUID: Long = 1L /** * Read a [StackedLayersParameters] (serialized) from an input stream and decode it. * * @param inputStream the [InputStream] from which to read the serialized [StackedLayersParameters] * * @return the [StackedLayersParameters] read from [inputStream] and decoded */ fun load(inputStream: InputStream): StackedLayersParameters = Serializer.deserialize(inputStream) } /** * Secondary constructor. * * @param layersConfiguration a list of configurations, one per layer * @param weightsInitializer the initializer of the weights (zeros if null, default: Glorot) * @param biasesInitializer the initializer of the biases (zeros if null, default: Glorot) * * @return a new NeuralNetwork */ constructor( vararg layersConfiguration: LayerInterface, weightsInitializer: Initializer? = GlorotInitializer(), biasesInitializer: Initializer? = GlorotInitializer() ): this( layersConfiguration = layersConfiguration.toList(), weightsInitializer = weightsInitializer, biasesInitializer = biasesInitializer ) /** * The type of the input array. */ val inputType: LayerType.Input = this.layersConfiguration.first().type /** * Whether the input array is sparse binary. */ val sparseInput: Boolean = this.inputType == LayerType.Input.SparseBinary /** * The size of the input, meaningful when the first layer is not a Merge layer. */ val inputSize: Int = this.layersConfiguration.first().size /** * The size of the inputs, meaningful when the first layer is a Merge layer. */ val inputsSize: List<Int> = this.layersConfiguration.first().sizes /** * The output size. */ val outputSize: Int = this.layersConfiguration.last().size /** * The [LayerParameters] of each layer. */ val paramsPerLayer: List<LayerParameters> = List(this.layersConfiguration.size - 1) { i -> LayerParametersFactory( inputsSize = this.layersConfiguration[i].sizes, outputSize = this.layersConfiguration[i + 1].size, connectionType = this.layersConfiguration[i + 1].connectionType!!, weightsInitializer = weightsInitializer, biasesInitializer = biasesInitializer, sparseInput = this.layersConfiguration[i].type == LayerType.Input.SparseBinary) } /** * The number of stacked layers. */ val numOfLayers: Int = this.paramsPerLayer.size /** * Serialize this [StackedLayersParameters] and write it to an output stream. * * @param outputStream the [OutputStream] in which to write this serialized [StackedLayersParameters] */ fun dump(outputStream: OutputStream) = Serializer.serialize(this, outputStream) /** * @param index a stacked-layer index * * @return the parameters of the given layer, casted to the given type */ inline fun <reified T : LayerParameters>getLayerParams(index: Int): T { require(index >= 0 && index < this.numOfLayers) { "Layer index ($index) out of range ([0, ${numOfLayers - 1}])." } return this.paramsPerLayer[index] as T } }
mpl-2.0
57464c7ebb5da4c2897728c8a7567958
34.124031
118
0.712205
4.614053
false
true
false
false
mdaniel/intellij-community
plugins/kotlin/base/scripting/src/org/jetbrains/kotlin/idea/script/configuration/ScriptingSupportCheckerProvider.kt
2
1336
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.script.configuration import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.vfs.VirtualFile import org.jetbrains.annotations.Nls abstract class ScriptingSupportCheckerProvider { @get:Nls abstract val title: String open fun isSupportedScriptExtension(virtualFile: VirtualFile): Boolean = false abstract fun isSupportedUnderSourceRoot(virtualFile: VirtualFile): Boolean companion object { @JvmField val CHECKER_PROVIDERS: ExtensionPointName<ScriptingSupportCheckerProvider> = ExtensionPointName.create("org.jetbrains.kotlin.scripting.support.checker.provider") } } abstract class SupportedScriptScriptingSupportCheckerProvider(private val suffix: String, private val supportedUnderSourceRoot: Boolean = false) : ScriptingSupportCheckerProvider() { override val title: String = "$suffix script" override fun isSupportedScriptExtension(virtualFile: VirtualFile): Boolean = virtualFile.name.endsWith(suffix) override fun isSupportedUnderSourceRoot(virtualFile: VirtualFile): Boolean = if (supportedUnderSourceRoot) isSupportedScriptExtension(virtualFile) else false }
apache-2.0
19d839fb4697316b3444cadd84556bb8
42.129032
182
0.791168
5.178295
false
false
false
false
AsamK/TextSecure
app/src/main/java/org/thoughtcrime/securesms/keyboard/sticker/KeyboardStickerPackListAdapter.kt
2
2627
package org.thoughtcrime.securesms.keyboard.sticker import android.content.res.ColorStateList import android.view.View import android.widget.ImageView import androidx.core.widget.ImageViewCompat import org.thoughtcrime.securesms.R import org.thoughtcrime.securesms.glide.cache.ApngOptions import org.thoughtcrime.securesms.mms.DecryptableStreamUriLoader.DecryptableUri import org.thoughtcrime.securesms.mms.GlideRequests import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder class KeyboardStickerPackListAdapter(private val glideRequests: GlideRequests, private val allowApngAnimation: Boolean, private val onTabSelected: (StickerPack) -> Unit) : MappingAdapter() { init { registerFactory(StickerPack::class.java, LayoutFactory(::StickerPackViewHolder, R.layout.keyboard_pager_category_icon)) } data class StickerPack(val packRecord: StickerKeyboardRepository.KeyboardStickerPack, val selected: Boolean = false) : MappingModel<StickerPack> { val loadImage: Boolean = packRecord.coverResource == null val uri: DecryptableUri? = packRecord.coverUri?.let { DecryptableUri(packRecord.coverUri) } val iconResource: Int = packRecord.coverResource ?: 0 override fun areItemsTheSame(newItem: StickerPack): Boolean { return packRecord.packId == newItem.packRecord.packId } override fun areContentsTheSame(newItem: StickerPack): Boolean { return areItemsTheSame(newItem) && selected == newItem.selected } } private inner class StickerPackViewHolder(itemView: View) : MappingViewHolder<StickerPack>(itemView) { private val selected: View = findViewById(R.id.category_icon_selected) private val icon: ImageView = findViewById(R.id.category_icon) private val defaultTint: ColorStateList? = ImageViewCompat.getImageTintList(icon) override fun bind(model: StickerPack) { itemView.setOnClickListener { onTabSelected(model) } selected.isSelected = model.selected if (model.loadImage) { ImageViewCompat.setImageTintList(icon, null) icon.alpha = if (model.selected) 1f else 0.5f glideRequests.load(model.uri) .set(ApngOptions.ANIMATE, allowApngAnimation) .into(icon) } else { ImageViewCompat.setImageTintList(icon, defaultTint) icon.setImageResource(model.iconResource) icon.alpha = 1f icon.isSelected = model.selected } } } }
gpl-3.0
bf02241976321a303367cda76022aee1
42.065574
190
0.769699
4.513746
false
false
false
false
yongce/AndroidLib
baseLib/src/main/java/me/ycdev/android/lib/common/utils/EncodingUtils.kt
1
2273
package me.ycdev.android.lib.common.utils object EncodingUtils { private val HEX_ARRAY_UPPERCASE = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F') private val HEX_ARRAY_LOWERCASE = charArrayOf('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f') /** * Encode the data with HEX (Base16) encoding */ fun encodeWithHex(bytes: ByteArray?, uppercase: Boolean = true): String { return if (bytes == null) { "null" } else encodeWithHex(bytes, 0, bytes.size, uppercase) } /** * Encode the data with HEX (Base16) encoding */ fun encodeWithHex( bytes: ByteArray, startPos: Int, endPos: Int, uppercase: Boolean = true ): String { var endPosTmp = endPos if (endPosTmp > bytes.size) { endPosTmp = bytes.size } val size = endPosTmp - startPos val charsArray = if (uppercase) HEX_ARRAY_UPPERCASE else HEX_ARRAY_LOWERCASE val hexChars = CharArray(size * 2) var i = startPos var j = 0 while (i < endPosTmp) { val v = bytes[i].toInt() and 0xFF hexChars[j] = charsArray[v.ushr(4)] hexChars[j + 1] = charsArray[v and 0x0F] i++ j += 2 } return String(hexChars) } fun fromHexString(hexStr: String): ByteArray { val hexStrTmp = hexStr.replace(" ", "") // support spaces if (hexStrTmp.length % 2 != 0) { throw IllegalArgumentException("Bad length: $hexStrTmp") } val result = ByteArray(hexStrTmp.length / 2) for (i in result.indices) { val high = fromHexChar(hexStrTmp, i * 2) shl 4 val low = fromHexChar(hexStrTmp, i * 2 + 1) result[i] = (high or low and 0xFF).toByte() } return result } private fun fromHexChar(hexStr: String, index: Int): Int { return when (val ch = hexStr[index]) { in '0'..'9' -> ch - '0' in 'a'..'f' -> 10 + (ch - 'a') in 'A'..'F' -> 10 + (ch - 'A') else -> throw IllegalArgumentException("Not hex string: $hexStr") } } }
apache-2.0
81666880987400268bebbcfb38d8f8d5
31.942029
99
0.512099
3.585174
false
false
false
false
Philip-Trettner/GlmKt
GlmKt/src/glm/vec/Byte/ByteVec3.kt
1
25096
package glm data class ByteVec3(val x: Byte, val y: Byte, val z: Byte) { // Initializes each element by evaluating init from 0 until 2 constructor(init: (Int) -> Byte) : this(init(0), init(1), init(2)) operator fun get(idx: Int): Byte = when (idx) { 0 -> x 1 -> y 2 -> z else -> throw IndexOutOfBoundsException("index $idx is out of bounds") } // Operators operator fun inc(): ByteVec3 = ByteVec3(x.inc(), y.inc(), z.inc()) operator fun dec(): ByteVec3 = ByteVec3(x.dec(), y.dec(), z.dec()) operator fun unaryPlus(): IntVec3 = IntVec3(+x, +y, +z) operator fun unaryMinus(): IntVec3 = IntVec3(-x, -y, -z) operator fun plus(rhs: ByteVec3): IntVec3 = IntVec3(x + rhs.x, y + rhs.y, z + rhs.z) operator fun minus(rhs: ByteVec3): IntVec3 = IntVec3(x - rhs.x, y - rhs.y, z - rhs.z) operator fun times(rhs: ByteVec3): IntVec3 = IntVec3(x * rhs.x, y * rhs.y, z * rhs.z) operator fun div(rhs: ByteVec3): IntVec3 = IntVec3(x / rhs.x, y / rhs.y, z / rhs.z) operator fun rem(rhs: ByteVec3): IntVec3 = IntVec3(x % rhs.x, y % rhs.y, z % rhs.z) operator fun plus(rhs: Byte): IntVec3 = IntVec3(x + rhs, y + rhs, z + rhs) operator fun minus(rhs: Byte): IntVec3 = IntVec3(x - rhs, y - rhs, z - rhs) operator fun times(rhs: Byte): IntVec3 = IntVec3(x * rhs, y * rhs, z * rhs) operator fun div(rhs: Byte): IntVec3 = IntVec3(x / rhs, y / rhs, z / rhs) operator fun rem(rhs: Byte): IntVec3 = IntVec3(x % rhs, y % rhs, z % rhs) inline fun map(func: (Byte) -> Byte): ByteVec3 = ByteVec3(func(x), func(y), func(z)) fun toList(): List<Byte> = listOf(x, y, z) // Predefined vector constants companion object Constants { val zero: ByteVec3 = ByteVec3(0.toByte(), 0.toByte(), 0.toByte()) val ones: ByteVec3 = ByteVec3(1.toByte(), 1.toByte(), 1.toByte()) val unitX: ByteVec3 = ByteVec3(1.toByte(), 0.toByte(), 0.toByte()) val unitY: ByteVec3 = ByteVec3(0.toByte(), 1.toByte(), 0.toByte()) val unitZ: ByteVec3 = ByteVec3(0.toByte(), 0.toByte(), 1.toByte()) } // Conversions to Float fun toVec(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toVec(conv: (Byte) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec2(): Vec2 = Vec2(x.toFloat(), y.toFloat()) inline fun toVec2(conv: (Byte) -> Float): Vec2 = Vec2(conv(x), conv(y)) fun toVec3(): Vec3 = Vec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toVec3(conv: (Byte) -> Float): Vec3 = Vec3(conv(x), conv(y), conv(z)) fun toVec4(w: Float = 0f): Vec4 = Vec4(x.toFloat(), y.toFloat(), z.toFloat(), w) inline fun toVec4(w: Float = 0f, conv: (Byte) -> Float): Vec4 = Vec4(conv(x), conv(y), conv(z), w) // Conversions to Float fun toMutableVec(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toMutableVec(conv: (Byte) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec2(): MutableVec2 = MutableVec2(x.toFloat(), y.toFloat()) inline fun toMutableVec2(conv: (Byte) -> Float): MutableVec2 = MutableVec2(conv(x), conv(y)) fun toMutableVec3(): MutableVec3 = MutableVec3(x.toFloat(), y.toFloat(), z.toFloat()) inline fun toMutableVec3(conv: (Byte) -> Float): MutableVec3 = MutableVec3(conv(x), conv(y), conv(z)) fun toMutableVec4(w: Float = 0f): MutableVec4 = MutableVec4(x.toFloat(), y.toFloat(), z.toFloat(), w) inline fun toMutableVec4(w: Float = 0f, conv: (Byte) -> Float): MutableVec4 = MutableVec4(conv(x), conv(y), conv(z), w) // Conversions to Double fun toDoubleVec(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toDoubleVec(conv: (Byte) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec2(): DoubleVec2 = DoubleVec2(x.toDouble(), y.toDouble()) inline fun toDoubleVec2(conv: (Byte) -> Double): DoubleVec2 = DoubleVec2(conv(x), conv(y)) fun toDoubleVec3(): DoubleVec3 = DoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toDoubleVec3(conv: (Byte) -> Double): DoubleVec3 = DoubleVec3(conv(x), conv(y), conv(z)) fun toDoubleVec4(w: Double = 0.0): DoubleVec4 = DoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w) inline fun toDoubleVec4(w: Double = 0.0, conv: (Byte) -> Double): DoubleVec4 = DoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Double fun toMutableDoubleVec(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toMutableDoubleVec(conv: (Byte) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec2(): MutableDoubleVec2 = MutableDoubleVec2(x.toDouble(), y.toDouble()) inline fun toMutableDoubleVec2(conv: (Byte) -> Double): MutableDoubleVec2 = MutableDoubleVec2(conv(x), conv(y)) fun toMutableDoubleVec3(): MutableDoubleVec3 = MutableDoubleVec3(x.toDouble(), y.toDouble(), z.toDouble()) inline fun toMutableDoubleVec3(conv: (Byte) -> Double): MutableDoubleVec3 = MutableDoubleVec3(conv(x), conv(y), conv(z)) fun toMutableDoubleVec4(w: Double = 0.0): MutableDoubleVec4 = MutableDoubleVec4(x.toDouble(), y.toDouble(), z.toDouble(), w) inline fun toMutableDoubleVec4(w: Double = 0.0, conv: (Byte) -> Double): MutableDoubleVec4 = MutableDoubleVec4(conv(x), conv(y), conv(z), w) // Conversions to Int fun toIntVec(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toIntVec(conv: (Byte) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec2(): IntVec2 = IntVec2(x.toInt(), y.toInt()) inline fun toIntVec2(conv: (Byte) -> Int): IntVec2 = IntVec2(conv(x), conv(y)) fun toIntVec3(): IntVec3 = IntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toIntVec3(conv: (Byte) -> Int): IntVec3 = IntVec3(conv(x), conv(y), conv(z)) fun toIntVec4(w: Int = 0): IntVec4 = IntVec4(x.toInt(), y.toInt(), z.toInt(), w) inline fun toIntVec4(w: Int = 0, conv: (Byte) -> Int): IntVec4 = IntVec4(conv(x), conv(y), conv(z), w) // Conversions to Int fun toMutableIntVec(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toMutableIntVec(conv: (Byte) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec2(): MutableIntVec2 = MutableIntVec2(x.toInt(), y.toInt()) inline fun toMutableIntVec2(conv: (Byte) -> Int): MutableIntVec2 = MutableIntVec2(conv(x), conv(y)) fun toMutableIntVec3(): MutableIntVec3 = MutableIntVec3(x.toInt(), y.toInt(), z.toInt()) inline fun toMutableIntVec3(conv: (Byte) -> Int): MutableIntVec3 = MutableIntVec3(conv(x), conv(y), conv(z)) fun toMutableIntVec4(w: Int = 0): MutableIntVec4 = MutableIntVec4(x.toInt(), y.toInt(), z.toInt(), w) inline fun toMutableIntVec4(w: Int = 0, conv: (Byte) -> Int): MutableIntVec4 = MutableIntVec4(conv(x), conv(y), conv(z), w) // Conversions to Long fun toLongVec(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toLongVec(conv: (Byte) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec2(): LongVec2 = LongVec2(x.toLong(), y.toLong()) inline fun toLongVec2(conv: (Byte) -> Long): LongVec2 = LongVec2(conv(x), conv(y)) fun toLongVec3(): LongVec3 = LongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toLongVec3(conv: (Byte) -> Long): LongVec3 = LongVec3(conv(x), conv(y), conv(z)) fun toLongVec4(w: Long = 0L): LongVec4 = LongVec4(x.toLong(), y.toLong(), z.toLong(), w) inline fun toLongVec4(w: Long = 0L, conv: (Byte) -> Long): LongVec4 = LongVec4(conv(x), conv(y), conv(z), w) // Conversions to Long fun toMutableLongVec(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toMutableLongVec(conv: (Byte) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec2(): MutableLongVec2 = MutableLongVec2(x.toLong(), y.toLong()) inline fun toMutableLongVec2(conv: (Byte) -> Long): MutableLongVec2 = MutableLongVec2(conv(x), conv(y)) fun toMutableLongVec3(): MutableLongVec3 = MutableLongVec3(x.toLong(), y.toLong(), z.toLong()) inline fun toMutableLongVec3(conv: (Byte) -> Long): MutableLongVec3 = MutableLongVec3(conv(x), conv(y), conv(z)) fun toMutableLongVec4(w: Long = 0L): MutableLongVec4 = MutableLongVec4(x.toLong(), y.toLong(), z.toLong(), w) inline fun toMutableLongVec4(w: Long = 0L, conv: (Byte) -> Long): MutableLongVec4 = MutableLongVec4(conv(x), conv(y), conv(z), w) // Conversions to Short fun toShortVec(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toShortVec(conv: (Byte) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec2(): ShortVec2 = ShortVec2(x.toShort(), y.toShort()) inline fun toShortVec2(conv: (Byte) -> Short): ShortVec2 = ShortVec2(conv(x), conv(y)) fun toShortVec3(): ShortVec3 = ShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toShortVec3(conv: (Byte) -> Short): ShortVec3 = ShortVec3(conv(x), conv(y), conv(z)) fun toShortVec4(w: Short = 0.toShort()): ShortVec4 = ShortVec4(x.toShort(), y.toShort(), z.toShort(), w) inline fun toShortVec4(w: Short = 0.toShort(), conv: (Byte) -> Short): ShortVec4 = ShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Short fun toMutableShortVec(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toMutableShortVec(conv: (Byte) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec2(): MutableShortVec2 = MutableShortVec2(x.toShort(), y.toShort()) inline fun toMutableShortVec2(conv: (Byte) -> Short): MutableShortVec2 = MutableShortVec2(conv(x), conv(y)) fun toMutableShortVec3(): MutableShortVec3 = MutableShortVec3(x.toShort(), y.toShort(), z.toShort()) inline fun toMutableShortVec3(conv: (Byte) -> Short): MutableShortVec3 = MutableShortVec3(conv(x), conv(y), conv(z)) fun toMutableShortVec4(w: Short = 0.toShort()): MutableShortVec4 = MutableShortVec4(x.toShort(), y.toShort(), z.toShort(), w) inline fun toMutableShortVec4(w: Short = 0.toShort(), conv: (Byte) -> Short): MutableShortVec4 = MutableShortVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte fun toByteVec(): ByteVec3 = ByteVec3(x, y, z) inline fun toByteVec(conv: (Byte) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec2(): ByteVec2 = ByteVec2(x, y) inline fun toByteVec2(conv: (Byte) -> Byte): ByteVec2 = ByteVec2(conv(x), conv(y)) fun toByteVec3(): ByteVec3 = ByteVec3(x, y, z) inline fun toByteVec3(conv: (Byte) -> Byte): ByteVec3 = ByteVec3(conv(x), conv(y), conv(z)) fun toByteVec4(w: Byte = 0.toByte()): ByteVec4 = ByteVec4(x, y, z, w) inline fun toByteVec4(w: Byte = 0.toByte(), conv: (Byte) -> Byte): ByteVec4 = ByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Byte fun toMutableByteVec(): MutableByteVec3 = MutableByteVec3(x, y, z) inline fun toMutableByteVec(conv: (Byte) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec2(): MutableByteVec2 = MutableByteVec2(x, y) inline fun toMutableByteVec2(conv: (Byte) -> Byte): MutableByteVec2 = MutableByteVec2(conv(x), conv(y)) fun toMutableByteVec3(): MutableByteVec3 = MutableByteVec3(x, y, z) inline fun toMutableByteVec3(conv: (Byte) -> Byte): MutableByteVec3 = MutableByteVec3(conv(x), conv(y), conv(z)) fun toMutableByteVec4(w: Byte = 0.toByte()): MutableByteVec4 = MutableByteVec4(x, y, z, w) inline fun toMutableByteVec4(w: Byte = 0.toByte(), conv: (Byte) -> Byte): MutableByteVec4 = MutableByteVec4(conv(x), conv(y), conv(z), w) // Conversions to Char fun toCharVec(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toCharVec(conv: (Byte) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) fun toCharVec2(): CharVec2 = CharVec2(x.toChar(), y.toChar()) inline fun toCharVec2(conv: (Byte) -> Char): CharVec2 = CharVec2(conv(x), conv(y)) fun toCharVec3(): CharVec3 = CharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toCharVec3(conv: (Byte) -> Char): CharVec3 = CharVec3(conv(x), conv(y), conv(z)) fun toCharVec4(w: Char): CharVec4 = CharVec4(x.toChar(), y.toChar(), z.toChar(), w) inline fun toCharVec4(w: Char, conv: (Byte) -> Char): CharVec4 = CharVec4(conv(x), conv(y), conv(z), w) // Conversions to Char fun toMutableCharVec(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toMutableCharVec(conv: (Byte) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) fun toMutableCharVec2(): MutableCharVec2 = MutableCharVec2(x.toChar(), y.toChar()) inline fun toMutableCharVec2(conv: (Byte) -> Char): MutableCharVec2 = MutableCharVec2(conv(x), conv(y)) fun toMutableCharVec3(): MutableCharVec3 = MutableCharVec3(x.toChar(), y.toChar(), z.toChar()) inline fun toMutableCharVec3(conv: (Byte) -> Char): MutableCharVec3 = MutableCharVec3(conv(x), conv(y), conv(z)) fun toMutableCharVec4(w: Char): MutableCharVec4 = MutableCharVec4(x.toChar(), y.toChar(), z.toChar(), w) inline fun toMutableCharVec4(w: Char, conv: (Byte) -> Char): MutableCharVec4 = MutableCharVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toBoolVec(): BoolVec3 = BoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte()) inline fun toBoolVec(conv: (Byte) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec2(): BoolVec2 = BoolVec2(x != 0.toByte(), y != 0.toByte()) inline fun toBoolVec2(conv: (Byte) -> Boolean): BoolVec2 = BoolVec2(conv(x), conv(y)) fun toBoolVec3(): BoolVec3 = BoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte()) inline fun toBoolVec3(conv: (Byte) -> Boolean): BoolVec3 = BoolVec3(conv(x), conv(y), conv(z)) fun toBoolVec4(w: Boolean = false): BoolVec4 = BoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w) inline fun toBoolVec4(w: Boolean = false, conv: (Byte) -> Boolean): BoolVec4 = BoolVec4(conv(x), conv(y), conv(z), w) // Conversions to Boolean fun toMutableBoolVec(): MutableBoolVec3 = MutableBoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte()) inline fun toMutableBoolVec(conv: (Byte) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec2(): MutableBoolVec2 = MutableBoolVec2(x != 0.toByte(), y != 0.toByte()) inline fun toMutableBoolVec2(conv: (Byte) -> Boolean): MutableBoolVec2 = MutableBoolVec2(conv(x), conv(y)) fun toMutableBoolVec3(): MutableBoolVec3 = MutableBoolVec3(x != 0.toByte(), y != 0.toByte(), z != 0.toByte()) inline fun toMutableBoolVec3(conv: (Byte) -> Boolean): MutableBoolVec3 = MutableBoolVec3(conv(x), conv(y), conv(z)) fun toMutableBoolVec4(w: Boolean = false): MutableBoolVec4 = MutableBoolVec4(x != 0.toByte(), y != 0.toByte(), z != 0.toByte(), w) inline fun toMutableBoolVec4(w: Boolean = false, conv: (Byte) -> Boolean): MutableBoolVec4 = MutableBoolVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toStringVec(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec(conv: (Byte) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec2(): StringVec2 = StringVec2(x.toString(), y.toString()) inline fun toStringVec2(conv: (Byte) -> String): StringVec2 = StringVec2(conv(x), conv(y)) fun toStringVec3(): StringVec3 = StringVec3(x.toString(), y.toString(), z.toString()) inline fun toStringVec3(conv: (Byte) -> String): StringVec3 = StringVec3(conv(x), conv(y), conv(z)) fun toStringVec4(w: String = ""): StringVec4 = StringVec4(x.toString(), y.toString(), z.toString(), w) inline fun toStringVec4(w: String = "", conv: (Byte) -> String): StringVec4 = StringVec4(conv(x), conv(y), conv(z), w) // Conversions to String fun toMutableStringVec(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec(conv: (Byte) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec2(): MutableStringVec2 = MutableStringVec2(x.toString(), y.toString()) inline fun toMutableStringVec2(conv: (Byte) -> String): MutableStringVec2 = MutableStringVec2(conv(x), conv(y)) fun toMutableStringVec3(): MutableStringVec3 = MutableStringVec3(x.toString(), y.toString(), z.toString()) inline fun toMutableStringVec3(conv: (Byte) -> String): MutableStringVec3 = MutableStringVec3(conv(x), conv(y), conv(z)) fun toMutableStringVec4(w: String = ""): MutableStringVec4 = MutableStringVec4(x.toString(), y.toString(), z.toString(), w) inline fun toMutableStringVec4(w: String = "", conv: (Byte) -> String): MutableStringVec4 = MutableStringVec4(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toTVec(conv: (Byte) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec2(conv: (Byte) -> T2): TVec2<T2> = TVec2<T2>(conv(x), conv(y)) inline fun <T2> toTVec3(conv: (Byte) -> T2): TVec3<T2> = TVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toTVec4(w: T2, conv: (Byte) -> T2): TVec4<T2> = TVec4<T2>(conv(x), conv(y), conv(z), w) // Conversions to T2 inline fun <T2> toMutableTVec(conv: (Byte) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec2(conv: (Byte) -> T2): MutableTVec2<T2> = MutableTVec2<T2>(conv(x), conv(y)) inline fun <T2> toMutableTVec3(conv: (Byte) -> T2): MutableTVec3<T2> = MutableTVec3<T2>(conv(x), conv(y), conv(z)) inline fun <T2> toMutableTVec4(w: T2, conv: (Byte) -> T2): MutableTVec4<T2> = MutableTVec4<T2>(conv(x), conv(y), conv(z), w) // Allows for swizzling, e.g. v.swizzle.xzx inner class Swizzle { val xx: ByteVec2 get() = ByteVec2(x, x) val xy: ByteVec2 get() = ByteVec2(x, y) val xz: ByteVec2 get() = ByteVec2(x, z) val yx: ByteVec2 get() = ByteVec2(y, x) val yy: ByteVec2 get() = ByteVec2(y, y) val yz: ByteVec2 get() = ByteVec2(y, z) val zx: ByteVec2 get() = ByteVec2(z, x) val zy: ByteVec2 get() = ByteVec2(z, y) val zz: ByteVec2 get() = ByteVec2(z, z) val xxx: ByteVec3 get() = ByteVec3(x, x, x) val xxy: ByteVec3 get() = ByteVec3(x, x, y) val xxz: ByteVec3 get() = ByteVec3(x, x, z) val xyx: ByteVec3 get() = ByteVec3(x, y, x) val xyy: ByteVec3 get() = ByteVec3(x, y, y) val xyz: ByteVec3 get() = ByteVec3(x, y, z) val xzx: ByteVec3 get() = ByteVec3(x, z, x) val xzy: ByteVec3 get() = ByteVec3(x, z, y) val xzz: ByteVec3 get() = ByteVec3(x, z, z) val yxx: ByteVec3 get() = ByteVec3(y, x, x) val yxy: ByteVec3 get() = ByteVec3(y, x, y) val yxz: ByteVec3 get() = ByteVec3(y, x, z) val yyx: ByteVec3 get() = ByteVec3(y, y, x) val yyy: ByteVec3 get() = ByteVec3(y, y, y) val yyz: ByteVec3 get() = ByteVec3(y, y, z) val yzx: ByteVec3 get() = ByteVec3(y, z, x) val yzy: ByteVec3 get() = ByteVec3(y, z, y) val yzz: ByteVec3 get() = ByteVec3(y, z, z) val zxx: ByteVec3 get() = ByteVec3(z, x, x) val zxy: ByteVec3 get() = ByteVec3(z, x, y) val zxz: ByteVec3 get() = ByteVec3(z, x, z) val zyx: ByteVec3 get() = ByteVec3(z, y, x) val zyy: ByteVec3 get() = ByteVec3(z, y, y) val zyz: ByteVec3 get() = ByteVec3(z, y, z) val zzx: ByteVec3 get() = ByteVec3(z, z, x) val zzy: ByteVec3 get() = ByteVec3(z, z, y) val zzz: ByteVec3 get() = ByteVec3(z, z, z) val xxxx: ByteVec4 get() = ByteVec4(x, x, x, x) val xxxy: ByteVec4 get() = ByteVec4(x, x, x, y) val xxxz: ByteVec4 get() = ByteVec4(x, x, x, z) val xxyx: ByteVec4 get() = ByteVec4(x, x, y, x) val xxyy: ByteVec4 get() = ByteVec4(x, x, y, y) val xxyz: ByteVec4 get() = ByteVec4(x, x, y, z) val xxzx: ByteVec4 get() = ByteVec4(x, x, z, x) val xxzy: ByteVec4 get() = ByteVec4(x, x, z, y) val xxzz: ByteVec4 get() = ByteVec4(x, x, z, z) val xyxx: ByteVec4 get() = ByteVec4(x, y, x, x) val xyxy: ByteVec4 get() = ByteVec4(x, y, x, y) val xyxz: ByteVec4 get() = ByteVec4(x, y, x, z) val xyyx: ByteVec4 get() = ByteVec4(x, y, y, x) val xyyy: ByteVec4 get() = ByteVec4(x, y, y, y) val xyyz: ByteVec4 get() = ByteVec4(x, y, y, z) val xyzx: ByteVec4 get() = ByteVec4(x, y, z, x) val xyzy: ByteVec4 get() = ByteVec4(x, y, z, y) val xyzz: ByteVec4 get() = ByteVec4(x, y, z, z) val xzxx: ByteVec4 get() = ByteVec4(x, z, x, x) val xzxy: ByteVec4 get() = ByteVec4(x, z, x, y) val xzxz: ByteVec4 get() = ByteVec4(x, z, x, z) val xzyx: ByteVec4 get() = ByteVec4(x, z, y, x) val xzyy: ByteVec4 get() = ByteVec4(x, z, y, y) val xzyz: ByteVec4 get() = ByteVec4(x, z, y, z) val xzzx: ByteVec4 get() = ByteVec4(x, z, z, x) val xzzy: ByteVec4 get() = ByteVec4(x, z, z, y) val xzzz: ByteVec4 get() = ByteVec4(x, z, z, z) val yxxx: ByteVec4 get() = ByteVec4(y, x, x, x) val yxxy: ByteVec4 get() = ByteVec4(y, x, x, y) val yxxz: ByteVec4 get() = ByteVec4(y, x, x, z) val yxyx: ByteVec4 get() = ByteVec4(y, x, y, x) val yxyy: ByteVec4 get() = ByteVec4(y, x, y, y) val yxyz: ByteVec4 get() = ByteVec4(y, x, y, z) val yxzx: ByteVec4 get() = ByteVec4(y, x, z, x) val yxzy: ByteVec4 get() = ByteVec4(y, x, z, y) val yxzz: ByteVec4 get() = ByteVec4(y, x, z, z) val yyxx: ByteVec4 get() = ByteVec4(y, y, x, x) val yyxy: ByteVec4 get() = ByteVec4(y, y, x, y) val yyxz: ByteVec4 get() = ByteVec4(y, y, x, z) val yyyx: ByteVec4 get() = ByteVec4(y, y, y, x) val yyyy: ByteVec4 get() = ByteVec4(y, y, y, y) val yyyz: ByteVec4 get() = ByteVec4(y, y, y, z) val yyzx: ByteVec4 get() = ByteVec4(y, y, z, x) val yyzy: ByteVec4 get() = ByteVec4(y, y, z, y) val yyzz: ByteVec4 get() = ByteVec4(y, y, z, z) val yzxx: ByteVec4 get() = ByteVec4(y, z, x, x) val yzxy: ByteVec4 get() = ByteVec4(y, z, x, y) val yzxz: ByteVec4 get() = ByteVec4(y, z, x, z) val yzyx: ByteVec4 get() = ByteVec4(y, z, y, x) val yzyy: ByteVec4 get() = ByteVec4(y, z, y, y) val yzyz: ByteVec4 get() = ByteVec4(y, z, y, z) val yzzx: ByteVec4 get() = ByteVec4(y, z, z, x) val yzzy: ByteVec4 get() = ByteVec4(y, z, z, y) val yzzz: ByteVec4 get() = ByteVec4(y, z, z, z) val zxxx: ByteVec4 get() = ByteVec4(z, x, x, x) val zxxy: ByteVec4 get() = ByteVec4(z, x, x, y) val zxxz: ByteVec4 get() = ByteVec4(z, x, x, z) val zxyx: ByteVec4 get() = ByteVec4(z, x, y, x) val zxyy: ByteVec4 get() = ByteVec4(z, x, y, y) val zxyz: ByteVec4 get() = ByteVec4(z, x, y, z) val zxzx: ByteVec4 get() = ByteVec4(z, x, z, x) val zxzy: ByteVec4 get() = ByteVec4(z, x, z, y) val zxzz: ByteVec4 get() = ByteVec4(z, x, z, z) val zyxx: ByteVec4 get() = ByteVec4(z, y, x, x) val zyxy: ByteVec4 get() = ByteVec4(z, y, x, y) val zyxz: ByteVec4 get() = ByteVec4(z, y, x, z) val zyyx: ByteVec4 get() = ByteVec4(z, y, y, x) val zyyy: ByteVec4 get() = ByteVec4(z, y, y, y) val zyyz: ByteVec4 get() = ByteVec4(z, y, y, z) val zyzx: ByteVec4 get() = ByteVec4(z, y, z, x) val zyzy: ByteVec4 get() = ByteVec4(z, y, z, y) val zyzz: ByteVec4 get() = ByteVec4(z, y, z, z) val zzxx: ByteVec4 get() = ByteVec4(z, z, x, x) val zzxy: ByteVec4 get() = ByteVec4(z, z, x, y) val zzxz: ByteVec4 get() = ByteVec4(z, z, x, z) val zzyx: ByteVec4 get() = ByteVec4(z, z, y, x) val zzyy: ByteVec4 get() = ByteVec4(z, z, y, y) val zzyz: ByteVec4 get() = ByteVec4(z, z, y, z) val zzzx: ByteVec4 get() = ByteVec4(z, z, z, x) val zzzy: ByteVec4 get() = ByteVec4(z, z, z, y) val zzzz: ByteVec4 get() = ByteVec4(z, z, z, z) } val swizzle: Swizzle get() = Swizzle() } fun vecOf(x: Byte, y: Byte, z: Byte): ByteVec3 = ByteVec3(x, y, z) operator fun Byte.plus(rhs: ByteVec3): IntVec3 = IntVec3(this + rhs.x, this + rhs.y, this + rhs.z) operator fun Byte.minus(rhs: ByteVec3): IntVec3 = IntVec3(this - rhs.x, this - rhs.y, this - rhs.z) operator fun Byte.times(rhs: ByteVec3): IntVec3 = IntVec3(this * rhs.x, this * rhs.y, this * rhs.z) operator fun Byte.div(rhs: ByteVec3): IntVec3 = IntVec3(this / rhs.x, this / rhs.y, this / rhs.z) operator fun Byte.rem(rhs: ByteVec3): IntVec3 = IntVec3(this % rhs.x, this % rhs.y, this % rhs.z)
mit
5bad6333257b1bb1207e91002991bb6d
67.01084
147
0.628706
3.25162
false
false
false
false
cfieber/orca
orca-queue/src/test/kotlin/com/netflix/spinnaker/orca/q/metrics/AtlasQueueMonitorTest.kt
1
11558
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.orca.q.metrics import com.netflix.spectator.api.Counter import com.netflix.spectator.api.Registry import com.netflix.spectator.api.Tag import com.netflix.spectator.api.Timer import com.netflix.spinnaker.orca.ExecutionStatus.RUNNING import com.netflix.spinnaker.orca.ExecutionStatus.SUCCEEDED import com.netflix.spinnaker.orca.fixture.pipeline import com.netflix.spinnaker.orca.notifications.NotificationClusterLock import com.netflix.spinnaker.orca.pipeline.model.Execution.ExecutionType.PIPELINE import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository import com.netflix.spinnaker.orca.pipeline.persistence.ExecutionRepository.ExecutionCriteria import com.netflix.spinnaker.orca.q.StartExecution import com.netflix.spinnaker.q.Activator import com.netflix.spinnaker.q.metrics.* import com.netflix.spinnaker.time.fixedClock import com.nhaarman.mockito_kotlin.* import org.assertj.core.api.Assertions.assertThat import org.jetbrains.spek.api.dsl.describe import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.api.dsl.on import org.jetbrains.spek.api.lifecycle.CachingMode.GROUP import org.jetbrains.spek.subject.SubjectSpek import rx.Observable.just import rx.schedulers.Schedulers import java.time.Duration import java.time.Instant.now import java.time.temporal.ChronoUnit.HOURS import java.util.* import java.util.concurrent.TimeUnit.MILLISECONDS object AtlasQueueMonitorTest : SubjectSpek<AtlasQueueMonitor>({ val queue: MonitorableQueue = mock() val repository: ExecutionRepository = mock() val clock = fixedClock(instant = now().minus(Duration.ofHours(1))) val activator: Activator = mock() val conch: NotificationClusterLock = mock() val pushCounter: Counter = mock() val ackCounter: Counter = mock() val retryCounter: Counter = mock() val deadCounter: Counter = mock() val duplicateCounter: Counter = mock() val lockFailedCounter: Counter = mock() val messageLagTimer: Timer = mock() val zombieCounter: Counter = mock() val registry: Registry = mock { on { counter(eq("queue.pushed.messages"), anyVararg<String>()) } doReturn pushCounter on { counter("queue.acknowledged.messages") } doReturn ackCounter on { counter("queue.retried.messages") } doReturn retryCounter on { counter("queue.dead.messages") } doReturn deadCounter on { counter(eq("queue.duplicate.messages"), anyVararg<String>()) } doReturn duplicateCounter on { counter("queue.lock.failed") } doReturn lockFailedCounter on { timer("queue.message.lag") } doReturn messageLagTimer on { counter(eq("queue.zombies"), any<Iterable<Tag>>()) } doReturn zombieCounter } subject(GROUP) { AtlasQueueMonitor( queue, registry, repository, clock, listOf(activator), conch, true, Optional.of(Schedulers.immediate()), 10 ) } fun resetMocks() = reset(queue, repository, pushCounter, ackCounter, retryCounter, deadCounter, duplicateCounter, zombieCounter) describe("default values") { it("reports system uptime if the queue has never been polled") { assertThat(subject.lastQueuePoll).isEqualTo(clock.instant()) assertThat(subject.lastRetryPoll).isEqualTo(clock.instant()) } } describe("responding to queue events") { describe("when the queue is polled") { afterGroup(::resetMocks) val event = QueuePolled on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("updates the last poll time") { assertThat(subject.lastQueuePoll).isEqualTo(clock.instant()) } } describe("when the retry queue is polled") { afterGroup(::resetMocks) val event = RetryPolled on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("updates the last poll time") { assertThat(subject.lastRetryPoll).isEqualTo(clock.instant()) } } describe("when a message is processed") { afterGroup(::resetMocks) val event = MessageProcessing(StartExecution(PIPELINE, "1", "covfefe"), Duration.ofSeconds(5)) on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("records the lag") { verify(messageLagTimer).record(event.lag.toMillis(), MILLISECONDS) } } describe("when a message is pushed") { afterGroup(::resetMocks) val event = MessagePushed(StartExecution(PIPELINE, "1", "covfefe")) on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("increments a counter") { verify(pushCounter).increment() } } describe("when a message is acknowledged") { afterGroup(::resetMocks) val event = MessageAcknowledged on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("increments a counter") { verify(ackCounter).increment() } } describe("when a message is retried") { afterGroup(::resetMocks) val event = MessageRetried on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("increments a counter") { verify(retryCounter).increment() } } describe("when a message is dead") { afterGroup(::resetMocks) val event = MessageDead on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("increments a counter") { verify(deadCounter).increment() } } describe("when a duplicate message is pushed") { afterGroup(::resetMocks) val event = MessageDuplicate(StartExecution(PIPELINE, "1", "covfefe")) on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("increments a counter") { verify(duplicateCounter).increment() } } describe("when an instance fails to lock a message") { afterGroup(::resetMocks) val event = LockFailed on("receiving a ${event.javaClass.simpleName} event") { subject.onQueueEvent(event) } it("increments a counter") { verify(lockFailedCounter).increment() } } } describe("checking queue state") { afterGroup(::resetMocks) val queueState = QueueState(4, 1, 2, 0) beforeGroup { whenever(queue.readState()) doReturn queueState } on("checking queue state") { subject.pollQueueState() } it("updates the queue state") { assertThat(subject.lastState).isEqualTo(queueState) } } describe("detecting zombie executions") { val criteria = ExecutionCriteria().setStatuses(RUNNING) given("the instance is disabled") { beforeGroup { whenever(activator.enabled) doReturn false whenever(conch.tryAcquireLock(eq("zombie"), any())) doReturn true } afterGroup { reset(activator, conch) } given("a running pipeline with no associated messages") { val pipeline = pipeline { status = RUNNING buildTime = clock.instant().minus(1, HOURS).toEpochMilli() } beforeGroup { whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline) whenever(queue.containsMessage(any())) doReturn true } afterGroup(::resetMocks) on("looking for zombies") { subject.checkForZombies() it("does not run a zombie check") { verifyZeroInteractions(repository, queue, zombieCounter) } } } } given("the instance cannot acquire a cluster lock") { beforeGroup { whenever(activator.enabled) doReturn true whenever(conch.tryAcquireLock(eq("zombie"), any())) doReturn false } afterGroup { reset(activator, conch) } given("a running pipeline with no associated messages") { val pipeline = pipeline { status = RUNNING buildTime = clock.instant().minus(1, HOURS).toEpochMilli() } beforeGroup { whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline) whenever(queue.containsMessage(any())) doReturn true } afterGroup(::resetMocks) on("looking for zombies") { subject.checkForZombies() it("does not run a zombie check") { verifyZeroInteractions(repository, queue, zombieCounter) } } } } given("the instance is active and can acquire a cluster lock") { beforeGroup { whenever(activator.enabled) doReturn true whenever(conch.tryAcquireLock(eq("zombie"), any())) doReturn true } afterGroup { reset(activator, conch) } given("a non-running pipeline with no associated messages") { val pipeline = pipeline { status = SUCCEEDED buildTime = clock.instant().minus(1, HOURS).toEpochMilli() } beforeGroup { whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline) whenever(queue.containsMessage(any())) doReturn true } afterGroup(::resetMocks) on("looking for zombies") { subject.checkForZombies() it("does not increment the counter") { verifyZeroInteractions(zombieCounter) } } } given("a running pipeline with an associated messages") { val pipeline = pipeline { status = RUNNING buildTime = clock.instant().minus(1, HOURS).toEpochMilli() } beforeGroup { whenever(repository.retrieve(pipeline.type, criteria)) doReturn just(pipeline) whenever(queue.containsMessage(any())) doReturn true } afterGroup(::resetMocks) on("looking for zombies") { subject.checkForZombies() it("does not increment the counter") { verifyZeroInteractions(zombieCounter) } } } given("a running pipeline with no associated messages") { val pipeline = pipeline { status = RUNNING buildTime = clock.instant().minus(1, HOURS).toEpochMilli() } beforeGroup { whenever(repository.retrieve(PIPELINE, criteria)) doReturn just(pipeline) whenever(queue.containsMessage(any())) doReturn false } afterGroup(::resetMocks) on("looking for zombies") { subject.checkForZombies() it("increments the counter") { verify(zombieCounter).increment() } } } } } }) private fun Sequence<Duration>.average() = map { it.toMillis() } .average() .let { Duration.ofMillis(it.toLong()) }
apache-2.0
2842dc775e3757249e8b622d38f22bdf
27.967419
113
0.65539
4.499027
false
false
false
false
ayatk/biblio
app/src/main/kotlin/com/ayatk/biblio/ui/detail/DetailActivity.kt
1
2911
/* * Copyright (c) 2016-2018 ayatk. * * 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.ayatk.biblio.ui.detail import android.content.Context import android.content.Intent import android.os.Bundle import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.fragment.app.FragmentPagerAdapter import com.ayatk.biblio.R import com.ayatk.biblio.databinding.ActivityDetailBinding import com.ayatk.biblio.model.Novel import com.ayatk.biblio.ui.detail.index.IndexFragment import com.ayatk.biblio.ui.detail.info.InfoFragment import com.ayatk.biblio.ui.util.initBackToolbar import com.ayatk.biblio.util.ext.extraOf import dagger.android.support.DaggerAppCompatActivity class DetailActivity : DaggerAppCompatActivity() { private val binding: ActivityDetailBinding by lazy { DataBindingUtil.setContentView<ActivityDetailBinding>(this, R.layout.activity_detail) } private val novel: Novel by lazy { intent.extras?.get(EXTRA_NOVEL) as Novel } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding.toolbar.title = novel.title initBackToolbar(binding.toolbar) // ViewPager val viewPager = binding.containerPager viewPager.adapter = DetailPagerAdapter(supportFragmentManager) binding.tab.setupWithViewPager(viewPager) } companion object { private const val EXTRA_NOVEL = "extra_novel" fun createIntent(context: Context, novel: Novel): Intent = Intent(context, DetailActivity::class.java).extraOf( EXTRA_NOVEL to novel ) } inner class DetailPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) { override fun getItem(position: Int): Fragment = DetailPage.values()[position].createFragment(novel) override fun getCount(): Int = DetailPage.values().size override fun getPageTitle(position: Int): CharSequence = getString(DetailPage.values()[position].title) } private enum class DetailPage(val title: Int) { INDEX(R.string.novel_index_title) { override fun createFragment(novel: Novel): Fragment = IndexFragment.newInstance(novel) }, INFO(R.string.novel_info_title) { override fun createFragment(novel: Novel): Fragment = InfoFragment.newInstance(novel) }; abstract fun createFragment(novel: Novel): Fragment } }
apache-2.0
6bccb81c914251b558f8794ee246aab6
32.079545
92
0.757815
4.325409
false
false
false
false
google/android-fhir
buildSrc/src/main/kotlin/Dependencies.kt
1
10990
/* * Copyright 2022 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ object Dependencies { object Androidx { const val activity = "androidx.activity:activity:${Versions.Androidx.activity}" const val appCompat = "androidx.appcompat:appcompat:${Versions.Androidx.appCompat}" const val constraintLayout = "androidx.constraintlayout:constraintlayout:${Versions.Androidx.constraintLayout}" const val coreKtx = "androidx.core:core-ktx:${Versions.Androidx.coreKtx}" const val datastorePref = "androidx.datastore:datastore-preferences:${Versions.Androidx.datastorePref}" const val fragmentKtx = "androidx.fragment:fragment-ktx:${Versions.Androidx.fragmentKtx}" const val recyclerView = "androidx.recyclerview:recyclerview:${Versions.Androidx.recyclerView}" const val sqliteKtx = "androidx.sqlite:sqlite-ktx:${Versions.Androidx.sqliteKtx}" const val workRuntimeKtx = "androidx.work:work-runtime-ktx:${Versions.Androidx.workRuntimeKtx}" } object Cql { const val openCdsGroup = "org.opencds.cqf.cql" const val translatorGroup = "info.cqframework" // Remove this after this issue has been fixed: // https://github.com/cqframework/clinical_quality_language/issues/799 const val antlr4Runtime = "org.antlr:antlr4-runtime:${Versions.Cql.antlr}" const val engine = "$openCdsGroup:engine:${Versions.Cql.engine}" const val engineJackson = "$openCdsGroup:engine.jackson:${Versions.Cql.engine}" const val evaluator = "$openCdsGroup:evaluator:${Versions.Cql.evaluator}" const val evaluatorBuilder = "$openCdsGroup:evaluator.builder:${Versions.Cql.evaluator}" const val evaluatorDagger = "$openCdsGroup:evaluator.dagger:${Versions.Cql.evaluator}" const val evaluatorPlanDef = "$openCdsGroup:evaluator.plandefinition:${Versions.Cql.evaluator}" const val translatorCqlToElm = "$translatorGroup:cql-to-elm:${Versions.Cql.translator}" const val translatorElm = "$translatorGroup:elm:${Versions.Cql.translator}" const val translatorModel = "$translatorGroup:model:${Versions.Cql.translator}" const val translatorElmJackson = "$translatorGroup:elm-jackson:${Versions.Cql.translator}" const val translatorModelJackson = "$translatorGroup:model-jackson:${Versions.Cql.translator}" } object HapiFhir { const val structuresR4 = "ca.uhn.hapi.fhir:hapi-fhir-structures-r4:${Versions.hapiFhir}" const val validation = "ca.uhn.hapi.fhir:hapi-fhir-validation:${Versions.hapiFhir}" // Runtime dependency that is required to run FhirPath (also requires minSDK of 26). // Version 3.0 uses java.lang.System.Logger, which is not available on Android // Replace for Guava when this PR gets merged: https://github.com/hapifhir/hapi-fhir/pull/3977 const val caffeine = "com.github.ben-manes.caffeine:caffeine:${Versions.caffeine}" } object Jackson { const val annotations = "com.fasterxml.jackson.core:jackson-annotations:${Versions.jackson}" const val core = "com.fasterxml.jackson.core:jackson-core:${Versions.jackson}" const val databind = "com.fasterxml.jackson.core:jackson-databind:${Versions.jackson}" } object Kotlin { const val kotlinCoroutinesAndroid = "org.jetbrains.kotlinx:kotlinx-coroutines-android:${Versions.Kotlin.kotlinCoroutinesCore}" const val kotlinCoroutinesCore = "org.jetbrains.kotlinx:kotlinx-coroutines-core:${Versions.Kotlin.kotlinCoroutinesCore}" const val kotlinTestJunit = "org.jetbrains.kotlin:kotlin-test-junit:${Versions.Kotlin.stdlib}" const val kotlinCoroutinesTest = "org.jetbrains.kotlinx:kotlinx-coroutines-test:${Versions.Kotlin.kotlinCoroutinesCore}" const val stdlib = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.Kotlin.stdlib}" } object Lifecycle { const val liveDataKtx = "androidx.lifecycle:lifecycle-livedata-ktx:${Versions.Androidx.lifecycle}" const val runtime = "androidx.lifecycle:lifecycle-runtime:${Versions.Androidx.lifecycle}" const val viewModelKtx = "androidx.lifecycle:lifecycle-viewmodel-ktx:${Versions.Androidx.lifecycle}" } object Navigation { const val navFragmentKtx = "androidx.navigation:navigation-fragment-ktx:${Versions.Androidx.navigation}" const val navUiKtx = "androidx.navigation:navigation-ui-ktx:${Versions.Androidx.navigation}" } object Retrofit { const val coreRetrofit = "com.squareup.retrofit2:retrofit:${Versions.retrofit}" const val gsonConverter = "com.squareup.retrofit2:converter-gson:${Versions.retrofit}" } object Room { const val compiler = "androidx.room:room-compiler:${Versions.Androidx.room}" const val ktx = "androidx.room:room-ktx:${Versions.Androidx.room}" const val runtime = "androidx.room:room-runtime:${Versions.Androidx.room}" } object Mlkit { const val barcodeScanning = "com.google.mlkit:barcode-scanning:${Versions.Mlkit.barcodeScanning}" const val objectDetection = "com.google.mlkit:object-detection:${Versions.Mlkit.objectDetection}" const val objectDetectionCustom = "com.google.mlkit:object-detection-custom:${Versions.Mlkit.objectDetectionCustom}" } const val androidFhirGroup = "com.google.android.fhir" const val androidFhirCommon = "$androidFhirGroup:common:${Versions.androidFhirCommon}" const val androidFhirEngineModule = "engine" const val androidFhirEngine = "$androidFhirGroup:$androidFhirEngineModule:${Versions.androidFhirEngine}" const val lifecycleExtensions = "androidx.lifecycle:lifecycle-extensions:${Versions.Androidx.lifecycle}" const val desugarJdkLibs = "com.android.tools:desugar_jdk_libs:${Versions.desugarJdkLibs}" const val fhirUcum = "org.fhir:ucum:${Versions.fhirUcum}" const val guava = "com.google.guava:guava:${Versions.guava}" const val httpInterceptor = "com.squareup.okhttp3:logging-interceptor:${Versions.http}" const val http = "com.squareup.okhttp3:okhttp:${Versions.http}" const val jsonToolsPatch = "com.github.java-json-tools:json-patch:${Versions.jsonToolsPatch}" const val kotlinPoet = "com.squareup:kotlinpoet:${Versions.kotlinPoet}" const val material = "com.google.android.material:material:${Versions.material}" const val sqlcipher = "net.zetetic:android-database-sqlcipher:${Versions.sqlcipher}" const val timber = "com.jakewharton.timber:timber:${Versions.timber}" const val woodstox = "com.fasterxml.woodstox:woodstox-core:${Versions.woodstox}" const val xerces = "xerces:xercesImpl:${Versions.xerces}" // Dependencies for testing go here object AndroidxTest { const val archCore = "androidx.arch.core:core-testing:${Versions.AndroidxTest.archCore}" const val core = "androidx.test:core:${Versions.AndroidxTest.core}" const val extJunit = "androidx.test.ext:junit:${Versions.AndroidxTest.extJunit}" const val extJunitKtx = "androidx.test.ext:junit-ktx:${Versions.AndroidxTest.extJunit}" const val fragmentTesting = "androidx.fragment:fragment-testing:${Versions.AndroidxTest.fragmentVersion}" const val rules = "androidx.test:rules:${Versions.AndroidxTest.rules}" const val runner = "androidx.test:runner:${Versions.AndroidxTest.runner}" const val workTestingRuntimeKtx = "androidx.work:work-testing:${Versions.Androidx.workRuntimeKtx}" } object Espresso { const val espressoCore = "androidx.test.espresso:espresso-core:${Versions.espresso}" const val espressoContrib = "androidx.test.espresso:espresso-contrib:${Versions.espresso}" } const val androidJunitRunner = "androidx.test.runner.AndroidJUnitRunner" // Makes Json assertions where the order of elements, tabs/whitespaces are not important. const val jsonAssert = "org.skyscreamer:jsonassert:${Versions.jsonAssert}" const val junit = "junit:junit:${Versions.junit}" const val mockitoKotlin = "org.mockito.kotlin:mockito-kotlin:${Versions.mockitoKotlin}" const val mockitoInline = "org.mockito:mockito-inline:${Versions.mockitoInline}" const val robolectric = "org.robolectric:robolectric:${Versions.robolectric}" const val slf4j = "org.slf4j:slf4j-android:${Versions.slf4j}" const val truth = "com.google.truth:truth:${Versions.truth}" // Makes XML assertions where the order of elements, tabs/whitespaces are not important. const val xmlUnit = "org.xmlunit:xmlunit-core:${Versions.xmlUnit}" object Versions { object Androidx { const val activity = "1.2.1" const val appCompat = "1.1.0" const val constraintLayout = "2.1.1" const val coreKtx = "1.2.0" const val datastorePref = "1.0.0" const val fragmentKtx = "1.3.1" const val lifecycle = "2.2.0" const val navigation = "2.3.4" const val recyclerView = "1.1.0" const val room = "2.4.2" const val sqliteKtx = "2.1.0" const val workRuntimeKtx = "2.7.1" } object Cql { const val antlr = "4.10.1" const val engine = "2.1.0" const val evaluator = "2.1.0" const val translator = "2.2.0" } object Kotlin { const val kotlinCoroutinesCore = "1.6.2" const val stdlib = "1.6.10" } const val androidFhirCommon = "0.1.0-alpha03" const val androidFhirEngine = "0.1.0-beta02" const val desugarJdkLibs = "1.1.5" const val caffeine = "2.9.1" const val fhirUcum = "1.0.3" const val guava = "28.2-android" const val hapiFhir = "6.0.1" const val http = "4.9.1" const val jackson = "2.12.2" const val jsonToolsPatch = "1.13" const val jsonAssert = "1.5.1" const val kotlinPoet = "1.9.0" const val material = "1.6.0" const val retrofit = "2.7.2" const val slf4j = "1.7.36" const val sqlcipher = "4.5.0" const val timber = "5.0.1" const val truth = "1.0.1" const val woodstox = "6.2.7" const val xerces = "2.12.2" const val xmlUnit = "2.9.0" // Test dependencies object AndroidxTest { const val core = "1.4.0" const val archCore = "2.1.0" const val extJunit = "1.1.3" const val rules = "1.4.0" const val runner = "1.4.0" const val fragmentVersion = "1.3.6" } const val espresso = "3.4.0" const val jacoco = "0.8.7" const val junit = "4.13.2" const val mockitoKotlin = "3.2.0" const val mockitoInline = "4.0.0" const val robolectric = "4.7.3" object Mlkit { const val barcodeScanning = "16.1.1" const val objectDetection = "16.2.3" const val objectDetectionCustom = "16.3.1" } } }
apache-2.0
c352254b81a78b26685f39d7629901fc
44.040984
99
0.717197
3.720379
false
true
false
false
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_indirect_parameters.kt
4
4641
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_indirect_parameters = "ARBIndirectParameters".nativeClassGL("ARB_indirect_parameters", postfix = ARB) { documentation = """ Native bindings to the $registryLink extension. OpenGL 4.3 (with the introduction of the ${ARB_multi_draw_indirect.link} extension) enhanced the ability of OpenGL to allow a large sets of parameters for indirect draws (introduced with OpenGL 4.0) into a buffer object and dispatch the entire list with one API call. This allows, for example, a shader (such as a compute shader via shader storage buffers, or a geometry shader via transform feedback) to produce lists of draw commands that can then be consumed by OpenGL without a server-client round trip. However, when a variable and potentially unknown number of draws are produced by such a shader, it becomes difficult to know how many draws are in the output array(s). Applications must resort to techniques such as transform feedback primitive queries, or mapping buffers containing the content of atomic counters, which can cause stalls or bubbles in the OpenGL pipeline. This extension introduces the concept of the "parameter buffer", which is a target allowing buffers to store parameters for certain drawing commands. Also in this extension, new variants of #MultiDrawArraysIndirect() and #MultiDrawElementsIndirect() are introduced that source some of their parameters from this buffer. Further commands could potentially be introduced that source other parameters from a buffer. Requires ${GL42.core}. """ IntConstant( """ Accepted by the {@code target} parameters of BindBuffer, BufferData, BufferSubData, MapBuffer, UnmapBuffer, GetBufferSubData, GetBufferPointerv, MapBufferRange, FlushMappedBufferRange, GetBufferParameteriv, and CopyBufferSubData. """, "PARAMETER_BUFFER_ARB"..0x80EE ) IntConstant( "Accepted by the {@code value} parameter of GetIntegerv, GetBooleanv, GetFloatv, and GetDoublev.", "PARAMETER_BUFFER_BINDING_ARB"..0x80EF ) var src = GL43["MultiDrawArraysIndirect"] void( "MultiDrawArraysIndirectCountARB", """ Behaves similarly to #MultiDrawArraysIndirect(), except that {@code drawcount} defines an offset (in bytes) into the buffer object bound to the #PARAMETER_BUFFER_ARB binding point at which a single {@code sizei} typed value is stored, which contains the draw count. {@code maxdrawcount} specifies the maximum number of draws that are expected to be stored in the buffer. If the value stored at {@code drawcount} into the buffer is greater than {@code maxdrawcount}, an implementation stop processing draws after {@code maxdrawcount} parameter sets. {@code drawcount} must be a multiple of four. """, src["mode"], Check("maxdrawcount * (stride == 0 ? (4 * 4) : stride)")..MultiType( PointerMapping.DATA_INT )..RawPointer..void.const.p("indirect", "an array of structures containing the draw parameters"), GLintptr("drawcount", "the offset into the parameter buffer object"), GLsizei("maxdrawcount", "the maximum number of draws"), src["stride"] ) src = GL43["MultiDrawElementsIndirect"] void( "MultiDrawElementsIndirectCountARB", """ Behaves similarly to #MultiDrawElementsIndirect(), except that {@code drawcount} defines an offset (in bytes) into the buffer object bound to the #PARAMETER_BUFFER_ARB binding point at which a single {@code sizei} typed value is stored, which contains the draw count. {@code maxdrawcount} specifies the maximum number of draws that are expected to be stored in the buffer. If the value stored at {@code drawcount} into the buffer is greater than {@code maxdrawcount}, an implementation stop processing draws after {@code maxdrawcount} parameter sets. {@code drawcount} must be a multiple of four. """, src["mode"], src["type"], Check("maxdrawcount * (stride == 0 ? (5 * 4) : stride)")..MultiType( PointerMapping.DATA_INT )..RawPointer..void.const.p("indirect", "a structure containing an array of draw parameters"), GLintptr("drawcount", "the offset into the parameter buffer object"), GLsizei("maxdrawcount", "the maximum number of draws"), src["stride"] ) }
bsd-3-clause
f30103a320cc2c3869b931111d38b9af
55.609756
160
0.704374
4.829344
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/packet/PacketOutLoginEncryptionRequest.kt
1
2615
/* * Copyright (C) 2016-Present The MoonLake ([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.mcmoonlake.api.packet import com.mcmoonlake.api.security.RSAUtils import java.security.PublicKey import java.util.* data class PacketOutLoginEncryptionRequest( var serverId: String, var publicKey: PublicKey, var verifyToken: ByteArray ) : PacketOutBukkitAbstract("PacketLoginOutEncryptionBegin"), PacketLogin { @Deprecated("") constructor() : this("Unknown", EMPTY_KEY, byteArrayOf()) override fun read(data: PacketBuffer) { serverId = data.readString() publicKey = RSAUtils.decodePublicKey(data.readBytes(data.readVarInt())) verifyToken = data.readBytes(data.readVarInt()) } override fun write(data: PacketBuffer) { data.writeString(serverId) val encoded = publicKey.encoded data.writeVarInt(encoded.size) data.writeBytes(encoded) data.writeVarInt(verifyToken.size) data.writeBytes(verifyToken) } override fun equals(other: Any?): Boolean { if(other === this) return true if(other is PacketOutLoginEncryptionRequest) return super.equals(other) && serverId == other.serverId && publicKey == other.publicKey && Arrays.equals(verifyToken, other.verifyToken) return false } override fun hashCode(): Int { var result = super.hashCode() result = 31 * result + serverId.hashCode() result = 31 * result + publicKey.hashCode() result = 31 * result + Arrays.hashCode(verifyToken) return result } companion object { @JvmStatic private val EMPTY_KEY = object: PublicKey { override fun getAlgorithm(): String = "Empty" override fun getEncoded(): ByteArray = byteArrayOf() override fun getFormat(): String = "Empty" } } }
gpl-3.0
194d6d451f30a962a5330fea8d0bacc6
32.961039
149
0.658509
4.669643
false
false
false
false
Talentica/AndroidWithKotlin
app/src/main/java/com/talentica/androidkotlin/ProductFragment.kt
1
3440
/* * Copyright 2017, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.talentica.androidkotlin import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.fragment.app.Fragment import androidx.lifecycle.ViewModelProviders import com.talentica.androidkotlin.databinding.ProductFragmentBinding import com.talentica.androidkotlin.model.Comment import com.talentica.androidkotlin.ui.CommentAdapter import com.talentica.androidkotlin.ui.CommentClickCallback import com.talentica.androidkotlin.viewmodel.ProductViewModel class ProductFragment : Fragment() { private lateinit var mBinding: ProductFragmentBinding private var mCommentAdapter: CommentAdapter? = null override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // Inflate this data binding layout mBinding = DataBindingUtil.inflate(inflater, R.layout.product_fragment, container, false) // Create and set the adapter for the RecyclerView. mCommentAdapter = CommentAdapter(mCommentClickCallback) mBinding.commentList.adapter = mCommentAdapter return mBinding.root } private val mCommentClickCallback = object : CommentClickCallback { override fun onClick(comment: Comment?) { // no-op } } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) val factory = ProductViewModel.Factory( requireActivity().application, requireArguments().getInt(KEY_PRODUCT_ID) ) val model = ViewModelProviders.of(this, factory) .get(ProductViewModel::class.java) mBinding.productViewModel = model subscribeToModel(model) } private fun subscribeToModel(model: ProductViewModel) { // Observe product data model.observableProduct?.observe( viewLifecycleOwner, { productEntity -> model.setProduct(productEntity) }) // Observe comments model.comments?.observe(viewLifecycleOwner, { commentEntities -> if (commentEntities != null) { mBinding.isLoading = false mCommentAdapter!!.setCommentList(commentEntities) } else { mBinding.isLoading = true } }) } companion object { private const val KEY_PRODUCT_ID = "product_id" /** Creates product fragment for specific product ID */ fun forProduct(productId: Int): ProductFragment { val fragment = ProductFragment() val args = Bundle() args.putInt(KEY_PRODUCT_ID, productId) fragment.arguments = args return fragment } } }
apache-2.0
f65a1b2f44d920c5c6ccde9d26515f56
35.606383
97
0.695058
5.103858
false
false
false
false
nlgcoin/guldencoin-official
src/frontend/android/unity_wallet/app/src/main/java/com/gulden/unity_wallet/ui/monitor/NetworkMonitorActivity.kt
2
2525
// Copyright (c) 2018-2019 The Gulden developers // Authored by: Malcolm MacLeod ([email protected]), Willem de Jonge ([email protected]) // Distributed under the GULDEN software license, see the accompanying // file COPYING package com.gulden.unity_wallet.ui.monitor import android.os.Bundle import android.view.View import com.google.android.material.bottomnavigation.BottomNavigationView import com.gulden.unity_wallet.R import com.gulden.unity_wallet.UnityCore import com.gulden.unity_wallet.util.AppBaseActivity import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.Job class NetworkMonitorActivity : UnityCore.Observer, AppBaseActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_network_monitor) navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) syncProgress.max = 1000000 } override fun onDestroy() { super.onDestroy() coroutineContext[Job]!!.cancel() } override fun onStart() { super.onStart() UnityCore.instance.addObserver(this, fun (callback:() -> Unit) { runOnUiThread { callback() }}) if (supportFragmentManager.fragments.isEmpty()) { addFragment(PeerListFragment(), R.id.networkMonitorMainLayout) } } override fun onStop() { super.onStop() UnityCore.instance.removeObserver(this) } override fun onWalletReady() { setSyncProgress(UnityCore.instance.progressPercent) } fun onBackButtonPushed(view : View) { finish() } private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> val page = when (item.itemId) { R.id.navigation_peers -> PeerListFragment() R.id.navigation_blocks -> BlockListFragment() R.id.navigation_processing -> ProcessingFragment() else -> return@OnNavigationItemSelectedListener false } gotoFragment(page, R.id.networkMonitorMainLayout) true } override fun syncProgressChanged(percent: Float) { setSyncProgress(percent) } private fun setSyncProgress(percent: Float) { syncProgress.progress = (syncProgress.max * (percent/100)).toInt() if (percent < 100.0) syncProgress.visibility = View.VISIBLE else syncProgress.visibility = View.INVISIBLE } }
mit
57b9cc8c40807bed2cdfbea8dcc24855
29.421687
115
0.693069
4.728464
false
false
false
false
dahlstrom-g/intellij-community
plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogExtension.kt
5
5424
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.ui.cloneDialog import com.intellij.openapi.Disposable import com.intellij.openapi.application.ModalityState import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.vcs.ui.cloneDialog.VcsCloneDialogExtensionComponent import com.intellij.ui.components.ActionLink import com.intellij.ui.components.JBLabel import com.intellij.ui.components.JBPanel import com.intellij.ui.components.panels.HorizontalLayout import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.components.panels.Wrapper import com.intellij.util.ui.JBEmptyBorder import com.intellij.util.ui.JBFont import com.intellij.util.ui.JBUI.Borders.empty import com.intellij.util.ui.JBUI.Panels.simplePanel import com.intellij.util.ui.UIUtil.ComponentStyle import com.intellij.util.ui.UIUtil.getRegularPanelInsets import com.intellij.util.ui.cloneDialog.AccountMenuItem import org.jetbrains.plugins.github.api.GithubApiRequestExecutorManager import org.jetbrains.plugins.github.api.GithubServerPath import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.accounts.GithubAccountInformationProvider import org.jetbrains.plugins.github.authentication.accounts.isGHAccount import org.jetbrains.plugins.github.i18n.GithubBundle.message import org.jetbrains.plugins.github.util.CachingGHUserAvatarLoader import org.jetbrains.plugins.github.util.GithubUtil import javax.swing.JButton import javax.swing.JComponent import javax.swing.JPanel class GHCloneDialogExtension : BaseCloneDialogExtension() { override fun getName() = GithubUtil.SERVICE_DISPLAY_NAME override fun getAccounts(): Collection<GithubAccount> = GithubAuthenticationManager.getInstance().getAccounts().filter { it.isGHAccount } override fun createMainComponent(project: Project, modalityState: ModalityState): VcsCloneDialogExtensionComponent = GHCloneDialogExtensionComponent(project) } private class GHCloneDialogExtensionComponent(project: Project) : GHCloneDialogExtensionComponentBase( project, GithubAuthenticationManager.getInstance(), GithubApiRequestExecutorManager.getInstance() ) { override fun isAccountHandled(account: GithubAccount): Boolean = account.isGHAccount override fun createLoginPanel(account: GithubAccount?, cancelHandler: () -> Unit): JComponent = GHCloneDialogLoginPanel(account).apply { val chooseLoginUiHandler = { setChooseLoginUi() } loginPanel.setCancelHandler(if (getAccounts().isEmpty()) chooseLoginUiHandler else cancelHandler) }.also { Disposer.register(this, it) } override fun createAccountMenuLoginActions(account: GithubAccount?): Collection<AccountMenuItem.Action> = listOf(createLoginAction(account), createLoginWithTokenAction(account)) private fun createLoginAction(account: GithubAccount?): AccountMenuItem.Action { val isExistingAccount = account != null return AccountMenuItem.Action( message("login.via.github.action"), { switchToLogin(account) getLoginPanel()?.setOAuthLoginUi() }, showSeparatorAbove = !isExistingAccount ) } private fun createLoginWithTokenAction(account: GithubAccount?): AccountMenuItem.Action = AccountMenuItem.Action( message("login.with.token.action"), { switchToLogin(account) getLoginPanel()?.setTokenUi() } ) private fun getLoginPanel(): GHCloneDialogLoginPanel? = content as? GHCloneDialogLoginPanel } private class GHCloneDialogLoginPanel(account: GithubAccount?) : JBPanel<GHCloneDialogLoginPanel>(VerticalLayout(0)), Disposable { private val titlePanel = simplePanel().apply { val title = JBLabel(message("login.to.github"), ComponentStyle.LARGE).apply { font = JBFont.label().biggerOn(5.0f) } addToLeft(title) } private val contentPanel = Wrapper() private val chooseLoginUiPanel: JPanel = JPanel(HorizontalLayout(0)).apply { border = JBEmptyBorder(getRegularPanelInsets()) val loginViaGHButton = JButton(message("login.via.github.action")).apply { addActionListener { setOAuthLoginUi() } } val useTokenLink = ActionLink(message("link.label.use.token")) { setTokenUi() } add(loginViaGHButton) add(JBLabel(message("label.login.option.separator")).apply { border = empty(0, 6, 0, 4) }) add(useTokenLink) } val loginPanel = CloneDialogLoginPanel(account).apply { setServer(GithubServerPath.DEFAULT_HOST, false) }.also { Disposer.register(this, it) } init { add(titlePanel.apply { border = JBEmptyBorder(getRegularPanelInsets().apply { bottom = 0 }) }) add(contentPanel) setChooseLoginUi() } fun setChooseLoginUi() = setContent(chooseLoginUiPanel) fun setOAuthLoginUi() { setContent(loginPanel) loginPanel.setOAuthUi() } fun setTokenUi() { setContent(loginPanel) loginPanel.setTokenUi() // after `loginPanel` is set as content to ensure correct focus behavior } private fun setContent(content: JComponent) { contentPanel.setContent(content) revalidate() repaint() } override fun dispose() = Unit }
apache-2.0
5e23f034e95b5efc357b0a2800949b77
37.204225
140
0.775996
4.554156
false
false
false
false
TheMrMilchmann/lwjgl3
modules/lwjgl/openvr/src/templates/kotlin/openvr/OpenVRTypes.kt
1
44106
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package openvr import org.lwjgl.generator.* val OPENVR_API_BINDING = simpleBinding( Module.OPENVR, libraryExpression = """Configuration.OPENVR_LIBRARY_NAME.get(Platform.mapLibraryNameBundled("openvr_api"))""", bundledWithLWJGL = true ) val EVRApplicationError = "EVRApplicationError".enumType val EVRCompositorError = "EVRCompositorError".enumType val EVRFirmwareError = "EVRFirmwareError".enumType val EVRInitError = "EVRInitError".enumType val EVRNotificationError = "EVRNotificationError".enumType val EVROverlayError = "EVROverlayError".enumType val EVRRenderModelError = "EVRRenderModelError".enumType val EVRScreenshotError = "EVRScreenshotError".enumType val EVRSettingsError = "EVRSettingsError".enumType val EVRTrackedCameraError = "EVRTrackedCameraError".enumType val EVRInputError = "EVRInputError".enumType val EIOBufferError = "EIOBufferError".enumType val EVRSpatialAnchorError = "EVRSpatialAnchorError".enumType val EVRApplicationProperty = "EVRApplicationProperty".enumType val EVRApplicationType = "EVRApplicationType".enumType val EVRButtonId = "EVRButtonId".enumType val EVRCompositorTimingMode = "EVRCompositorTimingMode".enumType val EVRControllerAxisType = "EVRControllerAxisType".enumType val EVRDebugError = "EVRDebugError".enumType val EVREye = "EVREye".enumType val EVREventType = "EVREventType".enumType val EVRNotificationStyle = "EVRNotificationStyle".enumType val EVRNotificationType = "EVRNotificationType".enumType val EVROverlayIntersectionMaskPrimitiveType = "EVROverlayIntersectionMaskPrimitiveType".enumType val EVRRenderModelTextureFormat = "EVRRenderModelTextureFormat".enumType val EVRSceneApplicationState = "EVRSceneApplicationState".enumType val EVRScreenshotPropertyFilenames = "EVRScreenshotPropertyFilenames".enumType val EVRScreenshotType = "EVRScreenshotType".enumType val EVRSubmitFlags = "EVRSubmitFlags".enumType val EVRSummaryType = "EVRSummaryType".enumType val EVRTrackedCameraFrameType = "EVRTrackedCameraFrameType".enumType val EVRSkeletalTransformSpace = "EVRSkeletalTransformSpace".enumType val EVRSkeletalMotionRange = "EVRSkeletalMotionRange".enumType val EVRSkeletalReferencePose = "EVRSkeletalReferencePose".enumType val EVRSkeletalTrackingLevel = "EVRSkeletalTrackingLevel".enumType val ChaperoneCalibrationState = "ChaperoneCalibrationState".enumType val EBlockQueueError = "EBlockQueueError".enumType val EBlockQueueReadType = "EBlockQueueReadType".enumType val EChaperoneConfigFile = "EChaperoneConfigFile".enumType val EColorSpace = "EColorSpace".enumType val EDeviceActivityLevel = "EDeviceActivityLevel".enumType val EDeviceType = "EDeviceType".enumType val EGamepadTextInputMode = "EGamepadTextInputMode".enumType val EGamepadTextInputLineMode = "EGamepadTextInputLineMode".enumType val EHDCPError = "EHDCPError".enumType val EHiddenAreaMeshType = "EHiddenAreaMeshType".enumType val EIOBufferMode = "EIOBufferMode".enumType val EOverlayDirection = "EOverlayDirection".enumType val EPropertyWriteType = "EPropertyWriteType".enumType val EShowUIType = "EShowUIType".enumType val ETextureType = "ETextureType".enumType val ETrackedControllerRole = "ETrackedControllerRole".enumType val ETrackedDeviceClass = "ETrackedDeviceClass".enumType val ETrackedDeviceProperty = "ETrackedDeviceProperty".enumType val ETrackedPropertyError = "ETrackedPropertyError".enumType val ETrackingResult = "ETrackingResult".enumType val ETrackingUniverseOrigin = "ETrackingUniverseOrigin".enumType val HeadsetViewMode_t = "HeadsetViewMode_t".enumType val VRMessageOverlayResponse = "VRMessageOverlayResponse".enumType val VROverlayFlags = "VROverlayFlags".enumType val VROverlayInputMethod = "VROverlayInputMethod".enumType val VROverlayTransformType = "VROverlayTransformType".enumType val PropertyContainerHandle_t = typedef(uint64_t, "PropertyContainerHandle_t") val PropertyTypeTag_t = typedef(uint32_t, "PropertyTypeTag_t") val DriverHandle_t = typedef(PropertyContainerHandle_t, "DriverHandle_t") val VRActionHandle_t = typedef(uint64_t, "VRActionHandle_t") val VRActionSetHandle_t = typedef(uint64_t, "VRActionSetHandle_t") val VRInputValueHandle_t = typedef(uint64_t, "VRInputValueHandle_t") val ScreenshotHandle_t = typedef(uint32_t, "ScreenshotHandle_t") val TextureID_t = typedef(int32_t, "TextureID_t") val TrackedCameraHandle_t = typedef(uint64_t, "TrackedCameraHandle_t") val TrackedDeviceIndex_t = typedef(uint32_t, "TrackedDeviceIndex_t") val WebConsoleHandle_t = typedef(uint64_t, "WebConsoleHandle_t") val DriverId_t = typedef(uint32_t, "DriverId_t") val PathHandle_t = typedef(uint64_t, "PathHandle_t") val VRComponentProperties = typedef(uint32_t, "VRComponentProperties") val VRNotificationId = typedef(uint32_t, "VRNotificationId") val VROverlayHandle_t = typedef(uint64_t, "VROverlayHandle_t") val BoneIndex_t = typedef(int32_t, "BoneIndex_t") val IOBufferHandle_t = typedef(uint64_t, "IOBufferHandle_t") val VrProfilerEventHandle_t = typedef(uint64_t, "VrProfilerEventHandle_t") val SpatialAnchorHandle_t = typedef(uint32_t, "SpatialAnchorHandle_t") val glSharedTextureHandle_t = typedef(opaque_p, "glSharedTextureHandle_t") val glInt_t = typedef(int32_t, "glInt_t") val glUInt_t = typedef(uint32_t, "glUInt_t") val VkInstance_T = "VkInstance_T".opaque val VkPhysicalDevice_T = "VkPhysicalDevice_T".opaque val VkDevice_T = "VkDevice_T".opaque val VkQueue_T = "VkQueue_T".opaque val HmdMatrix34_t = struct(Module.OPENVR, "HmdMatrix34", nativeName = "HmdMatrix34_t") { float("m", "")[3 x 4] } val HmdMatrix33_t = struct(Module.OPENVR, "HmdMatrix33", nativeName = "HmdMatrix33_t") { float("m", "")[3 x 3] } val HmdMatrix44_t = struct(Module.OPENVR, "HmdMatrix44", nativeName = "HmdMatrix44_t") { float("m", "")[4 x 4] } val HmdVector3_t = struct(Module.OPENVR, "HmdVector3", nativeName = "HmdVector3_t") { float("v", "")[3] } val HmdVector4_t = struct(Module.OPENVR, "HmdVector4", nativeName = "HmdVector4_t") { float("v", "")[4] } val HmdVector3d_t = struct(Module.OPENVR, "HmdVector3d", nativeName = "HmdVector3d_t") { double("v", "")[3] } val HmdVector2_t = struct(Module.OPENVR, "HmdVector2", nativeName = "HmdVector2_t") { float("v", "")[2] } val HmdQuaternion_t = struct(Module.OPENVR, "HmdQuaternion", nativeName = "HmdQuaternion_t") { double("w", "") double("x", "") double("y", "") double("z", "") } val HmdQuaternionf_t = struct(Module.OPENVR, "HmdQuaternionf", nativeName = "HmdQuaternionf_t") { float("w", "") float("x", "") float("y", "") float("z", "") } val HmdColor_t = struct(Module.OPENVR, "HmdColor", nativeName = "HmdColor_t") { float("r", "") float("g", "") float("b", "") float("a", "") } val HmdQuad_t = struct(Module.OPENVR, "HmdQuad", nativeName = "HmdQuad_t") { HmdVector3_t("vCorners", "")[4] } val HmdRect2_t = struct(Module.OPENVR, "HmdRect2", nativeName = "HmdRect2_t") { HmdVector2_t("vTopLeft", "") HmdVector2_t("vBottomRight", "") } val DistortionCoordinates_t = struct(Module.OPENVR, "DistortionCoordinates", nativeName = "DistortionCoordinates_t", mutable = false) { documentation = """ Used to return the post-distortion UVs for each color channel. UVs range from 0 to 1 with 0,0 in the upper left corner of the source render target. The 0,0 to 1,1 range covers a single eye. """ float("rfRed", "the UVs for the red channel")[2] float("rfGreen", "the UVs for the green channel")[2] float("rfBlue", "the UVs for the blue channel")[2] } val Texture_t = struct(Module.OPENVR, "Texture", nativeName = "Texture_t") { opaque_p("handle", "") // See ETextureType definition above ETextureType("eType", "").links("ETextureType_\\w+") EColorSpace("eColorSpace", "").links("EColorSpace_\\w+") } val TrackedDevicePose_t = struct(Module.OPENVR, "TrackedDevicePose", nativeName = "TrackedDevicePose_t") { documentation = "Describes a single pose for a tracked object." HmdMatrix34_t("mDeviceToAbsoluteTracking", "") HmdVector3_t("vVelocity", "velocity in tracker space in m/s") HmdVector3_t("vAngularVelocity", "angular velocity in radians/s") ETrackingResult("eTrackingResult", "").links("ETrackingResult_\\w+") bool("bPoseIsValid", "") bool( "bDeviceIsConnected", "This indicates that there is a device connected for this spot in the pose array. It could go from true to false if the user unplugs the device." ) } val VRTextureBounds_t = struct(Module.OPENVR, "VRTextureBounds", nativeName = "VRTextureBounds_t") { documentation = "Allows the application to control what part of the provided texture will be used in the frame buffer." float("uMin", "") float("vMin", "") float("uMax", "") float("vMax", "") } val VRTextureWithPose_t = struct(Module.OPENVR, "VRTextureWithPose", nativeName = "VRTextureWithPose_t") { documentation = "Allows specifying pose used to render provided scene texture (if different from value returned by #WaitGetPoses())." opaque_p("handle", "") ETextureType("eType", "") EColorSpace("eColorSpace", "") HmdMatrix34_t("mDeviceToAbsoluteTracking", "actual pose used to render scene textures") } val VRTextureDepthInfo_t = struct(Module.OPENVR, "VRTextureDepthInfo", nativeName = "VRTextureDepthInfo_t") { documentation = "" opaque_p("handle", "") HmdMatrix44_t("mProjection", "") HmdVector2_t("vRange", "") } val VRTextureWithDepth_t = struct(Module.OPENVR, "VRTextureWithDepth", nativeName = "VRTextureWithDepth_t") { documentation = "" opaque_p("handle", "") ETextureType("eType", "") EColorSpace("eColorSpace", "") VRTextureDepthInfo_t("depth", "") } val VRTextureWithPoseAndDepth_t = struct(Module.OPENVR, "VRTextureWithPoseAndDepth", nativeName = "VRTextureWithPoseAndDepth_t") { documentation = "" opaque_p("handle", "") ETextureType("eType", "") EColorSpace("eColorSpace", "") HmdMatrix34_t("mDeviceToAbsoluteTracking", "") VRTextureDepthInfo_t("depth", "") } val VRVulkanTextureData_t = struct(Module.OPENVR, "VRVulkanTextureData", nativeName = "VRVulkanTextureData_t") { documentation = """ Data required for passing Vulkan textures to #Submit(). Be sure to call #ShutdownInternal() before destroying these resources. Please see <a href="https://github.com/ValveSoftware/openvr/wiki/Vulkan">https://github.com/ValveSoftware/openvr/wiki/Vulkan</a> for Vulkan-specific documentation. """ uint64_t("m_nImage", "VkImage") VkDevice_T.p("m_pDevice", "") VkPhysicalDevice_T.p("m_pPhysicalDevice", "") VkInstance_T.p("m_pInstance", "") VkQueue_T.p("m_pQueue", "") uint32_t("m_nQueueFamilyIndex", "") uint32_t("m_nWidth", "") uint32_t("m_nHeight", "") uint32_t("m_nFormat", "") uint32_t("m_nSampleCount", "") } val VRVulkanTextureArrayData_t = struct(Module.OPENVR, "VRVulkanTextureArrayData", nativeName = "VRVulkanTextureArrayData_t") { documentation = """ Data required for passing Vulkan textures to #Submit(). Be sure to call #ShutdownInternal() before destroying these resources. Please see <a href="https://github.com/ValveSoftware/openvr/wiki/Vulkan">https://github.com/ValveSoftware/openvr/wiki/Vulkan</a> for Vulkan-specific documentation. """ uint32_t("m_unArrayIndex", "") uint32_t("m_unArraySize", "") } val VREvent_Controller_t = struct(Module.OPENVR, "VREventController", nativeName = "VREvent_Controller_t", mutable = false) { documentation = "Used for controller button events." uint32_t("button", "").links("EVRButtonId_\\w+") } val VREvent_Mouse_t = struct(Module.OPENVR, "VREventMouse", nativeName = "VREvent_Mouse_t", mutable = false) { documentation = "Used for simulated mouse events in overlay space." float("x", "coords are in GL space, bottom left of the texture is 0,0") float("y", "") uint32_t("button", "").links("EVRMouseButton_\\w+") } val VREvent_Scroll_t = struct(Module.OPENVR, "VREventScroll", nativeName = "VREvent_Scroll_t", mutable = false) { documentation = "Used for simulated mouse wheel scroll." float("xdelta", "movement in fraction of the pad traversed since last delta, 1.0 for a full swipe") float("ydelta", "") uint32_t("unused", "") float( "viewportscale", "for scrolling on an overlay with laser mouse, this is the overlay's vertical size relative to the overlay height. Range: {@code [0,1]}" ) } val VREvent_Process_t = struct(Module.OPENVR, "VREventProcess", nativeName = "VREvent_Process_t", mutable = false) { documentation = "Used for events about processes." uint32_t("pid", "") uint32_t("oldPid", "") bool("bForced", "") bool("bConnectionLost", "if the associated event was triggered by a connection loss") } val VREvent_Notification_t = struct(Module.OPENVR, "VREventNotification", nativeName = "VREvent_Notification_t", mutable = false) { documentation = "Notification related events. Details will still change at this point." uint64_t("ulUserValue", "") uint32_t("notificationId", "") } val VREvent_Overlay_t = struct(Module.OPENVR, "VREventOverlay", nativeName = "VREvent_Overlay_t", mutable = false) { documentation = "Used for a few events about overlays." uint64_t("overlayHandle", "").links("EVRState_\\w+") uint64_t("devicePath", "") uint64_t("memoryBlockId", "") } val VREvent_Status_t = struct(Module.OPENVR, "VREventStatus", nativeName = "VREvent_Status_t", mutable = false) { documentation = "Used for a few events about overlays." uint32_t("statusState", "") } val VREvent_Keyboard_t = struct(Module.OPENVR, "VREventKeyboard", nativeName = "VREvent_Keyboard_t", mutable = false) { documentation = "Used for keyboard events." char("cNewInput", "up to 8 bytes of new input")[8] uint64_t("uUserValue", "possible flags about the new input") } val VREvent_Ipd_t = struct(Module.OPENVR, "VREventIpd", nativeName = "VREvent_Ipd_t", mutable = false) { float("ipdMeters", "") } val VREvent_Chaperone_t = struct(Module.OPENVR, "VREventChaperone", nativeName = "VREvent_Chaperone_t", mutable = false) { uint64_t("m_nPreviousUniverse", "") uint64_t("m_nCurrentUniverse", "") } val VREvent_Reserved_t = struct(Module.OPENVR, "VREventReserved", nativeName = "VREvent_Reserved_t", mutable = false) { documentation = "Not actually used for any events." uint64_t("reserved0", "") uint64_t("reserved1", "") uint64_t("reserved2", "") uint64_t("reserved3", "") uint64_t("reserved4", "") uint64_t("reserved5", "") } val VREvent_PerformanceTest_t = struct(Module.OPENVR, "VREventPerformanceTest", nativeName = "VREvent_PerformanceTest_t", mutable = false) { uint32_t("m_nFidelityLevel", "") } val VREvent_TouchPadMove_t = struct(Module.OPENVR, "VREventTouchPadMove", nativeName = "VREvent_TouchPadMove_t", mutable = false) { documentation = """ When in mouse input mode you can receive data from the touchpad, these events are only sent if the users finger is on the touchpad (or just released from it). These events are sent to overlays with the #VROverlayFlags_SendVRTouchpadEvents flag set. """ bool("bFingerDown", "true if the users finger is detected on the touch pad") float("flSecondsFingerDown", "how long the finger has been down in seconds") float("fValueXFirst", "these values indicate the starting finger position (so you can do some basic swipe stuff)") float("fValueYFirst", "") float("fValueXRaw", "this is the raw sampled coordinate without deadzoning") float("fValueYRaw", "") } val VREvent_SeatedZeroPoseReset_t = struct(Module.OPENVR, "VREventSeatedZeroPoseReset", nativeName = "VREvent_SeatedZeroPoseReset_t", mutable = false) { bool("bResetBySystemMenu", "") } val VREvent_Screenshot_t = struct(Module.OPENVR, "VREventScreenshot", nativeName = "VREvent_Screenshot_t", mutable = false) { uint32_t("handle", "") uint32_t("type", "") } val VREvent_ScreenshotProgress_t = struct(Module.OPENVR, "VREventScreenshotProgress", nativeName = "VREvent_ScreenshotProgress_t", mutable = false) { float("progress", "") } val VREvent_ApplicationLaunch_t = struct(Module.OPENVR, "VREventApplicationLaunch", nativeName = "VREvent_ApplicationLaunch_t", mutable = false) { uint32_t("pid", "") uint32_t("unArgsHandle", "") } val VREvent_EditingCameraSurface_t = struct(Module.OPENVR, "VREventEditingCameraSurface", nativeName = "VREvent_EditingCameraSurface_t", mutable = false) { uint64_t("overlayHandle", "") uint32_t("nVisualMode", "") } val VREvent_MessageOverlay_t = struct(Module.OPENVR, "VREventMessageOverlay", nativeName = "VREvent_MessageOverlay_t", mutable = false) { uint32_t("unVRMessageOverlayResponse", "").links("VRMessageOverlayResponse_\\w+") } val VREvent_Property_t = struct(Module.OPENVR, "VREventProperty", nativeName = "VREvent_Property_t", mutable = false) { PropertyContainerHandle_t("container", "") ETrackedDeviceProperty("prop", "").links("ETrackedDeviceProperty_\\w+") } val VREvent_HapticVibration_t = struct(Module.OPENVR, "VREventHapticVibration", nativeName = "VREvent_HapticVibration_t", mutable = false) { uint64_t("containerHandle", "property container handle of the device with the haptic component") uint64_t("componentHandle", "which haptic component needs to vibrate") float("fDurationSeconds", "") float("fFrequency", "") float("fAmplitude", "") } val VREvent_WebConsole_t = struct(Module.OPENVR, "VREventWebConsole", nativeName = "VREvent_WebConsole_t", mutable = false) { WebConsoleHandle_t("webConsoleHandle", "") } val VREvent_InputBindingLoad_t = struct(Module.OPENVR, "VREventInputBindingLoad", nativeName = "VREvent_InputBindingLoad_t", mutable = false) { PropertyContainerHandle_t("ulAppContainer", "") uint64_t("pathMessage", "") uint64_t("pathUrl", "") uint64_t("pathControllerType", "") } val VREvent_InputActionManifestLoad_t = struct(Module.OPENVR, "VREventInputActionManifestLoad", nativeName = "VREvent_InputActionManifestLoad_t", mutable = false) { uint64_t("pathAppKey", "") uint64_t("pathMessage", "") uint64_t("pathMessageParam", "") uint64_t("pathManifestPath", "") } val VREvent_SpatialAnchor_t = struct(Module.OPENVR, "VREventSpatialAnchor", nativeName = "VREvent_SpatialAnchor_t", mutable = false) { SpatialAnchorHandle_t("unHandle", "") } val VREvent_ProgressUpdate_t = struct(Module.OPENVR, "VREventProgressUpdate", nativeName = "VREvent_ProgressUpdate_t", mutable = false) { uint64_t("ulApplicationPropertyContainer", "") uint64_t("pathDevice", "") uint64_t("pathInputSource", "") uint64_t("pathProgressAction", "") uint64_t("pathIcon", "") float("fProgress", "") } val VREvent_ShowUI_t = struct(Module.OPENVR, "VREventShowUI", nativeName = "VREvent_ShowUI_t", mutable = false) { EShowUIType("eType", "") } val VREvent_ShowDevTools_t = struct(Module.OPENVR, "VREventShowDevTools", nativeName = "VREvent_ShowDevTools_t", mutable = false) { int32_t("nBrowserIdentifier", "") } val VREvent_HDCPError_t = struct(Module.OPENVR, "VREventHDCPError", nativeName = "VREvent_HDCPError_t", mutable = false) { EHDCPError("eCode", "") } val VREvent_Data_t = union(Module.OPENVR, "VREventData", nativeName = "VREvent_Data_t", mutable = false) { VREvent_Reserved_t("reserved", "") VREvent_Controller_t("controller", "") VREvent_Mouse_t("mouse", "") VREvent_Scroll_t("scroll", "") VREvent_Process_t("process", "") VREvent_Notification_t("notification", "") VREvent_Overlay_t("overlay", "") VREvent_Status_t("status", "") VREvent_Keyboard_t("keyboard", "") VREvent_Ipd_t("ipd", "") VREvent_Chaperone_t("chaperone", "") VREvent_PerformanceTest_t("performanceTest", "") VREvent_TouchPadMove_t("touchPadMove", "") VREvent_SeatedZeroPoseReset_t("seatedZeroPoseReset", "") VREvent_Screenshot_t("screenshot", "") VREvent_ScreenshotProgress_t("screenshotProgress", "") VREvent_ApplicationLaunch_t("applicationLaunch", "") VREvent_EditingCameraSurface_t("cameraSurface", "") VREvent_MessageOverlay_t("messageOverlay", "") VREvent_Property_t("property", "") VREvent_HapticVibration_t("hapticVibration", "") VREvent_WebConsole_t("webConsole", "") VREvent_InputBindingLoad_t("inputBinding", "") VREvent_InputActionManifestLoad_t("actionManifest", "") VREvent_SpatialAnchor_t("spatialAnchor", "") } val VREvent_t = struct(Module.OPENVR, "VREvent", nativeName = "VREvent_t", mutable = false) { documentation = "An event posted by the server to all running applications." pack("Platform.get() == Platform.LINUX || Platform.get() == Platform.MACOSX ? 4 : DEFAULT_PACK_ALIGNMENT") uint32_t("eventType", "the type of the event").links("EVREventType_\\w+") TrackedDeviceIndex_t( "trackedDeviceIndex", "the tracked device index of the event. For events that aren't connected to a tracked device this is #k_unTrackedDeviceIndexInvalid." ) float("eventAgeSeconds", "the age of the event in seconds") VREvent_Data_t( "data", """ more information about the event. This is a union of several structs. See the event type enum for information about which union member to look at for each event. """ ) } val IntersectionMaskRectangle_t = struct(Module.OPENVR, "IntersectionMaskRectangle", nativeName = "IntersectionMaskRectangle_t") { float("m_flTopLeftX", "") float("m_flTopLeftY", "") float("m_flWidth", "") float("m_flHeight", "") } val IntersectionMaskCircle_t = struct(Module.OPENVR, "IntersectionMaskCircle", nativeName = "IntersectionMaskCircle_t") { float("m_flCenterX", "") float("m_flCenterY", "") float("m_flRadius", "") } val VROverlayProjection_t = struct(Module.OPENVR, "VROverlayProjection", nativeName = "VROverlayProjection_t") { documentation = "Defines the project used in an overlay that is using #SetOverlayTransformProjection()." float("fLeft", "tangent of the left side of the frustum") float("fRight", "tangent of the right side of the frustum") float("fTop", "tangent of the top side of the frustum") float("fBottom", "tangent of the bottom side of the frustum") } val VROverlayView_t = struct(Module.OPENVR, "VROverlayView_t", mutable = false) { VROverlayHandle_t("overlayHandle", "") Texture_t("texture", "") VRTextureBounds_t("textureBounds", "") } val VRVulkanDevice_t = struct(Module.OPENVR, "VRVulkanDevice", nativeName = "VRVulkanDevice_t") { VkInstance_T.p("m_pInstance", "") VkDevice_T.p("m_pDevice", "") VkPhysicalDevice_T.p("m_pPhysicalDevice", "") VkQueue_T.p("m_pQueue", "") uint32_t("m_uQueueFamilyIndex", "") } val VRNativeDevice_t = struct(Module.OPENVR, "VRNativeDevice", nativeName = "VRNativeDevice_t") { opaque_p("handle", "") EDeviceType("eType", "", ) } val VROverlayIntersectionMaskPrimitive_Data_t = union(Module.OPENVR, "VROverlayIntersectionMaskPrimitiveData", nativeName = "VROverlayIntersectionMaskPrimitive_Data_t") { IntersectionMaskRectangle_t("m_Rectangle", "") IntersectionMaskCircle_t("m_Circle", "") } val VROverlayIntersectionMaskPrimitive_t = struct(Module.OPENVR, "VROverlayIntersectionMaskPrimitive", nativeName = "VROverlayIntersectionMaskPrimitive_t") { EVROverlayIntersectionMaskPrimitiveType("m_nPrimitiveType", "") VROverlayIntersectionMaskPrimitive_Data_t("m_Primitive", "") } val HiddenAreaMesh_t = struct(Module.OPENVR, "HiddenAreaMesh", nativeName = "HiddenAreaMesh_t", mutable = false) { documentation = """ The mesh to draw into the stencil (or depth) buffer to perform early stencil (or depth) kills of pixels that will never appear on the HMD. This mesh draws on all the pixels that will be hidden after distortion. If the HMD does not provide a visible area mesh {@code pVertexData} will be #NULL and {@code unTriangleCount} will be 0. """ HmdVector2_t.p("pVertexData", "") AutoSize("pVertexData", optional = true)..uint32_t("unTriangleCount", "") } val VRControllerAxis_t = struct(Module.OPENVR, "VRControllerAxis", nativeName = "VRControllerAxis_t") { documentation = "Contains information about one axis on the controller." float("x", "Ranges from -1.0 to 1.0 for joysticks and track pads. Ranges from 0.0 to 1.0 for triggers were 0 is fully released.") float("y", "Ranges from -1.0 to 1.0 for joysticks and track pads. Is always 0.0 for triggers.") } val VRControllerState_t = struct(Module.OPENVR, "VRControllerState", nativeName = "VRControllerState_t") { documentation = "Holds all the state of a controller at one moment in time." uint32_t( "unPacketNum", "If packet num matches that on your prior call, then the controller state hasn't been changed since your last call and there is no need to process it." ) uint64_t("ulButtonPressed", "bit flags for each of the buttons. Use {@code ButtonMaskFromId} to turn an ID into a mask") uint64_t("ulButtonTouched", "") VRControllerAxis_t("rAxis", "axis data for the controller's analog inputs")[5] } val VRBoneTransform_t = struct(Module.OPENVR, "VRBoneTransform", nativeName = "VRBoneTransform_t", mutable = false) { documentation = "Holds the transform for a single bone." HmdVector4_t("position", "") HmdQuaternionf_t("orientation", "") } val Compositor_FrameTiming = struct(Module.OPENVR, "CompositorFrameTiming", nativeName = "Compositor_FrameTiming", mutable = false) { documentation = "Provides a single frame's timing information to the app." uint32_t("m_nSize", "Set to {@code sizeof( Compositor_FrameTiming )}") uint32_t("m_nFrameIndex", "") uint32_t("m_nNumFramePresents", "number of times this frame was presented") uint32_t("m_nNumMisPresented", "number of times this frame was presented on a vsync other than it was originally predicted to") uint32_t("m_nNumDroppedFrames", "number of additional times previous frame was scanned out") uint32_t("m_nReprojectionFlags", "") double("m_flSystemTimeInSeconds", "Absolute time reference for comparing frames. This aligns with the vsync that running start is relative to.") /** These times may include work from other processes due to OS scheduling. * The fewer packets of work these are broken up into, the less likely this will happen. * GPU work can be broken up by calling Flush. This can sometimes be useful to get the GPU started * processing that work earlier in the frame. */ float("m_flPreSubmitGpuMs", "time spent rendering the scene (gpu work submitted between WaitGetPoses and second Submit)") float("m_flPostSubmitGpuMs", "additional time spent rendering by application (e.g. companion window)") float("m_flTotalRenderGpuMs", "time between work submitted immediately after present (ideally vsync) until the end of compositor submitted work") float("m_flCompositorRenderGpuMs", "time spend performing distortion correction, rendering chaperone, overlays, etc.") float("m_flCompositorRenderCpuMs", "time spent on cpu submitting the above work for this frame") float("m_flCompositorIdleCpuMs", "time spent waiting for running start (application could have used this much more time)") /** Miscellaneous measured intervals. */ float("m_flClientFrameIntervalMs", "time between calls to #WaitGetPoses()") float("m_flPresentCallCpuMs", "time blocked on call to present (usually 0.0, but can go long)") float("m_flWaitForPresentCpuMs", "time spent spin-waiting for frame index to change (not near-zero indicates wait object failure)") float("m_flSubmitFrameMs", "time spent in #Submit() (not near-zero indicates driver issue)") /** The following are all relative to this frame's SystemTimeInSeconds */ float("m_flWaitGetPosesCalledMs", "") float("m_flNewPosesReadyMs", "") float("m_flNewFrameReadyMs", "second call to #Submit()") float("m_flCompositorUpdateStartMs", "") float("m_flCompositorUpdateEndMs", "") float("m_flCompositorRenderStartMs", "") TrackedDevicePose_t("m_HmdPose", "pose used by app to render this frame") uint32_t("m_nNumVSyncsReadyForUse", "") uint32_t("m_nNumVSyncsToFirstView", "") } val Compositor_CumulativeStats = struct(Module.OPENVR, "CompositorCumulativeStats", nativeName = "Compositor_CumulativeStats", mutable = false) { documentation = """ Cumulative stats for current application. These are not cleared until a new app connects, but they do stop accumulating once the associated app disconnects. """ uint32_t("m_nPid", "Process id associated with these stats (may no longer be running).") uint32_t("m_nNumFramePresents", "total number of times we called present (includes reprojected frames)") uint32_t("m_nNumDroppedFrames", "total number of times an old frame was re-scanned out (without reprojection)") uint32_t("m_nNumReprojectedFrames", "total number of times a frame was scanned out a second time (with reprojection)") /** Values recorded at startup before application has fully faded in the first time. */ uint32_t("m_nNumFramePresentsOnStartup", "") uint32_t("m_nNumDroppedFramesOnStartup", "") uint32_t("m_nNumReprojectedFramesOnStartup", "") /** Applications may explicitly fade to the compositor. This is usually to handle level transitions, and loading often causes * system wide hitches. The following stats are collected during this period. Does not include values recorded during startup. */ uint32_t("m_nNumLoading", "") uint32_t("m_nNumFramePresentsLoading", "") uint32_t("m_nNumDroppedFramesLoading", "") uint32_t("m_nNumReprojectedFramesLoading", "") /** If we don't get a new frame from the app in less than 2.5 frames, then we assume the app has hung and start * fading back to the compositor. The following stats are a result of this, and are a subset of those recorded above. * Does not include values recorded during start up or loading. */ uint32_t("m_nNumTimedOut", "") uint32_t("m_nNumFramePresentsTimedOut", "") uint32_t("m_nNumDroppedFramesTimedOut", "") uint32_t("m_nNumReprojectedFramesTimedOut", "") } val Compositor_StageRenderSettings = struct(Module.OPENVR, "CompositorStageRenderSettings", nativeName = "Compositor_StageRenderSettings", mutable = false) { HmdColor_t("m_PrimaryColor", "Primary color is applied as a tint to (i.e. multiplied with) the model's texture.") HmdColor_t("m_SecondaryColor", "") float( "m_flVignetteInnerRadius", "Vignette radius is in meters and is used to fade to the specified secondary solid color over that 3D distance from the origin of the playspace." ) float("m_flVignetteOuterRadius", "") float( "m_flFresnelStrength", """ Fades to the secondary color based on view incidence. This variable controls the linearity of the effect. It is mutually exclusive with vignette. Additionally, it treats the mesh as faceted. """ ) bool("m_bBackfaceCulling", "Controls backface culling.") bool( "m_bGreyscale", """ Converts the render model's texture to luma and applies to rgb equally. This is useful to combat compression artifacts that can occur on desaturated source material. """ ) bool("m_bWireframe", "Renders mesh as a wireframe.") } val NotificationBitmap_t = struct(Module.OPENVR, "NotificationBitmap", nativeName = "NotificationBitmap_t") { documentation = "Used for passing graphic data." void.p("m_pImageData", "") int32_t("m_nWidth", "") int32_t("m_nHeight", "") int32_t("m_nBytesPerPixel", "") } val InputAnalogActionData_t = struct(Module.OPENVR, "InputAnalogActionData", nativeName = "InputAnalogActionData_t", mutable = false) { bool("bActive", "whether or not this action is currently available to be bound in the active action set") VRInputValueHandle_t("activeOrigin", "the origin that caused this action's current state") float("x", "the current state of this action; will be delta updates for mouse actions") float("y", "the current state of this action; will be delta updates for mouse actions") float("z", "the current state of this action; will be delta updates for mouse actions") float("deltaX", "teltas since the previous call to #UpdateActionState()") float("deltaY", "teltas since the previous call to #UpdateActionState()") float("deltaZ", "teltas since the previous call to #UpdateActionState()") float("fUpdateTime", "time relative to now when this event happened. Will be negative to indicate a past time") } val InputDigitalActionData_t = struct(Module.OPENVR, "InputDigitalActionData", nativeName = "InputDigitalActionData_t", mutable = false) { bool("bActive", "whether or not this action is currently available to be bound in the active action set") VRInputValueHandle_t("activeOrigin", "the origin that caused this action's current state") bool("bState", "the current state of this action; will be true if currently pressed") bool("bChanged", "this is true if the state has changed since the last frame") float("fUpdateTime", "time relative to now when this event happened. Will be negative to indicate a past time.") } val InputPoseActionData_t = struct(Module.OPENVR, "InputPoseActionData", nativeName = "InputPoseActionData_t", mutable = false) { bool("bActive", "whether or not this action is currently available to be bound in the active action set") VRInputValueHandle_t("activeOrigin", "the origin that caused this action's current state") TrackedDevicePose_t("pose", "the current state of this action") } val InputSkeletalActionData_t = struct(Module.OPENVR, "InputSkeletalActionData", nativeName = "InputSkeletalActionData_t", mutable = false) { bool("bActive", "whether or not this action is currently available to be bound in the active action set") VRInputValueHandle_t("activeOrigin", "the origin that caused this action's current state") } val InputOriginInfo_t = struct(Module.OPENVR, "InputOriginInfo", nativeName = "InputOriginInfo_t", mutable = false) { VRInputValueHandle_t("devicePath", "") TrackedDeviceIndex_t("trackedDeviceIndex", "") charUTF8("rchRenderModelComponentName", "")[128] } val InputBindingInfo_t = struct(Module.OPENVR, "InputBindingInfo", nativeName = "InputBindingInfo_t", mutable = false) { charASCII("rchDevicePathName", "")[128] charASCII("rchInputPathName", "")[128] charASCII("rchModeName", "")[128] charASCII("rchSlotName", "")[128] charASCII("rchInputSourceType", "")[32] } val VRActiveActionSet_t = struct(Module.OPENVR, "VRActiveActionSet", nativeName = "VRActiveActionSet_t") { VRActionSetHandle_t("ulActionSet", "this is the handle of the action set to activate for this frame") VRInputValueHandle_t( "ulRestrictedToDevice", "this is the handle of a device path that this action set should be active for. To activate for all devices, set this to #k_ulInvalidInputValueHandle.") VRActionSetHandle_t( "ulSecondaryActionSet", """ the action set to activate for all devices other than {@code ulRestrictedDevice}. If {@code ulRestrictedToDevice} is set to #k_ulInvalidInputValueHandle, this parameter is ignored. """ ) padding(4) int32_t( "nPriority", """ the priority of this action set relative to other action sets. Any inputs bound to a source (e.g. trackpad, joystick, trigger) will disable bindings in other active action sets with a smaller priority. Overlay applications (i.e. ApplicationType_Overlay) may set their action set priority to a value between #k_nActionSetOverlayGlobalPriorityMin and #k_nActionSetOverlayGlobalPriorityMax to cause any inputs bound to a source used by that action set to be disabled in scene applications. No action set priority may value may be larger than #k_nActionSetPriorityReservedMin. """ ) } val VRSkeletalSummaryData_t = struct(Module.OPENVR, "VRSkeletalSummaryData", nativeName = "VRSkeletalSummaryData_t", mutable = false) { documentation = "Contains summary information about the current skeletal pose." float( "flFingerCurl", """ The amount that each finger is 'curled' inwards towards the palm. In the case of the thumb, this represents how much the thumb is wrapped around the fist. 0 means straight, 1 means fully curled. """ )[5] float( "flFingerSplay", """ The amount that each pair of adjacent fingers are separated. 0 means the digits are touching, 1 means they are fully separated. """ )[4] } val SpatialAnchorPose_t = struct(Module.OPENVR, "SpatialAnchorPose", nativeName = "SpatialAnchorPose_t", mutable = false) { HmdMatrix34_t("mAnchorToAbsoluteTracking", "") } /*val PropertyWrite_t = struct(Module.OPENVR, "PropertyWrite", nativeName = "PropertyWrite_t") { ETrackedDeviceProperty("prop", "").links("ETrackedDeviceProperty_\\w+") EPropertyWriteType("writeType", "").links("EPropertyWriteType_\\w+") ETrackedPropertyError("eSetError", "").links("ETrackedPropertyError_\\w+") void.p("pvBuffer", ""); AutoSize("pvBuffer")..uint32_t("unBufferSize", "") PropertyTypeTag_t("unTag", "") ETrackedPropertyError("eError", "").links("ETrackedPropertyError_\\w+") } val PropertyRead_t = struct(Module.OPENVR, "PropertyRead", nativeName = "PropertyRead_t") { ETrackedDeviceProperty("prop", "").links("ETrackedDeviceProperty_\\w+") void.p("pvBuffer", ""); AutoSize("pvBuffer")..uint32_t("unBufferSize", "") PropertyTypeTag_t("unTag", "") uint32_t("unRequiredBufferSize", "") ETrackedPropertyError("eError", "").links("ETrackedPropertyError_\\w+") } val CVRPropertyHelpers = struct(Module.OPENVR, "CVRPropertyHelpers", mutable = false) { intptr_t("m_pProperties", "") } val PathWrite_t = struct(Module.OPENVR, "PathWrite", nativeName = "PathWrite_t") { PathHandle_t("ulPath", "") EPropertyWriteType("writeType", "").links("EPropertyWriteType_\\w+") ETrackedPropertyError("eSetError", "").links("ETrackedPropertyError_\\w+") void.p("pvBuffer", ""); AutoSize("pvBuffer")..uint32_t("unBufferSize", "") PropertyTypeTag_t("unTag", "") ETrackedPropertyError("eError", "").links("ETrackedPropertyError_\\w+") charASCII.p("pszPath", "") } val PathRead_t = struct(Module.OPENVR, "PathRead", nativeName = "PathRead_t") { PathHandle_t("ulPath", "") void.p("pvBuffer", ""); AutoSize("pvBuffer")..uint32_t("unBufferSize", "") PropertyTypeTag_t("unTag", "") uint32_t("unRequiredBufferSize", "") ETrackedPropertyError("eError", "").links("ETrackedPropertyError_\\w+") charASCII.p("pszPath", "") }*/ val RenderModel_Vertex_t = struct(Module.OPENVR, "RenderModelVertex", nativeName = "RenderModel_Vertex_t", mutable = false) { documentation = "A single vertex in a render model." HmdVector3_t("vPosition", "position in meters in device space") HmdVector3_t("vNormal", "") float("rfTextureCoord", "")[2] } val RenderModel_t = struct(Module.OPENVR, "RenderModel", nativeName = "RenderModel_t", mutable = false) { pack("Platform.get() == Platform.LINUX || Platform.get() == Platform.MACOSX ? 4 : DEFAULT_PACK_ALIGNMENT") RenderModel_Vertex_t.const.p("rVertexData", "Vertex data for the mesh") AutoSize("rVertexData")..uint32_t("unVertexCount", "Number of vertices in the vertex data") uint16_t.const.p("IndexData", "Indices into the vertex data for each triangle") AutoSizeMul("3", "IndexData")..uint32_t("unTriangleCount", "Number of triangles in the mesh. Index count is 3 * TriangleCount.") TextureID_t( "diffuseTextureId", "Session unique texture identifier. Rendermodels which share the same texture will have the same id. 0 == texture not present." ) } val RenderModel_TextureMap_t = struct(Module.OPENVR, "RenderModelTextureMap", nativeName = "RenderModel_TextureMap_t", mutable = false) { documentation = "A texture map for use on a render model." pack("Platform.get() == Platform.LINUX || Platform.get() == Platform.MACOSX ? 4 : DEFAULT_PACK_ALIGNMENT") uint16_t("unWidth", "") uint16_t("unHeight", "width and height of the texture map in pixels") uint8_t.const.p("rubTextureMapData", "Map texture data.") EVRRenderModelTextureFormat("format", "").links("EVRRenderModelTextureFormat_\\w+") } val RenderModel_ControllerMode_State_t = struct(Module.OPENVR, "RenderModelControllerModeState", nativeName = "RenderModel_ControllerMode_State_t") { bool("bScrollWheelVisible", "is this controller currently set to be in a scroll wheel mode") } val RenderModel_ComponentState_t = struct(Module.OPENVR, "RenderModelComponentState", nativeName = "RenderModel_ComponentState_t", mutable = false) { documentation = "Describes state information about a render-model component, including transforms and other dynamic properties." HmdMatrix34_t("mTrackingToComponentRenderModel", "Transform required when drawing the component render model") HmdMatrix34_t("mTrackingToComponentLocal", "Transform available for attaching to a local component coordinate system (-Z out from surface )") VRComponentProperties("uProperties", "") } val CameraVideoStreamFrameHeader_t = struct(Module.OPENVR, "CameraVideoStreamFrameHeader", nativeName = "CameraVideoStreamFrameHeader_t", mutable = false) { EVRTrackedCameraFrameType("eFrameType", "") uint32_t("nWidth", "") uint32_t("nHeight", "") uint32_t("nBytesPerPixel", "") uint32_t("nFrameSequence", "") TrackedDevicePose_t("trackedDevicePose", "") uint64_t("ulFrameExposureTime", "mid-point of the exposure of the image in host system ticks") } val Compositor_BenchmarkResults = struct(Module.OPENVR, "Compositor_BenchmarkResults", nativeName = "Compositor_BenchmarkResults", mutable = false) { documentation = "Provides compositor benchmark results to the app." float("m_flMegaPixelsPerSecond", "Measurement of GPU MP/s performed by compositor benchmark") float("m_flHmdRecommendedMegaPixelsPerSecond", "Recommended default MP/s given the HMD resolution, refresh, and panel mask.") } val DriverDirectMode_FrameTiming = struct(Module.OPENVR, "DriverDirectModeFrameTiming", nativeName = "DriverDirectMode_FrameTiming", mutable = false) { documentation = "Frame timing data provided by direct mode drivers." uint32_t("m_nSize", "sSet to {@code sizeof( DriverDirectMode_FrameTiming )}") uint32_t("m_nNumFramePresents", "number of times frame was presented") uint32_t("m_nNumMisPresented", "number of times frame was presented on a vsync other than it was originally predicted to") uint32_t("m_nNumDroppedFrames", "number of additional times previous frame was scanned out (i.e. compositor missed vsync)") uint32_t("m_nReprojectionFlags", "") } val ImuSample_t = struct(Module.OPENVR, "ImuSample", nativeName = "ImuSample_t", mutable = false) { double("fSampleTime", "") HmdVector3d_t("vAccel", "") HmdVector3d_t("vGyro", "") uint32_t("unOffScaleFlags", "") } val AppOverrideKeys_t = struct(Module.OPENVR, "AppOverrideKeys", nativeName = "AppOverrideKeys_t") { charASCII.p("pchKey", "") char.p("pchValue", "") } val VROverlayIntersectionParams_t = struct(Module.OPENVR, "VROverlayIntersectionParams", nativeName = "VROverlayIntersectionParams_t") { HmdVector3_t("vSource", "") HmdVector3_t("vDirection", "") ETrackingUniverseOrigin("eOrigin", "") } val VROverlayIntersectionResults_t = struct(Module.OPENVR, "VROverlayIntersectionResults", nativeName = "VROverlayIntersectionResults_t", mutable = false) { HmdVector3_t("vPoint", "") HmdVector3_t("vNormal", "") HmdVector2_t("vUVs", "") float("fDistance", "") }
bsd-3-clause
1bc13a90a0e46956708bf13697e57e1c
44.801661
170
0.71836
3.635809
false
false
false
false
phylame/jem
jem-formats/src/main/kotlin/jem/format/epub/opf/Package.kt
1
893
package jem.format.epub.opf import jclp.text.ifNotEmpty import jclp.xml.attribute import jclp.xml.endTag import jclp.xml.startTag import jem.format.epub.EPUB import jem.format.epub.Taggable import org.xmlpull.v1.XmlSerializer class Package(val version: String, var uniqueIdentifier: String = "", id: String = "") : Taggable(id) { val metadata = Metadata() val manifest = Manifest() val spine = Spine() override fun renderTo(xml: XmlSerializer) { with(xml) { startTag("", EPUB.XMLNS_OPF, "package") attribute("version", version) attribute("unique-identifier", uniqueIdentifier) id.ifNotEmpty { attribute("id", it) } attr.forEach { attribute(it.key, it.value) } metadata.renderTo(this) manifest.renderTo(this) spine.renderTo(this) endTag() } } }
apache-2.0
b55b6d4f240d716a5471fd69c2bcf7a0
27.806452
103
0.632699
3.899563
false
false
false
false
vicboma1/GameBoyEmulatorEnvironment
src/main/kotlin/assets/panel/tab/TabPaneListener.kt
1
1517
package assets.panel.tab import assets.panel.multipleImages.base.PanelMultipleImages import assets.table.TableImpl import javax.swing.JTabbedPane import javax.swing.event.ChangeEvent import javax.swing.event.ChangeListener /** * Created by vicboma on 15/01/17. */ class TabPaneListener internal constructor(private val table: TableImpl) : ChangeListener { companion object{ fun create(table: TableImpl) = TabPaneListener(table) } override fun stateChanged(e: ChangeEvent?) { val source = e?.getSource() if (source is JTabbedPane) { var selectedRow = table.selectedRow if(selectedRow != -1) { val selectedIntdexTab = source.selectedIndex val folder = source.getTitleAt(selectedIntdexTab).toLowerCase() val model = table.getModel() val available = model?.getValueAt(selectedRow!!, 0).toString().toUpperCase() val nameRom = model?.getValueAt(selectedRow!!, 1).toString().toLowerCase().split(".")[0].toString().plus(".png") val panel = source.getComponent(selectedIntdexTab) as PanelMultipleImages val path = folder.plus("/$nameRom") panel.setFront(path) //panel.setBack("_bg.png") val IsVisible = source.isVisible if ( IsVisible ) source.repaint(); } } } }
lgpl-3.0
3f0fb3a92bed2e1b0d12836c7a986781
33.5
132
0.589321
4.957516
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/redshift/src/main/kotlin/com/kotlin/redshift/CreateAndModifyCluster.kt
1
4354
// snippet-sourcedescription:[CreateAndModifyCluster.kt demonstrates how to create and modify an Amazon Redshift cluster.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[Amazon Redshift] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.redshift // snippet-start:[redshift.kotlin.create_cluster.import] import aws.sdk.kotlin.services.redshift.RedshiftClient import aws.sdk.kotlin.services.redshift.model.CreateClusterRequest import aws.sdk.kotlin.services.redshift.model.DescribeClustersRequest import aws.sdk.kotlin.services.redshift.model.ModifyClusterRequest import kotlinx.coroutines.delay import kotlin.system.exitProcess // snippet-end:[redshift.kotlin.create_cluster.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: <clusterId> <masterUsername> <masterUserPassword> Where: clusterId - The id of the cluster to create. masterUsername - The master user name. masterUserPassword - The password that corresponds to the master user name. """ if (args.size != 3) { println(usage) exitProcess(0) } val clusterId = args[0] val masterUsername = args[1] val masterUserPassword = args[2] createCluster(clusterId, masterUsername, masterUserPassword) waitForClusterReady(clusterId) modifyCluster(clusterId) println("The example is done") } // snippet-start:[redshift.kotlin.create_cluster.main] suspend fun createCluster(clusterId: String?, masterUsernameVal: String?, masterUserPasswordVal: String?) { val clusterRequest = CreateClusterRequest { clusterIdentifier = clusterId masterUsername = masterUsernameVal // set the user name here masterUserPassword = masterUserPasswordVal // set the user password here nodeType = "ds2.xlarge" publiclyAccessible = true numberOfNodes = 2 } RedshiftClient { region = "us-west-2" }.use { redshiftClient -> val clusterResponse = redshiftClient.createCluster(clusterRequest) println("Created cluster ${clusterResponse.cluster?.clusterIdentifier}") } } // snippet-end:[redshift.kotlin.create_cluster.main] // Waits until the cluster is available. suspend fun waitForClusterReady(clusterId: String?) { var clusterReady = false var clusterReadyStr: String val sleepTime: Long = 20 println("Waiting for the cluster to become available.") val clustersRequest = DescribeClustersRequest { clusterIdentifier = clusterId } RedshiftClient { region = "us-west-2" }.use { redshiftClient -> // Loop until the cluster is ready. while (!clusterReady) { val clusterResponse = redshiftClient.describeClusters(clustersRequest) val clusterList = clusterResponse.clusters if (clusterList != null) { for (cluster in clusterList) { clusterReadyStr = cluster.clusterStatus.toString() if (clusterReadyStr.contains("available")) { clusterReady = true } else { print(".") delay(sleepTime * 1000) } } } } println("Cluster is available!") } } // snippet-start:[redshift.kotlin.mod_cluster.main] suspend fun modifyCluster(clusterId: String?) { val modifyClusterRequest = ModifyClusterRequest { clusterIdentifier = clusterId preferredMaintenanceWindow = "wed:07:30-wed:08:00" } RedshiftClient { region = "us-west-2" }.use { redshiftClient -> val clusterResponse = redshiftClient.modifyCluster(modifyClusterRequest) println("The modified cluster was successfully modified and has ${clusterResponse.cluster?.preferredMaintenanceWindow} as the maintenance window") } } // snippet-end:[redshift.kotlin.mod_cluster.main]
apache-2.0
fa93bc701e08e8d8fbee631be9175887
35.86087
154
0.671337
4.456499
false
false
false
false
chrislo27/Tickompiler
src/main/kotlin/rhmodding/tickompiler/output/Outputter.kt
2
467
package rhmodding.tickompiler.output object Outputter { fun toHexBytes(array: ByteArray, group4: Boolean): String { val sb = StringBuilder() var count = 0 val grouping = if (group4) 4 else 1 array.forEach { sb.append(String.format("%02x", it)) if (++count >= grouping) { count = 0 sb.append(" ") } } return sb.toString().toUpperCase() } }
mit
cff9ea022f4c4ce8c7dd8bf4506cd390
21.285714
63
0.511777
4.40566
false
false
false
false
esafirm/android-playground
app/src/main/java/com/esafirm/androidplayground/network/Net.kt
1
2073
package com.esafirm.androidplayground.network import android.content.Context import com.pandulapeter.beagle.BeagleNetworkInterceptor import okhttp3.Cache import okhttp3.CacheControl import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.Response import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory object Net { const val BASE_URL = "https://dog.ceo/api/" private val okHttpClient by lazy { OkHttpClient.Builder() .addInterceptor(BeagleNetworkInterceptor) .build() } private val retrofit by lazy { Retrofit.Builder() .client(okHttpClient) .baseUrl(BASE_URL) .addConverterFactory(GsonConverterFactory.create()) .build() } private val cacheInterceptor by lazy { object : Interceptor { override fun intercept(chain: Interceptor.Chain): Response { val cacheRequest: Request = chain.request().newBuilder() .cacheControl(CacheControl.FORCE_CACHE) .build() return chain.proceed(cacheRequest) } } } fun <T> getCacheService( context: Context, baseUrl: String, service: Class<T>, forceCache: Boolean = false ): T { val cache = Cache( context.cacheDir, maxSize = 50L * 1024L * 1024L ) val retrofit = Retrofit.Builder() .client( OkHttpClient.Builder() .cache(cache) .apply { if (forceCache) { addInterceptor(cacheInterceptor) } } .build() ) .baseUrl(baseUrl) .addConverterFactory(GsonConverterFactory.create()) .build() return retrofit.create(service) } fun <T> getService(service: Class<T>): T { return retrofit.create(service) } }
mit
cfba4431166d2230e4ab2705519beac4
25.922078
72
0.565364
5.105911
false
false
false
false
DemonWav/MinecraftDevIntelliJ
src/main/kotlin/com/demonwav/mcdev/platform/mixin/util/Accessor.kt
1
2994
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2020 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.util import com.demonwav.mcdev.util.constantStringValue import com.demonwav.mcdev.util.findAnnotation import com.demonwav.mcdev.util.ifEmpty import com.demonwav.mcdev.util.isErasureEquivalentTo import com.demonwav.mcdev.util.mapFirstNotNull import com.intellij.psi.PsiAnnotation import com.intellij.psi.PsiClass import com.intellij.psi.PsiMember import com.intellij.psi.PsiMethod import com.intellij.psi.PsiType import com.intellij.psi.SmartPsiElementPointer import com.intellij.psi.util.createSmartPointer import java.util.Locale fun PsiMember.findAccessorTarget(): SmartPsiElementPointer<PsiMember>? { val accessor = findAnnotation(MixinConstants.Annotations.ACCESSOR) ?: return null val containingClass = containingClass ?: return null val targetClasses = containingClass.mixinTargets.ifEmpty { return null } return resolveAccessorTarget(accessor, targetClasses, this)?.createSmartPointer() } fun resolveAccessorTarget( accessor: PsiAnnotation, targetClasses: Collection<PsiClass>, member: PsiMember ): PsiMember? { val accessorInfo = getAccessorInfo(accessor, member) ?: return null return when (member) { is PsiMethod -> targetClasses.mapFirstNotNull { psiClass -> psiClass.findFieldByName(accessorInfo.name, false)?.takeIf { // Accessors either have a return value (field getter) or a parameter (field setter) if (!member.hasParameters() && accessorInfo.type.allowGetters) { it.type.isErasureEquivalentTo(member.returnType) } else if (PsiType.VOID == member.returnType && accessorInfo.type.allowSetters) { it.type.isErasureEquivalentTo(member.parameterList.parameters[0].type) } else { false } } } else -> null } } fun getAccessorInfo(accessor: PsiAnnotation, member: PsiMember): AccessorInfo? { val value = accessor.findDeclaredAttributeValue("value")?.constantStringValue if (value != null) { return AccessorInfo(value, AccessorType.UNKNOWN) } val memberName = member.name ?: return null val result = PATTERN.matchEntire(memberName) ?: return null val prefix = result.groupValues[1] var name = result.groupValues[2] if (name.toUpperCase(Locale.ROOT) != name) { name = name.decapitalize() } val type = if (prefix == "set") { AccessorType.SETTER } else { AccessorType.GETTER } return AccessorInfo(name, type) } private val PATTERN = Regex("(get|is|set)([A-Z].*?)(_\\\$md.*)?") data class AccessorInfo(val name: String, val type: AccessorType) enum class AccessorType(val allowGetters: Boolean, val allowSetters: Boolean) { GETTER(true, false), SETTER(false, true), UNKNOWN(true, true); }
mit
e0a8c093734a14fd6fcbb4c43945706d
33.813953
100
0.697729
4.402941
false
false
false
false
ewrfedf/Bandhook-Kotlin
app/src/main/java/butterknife/KotterKnife.kt
4
5668
/* * Copyright 2014 Jake Wharton * 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 butterknife import android.app.Activity import android.app.Dialog import android.app.Fragment import android.support.v7.widget.RecyclerView.ViewHolder import android.view.View import android.view.ViewGroup import kotlin.properties.ReadOnlyProperty import android.support.v4.app.Fragment as SupportFragment public fun <T : View> ViewGroup.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> Activity.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> Dialog.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> Fragment.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> SupportFragment.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> ViewHolder.bindView(id: Int): ReadOnlyProperty<Any, T> = ViewBinding(id) public fun <T : View> ViewGroup.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> Activity.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> Dialog.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> Fragment.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> SupportFragment.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> ViewHolder.bindOptionalView(id: Int): ReadOnlyProperty<Any, T?> = OptionalViewBinding(id) public fun <T : View> ViewGroup.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> Activity.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> Dialog.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> Fragment.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> SupportFragment.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> ViewHolder.bindViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = ViewListBinding(ids) public fun <T : View> ViewGroup.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> Activity.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> Dialog.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> Fragment.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> SupportFragment.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) public fun <T : View> ViewHolder.bindOptionalViews(vararg ids: Int): ReadOnlyProperty<Any, List<T>> = OptionalViewListBinding(ids) private fun findView<T : View>(thisRef: Any, id: Int): T? { @suppress("UNCHECKED_CAST") return when (thisRef) { is View -> thisRef.findViewById(id) is Activity -> thisRef.findViewById(id) is Dialog -> thisRef.findViewById(id) is Fragment -> thisRef.getView().findViewById(id) is SupportFragment -> thisRef.getView().findViewById(id) is ViewHolder -> thisRef.itemView.findViewById(id) else -> throw IllegalStateException("Unable to find views on type.") } as T? } private class ViewBinding<T : View>(val id: Int) : ReadOnlyProperty<Any, T> { private val lazy = Lazy<T>() override fun get(thisRef: Any, desc: PropertyMetadata): T = lazy.get { findView<T>(thisRef, id) ?: throw IllegalStateException("View ID $id for '${desc.name}' not found.") } } private class OptionalViewBinding<T : View>(val id: Int) : ReadOnlyProperty<Any, T?> { private val lazy = Lazy<T?>() override fun get(thisRef: Any, desc: PropertyMetadata): T? = lazy.get { findView<T>(thisRef, id) } } private class ViewListBinding<T : View>(val ids: IntArray) : ReadOnlyProperty<Any, List<T>> { private var lazy = Lazy<List<T>>() override fun get(thisRef: Any, desc: PropertyMetadata): List<T> = lazy.get { ids.map { id -> findView<T>(thisRef, id) ?: throw IllegalStateException("View ID $id for '${desc.name}' not found.") } } } private class OptionalViewListBinding<T : View>(val ids: IntArray) : ReadOnlyProperty<Any, List<T>> { private var lazy = Lazy<List<T>>() override fun get(thisRef: Any, desc: PropertyMetadata): List<T> = lazy.get { ids.map { id -> findView<T>(thisRef, id) }.filterNotNull() } } private class Lazy<T> { private object EMPTY private var value: Any? = EMPTY fun get(initializer: () -> T): T { if (value == EMPTY) { value = initializer.invoke() } @suppress("UNCHECKED_CAST") return value as T } }
apache-2.0
a77405526524e12e4a73c0aa62cabd96
47.452991
135
0.712421
3.925208
false
false
false
false
nielsutrecht/adventofcode
src/main/kotlin/com/nibado/projects/advent/y2017/Day22.kt
1
2325
package com.nibado.projects.advent.y2017 import com.nibado.projects.advent.Day import com.nibado.projects.advent.Direction import com.nibado.projects.advent.Point import com.nibado.projects.advent.resourceLines object Day22 : Day { private val input = resourceLines(2017, 22).mapIndexed { y, s -> s.trim().toCharArray().mapIndexed { x, c -> Point(x, y) to (if (c == '#') State.INFECTED else State.CLEAN) } }.flatMap { it }.toMap() private enum class State { CLEAN, WEAKENED, INFECTED, FLAGGED } override fun part1() = solve(10000, { s, d -> when (s) { State.INFECTED -> d.cw() else -> d.ccw() } }, { when (it) { State.CLEAN -> State.INFECTED else -> State.CLEAN } }) override fun part2() = solve(10000000, { s, d -> when (s) { State.CLEAN -> d.ccw() State.INFECTED -> d.cw() State.FLAGGED -> d.cw().cw() State.WEAKENED -> d } }, { when (it) { State.CLEAN -> State.WEAKENED State.WEAKENED -> State.INFECTED State.INFECTED -> State.FLAGGED State.FLAGGED -> State.CLEAN } }) private fun solve(iterations: Int, dir: (State, Direction) -> Direction, state: (State) -> State): String { val points = input.toMutableMap() val min = Point(points.keys.minByOrNull { it.x }!!.x, points.keys.minByOrNull { it.y }!!.y) val max = Point(points.keys.maxByOrNull { it.x }!!.x, points.keys.maxByOrNull { it.y }!!.y) var current = Point(min.x + (max.x - min.x) / 2, min.y + (max.y - min.y) / 2) var direction = Direction.NORTH var count = 0 (1..iterations).forEach { direction = dir(points[current] ?: State.CLEAN, direction) points[current] = state(points[current] ?: State.CLEAN) if (points[current] == State.INFECTED) { count++ } current = current.plus(direction) } return count.toString() } }
mit
6ff2c3cf382a6de52d9f32d0f6312caa
33.205882
202
0.495054
4.151786
false
false
false
false
spacecowboy/Feeder
app/src/main/java/com/nononsenseapps/feeder/crypto/AesCbcWithIntegrity.kt
1
20839
/* * Copyright (c) 2014-2015 Tozny LLC * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * * Created by Isaac Potoczny-Jones on 11/12/14. */ package com.nononsenseapps.feeder.crypto import android.util.Base64 import java.io.UnsupportedEncodingException import java.lang.Exception import java.nio.charset.Charset import java.security.GeneralSecurityException import java.security.InvalidKeyException import java.security.NoSuchAlgorithmException import java.security.SecureRandom import java.security.spec.KeySpec import javax.crypto.Cipher import javax.crypto.KeyGenerator import javax.crypto.Mac import javax.crypto.SecretKey import javax.crypto.SecretKeyFactory import javax.crypto.spec.IvParameterSpec import javax.crypto.spec.PBEKeySpec import javax.crypto.spec.SecretKeySpec import kotlin.experimental.xor /** * Simple library for the "right" defaults for AES key generation, encryption, * and decryption using 128-bit AES, CBC, PKCS5 padding, and a random 16-byte IV * with SHA1PRNG. Integrity with HmacSHA256. */ object AesCbcWithIntegrity { private const val CIPHER_TRANSFORMATION = "AES/CBC/PKCS5Padding" private const val CIPHER = "AES" private const val AES_KEY_LENGTH_BITS = 128 private const val IV_LENGTH_BYTES = 16 private const val PBE_ITERATION_COUNT = 10000 private const val PBE_SALT_LENGTH_BITS = AES_KEY_LENGTH_BITS // same size as key output private const val PBE_ALGORITHM = "PBKDF2WithHmacSHA1" // Made BASE_64_FLAGS public as it's useful to know for compatibility. const val BASE64_FLAGS = Base64.NO_WRAP // default for testing private const val HMAC_ALGORITHM = "HmacSHA256" private const val HMAC_KEY_LENGTH_BITS = 256 /** * Converts the given AES/HMAC keys into a base64 encoded string suitable for * storage. Sister function of keys. * * @param keys The combined aes and hmac keys * @return a base 64 encoded AES string and hmac key as base64(aesKey) : base64(hmacKey) */ fun encodeKey(keys: SecretKeys): String { return keys.toString() } /** * An aes key derived from a base64 encoded key. This does not generate the * key. It's not random or a PBE key. * * @param keysStr a base64 encoded AES key / hmac key as base64(aesKey) : base64(hmacKey). * @return an AES and HMAC key set suitable for other functions. */ @Throws(InvalidKeyException::class) fun decodeKey(keysStr: String): SecretKeys { val keysArr = keysStr.split(":") return if (keysArr.size != 2) { throw IllegalArgumentException("Cannot parse aesKey:hmacKey") } else { val confidentialityKey = Base64.decode(keysArr[0], BASE64_FLAGS) if (confidentialityKey.size != AES_KEY_LENGTH_BITS / 8) { throw InvalidKeyException("Base64 decoded key is not $AES_KEY_LENGTH_BITS bytes") } val integrityKey = Base64.decode(keysArr[1], BASE64_FLAGS) if (integrityKey.size != HMAC_KEY_LENGTH_BITS / 8) { throw InvalidKeyException("Base64 decoded key is not $HMAC_KEY_LENGTH_BITS bytes") } SecretKeys( SecretKeySpec(confidentialityKey, 0, confidentialityKey.size, CIPHER), SecretKeySpec(integrityKey, HMAC_ALGORITHM) ) } } fun isKeyDecodable(keysStr: String): Boolean { return try { decodeKey(keysStr) true } catch (e: Exception) { false } } /** * A function that generates random AES and HMAC keys and prints out exceptions but * doesn't throw them since none should be encountered. If they are * encountered, the return value is null. * * @return The AES and HMAC keys. * @throws GeneralSecurityException if AES is not implemented on this system, * or a suitable RNG is not available */ @Throws(GeneralSecurityException::class) fun generateKey(): SecretKeys { val keyGen = KeyGenerator.getInstance(CIPHER) // No need to provide a SecureRandom or set a seed since that will // happen automatically. keyGen.init(AES_KEY_LENGTH_BITS) val confidentialityKey = keyGen.generateKey() // Now make the HMAC key val integrityKeyBytes = randomBytes(HMAC_KEY_LENGTH_BITS / 8) // to get bytes val integrityKey: SecretKey = SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM) return SecretKeys(confidentialityKey, integrityKey) } /** * A function that generates password-based AES and HMAC keys. It prints out exceptions but * doesn't throw them since none should be encountered. If they are * encountered, the return value is null. * * @param password The password to derive the keys from. * @return The AES and HMAC keys. * @throws GeneralSecurityException if AES is not implemented on this system, * or a suitable RNG is not available */ @Throws(GeneralSecurityException::class) fun generateKeyFromPassword(password: String, salt: ByteArray): SecretKeys { // Get enough random bytes for both the AES key and the HMAC key: val keySpec: KeySpec = PBEKeySpec( password.toCharArray(), salt, PBE_ITERATION_COUNT, AES_KEY_LENGTH_BITS + HMAC_KEY_LENGTH_BITS ) val keyFactory = SecretKeyFactory .getInstance(PBE_ALGORITHM) val keyBytes = keyFactory.generateSecret(keySpec).encoded // Split the random bytes into two parts: val confidentialityKeyBytes = keyBytes.copyOfRange(0, AES_KEY_LENGTH_BITS / 8) val integrityKeyBytes = keyBytes.copyOfRange( AES_KEY_LENGTH_BITS / 8, AES_KEY_LENGTH_BITS / 8 + HMAC_KEY_LENGTH_BITS / 8 ) // Generate the AES key val confidentialityKey: SecretKey = SecretKeySpec(confidentialityKeyBytes, CIPHER) // Generate the HMAC key val integrityKey: SecretKey = SecretKeySpec(integrityKeyBytes, HMAC_ALGORITHM) return SecretKeys(confidentialityKey, integrityKey) } /** * A function that generates password-based AES and HMAC keys. See generateKeyFromPassword. * @param password The password to derive the AES/HMAC keys from * @param salt A string version of the salt; base64 encoded. * @return The AES and HMAC keys. * @throws GeneralSecurityException */ @Throws(GeneralSecurityException::class) fun generateKeyFromPassword(password: String, salt: String): SecretKeys { return generateKeyFromPassword(password, Base64.decode(salt, BASE64_FLAGS)) } /** * Generates a random salt. * @return The random salt suitable for generateKeyFromPassword. */ @Throws(GeneralSecurityException::class) fun generateSalt(): ByteArray { return randomBytes(PBE_SALT_LENGTH_BITS) } /** * Converts the given salt into a base64 encoded string suitable for * storage. * * @param salt * @return a base 64 encoded salt string suitable to pass into generateKeyFromPassword. */ fun saltString(salt: ByteArray): String { return Base64.encodeToString(salt, BASE64_FLAGS) } /** * Creates a random Initialization Vector (IV) of IV_LENGTH_BYTES. * * @return The byte array of this IV * @throws GeneralSecurityException if a suitable RNG is not available */ @Throws(GeneralSecurityException::class) fun generateIv(): ByteArray { return randomBytes(IV_LENGTH_BYTES) } @Throws(GeneralSecurityException::class) private fun randomBytes(length: Int): ByteArray { val random = SecureRandom() val b = ByteArray(length) random.nextBytes(b) return b } /* * ----------------------------------------------------------------- * Encryption * ----------------------------------------------------------------- */ /** * Generates a random IV and encrypts this plain text with the given key. Then attaches * a hashed MAC, which is contained in the CipherTextIvMac class. * * @param plaintext The text that will be encrypted, which * will be serialized with UTF-8 * @param secretKeys The AES and HMAC keys with which to encrypt * @param encoding The string encoding to use to encode the bytes before encryption * @return a tuple of the IV, ciphertext, mac * @throws GeneralSecurityException if AES is not implemented on this system * @throws UnsupportedEncodingException if UTF-8 is not supported in this system */ @Throws(UnsupportedEncodingException::class, GeneralSecurityException::class) fun encryptString( plaintext: String, secretKeys: SecretKeys, encoding: Charset = Charsets.UTF_8 ): String = encrypt( plaintext = plaintext, secretKeys = secretKeys, encoding = encoding, ).toString() /** * Generates a random IV and encrypts this plain text with the given key. Then attaches * a hashed MAC, which is contained in the CipherTextIvMac class. * * @param plaintext The text that will be encrypted, which * will be serialized with UTF-8 * @param secretKeys The AES and HMAC keys with which to encrypt * @param encoding The string encoding to use to encode the bytes before encryption * @return a tuple of the IV, ciphertext, mac * @throws GeneralSecurityException if AES is not implemented on this system * @throws UnsupportedEncodingException if UTF-8 is not supported in this system */ @Throws(UnsupportedEncodingException::class, GeneralSecurityException::class) fun encrypt( plaintext: String, secretKeys: SecretKeys, encoding: Charset = Charsets.UTF_8 ): CipherTextIvMac { return encrypt(plaintext.toByteArray(encoding), secretKeys) } /** * Generates a random IV and encrypts this plain text with the given key. Then attaches * a hashed MAC, which is contained in the CipherTextIvMac class. * * @param plaintext The text that will be encrypted * @param secretKeys The combined AES and HMAC keys with which to encrypt * @return a tuple of the IV, ciphertext, mac * @throws GeneralSecurityException if AES is not implemented on this system */ @Throws(GeneralSecurityException::class) fun encrypt(plaintext: ByteArray, secretKeys: SecretKeys): CipherTextIvMac { var iv = generateIv() val aesCipherForEncryption = Cipher.getInstance(CIPHER_TRANSFORMATION) aesCipherForEncryption.init( Cipher.ENCRYPT_MODE, secretKeys.confidentialityKey, IvParameterSpec(iv) ) /* * Now we get back the IV that will actually be used. Some Android * versions do funny stuff w/ the IV, so this is to work around bugs: */ iv = aesCipherForEncryption.iv val byteCipherText = aesCipherForEncryption.doFinal(plaintext) val ivCipherConcat = CipherTextIvMac.ivCipherConcat(iv, byteCipherText) val integrityMac = generateMac(ivCipherConcat, secretKeys.integrityKey) return CipherTextIvMac(byteCipherText, iv, integrityMac) } /* * ----------------------------------------------------------------- * Decryption * ----------------------------------------------------------------- */ /** * AES CBC decrypt. * * @param civ The cipher text, IV, and mac * @param secretKeys The AES and HMAC keys * @param encoding The string encoding to use to decode the bytes after decryption * @return A string derived from the decrypted bytes (not base64 encoded) * @throws GeneralSecurityException if AES is not implemented on this system * @throws UnsupportedEncodingException if the encoding is unsupported */ @Throws(UnsupportedEncodingException::class, GeneralSecurityException::class) fun decryptString( civ: String, secretKeys: SecretKeys, encoding: Charset = Charsets.UTF_8 ): String { return String(decrypt(CipherTextIvMac(civ), secretKeys), encoding) } /** * AES CBC decrypt. * * @param civ The cipher text, IV, and mac * @param secretKeys The AES and HMAC keys * @param encoding The string encoding to use to decode the bytes after decryption * @return A string derived from the decrypted bytes (not base64 encoded) * @throws GeneralSecurityException if AES is not implemented on this system * @throws UnsupportedEncodingException if the encoding is unsupported */ @Throws(UnsupportedEncodingException::class, GeneralSecurityException::class) fun decrypt( civ: CipherTextIvMac, secretKeys: SecretKeys, encoding: Charset = Charsets.UTF_8 ): String { return String(decrypt(civ, secretKeys), encoding) } /** * AES CBC decrypt. * * @param civ the cipher text, iv, and mac * @param secretKeys the AES and HMAC keys * @return The raw decrypted bytes * @throws GeneralSecurityException if MACs don't match or AES is not implemented */ @Throws(GeneralSecurityException::class) fun decrypt(civ: CipherTextIvMac, secretKeys: SecretKeys): ByteArray { val ivCipherConcat = CipherTextIvMac.ivCipherConcat(civ.iv, civ.cipherText) val computedMac = generateMac(ivCipherConcat, secretKeys.integrityKey) return if (constantTimeEq(computedMac, civ.mac)) { val aesCipherForDecryption = Cipher.getInstance(CIPHER_TRANSFORMATION) aesCipherForDecryption.init( Cipher.DECRYPT_MODE, secretKeys.confidentialityKey, IvParameterSpec(civ.iv) ) aesCipherForDecryption.doFinal(civ.cipherText) } else { throw GeneralSecurityException("MAC stored in civ does not match computed MAC.") } } /* * ----------------------------------------------------------------- * Helper Code * ----------------------------------------------------------------- */ /** * Generate the mac based on HMAC_ALGORITHM * @param integrityKey The key used for hmac * @param byteCipherText the cipher text * @return A byte array of the HMAC for the given key and ciphertext * @throws NoSuchAlgorithmException * @throws InvalidKeyException */ @Throws(NoSuchAlgorithmException::class, InvalidKeyException::class) fun generateMac(byteCipherText: ByteArray, integrityKey: SecretKey): ByteArray { // Now compute the mac for later integrity checking val sha256HMAC = Mac.getInstance(HMAC_ALGORITHM) sha256HMAC.init(integrityKey) return sha256HMAC.doFinal(byteCipherText) } /** * Simple constant-time equality of two byte arrays. Used for security to avoid timing attacks. * @param a * @param b * @return true iff the arrays are exactly equal. */ private fun constantTimeEq(a: ByteArray, b: ByteArray): Boolean { if (a.size != b.size) { return false } var result = 0 for (i in a.indices) { result = result or (a[i] xor b[i]).toInt() } return result == 0 } } /** * Holder class that has both the secret AES key for encryption (confidentiality) * and the secret HMAC key for integrity. */ class SecretKeys( val confidentialityKey: SecretKey, val integrityKey: SecretKey ) { /** * Encodes the two keys as a string * @return base64(confidentialityKey):base64(integrityKey) */ override fun toString(): String { return ( Base64.encodeToString( confidentialityKey.encoded, AesCbcWithIntegrity.BASE64_FLAGS ) + ":" + Base64.encodeToString( integrityKey.encoded, AesCbcWithIntegrity.BASE64_FLAGS ) ) } override fun hashCode(): Int { val prime = 31 var result = 1 result = prime * result + confidentialityKey.hashCode() result = prime * result + integrityKey.hashCode() return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (other !is SecretKeys) return false if (integrityKey != other.integrityKey) return false return confidentialityKey == other.confidentialityKey } } /** * Holder class that allows us to bundle ciphertext and IV together. */ class CipherTextIvMac { val cipherText: ByteArray val iv: ByteArray val mac: ByteArray /** * Construct a new bundle of ciphertext and IV. * @param c The ciphertext * @param i The IV * @param h The mac */ constructor(c: ByteArray, i: ByteArray, h: ByteArray) { cipherText = ByteArray(c.size) System.arraycopy(c, 0, cipherText, 0, c.size) iv = ByteArray(i.size) System.arraycopy(i, 0, iv, 0, i.size) mac = ByteArray(h.size) System.arraycopy(h, 0, mac, 0, h.size) } /** * Constructs a new bundle of ciphertext and IV from a string of the * format `base64(iv):base64(ciphertext)`. * * @param base64IvAndCiphertext A string of the format * `iv:ciphertext` The IV and ciphertext must each * be base64-encoded. */ constructor(base64IvAndCiphertext: String) { val civArray = base64IvAndCiphertext.split(":") require(civArray.size == 3) { "Cannot parse iv:mac:ciphertext" } iv = Base64.decode(civArray[0], AesCbcWithIntegrity.BASE64_FLAGS) mac = Base64.decode(civArray[1], AesCbcWithIntegrity.BASE64_FLAGS) cipherText = Base64.decode(civArray[2], AesCbcWithIntegrity.BASE64_FLAGS) } /** * Encodes this ciphertext, IV, mac as a string. * * @return base64(iv) : base64(mac) : base64(ciphertext). * The iv and mac go first because they're fixed length. */ override fun toString(): String { val ivString = Base64.encodeToString(iv, AesCbcWithIntegrity.BASE64_FLAGS) val cipherTextString = Base64.encodeToString(cipherText, AesCbcWithIntegrity.BASE64_FLAGS) val macString = Base64.encodeToString(mac, AesCbcWithIntegrity.BASE64_FLAGS) return String.format("$ivString:$macString:$cipherTextString") } override fun hashCode(): Int { val prime = 31 var result = 1 result = prime * result + cipherText.contentHashCode() result = prime * result + iv.contentHashCode() result = prime * result + mac.contentHashCode() return result } override fun equals(other: Any?): Boolean { if (this === other) return true if (other == null) return false if (other !is CipherTextIvMac) return false if (!cipherText.contentEquals(other.cipherText)) return false if (!iv.contentEquals(other.iv)) return false return mac.contentEquals(other.mac) } companion object { /** * Concatenate the IV to the cipherText using array copy. * This is used e.g. before computing mac. * @param iv The IV to prepend * @param cipherText the cipherText to append * @return iv:cipherText, a new byte array. */ fun ivCipherConcat(iv: ByteArray, cipherText: ByteArray): ByteArray { val combined = ByteArray(iv.size + cipherText.size) System.arraycopy(iv, 0, combined, 0, iv.size) System.arraycopy(cipherText, 0, combined, iv.size, cipherText.size) return combined } } }
gpl-3.0
3b58741b382fe023ab606d1131968616
37.878731
99
0.654206
4.506704
false
false
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/common/src/channels/Deprecated.kt
1
15680
/* * Copyright 2016-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ @file:JvmMultifileClass @file:JvmName("ChannelsKt") @file:Suppress("unused") package kotlinx.coroutines.channels import kotlinx.coroutines.* import kotlin.coroutines.* import kotlin.jvm.* /** @suppress **/ @PublishedApi // Binary compatibility internal fun consumesAll(vararg channels: ReceiveChannel<*>): CompletionHandler = { cause: Throwable? -> var exception: Throwable? = null for (channel in channels) try { channel.cancelConsumed(cause) } catch (e: Throwable) { if (exception == null) { exception = e } else { exception.addSuppressedThrowable(e) } } exception?.let { throw it } } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.elementAt(index: Int): E = consume { if (index < 0) throw IndexOutOfBoundsException("ReceiveChannel doesn't contain element at index $index.") var count = 0 for (element in this) { @Suppress("UNUSED_CHANGED_VALUE") // KT-47628 if (index == count++) return element } throw IndexOutOfBoundsException("ReceiveChannel doesn't contain element at index $index.") } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.elementAtOrNull(index: Int): E? = consume { if (index < 0) return null var count = 0 for (element in this) { if (index == count++) return element } return null } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.first(): E = consume { val iterator = iterator() if (!iterator.hasNext()) throw NoSuchElementException("ReceiveChannel is empty.") return iterator.next() } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.firstOrNull(): E? = consume { val iterator = iterator() if (!iterator.hasNext()) return null return iterator.next() } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.indexOf(element: E): Int { var index = 0 consumeEach { if (element == it) return index index++ } return -1 } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.last(): E = consume { val iterator = iterator() if (!iterator.hasNext()) throw NoSuchElementException("ReceiveChannel is empty.") var last = iterator.next() while (iterator.hasNext()) last = iterator.next() return last } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.lastIndexOf(element: E): Int { var lastIndex = -1 var index = 0 consumeEach { if (element == it) lastIndex = index index++ } return lastIndex } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.lastOrNull(): E? = consume { val iterator = iterator() if (!iterator.hasNext()) return null var last = iterator.next() while (iterator.hasNext()) last = iterator.next() return last } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.single(): E = consume { val iterator = iterator() if (!iterator.hasNext()) throw NoSuchElementException("ReceiveChannel is empty.") val single = iterator.next() if (iterator.hasNext()) throw IllegalArgumentException("ReceiveChannel has more than one element.") return single } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.singleOrNull(): E? = consume { val iterator = iterator() if (!iterator.hasNext()) return null val single = iterator.next() if (iterator.hasNext()) return null return single } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E> ReceiveChannel<E>.drop(n: Int, context: CoroutineContext = Dispatchers.Unconfined): ReceiveChannel<E> = GlobalScope.produce(context, onCompletion = consumes()) { require(n >= 0) { "Requested element count $n is less than zero." } var remaining: Int = n if (remaining > 0) for (e in this@drop) { remaining-- if (remaining == 0) break } for (e in this@drop) { send(e) } } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E> ReceiveChannel<E>.dropWhile( context: CoroutineContext = Dispatchers.Unconfined, predicate: suspend (E) -> Boolean ): ReceiveChannel<E> = GlobalScope.produce(context, onCompletion = consumes()) { for (e in this@dropWhile) { if (!predicate(e)) { send(e) break } } for (e in this@dropWhile) { send(e) } } @PublishedApi internal fun <E> ReceiveChannel<E>.filter( context: CoroutineContext = Dispatchers.Unconfined, predicate: suspend (E) -> Boolean ): ReceiveChannel<E> = GlobalScope.produce(context, onCompletion = consumes()) { for (e in this@filter) { if (predicate(e)) send(e) } } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E> ReceiveChannel<E>.filterIndexed( context: CoroutineContext = Dispatchers.Unconfined, predicate: suspend (index: Int, E) -> Boolean ): ReceiveChannel<E> = GlobalScope.produce(context, onCompletion = consumes()) { var index = 0 for (e in this@filterIndexed) { if (predicate(index++, e)) send(e) } } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E> ReceiveChannel<E>.filterNot( context: CoroutineContext = Dispatchers.Unconfined, predicate: suspend (E) -> Boolean ): ReceiveChannel<E> = filter(context) { !predicate(it) } @PublishedApi @Suppress("UNCHECKED_CAST") internal fun <E : Any> ReceiveChannel<E?>.filterNotNull(): ReceiveChannel<E> = filter { it != null } as ReceiveChannel<E> /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E : Any, C : MutableCollection<in E>> ReceiveChannel<E?>.filterNotNullTo(destination: C): C { consumeEach { if (it != null) destination.add(it) } return destination } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E : Any, C : SendChannel<E>> ReceiveChannel<E?>.filterNotNullTo(destination: C): C { consumeEach { if (it != null) destination.send(it) } return destination } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E> ReceiveChannel<E>.take(n: Int, context: CoroutineContext = Dispatchers.Unconfined): ReceiveChannel<E> = GlobalScope.produce(context, onCompletion = consumes()) { if (n == 0) return@produce require(n >= 0) { "Requested element count $n is less than zero." } var remaining: Int = n for (e in this@take) { send(e) remaining-- if (remaining == 0) return@produce } } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E> ReceiveChannel<E>.takeWhile( context: CoroutineContext = Dispatchers.Unconfined, predicate: suspend (E) -> Boolean ): ReceiveChannel<E> = GlobalScope.produce(context, onCompletion = consumes()) { for (e in this@takeWhile) { if (!predicate(e)) return@produce send(e) } } @PublishedApi internal suspend fun <E, C : SendChannel<E>> ReceiveChannel<E>.toChannel(destination: C): C { consumeEach { destination.send(it) } return destination } @PublishedApi internal suspend fun <E, C : MutableCollection<in E>> ReceiveChannel<E>.toCollection(destination: C): C { consumeEach { destination.add(it) } return destination } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <K, V> ReceiveChannel<Pair<K, V>>.toMap(): Map<K, V> = toMap(LinkedHashMap()) @PublishedApi internal suspend fun <K, V, M : MutableMap<in K, in V>> ReceiveChannel<Pair<K, V>>.toMap(destination: M): M { consumeEach { destination += it } return destination } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.toMutableList(): MutableList<E> = toCollection(ArrayList()) /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.toSet(): Set<E> = this.toMutableSet() /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E, R> ReceiveChannel<E>.flatMap( context: CoroutineContext = Dispatchers.Unconfined, transform: suspend (E) -> ReceiveChannel<R> ): ReceiveChannel<R> = GlobalScope.produce(context, onCompletion = consumes()) { for (e in this@flatMap) { transform(e).toChannel(this) } } @PublishedApi internal fun <E, R> ReceiveChannel<E>.map( context: CoroutineContext = Dispatchers.Unconfined, transform: suspend (E) -> R ): ReceiveChannel<R> = GlobalScope.produce(context, onCompletion = consumes()) { consumeEach { send(transform(it)) } } @PublishedApi internal fun <E, R> ReceiveChannel<E>.mapIndexed( context: CoroutineContext = Dispatchers.Unconfined, transform: suspend (index: Int, E) -> R ): ReceiveChannel<R> = GlobalScope.produce(context, onCompletion = consumes()) { var index = 0 for (e in this@mapIndexed) { send(transform(index++, e)) } } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E, R : Any> ReceiveChannel<E>.mapIndexedNotNull( context: CoroutineContext = Dispatchers.Unconfined, transform: suspend (index: Int, E) -> R? ): ReceiveChannel<R> = mapIndexed(context, transform).filterNotNull() /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E, R : Any> ReceiveChannel<E>.mapNotNull( context: CoroutineContext = Dispatchers.Unconfined, transform: suspend (E) -> R? ): ReceiveChannel<R> = map(context, transform).filterNotNull() /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E> ReceiveChannel<E>.withIndex(context: CoroutineContext = Dispatchers.Unconfined): ReceiveChannel<IndexedValue<E>> = GlobalScope.produce(context, onCompletion = consumes()) { var index = 0 for (e in this@withIndex) { send(IndexedValue(index++, e)) } } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E> ReceiveChannel<E>.distinct(): ReceiveChannel<E> = this.distinctBy { it } @PublishedApi internal fun <E, K> ReceiveChannel<E>.distinctBy( context: CoroutineContext = Dispatchers.Unconfined, selector: suspend (E) -> K ): ReceiveChannel<E> = GlobalScope.produce(context, onCompletion = consumes()) { val keys = HashSet<K>() for (e in this@distinctBy) { val k = selector(e) if (k !in keys) { send(e) keys += k } } } @PublishedApi internal suspend fun <E> ReceiveChannel<E>.toMutableSet(): MutableSet<E> = toCollection(LinkedHashSet()) /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.any(): Boolean = consume { return iterator().hasNext() } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.count(): Int { var count = 0 consumeEach { count++ } return count } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.maxWith(comparator: Comparator<in E>): E? = consume { val iterator = iterator() if (!iterator.hasNext()) return null var max = iterator.next() while (iterator.hasNext()) { val e = iterator.next() if (comparator.compare(max, e) < 0) max = e } return max } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.minWith(comparator: Comparator<in E>): E? = consume { val iterator = iterator() if (!iterator.hasNext()) return null var min = iterator.next() while (iterator.hasNext()) { val e = iterator.next() if (comparator.compare(min, e) > 0) min = e } return min } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public suspend fun <E> ReceiveChannel<E>.none(): Boolean = consume { return !iterator().hasNext() } /** @suppress **/ @Deprecated(message = "Left for binary compatibility", level = DeprecationLevel.HIDDEN) public fun <E : Any> ReceiveChannel<E?>.requireNoNulls(): ReceiveChannel<E> = map { it ?: throw IllegalArgumentException("null element found in $this.") } /** @suppress **/ @Deprecated(message = "Binary compatibility", level = DeprecationLevel.HIDDEN) public infix fun <E, R> ReceiveChannel<E>.zip(other: ReceiveChannel<R>): ReceiveChannel<Pair<E, R>> = zip(other) { t1, t2 -> t1 to t2 } @PublishedApi // Binary compatibility internal fun <E, R, V> ReceiveChannel<E>.zip( other: ReceiveChannel<R>, context: CoroutineContext = Dispatchers.Unconfined, transform: (a: E, b: R) -> V ): ReceiveChannel<V> = GlobalScope.produce(context, onCompletion = consumesAll(this, other)) { val otherIterator = other.iterator() [email protected] { element1 -> if (!otherIterator.hasNext()) return@consumeEach val element2 = otherIterator.next() send(transform(element1, element2)) } } @PublishedApi // Binary compatibility internal fun ReceiveChannel<*>.consumes(): CompletionHandler = { cause: Throwable? -> cancelConsumed(cause) }
apache-2.0
3004864428d2db204bd552f22e071f1c
31.803347
129
0.634311
4.367688
false
false
false
false
code-helix/slatekit
src/apps/kotlin/slatekit-samples/src/main/kotlin/slatekit/samples/cli/CLI.kt
1
4076
package slatekit.samples.cli import slatekit.apis.* import slatekit.apis.routes.Api import slatekit.apis.support.Authenticator import slatekit.cli.CliSettings import slatekit.common.info.ApiKey import slatekit.common.types.* import slatekit.connectors.cli.CliApi import slatekit.connectors.entities.AppEntContext import slatekit.entities.EntityLongId import slatekit.entities.EntityService import slatekit.results.Try import slatekit.serialization.Serialization import slatekit.integration.apis.* import slatekit.integration.mods.* import slatekit.migrations.MigrationService import slatekit.migrations.MigrationSettings import slatekit.samples.common.apis.SampleAPI import slatekit.samples.common.models.Movie class CLI(val ctx: AppEntContext) { /** * executes the CLI integrated with the API module * to be able to call APIs on the command line * @return */ suspend fun execute(): Try<Any> { // 1. The API keys( DocApi, SetupApi are authenticated using an sample API key ) val keys = listOf(ApiKey( name ="cli", key = "abc", roles = "dev,qa,ops,admin")) // 2. Authentication val auth = Authenticator(keys) // 3. Load all the Slate Kit Universal APIs ctx.ent.register<Long, Movie>(EntityLongId(), "movie") { repo -> EntityService( repo ) } ctx.ent.register<Long, Mod>(EntityLongId(), "mod") { repo -> ModService(ctx.ent, repo)} val modSvc = ctx.ent.getServiceByType(Mod::class) as ModService val migSvc = MigrationService(ctx.ent, ctx.ent.dbs, MigrationSettings(true, true), ctx.dirs) val modCtx = ModuleContext(modSvc, migSvc ) val modApi = ModuleApi(modCtx, ctx) modApi.register(MovieModule(ctx, modCtx)) val apis = apis(modApi) // 4. Makes the APIs accessible on the CLI runner val cli = CliApi( ctx = ctx, auth = auth, settings = CliSettings(enableLogging = true, enableOutput = true), apiItems = apis, metaTransform = { listOf("api-key" to keys.first().key) }, serializer = {item, type -> print(item, type)} ) // 5. Run interactive mode cli.showOverview("Slate Kit CLI Sample") return cli.run() } fun apis(modApi:ModuleApi): List<Api> { return listOf( Api(klass = SampleAPI::class, singleton = SampleAPI(ctx), setup = SetupType.Annotated), Api(klass = EntitiesApi::class, singleton = EntitiesApi(ctx), setup = SetupType.Annotated), Api(klass = ModuleApi::class, singleton = modApi, setup = SetupType.Annotated) ) } private fun print(item:Any?, type:ContentType) : Content { val serializer = when(type){ ContentTypeCsv -> Serialization.csv() ContentTypeProp -> Serialization.props() else -> Serialization.json() } val text = serializer.serialize(item) return if(type == ContentTypeJson) { val wrap = """{ "value" : $text }""".trimMargin() val body = org.json.JSONObject(wrap) val pretty = body.toString(4) Content.text(pretty) } else { when(type){ ContentTypeCsv -> Content.csv(text) ContentTypeProp -> Content.prop(text) else -> Content.text(text) } } } class MovieModule(ctx:AppEntContext, mod:ModuleContext) : Module(ctx, mod) { override val info: ModuleInfo = ModuleInfo( name = Movie::class.qualifiedName!!, desc = "Supports user registration", version = "1.0", isInstalled = false, isEnabled = true, isDbDependent = true, totalModels = 1, source = Movie::class.qualifiedName!!, dependencies = "none", models = listOf<String>(Movie::class.qualifiedName!!) ) } }
apache-2.0
512933e1175da91f71537ba3da587898
36.063636
107
0.606968
4.420824
false
false
false
false
leafclick/intellij-community
java/java-tests/testSrc/com/intellij/java/psi/impl/search/JavaNullMethodArgumentIndexTest.kt
1
3599
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.java.psi.impl.search import com.intellij.openapi.fileTypes.StdFileTypes import com.intellij.psi.impl.search.JavaNullMethodArgumentIndex import com.intellij.testFramework.fixtures.BasePlatformTestCase import com.intellij.util.indexing.FileContentImpl import com.intellij.util.indexing.IndexingDataKeys class JavaNullMethodArgumentIndexTest : BasePlatformTestCase() { fun testIndex() { val file = myFixture.configureByText(StdFileTypes.JAVA, """ package org.some; class Main111 { Main111(Object o) { } void someMethod(Object o, Object o2, Object o3) { } static void staticMethod(Object o, Object o2, Object o3) { } public static void main(String[] args) { staticMethod(null , "", ""); org.some.Main111.staticMethod("", "", null""" + '\t' + """); new Main111(null).someMethod("", "", null ); String s = null; Main111 m = new Main111(null); m.someMethod(null, "", ""); } static class SubClass { SubClass(Object o) { } } static class SubClass2 { SubClass2(Object o) { } } static void main() { new org.some.Main111(null); new org.some.Main111.SubClass(null); new SubClass2(null); new ParametrizedRunnable(null) { @Override void run() { }}; } abstract class ParametrizedRunnable { Object parameter; ParametrizedRunnable(Object parameter){ this.parameter = parameter; } abstract void run(); } } """).virtualFile val content = FileContentImpl.createByFile(file, project) val data = JavaNullMethodArgumentIndex().indexer.map(content).keys assertSize(8, data) assertContainsElements(data, JavaNullMethodArgumentIndex.MethodCallData("staticMethod", 0), JavaNullMethodArgumentIndex.MethodCallData("staticMethod", 2), JavaNullMethodArgumentIndex.MethodCallData("someMethod", 0), JavaNullMethodArgumentIndex.MethodCallData("someMethod", 2), JavaNullMethodArgumentIndex.MethodCallData("Main111", 0), JavaNullMethodArgumentIndex.MethodCallData("SubClass", 0), JavaNullMethodArgumentIndex.MethodCallData("SubClass2", 0), JavaNullMethodArgumentIndex.MethodCallData("ParametrizedRunnable", 0)) } }
apache-2.0
7f84436db012b67b8c5937683e72ab77
33.285714
97
0.558488
5.685624
false
false
false
false
jackbbb95/LurkApp
app/src/main/java/com/jonathan/bogle/lurk/data/presenter/main/MainActivityPresenter.kt
1
5732
package com.jonathan.bogle.lurk.data.presenter.main import android.util.Log import com.jonathan.bogle.lurk.R import com.jonathan.bogle.lurk.prefs import com.jonathan.bogle.lurk.ui.Contracts import com.jonathan.bogle.lurk.ui.main.MainActivity import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.Deferred import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.async import kotlinx.coroutines.experimental.delay import net.dean.jraw.RedditClient import net.dean.jraw.http.UserAgent import net.dean.jraw.http.oauth.Credentials import net.dean.jraw.models.Listing import net.dean.jraw.models.Submission import net.dean.jraw.paginators.Sorting import net.dean.jraw.paginators.SubredditPaginator import net.dean.jraw.paginators.TimePeriod import java.util.* import kotlin.system.measureTimeMillis /** * Created by bogle on 7/27/17. */ class MainActivityPresenter(val view: Contracts.MainActivity) { private val userAgent by lazy { UserAgent.of("mobile", "com.jonathan.bogle.lurk", "v0.1", "ImAzN"); } private val credentials by lazy { getRedditCredentials() } private val reddit by lazy { RedditClient(userAgent) } private var currentPaginator: SubredditPaginator? = null private var currentSubreddits: ArrayList<String>? = null private var currentTimePeriod: TimePeriod? = null private var currentSorting: Sorting? = null private var currentPage: Int = 0 companion object { const val SUBMISSIONS_PER_CALL = 25 const val MINIMUM_LOAD_TIME = 1000 //ms } //Gets next submissions based on parameters (could be next page or new results) fun getSubmissions(sr: ArrayList<String>?, subLimit: Int?, timePeriod: TimePeriod?, sorting: Sorting?) { val paginator = getSubredditPaginator(sr,subLimit,timePeriod,sorting) getNextAsync(paginator) } //Gets the next page of results fun getMoreSubmissions() { currentPaginator?.let { getNextAsync(currentPaginator!!) } } //Recreates the paginator and re-retrieves submissions fun refreshSubmissions() { currentPaginator = null currentPage = 0 getSubmissions(currentSubreddits,SUBMISSIONS_PER_CALL,currentTimePeriod,currentSorting) } //Makes the call to the API fun getNextAsync(paginator: SubredditPaginator) = async(UI) { Log.d("JRAW", "${paginator.subreddit} : ${paginator.sorting} : ${paginator.timePeriod} : ${paginator.pageIndex}") try { if(currentPage < 1) view.showLoading() var results: Listing<Submission>? = null val loadTime = measureTimeMillis { if(!reddit.isAuthenticated) asyncAuthenticate().await() results = asyncGetNext(paginator).await() } //Minimum load time if(loadTime < MINIMUM_LOAD_TIME) delay(MINIMUM_LOAD_TIME - loadTime) view.addSubmissionsToRecycler(ArrayList(results), ++currentPage == 1) } catch (e: Exception) { e.printStackTrace() } finally { view.hideLoading() } } //Returns a paginator of the following parameters. Returns the previous paginator if there is no difference private fun getSubredditPaginator(sr: ArrayList<String>?, subLimit: Int?, timePeriod: TimePeriod?, sorting: Sorting?): SubredditPaginator { if(currentPaginator == null || currentSubreddits != sr || currentTimePeriod != timePeriod || currentSorting != sorting) { //Create new paginator if it differs from the current one currentPaginator = getNewSubredditPaginator(sr).apply { currentSubreddits = sr currentTimePeriod = timePeriod currentSorting = sorting currentPage = 0 if(currentSorting != Sorting.TOP && currentSorting != Sorting.CONTROVERSIAL) currentTimePeriod = null subLimit?.let { setLimit(subLimit) } ?: setLimit(SUBMISSIONS_PER_CALL) currentTimePeriod?.let { setTimePeriod(currentTimePeriod) } ?: setTimePeriod(null) currentSorting?.let { setSorting(currentSorting) } ?: setSorting(null) } } return currentPaginator as SubredditPaginator } //Returns a SubredditPaginator for the list of subreddits (Defaults to All) private fun getNewSubredditPaginator(sr: ArrayList<String>?): SubredditPaginator { sr?.let { if(sr.size == 1) return SubredditPaginator(reddit,sr[0]) else return SubredditPaginator(reddit, sr[0], *sr.subList(1, sr.size).toTypedArray()) } ?: return SubredditPaginator(reddit,"all") } private fun getRedditCredentials(): Credentials { val context = view as MainActivity if(prefs.needsLogin) //TODO change to login credential logic return Credentials.userlessApp(context.getString(R.string.reddit_client_id), UUID.randomUUID()) else return Credentials.userlessApp(context.getString(R.string.reddit_client_id), UUID.randomUUID()) } private fun asyncGetNext(paginator: SubredditPaginator): Deferred<Listing<Submission>> = async(CommonPool) { paginator.next() } private fun asyncAuthenticate() = async(CommonPool) { val auth = reddit.oAuthHelper.easyAuth(credentials) reddit.authenticate(auth) } }
apache-2.0
598cdf5f063b0d4287154a9dda0a0784
39.373239
143
0.654571
4.694513
false
false
false
false
moko256/twicalico
app/src/main/java/com/github/moko256/twitlatte/ListsTimelineActivity.kt
1
2220
/* * Copyright 2015-2019 The twitlatte 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 com.github.moko256.twitlatte import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import com.github.moko256.latte.client.base.entity.ListEntry /** * Created by moko256 on 2019/01/02. * * @author moko256 */ class ListsTimelineActivity : AppCompatActivity(), BaseListFragment.GetViewForSnackBar { private var listId = -1L public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val intent = intent listId = intent?.getLongExtra("listId", -1) ?: -1 supportActionBar?.let { it.title = intent?.getCharSequenceExtra("title") ?: "" it.setDisplayHomeAsUpEnabled(true) it.setHomeAsUpIndicator(R.drawable.ic_back_white_24dp) } supportFragmentManager .beginTransaction() .add(android.R.id.content, ListsTimelineFragment().apply { arguments = intent.extras }) .commit() } override fun getViewForSnackBar(): View { return findViewById(android.R.id.content) } override fun onSupportNavigateUp(): Boolean { finish() return true } companion object { fun getIntent(context: Context, entry: ListEntry): Intent { return Intent(context, ListsTimelineActivity::class.java) .apply { putExtra("listId", entry.listId) putExtra("title", entry.title) } } } }
apache-2.0
fa02d4190bc0dc4ee0dadb1f70b51953
29.424658
103
0.659459
4.634656
false
false
false
false
ingokegel/intellij-community
platform/workspaceModel/storage/gen/com/intellij/workspaceModel/storage/bridgeEntities/api/ModuleOutputPackagingElementEntityImpl.kt
1
11365
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.workspaceModel.storage.bridgeEntities.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.PersistentEntityId import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.EntityLink import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.SoftLinkable import com.intellij.workspaceModel.storage.impl.UsedClassesCollector import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import com.intellij.workspaceModel.storage.impl.extractOneToAbstractManyParent import com.intellij.workspaceModel.storage.impl.indices.WorkspaceMutableIndex import com.intellij.workspaceModel.storage.impl.updateOneToAbstractManyParentOfChild import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Abstract import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ModuleOutputPackagingElementEntityImpl : ModuleOutputPackagingElementEntity, WorkspaceEntityBase() { companion object { internal val PARENTENTITY_CONNECTION_ID: ConnectionId = ConnectionId.create(CompositePackagingElementEntity::class.java, PackagingElementEntity::class.java, ConnectionId.ConnectionType.ONE_TO_ABSTRACT_MANY, true) val connections = listOf<ConnectionId>( PARENTENTITY_CONNECTION_ID, ) } override val parentEntity: CompositePackagingElementEntity? get() = snapshot.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) @JvmField var _module: ModuleId? = null override val module: ModuleId? get() = _module override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ModuleOutputPackagingElementEntityData?) : ModifiableWorkspaceEntityBase<ModuleOutputPackagingElementEntity>(), ModuleOutputPackagingElementEntity.Builder { constructor() : this(ModuleOutputPackagingElementEntityData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ModuleOutputPackagingElementEntity is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isEntitySourceInitialized()) { error("Field WorkspaceEntity#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } // Relabeling code, move information from dataSource to this builder override fun relabel(dataSource: WorkspaceEntity, parents: Set<WorkspaceEntity>?) { dataSource as ModuleOutputPackagingElementEntity this.entitySource = dataSource.entitySource this.module = dataSource.module if (parents != null) { this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() } } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override var parentEntity: CompositePackagingElementEntity? get() { val _diff = diff return if (_diff != null) { _diff.extractOneToAbstractManyParent(PARENTENTITY_CONNECTION_ID, this) ?: this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } else { this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] as? CompositePackagingElementEntity } } set(value) { checkModificationAllowed() val _diff = diff if (_diff != null && value is ModifiableWorkspaceEntityBase<*> && value.diff == null) { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable _diff.addEntity(value) } if (_diff != null && (value !is ModifiableWorkspaceEntityBase<*> || value.diff != null)) { _diff.updateOneToAbstractManyParentOfChild(PARENTENTITY_CONNECTION_ID, this, value) } else { // Setting backref of the list if (value is ModifiableWorkspaceEntityBase<*>) { val data = (value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] as? List<Any> ?: emptyList()) + this value.entityLinks[EntityLink(true, PARENTENTITY_CONNECTION_ID)] = data } // else you're attaching a new entity to an existing entity that is not modifiable this.entityLinks[EntityLink(false, PARENTENTITY_CONNECTION_ID)] = value } changedProperty.add("parentEntity") } override var module: ModuleId? get() = getEntityData().module set(value) { checkModificationAllowed() getEntityData().module = value changedProperty.add("module") } override fun getEntityData(): ModuleOutputPackagingElementEntityData = result ?: super.getEntityData() as ModuleOutputPackagingElementEntityData override fun getEntityClass(): Class<ModuleOutputPackagingElementEntity> = ModuleOutputPackagingElementEntity::class.java } } class ModuleOutputPackagingElementEntityData : WorkspaceEntityData<ModuleOutputPackagingElementEntity>(), SoftLinkable { var module: ModuleId? = null override fun getLinks(): Set<PersistentEntityId<*>> { val result = HashSet<PersistentEntityId<*>>() val optionalLink_module = module if (optionalLink_module != null) { result.add(optionalLink_module) } return result } override fun index(index: WorkspaceMutableIndex<PersistentEntityId<*>>) { val optionalLink_module = module if (optionalLink_module != null) { index.index(this, optionalLink_module) } } override fun updateLinksIndex(prev: Set<PersistentEntityId<*>>, index: WorkspaceMutableIndex<PersistentEntityId<*>>) { // TODO verify logic val mutablePreviousSet = HashSet(prev) val optionalLink_module = module if (optionalLink_module != null) { val removedItem_optionalLink_module = mutablePreviousSet.remove(optionalLink_module) if (!removedItem_optionalLink_module) { index.index(this, optionalLink_module) } } for (removed in mutablePreviousSet) { index.remove(this, removed) } } override fun updateLink(oldLink: PersistentEntityId<*>, newLink: PersistentEntityId<*>): Boolean { var changed = false var module_data_optional = if (module != null) { val module___data = if (module!! == oldLink) { changed = true newLink as ModuleId } else { null } module___data } else { null } if (module_data_optional != null) { module = module_data_optional } return changed } override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ModuleOutputPackagingElementEntity> { val modifiable = ModuleOutputPackagingElementEntityImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ModuleOutputPackagingElementEntity { val entity = ModuleOutputPackagingElementEntityImpl() entity._module = module entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ModuleOutputPackagingElementEntity::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun createDetachedEntity(parents: List<WorkspaceEntity>): WorkspaceEntity { return ModuleOutputPackagingElementEntity(entitySource) { this.module = [email protected] this.parentEntity = parents.filterIsInstance<CompositePackagingElementEntity>().singleOrNull() } } override fun getRequiredParents(): List<Class<out WorkspaceEntity>> { val res = mutableListOf<Class<out WorkspaceEntity>>() return res } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ModuleOutputPackagingElementEntityData if (this.entitySource != other.entitySource) return false if (this.module != other.module) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ModuleOutputPackagingElementEntityData if (this.module != other.module) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + module.hashCode() return result } override fun hashCodeIgnoringEntitySource(): Int { var result = javaClass.hashCode() result = 31 * result + module.hashCode() return result } override fun collectClassUsagesData(collector: UsedClassesCollector) { collector.add(ModuleId::class.java) collector.sameForAllEntities = true } }
apache-2.0
3400c7e3cebadd806e94e5e63e3d93ab
36.508251
184
0.704619
5.612346
false
false
false
false
mdaniel/intellij-community
platform/workspaceModel/storage/testEntities/gen/com/intellij/workspaceModel/storage/entities/test/api/ChildWithNullsMultipleImpl.kt
1
5906
package com.intellij.workspaceModel.storage.entities.test.api import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntityInformation import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.EntityStorage import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.GeneratedCodeImplVersion import com.intellij.workspaceModel.storage.ModifiableWorkspaceEntity import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.ConnectionId import com.intellij.workspaceModel.storage.impl.ModifiableWorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityBase import com.intellij.workspaceModel.storage.impl.WorkspaceEntityData import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child @GeneratedCodeApiVersion(1) @GeneratedCodeImplVersion(1) open class ChildWithNullsMultipleImpl: ChildWithNullsMultiple, WorkspaceEntityBase() { companion object { val connections = listOf<ConnectionId>( ) } @JvmField var _childData: String? = null override val childData: String get() = _childData!! override fun connectionIdList(): List<ConnectionId> { return connections } class Builder(val result: ChildWithNullsMultipleData?): ModifiableWorkspaceEntityBase<ChildWithNullsMultiple>(), ChildWithNullsMultiple.Builder { constructor(): this(ChildWithNullsMultipleData()) override fun applyToBuilder(builder: MutableEntityStorage) { if (this.diff != null) { if (existsInBuilder(builder)) { this.diff = builder return } else { error("Entity ChildWithNullsMultiple is already created in a different builder") } } this.diff = builder this.snapshot = builder addToBuilder() this.id = getEntityData().createEntityId() // Process linked entities that are connected without a builder processLinkedEntities(builder) checkInitialization() // TODO uncomment and check failed tests } fun checkInitialization() { val _diff = diff if (!getEntityData().isChildDataInitialized()) { error("Field ChildWithNullsMultiple#childData should be initialized") } if (!getEntityData().isEntitySourceInitialized()) { error("Field ChildWithNullsMultiple#entitySource should be initialized") } } override fun connectionIdList(): List<ConnectionId> { return connections } override var childData: String get() = getEntityData().childData set(value) { checkModificationAllowed() getEntityData().childData = value changedProperty.add("childData") } override var entitySource: EntitySource get() = getEntityData().entitySource set(value) { checkModificationAllowed() getEntityData().entitySource = value changedProperty.add("entitySource") } override fun getEntityData(): ChildWithNullsMultipleData = result ?: super.getEntityData() as ChildWithNullsMultipleData override fun getEntityClass(): Class<ChildWithNullsMultiple> = ChildWithNullsMultiple::class.java } } class ChildWithNullsMultipleData : WorkspaceEntityData<ChildWithNullsMultiple>() { lateinit var childData: String fun isChildDataInitialized(): Boolean = ::childData.isInitialized override fun wrapAsModifiable(diff: MutableEntityStorage): ModifiableWorkspaceEntity<ChildWithNullsMultiple> { val modifiable = ChildWithNullsMultipleImpl.Builder(null) modifiable.allowModifications { modifiable.diff = diff modifiable.snapshot = diff modifiable.id = createEntityId() modifiable.entitySource = this.entitySource } modifiable.changedProperty.clear() return modifiable } override fun createEntity(snapshot: EntityStorage): ChildWithNullsMultiple { val entity = ChildWithNullsMultipleImpl() entity._childData = childData entity.entitySource = entitySource entity.snapshot = snapshot entity.id = createEntityId() return entity } override fun getEntityInterface(): Class<out WorkspaceEntity> { return ChildWithNullsMultiple::class.java } override fun serialize(ser: EntityInformation.Serializer) { } override fun deserialize(de: EntityInformation.Deserializer) { } override fun equals(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildWithNullsMultipleData if (this.childData != other.childData) return false if (this.entitySource != other.entitySource) return false return true } override fun equalsIgnoringEntitySource(other: Any?): Boolean { if (other == null) return false if (this::class != other::class) return false other as ChildWithNullsMultipleData if (this.childData != other.childData) return false return true } override fun hashCode(): Int { var result = entitySource.hashCode() result = 31 * result + childData.hashCode() return result } }
apache-2.0
b09f6393116f29cb6f92f5c894e69fed
35.239264
149
0.660007
6.120207
false
false
false
false