repo_name
stringlengths
7
81
path
stringlengths
6
242
copies
stringclasses
55 values
size
stringlengths
2
6
content
stringlengths
55
737k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
5.44
99.8
line_max
int64
15
979
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.93
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
EMResearch/EvoMaster
core/src/main/kotlin/org/evomaster/core/problem/httpws/service/HttpWsFitness.kt
1
11967
package org.evomaster.core.problem.httpws.service import com.fasterxml.jackson.databind.ObjectMapper import org.evomaster.client.java.controller.api.dto.* import org.evomaster.core.StaticCounter import org.evomaster.core.database.DbAction import org.evomaster.core.database.DbActionTransformer import org.evomaster.core.logging.LoggingUtil import org.evomaster.core.output.CookieWriter import org.evomaster.core.output.TokenWriter import org.evomaster.core.problem.api.service.ApiWsFitness import org.evomaster.core.problem.api.service.ApiWsIndividual import org.evomaster.core.problem.rest.* import org.evomaster.core.problem.rest.param.HeaderParam import org.evomaster.core.remote.SutProblemException import org.evomaster.core.search.Action import org.evomaster.core.search.Individual import org.glassfish.jersey.client.ClientConfig import org.glassfish.jersey.client.ClientProperties import org.glassfish.jersey.client.HttpUrlConnectorProvider import org.slf4j.Logger import org.slf4j.LoggerFactory import java.net.MalformedURLException import java.net.URL import javax.annotation.PostConstruct import javax.ws.rs.client.Client import javax.ws.rs.client.ClientBuilder import javax.ws.rs.client.Entity import javax.ws.rs.client.Invocation import javax.ws.rs.core.MediaType import javax.ws.rs.core.NewCookie import javax.ws.rs.core.Response abstract class HttpWsFitness<T>: ApiWsFitness<T>() where T : Individual { companion object { private val log: Logger = LoggerFactory.getLogger(HttpWsFitness::class.java) init{ System.setProperty("sun.net.http.allowRestrictedHeaders", "true"); } } protected lateinit var client : Client @PostConstruct protected fun initialize() { log.debug("Initializing {}", HttpWsFitness::class.simpleName) val clientConfiguration = ClientConfig() .property(ClientProperties.CONNECT_TIMEOUT, 10_000) .property(ClientProperties.READ_TIMEOUT, config.tcpTimeoutMs) //workaround bug in Jersey client .property(HttpUrlConnectorProvider.SET_METHOD_WORKAROUND, true) .property(ClientProperties.FOLLOW_REDIRECTS, false) client = ClientBuilder.newClient(clientConfiguration) if (!config.blackBox || config.bbExperiments) { rc.checkConnection() val started = rc.startSUT() if (!started) { throw SutProblemException("Failed to start the system under test") } infoDto = rc.getSutInfo() ?: throw SutProblemException("Failed to retrieve the info about the system under test") } log.debug("Done initializing {}", HttpWsFitness::class.simpleName) } override fun reinitialize(): Boolean { try { if (!config.blackBox) { rc.stopSUT() } initialize() } catch (e: Exception) { log.warn("Failed to re-initialize the SUT: $e") return false } return true } open fun getlocation5xx(status: Int, additionalInfoList: List<AdditionalInfoDto>, indexOfAction: Int, result: HttpWsCallResult, name: String) : String?{ var location5xx : String? = null if (status == 500){ val statement = additionalInfoList[indexOfAction].lastExecutedStatement location5xx = statement ?: DEFAULT_FAULT_CODE result.setLastStatementWhen500(location5xx) } return location5xx } protected fun getBaseUrl(): String { var baseUrl = if (!config.blackBox || config.bbExperiments) { infoDto.baseUrlOfSUT } else { BlackBoxUtils.targetUrl(config, sampler) } try{ /* Note: this in theory should already been checked: either in EMConfig for Black-box testing, or already in the driver for White-Box testing */ URL(baseUrl) } catch (e: MalformedURLException){ val base = "Invalid 'baseUrl'." val wb = "In the EvoMaster driver, in the startSut() method, you must make sure to return a valid URL." val err = " ERROR: $e" val msg = if(config.blackBox) "$base $err" else "$base $wb $err" throw SutProblemException(msg) } if (baseUrl.endsWith("/")) { baseUrl = baseUrl.substring(0, baseUrl.length - 1) } return baseUrl } /** * If any action needs auth based on tokens via JSON, do a "login" before * running the actions, and store the tokens */ protected fun getTokens(ind: T): Map<String, String>{ val tokensLogin = TokenWriter.getTokenLoginAuth(ind) //from userId to Token val map = mutableMapOf<String, String>() val baseUrl = getBaseUrl() for(tl in tokensLogin){ val response = try { client.target(baseUrl + tl.endpoint) .request() .buildPost(Entity.entity(tl.jsonPayload, MediaType.APPLICATION_JSON_TYPE)) .invoke() } catch (e: Exception) { log.warn("Failed to login for ${tl.userId}: $e") continue } if (response.statusInfo.family != Response.Status.Family.SUCCESSFUL) { log.warn("Login request failed with status ${response.status}") continue } if(! response.hasEntity()){ log.warn("Login request failed, with no body response from which to extract the auth token") continue } val body = response.readEntity(String::class.java) val jackson = ObjectMapper() val tree = jackson.readTree(body) var token = tree.at(tl.extractTokenField).asText() if(token == null || token.isEmpty()){ log.warn("Failed login. Cannot extract token '${tl.extractTokenField}' from response: $body") continue } if(tl.headerPrefix.isNotEmpty()){ token = tl.headerPrefix + token } map[tl.userId] = token } return map } /** * If any action needs auth based on cookies, do a "login" before * running the actions, and collect the cookies from the server. * * @return a map from username to auth cookie for those users */ protected fun getCookies(ind: T): Map<String, List<NewCookie>> { val cookieLogins = CookieWriter.getCookieLoginAuth(ind) val map: MutableMap<String, List<NewCookie>> = mutableMapOf() val baseUrl = getBaseUrl() for (cl in cookieLogins) { val mediaType = when (cl.contentType) { ContentType.X_WWW_FORM_URLENCODED -> MediaType.APPLICATION_FORM_URLENCODED_TYPE ContentType.JSON -> MediaType.APPLICATION_JSON_TYPE } val response = try { client.target(cl.getUrl(baseUrl)) .request() //TODO could consider other cases besides POST .buildPost(Entity.entity(cl.payload(), mediaType)) .invoke() } catch (e: Exception) { log.warn("Failed to login for ${cl.username}/${cl.password}: $e") continue } if (response.statusInfo.family != Response.Status.Family.SUCCESSFUL) { /* if it is a 3xx, we need to look at Location header to determine if a success or failure. TODO: could explicitly ask for this info in the auth DTO. However, as 3xx makes little sense in a REST API, maybe not so important right now, although had this issue with some APIs using default settings in Spring Security */ if (response.statusInfo.family == Response.Status.Family.REDIRECTION) { val location = response.getHeaderString("location") if (location != null && (location.contains("error", true) || location.contains("login", true))) { log.warn("Login request failed with ${response.status} redirection toward $location") continue } } else { log.warn("Login request failed with status ${response.status}") continue } } if (response.cookies.isEmpty()) { log.warn("Cookie-based login request did not give back any new cookie") continue } map[cl.username] = response.cookies.values.toList() } return map } protected fun registerNewAction(action: Action, index: Int){ rc.registerNewAction(getActionDto(action, index)) } @Deprecated("replaced by doDbCalls()") open fun doInitializingActions(ind: ApiWsIndividual) { if (log.isTraceEnabled){ log.trace("do {} InitializingActions: {}", ind.seeInitializingActions().size, ind.seeInitializingActions().filterIsInstance<DbAction>().joinToString(","){ it.getResolvedName() }) } if (ind.seeInitializingActions().filterIsInstance<DbAction>().none { !it.representExistingData }) { /* We are going to do an initialization of database only if there is data to add. Note that current data structure also keeps info on already existing data (which of course should not be re-inserted...) */ return } val dto = DbActionTransformer.transform(ind.seeInitializingActions().filterIsInstance<DbAction>()) dto.idCounter = StaticCounter.getAndIncrease() val ok = rc.executeDatabaseCommand(dto) if (!ok) { //this can happen if we do not handle all constraints LoggingUtil.uniqueWarn(log, "Failed in executing database command") } } protected fun handleHeaders(a: HttpWsAction, builder: Invocation.Builder, cookies: Map<String, List<NewCookie>>, tokens: Map<String, String>) { a.auth.headers.forEach { builder.header(it.name, it.value) } val prechosenAuthHeaders = a.auth.headers.map { it.name } /* TODO: optimization, avoid mutating header gene if anyway using pre-chosen one */ a.parameters.filterIsInstance<HeaderParam>() //TODO those should be skipped directly in the search, ie, right now they are useless genes .filter { !prechosenAuthHeaders.contains(it.name) } .filter { !(a.auth.jsonTokenPostLogin != null && it.name.equals("Authorization", true)) } .filter{ it.isInUse()} .forEach { builder.header(it.name, it.gene.getValueAsRawString()) } if (a.auth.cookieLogin != null) { val list = cookies[a.auth.cookieLogin!!.username] if (list == null || list.isEmpty()) { log.warn("No cookies for ${a.auth.cookieLogin!!.username}") } else { list.forEach { builder.cookie(it.toCookie()) } } } if (a.auth.jsonTokenPostLogin != null) { val token = tokens[a.auth.jsonTokenPostLogin!!.userId] if (token == null || token.isEmpty()) { log.warn("No auth token for ${a.auth.jsonTokenPostLogin!!.userId}") } else { builder.header("Authorization", token) } } } }
lgpl-3.0
c66bce89e28306a52dad30bac2d298e9
35.266667
156
0.591376
4.868592
false
false
false
false
fuzhouch/qbranch
core/src/main/kotlin/net/dummydigit/qbranch/ReflectionExtensions.kt
1
2706
// Licensed under the MIT license. See LICENSE file in the project root // for full license information. @file:JvmName("ReflectionExtensions") package net.dummydigit.qbranch import net.dummydigit.qbranch.annotations.QBranchGeneratedCode import java.lang.reflect.Field import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import kotlin.reflect.KClass /** A function to check if given class is a generated bond class. * @return True if cls is Bond generated, or false if not. */ fun Class<*>.isQBranchGeneratedStruct() : Boolean { val isBondGenerated = this.getAnnotation(QBranchGeneratedCode::class.java) != null return isBondGenerated && !this.isEnum } /** * A function to check if given class is a generic type. * @return True if class is generic type, or false if not. */ fun Class<*>.isGenericClass() : Boolean { return this.typeParameters.size > 0 } /** * A function to check if given Kotlin class is a generic type. * @return True if class is generic type, or false if not. */ fun KClass<*>.isGenericClass() : Boolean { return this.java.isGenericClass() } fun Class<*>.isQBranchBuiltinType() : Boolean = when (this) { String::class.java -> true Byte::class.java -> true Short::class.java -> true Int::class.java -> true Long::class.java -> true UnsignedByte::class.java -> true UnsignedShort::class.java -> true UnsignedInt::class.java -> true UnsignedLong::class.java -> true ByteString::class.java -> true // TODO: Add container types later. else -> false } fun KClass<*>.isQBranchBuiltinType() : Boolean { return this.java.isQBranchBuiltinType() } /** * Tell whether a given field has a generic type. */ fun Field.isGenericType() : Boolean { val declaredType = this.genericType val realType = this.type return (declaredType !is ParameterizedType) && declaredType != (realType) } /** * A helper class to retrieve type arguments of given type. */ abstract class TypeReference<T> : Comparable<TypeReference<T>> { val type: Type = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0] override fun compareTo(other: TypeReference<T>) = 0 } /** * Extract type arguments of generic types. Callable from Kotlin code only. * @return An array of type, which represents the list of type arguments. */ inline fun <reified T: Any> extractGenericTypeArguments() : Array<Type> { // Make use of generic type token to allow we val type = object : TypeReference<T>() {}.type if (type is ParameterizedType) { return type.actualTypeArguments } else { throw UnsupportedOperationException("NonParameterizedType:type=$type") } }
mit
f4d62bb6bb103af3ea71cb28e6580f9e
30.103448
94
0.712491
4.112462
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/bitmapFont/highlighting/BitmapFontHighlighter.kt
1
3606
package com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.highlighting import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.BitmapFontElementTypes import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.BitmapFontKey import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.BitmapFontProperty import com.gmail.blueboxware.libgdxplugin.filetypes.bitmapFont.psi.BitmapFontValue import com.gmail.blueboxware.libgdxplugin.utils.isLeaf import com.intellij.lang.annotation.AnnotationHolder import com.intellij.lang.annotation.Annotator import com.intellij.lang.annotation.HighlightSeverity import com.intellij.openapi.util.TextRange import com.intellij.psi.PsiElement import org.jetbrains.kotlin.psi.psiUtil.startOffset /* * Copyright 2017 Blue Box Ware * * 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. */ class BitmapFontHighlighter : Annotator { companion object { val KEYWORDS = listOf("info", "common", "page", "chars", "char", "kernings", "kerning") } override fun annotate(element: PsiElement, holder: AnnotationHolder) { if (element is BitmapFontProperty) { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(element.keyElement) .textAttributes(BitmapFontColorSettingsPage.KEY) .create() element.valueElement?.let { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(it) .textAttributes(BitmapFontColorSettingsPage.VALUE) .create() } element.node.getChildren(null).forEach { node -> if (node.text == "=") { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(node) .textAttributes(BitmapFontColorSettingsPage.EQUALS_SIGN) .create() } } element.valueElement?.let { valueElement -> val valueText = valueElement.text val start = valueElement.startOffset for (i in valueText.indices) { if (valueText[i] == ',') { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(TextRange(start + i, start + i + 1)) .textAttributes(BitmapFontColorSettingsPage.COMMA) .create() } } } } else if (element.isLeaf(BitmapFontElementTypes.UNQUOTED_STRING)) { if (KEYWORDS.contains(element.text) && element.parent !is BitmapFontKey && element.parent !is BitmapFontValue) { holder .newSilentAnnotation(HighlightSeverity.INFORMATION) .range(element) .textAttributes(BitmapFontColorSettingsPage.KEYWORD) .create() } } } }
apache-2.0
6975ef92bcef1fdf26029b5fab538194
39.977273
124
0.621742
5.414414
false
false
false
false
BlueBoxWare/LibGDXPlugin
src/main/kotlin/com/gmail/blueboxware/libgdxplugin/filetypes/json/inspections/GdxJsonBaseInspection.kt
1
1530
package com.gmail.blueboxware.libgdxplugin.filetypes.json.inspections import com.gmail.blueboxware.libgdxplugin.filetypes.json.psi.GdxJsonElement import com.gmail.blueboxware.libgdxplugin.filetypes.json.utils.isSuppressed import com.intellij.codeInspection.LocalInspectionTool import com.intellij.codeInspection.SuppressQuickFix import com.intellij.psi.PsiElement /* * Copyright 2019 Blue Box Ware * * 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. */ abstract class GdxJsonBaseInspection : LocalInspectionTool() { protected fun getShortID() = id.removePrefix("LibGDXJson") override fun getGroupPath() = arrayOf("libGDX", "JSON") @Suppress("DialogTitleCapitalization") override fun getGroupDisplayName() = "libGDX" override fun isEnabledByDefault() = true override fun isSuppressedFor(element: PsiElement): Boolean = (element as? GdxJsonElement)?.isSuppressed(getShortID()) ?: false abstract override fun getBatchSuppressActions(element: PsiElement?): Array<SuppressQuickFix> }
apache-2.0
7e39acff8d819e62fb223144a573c366
35.428571
96
0.773856
4.766355
false
false
false
false
eurofurence/ef-app_android
app/src/main/kotlin/org/eurofurence/connavigator/util/v2/Stored.kt
1
8838
@file:Suppress("unused") package org.eurofurence.connavigator.util.v2 import android.content.Context import com.google.gson.stream.JsonReader import com.google.gson.stream.JsonToken import com.google.gson.stream.JsonWriter import io.reactivex.Flowable import io.swagger.client.JsonUtil.getGson import io.swagger.client.JsonUtil.getListTypeForDeserialization import org.eurofurence.connavigator.util.extensions.* import java.io.File import java.io.ObjectInputStream import java.io.ObjectOutputStream import java.util.* import kotlin.reflect.KClass import kotlin.reflect.KProperty /** * Container of stored values. */ abstract class Stored(val context: Context) { /** * A stored value. */ inner class StoredValue<T : Any>( private val elementClass: KClass<T>, private val swaggerStored: Boolean) { operator fun getValue(any: Any, kProperty: KProperty<*>): T? { val file = File(context.filesDir, "${kProperty.name}.val") if (!file.exists()) return null else if (swaggerStored) JsonReader(file.safeReader()).use { return getGson().fromJson<T>(it, elementClass.java) } else ObjectInputStream(file.safeInStream()).use { @Suppress("unchecked_cast") return it.readObject() as T } } operator fun setValue(any: Any, kProperty: KProperty<*>, t: T?) { val file = File(context.filesDir, "${kProperty.name}.val") if (t == null) file.delete() else if (swaggerStored) JsonWriter(file.safeWriter()).use { getGson().toJson(t, elementClass.java, it) } else file.substitute { sub -> ObjectOutputStream(sub.safeOutStream()).use { it.writeObject(t) } } } } /** * A stored list of values. */ inner class StoredValues<T : Any>( private val elementClass: KClass<T>, private val swaggerStored: Boolean) { operator fun getValue(any: Any, kProperty: KProperty<*>): List<T> { val file = File(context.filesDir, "${kProperty.name}.val") if (!file.exists()) return emptyList() else if (swaggerStored) JsonReader(file.safeReader()).use { return getGson().fromJson<List<T>>(it, getListTypeForDeserialization(elementClass.java)) } else ObjectInputStream(file.safeInStream()).use { @Suppress("unchecked_cast") return it.readObject() as List<T> } } operator fun setValue(any: Any, kProperty: KProperty<*>, t: List<T>) { val file = File(context.filesDir, "${kProperty.name}.val") when { t.isEmpty() -> file.delete() swaggerStored -> JsonWriter(file.safeWriter()).use { getGson().toJson(t, getListTypeForDeserialization(elementClass.java), it) } else -> file.substitute { sub -> ObjectOutputStream(sub.safeOutStream()).use { it.writeObject(t) } } } } } /** * A stored source that caches elements and creates an index via the [id] function. */ inner class StoredSource<T : Any>( private val elementClass: KClass<T>, val id: (T) -> UUID) : Source<T, UUID> { /** * Storage file, generated from the type name. */ private val file = File(context.filesDir, "${elementClass.qualifiedName}.db") /** * Last time of read or write-through. */ private var readTime: Long? = null /** * Last value of read or write-through. */ private val readValue = hashMapOf<UUID, T>() /** * Streams the elements as an observable. */ fun stream(): Flowable<T> = Flowable.fromIterable(items) /** * The entries of the database, writing serializes with GSON. */ var entries: Map<UUID, T> get() { synchronized(file) { // File does not exist, therefore not content if (!file.exists()) return emptyMap() // File modified since last read, load changes if (file.lastModified() != readTime) JsonReader(file.safeReader()).use { // Carry file time attribute and reset the values. readTime = file.lastModified() readValue.clear() // Get the GSON object and keep it, as it is used multiple times. val gson = getGson() // Assert that the file contains an array. if (it.peek() == JsonToken.BEGIN_ARRAY) { // Consume the start. it.beginArray() // Until stopped on the end of the array, produce items. while (it.peek() != JsonToken.END_ARRAY) { // Get the current item from the reader at it's position. val current = gson.fromJson<T>(it, elementClass.java) // Add it to the map. readValue[id(current)] = current } // After the array, consume end for sanity. it.endArray() } } // Return the cached value return readValue } } set(values) { synchronized(file) { // Write values file.substitute { sub -> JsonWriter(sub.safeWriter()).use { getGson().toJson(values.values, getListTypeForDeserialization(elementClass.java), it) } } // Cache values and store the write time readTime = file.lastModified() readValue.clear() readValue.putAll(values) } } var items: Collection<T> get() = entries.values set(values) { entries = values.associateBy(id) } val fileTime get() = if (file.exists()) file.lastModified() else null override fun get(i: UUID?) = if (i != null) entries[i] else null /** * Applies the delta to the store. */ fun apply(abstractDelta: AbstractDelta<T>) { // Make new entries from original or new empty map val newEntries = if (abstractDelta.clearBeforeInsert) hashMapOf() else entries.toMutableMap() // Remove removed entities for (d in abstractDelta.deleted) newEntries.remove(d) // Replace changed entities for (c in abstractDelta.changed) newEntries[id(c)] = c // Transfer value if new. if (entries != newEntries) entries = newEntries } /** * Deletes the content and resets the values. */ fun delete() { synchronized(file) { file.delete() readTime = null readValue.clear() } } fun <U : Comparable<U>> asc(by: (T) -> U) = items.sortedBy(by) fun <U : Comparable<U>> desc(by: (T) -> U) = items.sortedByDescending(by) val size get() = items.size val isPresent get() = file.exists() } /** * Creates a stored value. */ protected inline fun <reified T : Any> storedValue(swaggerStored: Boolean = false) = StoredValue(T::class, swaggerStored) /** * Creates a stored list of values. */ protected inline fun <reified T : Any> storedValues(swaggerStored: Boolean = false) = StoredValues(T::class, swaggerStored) /** * Creates a stored source with the given identity function */ protected inline fun <reified T : Any> storedSource(noinline id: (T) -> UUID) = StoredSource(T::class, id) }
mit
ac864d4f2982c655303180c67a2bb241
33.127413
113
0.496945
5.220319
false
false
false
false
KrenVpravo/CheckReaction
app/src/main/java/com/two_two/checkreaction/ui/finishscreen/ScienceFinishActivity.kt
1
2737
package com.two_two.checkreaction.ui.finishscreen import android.app.Activity import android.content.Intent import android.os.Bundle import android.os.Parcelable import android.view.View import com.two_two.checkreaction.R import com.two_two.checkreaction.domain.firebase.FirebaseSender import com.two_two.checkreaction.models.App import com.two_two.checkreaction.models.firebase.FirebaseScienceResult import com.two_two.checkreaction.models.science.ScienceTestResult import com.two_two.checkreaction.ui.gamescore.science.ScienceScoreActivity import kotlinx.android.synthetic.main.activity_science_finish.* import java.io.Serializable class ScienceFinishActivity : Activity() { var testResult: ScienceTestResult? = null var firebaseResult : FirebaseScienceResult? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_science_finish) testResult = intent.getSerializableExtra(ScienceTestResult.TAG) as ScienceTestResult? if (testResult == null) { accuracy_result_text.setText(R.string.error_cannot_find_result) average_result_text.visibility = View.INVISIBLE } else { calcFirebaseTestResult() fillTextForResult() updateScienceTestResult() } rating_button.setOnClickListener { openResultsScreen() } } private fun calcFirebaseTestResult() { val username = App.getInstance().getLocalData().getUsername() firebaseResult = FirebaseScienceResult(testResult!!.currectHits, testResult!!.average, username) } private fun ScienceFinishActivity.fillTextForResult() { val accuracySb = StringBuilder() accuracySb.append(getString(R.string.accuracy)) accuracySb.append(testResult?.currectHits) accuracySb.append(getString(R.string.of)) accuracySb.append(testResult?.testType?.maxAttempts) accuracySb.append(getString(R.string.tapped_ok)) accuracy_result_text.text = accuracySb.toString() val averageSB = StringBuilder() averageSB.append(getString(R.string.speed)) averageSB.append(testResult?.average) averageSB.append(getString(R.string.milliseconds_descroption)) average_result_text.text = averageSB.toString() } private fun openResultsScreen() { intent = Intent(this, ScienceScoreActivity::class.java) intent.putExtra(FirebaseScienceResult.TAG, firebaseResult as Serializable) startActivity(intent) } private fun updateScienceTestResult() { val fireResult = firebaseResult ?: return FirebaseSender.getInstance().updateScienceTestResult(fireResult) } }
mit
9ac042ef027c68f680537096d94d1458
39.850746
104
0.733285
4.654762
false
true
false
false
VoIPGRID/vialer-android
app/src/main/java/com/voipgrid/vialer/api/UserSynchronizer.kt
1
3402
package com.voipgrid.vialer.api import android.content.Context import com.voipgrid.vialer.User import com.voipgrid.vialer.api.models.SystemUser import com.voipgrid.vialer.logging.Logger import com.voipgrid.vialer.middleware.MiddlewareHelper import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlinx.coroutines.withContext /** * The responsibility of this is to make sure our local user information matches the information stored * in the api. * */ class UserSynchronizer(private val voipgridApi: VoipgridApi, private val context: Context, private val secureCalling: SecureCalling) { private val logger = Logger(this) /** * Sync our local user information with that on voipgrid. * */ suspend fun sync() { syncVoipgridUser() val voipgridUser = User.voipgridUser ?: return syncUserDestinations() if (!voipgridUser.hasVoipAccount()) { handleMissingVoipAccount() return } syncVoipAccount(voipgridUser) if (User.hasVoipAccount) { secureCalling.updateApiBasedOnCurrentPreferenceSetting() MiddlewareHelper.registerAtMiddleware(context) } } /** * Temporary method for java interop, to be removed after SettingsActivity has been * reverted to Kotlin. * */ fun syncWithCallback(callback: () -> Unit) = GlobalScope.launch(Dispatchers.IO) { sync() callback.invoke() } /** * If there is no voip account we want to make sure that our local version * reflects that. * */ private fun handleMissingVoipAccount() { logger.i("User does not have a VoIP account, disabling sip") User.voipAccount = null User.voip.hasEnabledSip = false } /** * Fetch the voipgrid user from the api and update our stored version. * */ private suspend fun syncVoipgridUser() = withContext(Dispatchers.IO) { val response = voipgridApi.systemUser().execute() if (!response.isSuccessful) { logger.e("Unable to retrieve a system user") return@withContext } User.voipgridUser = response.body() User.voip.isAccountSetupForSip = true } /** * Sync the voip account with the remote version. * */ private suspend fun syncVoipAccount(voipgridUser: SystemUser) = withContext(Dispatchers.IO) { val response = voipgridApi.phoneAccount(voipgridUser.voipAccountId).execute() if (!response.isSuccessful) { logger.e("Unable to retrieve voip account from api") return@withContext } val voipAccount = response.body() ?: return@withContext if (voipAccount.accountId == null) { handleMissingVoipAccount() return@withContext } User.voipAccount = response.body() } private suspend fun syncUserDestinations() = withContext(Dispatchers.IO) { val response = voipgridApi.fetchDestinations().execute() if (!response.isSuccessful) { logger.e("Unable to retrieve sync user destinations: " + response.code()) return@withContext } val destinations = response.body()?.objects ?: return@withContext User.internal.destinations = destinations } }
gpl-3.0
0a9a8ce8ee3e9fb2013255880af15aa1
28.08547
134
0.656085
4.825532
false
false
false
false
Camano/CoolKotlin
utilities/bmi.kt
1
1150
/* * You can change the height of the bmi calculator down below. * First enter your weight in kg, then * the bmi calculator will give you your bmi and tell you if you are underweight, normal, or overweight */ import java.util.Scanner fun main(args: Array<String>) { // Height val height = 1.84 /*Change ^ for your height(m)*/ // Weight val w = Scanner(System.`in`) println("How heavy are you in kg?") val weight = w.nextDouble() println(weight.toString() + "kg") print("How tall are you?") println(" " + height + "m") val bmi = weight / (height * height) println("BMI: " + bmi) if (bmi < 16) { println("You are severely underweight!") } else if (bmi < 17) { println("You are moderately underweight!") } else if (bmi <= 18.5) { println("You are a little bit underweight!") } else if (bmi <= 25) { println("Your bmi is normal") } else if (bmi <= 30) { println("You are overweight!") } else if (bmi <= 35) { println("You are obese!") } else if (bmi >= 35) { println("You are morbidly obese!") } }
apache-2.0
3bff7cb40557ffd910b409bef7815513
28.487179
110
0.576522
3.62776
false
false
false
false
AndroidX/constraintlayout
projects/ComposeConstraintLayout/app/src/main/java/com/example/constraintlayout/test3.kt
2
2547
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.constraintlayout import androidx.compose.animation.core.animateFloatAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.* import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.layoutId import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.constraintlayout.compose.* import java.util.* @Preview(group = "new") @Composable public fun ExampleLayout() { ConstraintLayout( ConstraintSet(""" { Header: { exportAs: 'example 3'}, g1: { type: 'vGuideline', start: 80 }, g2: { type: 'vGuideline', end: 80 }, button: { width: 'spread', top: ['title', 'bottom', 16], start: ['g1', 'start'], end: ['g2', 'end'] }, title: { width: { value: 'wrap', max: 300 }, centerVertically: 'parent', start: ['g1', 'start'], end: ['g2','end'] } } """), modifier = Modifier.fillMaxSize() ) { Button( modifier = Modifier.layoutId("button"), onClick = {}, ) { Text(text = stringResource(id = R.string.log_in)) } Text(modifier = Modifier.layoutId("title").background(Color.Red), text = "ABC dsa sdfs sdf adfas asdas asdad asdas",// DEF GHI JKL MNO PQR STU VWX YZ ABC DEF", style = MaterialTheme.typography.body1, ) } }
apache-2.0
7f093fe81520896247266f51d2b621dc
34.375
105
0.621908
4.414211
false
false
false
false
industrial-data-space/trusted-connector
ids-api/src/main/java/de/fhg/aisec/ids/api/settings/ConnectorConfig.kt
1
1470
/*- * ========================LICENSE_START================================= * ids-api * %% * Copyright (C) 2019 Fraunhofer AISEC * %% * 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 de.fhg.aisec.ids.api.settings import java.io.Serializable class ConnectorConfig : Serializable { val appstoreUrl = "https://raw.githubusercontent.com/industrial-data-space/templates/master/templates.json" val brokerUrl = "" val ttpHost = "" val ttpPort = 443 val acmeServerWebcon = "" val acmeDnsWebcon = "" val acmePortWebcon = 80 val tosAcceptWebcon = false val dapsUrl = "https://daps.aisec.fraunhofer.de" val keystoreName = "provider-keystore.p12" val keystorePassword = "password" val keystoreAliasName = "1" val truststoreName = "truststore.p12" companion object { private const val serialVersionUID = 1L } }
apache-2.0
fa3449e27b80070c3e2d0c26dcbd4128
34
111
0.65102
4.117647
false
false
false
false
RyotaMurohoshi/snippets
kotlin/kotlin_playground/src/main/kotlin/iterator_example.kt
1
1348
package com.mrstar.kotlin_playground; fun main(args: Array<String>) { // This is compile error. // for (num in IteratorOperator(10)) { // println(num) // } for (num in IteratorImplementation(10)) { println(num) } for (num in CountLooperWithOperatorClass(10)) { println(num) } for (num in CountLooperWithIteratorClass(10)) { println(num) } val team = Team(listOf( Player("Taro"), Player("Jiro"), Player("Saburo") )) for (member in team){ println(member) } } class IteratorImplementation(val count: Int) : kotlin.collections.Iterator<Int> { var currentCount = 0 override operator fun hasNext(): Boolean = currentCount < count override operator fun next(): Int = currentCount++ } class IteratorOperator(val count: Int) { var currentCount = 0 operator fun hasNext(): Boolean = currentCount < count operator fun next(): Int = currentCount++ } class CountLooperWithIteratorClass(val count: Int) { operator fun iterator() = IteratorImplementation(count) } class CountLooperWithOperatorClass(val count: Int) { operator fun iterator() = IteratorOperator(count) } data class Player(val name: String) data class Team(val members: List<Player>) operator fun Team.iterator() = members.iterator()
mit
d85e9cf2a91e0291c08d07c876a6a7c8
24.45283
81
0.65727
4.084848
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/vanilla/economy/bet/coinflipglobal/CoinFlipBetGlobalSonhosQuantityAutocompleteExecutor.kt
1
6051
package net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.bet.coinflipglobal import kotlinx.datetime.Clock import net.perfectdreams.discordinteraktions.common.autocomplete.FocusedCommandOption import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.cinnamon.discord.interactions.autocomplete.AutocompleteContext import net.perfectdreams.loritta.cinnamon.discord.interactions.autocomplete.CinnamonAutocompleteHandler import net.perfectdreams.loritta.cinnamon.discord.interactions.vanilla.economy.declarations.BetCommand import net.perfectdreams.loritta.cinnamon.discord.utils.NumberUtils import net.perfectdreams.loritta.cinnamon.pudding.data.UserId import kotlin.time.Duration.Companion.minutes class CoinFlipBetGlobalSonhosQuantityAutocompleteExecutor(loritta: LorittaBot) : CinnamonAutocompleteHandler<String>(loritta) { override suspend fun handle(context: AutocompleteContext, focusedOption: FocusedCommandOption): Map<String, String> { val currentInput = focusedOption.value val trueNumber = NumberUtils.convertShortenedNumberToLong( context.i18nContext, currentInput ) val trueNumberAsString = trueNumber.toString() val matchedChoices = mutableSetOf<Long>() for (quantity in CoinFlipBetGlobalExecutor.QUANTITIES) { if (focusedOption.value.isEmpty() || quantity.toString().startsWith(trueNumberAsString)) { matchedChoices.add(quantity) } } val discordChoices = mutableMapOf<String, String>() val matchmakingStats = loritta.pudding.bets.getUserCoinFlipBetGlobalMatchmakingStats( UserId(context.sender.id.value), matchedChoices.toList(), Clock.System.now().minus(5.minutes) ) for (choice in matchedChoices) { val mmStat = matchmakingStats[choice] discordChoices[ buildString { if (mmStat == null) { if (choice == 0L) { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.JustForFun ) ) } else { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.MatchmakingSonhos( choice ) ) ) } } else { if (mmStat.userPresentInMatchmakingQueue) { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.QuitMatchmakingQueue( choice ) ) ) } else { if (choice == 0L) { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.JustForFun ) ) } else { append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.MatchmakingSonhos( choice ) ) ) } val averageTimeOnQueue = mmStat.averageTimeOnQueue if (averageTimeOnQueue != null) { append(" (${ context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.AverageTimeInSeconds( averageTimeOnQueue.toMillis().toDouble() / 1_000 ) ) })") } append(" ") append("[") if (mmStat.playersPresentInMatchmakingQueue) { append( context.i18nContext.get(BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.PlayersInMatchmakingQueue) ) append(" | ") } append( context.i18nContext.get( BetCommand.COINFLIP_GLOBAL_I18N_PREFIX.Options.Quantity.Choice.RecentMatches( mmStat.recentMatches ) ) ) append("]") } } } ] = if (mmStat?.userPresentInMatchmakingQueue == true) "q$choice" else choice.toString() } return discordChoices } }
agpl-3.0
ffb2150587839e49baebe1bd8f35ffb0
47.806452
153
0.437944
6.798876
false
false
false
false
darakeon/dfm
android/App/src/test/kotlin/com/darakeon/dfm/dialogs/DateDialogTest.kt
1
3160
package com.darakeon.dfm.dialogs import android.app.AlertDialog import android.app.DatePickerDialog import android.app.Dialog import android.content.res.Resources import android.view.View import com.darakeon.dfm.testutils.BaseTest import com.darakeon.dfm.testutils.getPrivate import com.darakeon.dfm.testutils.robolectric.waitTasks import com.darakeon.dfm.utils.activity.TestActivity import com.darakeon.dfm.utils.api.ActivityMock import org.hamcrest.CoreMatchers.`is` import org.hamcrest.MatcherAssert.assertThat import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.shadows.ShadowAlertDialog.getLatestAlertDialog import java.util.Calendar.DECEMBER import java.util.Calendar.MARCH @RunWith(RobolectricTestRunner::class) class DateDialogTest: BaseTest() { private val yearId = getResId("year") private val monthId = getResId("month") private val dayId = getResId("day") private lateinit var mocker: ActivityMock<TestActivity> private val spinner = 1 private val calendar = 2 @Before fun setup() { mocker = ActivityMock(TestActivity::class) } @Test fun getDateDialogWithDayMonthYear() { var year = 1986 var month = MARCH var day = 27 val activity = mocker.create() activity.getDateDialog(2013, DECEMBER, 23) { y, m, d -> year = y month = m day = d }.show() val dialog = getLatestAlertDialog() as DatePickerDialog assertThat(dialog.datePicker.getPrivate("mMode"), `is`(calendar)) dialog.getButton(Dialog.BUTTON_POSITIVE).performClick() activity.waitTasks(mocker.server) assertThat(day, `is`(23)) assertThat(month, `is`(DECEMBER)) assertThat(year, `is`(2013)) } @Test fun getDateDialogWithMonthYear() { var year = 1986 var month = MARCH val activity = mocker.create() activity.getDateDialog(2013, DECEMBER) { y, m -> year = y month = m }.show() val dialog = getLatestAlertDialog() as DatePickerDialog assertThat(dialog.datePicker.getPrivate("mMode"), `is`(spinner)) assertFalse(isVisible(dialog, dayId)) assertTrue(isVisible(dialog, monthId)) assertTrue(isVisible(dialog, yearId)) dialog.getButton(Dialog.BUTTON_POSITIVE).performClick() activity.waitTasks(mocker.server) assertThat(month, `is`(DECEMBER)) assertThat(year, `is`(2013)) } @Test fun getDateDialogWithYear() { var year = 1986 val activity = mocker.create() activity.getDateDialog(2013) { y -> year = y }.show() val dialog = getLatestAlertDialog() as DatePickerDialog assertThat(dialog.datePicker.getPrivate("mMode"), `is`(spinner)) assertFalse(isVisible(dialog, dayId)) assertFalse(isVisible(dialog, monthId)) assertTrue(isVisible(dialog, yearId)) dialog.getButton(Dialog.BUTTON_POSITIVE).performClick() activity.waitTasks(mocker.server) assertThat(year, `is`(2013)) } private fun isVisible(dialog: AlertDialog, resId: Int) = dialog.findViewById<View>(resId) .visibility == View.VISIBLE private fun getResId(name: String) = Resources.getSystem() .getIdentifier(name, "id", "android") }
gpl-3.0
af60b2ccde272da6b3ea74f7a2fb0dd1
25.554622
69
0.75443
3.619702
false
true
false
false
Tomlezen/RxCommons
lib/src/test/java/com/tlz/rxcommons/RxPreferencesTest.kt
1
1641
package com.tlz.rxcommons import android.content.Context import android.content.SharedPreferences import org.junit.Assert import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.RuntimeEnvironment import org.robolectric.annotation.Config /** * Created by LeiShao. * Data 2017/5/24. * Time 19:54. * Email [email protected]. */ @RunWith(RobolectricTestRunner::class) @Config(manifest = Config.NONE) class RxPreferencesTest { lateinit var mPreference: RxPreferences lateinit var mSharePreference: SharedPreferences @Before fun setup(){ mSharePreference = RuntimeEnvironment.application.getSharedPreferences("test", Context.MODE_PRIVATE) mPreference = RxPreferences(mSharePreference) } @Test fun observeBoolean() { var value = false mPreference.observeBoolean("testBoolean", false ,false) .subscribe({ value = it }) mSharePreference.edit().putBoolean("testBoolean", true).apply() Assert.assertTrue(value) } @Test fun observeString() { var value = "test" mPreference.observeString("testString", "" , false) .subscribe({ value = it }) mSharePreference.edit().putString("testString", "test").apply() Assert.assertEquals(value, "test") } @Test fun observeInt() { } @Test fun observeLong() { } @Test fun observeFloat() { } @Test fun observeStringSet() { } }
apache-2.0
018f8864128a162c6d427c9bd21e8cc7
20.893333
108
0.640463
4.49589
false
true
false
false
angcyo/RLibrary
uiview/src/main/java/com/angcyo/uiview/base/UISlidingTabView.kt
1
4478
package com.angcyo.uiview.base import android.os.Bundle import android.support.v4.content.ContextCompat import android.view.LayoutInflater import com.angcyo.uiview.R import com.angcyo.uiview.container.ContentLayout import com.angcyo.uiview.github.tablayout.SlidingTabLayout import com.angcyo.uiview.skin.SkinHelper import com.angcyo.uiview.view.IView import com.angcyo.uiview.widget.viewpager.UIPagerAdapter import com.angcyo.uiview.widget.viewpager.UIViewPager /** * Copyright (C) 2016,深圳市红鸟网络科技股份有限公司 All rights reserved. * 项目名称: * 类的描述:标准的SlidingTab和UIViewPager组合的界面 * 创建人员:Robi * 创建时间:2017/06/28 11:43 * 修改人员:Robi * 修改时间:2017/06/28 11:43 * 修改备注: * Version: 1.0.0 */ abstract class UISlidingTabView : UIContentView(), UIBaseView.OnViewLoadListener { companion object { fun baseInitTabLayout(tabLayout: SlidingTabLayout) { val density = tabLayout.context.resources.displayMetrics.density tabLayout.setIndicatorWidthEqualTitle(true) //tabLayout.indicatorWidth = 100 * density tabLayout.textSelectColor = SkinHelper.getSkin().themeSubColor tabLayout.textUnselectColor = ContextCompat.getColor(tabLayout.context, R.color.base_text_color) tabLayout.indicatorHeight = 1 * density tabLayout.indicatorColor = SkinHelper.getSkin().themeSubColor tabLayout.indicatorStyle = SlidingTabLayout.STYLE_NORMAL tabLayout.indicatorCornerRadius = 3 * density //指示器的圆角 tabLayout.indicatorMarginLeft = 0f //指示器左偏移的距离 tabLayout.tabPadding = 5 * density tabLayout.setTextSizePx(SkinHelper.getSkin().mainTextSize) tabLayout.isTabSpaceEqual = false //tab 是否平分 TabLayout的宽度 tabLayout.setItemNoBackground(false) //item 是否禁用点击效果 } } override fun onShowLoadView() { showLoadView() } override fun onHideLoadView() { hideLoadView() } val pages: ArrayList<TabPageBean> by lazy { arrayListOf<TabPageBean>() } val mViewPager: UIViewPager by lazy { val uiViewPager = mViewHolder.v<UIViewPager>(R.id.base_view_pager) uiViewPager.setParentUIView(this) uiViewPager } val mSlidingTab: SlidingTabLayout by lazy { mViewHolder.v<SlidingTabLayout>(R.id.base_tab_layout) } override fun inflateContentLayout(baseContentLayout: ContentLayout?, inflater: LayoutInflater?) { inflate(R.layout.base_sliding_tab_view) } override fun onViewLoad() { super.onViewLoad() createPages(pages) initTabLayout(mSlidingTab) initViewPager(mViewPager) mViewPager.adapter = createAdapter() mSlidingTab.setViewPager(mViewPager) } override fun onViewShowFirst(bundle: Bundle?) { super.onViewShowFirst(bundle) // createPages(pages) // mViewPager.adapter = createAdapter() // // initTabLayout(mSlidingTab) // initViewPager(mViewPager) // // mSlidingTab.setViewPager(mViewPager) } open fun initTabLayout(tabLayout: SlidingTabLayout) { baseInitTabLayout(tabLayout) } open fun initViewPager(viewPager: UIViewPager) { viewPager.offscreenPageLimit = getPageCount() } /**重写此方法, 创建页面*/ open fun createPages(pages: ArrayList<TabPageBean>) { } /**页面数量*/ open fun getPageCount(): Int = pages.size /**对应页面*/ open fun getPageIView(position: Int): IView = pages[position].iView /**页面标题*/ open fun getPageTitle(position: Int): String? = pages[position].title open fun createAdapter() = object : UIPagerAdapter() { override fun getIView(position: Int): IView = (getPageIView(position) as UIBaseView).apply { this.bindParentILayout(mILayout) this.setOnViewLoadListener(this@UISlidingTabView) } override fun getCount(): Int = getPageCount() override fun getPageTitle(position: Int): CharSequence? = [email protected](position) } /**页面*/ data class TabPageBean(val iView: IView, val title: String? = null) }
apache-2.0
37b329f6f764cbe6f4a6235ee3f1e808
30.738462
110
0.667842
4.412863
false
false
false
false
alessio-b-zak/myRivers
android/app/src/main/java/com/epimorphics/android/myrivers/models/InputStreamToRNAG.kt
1
3593
package com.epimorphics.android.myrivers.models import android.util.JsonReader import com.epimorphics.android.myrivers.data.CDEPoint import com.epimorphics.android.myrivers.data.RNAG import com.epimorphics.android.myrivers.helpers.InputStreamHelper import java.io.IOException import java.io.InputStream import java.io.InputStreamReader /** * Consumes an InputStream and converts it to a list of RNAGs * * @see CDEPoint * @see RNAG */ class InputStreamToRNAG : InputStreamHelper() { /** * Converts InputStream to JsonReader and consumes it. * * @param cdePoint CDEPoint to which parsed RNAGs belong * @param inputStream InputStream to be consumed * * @throws IOException */ @Throws(IOException::class) fun readJsonStream(cdePoint: CDEPoint, inputStream: InputStream) { val reader = JsonReader(InputStreamReader(inputStream, "UTF-8")) reader.isLenient = true reader.use { readMessagesArray(cdePoint, reader) } } /** * Focuses on the array of objects that are to be converted to RNAGs and parses * them one by one. * * @param cdePoint CDEPoint to which parsed RNAGs belong * @param reader JsonReader to be consumed * * @throws IOException */ @Throws(IOException::class) fun readMessagesArray(cdePoint: CDEPoint, reader: JsonReader) { reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() if (name == "items") { reader.beginArray() while (reader.hasNext()) { readMessage(cdePoint, reader) } reader.endArray() } else { reader.skipValue() } } reader.endObject() } /** * Converts single JsonObject to RNAG and adds it to the given CDEPoint's rnagList. * * @param cdePoint CDEPoint to which parsed RNAG belongs * @param reader JsonReader to be consumed * * @throws IOException */ @Throws(IOException::class) fun readMessage(cdePoint: CDEPoint, reader: JsonReader) { var element = "" var rating = "" var activity = "" var category = "" var year = "" reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() when (name) { "activity" -> activity = readItemToString(reader) "classificationItem" -> element = readItemToString(reader) "classification" -> rating = readClassificationToString(reader) "classificationYear" -> year = reader.nextString() "category" -> category = readItemToString(reader) else -> reader.skipValue() } } reader.endObject() cdePoint.addRNAG(RNAG(element, rating, activity, category, year.toInt())) } /** * Reads group value from the reader and returns it as a string * * @param reader JsonReader to be consumed * @return String group value * * @throws IOException */ fun readClassificationToString(reader: JsonReader): String { var item = "" reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() if (name == "classificationValue") { item = readItemToString(reader) } else { reader.skipValue() } } reader.endObject() return item } }
mit
ec9070dffc3cb28c8653e5cc90e60267
28.95
87
0.590593
4.928669
false
false
false
false
lttng/lttng-scope
jabberwockd/src/test/kotlin/com/efficios/jabberwocky/jabberwockd/TraceUploadTest.kt
2
3302
/* * Copyright (C) 2017 EfficiOS Inc., Alexandre Montplaisir <[email protected]> * * All rights reserved. This program and the accompanying materials are * made available under the terms of the Eclipse Public License v1.0 which * accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package com.efficios.jabberwocky.jabberwockd import com.efficios.jabberwocky.utils.using import org.junit.jupiter.api.Disabled import org.junit.jupiter.api.Test import java.io.File import java.net.HttpURLConnection import java.net.URL import java.net.URLConnection import java.nio.file.Files class TraceUploadTest { companion object { private const val SERVER_URL = "http://localhost:$LISTENING_PORT/test" private val UTF8 = Charsets.UTF_8 private const val CRLF = "\r\n" // Line separator required by multipart/form-data. } @Test @Disabled("NYI") fun testTraceUpload() { val param = "value" val textFile = File("/path/to/file.txt") val binaryFile = File("/path/to/file.bin") val boundary = System.currentTimeMillis().toString(16) // Just generate some unique random value. val connection = URL(SERVER_URL).openConnection() connection.doOutput = true connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=$boundary") using { val output = connection.getOutputStream().autoClose() val writer = output.bufferedWriter().autoClose() with(writer) { // Send normal param. append("--$boundary").append(CRLF) append("Content-Disposition: form-data; name=\"param\"").append(CRLF) append("Content-Type: text/plain; charset=" + UTF8).append(CRLF) append(CRLF).append(param).append(CRLF).flush() // Send text file. append("--$boundary").append(CRLF) append("Content-Disposition: form-data; name=\"textFile\"; filename=\"${textFile.name}\"").append(CRLF) append("Content-Type: text/plain; charset=" + UTF8).append(CRLF) // Text file itself must be saved in this charset! append(CRLF).flush() Files.copy(textFile.toPath(), output) output.flush() append(CRLF).flush() // Send binary file. append("--$boundary").append(CRLF) append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"${binaryFile.name}\"").append(CRLF) append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.name)).append(CRLF) append("Content-Transfer-Encoding: binary").append(CRLF) append(CRLF).flush() Files.copy(binaryFile.toPath(), output) output.flush() append(CRLF).flush() // End of multipart/form-data. append("--$boundary--").append(CRLF).flush() } } // Request is lazily fired whenever you need to obtain information about response. val responseCode = (connection as HttpURLConnection).responseCode System.out.println(responseCode) // Should be 200 } }
epl-1.0
06e7917b1ed558e734b6ec623120ff4e
39.280488
131
0.622047
4.57975
false
true
false
false
robinverduijn/gradle
subprojects/kotlin-dsl/src/main/kotlin/org/gradle/kotlin/dsl/ScriptHandlerScope.kt
1
6819
/* * Copyright 2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradle.kotlin.dsl import org.gradle.api.NamedDomainObjectContainer import org.gradle.api.NamedDomainObjectProvider import org.gradle.api.artifacts.Configuration import org.gradle.api.artifacts.Dependency import org.gradle.api.artifacts.DependencyConstraint import org.gradle.api.artifacts.ExternalModuleDependency import org.gradle.api.artifacts.ModuleDependency import org.gradle.api.artifacts.dsl.DependencyConstraintHandler import org.gradle.api.artifacts.dsl.DependencyHandler import org.gradle.api.initialization.dsl.ScriptHandler import org.gradle.api.initialization.dsl.ScriptHandler.CLASSPATH_CONFIGURATION import org.gradle.kotlin.dsl.support.delegates.ScriptHandlerDelegate import org.gradle.kotlin.dsl.support.unsafeLazy /** * Receiver for the `buildscript` block. */ class ScriptHandlerScope private constructor( override val delegate: ScriptHandler ) : ScriptHandlerDelegate() { companion object { fun of(scriptHandler: ScriptHandler) = ScriptHandlerScope(scriptHandler) } /** * The dependencies of the script. */ val dependencies by unsafeLazy { DependencyHandlerScope.of(delegate.dependencies) } /** * The script classpath configuration. */ val NamedDomainObjectContainer<Configuration>.classpath: NamedDomainObjectProvider<Configuration> get() = named(CLASSPATH_CONFIGURATION) /** * Adds a dependency to the script classpath. * * @param dependencyNotation notation for the dependency to be added. * @return The dependency. * * @see [DependencyHandler.add] */ fun DependencyHandler.classpath(dependencyNotation: Any): Dependency? = add(CLASSPATH_CONFIGURATION, dependencyNotation) /** * Adds a dependency to the script classpath. * * @param dependencyNotation notation for the dependency to be added. * @param dependencyConfiguration expression to use to configure the dependency. * @return The dependency. * * @see [DependencyHandler.add] */ inline fun DependencyHandler.classpath( dependencyNotation: String, dependencyConfiguration: ExternalModuleDependency.() -> Unit ): ExternalModuleDependency = add(CLASSPATH_CONFIGURATION, dependencyNotation, dependencyConfiguration) /** * Adds a dependency to the script classpath. * * @param group the group of the module to be added as a dependency. * @param name the name of the module to be added as a dependency. * @param version the optional version of the module to be added as a dependency. * @param configuration the optional configuration of the module to be added as a dependency. * @param classifier the optional classifier of the module artifact to be added as a dependency. * @param ext the optional extension of the module artifact to be added as a dependency. * @return The dependency. * * @see [DependencyHandler.add] */ fun DependencyHandler.classpath( group: String, name: String, version: String? = null, configuration: String? = null, classifier: String? = null, ext: String? = null ): ExternalModuleDependency = create(group, name, version, configuration, classifier, ext).also { add(CLASSPATH_CONFIGURATION, it) } /** * Adds a dependency to the script classpath. * * @param group the group of the module to be added as a dependency. * @param name the name of the module to be added as a dependency. * @param version the optional version of the module to be added as a dependency. * @param configuration the optional configuration of the module to be added as a dependency. * @param classifier the optional classifier of the module artifact to be added as a dependency. * @param ext the optional extension of the module artifact to be added as a dependency. * @param dependencyConfiguration expression to use to configure the dependency. * @return The dependency. * * @see [DependencyHandler.create] * @see [DependencyHandler.add] */ inline fun DependencyHandler.classpath( group: String, name: String, version: String? = null, configuration: String? = null, classifier: String? = null, ext: String? = null, dependencyConfiguration: ExternalModuleDependency.() -> Unit ): ExternalModuleDependency = create(group, name, version, configuration, classifier, ext).also { add(CLASSPATH_CONFIGURATION, it, dependencyConfiguration) } /** * Adds a dependency to the script classpath. * * @param dependency dependency to be added. * @param dependencyConfiguration expression to use to configure the dependency. * @return The dependency. * * @see [DependencyHandler.add] */ inline fun <T : ModuleDependency> DependencyHandler.classpath( dependency: T, dependencyConfiguration: T.() -> Unit ): T = add(CLASSPATH_CONFIGURATION, dependency, dependencyConfiguration) /** * Adds a dependency constraint to the script classpath configuration. * * @param dependencyConstraintNotation the dependency constraint notation * * @return the added dependency constraint * * @see [DependencyConstraintHandler.add] * @since 5.0 */ fun DependencyConstraintHandler.classpath(dependencyConstraintNotation: Any): DependencyConstraint? = add(CLASSPATH_CONFIGURATION, dependencyConstraintNotation) /** * Adds a dependency constraint to the script classpath configuration. * * @param dependencyConstraintNotation the dependency constraint notation * @param configuration the block to use to configure the dependency constraint * * @return the added dependency constraint * * @see [DependencyConstraintHandler.add] * @since 5.0 */ fun DependencyConstraintHandler.classpath(dependencyConstraintNotation: Any, configuration: DependencyConstraint.() -> Unit): DependencyConstraint? = add(CLASSPATH_CONFIGURATION, dependencyConstraintNotation, configuration) }
apache-2.0
a26b82735066751eb27933fb62190425
38.189655
153
0.712861
5.092606
false
true
false
false
facebook/litho
sample/src/main/java/com/facebook/samples/litho/kotlin/lithography/components/DecadeSeparator.kt
1
1948
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.samples.litho.kotlin.lithography.components import com.facebook.litho.ComponentScope import com.facebook.litho.KComponent import com.facebook.litho.Row import com.facebook.litho.Style import com.facebook.litho.core.height import com.facebook.litho.core.margin import com.facebook.litho.core.padding import com.facebook.litho.dp import com.facebook.litho.drawableColor import com.facebook.litho.flexbox.flex import com.facebook.litho.kotlin.widget.Text import com.facebook.litho.px import com.facebook.litho.sp import com.facebook.litho.view.background import com.facebook.samples.litho.kotlin.lithography.data.Decade import com.facebook.yoga.YogaAlign.CENTER class DecadeSeparator(val decade: Decade) : KComponent() { override fun ComponentScope.render() = Row(alignItems = CENTER, style = Style.padding(16.dp).background(drawableColor(0xFFFAFAFA))) { child(Row(style = Style.height(1.px).flex(grow = 1f).background(drawableColor(0xFFAAAAAA)))) child( Text( text = "${decade.year}", textSize = 14.sp, textColor = 0xFFAAAAAA.toInt(), style = Style.margin(horizontal = 10.dp).flex(shrink = 0f))) child(Row(style = Style.height(1.px).flex(grow = 1f).background(drawableColor(0xFFAAAAAA)))) } }
apache-2.0
aaffea6c861669f85b7f88982486fef4
39.583333
100
0.73152
3.804688
false
false
false
false
moxi/weather-app-demo
weather-app/src/main/java/rcgonzalezf/org/weather/common/analytics/AnalyticsDataCatalog.kt
1
621
package rcgonzalezf.org.weather.common.analytics interface AnalyticsDataCatalog { interface WeatherListActivity { companion object { const val NO_NETWORK_SEARCH = "NO_NETWORK_SEARCH" const val MANUAL_SEARCH = "MANUAL_SEARCH" const val LOCATION_SEARCH = "LOCATION_SEARCH" const val SEARCH_COMPLETED = "SEARCH_COMPLETED" } } interface SettingsActivity { companion object { const val TEMP_UNITS_TOGGLE = "TEMP_UNITS_TOGGLE" const val ON_NAME = "ON_NAME" const val ON_LOAD = "ON_LOAD" } } }
mit
a162a9bed15a25dd6b39e660bc40119e
30.05
61
0.607085
4.5
false
false
false
false
camsteffen/polite
src/main/java/me/camsteffen/polite/model/DefaultRules.kt
1
1238
package me.camsteffen.polite.model import android.content.Context import me.camsteffen.polite.R import me.camsteffen.polite.rule.ScheduleRuleSchedule import org.threeten.bp.DayOfWeek import javax.inject.Inject import javax.inject.Singleton @Singleton class DefaultRules @Inject constructor(val context: Context) { fun calendar() = CalendarRule( id = Rule.NEW_ID, name = context.getString(R.string.rule_default_name), enabled = RuleDefaults.enabled, vibrate = RuleDefaults.vibrate, busyOnly = false, calendarIds = emptySet(), matchBy = CalendarEventMatchBy.ALL, inverseMatch = false, keywords = emptySet() ) fun schedule() = ScheduleRule( id = Rule.NEW_ID, name = context.getString(R.string.rule_default_name), enabled = RuleDefaults.enabled, vibrate = RuleDefaults.vibrate, schedule = ScheduleRuleSchedule( 12, 0, 13, 0, DayOfWeek.MONDAY, DayOfWeek.TUESDAY, DayOfWeek.WEDNESDAY, DayOfWeek.THURSDAY, DayOfWeek.FRIDAY ) ) } private object RuleDefaults { const val enabled = true const val vibrate = false }
mpl-2.0
4c3098b8fcb22456ece344bea5198bb3
25.913043
61
0.64378
4.534799
false
false
false
false
jksiezni/xpra-client
xpra-client-android/src/main/java/com/github/jksiezni/xpra/config/ServerDetailsFragment.kt
1
7046
/* * Copyright (C) 2020 Jakub Ksiezniak * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.github.jksiezni.xpra.config import android.content.Intent import android.os.Bundle import android.text.TextUtils import android.util.Patterns import android.view.Menu import android.view.MenuInflater import android.view.MenuItem import android.widget.Toast import androidx.preference.EditTextPreference import androidx.preference.ListPreference import androidx.preference.Preference import androidx.preference.Preference.SummaryProvider import androidx.preference.PreferenceFragmentCompat import com.github.jksiezni.xpra.R import java.util.regex.Pattern class ServerDetailsFragment : PreferenceFragmentCompat() { private lateinit var dataStore: ServerDetailsDataStore init { setHasOptionsMenu(true) } override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { val serverDetails = requireArguments().getSerializable(KEY_SERVER_DETAILS) as ServerDetails val dao = ConfigDatabase.getInstance().configs dataStore = ServerDetailsDataStore(serverDetails, dao) preferenceManager.preferenceDataStore = dataStore addPreferencesFromResource(R.xml.server_details_preference) setupPreferences() } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { inflater.inflate(R.menu.server_details_menu, menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.action_save -> if (save()) { parentFragmentManager.popBackStack() } android.R.id.home -> parentFragmentManager.popBackStack() } return super.onOptionsItemSelected(item) } private fun setupPreferences() { findPreference<Preference>(ServerDetailsDataStore.PREF_NAME)?.summaryProvider = EditTextSummaryProvider(getString(R.string.enter_unique_name)) findPreference<Preference>(ServerDetailsDataStore.PREF_HOST)?.summaryProvider = EditTextSummaryProvider(getString(R.string.enter_unique_name)) findPreference<Preference>(ServerDetailsDataStore.PREF_USERNAME)?.summaryProvider = EditTextSummaryProvider(getString(R.string.enter_unique_name)) findPreference<Preference>(ServerDetailsDataStore.PREF_DISPLAY_ID)?.summaryProvider = DisplayIdSummaryProvider(getString(R.string.automatic)) findPreference<ListPreference>(ServerDetailsDataStore.PREF_CONNECTION_TYPE)?.let { it.setOnPreferenceChangeListener { _, newValue -> setSshPreferencesEnabled(ConnectionType.SSH.name == newValue) true } setSshPreferencesEnabled(ConnectionType.SSH.name == it.value) } findPreference<Preference>(ServerDetailsDataStore.PREF_PRIVATE_KEY)?.setOnPreferenceClickListener { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply { addCategory(Intent.CATEGORY_OPENABLE) type = "application/x-pem-file" // https://pki-tutorial.readthedocs.io/en/latest/mime.html } startActivity(intent) true } } private fun save(): Boolean { return if (validate(dataStore.serverDetails)) { dataStore.save() true } else { false } } private fun setSshPreferencesEnabled(enabled: Boolean) { val portPref = findPreference<EditTextPreference>(ServerDetailsDataStore.PREF_PORT) if (enabled) { if ("10000" == portPref?.text) { portPref.text = "22" } } else { if ("22" == portPref?.text) { portPref.text = "10000" } } findPreference<Preference>(ServerDetailsDataStore.PREF_USERNAME)?.isEnabled = enabled findPreference<Preference>(ServerDetailsDataStore.PREF_PRIVATE_KEY)?.isEnabled = enabled } private fun validateName(name: String?): Boolean { if (name == null || name.isEmpty()) { Toast.makeText(activity, "The connection name must not be empty.", Toast.LENGTH_LONG).show() return false } // else if (!connectionDao.queryForEq("name", name).isEmpty()) { // Toast.makeText(getActivity(), "The connection with that name exists already.", Toast.LENGTH_LONG).show(); // return false; // } return true } private fun validateHostname(host: String?): Boolean { if (host == null || host.isEmpty()) { Toast.makeText(activity, "The hostname must not be empty.", Toast.LENGTH_LONG).show() return false } else if (!HOSTNAME_PATTERN.matcher(host).matches()) { val matcher = Patterns.IP_ADDRESS.matcher(host) if (!matcher.matches()) { Toast.makeText(activity, "Invalid hostname: $host", Toast.LENGTH_LONG).show() return false } } return true } private fun validate(serverDetails: ServerDetails): Boolean { return validateName(serverDetails.name) && validateHostname(serverDetails.host) } companion object { private const val KEY_SERVER_DETAILS = "server_details" private val HOSTNAME_PATTERN = Pattern.compile("^[0-9a-zA-Z_\\-.]*$") fun create(serverDetails: ServerDetails): ServerDetailsFragment { return ServerDetailsFragment().apply { arguments = Bundle().apply { putSerializable(KEY_SERVER_DETAILS, serverDetails) } } } } } class EditTextSummaryProvider(private val emptySummary: String) : SummaryProvider<EditTextPreference> { override fun provideSummary(preference: EditTextPreference): CharSequence { return if (TextUtils.isEmpty(preference.text)) { emptySummary } else { preference.text } } } class DisplayIdSummaryProvider(private val emptySummary: String) : SummaryProvider<EditTextPreference> { override fun provideSummary(preference: EditTextPreference): CharSequence { val text = preference.text return if (TextUtils.isEmpty(text) || "-1" == text) { emptySummary } else { text } } }
gpl-3.0
2b9aa44f6aaa45e10a177472fe8cc6f3
37.928177
154
0.666052
4.941094
false
false
false
false
KawakawaRitsuki/JapaneCraft
src/main/kotlin/com/wcaokaze/japanecraft/RomajiConverter.kt
1
1519
package com.wcaokaze.japanecraft class RomajiConverter(romajiMap: Map<String, Output>) { private val romajiTable = romajiMap.toTrie() operator fun invoke(romajiStr: String): String { val romajiBuffer = StringBuffer(romajiStr) fun StringBuffer.parseHeadRomaji(): String { val strBuffer = this fun loop(strIdx: Int, prevNode: Trie<Output>): String { val node = prevNode[strBuffer[strIdx]] fun confirm(strIdx: Int, node: Trie<Output>): String { val output = node.value val jpStr = output?.jpChar ?: strBuffer.substring(0..strIdx) strBuffer.delete(0, strIdx + 1) if (output != null) strBuffer.insert(0, output.nextInput) return jpStr } return when { node == null -> confirm(strIdx - 1, prevNode) node.childCount == 0 -> confirm(strIdx, node) strIdx == strBuffer.lastIndex -> confirm(strIdx, node) else -> return loop(strIdx + 1, node) } } val trieNode = romajiTable[romajiBuffer.first()] if (trieNode != null) { return loop(0, romajiTable) } else { val char = romajiBuffer.first() romajiBuffer.deleteCharAt(0) return String(charArrayOf(char)) } } return buildString { while (romajiBuffer.isNotEmpty()) { append(romajiBuffer.parseHeadRomaji()) } } } class Output(val jpChar: String, val nextInput: String) }
lgpl-2.1
561c455bf791db5224f3ae0e23289157
27.660377
72
0.591178
4.278873
false
false
false
false
Doctoror/FuckOffMusicPlayer
presentation/src/main/java/com/doctoror/fuckoffmusicplayer/presentation/recentactivity/RecentActivityFragment.kt
2
3831
/* * Copyright (C) 2018 Yaroslav Mytkalyk * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.doctoror.fuckoffmusicplayer.presentation.recentactivity import android.databinding.DataBindingUtil import android.os.Bundle import android.support.v7.widget.GridLayoutManager import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.doctoror.fuckoffmusicplayer.R import com.doctoror.fuckoffmusicplayer.databinding.FragmentRecentActivityBinding import com.doctoror.fuckoffmusicplayer.presentation.base.BaseFragment import com.doctoror.fuckoffmusicplayer.presentation.util.ViewUtils import com.doctoror.fuckoffmusicplayer.presentation.widget.SpacesItemDecoration import dagger.android.support.AndroidSupportInjection import javax.inject.Inject class RecentActivityFragment : BaseFragment() { @Inject lateinit var presenter: RecentActivityPresenter @Inject lateinit var viewModel: RecentActivityViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) AndroidSupportInjection.inject(this) setHasOptionsMenu(true) if (savedInstanceState != null) { presenter.restoreInstanceState(savedInstanceState) } lifecycle.addObserver(presenter) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) presenter.onSaveInstanceState(outState) } override fun onDestroy() { super.onDestroy() lifecycle.removeObserver(presenter) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { val binding = DataBindingUtil.inflate<FragmentRecentActivityBinding>(inflater, R.layout.fragment_recent_activity, container, false) setupRecyclerView(binding.recyclerView) binding.model = viewModel binding.root.findViewById<View>(R.id.btnRequest).setOnClickListener { presenter.requestPermission() } val adapter = RecentActivityRecyclerAdapter(requireContext()) adapter.setOnAlbumClickListener { position, id, album -> presenter.onAlbumClick(id, album) { ViewUtils.getItemView(binding.recyclerView, position) } } viewModel.recyclerAdapter.set(adapter) return binding.root } private fun setupRecyclerView(recyclerView: RecyclerView) { val columns = resources.getInteger(R.integer.recent_activity_grid_columns) val lm = GridLayoutManager(activity, columns) lm.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() { override fun getSpanSize(position: Int): Int { val adapter = recyclerView.adapter ?: return 1 return when (adapter.getItemViewType(position)) { RecentActivityRecyclerAdapter.VIEW_TYPE_HEADER -> columns else -> 1 } } } recyclerView.layoutManager = lm recyclerView.addItemDecoration(SpacesItemDecoration( resources.getDimensionPixelSize(R.dimen.recent_activity_grid_spacing))) } }
apache-2.0
7e3b34f3e89cf22aa82908fabc637a08
35.485714
87
0.712086
5.320833
false
false
false
false
vsch/idea-multimarkdown
src/main/java/com/vladsch/md/nav/psi/element/MdAsideBlockImpl.kt
1
2813
// Copyright (c) 2015-2020 Vladimir Schneider <[email protected]> Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.vladsch.md.nav.psi.element import com.intellij.lang.ASTNode import com.intellij.navigation.ItemPresentation import com.intellij.psi.PsiElement import com.vladsch.flexmark.util.sequence.LineAppendable import com.vladsch.md.nav.actions.handlers.util.PsiEditContext import com.vladsch.md.nav.psi.util.MdPsiBundle import com.vladsch.md.nav.psi.util.MdPsiImplUtil import com.vladsch.md.nav.settings.MdApplicationSettings import com.vladsch.md.nav.util.format.CharLinePrefixMatcher import com.vladsch.md.nav.util.format.LinePrefixMatcher import icons.MdIcons import javax.swing.Icon class MdAsideBlockImpl(node: ASTNode) : MdIndentingCompositeImpl(node), MdAsideBlock, MdStructureViewPresentableElement, MdStructureViewPresentableItem, MdBreadcrumbElement { companion object { @JvmField val INDENT_PREFIX = "| " private val INDENT_PREFIX_MATCHER = CharLinePrefixMatcher('|') } override fun isTextStart(node: ASTNode): Boolean { return node !== node.firstChildNode } override fun getPrefixMatcher(editContext: PsiEditContext): LinePrefixMatcher { return INDENT_PREFIX_MATCHER } override fun removeLinePrefix(lines: LineAppendable, indentColumns: IntArray, isFirstChild: Boolean, editContext: PsiEditContext) { removeLinePrefix(lines, indentColumns, false, editContext, INDENT_PREFIX_MATCHER, 0) } override fun getIcon(flags: Int): Icon? { return MdIcons.Element.ASIDE_BLOCK } override fun getPresentableText(): String? { return MdPsiBundle.message("aside-block") } override fun getLocationString(): String? { return null } override fun getStructureViewPresentation(): ItemPresentation { return MdPsiImplUtil.getPresentation(this) } fun getBlockQuoteNesting(): Int { var nesting = 1 var parent = parent while (parent is MdAsideBlock) { nesting++ parent = parent.parent } return nesting } override fun getBreadcrumbInfo(): String { // val message = PsiBundle.message("block-quote") // val nesting = getBlockQuoteNesting() // return if (nesting > 1) "$message ×$nesting" else message val settings = MdApplicationSettings.instance.documentSettings if (settings.showBreadcrumbText) { return "|" } return MdPsiBundle.message("aside-block") } override fun getBreadcrumbTooltip(): String? { return null } override fun getBreadcrumbTextElement(): PsiElement? { return null } }
apache-2.0
2c7a057726fdcee6caac9836dac725e6
32.879518
177
0.703058
4.594771
false
false
false
false
robfletcher/kork
kork-plugins/src/test/kotlin/com/netflix/spinnaker/kork/plugins/SpinnakerServiceVersionManagerTest.kt
3
3576
/* * Copyright 2020 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.kork.plugins import dev.minutest.junit.JUnit5Minutests import dev.minutest.rootContext import strikt.api.expectThat import strikt.assertions.isEqualTo import strikt.assertions.isFalse import strikt.assertions.isTrue class SpinnakerServiceVersionManagerTest : JUnit5Minutests { fun tests() = rootContext<Fixture> { fixture { Fixture() } test("Service version satisfies plugin requirement constraint") { val satisfiedConstraint = subject.checkVersionConstraint( "0.0.9", "$serviceName<=1.0.0" ) expectThat(satisfiedConstraint).isTrue() } test("Service version does not satisfies plugin requirement constraint with upper limit") { val satisfiedConstraint = subject.checkVersionConstraint( "1.0.1", "$serviceName<=1.0.0" ) expectThat(satisfiedConstraint).isFalse() } test("Service version does not satisfy plugin requirement constraint with lower limit") { val satisfiedConstraint = subject.checkVersionConstraint( "0.0.9", "$serviceName>=1.0.0" ) expectThat(satisfiedConstraint).isFalse() } test("Service version satisfy plugin requirement constraint") { val satisfiedConstraint = subject.checkVersionConstraint( "1.0.0", "$serviceName>=1.0.0" ) expectThat(satisfiedConstraint).isTrue() } test("Service version satisfy plugin requirement constraint range") { val satisfiedConstraint = subject.checkVersionConstraint( "1.0.5", "$serviceName>=1.0.0 & <1.1.0" ) expectThat(satisfiedConstraint).isTrue() } test("Service version does not satisfy plugin requirement constraint range with upper limit") { val satisfiedConstraint = subject.checkVersionConstraint( "1.1.0", "$serviceName>=1.0.0 & <1.1.0" ) expectThat(satisfiedConstraint).isFalse() } test("Service version does not satisfy plugin requirement constraint range with lower limit") { val satisfiedConstraint = subject.checkVersionConstraint( "0.0.9", "$serviceName>=1.0.0 & <1.1.0" ) expectThat(satisfiedConstraint).isFalse() } test("Plugin version X is less than plugin version Y by -1") { val x = "2.9.8" val y = "2.9.9" val comparisonResult = subject.compareVersions(x, y) expectThat(comparisonResult).isEqualTo(-1) } test("Plugin version X is greater than plugin version Y by 1") { val x = "3.0.0" val y = "2.0.0" val comparisonResult = subject.compareVersions(x, y) expectThat(comparisonResult).isEqualTo(1) } test("Empty requires is allowed") { val satisfiedConstraint = subject.checkVersionConstraint("0.0.9", "") expectThat(satisfiedConstraint).isTrue() } } private class Fixture { val serviceName = "orca" val subject = SpinnakerServiceVersionManager(serviceName) } }
apache-2.0
4b19dfd4bff28e65ccaf07a3adccae24
30.646018
99
0.67981
4.47
false
true
false
false
charlesmadere/smash-ranks-android
smash-ranks-android/app/src/main/java/com/garpr/android/features/splash/SplashScreenViewModel.kt
1
3114
package com.garpr.android.features.splash import androidx.annotation.AnyThread import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.garpr.android.data.models.FavoritePlayer import com.garpr.android.data.models.Region import com.garpr.android.features.common.viewModels.BaseViewModel import com.garpr.android.misc.Schedulers import com.garpr.android.misc.Timber import com.garpr.android.preferences.GeneralPreferenceStore import com.garpr.android.repositories.IdentityRepository import com.garpr.android.repositories.RegionRepository class SplashScreenViewModel( private val generalPreferenceStore: GeneralPreferenceStore, private val identityRepository: IdentityRepository, private val regionRepository: RegionRepository, private val schedulers: Schedulers, private val timber: Timber ) : BaseViewModel() { private val _stateLiveData = MutableLiveData<State>() val stateLiveData: LiveData<State> = _stateLiveData private var state: State = State( isSplashScreenComplete = generalPreferenceStore.hajimeteKimasu.get() == false, region = regionRepository.region ) set(value) { field = value _stateLiveData.postValue(value) } companion object { private const val TAG = "SplashScreenViewModel" } init { initListeners() } private fun initListeners() { disposables.add(generalPreferenceStore.hajimeteKimasu.observable .subscribeOn(schedulers.background) .observeOn(schedulers.background) .subscribe { hajimeteKimasu -> refreshIsSplashScreenComplete(hajimeteKimasu.orElse(false)) }) disposables.add(identityRepository.identityObservable .subscribeOn(schedulers.background) .observeOn(schedulers.background) .subscribe { identity -> refreshIdentity(identity.orNull()) }) disposables.add(regionRepository.observable .subscribeOn(schedulers.background) .observeOn(schedulers.background) .subscribe { region -> refreshRegion(region) }) } @AnyThread private fun refreshIsSplashScreenComplete(hajimeteKimasu: Boolean) { state = state.copy(isSplashScreenComplete = !hajimeteKimasu) } @AnyThread private fun refreshIdentity(identity: FavoritePlayer?) { state = state.copy(identity = identity) } @AnyThread private fun refreshRegion(region: Region) { state = state.copy(region = region) } fun removeIdentity() { identityRepository.removeIdentity() } fun setSplashScreenComplete() { timber.d(TAG, "splash screen has been completed") generalPreferenceStore.hajimeteKimasu.set(false) } data class State( val isSplashScreenComplete: Boolean, val identity: FavoritePlayer? = null, val region: Region ) }
unlicense
a0976e0bfcc787f6326493d671a9deea
31.4375
90
0.668915
5.295918
false
false
false
false
iluu/algs-progfun
src/main/kotlin/com/hackerrank/ClimbingTheLeaderboard.kt
1
581
package com.hackerrank import java.util.* fun main(args: Array<String>) { val scan = Scanner(System.`in`) val n = scan.nextInt() val scores = Stack<Int>() for (i in 0..n - 1) { val score = scan.nextInt() if (i == 0 || scores.peek() != score) { scores.push(score) } } val m = scan.nextInt() for (i in 0..m - 1) { val alice = scan.nextInt() while (!scores.empty() && scores.peek() <= alice) { scores.pop() } println(if (scores.isEmpty()) "1" else scores.size + 1) } }
mit
fba82acc82b135b4ff3730153c5fbe23
22.28
63
0.504303
3.43787
false
false
false
false
http4k/http4k
http4k-core/src/main/kotlin/org/http4k/routing/inspect/inspection.kt
1
2648
package org.http4k.routing.inspect import org.http4k.routing.RouterDescription import org.http4k.routing.RouterMatch import org.http4k.routing.RouterMatch.MatchedWithoutHandler import org.http4k.routing.RouterMatch.MatchingHandler import org.http4k.routing.RouterMatch.MethodNotMatched import org.http4k.routing.RouterMatch.Unmatched import org.http4k.routing.inspect.EscapeMode.Ansi fun RouterDescription.prettify(depth: Int = 0, escape: EscapeMode = Ansi) = PrettyNode(this).prettify(depth, escape) fun RouterMatch.prettify(depth: Int = 0, escape: EscapeMode = Ansi) = PrettyNode(this).prettify(depth, escape) private data class PrettyNode(val name: String, val textStyle: TextStyle, val groupStyle: TextStyle, val children: List<PrettyNode>) { constructor(description: RouterDescription) : this( description.description, TextStyle(ForegroundColour.Cyan), TextStyle(), description.children.map { PrettyNode(it) } ) constructor(match: RouterMatch) : this( match.description.description, match.resolveStyle(), match.resolveStyle(), match.subMatches.map { PrettyNode(it) } ) fun prettify(depth: Int = 0, escapeMode: EscapeMode = Ansi) = when (name) { "or" -> orRendering(depth, escapeMode) "and" -> andRenderer(depth, escapeMode) else -> name.styled(textStyle, escapeMode) } private fun orRendering(depth: Int, escapeMode: EscapeMode): String = if (children.isEmpty()) { name.styled(textStyle, escapeMode) } else { val nIndent = (" ".repeat(depth * 2)).let{"\n$it"} val prefix = if(depth == 0 /*no leading newline*/) "" else nIndent prefix + "(".styled(groupStyle, escapeMode) + children.joinToString("$nIndent ${name.styled(groupStyle, escapeMode)} ") { it.prettify(depth + 1, escapeMode) } + ")".styled(groupStyle, escapeMode) } private fun andRenderer(depth: Int, escapeMode: EscapeMode): String = if (children.isEmpty()) { name.styled(textStyle, escapeMode) } else { "(".styled(groupStyle, escapeMode) + children.joinToString(" ${name.styled(groupStyle, escapeMode)} ") { it.prettify(depth + 1, escapeMode) } + ")".styled(groupStyle, escapeMode) } } private fun RouterMatch.resolveStyle(): TextStyle = when (this) { is MatchingHandler, is MatchedWithoutHandler -> TextStyle(ForegroundColour.Green) is MethodNotMatched, is Unmatched -> TextStyle(ForegroundColour.Red, variation = Variation.Strikethrough) }
apache-2.0
5ae310dc43104c0addfcc48ba07f8970
41.709677
134
0.671828
4.298701
false
false
false
false
jankotek/mapdb-benchmarks
src/test/java/org/mapdb/benchmark/Bench.kt
1
3381
package org.mapdb.benchmark import java.io.* import java.util.* /** * Benchmark utilities */ object Bench{ val propFile = File("target/benchmark.properties") fun bench(benchName:String=callerName(), body:()->Long){ val many = testScale()>0; val metric = if(!many) { body() }else{ //run many times and do average var t=0L; for(i in 0 until 100) t += body() t/100 } var formatedMetrics = String.format("%12s", String.format("%,d", metric)) println("BENCH: $formatedMetrics - $benchName ") //load, update and save property file with results val props = object : Properties(){ //save keys in sorted order override fun keys(): Enumeration<Any>? { return Collections.enumeration(TreeSet(keys)); } } if(propFile.exists()) props.load(propFile.inputStream().buffered()) props.put(benchName, metric.toString()) val out = propFile.outputStream() val out2 = out.buffered() props.store(out2,"mapdb benchmark") out2.flush() out.close() //remove all temp dirs tempDirs.forEach { tempDeleteRecur(it) } tempDirs.clear() } fun stopwatch(body:()->Unit):Long{ val start = System.currentTimeMillis() body() return System.currentTimeMillis() - start } /** returns class name and method name of caller from previous stack trace frame */ inline fun callerName():String{ val t = Thread.currentThread().stackTrace val t0 = t[2] return t0.className+"."+t0.methodName } @JvmStatic fun testScale(): Int { val prop = System.getProperty("testLong")?:"0" try { return Integer.valueOf(prop); } catch(e:NumberFormatException) { return 0; } } private val tempDir = System.getProperty("java.io.tmpdir"); private val tempDirs = HashSet<File>() /* * Create temporary directory in temp folder. */ @JvmStatic fun tempDir(): File { try { val stackTrace = Thread.currentThread().stackTrace; val elem = stackTrace[2]; val prefix = "mapdbTest_"+elem.className+"#"+elem.methodName+":"+elem.lineNumber+"_" while(true){ val dir = File(tempDir+"/"+prefix+System.currentTimeMillis()+"_"+Math.random()); if(dir.exists()) continue dir.mkdirs() tempDirs+=dir return dir } } catch (e: IOException) { throw IOError(e) } } @JvmStatic fun tempFile(): File { return File(tempDir(), "benchFile") } @JvmStatic fun tempDelete(file: File){ val name = file.getName() for (f2 in file.getParentFile().listFiles()!!) { if (f2.name.startsWith(name)) tempDeleteRecur(f2) } tempDeleteRecur(file) } @JvmStatic fun tempDeleteRecur(file: File) { if(file.isDirectory){ for(child in file.listFiles()) tempDeleteRecur(child) } file.delete() } }
apache-2.0
f0b92054a1d37f4a482909c02a361779
26.942149
96
0.529725
4.587517
false
false
false
false
kgtkr/mhxx-switch-cis
src/main/kotlin/Analysis.kt
1
4244
package com.github.kgtkr.mhxxSwitchCIS import org.apache.commons.io.FileUtils import org.apache.commons.io.FilenameUtils import java.awt.Color import java.awt.image.BufferedImage import java.io.ByteArrayInputStream import java.io.File import java.util.* import javax.imageio.ImageIO typealias BitImages=List<Pair<String,BitImage>> private fun readImage(name:String):List<Pair<String,BufferedImage>> { val data = FileUtils.readFileToString(File("./data/${name}"), "utf8") return data.split("\n") .map { s -> s.split(",") } .map { s -> Pair(s[0], s[1]) } .map { data -> Pair(data.first, Base64.getDecoder().decode(data.second)) } .map { data -> Pair(data.first, ImageIO.read(ByteArrayInputStream(data.second))) } } private fun readBitImage(name:String):BitImages{ return readImage(name) .map{x-> Pair(x.first,x.second.toBitImage(IC.COLOR,IC.THRESHOLD)) } } private fun Triple<BufferedImage, BufferedImage, BufferedImage>.getVal(values:Triple<BitImages,BitImages,BitImages>):Int{ val val0=this.first.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(values.first) val val1=when(val0){ ""->this.second.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(values.second) else->"1" } val val2=when(val1){ "1"->this.third.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(values.third.filter { x->x.first=="0"||x.first=="1"||x.first=="2"||x.first=="3" }) else->this.third.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(values.third.filter { x->x.first!="0"}) } return (val0+val1+val2).toInt() } private fun BufferedImage.getSlot():Int{ val slot1Color= Color(this.getRGB(IC.SLOT1_COLOR_X,IC.SLOT_COLOR_Y)) val slot2Color= Color(this.getRGB(IC.SLOT2_COLOR_X,IC.SLOT_COLOR_Y)) val slot3Color= Color(this.getRGB(IC.SLOT3_COLOR_X,IC.SLOT_COLOR_Y)) return if(slot3Color.deff(IC.SLOT_COLOR)>IC.SLOT_THRESHOLD){ 3 }else if(slot2Color.deff(IC.SLOT_COLOR)>IC.SLOT_THRESHOLD){ 2 }else if(slot1Color.deff(IC.SLOT_COLOR)>IC.SLOT_THRESHOLD){ 1 }else{ 0 } } private fun BufferedImage.getGoseki(gosekis:List<Pair<String,Color>>):String{ return this.deffMinIndex(IC.GOSEKI_COLOR_X,IC.GOSEKI_COLOR_Y,gosekis) } private fun BufferedImage.getSkillName(skills:BitImages):String{ return this.toBitImage(IC.COLOR,IC.THRESHOLD).deffMinIndex(skills) } fun analysisCmd(){ //データ読み込み val skills=readBitImage("skill") val values=Triple(readBitImage("value0"),readBitImage("value1"),readBitImage("value2")) val gosekis=readImage("goseki") .map{x->Pair(x.first,Color(x.second.getRGB(IC.GOSEKI_COLOR_X,IC.GOSEKI_COLOR_Y)))} val csv=readImages("./input") .map{row-> val skill1Name=row.oneSkillName.getSkillName(skills.filter { s->s.first.isNotEmpty() }) if(skill1Name!="(無)") { val goseki = row.goseki.getGoseki(gosekis) val skill1 = Pair(skill1Name, row.oneSkillValue.getVal(values.copy(first = values.first.filter { s->s.first!="-" },second = values.second.filter { s->s.first!="-" }))) val skill2Name = row.twoSkillName.getSkillName(skills.filter { s -> s.first != "(無)" }) val skill2 = when (skill2Name) { "" -> null else -> Pair(skill2Name, row.twoSkillValue.getVal(values)) } val slot = row.slot.getSlot() Goseki(goseki, skill1, skill2, slot) }else{ null } } .filterNotNull() .map{g-> if(g.skill2!=null){ "${g.goseki},${g.slot},${g.skill1.first},${g.skill1.second},${g.skill2.first},${g.skill2.second}" }else{ "${g.goseki},${g.slot},${g.skill1.first},${g.skill1.second}" } } .joinToString("\n") val header="#護石名,スロット,第一スキル名,第一スキルポイント,第ニスキル名,第ニスキルポイント\n" FileUtils.write(File("./CHARM.csv"),header+csv,"sjis") }
gpl-3.0
321118fde543bafece58b3328d5287ad
38.923077
187
0.617052
3.37013
false
false
false
false
Retronic/life-in-space
core/src/main/kotlin/com/retronicgames/lis/visual/buildings/DataVisualBuildings.kt
1
690
package com.retronicgames.lis.visual.buildings import com.retronicgames.lis.visual.DataVisual import com.retronicgames.utils.IntVector2 object DataVisualBuildingLandingZone : DataVisual { override val offset = IntVector2.ZERO } object DataVisualBuildingLivingBlock : DataVisual { override val offset = IntVector2.ZERO } object DataVisualBuildingDigSite: DataVisual { override val offset = IntVector2.ZERO } object DataVisualBuildingPowerBlock: DataVisual { override val offset = IntVector2.ZERO } object DataVisualBuildingSolarPanels: DataVisual { override val offset = IntVector2.ZERO } object DataVisualBuildingLaboratory: DataVisual { override val offset = IntVector2.ZERO }
gpl-3.0
7cd248ae974c1a9a8f4a52e06784e23d
23.678571
51
0.824638
4.285714
false
false
false
false
FarbodSalamat-Zadeh/TimetableApp
app/src/main/java/co/timetableapp/util/UiUtils.kt
1
5744
/* * Copyright 2017 Farbod Salamat-Zadeh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package co.timetableapp.util import android.app.Activity import android.content.Context import android.graphics.Typeface import android.graphics.drawable.Drawable import android.os.Build import android.support.annotation.ColorRes import android.support.annotation.DrawableRes import android.support.annotation.IdRes import android.support.annotation.StringRes import android.support.graphics.drawable.VectorDrawableCompat import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat import android.view.LayoutInflater import android.view.Menu import android.view.View import android.widget.ImageView import android.widget.TextView import co.timetableapp.R import co.timetableapp.model.Color object UiUtils { @JvmStatic fun setBarColors(color: Color, activity: Activity, vararg views: View) { for (view in views) { view.setBackgroundColor(ContextCompat.getColor( activity, color.getPrimaryColorResId(activity))) } if (Build.VERSION.SDK_INT >= 21) { activity.window.statusBarColor = ContextCompat.getColor(activity, color.getPrimaryDarkColorResId(activity)) } } @JvmStatic fun tintMenuIcons(context: Context, menu: Menu, vararg @IdRes menuItems: Int) { menuItems.forEach { val icon = menu.findItem(it).icon icon?.let { tintMenuDrawableWhite(context, icon) } } } @JvmOverloads @JvmStatic fun tintDrawable(context: Context, @DrawableRes drawableRes: Int, @ColorRes colorRes: Int = R.color.mdu_white): Drawable { val vectorDrawableCompat = VectorDrawableCompat.create(context.resources, drawableRes, null) val drawable = DrawableCompat.wrap(vectorDrawableCompat!!.current) DrawableCompat.setTint(drawable, ContextCompat.getColor(context, colorRes)) return drawable } private fun tintMenuDrawableWhite(context: Context, d: Drawable): Drawable { val drawable = DrawableCompat.wrap(d) DrawableCompat.setTint(drawable, ContextCompat.getColor(context, R.color.mdu_white)) return drawable } @JvmOverloads @JvmStatic fun makePlaceholderView(context: Context, @DrawableRes drawableRes: Int, @StringRes titleRes: Int, @ColorRes backgroundColorRes: Int = R.color.mdu_grey_50, @ColorRes drawableColorRes: Int = R.color.mdu_grey_700, @ColorRes textColorRes: Int = R.color.mdu_text_black_secondary, largeIcon: Boolean = false, @StringRes subtitleRes: Int? = null): View { val placeholderView = LayoutInflater.from(context).inflate(R.layout.placeholder, null) val background = placeholderView.findViewById(R.id.background) background.setBackgroundColor(ContextCompat.getColor(context, backgroundColorRes)) val image = placeholderView.findViewById(R.id.imageView) as ImageView image.setImageDrawable(tintDrawable(context, drawableRes, drawableColorRes)) if (largeIcon) { image.layoutParams.width = dpToPixels(context, 108) image.layoutParams.height = dpToPixels(context, 108) } val title = placeholderView.findViewById(R.id.title) as TextView title.setText(titleRes) title.setTextColor(ContextCompat.getColor(context, textColorRes)) val subtitle = placeholderView.findViewById(R.id.subtitle) as TextView if (subtitleRes == null) { subtitle.visibility = View.GONE } else { subtitle.setText(subtitleRes) subtitle.setTextColor(ContextCompat.getColor(context, textColorRes)) } return placeholderView } /** * Formats the appearance of a TextView displaying item notes. For example, assignment notes or * exam notes. * * If there are no notes to display (i.e. [notes] is blank), then a placeholder text will be * shown instead with a lighter font color. */ @JvmStatic fun formatNotesTextView(context: Context, textView: TextView, notes: String) { with(textView) { if (notes.isBlank()) { text = context.getString(R.string.placeholder_notes_empty) setTypeface(null, Typeface.ITALIC) setTextColor(ContextCompat.getColor(context, R.color.mdu_text_black_secondary)) } else { text = notes setTypeface(null, android.graphics.Typeface.NORMAL) setTextColor(ContextCompat.getColor(context, R.color.mdu_text_black)) } } } @JvmStatic fun dpToPixels(context: Context, dps: Int): Int { val density = context.resources.displayMetrics.density val dpAsPixels = (dps * density + 0.5f).toInt() return dpAsPixels } @JvmStatic fun isApi21() = Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP }
apache-2.0
fd73739f8a05c4758c4255d3e5deef04
37.293333
100
0.668175
4.754967
false
false
false
false
Ch3D/AndroidUtils
app/src/main/kotlin/com/ch3d/android/utils/StringUtils.kt
1
1529
package com.ch3d.android.utils import android.content.Context import android.util.TypedValue class StringUtils { companion object { fun dpToPx(context: Context, i: Float): Float { val displayMetrics = context.resources.displayMetrics return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, i, displayMetrics) } val EMPTY_STRING = "" val DASH = "-" val SPACE = " " val UNDERSCORE = "_" val NEXT_STRING = "\n" /** * Safely checks whether two strings are equal or not * @return true - if strings are equal, false - otherwise */ fun hasChanges(newValue: String, oldValue: String): Boolean { if (StringUtils.isEmpty(newValue) && StringUtils.isEmpty(oldValue)) { return false } else if (StringUtils.isEmpty(newValue) && !StringUtils.isEmpty(oldValue)) { return true } else return !StringUtils.isEmpty(newValue) && StringUtils.isEmpty( oldValue) || newValue.trim { it <= ' ' } != oldValue.trim { it <= ' ' } } /** * Returns true if the string is null or 0-length. * @param str the string to be examined * * * @return true if str is null or zero length */ fun hasNoEmptyValue(vararg str: CharSequence) = str.all { seq -> !isEmpty(seq) } fun isEmpty(str: CharSequence?) = str == null || str.length == 0 } }
apache-2.0
5d837093d1edb45ec88e94c071699c39
32.23913
95
0.568999
4.619335
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/livedata/LiveSharedPreference.kt
1
1108
package com.boardgamegeek.livedata import android.content.Context import android.content.SharedPreferences import androidx.lifecycle.MutableLiveData import com.boardgamegeek.extensions.preferences @Suppress("UNCHECKED_CAST") class LiveSharedPreference<T>(context: Context, preferenceKey: String, sharedPreferencesName: String? = null) : MutableLiveData<T>() { private val listener: SharedPreferences.OnSharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key -> if (key == preferenceKey) { value = sharedPreferences.all[key] as T } } private val sharedPreferences: SharedPreferences = context.preferences(sharedPreferencesName) init { value = sharedPreferences.all[preferenceKey] as T } override fun onActive() { super.onActive() sharedPreferences.registerOnSharedPreferenceChangeListener(listener) } override fun onInactive() { super.onInactive() sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener) } }
gpl-3.0
58f927037ed501aa3a82401702bcc1ff
34.741935
134
0.736462
5.925134
false
false
false
false
cfig/Nexus_boot_image_editor
helper/src/main/kotlin/cfig/io/Struct3.kt
1
22172
// Copyright 2021 [email protected] // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package cfig.io import cfig.io.Struct3.ByteArrayExt.Companion.toCString import cfig.io.Struct3.ByteArrayExt.Companion.toInt import cfig.io.Struct3.ByteArrayExt.Companion.toLong import cfig.io.Struct3.ByteArrayExt.Companion.toShort import cfig.io.Struct3.ByteArrayExt.Companion.toUInt import cfig.io.Struct3.ByteArrayExt.Companion.toULong import cfig.io.Struct3.ByteArrayExt.Companion.toUShort import cfig.io.Struct3.ByteBufferExt.Companion.appendByteArray import cfig.io.Struct3.ByteBufferExt.Companion.appendPadding import cfig.io.Struct3.ByteBufferExt.Companion.appendUByteArray import cfig.io.Struct3.InputStreamExt.Companion.getByteArray import cfig.io.Struct3.InputStreamExt.Companion.getCString import cfig.io.Struct3.InputStreamExt.Companion.getChar import cfig.io.Struct3.InputStreamExt.Companion.getInt import cfig.io.Struct3.InputStreamExt.Companion.getLong import cfig.io.Struct3.InputStreamExt.Companion.getPadding import cfig.io.Struct3.InputStreamExt.Companion.getShort import cfig.io.Struct3.InputStreamExt.Companion.getUByteArray import cfig.io.Struct3.InputStreamExt.Companion.getUInt import cfig.io.Struct3.InputStreamExt.Companion.getULong import cfig.io.Struct3.InputStreamExt.Companion.getUShort import org.slf4j.LoggerFactory import java.io.IOException import java.io.InputStream import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.charset.StandardCharsets import java.util.* import java.util.regex.Pattern import kotlin.random.Random class Struct3 { private val formatString: String private var byteOrder = ByteOrder.LITTLE_ENDIAN private val formats = ArrayList<Array<Any?>>() constructor(inFormatString: String) { assert(inFormatString.isNotEmpty()) { "FORMAT_STRING must not be empty" } formatString = inFormatString val m = Pattern.compile("(\\d*)([a-zA-Z])").matcher(formatString) when (formatString[0]) { '>', '!' -> this.byteOrder = ByteOrder.BIG_ENDIAN '@', '=' -> this.byteOrder = ByteOrder.nativeOrder() else -> this.byteOrder = ByteOrder.LITTLE_ENDIAN } while (m.find()) { //item[0]: Type, item[1]: multiple // if need to expand format items, explode it // eg: "4L" will be exploded to "1L 1L 1L 1L", so it's treated as primitive // eg: "10x" won't be exploded, it's still "10x", so it's treated as non-primitive val typeName: Any = when (m.group(2)) { //primitive types "x" -> Random //byte 1 (exploded) "b" -> Byte //byte 1 (exploded) "B" -> UByte //UByte 1 (exploded) "s" -> String //string (exploded) //zippable types, which need to be exploded with multiple=1 "c" -> Char "h" -> Short //2 "H" -> UShort //2 "i", "l" -> Int //4 "I", "L" -> UInt //4 "q" -> Long //8 "Q" -> ULong //8 else -> throw IllegalArgumentException("type [" + m.group(2) + "] not supported") } val bPrimitive = m.group(2) in listOf("x", "b", "B", "s") val multiple = if (m.group(1).isEmpty()) 1 else Integer.decode(m.group(1)) if (bPrimitive) { formats.add(arrayOf<Any?>(typeName, multiple)) } else { for (i in 0 until multiple) { formats.add(arrayOf<Any?>(typeName, 1)) } } } } private fun getFormatInfo(inCursor: Int): String { return ("type=" + formats.get(inCursor)[0] + ", value=" + formats.get(inCursor)[1]) } override fun toString(): String { val formatStr = mutableListOf<String>() formats.forEach { val fs = StringBuilder() when (it[0]) { Random -> fs.append("x") Byte -> fs.append("b") UByte -> fs.append("B") String -> fs.append("s") Char -> fs.append("c") Short -> fs.append("h") UShort -> fs.append("H") Int -> fs.append("i") UInt -> fs.append("I") Long -> fs.append("q") ULong -> fs.append("Q") else -> throw IllegalArgumentException("type [" + it[0] + "] not supported") } fs.append(":" + it[1]) formatStr.add(fs.toString()) } return "Struct3(formatString='$formatString', byteOrder=$byteOrder, formats=$formatStr)" } fun calcSize(): Int { var ret = 0 for (format in formats) { ret += when (val formatType = format[0]) { Random, Byte, UByte, Char, String -> format[1] as Int Short, UShort -> 2 * format[1] as Int Int, UInt -> 4 * format[1] as Int Long, ULong -> 8 * format[1] as Int else -> throw IllegalArgumentException("Class [$formatType] not supported") } } return ret } @Throws(IllegalArgumentException::class) fun pack(vararg args: Any?): ByteArray { if (args.size != this.formats.size) { throw IllegalArgumentException("argument size " + args.size + " doesn't match format size " + this.formats.size) } val bf = ByteBuffer.allocate(this.calcSize()) bf.order(this.byteOrder) for (i in args.indices) { val arg = args[i] val typeName = formats[i][0] val multiple = formats[i][1] as Int if (typeName !in arrayOf(Random, Byte, String, UByte)) { assert(1 == multiple) } //x: padding: if (Random == typeName) { when (arg) { null -> bf.appendPadding(0, multiple) is Byte -> bf.appendPadding(arg, multiple) is Int -> bf.appendPadding(arg.toByte(), multiple) else -> throw IllegalArgumentException("Index[" + i + "] Unsupported arg [" + arg + "] with type [" + formats[i][0] + "]") } continue } //c: character if (Char == typeName) { assert(arg is Char) { "[$arg](${arg!!::class.java}) is NOT Char" } if ((arg as Char) !in '\u0000'..'\u00ff') { throw IllegalArgumentException("arg[${arg.code}] exceeds 8-bit bound") } bf.put(arg.code.toByte()) continue } //b: byte array if (Byte == typeName) { when (arg) { is IntArray -> bf.appendByteArray(arg, multiple) is ByteArray -> bf.appendByteArray(arg, multiple) else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT ByteArray/IntArray") } continue } //B: UByte array if (UByte == typeName) { when (arg) { is ByteArray -> bf.appendByteArray(arg, multiple) is UByteArray -> bf.appendUByteArray(arg, multiple) is IntArray -> bf.appendUByteArray(arg, multiple) else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT ByteArray/IntArray") } continue } //s: String if (String == typeName) { assert(arg != null) { "arg can not be NULL for String, formatString=$formatString, ${getFormatInfo(i)}" } assert(arg is String) { "[$arg](${arg!!::class.java}) is NOT String, ${getFormatInfo(i)}" } bf.appendByteArray((arg as String).toByteArray(), multiple) continue } //h: Short if (Short == typeName) { when (arg) { is Int -> { assert(arg in Short.MIN_VALUE..Short.MAX_VALUE) { "[$arg] is truncated as type Short.class" } bf.putShort(arg.toShort()) } is Short -> bf.putShort(arg) //instance Short else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT Short/Int") } continue } //H: UShort if (UShort == typeName) { assert(arg is UShort || arg is UInt || arg is Int) { "[$arg](${arg!!::class.java}) is NOT UShort/UInt/Int" } when (arg) { is Int -> { assert(arg >= UShort.MIN_VALUE.toInt() && arg <= UShort.MAX_VALUE.toInt()) { "[$arg] is truncated as type UShort" } bf.putShort(arg.toShort()) } is UInt -> { assert(arg >= UShort.MIN_VALUE && arg <= UShort.MAX_VALUE) { "[$arg] is truncated as type UShort" } bf.putShort(arg.toShort()) } is UShort -> bf.putShort(arg.toShort()) } continue } //i, l: Int if (Int == typeName) { assert(arg is Int) { "[$arg](${arg!!::class.java}) is NOT Int" } bf.putInt(arg as Int) continue } //I, L: UInt if (UInt == typeName) { when (arg) { is Int -> { assert(arg >= 0) { "[$arg] is invalid as type UInt" } bf.putInt(arg) } is UInt -> bf.putInt(arg.toInt()) is Long -> { assert(arg >= 0) { "[$arg] is invalid as type UInt" } bf.putInt(arg.toInt()) } else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT UInt/Int/Long") } continue } //q: Long if (Long == typeName) { when (arg) { is Long -> bf.putLong(arg) is Int -> bf.putLong(arg.toLong()) else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT Long/Int") } continue } //Q: ULong if (ULong == typeName) { when (arg) { is Int -> { assert(arg >= 0) { "[$arg] is invalid as type ULong" } bf.putLong(arg.toLong()) } is Long -> { assert(arg >= 0) { "[$arg] is invalid as type ULong" } bf.putLong(arg) } is ULong -> bf.putLong(arg.toLong()) else -> throw IllegalArgumentException("[$arg](${arg!!::class.java}) is NOT Int/Long/ULong") } continue } throw IllegalArgumentException("unrecognized format $typeName") } return bf.array() } @Throws(IOException::class, IllegalArgumentException::class) fun unpack(iS: InputStream): List<*> { val ret = ArrayList<Any>() for (format in this.formats) { when (format[0]) { Random -> ret.add(iS.getPadding(format[1] as Int)) //return padding byte Byte -> ret.add(iS.getByteArray(format[1] as Int)) //b: byte array UByte -> ret.add(iS.getUByteArray(format[1] as Int)) //B: ubyte array Char -> ret.add(iS.getChar()) //char: 1 String -> ret.add(iS.getCString(format[1] as Int)) //c string Short -> ret.add(iS.getShort(this.byteOrder)) //h: short UShort -> ret.add(iS.getUShort(this.byteOrder)) //H: UShort Int -> ret.add(iS.getInt(this.byteOrder)) //i, l: Int UInt -> ret.add(iS.getUInt(this.byteOrder)) //I, L: UInt Long -> ret.add(iS.getLong(this.byteOrder)) //q: Long ULong -> ret.add(iS.getULong(this.byteOrder)) //Q: ULong else -> throw IllegalArgumentException("Class [" + format[0] + "] not supported") }//end-of-when }//end-of-for return ret } class ByteBufferExt { companion object { private val log = LoggerFactory.getLogger(ByteBufferExt::class.java) @Throws(IllegalArgumentException::class) fun ByteBuffer.appendPadding(b: Byte, bufSize: Int) { when { bufSize == 0 -> { log.debug("paddingSize is zero, perfect match") return } bufSize < 0 -> { throw IllegalArgumentException("illegal padding size: $bufSize") } else -> { log.debug("paddingSize $bufSize") } } val padding = ByteArray(bufSize) Arrays.fill(padding, b) this.put(padding) } fun ByteBuffer.appendByteArray(inIntArray: IntArray, bufSize: Int) { val arg2 = mutableListOf<Byte>() inIntArray.toMutableList().mapTo(arg2) { if (it in Byte.MIN_VALUE..Byte.MAX_VALUE) { it.toByte() } else { throw IllegalArgumentException("$it is not valid Byte") } } appendByteArray(arg2.toByteArray(), bufSize) } @Throws(IllegalArgumentException::class) fun ByteBuffer.appendByteArray(inByteArray: ByteArray, bufSize: Int) { val paddingSize = bufSize - inByteArray.size if (paddingSize < 0) throw IllegalArgumentException("arg length [${inByteArray.size}] exceeds limit: $bufSize") //data this.put(inByteArray) //padding this.appendPadding(0.toByte(), paddingSize) log.debug("paddingSize $paddingSize") } fun ByteBuffer.appendUByteArray(inIntArray: IntArray, bufSize: Int) { val arg2 = mutableListOf<UByte>() inIntArray.toMutableList().mapTo(arg2) { if (it in UByte.MIN_VALUE.toInt()..UByte.MAX_VALUE.toInt()) it.toUByte() else { throw IllegalArgumentException("$it is not valid Byte") } } appendUByteArray(arg2.toUByteArray(), bufSize) } fun ByteBuffer.appendUByteArray(inUByteArray: UByteArray, bufSize: Int) { val bl = mutableListOf<Byte>() inUByteArray.toMutableList().mapTo(bl) { it.toByte() } this.appendByteArray(bl.toByteArray(), bufSize) } } } class InputStreamExt { companion object { fun InputStream.getChar(): Char { val data = ByteArray(Byte.SIZE_BYTES) assert(Byte.SIZE_BYTES == this.read(data)) return data[0].toInt().toChar() } fun InputStream.getShort(inByteOrder: ByteOrder): Short { val data = ByteArray(Short.SIZE_BYTES) assert(Short.SIZE_BYTES == this.read(data)) return data.toShort(inByteOrder) } fun InputStream.getInt(inByteOrder: ByteOrder): Int { val data = ByteArray(Int.SIZE_BYTES) assert(Int.SIZE_BYTES == this.read(data)) return data.toInt(inByteOrder) } fun InputStream.getLong(inByteOrder: ByteOrder): Long { val data = ByteArray(Long.SIZE_BYTES) assert(Long.SIZE_BYTES == this.read(data)) return data.toLong(inByteOrder) } fun InputStream.getUShort(inByteOrder: ByteOrder): UShort { val data = ByteArray(UShort.SIZE_BYTES) assert(UShort.SIZE_BYTES == this.read(data)) return data.toUShort(inByteOrder) } fun InputStream.getUInt(inByteOrder: ByteOrder): UInt { val data = ByteArray(UInt.SIZE_BYTES) assert(UInt.SIZE_BYTES == this.read(data)) return data.toUInt(inByteOrder) } fun InputStream.getULong(inByteOrder: ByteOrder): ULong { val data = ByteArray(ULong.SIZE_BYTES) assert(ULong.SIZE_BYTES == this.read(data)) return data.toULong(inByteOrder) } fun InputStream.getByteArray(inSize: Int): ByteArray { val data = ByteArray(inSize) assert(inSize == this.read(data)) return data } fun InputStream.getUByteArray(inSize: Int): UByteArray { val data = ByteArray(inSize) assert(inSize == this.read(data)) val innerData2 = mutableListOf<UByte>() data.toMutableList().mapTo(innerData2) { it.toUByte() } return innerData2.toUByteArray() } fun InputStream.getCString(inSize: Int): String { val data = ByteArray(inSize) assert(inSize == this.read(data)) return data.toCString() } fun InputStream.getPadding(inSize: Int): Byte { val data = ByteArray(Byte.SIZE_BYTES) assert(Byte.SIZE_BYTES == this.read(data)) //sample the 1st byte val skipped = this.skip(inSize.toLong() - Byte.SIZE_BYTES)//skip remaining to save memory assert(inSize.toLong() - Byte.SIZE_BYTES == skipped) return data[0] } } } class ByteArrayExt { companion object { fun ByteArray.toShort(inByteOrder: ByteOrder): Short { val typeSize = Short.SIZE_BYTES / Byte.SIZE_BYTES assert(typeSize == this.size) { "Short must have $typeSize bytes" } return ByteBuffer.allocate(this.size).let { it.order(inByteOrder) it.put(this) it.flip() it.getShort() } } fun ByteArray.toInt(inByteOrder: ByteOrder): Int { val typeSize = Int.SIZE_BYTES / Byte.SIZE_BYTES assert(typeSize == this.size) { "Int must have $typeSize bytes" } return ByteBuffer.allocate(this.size).let { it.order(inByteOrder) it.put(this) it.flip() it.getInt() } } fun ByteArray.toLong(inByteOrder: ByteOrder): Long { val typeSize = Long.SIZE_BYTES / Byte.SIZE_BYTES assert(typeSize == this.size) { "Long must have $typeSize bytes" } return ByteBuffer.allocate(this.size).let { it.order(inByteOrder) it.put(this) it.flip() it.getLong() } } fun ByteArray.toUShort(inByteOrder: ByteOrder): UShort { val typeSize = UShort.SIZE_BYTES / Byte.SIZE_BYTES assert(typeSize == this.size) { "UShort must have $typeSize bytes" } return ByteBuffer.allocate(this.size).let { it.order(inByteOrder) it.put(this) it.flip() it.getShort().toUShort() } } fun ByteArray.toUInt(inByteOrder: ByteOrder): UInt { val typeSize = UInt.SIZE_BYTES / Byte.SIZE_BYTES assert(typeSize == this.size) { "UInt must have $typeSize bytes" } return ByteBuffer.allocate(this.size).let { it.order(inByteOrder) it.put(this) it.flip() it.getInt().toUInt() } } fun ByteArray.toULong(inByteOrder: ByteOrder): ULong { val typeSize = ULong.SIZE_BYTES / Byte.SIZE_BYTES assert(typeSize == this.size) { "ULong must have $typeSize bytes" } return ByteBuffer.allocate(this.size).let { it.order(inByteOrder) it.put(this) it.flip() it.getLong().toULong() } } //similar to this.toString(StandardCharsets.UTF_8).replace("${Character.MIN_VALUE}", "") // not Deprecated for now, "1.3.41 experimental api: ByteArray.decodeToString()") is a little different fun ByteArray.toCString(): String { return this.toString(StandardCharsets.UTF_8).let { str -> str.indexOf(Character.MIN_VALUE).let { nullPos -> if (nullPos >= 0) str.substring(0, nullPos) else str } } } }//end-of-Companion }//end-of-ByteArrayExt }
apache-2.0
0cc58624b9250cd25590865b69442c77
40.833962
142
0.509156
4.788769
false
false
false
false
world-federation-of-advertisers/cross-media-measurement
src/main/kotlin/org/wfanet/measurement/integration/deploy/gcloud/InProcessKingdom.kt
1
1787
// Copyright 2021 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.integration.deploy.gcloud import java.time.Clock import org.wfanet.measurement.common.identity.RandomIdGenerator import org.wfanet.measurement.gcloud.spanner.testing.SpannerEmulatorDatabaseRule import org.wfanet.measurement.integration.common.InProcessKingdom import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.SpannerDataServices import org.wfanet.measurement.kingdom.deploy.gcloud.spanner.testing.Schemata private const val REDIRECT_URI = "https://localhost:2048" private const val ALLOW_MPC_PROTOCOLS_FOR_SINGLE_DATA_PROVIDER = true fun buildKingdomSpannerEmulatorDatabaseRule(): SpannerEmulatorDatabaseRule { return SpannerEmulatorDatabaseRule(Schemata.KINGDOM_CHANGELOG_PATH) } fun buildSpannerInProcessKingdom( databaseRule: SpannerEmulatorDatabaseRule, clock: Clock = Clock.systemUTC(), verboseGrpcLogging: Boolean = false ): InProcessKingdom { return InProcessKingdom( dataServicesProvider = { SpannerDataServices(clock, RandomIdGenerator(clock), databaseRule.databaseClient) }, verboseGrpcLogging = verboseGrpcLogging, REDIRECT_URI, ALLOW_MPC_PROTOCOLS_FOR_SINGLE_DATA_PROVIDER ) }
apache-2.0
2498e537780317d19fef8a980e14f529
39.613636
87
0.797985
4.456359
false
false
false
false
SimonVT/cathode
trakt-api/src/main/java/net/simonvt/cathode/api/entity/Profile.kt
1
1161
/* * Copyright (C) 2014 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.api.entity import com.squareup.moshi.Json import net.simonvt.cathode.api.enumeration.Gender data class Profile( val username: String, @Json(name = "private") val isPrivate: Boolean? = null, val name: String? = null, val vip: Boolean? = null, val vip_ep: Boolean? = null, val vip_og: Boolean? = null, val vip_years: Int? = null, val joined_at: IsoTime? = null, val location: String? = null, val about: String? = null, val gender: Gender? = null, val age: Int? = null, val images: Images? = null )
apache-2.0
fe8aa5d5252728309ddea6013f7330d7
31.25
75
0.709733
3.650943
false
false
false
false
SimonVT/cathode
cathode-sync/src/main/java/net/simonvt/cathode/actions/user/SyncMovieRecommendations.kt
1
3031
/* * Copyright (C) 2013 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.actions.user import android.content.ContentProviderOperation import android.content.ContentValues import android.content.Context import net.simonvt.cathode.actions.CallAction import net.simonvt.cathode.api.entity.Movie import net.simonvt.cathode.api.enumeration.Extended import net.simonvt.cathode.api.service.RecommendationsService import net.simonvt.cathode.common.database.forEach import net.simonvt.cathode.common.database.getLong import net.simonvt.cathode.provider.DatabaseContract.MovieColumns import net.simonvt.cathode.provider.ProviderSchematic.Movies import net.simonvt.cathode.provider.batch import net.simonvt.cathode.provider.helper.MovieDatabaseHelper import net.simonvt.cathode.provider.query import net.simonvt.cathode.settings.SuggestionsTimestamps import retrofit2.Call import javax.inject.Inject class SyncMovieRecommendations @Inject constructor( private val context: Context, private val movieHelper: MovieDatabaseHelper, private val recommendationsService: RecommendationsService ) : CallAction<Unit, List<Movie>>() { override fun key(params: Unit): String = "SyncMovieRecommendations" override fun getCall(params: Unit): Call<List<Movie>> = recommendationsService.movies(LIMIT, Extended.FULL) override suspend fun handleResponse(params: Unit, response: List<Movie>) { val ops = arrayListOf<ContentProviderOperation>() val movieIds = mutableListOf<Long>() val localMovies = context.contentResolver.query(Movies.RECOMMENDED) localMovies.forEach { cursor -> movieIds.add(cursor.getLong(MovieColumns.ID)) } localMovies.close() response.forEachIndexed { index, movie -> val movieId = movieHelper.partialUpdate(movie) movieIds.remove(movieId) val values = ContentValues() values.put(MovieColumns.RECOMMENDATION_INDEX, index) val op = ContentProviderOperation.newUpdate(Movies.withId(movieId)).withValues(values).build() ops.add(op) } for (id in movieIds) { val op = ContentProviderOperation.newUpdate(Movies.withId(id)) .withValue(MovieColumns.RECOMMENDATION_INDEX, -1) .build() ops.add(op) } context.contentResolver.batch(ops) SuggestionsTimestamps.get(context) .edit() .putLong(SuggestionsTimestamps.MOVIES_RECOMMENDED, System.currentTimeMillis()) .apply() } companion object { private const val LIMIT = 50 } }
apache-2.0
5c18f236a6bbaf7b9bb4ba99e5b9e00a
35.518072
100
0.765424
4.367435
false
false
false
false
aucd29/common
library/src/main/java/net/sarangnamu/common/arch/viewmodel/RecyclerViewModel.kt
1
1613
/* * Copyright 2016 Burke Choi All rights reserved. * http://www.sarangnamu.net * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.sarangnamu.common.arch.viewmodel import android.arch.lifecycle.ViewModel import android.databinding.ObservableArrayList import android.databinding.ObservableField import net.sarangnamu.common.arch.adapter.BkAdapter /** * Created by <a href="mailto:[email protected]">Burke Choi</a> on 2018. 5. 11.. <p/> */ open class RecyclerViewModel<T> : ViewModel() { val items = ObservableArrayList<T>() val adapter = ObservableField<BkAdapter<T>>() open fun initAdapter(id: String) { val adapter = BkAdapter<T>(id) adapter.items = this.items adapter.vmodel = this this.adapter.set(adapter) } open fun initAdapter(ids: Array<String>) { val adapter = BkAdapter<T>(ids) adapter.items = this.items adapter.vmodel = this this.adapter.set(adapter) } fun clearItems(items: ArrayList<T>) { this.items.clear() this.items.addAll(items) } }
apache-2.0
c4bc3158a6039461777aed11ef7e1555
29.45283
84
0.689399
3.943765
false
false
false
false
SimonVT/cathode
trakt-api/src/main/java/net/simonvt/cathode/api/body/RateItems.kt
1
3614
/* * Copyright (C) 2014 Simon Vig Therkildsen * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.simonvt.cathode.api.body class RateItems private constructor(val movies: List<RatingMovie>, val shows: List<RatingShow>) { class Builder { val movies = mutableListOf<RatingMovie>() val shows = mutableListOf<RatingShow>() fun movie(traktId: Long, rating: Int, ratedAt: String): Builder { val movie = movies.firstOrNull { it.ids.trakt == traktId } if (movie != null) { throw IllegalArgumentException("Movie $traktId already rated in this request") } movies.add(RatingMovie(TraktId(traktId), rating, ratedAt)) return this } fun show(traktId: Long, rating: Int, ratedAt: String): Builder { val show = shows.firstOrNull { it.ids.trakt == traktId } if (show?.rating != null) { throw IllegalArgumentException("Show $traktId already rated in this request") } shows.add(RatingShow(TraktId(traktId), rating, ratedAt)) return this } fun season(showTraktId: Long, season: Int, rating: Int, ratedAt: String): Builder { var show: RatingShow? = shows.firstOrNull { it.ids.trakt == showTraktId } if (show == null) { show = RatingShow(TraktId(showTraktId)) shows.add(show) } val ratingSeason = show.seasons.firstOrNull { it.number == season } if (ratingSeason?.rating != null) { throw IllegalArgumentException("Season $showTraktId-$season already rated in this request") } show.seasons.add(RatingSeason(season, rating, ratedAt)) return this } fun episode( showTraktId: Long, season: Int, episode: Int, rating: Int, ratedAt: String ): Builder { var show: RatingShow? = shows.firstOrNull { it.ids.trakt == showTraktId } if (show == null) { show = RatingShow(TraktId(showTraktId)) shows.add(show) } var ratingSeason = show.seasons.firstOrNull { it.number == season } if (ratingSeason == null) { ratingSeason = RatingSeason(season) show.seasons.add(ratingSeason) } val ratingEpisode = ratingSeason.episodes.firstOrNull { it.number == episode } if (ratingEpisode == null) { ratingSeason.episodes.add(RatingEpisode(episode, rating, ratedAt)) } else { throw IllegalArgumentException("Episode $showTraktId-$season-$episode already rated in this request") } return this } fun build(): RateItems { return RateItems(movies, shows) } } } class RatingMovie internal constructor(val ids: TraktId, val rating: Int, val rated_at: String) class RatingShow internal constructor( val ids: TraktId, val rating: Int? = null, val rated_at: String? = null, val seasons: MutableList<RatingSeason> = mutableListOf() ) class RatingSeason( val number: Int, val rating: Int? = null, val rated_at: String? = null, val episodes: MutableList<RatingEpisode> = mutableListOf() ) class RatingEpisode(val number: Int, val rating: Int, val rated_at: String)
apache-2.0
8b286b9835ac82ba2a3ed0b0af5c288f
31.267857
109
0.669341
4.246769
false
false
false
false
i7c/cfm
server/recorder/src/main/kotlin/org/rliz/cfm/recorder/playback/data/RawPlaybackData.kt
1
1548
package org.rliz.cfm.recorder.playback.data import org.hibernate.annotations.Fetch import org.hibernate.annotations.FetchMode import javax.persistence.Column import javax.persistence.ElementCollection import javax.persistence.Entity import javax.persistence.FetchType import javax.persistence.GeneratedValue import javax.persistence.Id import javax.validation.constraints.NotNull import javax.validation.constraints.Size @Entity class RawPlaybackData { @Id @GeneratedValue var oid: Long? = null @NotNull @ElementCollection(fetch = FetchType.LAZY) @Size(min = 1) @Fetch(FetchMode.SUBSELECT) var artists: List<String>? = null @NotNull @Size(min = 1, max = 1024) @Column(length = 1024) var artistJson: String? = null @NotNull @Size(min = 1) var recordingTitle: String? = null @NotNull @Size(min = 1) var releaseTitle: String? = null var length: Long? = null var discNumber: Int? = null var trackNumber: Int? = null constructor() constructor( artists: List<String>?, artistJson: String?, recordingTitle: String?, releaseTitle: String?, length: Long? = null, discNumber: Int? = null, trackNumber: Int? = null ) : this() { this.artists = artists this.artistJson = artistJson this.recordingTitle = recordingTitle this.releaseTitle = releaseTitle this.length = length this.discNumber = discNumber this.trackNumber = trackNumber } }
gpl-3.0
f5deee2aaadfe6cb5891585bef15107c
22.815385
46
0.670543
4.229508
false
false
false
false
njasm/KotWave
src/main/kotlin/com/github/njasm/kotwave/Auth.kt
1
1294
/** * Created by njasm on 02/07/2017. */ package com.github.njasm.kotwave import com.github.kittinunf.fuel.core.Request import java.util.* internal class Auth(internal var token: Token) { internal var dataDate: Calendar = Calendar.getInstance() val accessToken get() = this.token.access_token val tokenScope get() = this.token.scope val refreshToken get() = this.token.refresh_token fun addOauthHeader(req: Request) { if (tokenIsNotEmpty() && !req.headers.containsKey("Authorization") && !isTokenExpired() ) { req.header("Authorization" to "OAuth " + this.accessToken.trim()) } } fun isTokenExpired(): Boolean { when (this.getExpiresIn()) { null -> return false else -> { dataDate.add(Calendar.SECOND, getExpiresIn()!!) return dataDate.compareTo(Calendar.getInstance()) <= 0 } } } private fun getExpiresIn(): Int? = this.token.expires_in private fun tokenIsNotEmpty(): Boolean = this.accessToken.isNotEmpty() } internal data class Token( val access_token: String = "", val scope: String = "", val expires_in: Int? = null, val refresh_token: String? = null )
mit
a8d33e6ec254223bd1c504b8a4cff5b7
24.88
77
0.601236
4.147436
false
false
false
false
FHannes/intellij-community
plugins/settings-repository/testSrc/GitTestCase.kt
17
4152
package org.jetbrains.settingsRepository.test import com.intellij.openapi.vcs.merge.MergeSession import com.intellij.testFramework.ProjectRule import org.eclipse.jgit.api.Git import org.eclipse.jgit.lib.Repository import org.jetbrains.settingsRepository.CannotResolveConflictInTestMode import org.jetbrains.settingsRepository.SyncType import org.jetbrains.settingsRepository.conflictResolver import org.jetbrains.settingsRepository.git.GitRepositoryManager import org.jetbrains.settingsRepository.git.commit import org.jetbrains.settingsRepository.git.resetHard import org.junit.ClassRule import java.nio.file.FileSystem import java.util.* import kotlin.properties.Delegates internal abstract class GitTestCase : IcsTestCase() { companion object { @JvmField @ClassRule val projectRule = ProjectRule() } protected val repositoryManager: GitRepositoryManager get() = icsManager.repositoryManager as GitRepositoryManager protected val repository: Repository get() = repositoryManager.repository protected var remoteRepository: Repository by Delegates.notNull() init { conflictResolver = { files, mergeProvider -> val mergeSession = mergeProvider.createMergeSession(files) for (file in files) { val mergeData = mergeProvider.loadRevisions(file) if (Arrays.equals(mergeData.CURRENT, MARKER_ACCEPT_MY) || Arrays.equals(mergeData.LAST, MARKER_ACCEPT_THEIRS)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedYours) } else if (Arrays.equals(mergeData.CURRENT, MARKER_ACCEPT_THEIRS) || Arrays.equals(mergeData.LAST, MARKER_ACCEPT_MY)) { mergeSession.conflictResolvedForFile(file, MergeSession.Resolution.AcceptedTheirs) } else if (Arrays.equals(mergeData.LAST, MARKER_ACCEPT_MY)) { file.setBinaryContent(mergeData.LAST) mergeProvider.conflictResolvedForFile(file) } else { throw CannotResolveConflictInTestMode() } } } } class FileInfo(val name: String, val data: ByteArray) protected fun addAndCommit(path: String): FileInfo { val data = """<file path="$path" />""".toByteArray() provider.write(path, data) repositoryManager.commit() return FileInfo(path, data) } protected fun createRemoteRepository(branchName: String? = null, initialCommit: Boolean = false) { val repository = tempDirManager.createRepository("upstream") if (initialCommit) { repository .add(SAMPLE_FILE_NAME, SAMPLE_FILE_CONTENT) .commit("") } if (branchName != null) { if (!initialCommit) { // jgit cannot checkout&create branch if no HEAD (no commits in our empty repository), so we create initial empty commit repository.commit("") } Git(repository).checkout().setCreateBranch(true).setName(branchName).call() } remoteRepository = repository } protected fun restoreRemoteAfterPush() { /** we must not push to non-bare repository - but we do it in test (our sync merge equals to "pull&push"), " By default, updating the current branch in a non-bare repository is denied, because it will make the index and work tree inconsistent with what you pushed, and will require 'git reset --hard' to match the work tree to HEAD. " so, we do "git reset --hard" */ remoteRepository.resetHard() } protected fun sync(syncType: SyncType) { icsManager.sync(syncType) } protected fun createLocalAndRemoteRepositories(remoteBranchName: String? = null, initialCommit: Boolean = false) { createRemoteRepository(remoteBranchName, true) configureLocalRepository(remoteBranchName) if (initialCommit) { addAndCommit("local.xml") } } protected fun configureLocalRepository(remoteBranchName: String? = null) { repositoryManager.setUpstream(remoteRepository.workTree.absolutePath, remoteBranchName) } protected fun FileSystem.compare(): FileSystem { val root = getPath("/")!! compareFiles(root, repository.workTreePath) compareFiles(root, remoteRepository.workTreePath) return this } }
apache-2.0
9e6646273d6277006565b9df6a793955
35.113043
128
0.729528
4.844807
false
true
false
false
QuickBlox/quickblox-android-sdk
sample-conference-kotlin/app/src/main/java/com/quickblox/sample/conference/kotlin/presentation/screens/main/MainViewModel.kt
1
11209
package com.quickblox.sample.conference.kotlin.presentation.screens.main import android.os.Bundle import com.quickblox.chat.model.QBChatDialog import com.quickblox.sample.conference.kotlin.R import com.quickblox.sample.conference.kotlin.domain.DomainCallback import com.quickblox.sample.conference.kotlin.domain.chat.ChatManager import com.quickblox.sample.conference.kotlin.domain.chat.ConnectionChatListener import com.quickblox.sample.conference.kotlin.domain.chat.DialogListener import com.quickblox.sample.conference.kotlin.domain.push.PushManager import com.quickblox.sample.conference.kotlin.domain.repositories.connection.ConnectionRepository import com.quickblox.sample.conference.kotlin.domain.repositories.connection.ConnectivityChangedListener import com.quickblox.sample.conference.kotlin.domain.user.UserManager import com.quickblox.sample.conference.kotlin.presentation.LiveData import com.quickblox.sample.conference.kotlin.presentation.resources.ResourcesManager import com.quickblox.sample.conference.kotlin.presentation.screens.base.BaseViewModel import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.ERROR import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.LIST_DIALOGS_UPDATED import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.MOVE_TO_FIRST_DIALOG import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.PROGRESS import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_CHAT_SCREEN import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_CREATE_SCREEN import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_DIALOGS import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.SHOW_LOGIN_SCREEN import com.quickblox.sample.conference.kotlin.presentation.screens.main.ViewState.Companion.USER_ERROR import com.quickblox.users.model.QBUser import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject const val DIALOGS_LIMIT = 100 const val EXTRA_TOTAL_ENTRIES = "total_entries" const val EXTRA_SKIP = "skip" /* * Created by Injoit in 2021-09-30. * Copyright © 2021 Quickblox. All rights reserved. */ @HiltViewModel class MainViewModel @Inject constructor(private val userManager: UserManager, private val chatManager: ChatManager, private val resourcesManager: ResourcesManager, private val pushManager: PushManager, private val connectionRepository: ConnectionRepository) : BaseViewModel() { private val TAG: String = MainViewModel::class.java.simpleName private var selectedDialogId: String? = null private val connectionListener = ConnectionListener(TAG) private val dialogListener = DialogListenerImpl(TAG) val liveData = LiveData<Pair<Int, Any?>>() var user: QBUser? = null private set private val connectivityChangedListener = ConnectivityChangedListenerImpl(TAG) init { user = userManager.getCurrentUser() } fun getDialogs(): ArrayList<QBChatDialog> { return chatManager.getDialogs() } private fun loginToChat(user: QBUser?) { if (user == null) { liveData.setValue(Pair(USER_ERROR, null)) } else { chatManager.loginToChat(user, object : DomainCallback<Unit, Exception> { override fun onSuccess(result: Unit, bundle: Bundle?) { subscribeChatListener() loadDialogs(refresh = true, reJoin = true) } override fun onError(error: Exception) { liveData.setValue(Pair(ERROR, error.message)) } }) } } fun singOut() { if (!connectionRepository.isInternetAvailable()) { liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.no_internet))) return } liveData.setValue(Pair(PROGRESS, null)) if (pushManager.isSubscribed()) { pushManager.unSubscribe { userManager.signOut(object : DomainCallback<Unit?, Exception> { override fun onSuccess(result: Unit?, bundle: Bundle?) { chatManager.clearDialogs() chatManager.unsubscribeDialogListener(dialogListener) chatManager.unSubscribeConnectionChatListener(connectionListener) chatManager.destroyChat() liveData.setValue(Pair(SHOW_LOGIN_SCREEN, null)) } override fun onError(error: Exception) { liveData.setValue(Pair(ERROR, error.message)) } }) } } else { userManager.signOut(object : DomainCallback<Unit?, Exception> { override fun onSuccess(result: Unit?, bundle: Bundle?) { chatManager.clearDialogs() chatManager.unsubscribeDialogListener(dialogListener) chatManager.unSubscribeConnectionChatListener(connectionListener) chatManager.destroyChat() liveData.setValue(Pair(SHOW_LOGIN_SCREEN, null)) } override fun onError(error: Exception) { liveData.setValue(Pair(ERROR, error.message)) } }) } } fun loadDialogs(refresh: Boolean, reJoin: Boolean) { liveData.setValue(Pair(PROGRESS, null)) chatManager.loadDialogs(refresh, reJoin, object : DomainCallback<ArrayList<QBChatDialog>, Exception> { override fun onSuccess(result: ArrayList<QBChatDialog>, bundle: Bundle?) { liveData.setValue(Pair(SHOW_DIALOGS, chatManager.getDialogs())) } override fun onError(error: Exception) { liveData.setValue(Pair(ERROR, error.message)) } }) } fun deleteDialogs(dialogs: ArrayList<QBChatDialog>) { liveData.setValue(Pair(PROGRESS, null)) user?.let { chatManager.deleteDialogs(dialogs, it, object : DomainCallback<List<QBChatDialog>, Exception> { override fun onSuccess(notDeletedDialogs: List<QBChatDialog>, bundle: Bundle?) { if (notDeletedDialogs.isNotEmpty()) { liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.not_deleted_dialogs, notDeletedDialogs.size))) return } liveData.setValue(Pair(LIST_DIALOGS_UPDATED, null)) } override fun onError(error: Exception) { // Empty } }) } } private fun subscribeChatListener() { chatManager.subscribeDialogListener(dialogListener) chatManager.subscribeConnectionChatListener(connectionListener) } override fun onResumeView() { connectionRepository.addListener(connectivityChangedListener) if (chatManager.isLoggedInChat()) { subscribeChatListener() loadDialogs(refresh = true, reJoin = true) } else { loginToChat(user) } } override fun onStopView() { connectionRepository.removeListener(connectivityChangedListener) chatManager.unsubscribeDialogListener(dialogListener) chatManager.unSubscribeConnectionChatListener(connectionListener) } override fun onStopApp() { chatManager.destroyChat() } fun onDialogClicked(dialog: QBChatDialog) { if (!connectionRepository.isInternetAvailable()) { liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.no_internet))) return } selectedDialogId = dialog.dialogId liveData.setValue(Pair(SHOW_CHAT_SCREEN, dialog)) } fun showCreateScreen() { if (!connectionRepository.isInternetAvailable()) { liveData.setValue(Pair(ERROR, Exception(resourcesManager.get().getString(R.string.no_internet)))) return } liveData.setValue(Pair(SHOW_CREATE_SCREEN, null)) } private inner class ConnectionListener(val tag: String) : ConnectionChatListener { override fun onConnectedChat() { liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.connected))) } override fun onError(exception: Exception) { liveData.setValue(Pair(ERROR, exception.message)) } override fun reconnectionFailed(exception: Exception) { liveData.setValue(Pair(ERROR, exception.message)) loginToChat(user) } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is ConnectionListener) { return false } return tag == other.tag } override fun hashCode(): Int { var hash = 1 hash = 31 * hash + tag.hashCode() return hash } } private inner class DialogListenerImpl(val tag: String) : DialogListener { override fun onUpdatedDialog(dialog: QBChatDialog) { if (chatManager.getDialogs().isEmpty()) { loadDialogs(refresh = true, reJoin = false) } else { liveData.setValue(Pair(MOVE_TO_FIRST_DIALOG, dialog)) } } override fun onError(exception: Exception) { liveData.setValue(Pair(ERROR, exception.message)) } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is DialogListenerImpl) { return false } return tag == other.tag } override fun hashCode(): Int { var hash = 1 hash = 31 * hash + tag.hashCode() return hash } } private inner class ConnectivityChangedListenerImpl(val tag: String) : ConnectivityChangedListener { override fun onAvailable() { if (!chatManager.isLoggedInChat()) { liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.internet_restored))) loginToChat(user) } } override fun onLost() { liveData.setValue(Pair(ERROR, resourcesManager.get().getString(R.string.no_internet))) } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is ConnectivityChangedListenerImpl) { return false } return tag == other.tag } override fun hashCode(): Int { var hash = 1 hash = 31 * hash + tag.hashCode() return hash } } }
bsd-3-clause
db2c73d93c62928163bdce7b57b5b235
39.032143
142
0.634904
5.169742
false
false
false
false
AoEiuV020/PaNovel
reader/src/main/java/cc/aoeiuv020/reader/simple/SimpleReader.kt
1
3596
package cc.aoeiuv020.reader.simple import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import cc.aoeiuv020.reader.* import kotlinx.android.synthetic.main.simple.view.* /** * * Created by AoEiuV020 on 2017.12.01-02:14:20. */ internal class SimpleReader(override var ctx: Context, novel: String, private val parent: ViewGroup, requester: TextRequester, override var config: ReaderConfig) : BaseNovelReader(novel, requester), ConfigChangedListener { private val layoutInflater = LayoutInflater.from(ctx) private val contentView: View = layoutInflater.inflate(R.layout.simple, parent, true) private val viewPager: androidx.viewpager.widget.ViewPager = contentView.viewPager private val background: ImageView = contentView.ivBackground private val dtfRoot: DispatchTouchFrameLayout = contentView.dtfRoot private val ntpAdapter: NovelTextPagerAdapter override var chapterList: List<String> get() = super.chapterList set(value) { super.chapterList = value ntpAdapter.notifyDataSetChanged() } override var textProgress: Int get() = ntpAdapter.getCurrentTextProgress() ?: 0 set(value) { ntpAdapter.setCurrentTextProgress(value) } override val maxTextProgress: Int get() = ntpAdapter.getCurrentTextCount() ?: 0 override var currentChapter: Int get() = viewPager.currentItem set(value) { viewPager.currentItem = value } init { config.listeners.add(this) viewPager.addOnPageChangeListener(object : androidx.viewpager.widget.ViewPager.OnPageChangeListener { override fun onPageScrollStateChanged(state: Int) { menuListener?.hide() } override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { if (position != currentChapter) { currentChapter = position readingListener?.onReading(position, 0) } } }) dtfRoot.reader = this ntpAdapter = NovelTextPagerAdapter(this) viewPager.adapter = ntpAdapter background.setBackgroundColor(config.backgroundColor) background.setImageURI(config.backgroundImage) } override fun destroy() { // 清空viewPager,自动调用destroyItem切断presenter, viewPager.adapter = null parent.removeView(contentView) } override fun refreshCurrentChapter() { ntpAdapter.refreshCurrentChapter() } override fun onConfigChanged(name: ReaderConfigName) { when (name) { ReaderConfigName.TextSize -> ntpAdapter.notifyAllItemDataSetChanged() ReaderConfigName.Font -> ntpAdapter.notifyAllItemDataSetChanged() ReaderConfigName.TextColor -> ntpAdapter.notifyAllItemDataSetChanged() ReaderConfigName.LineSpacing -> ntpAdapter.notifyAllItemDataSetChanged() ReaderConfigName.ParagraphSpacing -> ntpAdapter.notifyAllItemDataSetChanged() ReaderConfigName.ContentMargins -> ntpAdapter.notifyAllItemContentSpacingChanged() ReaderConfigName.BackgroundColor -> background.setBackgroundColor(config.backgroundColor) ReaderConfigName.BackgroundImage -> background.setImageURI(config.backgroundImage) else -> { } } } }
gpl-3.0
7d44ce22334b71eb4fcf053d750d0b8f
38.318681
161
0.683622
5.445967
false
true
false
false
didi/DoraemonKit
Android/dokit/src/main/java/com/didichuxing/doraemonkit/widget/brvah/animation/AlphaInAnimation.kt
1
728
package com.didichuxing.doraemonkit.widget.brvah.animation import android.animation.Animator import android.animation.ObjectAnimator import android.view.View import android.view.animation.LinearInterpolator /** * https://github.com/CymChad/BaseRecyclerViewAdapterHelper */ class AlphaInAnimation @JvmOverloads constructor(private val mFrom: Float = DEFAULT_ALPHA_FROM) : BaseAnimation { override fun animators(view: View): Array<Animator> { val animator = ObjectAnimator.ofFloat(view, "alpha", mFrom, 1f) animator.duration = 300L animator.interpolator = LinearInterpolator() return arrayOf(animator) } companion object { private const val DEFAULT_ALPHA_FROM = 0f } }
apache-2.0
9af8a1990ea004425f1f777ae523add2
30.695652
113
0.744505
4.439024
false
false
false
false
nemerosa/ontrack
ontrack-kdsl-acceptance/src/test/java/net/nemerosa/ontrack/kdsl/acceptance/tests/github/system/GitHubTestRepository.kt
1
10116
package net.nemerosa.ontrack.kdsl.acceptance.tests.github.system import com.fasterxml.jackson.annotation.JsonIgnoreProperties import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.json.parse import net.nemerosa.ontrack.kdsl.acceptance.tests.ACCProperties import net.nemerosa.ontrack.kdsl.acceptance.tests.github.gitHubClient import net.nemerosa.ontrack.kdsl.acceptance.tests.support.uid import net.nemerosa.ontrack.kdsl.acceptance.tests.support.waitUntil import net.nemerosa.ontrack.kdsl.spec.Branch import net.nemerosa.ontrack.kdsl.spec.Ontrack import net.nemerosa.ontrack.kdsl.spec.Project import net.nemerosa.ontrack.kdsl.spec.extension.git.GitBranchConfigurationProperty import net.nemerosa.ontrack.kdsl.spec.extension.git.gitBranchConfigurationProperty import net.nemerosa.ontrack.kdsl.spec.extension.github.GitHubConfiguration import net.nemerosa.ontrack.kdsl.spec.extension.github.GitHubProjectConfigurationProperty import net.nemerosa.ontrack.kdsl.spec.extension.github.gitHub import net.nemerosa.ontrack.kdsl.spec.extension.github.gitHubConfigurationProperty import org.apache.commons.codec.binary.Base64 import org.springframework.web.client.HttpClientErrorException import org.springframework.web.client.HttpClientErrorException.NotFound import org.springframework.web.client.RestClientException import java.util.* import kotlin.test.assertTrue import kotlin.test.fail fun withTestGitHubRepository( autoMerge: Boolean = false, code: GitHubRepositoryContext.() -> Unit, ) { // Unique name for the repository val uuid = UUID.randomUUID().toString() val repo = "ontrack-auto-versioning-test-$uuid" // Creates the repository gitHubClient.postForObject( "/orgs/${ACCProperties.GitHub.organization}/repos", mapOf( "name" to repo, "description" to "Test repository for auto versioning - can be deleted at any time", "private" to false, "has_issues" to false, "has_projects" to false, "has_wiki" to false ), Unit::class.java ) try { // Context val context = GitHubRepositoryContext(repo) // Running the code context.code() } finally { // Deleting the repository try { gitHubClient.delete("/repos/${ACCProperties.GitHub.organization}/$repo") } catch (ignored: RestClientException) { // Ignoring errors at deletion } } } class GitHubRepositoryContext( val repository: String, ) { fun repositoryFile( path: String, branch: String = "main", content: () -> String, ) { createBranchIfNotExisting(branch) val existingFile = getRawFile(path, branch) val body = mutableMapOf( "message" to "Creating $path", "content" to Base64.encodeBase64String(content().toByteArray()), "branch" to branch, ) if (existingFile != null) { body["sha"] = existingFile.sha } waitUntil(task = "Setting file content on branch $branch at path $path") { try { gitHubClient.put( "/repos/${ACCProperties.GitHub.organization}/${repository}/contents/$path", body ) // Assuming it's OK true } catch (_: NotFound) { // We need to retry false } } } private fun createBranchIfNotExisting(branch: String, base: String = "main") { if (branch != base) { // Checks if the branch exists val gitHubBranch = getBranch(branch) if (gitHubBranch == null) { // Gets the last commit of the base branch val baseBranch = getBranch(base) ?: throw IllegalStateException("Cannot find base branch $base") val baseCommit = baseBranch.commit.sha // Creates the branch gitHubClient.postForObject( "/repos/${ACCProperties.GitHub.organization}/${repository}/git/refs", mapOf( "ref" to "refs/heads/$branch", "sha" to baseCommit ), JsonNode::class.java ) } } } fun createGitHubConfiguration(ontrack: Ontrack): String { val name = uid("gh") ontrack.gitHub.createConfig( GitHubConfiguration( name = name, url = "https://github.com", oauth2Token = ACCProperties.GitHub.token, autoMergeToken = ACCProperties.GitHub.autoMergeToken, ) ) return name } fun Project.configuredForGitHub(ontrack: Ontrack): String { val config = createGitHubConfiguration(ontrack) gitHubConfigurationProperty = GitHubProjectConfigurationProperty( configuration = config, repository = "${ACCProperties.GitHub.organization}/$repository", ) return config } fun Branch.configuredForGitHubRepository( ontrack: Ontrack, scmBranch: String = "main", ): String { val configName = project.configuredForGitHub(ontrack) gitBranchConfigurationProperty = GitBranchConfigurationProperty(branch = scmBranch) return configName } fun assertThatGitHubRepository( code: AssertionContext.() -> Unit, ) { val context = AssertionContext() context.code() } private fun getPR(from: String?, to: String?): GitHubPR? { var url = "/repos/${ACCProperties.GitHub.organization}/$repository/pulls?state=all" if (from != null) { url += "&head=$from" } if (to != null) { url += "&base=$to" } return gitHubClient.getForObject( url, JsonNode::class.java )?.firstOrNull()?.parse() } private fun getPRReviews(pr: GitHubPR): List<GitHubPRReview> = gitHubClient.getForObject( "/repos/${ACCProperties.GitHub.organization}/$repository/pulls/${pr.number}/reviews", JsonNode::class.java )?.map { it.parse<GitHubPRReview>() } ?: emptyList() private fun getFile(path: String, branch: String): List<String> = getRawFile(path, branch)?.content?.run { String(Base64.decodeBase64(this)) }?.lines() ?.filter { it.isNotBlank() } ?: emptyList() private fun getRawFile(path: String, branch: String): GitHubContentsResponse? = try { gitHubClient.getForObject( "/repos/${ACCProperties.GitHub.organization}/$repository/contents/$path?ref=$branch", GitHubContentsResponse::class.java ) } catch (ex: NotFound) { null } private fun getBranch(branch: String) = try { gitHubClient.getForObject( "/repos/${ACCProperties.GitHub.organization}/$repository/branches/$branch", GitHubBranch::class.java ) } catch (ex: HttpClientErrorException.NotFound) { null } inner class AssertionContext { fun hasNoBranch(branch: String) { val gitHubBranch = getBranch(branch) if (gitHubBranch != null) { fail("Branch $branch exists when it was expected not to.") } } private fun checkPR(from: String?, to: String?, checkPR: (GitHubPR?) -> Boolean): GitHubPR? { var pr: GitHubPR? = null waitUntil( task = "Checking the PR from $from to $to", timeout = 120_000L, interval = 20_000L, ) { pr = getPR(from, to) checkPR(pr) } return pr } fun hasPR(from: String, to: String): GitHubPR = checkPR(from = from, to = to) { it != null } ?: error("PR cannot be null after the check") fun hasNoPR(to: String) { checkPR(from = null, to = to) { it == null } } fun checkPRIsNotApproved(pr: GitHubPR) { val reviews = getPRReviews(pr) assertTrue( reviews.none { it.state == "APPROVED" }, "No review was approved" ) } fun fileContains( path: String, branch: String = "main", timeout: Long = 60_000L, content: () -> String, ) { val expectedContent = content() var actualContent: String? waitUntil( timeout = timeout, task = "Waiting for file $path on branch $branch to have a given content.", onTimeout = { actualContent = getFile(path, branch).joinToString("\n") fail( """ Expected the following content for the $path file on the $branch branch: $expectedContent but got: $actualContent """.trimIndent() ) } ) { actualContent = getFile(path, branch).joinToString("\n") actualContent?.contains(expectedContent) ?: false } } } } @JsonIgnoreProperties(ignoreUnknown = true) class GitHubPR( val number: Int, val state: String, ) @JsonIgnoreProperties(ignoreUnknown = true) class GitHubPRReview( val user: GitHubUser, val state: String, ) @JsonIgnoreProperties(ignoreUnknown = true) private class GitHubContentsResponse( val content: String, val sha: String, ) @JsonIgnoreProperties(ignoreUnknown = true) class GitHubBranch( val name: String, val commit: GitHubCommit, ) @JsonIgnoreProperties(ignoreUnknown = true) class GitHubCommit( val sha: String, ) @JsonIgnoreProperties(ignoreUnknown = true) class GitHubUser( val login: String, )
mit
13c17864021a393fcbd176a552a7249f
30.514019
112
0.588968
4.856457
false
true
false
false
nemerosa/ontrack
ontrack-ui-graphql/src/main/java/net/nemerosa/ontrack/graphql/support/GQLArgumentUtils.kt
1
1678
package net.nemerosa.ontrack.graphql.support import graphql.Scalars.GraphQLInt import graphql.Scalars.GraphQLString import graphql.schema.DataFetchingEnvironment import graphql.schema.GraphQLArgument import java.util.* /** * Creates a `String` GraphQL argument. * * @param name Name of the argument * @param description Description of the argument */ fun stringArgument( name: String, description: String ): GraphQLArgument = GraphQLArgument.newArgument() .name(name) .description(description) .type(GraphQLString) .build() /** * Creates a `Int` GraphQL argument. * * @param name Name of the argument * @param description Description of the argument */ fun intArgument( name: String, description: String, nullable: Boolean = true, ): GraphQLArgument = GraphQLArgument.newArgument() .name(name) .description(description) .type(nullableInputType(GraphQLInt, nullable)) .build() /** * Creates a date/time GraphQL argument. * * @param name Name of the argument * @param description Description of the argument */ fun dateTimeArgument( name: String, description: String ): GraphQLArgument = GraphQLArgument.newArgument() .name(name) .description(description) .type(GQLScalarLocalDateTime.INSTANCE) .build() /** * Checks list of arguments */ fun checkArgList(environment: DataFetchingEnvironment, vararg args: String) { val actualArgs: Set<String> = environment.arguments.filterValues { it != null }.keys val expectedArgs: Set<String> = args.toSet() check(actualArgs == expectedArgs) { "Expected this list of arguments: $expectedArgs, but was: $actualArgs" } }
mit
5a429aae842bd3f36193816c03c8b2a6
24.815385
88
0.720501
4.237374
false
false
false
false
rsiebert/TVHClient
data/src/main/java/org/tvheadend/data/entity/Connection.kt
1
3023
package org.tvheadend.data.entity import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey data class Connection( var id: Int = 0, var name: String? = "", var hostname: String? = "", var port: Int = 9982, var username: String? = "*", var password: String? = "*", var isActive: Boolean = false, var streamingPort: Int = 9981, var isWolEnabled: Boolean = false, var wolMacAddress: String? = "", var wolPort: Int = 9, var isWolUseBroadcast: Boolean = false, var lastUpdate: Long = 0, var isSyncRequired: Boolean = true, var serverUrl: String? = "", var streamingUrl: String? = "" ) @Entity(tableName = "connections", indices = [Index(value = ["id"], unique = true)]) internal data class ConnectionEntity( @PrimaryKey(autoGenerate = true) var id: Int = 0, var name: String? = "", var hostname: String? = "", var port: Int = 9982, var username: String? = "", var password: String? = "", @ColumnInfo(name = "active") var isActive: Boolean = false, @ColumnInfo(name = "streaming_port") var streamingPort: Int = 9981, @ColumnInfo(name = "wol_enabled") var isWolEnabled: Boolean = false, @ColumnInfo(name = "wol_hostname") var wolMacAddress: String? = "", @ColumnInfo(name = "wol_port") var wolPort: Int = 9, @ColumnInfo(name = "wol_use_broadcast") var isWolUseBroadcast: Boolean = false, @ColumnInfo(name = "last_update") var lastUpdate: Long = 0, @ColumnInfo(name = "sync_required") var isSyncRequired: Boolean = true, @ColumnInfo(name = "server_url") var serverUrl: String? = "", @ColumnInfo(name = "streaming_url") var streamingUrl: String? = "" ) { companion object { fun from(connection: Connection): ConnectionEntity { return ConnectionEntity( connection.id, connection.name, connection.hostname, connection.port, connection.username, connection.password, connection.isActive, connection.streamingPort, connection.isWolEnabled, connection.wolMacAddress, connection.wolPort, connection.isWolUseBroadcast, connection.lastUpdate, connection.isSyncRequired, connection.serverUrl, connection.streamingUrl) } } fun toConnection(): Connection { return Connection(id, name, hostname, port, username, password, isActive, streamingPort, isWolEnabled, wolMacAddress, wolPort, isWolUseBroadcast, lastUpdate, isSyncRequired, serverUrl, streamingUrl) } }
gpl-3.0
cfc58adf10e987ea60d986d6472a0c85
34.988095
206
0.567317
4.7014
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/designer/psi/tset/TsetFile.kt
1
1800
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.designer.psi.tset import com.intellij.extapi.psi.PsiFileBase import com.intellij.lang.Language import com.intellij.openapi.fileTypes.FileType import com.intellij.psi.FileViewProvider /** * Created by thoma on 12/07/2016. */ class TsetFile : PsiFileBase { companion object Data { var fileProvider: FileViewProvider? = null var fileLanguage: Language? = null var fileTy: TsetFileType? = null } constructor(fileViewProvider: FileViewProvider, language: Language) : super(fileViewProvider, language) { fileProvider = fileViewProvider fileLanguage = language } override fun getFileType(): FileType { fileTy = TsetFileType() return fileTy as FileType } }
mit
ffc80878c0d913c829722b8a50334e68
35.02
106
0.787778
4.347826
false
false
false
false
06needhamt/Neuroph-Intellij-Plugin
neuroph-plugin/src/com/thomas/needham/neurophidea/actions/ShowExportNetworkFormAction.kt
1
2127
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.actions import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.thomas.needham.neurophidea.forms.export.ExportNetworkForm /** * Created by Thomas Needham on 28/05/2016. */ class ShowExportNetworkFormAction : AnAction() { var form: ExportNetworkForm? = null var itr: Long = 0L companion object ProjectInfo { var project: Project? = null var projectDirectory: String? = "" var isOpen: Boolean? = false } override fun actionPerformed(e: AnActionEvent) { InitialisationAction.project = e.project InitialisationAction.projectDirectory = InitialisationAction.project?.basePath InitialisationAction.isOpen = InitialisationAction.project?.isOpen form = ExportNetworkForm() } override fun update(e: AnActionEvent) { super.update(e) if (form != null) { form?.repaint(itr, 0, 0, form?.width!!, form?.height!!) itr++ } e.presentation.isEnabledAndVisible = true } }
mit
ed7825f8a0944d69fb4c1b7053bdd8fd
35.050847
80
0.779031
4.262525
false
false
false
false
xiaojinzi123/Component
ComponentImpl/src/main/java/com/xiaojinzi/component/impl/RouterRequest.kt
1
20343
package com.xiaojinzi.component.impl import android.app.Activity import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.text.TextUtils import androidx.annotation.Keep import androidx.annotation.UiContext import androidx.annotation.UiThread import androidx.fragment.app.Fragment import com.xiaojinzi.component.Component.requiredConfig import com.xiaojinzi.component.ComponentActivityStack import com.xiaojinzi.component.anno.support.CheckClassNameAnno import com.xiaojinzi.component.support.* import java.util.* interface IRouterRequestBuilder<T : IRouterRequestBuilder<T>> : IURIBuilder<T>, IBundleBuilder<T> { val options: Bundle? val intentFlags: List<Int> val intentCategories: List<String> val context: Context? val fragment: Fragment? /** * 是否是跳转拿 [com.xiaojinzi.component.bean.ActivityResult] 的 */ val isForResult: Boolean /** * 是否是为了目标 Intent */ val isForTargetIntent: Boolean val requestCode: Int? val intentConsumer: Consumer<Intent>? val beforeAction: (() -> Unit)? val beforeStartAction: (() -> Unit)? val afterStartAction: (() -> Unit)? val afterAction: (() -> Unit)? val afterErrorAction: (() -> Unit)? val afterEventAction: (() -> Unit)? fun context(context: Context?): T fun fragment(fragment: Fragment?): T fun isForResult(isForResult: Boolean): T fun isForTargetIntent(isForTargetIntent: Boolean): T fun requestCode(requestCode: Int?): T fun beforeAction(@UiThread action: Action?): T fun beforeAction(@UiThread action: (() -> Unit)?): T fun beforeStartAction(@UiThread action: Action?): T fun beforeStartAction(@UiThread action: (() -> Unit)?): T fun afterStartAction(@UiThread action: Action?): T fun afterStartAction(@UiThread action: (() -> Unit)?): T fun afterAction(@UiThread action: Action?): T fun afterAction(@UiThread action: (() -> Unit)?): T fun afterErrorAction(@UiThread action: Action?): T fun afterErrorAction(@UiThread action: (() -> Unit)?): T fun afterEventAction(@UiThread action: Action?): T fun afterEventAction(@UiThread action: (() -> Unit)?): T fun intentConsumer(@UiThread intentConsumer: Consumer<Intent>?): T fun addIntentFlags(vararg flags: Int): T fun addIntentCategories(vararg categories: String): T fun options(options: Bundle?): T fun build(): RouterRequest } class RouterRequestBuilderImpl<T : IRouterRequestBuilder<T>>( context: Context? = null, fragment: Fragment? = null, private val uriBuilder: IURIBuilder<T> = IURIBuilderImpl(), private val bundleBuilder: IBundleBuilder<T> = IBundleBuilderImpl(), private val targetDelegateImplCallable: DelegateImplCallable<T> = DelegateImplCallableImpl() ) : IRouterRequestBuilder<T>, IURIBuilder<T> by uriBuilder, IBundleBuilder<T> by bundleBuilder, DelegateImplCallable<T> by targetDelegateImplCallable { override var options: Bundle? = null /** * Intent 的 flag,允许修改的 */ override val intentFlags: MutableList<Int> = mutableListOf() /** * Intent 的 类别,允许修改的 */ override val intentCategories: MutableList<String> = mutableListOf() override var context: Context? = null override var fragment: Fragment? = null override var requestCode: Int? = null override var isForResult = false override var isForTargetIntent = false override var intentConsumer: Consumer<Intent>? = null /** * 路由开始之前 */ override var beforeAction: (() -> Unit)? = null /** * 执行 [Activity.startActivity] 之前 */ override var beforeStartAction: (() -> Unit)? = null /** * 执行 [Activity.startActivity] 之后 */ override var afterStartAction: (() -> Unit)? = null /** * 跳转成功之后的 Callback * 此时的跳转成功仅代表目标界面启动成功, 不代表跳转拿数据的回调被回调了 * 假如你是跳转拿数据的, 当你跳转到 A 界面, 此回调就会回调了, * 当你拿到 Intent 的回调了, 和此回调已经没关系了 */ override var afterAction: (() -> Unit)? = null /** * 跳转失败之后的 Callback */ override var afterErrorAction: (() -> Unit)? = null /** * 跳转成功和失败之后的 Callback */ override var afterEventAction: (() -> Unit)? = null override var delegateImplCallable: () -> T get() = targetDelegateImplCallable.delegateImplCallable set(value) { uriBuilder.delegateImplCallable = value bundleBuilder.delegateImplCallable = value targetDelegateImplCallable.delegateImplCallable = value } private fun getRealDelegateImpl(): T { return delegateImplCallable.invoke() } override fun context(context: Context?): T { this.context = context return getRealDelegateImpl() } override fun fragment(fragment: Fragment?): T { this.fragment = fragment return getRealDelegateImpl() } override fun isForResult(isForResult: Boolean): T { this.isForResult = isForResult return getRealDelegateImpl() } override fun isForTargetIntent(isForTargetIntent: Boolean): T { this.isForTargetIntent = isForTargetIntent return getRealDelegateImpl() } override fun requestCode(requestCode: Int?): T { this.requestCode = requestCode return getRealDelegateImpl() } override fun beforeAction(@UiThread action: Action?): T { return beforeAction(action = { action?.run() }) } override fun beforeAction(@UiThread action: (() -> Unit)?): T { beforeAction = action return getRealDelegateImpl() } override fun beforeStartAction(@UiThread action: Action?): T { return beforeStartAction(action = { action?.run() }) } override fun beforeStartAction(@UiThread action: (() -> Unit)?): T { beforeStartAction = action return getRealDelegateImpl() } override fun afterStartAction(@UiThread action: Action?): T { return afterStartAction(action = { action?.run() }) } override fun afterStartAction(@UiThread action: (() -> Unit)?): T { afterStartAction = action return getRealDelegateImpl() } override fun afterAction(@UiThread action: Action?): T { return afterAction(action = { action?.run() }) } override fun afterAction(@UiThread action: (() -> Unit)?): T { afterAction = action return getRealDelegateImpl() } override fun afterErrorAction(@UiThread action: Action?): T { return afterErrorAction(action = { action?.run() }) } override fun afterErrorAction(@UiThread action: (() -> Unit)?): T { afterErrorAction = action return getRealDelegateImpl() } override fun afterEventAction(@UiThread action: Action?): T { return afterEventAction(action = { action?.run() }) } override fun afterEventAction(@UiThread action: (() -> Unit)?): T { afterEventAction = action return getRealDelegateImpl() } /** * 当不是自定义跳转的时候, Intent 由框架生成,所以可以回调这个接口 * 当自定义跳转,这个回调不会回调的,这是需要注意的点 * * * 其实目标界面可以完全的自定义路由,这个功能实际上没有存在的必要,因为你可以为同一个界面添加上多个 [com.xiaojinzi.component.anno.RouterAnno] * 然后每一个 [com.xiaojinzi.component.anno.RouterAnno] 都可以有不同的行为.是可以完全的代替 [RouterRequest.intentConsumer] 方法的 * * @param intentConsumer Intent 是框架自动构建完成的,里面有跳转需要的所有参数和数据,这里就是给用户一个 * 更改的机会,最好别更改内部的参数等的信息,这里提供出来其实主要是可以让你调用Intent * 的 [Intent.addFlags] 等方法,并不是给你修改内部的 bundle 的 */ override fun intentConsumer(@UiThread intentConsumer: Consumer<Intent>?): T { this.intentConsumer = intentConsumer return getRealDelegateImpl() } override fun addIntentFlags(vararg flags: Int): T { intentFlags.addAll(flags.toList()) return getRealDelegateImpl() } override fun addIntentCategories(vararg categories: String): T { intentCategories.addAll(listOf(*categories)) return getRealDelegateImpl() } /** * 用于 API >= 16 的时候,调用 [Activity.startActivity] */ override fun options(options: Bundle?): T { this.options = options return getRealDelegateImpl() } /** * 构建请求对象,这个构建是必须的,不能错误的,如果出错了,直接崩溃掉,因为连最基本的信息都不全没法进行下一步的操作 * * @return 可能会抛出一个运行时异常, 由于您的参数在构建 uri 的时候出现的异常 */ override fun build(): RouterRequest { val builder = this return RouterRequest( context = builder.context, fragment = builder.fragment, uri = builder.buildURI(), requestCode = builder.requestCode, isForResult = builder.isForResult, isForTargetIntent = builder.isForTargetIntent, options = builder.options, intentFlags = Collections.unmodifiableList(builder.intentFlags), intentCategories = Collections.unmodifiableList(builder.intentCategories), bundle = Bundle().apply { this.putAll(builder.bundle) }, intentConsumer = builder.intentConsumer, beforeAction = builder.beforeAction, beforeStartAction = builder.beforeStartAction, afterStartAction = builder.afterStartAction, afterAction = builder.afterAction, afterErrorAction = builder.afterErrorAction, afterEventAction = builder.afterEventAction, ) } init { this.context = context this.fragment = fragment delegateImplCallable = targetDelegateImplCallable.delegateImplCallable } } /** * 构建一个路由请求对象 [RouterRequest] 对象的 Builder * * @author xiaojinzi */ class RouterRequestBuilder( private val routerRequestBuilder: IRouterRequestBuilder<RouterRequestBuilder> = RouterRequestBuilderImpl(), ) : IRouterRequestBuilder<RouterRequestBuilder> by routerRequestBuilder { init { delegateImplCallable = { this } } } /** * 表示路由的一个请求类,构建时候如果参数不对是有异常会发生的,使用的时候注意这一点 * 但是在拦截器 [RouterInterceptor] 中构建是不用关心错误的, * 因为拦截器的 [RouterInterceptor.intercept] 方法 * 允许抛出异常 * * * time : 2018/11/29 * * @author xiaojinzi */ @Keep @CheckClassNameAnno data class RouterRequest( val context: Context?, val fragment: Fragment?, /** * 这是一个很重要的参数, 一定不可以为空,如果这个为空了,一定不能继续下去,因为很多地方直接使用这个参数的,不做空判断的 * 而且这个参数不可以为空的 */ val uri: Uri, /** * 请求码 */ val requestCode: Int? = null, /** * 框架是否帮助用户跳转拿 [com.xiaojinzi.component.bean.ActivityResult] * 有 requestCode 只能说明用户使用了某一个 requestCode, * 会调用 [Activity.startActivityForResult]. * 但是不代表需要框架去帮你获取到 [com.xiaojinzi.component.bean.ActivityResult]. * 所以这个值就是标记是否需要框架帮助您去获取 [com.xiaojinzi.component.bean.ActivityResult] */ val isForResult: Boolean, /** * 是否是为了目标 Intent 来的 */ val isForTargetIntent: Boolean, /** * 跳转的时候 options 参数 */ val options: Bundle?, /** * Intent 的 flag, 集合不可更改 */ val intentFlags: List<Int>, /** * Intent 的 类别, 集合不可更改 */ val intentCategories: List<String>, /** * 携带的数据 */ val bundle: Bundle, /** * Intent 的回调, 可以让你做一些事情 */ val intentConsumer: Consumer<Intent>?, /** * 这个 [Action] 是在路由开始的时候调用的. * 和 [Activity.startActivity] 不是连着执行的. * 中间 post 到主线程的操作 */ val beforeAction: (() -> Unit)?, /** * 这个 [Action] 是在 [Activity.startActivity] 之前调用的. * 和 [Activity.startActivity] 是连着执行的. */ val beforeStartAction: (() -> Unit)?, /** * 这个 [Action] 是在 [Activity.startActivity] 之后调用的. * 和 [Activity.startActivity] 是连着执行的. */ val afterStartAction: (() -> Unit)?, /** * 这个 [Action] 是在结束之后调用的. * 和 [Activity.startActivity] 不是连着执行的. * 是在 [RouterInterceptor.Callback.onSuccess] * 方法中 post 到主线程完成的 */ val afterAction: (() -> Unit)?, /** * 这个 [Action] 是在结束之后调用的. * 和 [Activity.startActivity] 不是连着执行的. * 是在 [RouterInterceptor.Callback.onError] * 方法中 post 到主线程完成的 */ val afterErrorAction: (() -> Unit)?, /** * 这个 [Action] 是在结束之后调用的. * 和 [Activity.startActivity] 不是连着执行的. * 是在 [RouterInterceptor.Callback.onSuccess] 或者 * [RouterInterceptor.Callback.onError] * 方法中 post 到主线程完成的 */ val afterEventAction: (() -> Unit)?, ) // 占位 { companion object { const val KEY_SYNC_URI = "_componentSyncUri" } /** * 同步 Query 到 Bundle 中 */ fun syncUriToBundle() { // 如果 URI 没有变化就不同步了 if (bundle.getInt(KEY_SYNC_URI) == uri.hashCode()) { return } ParameterSupport.syncUriToBundle(uri = uri, bundle = bundle) // 更新新的 hashCode bundle.putInt(KEY_SYNC_URI, uri.hashCode()) } /** * 从 [Fragment] 和 [Context] 中获取上下文 * * * 参数中的 [RouterRequest.context] 可能是一个 [android.app.Application] 或者是一个 * [android.content.ContextWrapper] 或者是一个 [Activity] * 无论参数的类型是哪种, 此方法的返回值就只有两种类型: * 1. [android.app.Application] * 2. [Activity] * * * 如果返回的是 [Activity] 的 [Context], * 当 [Activity] 销毁了就会返回 null * 另外就是返回 [android.app.Application] * * @return [Context], 可能为 null, null 就只有一种情况就是界面销毁了. * 构建 [RouterRequest] 的时候已经保证了 */ val rawContext: Context? get() { var rawContext: Context? = null if (context != null) { rawContext = context } else if (fragment != null) { rawContext = fragment.context } val rawAct = Utils.getActivityFromContext(rawContext) // 如果不是 Activity 可能是 Application,所以直接返回 return if (rawAct == null) { rawContext } else { // 如果是 Activity 并且已经销毁了返回 null if (Utils.isActivityDestoryed(rawAct)) { null } else { rawContext } } } /** * 从 [Context] 中获取 [Activity], [Context] 可能是 [android.content.ContextWrapper] * * @return 如果 Activity 销毁了就会返回 null */ val activity: Activity? get() { if (context == null) { return null } val realActivity = Utils.getActivityFromContext(context) ?: return null return if (Utils.isActivityDestoryed(realActivity)) { null } else realActivity } /** * 从参数 [Fragment] 和 [Context] 获取 Activity, * * @return 如果 activity 已经销毁并且 fragment 销毁了就会返回 null */ val rawActivity: Activity? get() { var rawActivity = activity if (rawActivity == null) { if (fragment != null) { rawActivity = fragment.activity } } if (rawActivity == null) { return null } return if (Utils.isActivityDestoryed(rawActivity)) { null } else { // 如果不是为空返回的, 那么必定不是销毁的 rawActivity } } /** * 首先调用 [.getRawActivity] 尝试获取此次用户传入的 Context 中是否有关联的 Activity * 如果为空, 则尝试获取运行中的所有 Activity 中顶层的那个 */ val rawOrTopActivity: Activity? get() { var result = rawActivity if (result == null) { // 如果不是为空返回的, 那么必定不是销毁的 result = ComponentActivityStack.topAliveActivity } return result } /** * 这里转化的对象会比 [RouterRequestBuilder] 对象中的参数少一个 [RouterRequestBuilder.url] * 因为 uri 转化为了 scheme,host,path,queryMap 那么这时候就不需要 url 了 */ fun toBuilder(): RouterRequestBuilder { val builder = RouterRequestBuilder() // 有关界面的两个 builder.context(context = context) builder.fragment(fragment = fragment) // 还原一个 Uri 为各个零散的参数 builder.scheme(scheme = uri.scheme!!) builder.userInfo(userInfo = uri.userInfo) builder.host(host = uri.host) builder.path(path = uri.path) val queryParameterNames = uri.queryParameterNames if (queryParameterNames != null) { for (queryParameterName in queryParameterNames) { builder.query(queryName = queryParameterName, queryValue = uri.getQueryParameter(queryParameterName)!!) } } // 不能拆分每个参数, 因为可能 url 中可能没有 path 参数 // builder.url(url = uri.toString()) builder.bundle.putAll(bundle) builder.requestCode(requestCode = requestCode) builder.isForResult(isForResult = isForResult) builder.isForTargetIntent(isForTargetIntent = isForTargetIntent) builder.options(options = options) // 这里需要新创建一个是因为不可修改的集合不可以给别人 builder.addIntentCategories(*intentCategories.toTypedArray()) builder.addIntentFlags(*intentFlags.toIntArray()) builder.intentConsumer(intentConsumer = intentConsumer) builder.beforeAction(action = beforeAction) builder.beforeStartAction(action = beforeStartAction) builder.afterStartAction(action = afterStartAction) builder.afterAction(action = afterAction) builder.afterErrorAction(action = afterErrorAction) builder.afterEventAction(action = afterEventAction) return builder } }
apache-2.0
2cecbb2f4a7c7334a017894c39e8c9b9
29.215852
119
0.60451
4.544002
false
false
false
false
vondear/RxTools
RxFeature/src/main/java/com/tamsiree/rxfeature/activity/ActivityCodeTool.kt
1
4491
package com.tamsiree.rxfeature.activity import android.graphics.Color import android.os.Bundle import android.view.View import com.tamsiree.rxfeature.R import com.tamsiree.rxfeature.tool.RxBarCode import com.tamsiree.rxfeature.tool.RxQRCode import com.tamsiree.rxkit.* import com.tamsiree.rxkit.view.RxToast import com.tamsiree.rxui.activity.ActivityBase import com.tamsiree.rxui.view.ticker.RxTickerUtils import kotlinx.android.synthetic.main.activity_code_tool.* /** * @author tamsiree */ class ActivityCodeTool : ActivityBase() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) RxBarTool.noTitle(this) RxBarTool.setTransparentStatusBar(this) setContentView(R.layout.activity_code_tool) RxDeviceTool.setPortrait(this) } override fun onResume() { super.onResume() updateScanCodeCount() } override fun initView() { ticker_scan_count.setCharacterList(NUMBER_LIST) ticker_made_count.setCharacterList(NUMBER_LIST) updateMadeCodeCount() } override fun initData() { initEvent() } private fun updateScanCodeCount() { ticker_scan_count!!.setText(RxDataTool.stringToInt(RxSPTool.getContent(mContext.baseContext!!, RxConstants.SP_SCAN_CODE)).toString() + "", true) } private fun updateMadeCodeCount() { ticker_made_count.setText(RxDataTool.stringToInt(RxSPTool.getContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE)).toString() + "", true) } private fun initEvent() { rx_title.setLeftIconVisibility(true) rx_title.setTitleColor(Color.WHITE) rx_title.setTitleSize(RxImageTool.dp2px(20f)) rx_title.setLeftFinish(mContext) ticker_scan_count!!.animationDuration = 500 iv_create_qr_code.setOnClickListener { val str = et_qr_code.text.toString() if (RxDataTool.isNullString(str)) { RxToast.error("二维码文字内容不能为空!") } else { ll_code!!.visibility = View.VISIBLE //二维码生成方式一 推荐此方法 RxQRCode.builder(str).backColor(-0x1).codeColor(-0x1000000).codeSide(600).codeLogo(resources.getDrawable(R.drawable.faviconhandsome)).codeBorder(1).into(iv_qr_code) //二维码生成方式二 默认宽和高都为800 背景为白色 二维码为黑色 // RxQRCode.createQRCode(str,iv_qr_code); iv_qr_code!!.visibility = View.VISIBLE RxToast.success("二维码已生成!") RxSPTool.putContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE, (RxDataTool.stringToInt(RxSPTool.getContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE)) + 1).toString()) updateMadeCodeCount() nestedScrollView!!.computeScroll() } } iv_create_bar_code!!.setOnClickListener { val str1 = et_bar_code!!.text.toString() if (RxDataTool.isNullString(str1)) { RxToast.error("条形码文字内容不能为空!") } else { ll_bar_code!!.visibility = View.VISIBLE //条形码生成方式一 推荐此方法 RxBarCode.builder(str1).backColor(0x00000000).codeColor(-0x1000000).codeWidth(1000).codeHeight(300).into(iv_bar_code) //条形码生成方式二 默认宽为1000 高为300 背景为白色 二维码为黑色 //iv_bar_code.setImageBitmap(RxBarCode.createBarCode(str1, 1000, 300)); iv_bar_code!!.visibility = View.VISIBLE RxToast.success("条形码已生成!") RxSPTool.putContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE, (RxDataTool.stringToInt(RxSPTool.getContent(mContext.baseContext!!, RxConstants.SP_MADE_CODE)) + 1).toString()) updateMadeCodeCount() } } ll_scaner!!.setOnClickListener { RxActivityTool.skipActivity(mContext, ActivityScanerCode::class.java) } ll_qr!!.setOnClickListener { ll_qr_root!!.visibility = View.VISIBLE ll_bar_root!!.visibility = View.GONE } ll_bar!!.setOnClickListener { ll_bar_root!!.visibility = View.VISIBLE ll_qr_root!!.visibility = View.GONE } } companion object { private val NUMBER_LIST = RxTickerUtils.defaultNumberList } }
apache-2.0
a6e268bb74d9d3787f1aed30e6eba76a
38.5
197
0.646659
4.09309
false
false
false
false
dtarnawczyk/modernlrs
src/main/org/lrs/kmodernlrs/domain/ContextActivities.kt
1
347
package org.lrs.kmodernlrs.domain import java.io.Serializable data class ContextActivities( var parent: List<XapiObject>? = null, var grouping: List<XapiObject>? = null, var category: List<XapiObject>? = null, var other: List<XapiObject>? = null ) : Serializable { companion object { private val serialVersionUID:Long = 1 } }
apache-2.0
02d23efbcbd83733f23003da110e0e38
22.2
42
0.714697
3.652632
false
false
false
false
ffc-nectec/FFC
ffc/src/main/kotlin/ffc/app/location/Houses.kt
1
4386
package ffc.app.location import ffc.api.ApiErrorException import ffc.api.FfcCentral import ffc.app.mockRepository import ffc.app.person.mockPerson import ffc.app.util.RepoCallback import ffc.app.util.TaskCallback import ffc.entity.Organization import ffc.entity.Person import ffc.entity.place.House import me.piruin.geok.geometry.Point import retrofit2.dsl.enqueue interface Houses { fun house(id: String, callbackDsl: RepoCallback<House>.() -> Unit) fun houseNoLocation(callbackDsl: RepoCallback<List<House>>.() -> Unit) } interface HouseManipulator { fun update(callbackDsl: TaskCallback<House>.() -> Unit) } fun housesOf(org: Organization): Houses = if (mockRepository) DummyHouses() else ApiHouses(org) private class ApiHouses(val org: Organization) : Houses { val api = FfcCentral().service<PlaceService>() override fun house(id: String, callbackDsl: RepoCallback<House>.() -> Unit) { val callback = RepoCallback<House>().apply(callbackDsl) api.get(org.id, id).enqueue { onSuccess { callback.onFound!!.invoke(body()!!) } onError { callback.onFail!!.invoke(ApiErrorException(this)) } onFailure { callback.onFail!!.invoke(it) } } } override fun houseNoLocation(callbackDsl: RepoCallback<List<House>>.() -> Unit) { val callback = RepoCallback<List<House>>().apply(callbackDsl) api.listHouseNoLocation(org.id).enqueue { onSuccess { callback.onFound!!.invoke(body()!!) } onError { if (code() == 404) callback.onNotFound!!.invoke() else callback.onFail!!.invoke(ApiErrorException(this)) } onFailure { callback.onFail!!.invoke(it) } } } } private class ApiHouseManipulator(val org: Organization, val house: House) : HouseManipulator { val api = FfcCentral().service<PlaceService>() override fun update(callbackDsl: TaskCallback<House>.() -> Unit) { val callback = TaskCallback<House>().apply(callbackDsl) api.updateHouse(org.id, house).enqueue { onSuccess { callback.result(body()!!) } onError { callback.expception!!.invoke(ApiErrorException(this)) } onFailure { callback.expception!!.invoke(it) } } } } private class DummyHouses(val house: House? = null) : Houses, HouseManipulator { override fun houseNoLocation(callbackDsl: RepoCallback<List<House>>.() -> Unit) { val callback = RepoCallback<List<House>>().apply(callbackDsl) val houses = mutableListOf<House>() for (i in 1..100) { houses.add(House().apply { no = "100/$i" }) } callback.onFound!!.invoke(houses) } override fun update(callbackDsl: TaskCallback<House>.() -> Unit) { val callback = TaskCallback<House>().apply(callbackDsl) callback.result(house!!) } override fun house(id: String, callbackDsl: RepoCallback<House>.() -> Unit) { val callback = RepoCallback<House>().apply(callbackDsl) callback.onFound!!.invoke(House().apply { no = "112 อุทธยานวิทยาศาสตร์" location = Point(13.0, 102.0) }) } } internal fun House.resident(orgId: String, callbackDsl: RepoCallback<List<Person>>.() -> Unit) { val callback = RepoCallback<List<Person>>().apply(callbackDsl) if (mockRepository) { callback.onFound!!.invoke(listOf(mockPerson)) } else { FfcCentral().service<HouseApi>().personInHouse(orgId, this.id).enqueue { onSuccess { callback.onFound!!.invoke(body()!!) } onClientError { callback.onNotFound!!.invoke() } onServerError { callback.onFail!!.invoke(ApiErrorException(this)) } onFailure { callback.onFail!!.invoke(it) } } } } fun House.manipulator(org: Organization): HouseManipulator { return if (mockRepository) DummyHouses(this) else ApiHouseManipulator(org, this) } internal fun House.pushTo(org: Organization, callbackDsl: TaskCallback<House>.() -> Unit) { manipulator(org).update(callbackDsl) }
apache-2.0
fd0dc031b06396e2661ab296d74cab72
31.706767
96
0.615632
4.385081
false
false
false
false
icapps/niddler-ui
client-lib/src/main/kotlin/com/icapps/niddler/lib/utils/UrlUtil.kt
1
1427
package com.icapps.niddler.lib.utils import java.net.URL import java.net.URLDecoder import java.util.LinkedList import kotlin.collections.LinkedHashMap /** * @author Nicola Verbeeck * @date 09/11/2017. */ class UrlUtil(private val fullUrl: String?) { private val internalUrl = if (fullUrl != null) URL(fullUrl) else null val queryString: String? get() { return internalUrl?.query } val url: String? get() { if (internalUrl?.query == null) return fullUrl return fullUrl?.substring(0, fullUrl.indexOf('?')) + '?' + queryString } val query: Map<String, List<String>> get() { val query = internalUrl?.query ?: return emptyMap() val params = LinkedHashMap<String, MutableList<String>>() val pairs = query.split("&") for (pair in pairs) { val idx = pair.indexOf("=") val key = if (idx > 0) URLDecoder.decode(pair.substring(0, idx), "UTF-8") else pair if (!params.containsKey(key)) { params.put(key, LinkedList<String>()) } val value = if (idx > 0 && pair.length > idx + 1) URLDecoder.decode(pair.substring(idx + 1), "UTF-8") else null if (value != null) params[key]?.add(value) } return params } }
apache-2.0
7ba69582a95a38819485a589ac14b9e6
29.361702
127
0.542397
4.363914
false
false
false
false
RocketChat/Rocket.Chat.Android.Lily
app/src/main/java/chat/rocket/android/server/presentation/ChangeServerPresenter.kt
2
3143
package chat.rocket.android.server.presentation import chat.rocket.android.analytics.AnalyticsManager import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.infrastructure.LocalRepository import chat.rocket.android.server.domain.GetAccountInteractor import chat.rocket.android.server.domain.GetAccountsInteractor import chat.rocket.android.server.domain.GetCurrentServerInteractor import chat.rocket.android.server.domain.SaveCurrentServerInteractor import chat.rocket.android.server.domain.SettingsRepository import chat.rocket.android.server.domain.TokenRepository import chat.rocket.android.server.infrastructure.ConnectionManagerFactory import chat.rocket.android.util.extension.launchUI import chat.rocket.common.util.ifNull import javax.inject.Inject class ChangeServerPresenter @Inject constructor( private val view: ChangeServerView, private val navigator: ChangeServerNavigator, private val strategy: CancelStrategy, private val saveCurrentServerInteractor: SaveCurrentServerInteractor, private val getCurrentServerInteractor: GetCurrentServerInteractor, private val getAccountInteractor: GetAccountInteractor, private val getAccountsInteractor: GetAccountsInteractor, private val analyticsManager: AnalyticsManager, private val settingsRepository: SettingsRepository, private val tokenRepository: TokenRepository, private val localRepository: LocalRepository, private val connectionManager: ConnectionManagerFactory ) { fun loadServer(newUrl: String?, chatRoomId: String? = null) { launchUI(strategy) { view.showProgress() var url = newUrl val accounts = getAccountsInteractor.get() if (url == null) { // Try to load next server on the list... url = accounts.firstOrNull()?.serverUrl } url?.let { serverUrl -> val token = tokenRepository.get(serverUrl) if (token == null) { view.showInvalidCredentials() view.hideProgress() navigator.toServerScreen() return@launchUI } val settings = settingsRepository.get(serverUrl) if (settings == null) { // TODO - reload settings... } // Call disconnect on the old url if any... getCurrentServerInteractor.get()?.let { url -> connectionManager.get(url)?.disconnect() } // Save the current username. getAccountInteractor.get(serverUrl)?.let { account -> localRepository.save(LocalRepository.CURRENT_USERNAME_KEY, account.userName) } saveCurrentServerInteractor.save(serverUrl) view.hideProgress() analyticsManager.logServerSwitch() navigator.toChatRooms(chatRoomId) }.ifNull { view.hideProgress() navigator.toServerScreen() } } } }
mit
c51792675cdea828b0e320d1a12f49ce
40.368421
96
0.662743
5.602496
false
false
false
false
AndroidX/androidx
compose/ui/ui/src/commonMain/kotlin/androidx/compose/ui/focus/FocusProperties.kt
3
9940
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.ui.focus import androidx.compose.runtime.Stable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.modifier.ModifierLocalConsumer import androidx.compose.ui.modifier.ModifierLocalProvider import androidx.compose.ui.modifier.ModifierLocalReadScope import androidx.compose.ui.modifier.modifierLocalOf import androidx.compose.ui.platform.InspectorInfo import androidx.compose.ui.platform.InspectorValueInfo import androidx.compose.ui.platform.debugInspectorInfo /** * A Modifier local that stores [FocusProperties] for a sub-hierarchy. * * @see [focusProperties] */ internal val ModifierLocalFocusProperties = modifierLocalOf<FocusPropertiesModifier?> { null } /** * Properties that are applied to [focusTarget]s that can read the [ModifierLocalFocusProperties] * Modifier Local. * * @see [focusProperties] */ interface FocusProperties { /** * When set to false, indicates that the [focusTarget] that this is applied to can no longer * take focus. If the [focusTarget] is currently focused, setting this property to false will * end up clearing focus. */ var canFocus: Boolean /** * A custom item to be used when the user requests the focus to move to the "next" item. * * @sample androidx.compose.ui.samples.CustomFocusOrderSample */ var next: FocusRequester get() = FocusRequester.Default set(_) {} /** * A custom item to be used when the user requests the focus to move to the "previous" item. * * @sample androidx.compose.ui.samples.CustomFocusOrderSample */ var previous: FocusRequester get() = FocusRequester.Default set(_) {} /** * A custom item to be used when the user moves focus "up". * * @sample androidx.compose.ui.samples.CustomFocusOrderSample */ var up: FocusRequester get() = FocusRequester.Default set(_) {} /** * A custom item to be used when the user moves focus "down". * * @sample androidx.compose.ui.samples.CustomFocusOrderSample */ var down: FocusRequester get() = FocusRequester.Default set(_) {} /** * A custom item to be used when the user requests a focus moves to the "left" item. * * @sample androidx.compose.ui.samples.CustomFocusOrderSample */ var left: FocusRequester get() = FocusRequester.Default set(_) {} /** * A custom item to be used when the user requests a focus moves to the "right" item. * * @sample androidx.compose.ui.samples.CustomFocusOrderSample */ var right: FocusRequester get() = FocusRequester.Default set(_) {} /** * A custom item to be used when the user requests a focus moves to the "left" in LTR mode and * "right" in RTL mode. * * @sample androidx.compose.ui.samples.CustomFocusOrderSample */ var start: FocusRequester get() = FocusRequester.Default set(_) {} /** * A custom item to be used when the user requests a focus moves to the "right" in LTR mode * and "left" in RTL mode. * * @sample androidx.compose.ui.samples.CustomFocusOrderSample */ var end: FocusRequester get() = FocusRequester.Default set(_) {} /** * A custom item to be used when the user requests focus to move focus in * ([FocusDirection.Enter]). An automatic [Enter][FocusDirection.Enter]" * can be triggered when we move focus to a focus group that is not itself focusable. In this * case, users can use the the focus direction that triggered the move in to determine the * next item to be focused on. * * When you set the [enter] property, provide a lambda that takes the FocusDirection that * triggered the enter as an input, and provides a [FocusRequester] as an output. You can * return a custom destination by providing a [FocusRequester] attached to that destination, * a [Cancel][FocusRequester.Cancel] to cancel the focus enter or * [Default][FocusRequester.Default] to use the default focus enter behavior. * * @sample androidx.compose.ui.samples.CustomFocusEnterSample */ @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalComposeUiApi @set:ExperimentalComposeUiApi @ExperimentalComposeUiApi var enter: (FocusDirection) -> FocusRequester get() = { FocusRequester.Default } set(_) {} /** * A custom item to be used when the user requests focus to move out ([FocusDirection.Exit]). * An automatic [Exit][FocusDirection.Exit] can be triggered when we move focus outside the edge * of a parent. In this case, users can use the the focus direction that triggered the move out * to determine the next focus destination. * * When you set the [exit] property, provide a lambda that takes the FocusDirection that * triggered the exit as an input, and provides a [FocusRequester] as an output. You can * return a custom destination by providing a [FocusRequester] attached to that destination, * a [Cancel][FocusRequester.Cancel] to cancel the focus exit or * [Default][FocusRequester.Default] to use the default focus exit behavior. * * @sample androidx.compose.ui.samples.CustomFocusExitSample */ @Suppress("OPT_IN_MARKER_ON_WRONG_TARGET") @get:ExperimentalComposeUiApi @set:ExperimentalComposeUiApi @ExperimentalComposeUiApi var exit: (FocusDirection) -> FocusRequester get() = { FocusRequester.Default } set(_) {} } /** * This modifier allows you to specify properties that are accessible to [focusTarget]s further * down the modifier chain or on child layout nodes. * * @sample androidx.compose.ui.samples.FocusPropertiesSample */ fun Modifier.focusProperties(scope: FocusProperties.() -> Unit): Modifier = this.then( FocusPropertiesModifier( focusPropertiesScope = scope, inspectorInfo = debugInspectorInfo { name = "focusProperties" properties["scope"] = scope } ) ) @Stable internal class FocusPropertiesModifier( val focusPropertiesScope: FocusProperties.() -> Unit, inspectorInfo: InspectorInfo.() -> Unit ) : ModifierLocalConsumer, ModifierLocalProvider<FocusPropertiesModifier?>, InspectorValueInfo(inspectorInfo) { private var parent: FocusPropertiesModifier? by mutableStateOf(null) override fun onModifierLocalsUpdated(scope: ModifierLocalReadScope) { parent = scope.run { ModifierLocalFocusProperties.current } } override val key = ModifierLocalFocusProperties override val value: FocusPropertiesModifier get() = this override fun equals(other: Any?) = other is FocusPropertiesModifier && focusPropertiesScope == other.focusPropertiesScope override fun hashCode() = focusPropertiesScope.hashCode() fun calculateProperties(focusProperties: FocusProperties) { // Populate with the specified focus properties. focusProperties.apply(focusPropertiesScope) // Parent can override any values set by this parent?.calculateProperties(focusProperties) } } internal fun FocusModifier.setUpdatedProperties(properties: FocusProperties) { if (properties.canFocus) activateNode() else deactivateNode() } internal class FocusPropertiesImpl : FocusProperties { override var canFocus: Boolean = true override var next: FocusRequester = FocusRequester.Default override var previous: FocusRequester = FocusRequester.Default override var up: FocusRequester = FocusRequester.Default override var down: FocusRequester = FocusRequester.Default override var left: FocusRequester = FocusRequester.Default override var right: FocusRequester = FocusRequester.Default override var start: FocusRequester = FocusRequester.Default override var end: FocusRequester = FocusRequester.Default @OptIn(ExperimentalComposeUiApi::class) override var enter: (FocusDirection) -> FocusRequester = { FocusRequester.Default } @OptIn(ExperimentalComposeUiApi::class) override var exit: (FocusDirection) -> FocusRequester = { FocusRequester.Default } } internal fun FocusProperties.clear() { canFocus = true next = FocusRequester.Default previous = FocusRequester.Default up = FocusRequester.Default down = FocusRequester.Default left = FocusRequester.Default right = FocusRequester.Default start = FocusRequester.Default end = FocusRequester.Default @OptIn(ExperimentalComposeUiApi::class) enter = { FocusRequester.Default } @OptIn(ExperimentalComposeUiApi::class) exit = { FocusRequester.Default } } internal fun FocusModifier.refreshFocusProperties() { val coordinator = coordinator ?: return focusProperties.clear() coordinator.layoutNode.owner?.snapshotObserver?.observeReads(this, FocusModifier.RefreshFocusProperties ) { focusPropertiesModifier?.calculateProperties(focusProperties) } setUpdatedProperties(focusProperties) }
apache-2.0
66c38fac171d3026cf61b6a4a6b00b4f
35.95539
100
0.711871
4.896552
false
false
false
false
AndroidX/androidx
room/room-compiler/src/test/test-data/kotlinCodeGen/pojoRowAdapter_customTypeConverter_composite.kt
3
3042
import android.database.Cursor import androidx.room.EntityInsertionAdapter import androidx.room.RoomDatabase import androidx.room.RoomSQLiteQuery import androidx.room.RoomSQLiteQuery.Companion.acquire import androidx.room.util.getColumnIndexOrThrow import androidx.room.util.query import androidx.sqlite.db.SupportSQLiteStatement import java.lang.Class import javax.`annotation`.processing.Generated import kotlin.Int import kotlin.String import kotlin.Suppress import kotlin.Unit import kotlin.collections.List import kotlin.jvm.JvmStatic @Generated(value = ["androidx.room.RoomProcessor"]) @Suppress(names = ["UNCHECKED_CAST", "DEPRECATION"]) public class MyDao_Impl( __db: RoomDatabase, ) : MyDao { private val __db: RoomDatabase private val __insertionAdapterOfMyEntity: EntityInsertionAdapter<MyEntity> init { this.__db = __db this.__insertionAdapterOfMyEntity = object : EntityInsertionAdapter<MyEntity>(__db) { public override fun createQuery(): String = "INSERT OR ABORT INTO `MyEntity` (`pk`,`bar`) VALUES (?,?)" public override fun bind(statement: SupportSQLiteStatement, entity: MyEntity): Unit { statement.bindLong(1, entity.pk.toLong()) val _tmp: Foo = FooBarConverter.toFoo(entity.bar) val _tmp_1: String = FooBarConverter.toString(_tmp) statement.bindString(2, _tmp_1) } } } public override fun addEntity(item: MyEntity): Unit { __db.assertNotSuspendingTransaction() __db.beginTransaction() try { __insertionAdapterOfMyEntity.insert(item) __db.setTransactionSuccessful() } finally { __db.endTransaction() } } public override fun getEntity(): MyEntity { val _sql: String = "SELECT * FROM MyEntity" val _statement: RoomSQLiteQuery = acquire(_sql, 0) __db.assertNotSuspendingTransaction() val _cursor: Cursor = query(__db, _statement, false, null) try { val _cursorIndexOfPk: Int = getColumnIndexOrThrow(_cursor, "pk") val _cursorIndexOfBar: Int = getColumnIndexOrThrow(_cursor, "bar") val _result: MyEntity if (_cursor.moveToFirst()) { val _tmpPk: Int _tmpPk = _cursor.getInt(_cursorIndexOfPk) val _tmpBar: Bar val _tmp: String _tmp = _cursor.getString(_cursorIndexOfBar) val _tmp_1: Foo = FooBarConverter.fromString(_tmp) _tmpBar = FooBarConverter.fromFoo(_tmp_1) _result = MyEntity(_tmpPk,_tmpBar) } else { error("Cursor was empty, but expected a single item.") } return _result } finally { _cursor.close() _statement.release() } } public companion object { @JvmStatic public fun getRequiredConverters(): List<Class<*>> = emptyList() } }
apache-2.0
c8cf6f554c56058afceb26260a754a89
35.22619
97
0.621302
4.672811
false
false
false
false
ioc1778/incubator
incubator-events-benchmarks/src/main/java/com/riaektiv/akka/spices/OneToThreePipelineAkkaBenchmark.kt
2
1947
package com.riaektiv.akka.spices import akka.actor.ActorRef import akka.actor.ActorSystem import akka.actor.Props import org.openjdk.jmh.annotations.* import scala.concurrent.duration.FiniteDuration import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit /** * Coding With Passion Since 1991 * Created: 12/25/2016, 12:22 PM Eastern Time * @author Sergey Chuykov */ @State(Scope.Thread) @BenchmarkMode(Mode.Throughput) @OutputTimeUnit(TimeUnit.SECONDS) @Fork(jvmArgsAppend = arrayOf("-Xmx4g")) @Warmup(iterations = 8, time = 3) @Measurement(iterations = 8, time = 3) open class OneToThreePipelineAkkaBenchmark { val ONE_MINUTE = FiniteDuration(1, TimeUnit.MINUTES) companion object { const val EVENTS_TO_CONSUME = 1 * 1000 * 1000 } lateinit var system: ActorSystem lateinit var driver: ActorRef lateinit var journalingActor: ActorRef lateinit var replicationActor: ActorRef lateinit var exitActor: ActorRef lateinit var ticket: OneToThreePipelineTicket @Setup fun setup() { system = ActorSystem.create(); driver = system.actorOf(Props.create(LongEventProducerUntypedActor::class.java)) journalingActor = system.actorOf(Props.create(LongEventJournalingActor::class.java)) replicationActor = system.actorOf(Props.create(LongEventReplicationActor::class.java)) exitActor = system.actorOf(Props.create(LongEventExitActor::class.java)) } @Benchmark @OperationsPerInvocation(LongEventBatchSpiceBenchmark.EVENTS_TO_CONSUME) fun execute() { ticket = OneToThreePipelineTicket(EVENTS_TO_CONSUME, CountDownLatch(1), driver, journalingActor, replicationActor, exitActor) driver.tell(ticket, ActorRef.noSender()) ticket.latch.await(1, TimeUnit.MINUTES) } @TearDown fun tearDown() { system.terminate() system.awaitTermination(ONE_MINUTE) } }
bsd-3-clause
6fe320b02a6bcf9ca7b5008ca843dafd
28.969231
94
0.727786
4.196121
false
false
false
false
twilio/video-quickstart-android
common/src/main/java/com/twilio/video/examples/common/VideoFrameKtx.kt
1
4455
package com.twilio.video.examples.common import android.graphics.Bitmap import android.graphics.BitmapFactory import android.graphics.ImageDecoder import android.graphics.ImageFormat import android.graphics.Matrix import android.graphics.Rect import android.graphics.YuvImage import android.os.Build import java.io.ByteArrayOutputStream import java.io.IOException import java.nio.ByteBuffer import tvi.webrtc.VideoFrame import tvi.webrtc.YuvConverter /** * Converts a [tvi.webrtc.VideoFrame] to a Bitmap. This method must be called from a thread with a * valid EGL context when the frame buffer is a [VideoFrame.TextureBuffer]. */ fun VideoFrame.toBitmap(): Bitmap? { // Construct yuv image from image data val yuvImage = if (buffer is VideoFrame.TextureBuffer) { val yuvConverter = YuvConverter() val i420Buffer = yuvConverter.convert(buffer as VideoFrame.TextureBuffer) yuvConverter.release() i420ToYuvImage(i420Buffer, i420Buffer.width, i420Buffer.height) } else { val i420Buffer = buffer.toI420() val returnImage = i420ToYuvImage(i420Buffer, i420Buffer.width, i420Buffer.height) i420Buffer.release() returnImage } val stream = ByteArrayOutputStream() val rect = Rect(0, 0, yuvImage.width, yuvImage.height) // Compress YuvImage to jpeg yuvImage.compressToJpeg(rect, 100, stream) // Convert jpeg to Bitmap val imageBytes = stream.toByteArray() var bitmap = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) { val buffer = ByteBuffer.wrap(imageBytes) val src = ImageDecoder.createSource(buffer) try { ImageDecoder.decodeBitmap(src) } catch (e: IOException) { e.printStackTrace() return null } } else { BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.size) } val matrix = Matrix() // Apply any needed rotation matrix.postRotate(rotation.toFloat()) bitmap = Bitmap.createBitmap( bitmap!!, 0, 0, bitmap.width, bitmap.height, matrix, true ) return bitmap } private fun i420ToYuvImage(i420Buffer: VideoFrame.I420Buffer, width: Int, height: Int): YuvImage { val yuvPlanes = arrayOf( i420Buffer.dataY, i420Buffer.dataU, i420Buffer.dataV ) val yuvStrides = intArrayOf( i420Buffer.strideY, i420Buffer.strideU, i420Buffer.strideV ) if (yuvStrides[0] != width) { return fastI420ToYuvImage(yuvPlanes, yuvStrides, width, height) } if (yuvStrides[1] != width / 2) { return fastI420ToYuvImage(yuvPlanes, yuvStrides, width, height) } if (yuvStrides[2] != width / 2) { return fastI420ToYuvImage(yuvPlanes, yuvStrides, width, height) } val bytes = ByteArray( yuvStrides[0] * height + yuvStrides[1] * height / 2 + yuvStrides[2] * height / 2 ) var tmp = ByteBuffer.wrap(bytes, 0, width * height) copyPlane(yuvPlanes[0], tmp) val tmpBytes = ByteArray(width / 2 * height / 2) tmp = ByteBuffer.wrap(tmpBytes, 0, width / 2 * height / 2) copyPlane(yuvPlanes[2], tmp) for (row in 0 until height / 2) { for (col in 0 until width / 2) { bytes[width * height + row * width + col * 2] = tmpBytes[row * width / 2 + col] } } copyPlane(yuvPlanes[1], tmp) for (row in 0 until height / 2) { for (col in 0 until width / 2) { bytes[width * height + row * width + col * 2 + 1] = tmpBytes[row * width / 2 + col] } } return YuvImage(bytes, ImageFormat.NV21, width, height, null) } private fun fastI420ToYuvImage( yuvPlanes: Array<ByteBuffer>, yuvStrides: IntArray, width: Int, height: Int ): YuvImage { val bytes = ByteArray(width * height * 3 / 2) var i = 0 for (row in 0 until height) { for (col in 0 until width) { bytes[i++] = yuvPlanes[0].get(col + row * yuvStrides[0]) } } for (row in 0 until height / 2) { for (col in 0 until width / 2) { bytes[i++] = yuvPlanes[2].get(col + row * yuvStrides[2]) bytes[i++] = yuvPlanes[1].get(col + row * yuvStrides[1]) } } return YuvImage(bytes, ImageFormat.NV21, width, height, null) } private fun copyPlane(src: ByteBuffer, dst: ByteBuffer) { src.position(0).limit(src.capacity()) dst.put(src) dst.position(0).limit(dst.capacity()) }
mit
1030c417fc189d9b76888c38440ec51f
33.007634
98
0.64422
3.863833
false
false
false
false
androidx/androidx
compose/foundation/foundation-layout/src/androidAndroidTest/kotlin/androidx/compose/foundation/layout/SizeTest.kt
3
78899
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.layout import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.layout.Layout import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.layout.IntrinsicMeasurable import androidx.compose.ui.layout.IntrinsicMeasureScope import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.layout.Measurable import androidx.compose.ui.layout.MeasurePolicy import androidx.compose.ui.layout.MeasureResult import androidx.compose.ui.layout.MeasureScope import androidx.compose.ui.node.Ref import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.layout.positionInParent import androidx.compose.ui.layout.positionInRoot import androidx.compose.ui.platform.InspectableValue import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.platform.ValueElement import androidx.compose.ui.platform.isDebugInspectorInfoEnabled import androidx.compose.ui.unit.Constraints import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.IntSize import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.constrain import androidx.compose.ui.unit.dp import com.google.common.truth.Truth.assertThat import org.junit.After import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.filters.FlakyTest import androidx.test.filters.MediumTest import org.junit.Assert.assertNotEquals import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit import kotlin.math.roundToInt @MediumTest @RunWith(AndroidJUnit4::class) class SizeTest : LayoutTest() { @Before fun before() { isDebugInspectorInfoEnabled = true } @After fun after() { isDebugInspectorInfoEnabled = false } @Test fun testPreferredSize_withWidthSizeModifiers() = with(density) { val sizeDp = 50.toDp() val sizeIpx = sizeDp.roundToPx() val positionedLatch = CountDownLatch(6) val size = MutableList(6) { Ref<IntSize>() } val position = MutableList(6) { Ref<Offset>() } show { Box { Column { Container( Modifier.widthIn(min = sizeDp, max = sizeDp * 2) .height(sizeDp) .saveLayoutInfo(size[0], position[0], positionedLatch) ) { } Container( Modifier.widthIn(max = sizeDp * 2) .height(sizeDp) .saveLayoutInfo(size[1], position[1], positionedLatch) ) { } Container( Modifier.widthIn(min = sizeDp) .height(sizeDp) .saveLayoutInfo(size[2], position[2], positionedLatch) ) { } Container( Modifier.widthIn(max = sizeDp) .widthIn(min = sizeDp * 2) .height(sizeDp) .saveLayoutInfo(size[3], position[3], positionedLatch) ) { } Container( Modifier.widthIn(min = sizeDp * 2) .widthIn(max = sizeDp) .height(sizeDp) .saveLayoutInfo(size[4], position[4], positionedLatch) ) { } Container( Modifier.size(sizeDp) .saveLayoutInfo(size[5], position[5], positionedLatch) ) { } } } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(sizeIpx, sizeIpx), size[0].value) assertEquals(Offset.Zero, position[0].value) assertEquals(IntSize(0, sizeIpx), size[1].value) assertEquals(Offset(0f, sizeIpx.toFloat()), position[1].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[2].value) assertEquals(Offset(0f, (sizeIpx * 2).toFloat()), position[2].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[3].value) assertEquals(Offset(0f, (sizeIpx * 3).toFloat()), position[3].value) assertEquals(IntSize((sizeDp * 2).roundToPx(), sizeIpx), size[4].value) assertEquals(Offset(0f, (sizeIpx * 4).toFloat()), position[4].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[5].value) assertEquals(Offset(0f, (sizeIpx * 5).toFloat()), position[5].value) } @Test fun testPreferredSize_withHeightSizeModifiers() = with(density) { val sizeDp = 10.toDp() val sizeIpx = sizeDp.roundToPx() val positionedLatch = CountDownLatch(6) val size = MutableList(6) { Ref<IntSize>() } val position = MutableList(6) { Ref<Offset>() } show { Box { Row { Container( Modifier.heightIn(min = sizeDp, max = sizeDp * 2) .width(sizeDp) .saveLayoutInfo(size[0], position[0], positionedLatch) ) { } Container( Modifier.heightIn(max = sizeDp * 2) .width(sizeDp) .saveLayoutInfo(size[1], position[1], positionedLatch) ) { } Container( Modifier.heightIn(min = sizeDp) .width(sizeDp) .saveLayoutInfo(size[2], position[2], positionedLatch) ) { } Container( Modifier.heightIn(max = sizeDp) .heightIn(min = sizeDp * 2) .width(sizeDp) .saveLayoutInfo(size[3], position[3], positionedLatch) ) { } Container( Modifier.heightIn(min = sizeDp * 2) .heightIn(max = sizeDp) .width(sizeDp) .saveLayoutInfo(size[4], position[4], positionedLatch) ) { } Container( Modifier.height(sizeDp).then(Modifier.width(sizeDp)).then( Modifier.saveLayoutInfo(size[5], position[5], positionedLatch) ) ) { } } } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(sizeIpx, sizeIpx), size[0].value) assertEquals(Offset.Zero, position[0].value) assertEquals(IntSize(sizeIpx, 0), size[1].value) assertEquals(Offset(sizeIpx.toFloat(), 0f), position[1].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[2].value) assertEquals(Offset((sizeIpx * 2).toFloat(), 0f), position[2].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[3].value) assertEquals(Offset((sizeIpx * 3).toFloat(), 0f), position[3].value) assertEquals(IntSize(sizeIpx, (sizeDp * 2).roundToPx()), size[4].value) assertEquals(Offset((sizeIpx * 4).toFloat(), 0f), position[4].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[5].value) assertEquals(Offset((sizeIpx * 5).toFloat(), 0f), position[5].value) } @Test fun testPreferredSize_withSizeModifiers() = with(density) { val sizeDp = 50.toDp() val sizeIpx = sizeDp.roundToPx() val positionedLatch = CountDownLatch(5) val size = MutableList(5) { Ref<IntSize>() } val position = MutableList(5) { Ref<Offset>() } show { Box { Row { val maxSize = sizeDp * 2 Container( Modifier.sizeIn(maxWidth = maxSize, maxHeight = maxSize) .sizeIn(minWidth = sizeDp, minHeight = sizeDp) .saveLayoutInfo(size[0], position[0], positionedLatch) ) { } Container( Modifier.sizeIn(maxWidth = sizeDp, maxHeight = sizeDp) .sizeIn(minWidth = sizeDp * 2, minHeight = sizeDp) .saveLayoutInfo(size[1], position[1], positionedLatch) ) { } val maxSize1 = sizeDp * 2 Container( Modifier.sizeIn(minWidth = sizeDp, minHeight = sizeDp) .sizeIn(maxWidth = maxSize1, maxHeight = maxSize1) .saveLayoutInfo(size[2], position[2], positionedLatch) ) { } val minSize = sizeDp * 2 Container( Modifier.sizeIn(minWidth = minSize, minHeight = minSize) .sizeIn(maxWidth = sizeDp, maxHeight = sizeDp) .saveLayoutInfo(size[3], position[3], positionedLatch) ) { } Container( Modifier.size(sizeDp) .saveLayoutInfo(size[4], position[4], positionedLatch) ) { } } } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(sizeIpx, sizeIpx), size[0].value) assertEquals(Offset.Zero, position[0].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[1].value) assertEquals(Offset(sizeIpx.toFloat(), 0f), position[1].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[2].value) assertEquals(Offset((sizeIpx * 2).toFloat(), 0f), position[2].value) assertEquals(IntSize(sizeIpx * 2, sizeIpx * 2), size[3].value) assertEquals(Offset((sizeIpx * 3).toFloat(), 0f), position[3].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[4].value) assertEquals(Offset((sizeIpx * 5).toFloat(), 0f), position[4].value) } @Test fun testPreferredSizeModifiers_respectMaxConstraint() = with(density) { val sizeDp = 100.toDp() val size = sizeDp.roundToPx() val positionedLatch = CountDownLatch(2) val constrainedBoxSize = Ref<IntSize>() val childSize = Ref<IntSize>() val childPosition = Ref<Offset>() show { Box { Container(width = sizeDp, height = sizeDp) { Container( Modifier.width(sizeDp * 2) .height(sizeDp * 3) .onGloballyPositioned { coordinates: LayoutCoordinates -> constrainedBoxSize.value = coordinates.size positionedLatch.countDown() } ) { Container( expanded = true, modifier = Modifier.saveLayoutInfo( size = childSize, position = childPosition, positionedLatch = positionedLatch ) ) { } } } } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(size, size), constrainedBoxSize.value) assertEquals(IntSize(size, size), childSize.value) assertEquals(Offset.Zero, childPosition.value) } @Test fun testMaxModifiers_withInfiniteValue() = with(density) { val sizeDp = 20.toDp() val sizeIpx = sizeDp.roundToPx() val positionedLatch = CountDownLatch(4) val size = MutableList(4) { Ref<IntSize>() } val position = MutableList(4) { Ref<Offset>() } show { Box { Row { Container(Modifier.widthIn(max = Dp.Infinity)) { Container( width = sizeDp, height = sizeDp, modifier = Modifier.saveLayoutInfo( size[0], position[0], positionedLatch ) ) { } } Container(Modifier.heightIn(max = Dp.Infinity)) { Container( width = sizeDp, height = sizeDp, modifier = Modifier.saveLayoutInfo( size[1], position[1], positionedLatch ) ) { } } Container( Modifier.width(sizeDp) .height(sizeDp) .widthIn(max = Dp.Infinity) .heightIn(max = Dp.Infinity) .saveLayoutInfo(size[2], position[2], positionedLatch) ) { } Container( Modifier.sizeIn( maxWidth = Dp.Infinity, maxHeight = Dp.Infinity ) ) { Container( width = sizeDp, height = sizeDp, modifier = Modifier.saveLayoutInfo( size[3], position[3], positionedLatch ) ) { } } } } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(sizeIpx, sizeIpx), size[0].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[1].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[2].value) assertEquals(IntSize(sizeIpx, sizeIpx), size[3].value) } @Test fun testSize_smallerInLarger() = with(density) { val sizeIpx = 64 val sizeDp = sizeIpx.toDp() val positionedLatch = CountDownLatch(1) val boxSize = Ref<IntSize>() val boxPosition = Ref<Offset>() show { Box( Modifier.wrapContentSize(Alignment.TopStart) .requiredSize(sizeDp * 2) .requiredSize(sizeDp) .saveLayoutInfo(boxSize, boxPosition, positionedLatch) ) } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(sizeIpx, sizeIpx), boxSize.value) assertEquals( Offset( (sizeIpx / 2).toFloat(), (sizeIpx / 2).toFloat() ), boxPosition.value ) } @Test fun testSize_smallerBoxInLargerBox() = with(density) { val sizeIpx = 64 val sizeDp = sizeIpx.toDp() val positionedLatch = CountDownLatch(1) val boxSize = Ref<IntSize>() val boxPosition = Ref<Offset>() show { Box( Modifier.wrapContentSize(Alignment.TopStart).requiredSize(sizeDp * 2), propagateMinConstraints = true ) { Box( Modifier.requiredSize(sizeDp) .onGloballyPositioned { boxSize.value = it.size boxPosition.value = it.positionInRoot() positionedLatch.countDown() } ) } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(sizeIpx, sizeIpx), boxSize.value) assertEquals( Offset( (sizeIpx / 2).toFloat(), (sizeIpx / 2).toFloat() ), boxPosition.value ) } @Test fun testSize_largerInSmaller() = with(density) { val sizeIpx = 64 val sizeDp = sizeIpx.toDp() val positionedLatch = CountDownLatch(1) val boxSize = Ref<IntSize>() val boxPosition = Ref<Offset>() show { Box( Modifier.wrapContentSize(Alignment.TopStart) .requiredSize(sizeDp) .requiredSize(sizeDp * 2) .saveLayoutInfo(boxSize, boxPosition, positionedLatch) ) } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(sizeIpx * 2, sizeIpx * 2), boxSize.value) assertEquals( Offset((-sizeIpx / 2).toFloat(), (-sizeIpx / 2).toFloat()), boxPosition.value ) } @Test fun testMeasurementConstraints_preferredSatisfiable() = with(density) { assertConstraints( Constraints(10, 30, 15, 35), Modifier.width(20.toDp()), Constraints(20, 20, 15, 35) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.height(20.toDp()), Constraints(10, 30, 20, 20) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.size(20.toDp()), Constraints(20, 20, 20, 20) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.widthIn(20.toDp(), 25.toDp()), Constraints(20, 25, 15, 35) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.heightIn(20.toDp(), 25.toDp()), Constraints(10, 30, 20, 25) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.sizeIn(20.toDp(), 20.toDp(), 25.toDp(), 25.toDp()), Constraints(20, 25, 20, 25) ) } @Test fun testMeasurementConstraints_preferredUnsatisfiable() = with(density) { assertConstraints( Constraints(20, 40, 15, 35), Modifier.width(15.toDp()), Constraints(20, 20, 15, 35) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.height(10.toDp()), Constraints(10, 30, 15, 15) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.size(40.toDp()), Constraints(30, 30, 35, 35) ) assertConstraints( Constraints(20, 30, 15, 35), Modifier.widthIn(10.toDp(), 15.toDp()), Constraints(20, 20, 15, 35) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.heightIn(5.toDp(), 10.toDp()), Constraints(10, 30, 15, 15) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.sizeIn(40.toDp(), 50.toDp(), 45.toDp(), 55.toDp()), Constraints(30, 30, 35, 35) ) } @Test fun testMeasurementConstraints_compulsorySatisfiable() = with(density) { assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredWidth(20.toDp()), Constraints(20, 20, 15, 35) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredHeight(20.toDp()), Constraints(10, 30, 20, 20) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredSize(20.toDp()), Constraints(20, 20, 20, 20) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredWidthIn(20.toDp(), 25.toDp()), Constraints(20, 25, 15, 35) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredHeightIn(20.toDp(), 25.toDp()), Constraints(10, 30, 20, 25) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredSizeIn(20.toDp(), 20.toDp(), 25.toDp(), 25.toDp()), Constraints(20, 25, 20, 25) ) } @Test fun testMeasurementConstraints_compulsoryUnsatisfiable() = with(density) { assertConstraints( Constraints(20, 40, 15, 35), Modifier.requiredWidth(15.toDp()), Constraints(15, 15, 15, 35) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredHeight(10.toDp()), Constraints(10, 30, 10, 10) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredSize(40.toDp()), Constraints(40, 40, 40, 40) ) assertConstraints( Constraints(20, 30, 15, 35), Modifier.requiredWidthIn(10.toDp(), 15.toDp()), Constraints(10, 15, 15, 35) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredHeightIn(5.toDp(), 10.toDp()), Constraints(10, 30, 5, 10) ) assertConstraints( Constraints(10, 30, 15, 35), Modifier.requiredSizeIn(40.toDp(), 50.toDp(), 45.toDp(), 55.toDp()), Constraints(40, 45, 50, 55) ) // When one dimension is unspecified and the other contradicts the incoming constraint. assertConstraints( Constraints(10, 10, 10, 10), Modifier.requiredSizeIn(20.toDp(), 30.toDp(), Dp.Unspecified, Dp.Unspecified), Constraints(20, 20, 30, 30) ) assertConstraints( Constraints(40, 40, 40, 40), Modifier.requiredSizeIn(Dp.Unspecified, Dp.Unspecified, 20.toDp(), 30.toDp()), Constraints(20, 20, 30, 30) ) } @Test fun testDefaultMinSize() = with(density) { val latch = CountDownLatch(3) show { // Constraints are applied. Layout( {}, Modifier.wrapContentSize() .requiredSizeIn(maxWidth = 30.toDp(), maxHeight = 40.toDp()) .defaultMinSize(minWidth = 10.toDp(), minHeight = 20.toDp()) ) { _, constraints -> assertEquals(10, constraints.minWidth) assertEquals(20, constraints.minHeight) assertEquals(30, constraints.maxWidth) assertEquals(40, constraints.maxHeight) latch.countDown() layout(0, 0) {} } // Constraints are not applied. Layout( {}, Modifier.requiredSizeIn( minWidth = 10.toDp(), minHeight = 20.toDp(), maxWidth = 100.toDp(), maxHeight = 110.toDp() ).defaultMinSize( minWidth = 50.toDp(), minHeight = 50.toDp() ) ) { _, constraints -> assertEquals(10, constraints.minWidth) assertEquals(20, constraints.minHeight) assertEquals(100, constraints.maxWidth) assertEquals(110, constraints.maxHeight) latch.countDown() layout(0, 0) {} } // Defaults values are not changing. Layout( {}, Modifier.requiredSizeIn( minWidth = 10.toDp(), minHeight = 20.toDp(), maxWidth = 100.toDp(), maxHeight = 110.toDp() ).defaultMinSize() ) { _, constraints -> assertEquals(10, constraints.minWidth) assertEquals(20, constraints.minHeight) assertEquals(100, constraints.maxWidth) assertEquals(110, constraints.maxHeight) latch.countDown() layout(0, 0) {} } } assertTrue(latch.await(1, TimeUnit.SECONDS)) } @Test fun testDefaultMinSize_withCoercingMaxConstraints() = with(density) { val latch = CountDownLatch(1) show { Layout( {}, Modifier.wrapContentSize() .requiredSizeIn(maxWidth = 30.toDp(), maxHeight = 40.toDp()) .defaultMinSize(minWidth = 70.toDp(), minHeight = 80.toDp()) ) { _, constraints -> assertEquals(30, constraints.minWidth) assertEquals(40, constraints.minHeight) assertEquals(30, constraints.maxWidth) assertEquals(40, constraints.maxHeight) latch.countDown() layout(0, 0) {} } } assertTrue(latch.await(1, TimeUnit.SECONDS)) } @Test fun testMinWidthModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.widthIn(min = 10.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(10, minIntrinsicWidth(0)) assertEquals(10, minIntrinsicWidth(5)) assertEquals(50, minIntrinsicWidth(50)) assertEquals(10, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(0, minIntrinsicHeight(0)) assertEquals(35, minIntrinsicHeight(35)) assertEquals(50, minIntrinsicHeight(50)) assertEquals(0, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(10, maxIntrinsicWidth(0)) assertEquals(10, maxIntrinsicWidth(5)) assertEquals(50, maxIntrinsicWidth(50)) assertEquals(10, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(0, maxIntrinsicHeight(0)) assertEquals(35, maxIntrinsicHeight(35)) assertEquals(50, maxIntrinsicHeight(50)) assertEquals(0, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testMaxWidthModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.widthIn(max = 20.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(15, minIntrinsicWidth(15)) assertEquals(20, minIntrinsicWidth(50)) assertEquals(0, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(0, minIntrinsicHeight(0)) assertEquals(15, minIntrinsicHeight(15)) assertEquals(50, minIntrinsicHeight(50)) assertEquals(0, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(0, maxIntrinsicWidth(0)) assertEquals(15, maxIntrinsicWidth(15)) assertEquals(20, maxIntrinsicWidth(50)) assertEquals(0, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(0, maxIntrinsicHeight(0)) assertEquals(15, maxIntrinsicHeight(15)) assertEquals(50, maxIntrinsicHeight(50)) assertEquals(0, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testMinHeightModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.heightIn(min = 30.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(15, minIntrinsicWidth(15)) assertEquals(50, minIntrinsicWidth(50)) assertEquals(0, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(30, minIntrinsicHeight(0)) assertEquals(30, minIntrinsicHeight(15)) assertEquals(50, minIntrinsicHeight(50)) assertEquals(30, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(0, maxIntrinsicWidth(0)) assertEquals(15, maxIntrinsicWidth(15)) assertEquals(50, maxIntrinsicWidth(50)) assertEquals(0, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(30, maxIntrinsicHeight(0)) assertEquals(30, maxIntrinsicHeight(15)) assertEquals(50, maxIntrinsicHeight(50)) assertEquals(30, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testMaxHeightModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.heightIn(max = 40.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(15, minIntrinsicWidth(15)) assertEquals(50, minIntrinsicWidth(50)) assertEquals(0, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(0, minIntrinsicHeight(0)) assertEquals(15, minIntrinsicHeight(15)) assertEquals(40, minIntrinsicHeight(50)) assertEquals(0, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(0, maxIntrinsicWidth(0)) assertEquals(15, maxIntrinsicWidth(15)) assertEquals(50, maxIntrinsicWidth(50)) assertEquals(0, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(0, maxIntrinsicHeight(0)) assertEquals(15, maxIntrinsicHeight(15)) assertEquals(40, maxIntrinsicHeight(50)) assertEquals(0, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testWidthModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.width(10.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(10, minIntrinsicWidth(0)) assertEquals(10, minIntrinsicWidth(10)) assertEquals(10, minIntrinsicWidth(75)) assertEquals(10, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(0, minIntrinsicHeight(0)) assertEquals(35, minIntrinsicHeight(35)) assertEquals(70, minIntrinsicHeight(70)) assertEquals(0, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(10, maxIntrinsicWidth(0)) assertEquals(10, maxIntrinsicWidth(15)) assertEquals(10, maxIntrinsicWidth(75)) assertEquals(10, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(0, maxIntrinsicHeight(0)) assertEquals(35, maxIntrinsicHeight(35)) assertEquals(70, maxIntrinsicHeight(70)) assertEquals(0, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testHeightModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.height(10.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(15, minIntrinsicWidth(15)) assertEquals(75, minIntrinsicWidth(75)) assertEquals(0, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(10, minIntrinsicHeight(0)) assertEquals(10, minIntrinsicHeight(35)) assertEquals(10, minIntrinsicHeight(70)) assertEquals(10, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(0, maxIntrinsicWidth(0)) assertEquals(15, maxIntrinsicWidth(15)) assertEquals(75, maxIntrinsicWidth(75)) assertEquals(0, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(10, maxIntrinsicHeight(0)) assertEquals(10, maxIntrinsicHeight(35)) assertEquals(10, maxIntrinsicHeight(70)) assertEquals(10, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testWidthHeightModifiers_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container( Modifier.sizeIn( minWidth = 10.toDp(), maxWidth = 20.toDp(), minHeight = 30.toDp(), maxHeight = 40.toDp() ) ) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(10, minIntrinsicWidth(0)) assertEquals(15, minIntrinsicWidth(15)) assertEquals(20, minIntrinsicWidth(50)) assertEquals(10, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(30, minIntrinsicHeight(0)) assertEquals(35, minIntrinsicHeight(35)) assertEquals(40, minIntrinsicHeight(50)) assertEquals(30, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(10, maxIntrinsicWidth(0)) assertEquals(15, maxIntrinsicWidth(15)) assertEquals(20, maxIntrinsicWidth(50)) assertEquals(10, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(30, maxIntrinsicHeight(0)) assertEquals(35, maxIntrinsicHeight(35)) assertEquals(40, maxIntrinsicHeight(50)) assertEquals(30, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testMinSizeModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.sizeIn(minWidth = 20.toDp(), minHeight = 30.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(20, minIntrinsicWidth(0)) assertEquals(20, minIntrinsicWidth(10)) assertEquals(50, minIntrinsicWidth(50)) assertEquals(20, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(30, minIntrinsicHeight(0)) assertEquals(30, minIntrinsicHeight(10)) assertEquals(50, minIntrinsicHeight(50)) assertEquals(30, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(20, maxIntrinsicWidth(0)) assertEquals(20, maxIntrinsicWidth(10)) assertEquals(50, maxIntrinsicWidth(50)) assertEquals(20, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(30, maxIntrinsicHeight(0)) assertEquals(30, maxIntrinsicHeight(10)) assertEquals(50, maxIntrinsicHeight(50)) assertEquals(30, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testMaxSizeModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.sizeIn(maxWidth = 40.toDp(), maxHeight = 50.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(15, minIntrinsicWidth(15)) assertEquals(40, minIntrinsicWidth(50)) assertEquals(0, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(0, minIntrinsicHeight(0)) assertEquals(15, minIntrinsicHeight(15)) assertEquals(50, minIntrinsicHeight(75)) assertEquals(0, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(0, maxIntrinsicWidth(0)) assertEquals(15, maxIntrinsicWidth(15)) assertEquals(40, maxIntrinsicWidth(50)) assertEquals(0, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(0, maxIntrinsicHeight(0)) assertEquals(15, maxIntrinsicHeight(15)) assertEquals(50, maxIntrinsicHeight(75)) assertEquals(0, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testPreferredSizeModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.size(40.toDp(), 50.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(40, minIntrinsicWidth(0)) assertEquals(40, minIntrinsicWidth(35)) assertEquals(40, minIntrinsicWidth(75)) assertEquals(40, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(50, minIntrinsicHeight(0)) assertEquals(50, minIntrinsicHeight(35)) assertEquals(50, minIntrinsicHeight(70)) assertEquals(50, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(40, maxIntrinsicWidth(0)) assertEquals(40, maxIntrinsicWidth(35)) assertEquals(40, maxIntrinsicWidth(75)) assertEquals(40, maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(50, maxIntrinsicHeight(0)) assertEquals(50, maxIntrinsicHeight(35)) assertEquals(50, maxIntrinsicHeight(70)) assertEquals(50, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testFillModifier_correctSize() = with(density) { val parentWidth = 100 val parentHeight = 80 val parentModifier = Modifier.requiredSize(parentWidth.toDp(), parentHeight.toDp()) val childWidth = 40 val childHeight = 30 val childModifier = Modifier.size(childWidth.toDp(), childHeight.toDp()) assertEquals( IntSize(childWidth, childHeight), calculateSizeFor(parentModifier, childModifier) ) assertEquals( IntSize(parentWidth, childHeight), calculateSizeFor(parentModifier, Modifier.fillMaxWidth().then(childModifier)) ) assertEquals( IntSize(childWidth, parentHeight), calculateSizeFor(parentModifier, Modifier.fillMaxHeight().then(childModifier)) ) assertEquals( IntSize(parentWidth, parentHeight), calculateSizeFor(parentModifier, Modifier.fillMaxSize().then(childModifier)) ) } @Test fun testFillModifier_correctDpSize() = with(density) { val parentWidth = 100 val parentHeight = 80 val parentModifier = Modifier.requiredSize(DpSize(parentWidth.toDp(), parentHeight.toDp())) val childWidth = 40 val childHeight = 30 val childModifier = Modifier.size(DpSize(childWidth.toDp(), childHeight.toDp())) assertEquals( IntSize(childWidth, childHeight), calculateSizeFor(parentModifier, childModifier) ) assertEquals( IntSize(parentWidth, childHeight), calculateSizeFor(parentModifier, Modifier.fillMaxWidth().then(childModifier)) ) assertEquals( IntSize(childWidth, parentHeight), calculateSizeFor(parentModifier, Modifier.fillMaxHeight().then(childModifier)) ) assertEquals( IntSize(parentWidth, parentHeight), calculateSizeFor(parentModifier, Modifier.fillMaxSize().then(childModifier)) ) } @Test fun testFractionalFillModifier_correctSize_whenSmallerChild() = with(density) { val parentWidth = 100 val parentHeight = 80 val parentModifier = Modifier.requiredSize(parentWidth.toDp(), parentHeight.toDp()) val childWidth = 40 val childHeight = 30 val childModifier = Modifier.size(childWidth.toDp(), childHeight.toDp()) assertEquals( IntSize(childWidth, childHeight), calculateSizeFor(parentModifier, childModifier) ) assertEquals( IntSize(parentWidth / 2, childHeight), calculateSizeFor(parentModifier, Modifier.fillMaxWidth(0.5f).then(childModifier)) ) assertEquals( IntSize(childWidth, parentHeight / 2), calculateSizeFor(parentModifier, Modifier.fillMaxHeight(0.5f).then(childModifier)) ) assertEquals( IntSize(parentWidth / 2, parentHeight / 2), calculateSizeFor(parentModifier, Modifier.fillMaxSize(0.5f).then(childModifier)) ) } @Test fun testFractionalFillModifier_correctSize_whenLargerChild() = with(density) { val parentWidth = 100 val parentHeight = 80 val parentModifier = Modifier.requiredSize(parentWidth.toDp(), parentHeight.toDp()) val childWidth = 70 val childHeight = 50 val childModifier = Modifier.size(childWidth.toDp(), childHeight.toDp()) assertEquals( IntSize(childWidth, childHeight), calculateSizeFor(parentModifier, childModifier) ) assertEquals( IntSize(parentWidth / 2, childHeight), calculateSizeFor(parentModifier, Modifier.fillMaxWidth(0.5f).then(childModifier)) ) assertEquals( IntSize(childWidth, parentHeight / 2), calculateSizeFor(parentModifier, Modifier.fillMaxHeight(0.5f).then(childModifier)) ) assertEquals( IntSize(parentWidth / 2, parentHeight / 2), calculateSizeFor(parentModifier, Modifier.fillMaxSize(0.5f).then(childModifier)) ) } @Test fun testFractionalFillModifier_coerced() = with(density) { val childMinWidth = 40 val childMinHeight = 30 val childMaxWidth = 60 val childMaxHeight = 50 val childModifier = Modifier.requiredSizeIn( childMinWidth.toDp(), childMinHeight.toDp(), childMaxWidth.toDp(), childMaxHeight.toDp() ) assertEquals( IntSize(childMinWidth, childMinHeight), calculateSizeFor(Modifier, childModifier.then(Modifier.fillMaxSize(-0.1f))) ) assertEquals( IntSize(childMinWidth, childMinHeight), calculateSizeFor(Modifier, childModifier.then(Modifier.fillMaxSize(0.1f))) ) assertEquals( IntSize(childMaxWidth, childMaxHeight), calculateSizeFor(Modifier, childModifier.then(Modifier.fillMaxSize(1.2f))) ) } @Test fun testFillModifier_noChangeIntrinsicMeasurements() = with(density) { verifyIntrinsicMeasurements(Modifier.fillMaxWidth()) verifyIntrinsicMeasurements(Modifier.fillMaxHeight()) verifyIntrinsicMeasurements(Modifier.fillMaxSize()) } @Test fun testDefaultMinSizeModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.defaultMinSize(40.toDp(), 50.toDp())) { Container(Modifier.aspectRatio(1f)) { } } } ) { minIntrinsicWidth, minIntrinsicHeight, _, _ -> // Min width. assertEquals(40, minIntrinsicWidth(0)) assertEquals(40, minIntrinsicWidth(35)) assertEquals(55, minIntrinsicWidth(55)) assertEquals(40, minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(50, minIntrinsicHeight(0)) assertEquals(50, minIntrinsicHeight(35)) assertEquals(55, minIntrinsicHeight(55)) assertEquals(50, minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(40, minIntrinsicWidth(0)) assertEquals(40, minIntrinsicWidth(35)) assertEquals(55, minIntrinsicWidth(55)) assertEquals(40, minIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(50, minIntrinsicHeight(0)) assertEquals(50, minIntrinsicHeight(35)) assertEquals(55, minIntrinsicHeight(55)) assertEquals(50, minIntrinsicHeight(Constraints.Infinity)) } } @Test fun testInspectableParameter() { checkModifier(Modifier.requiredWidth(200.0.dp), "requiredWidth", 200.0.dp, listOf()) checkModifier(Modifier.requiredHeight(300.0.dp), "requiredHeight", 300.0.dp, listOf()) checkModifier(Modifier.requiredSize(400.0.dp), "requiredSize", 400.0.dp, listOf()) checkModifier( Modifier.requiredSize(100.0.dp, 200.0.dp), "requiredSize", null, listOf( ValueElement("width", 100.0.dp), ValueElement("height", 200.0.dp) ) ) checkModifier( Modifier.requiredWidthIn(100.0.dp, 200.0.dp), "requiredWidthIn", null, listOf(ValueElement("min", 100.0.dp), ValueElement("max", 200.0.dp)) ) checkModifier( Modifier.requiredHeightIn(10.0.dp, 200.0.dp), "requiredHeightIn", null, listOf(ValueElement("min", 10.0.dp), ValueElement("max", 200.0.dp)) ) checkModifier( Modifier.requiredSizeIn(10.dp, 20.dp, 30.dp, 40.dp), "requiredSizeIn", null, listOf( ValueElement("minWidth", 10.dp), ValueElement("minHeight", 20.dp), ValueElement("maxWidth", 30.dp), ValueElement("maxHeight", 40.dp) ) ) checkModifier(Modifier.width(200.0.dp), "width", 200.0.dp, listOf()) checkModifier(Modifier.height(300.0.dp), "height", 300.0.dp, listOf()) checkModifier(Modifier.size(400.0.dp), "size", 400.0.dp, listOf()) checkModifier( Modifier.size(100.0.dp, 200.0.dp), "size", null, listOf(ValueElement("width", 100.0.dp), ValueElement("height", 200.0.dp)) ) checkModifier( Modifier.widthIn(100.0.dp, 200.0.dp), "widthIn", null, listOf(ValueElement("min", 100.0.dp), ValueElement("max", 200.0.dp)) ) checkModifier( Modifier.heightIn(10.0.dp, 200.0.dp), "heightIn", null, listOf(ValueElement("min", 10.0.dp), ValueElement("max", 200.0.dp)) ) checkModifier( Modifier.sizeIn(10.dp, 20.dp, 30.dp, 40.dp), "sizeIn", null, listOf( ValueElement("minWidth", 10.dp), ValueElement("minHeight", 20.dp), ValueElement("maxWidth", 30.dp), ValueElement("maxHeight", 40.dp) ) ) checkModifier( Modifier.fillMaxWidth(), "fillMaxWidth", null, listOf(ValueElement("fraction", 1.0f)) ) checkModifier( Modifier.fillMaxWidth(0.7f), "fillMaxWidth", null, listOf(ValueElement("fraction", 0.7f)) ) checkModifier( Modifier.fillMaxHeight(), "fillMaxHeight", null, listOf(ValueElement("fraction", 1.0f)) ) checkModifier( Modifier.fillMaxHeight(0.15f), "fillMaxHeight", null, listOf(ValueElement("fraction", 0.15f)) ) checkModifier( Modifier.fillMaxSize(), "fillMaxSize", null, listOf(ValueElement("fraction", 1.0f)) ) checkModifier( Modifier.fillMaxSize(0.25f), "fillMaxSize", null, listOf(ValueElement("fraction", 0.25f)) ) checkModifier( Modifier.wrapContentWidth(), "wrapContentWidth", null, listOf( ValueElement("align", Alignment.CenterHorizontally), ValueElement("unbounded", false) ) ) checkModifier( Modifier.wrapContentWidth(Alignment.End, true), "wrapContentWidth", null, listOf( ValueElement("align", Alignment.End), ValueElement("unbounded", true) ) ) checkModifier( Modifier.wrapContentHeight(), "wrapContentHeight", null, listOf( ValueElement("align", Alignment.CenterVertically), ValueElement("unbounded", false) ) ) checkModifier( Modifier.wrapContentHeight(Alignment.Bottom, true), "wrapContentHeight", null, listOf( ValueElement("align", Alignment.Bottom), ValueElement("unbounded", true) ) ) checkModifier( Modifier.wrapContentSize(), "wrapContentSize", null, listOf( ValueElement("align", Alignment.Center), ValueElement("unbounded", false) ) ) checkModifier( Modifier.wrapContentSize(Alignment.BottomCenter, true), "wrapContentSize", null, listOf( ValueElement("align", Alignment.BottomCenter), ValueElement("unbounded", true) ) ) checkModifier( Modifier.defaultMinSize(10.0.dp, 20.0.dp), "defaultMinSize", null, listOf(ValueElement("minWidth", 10.dp), ValueElement("minHeight", 20.dp)) ) } private fun checkModifier( modifier: Modifier, expectedName: String, expectedValue: Any?, expectedElements: List<ValueElement> ) { assertThat(modifier).isInstanceOf(InspectableValue::class.java) val parameter = modifier as InspectableValue assertThat(parameter.nameFallback).isEqualTo(expectedName) assertThat(parameter.valueOverride).isEqualTo(expectedValue) assertThat(parameter.inspectableElements.toList()).isEqualTo(expectedElements) } private fun calculateSizeFor(parentModifier: Modifier, modifier: Modifier): IntSize { val positionedLatch = CountDownLatch(1) val size = Ref<IntSize>() val position = Ref<Offset>() show { Box(parentModifier) { Box(modifier.saveLayoutInfo(size, position, positionedLatch)) } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) return size.value!! } private fun assertConstraints( incomingConstraints: Constraints, modifier: Modifier, expectedConstraints: Constraints ) { val latch = CountDownLatch(1) // Capture constraints and assert on test thread var actualConstraints: Constraints? = null // Clear contents before each test so that we don't recompose the BoxWithConstraints call; // doing so would recompose the old subcomposition with old constraints in the presence of // new content before the measurement performs explicit composition the new constraints. show({}) show { Layout({ BoxWithConstraints(modifier) { actualConstraints = constraints latch.countDown() } }) { measurables, _ -> measurables[0].measure(incomingConstraints) layout(0, 0) { } } } assertTrue(latch.await(1, TimeUnit.SECONDS)) assertEquals(expectedConstraints, actualConstraints) } private fun verifyIntrinsicMeasurements(expandedModifier: Modifier) = with(density) { // intrinsic measurements do not change with the ExpandedModifier testIntrinsics( @Composable { Container( expandedModifier.then(Modifier.aspectRatio(2f)), width = 30.toDp(), height = 40.toDp() ) { } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Width assertEquals(40, minIntrinsicWidth(20)) assertEquals(30, minIntrinsicWidth(Constraints.Infinity)) assertEquals(40, maxIntrinsicWidth(20)) assertEquals(30, maxIntrinsicWidth(Constraints.Infinity)) // Height assertEquals(20, minIntrinsicHeight(40)) assertEquals(40, minIntrinsicHeight(Constraints.Infinity)) assertEquals(20, maxIntrinsicHeight(40)) assertEquals(40, maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun test2DWrapContentSize() = with(density) { val sizeDp = 50.dp val size = sizeDp.roundToPx() val positionedLatch = CountDownLatch(2) val alignSize = Ref<IntSize>() val alignPosition = Ref<Offset>() val childSize = Ref<IntSize>() val childPosition = Ref<Offset>() show { Container(Modifier.saveLayoutInfo(alignSize, alignPosition, positionedLatch)) { Container( Modifier.fillMaxSize() .wrapContentSize(Alignment.BottomEnd) .size(sizeDp) .saveLayoutInfo(childSize, childPosition, positionedLatch) ) { } } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) val root = findComposeView() waitForDraw(root) assertEquals(IntSize(root.width, root.height), alignSize.value) assertEquals(Offset(0f, 0f), alignPosition.value) assertEquals(IntSize(size, size), childSize.value) assertEquals( Offset(root.width - size.toFloat(), root.height - size.toFloat()), childPosition.value ) } @Test fun test1DWrapContentSize() = with(density) { val sizeDp = 50.dp val size = sizeDp.roundToPx() val positionedLatch = CountDownLatch(2) val alignSize = Ref<IntSize>() val alignPosition = Ref<Offset>() val childSize = Ref<IntSize>() val childPosition = Ref<Offset>() show { Container( Modifier.saveLayoutInfo( size = alignSize, position = alignPosition, positionedLatch = positionedLatch ) ) { Container( Modifier.fillMaxSize() .wrapContentWidth(Alignment.End) .width(sizeDp) .saveLayoutInfo(childSize, childPosition, positionedLatch) ) { } } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) val root = findComposeView() waitForDraw(root) assertEquals(IntSize(root.width, root.height), alignSize.value) assertEquals(Offset(0f, 0f), alignPosition.value) assertEquals(IntSize(size, root.height), childSize.value) assertEquals(Offset(root.width - size.toFloat(), 0f), childPosition.value) } @Test fun testWrapContentSize_rtl() = with(density) { val sizeDp = 200.toDp() val size = sizeDp.roundToPx() val positionedLatch = CountDownLatch(3) val childSize = Array(3) { Ref<IntSize>() } val childPosition = Array(3) { Ref<Offset>() } show { CompositionLocalProvider(LocalLayoutDirection provides LayoutDirection.Rtl) { Box(Modifier.fillMaxSize()) { Box(Modifier.fillMaxSize().wrapContentSize(Alignment.TopStart)) { Box( Modifier.size(sizeDp) .saveLayoutInfo(childSize[0], childPosition[0], positionedLatch) ) { } } Box(Modifier.fillMaxSize().wrapContentHeight(Alignment.CenterVertically)) { Box( Modifier.size(sizeDp) .saveLayoutInfo(childSize[1], childPosition[1], positionedLatch) ) { } } Box(Modifier.fillMaxSize().wrapContentSize(Alignment.BottomEnd)) { Box( Modifier.size(sizeDp) .saveLayoutInfo(childSize[2], childPosition[2], positionedLatch) ) { } } } } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) val root = findComposeView() waitForDraw(root) assertEquals( Offset((root.width - size).toFloat(), 0f), childPosition[0].value ) assertEquals( Offset( (root.width - size).toFloat(), ((root.height - size) / 2).toFloat() ), childPosition[1].value ) assertEquals( Offset(0f, (root.height - size).toFloat()), childPosition[2].value ) } @Test fun testModifier_wrapsContent() = with(density) { val contentSize = 50.dp val size = Ref<IntSize>() val latch = CountDownLatch(1) show { Container { Container(Modifier.saveLayoutInfo(size, Ref(), latch)) { Container( Modifier.wrapContentSize(Alignment.TopStart) .size(contentSize) ) {} } } } assertTrue(latch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(contentSize.roundToPx(), contentSize.roundToPx()), size.value) } @Test fun testWrapContentSize_wrapsContent_whenMeasuredWithInfiniteConstraints() = with(density) { val sizeDp = 50.dp val size = sizeDp.roundToPx() val positionedLatch = CountDownLatch(2) val alignSize = Ref<IntSize>() val alignPosition = Ref<Offset>() val childSize = Ref<IntSize>() val childPosition = Ref<Offset>() show { Layout( content = { Container( Modifier.saveLayoutInfo(alignSize, alignPosition, positionedLatch) ) { Container( Modifier.wrapContentSize(Alignment.BottomEnd) .size(sizeDp) .saveLayoutInfo(childSize, childPosition, positionedLatch) ) { } } }, measurePolicy = { measurables, constraints -> val placeable = measurables.first().measure(Constraints()) layout(constraints.maxWidth, constraints.maxHeight) { placeable.placeRelative(0, 0) } } ) } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) val root = findComposeView() waitForDraw(root) assertEquals(IntSize(size, size), alignSize.value) assertEquals(Offset(0f, 0f), alignPosition.value) assertEquals(IntSize(size, size), childSize.value) assertEquals(Offset(0f, 0f), childPosition.value) } @Test fun testWrapContentSize_respectsMinConstraints() = with(density) { val sizeDp = 50.dp val size = sizeDp.roundToPx() val doubleSizeDp = sizeDp * 2 val doubleSize = doubleSizeDp.roundToPx() val positionedLatch = CountDownLatch(2) val wrapSize = Ref<IntSize>() val childSize = Ref<IntSize>() val childPosition = Ref<Offset>() show { Container(Modifier.wrapContentSize(Alignment.TopStart)) { Layout( modifier = Modifier.onGloballyPositioned { coordinates: LayoutCoordinates -> wrapSize.value = coordinates.size positionedLatch.countDown() }, content = { Container( Modifier.wrapContentSize(Alignment.Center) .size(sizeDp) .saveLayoutInfo(childSize, childPosition, positionedLatch) ) { } }, measurePolicy = { measurables, incomingConstraints -> val measurable = measurables.first() val constraints = incomingConstraints.constrain( Constraints( minWidth = doubleSizeDp.roundToPx(), minHeight = doubleSizeDp.roundToPx() ) ) val placeable = measurable.measure(constraints) layout(placeable.width, placeable.height) { placeable.placeRelative(IntOffset.Zero) } } ) } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) assertEquals(IntSize(doubleSize, doubleSize), wrapSize.value) assertEquals(IntSize(size, size), childSize.value) assertEquals( Offset( ((doubleSize - size) / 2f).roundToInt().toFloat(), ((doubleSize - size) / 2f).roundToInt().toFloat() ), childPosition.value ) } @Test fun testWrapContentSize_unbounded() = with(density) { val outerSize = 10f val innerSize = 20f val positionedLatch = CountDownLatch(4) show { Box( Modifier.requiredSize(outerSize.toDp()) .onGloballyPositioned { assertEquals(outerSize, it.size.width.toFloat()) positionedLatch.countDown() } ) { Box( Modifier.wrapContentSize(Alignment.BottomEnd, unbounded = true) .requiredSize(innerSize.toDp()) .onGloballyPositioned { assertEquals( Offset(outerSize - innerSize, outerSize - innerSize), it.positionInParent() ) positionedLatch.countDown() } ) Box( Modifier.wrapContentWidth(Alignment.End, unbounded = true) .requiredSize(innerSize.toDp()) .onGloballyPositioned { assertEquals(outerSize - innerSize, it.positionInParent().x) positionedLatch.countDown() } ) Box( Modifier.wrapContentHeight(Alignment.Bottom, unbounded = true) .requiredSize(innerSize.toDp()) .onGloballyPositioned { assertEquals(outerSize - innerSize, it.positionInParent().y) positionedLatch.countDown() } ) } } assertTrue(positionedLatch.await(1, TimeUnit.SECONDS)) } @Test fun test2DAlignedModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics( @Composable { Container(Modifier.wrapContentSize(Alignment.TopStart).aspectRatio(2f)) { } } ) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(25.dp.roundToPx() * 2, minIntrinsicWidth(25.dp.roundToPx())) assertEquals(0.dp.roundToPx(), minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(0, minIntrinsicWidth(0)) assertEquals( (50.dp.roundToPx() / 2f).roundToInt(), minIntrinsicHeight(50.dp.roundToPx()) ) assertEquals(0.dp.roundToPx(), minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(25.dp.roundToPx() * 2, maxIntrinsicWidth(25.dp.roundToPx())) assertEquals(0.dp.roundToPx(), maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(0, minIntrinsicWidth(0)) assertEquals( (50.dp.roundToPx() / 2f).roundToInt(), maxIntrinsicHeight(50.dp.roundToPx()) ) assertEquals(0.dp.roundToPx(), maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun test1DAlignedModifier_hasCorrectIntrinsicMeasurements() = with(density) { testIntrinsics({ Container( Modifier.wrapContentHeight(Alignment.CenterVertically) .aspectRatio(2f) ) { } }) { minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, maxIntrinsicHeight -> // Min width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(25.dp.roundToPx() * 2, minIntrinsicWidth(25.dp.roundToPx())) assertEquals(0.dp.roundToPx(), minIntrinsicWidth(Constraints.Infinity)) // Min height. assertEquals(0, minIntrinsicWidth(0)) assertEquals( (50.dp.roundToPx() / 2f).roundToInt(), minIntrinsicHeight(50.dp.roundToPx()) ) assertEquals(0.dp.roundToPx(), minIntrinsicHeight(Constraints.Infinity)) // Max width. assertEquals(0, minIntrinsicWidth(0)) assertEquals(25.dp.roundToPx() * 2, maxIntrinsicWidth(25.dp.roundToPx())) assertEquals(0.dp.roundToPx(), maxIntrinsicWidth(Constraints.Infinity)) // Max height. assertEquals(0, minIntrinsicWidth(0)) assertEquals( (50.dp.roundToPx() / 2f).roundToInt(), maxIntrinsicHeight(50.dp.roundToPx()) ) assertEquals(0.dp.roundToPx(), maxIntrinsicHeight(Constraints.Infinity)) } } @Test fun testAlignedModifier_alignsCorrectly_whenOddDimensions_endAligned() = with(density) { // Given a 100 x 100 pixel container, we want to make sure that when aligning a 1 x 1 pixel // child to both ends (bottom, and right) we correctly position children at the last // possible pixel, and avoid rounding issues. Previously we first centered the coordinates, // and then aligned after, so the maths would actually be (99 / 2) * 2, which incorrectly // ends up at 100 (Int rounds up) - so the last pixels in both directions just wouldn't // be visible. val parentSize = 100.toDp() val childSizeDp = 1.toDp() val childSizeIpx = childSizeDp.roundToPx() val positionedLatch = CountDownLatch(2) val alignSize = Ref<IntSize>() val alignPosition = Ref<Offset>() val childSize = Ref<IntSize>() val childPosition = Ref<Offset>() show { Layout( content = { Container( Modifier.size(parentSize) .saveLayoutInfo(alignSize, alignPosition, positionedLatch) ) { Container( Modifier.fillMaxSize() .wrapContentSize(Alignment.BottomEnd) .size(childSizeDp) .saveLayoutInfo(childSize, childPosition, positionedLatch) ) { } } }, measurePolicy = { measurables, constraints -> val placeable = measurables.first().measure(Constraints()) layout(constraints.maxWidth, constraints.maxHeight) { placeable.placeRelative(0, 0) } } ) } positionedLatch.await(1, TimeUnit.SECONDS) val root = findComposeView() waitForDraw(root) assertEquals(IntSize(childSizeIpx, childSizeIpx), childSize.value) assertEquals( Offset( (alignSize.value!!.width - childSizeIpx).toFloat(), (alignSize.value!!.height - childSizeIpx).toFloat() ), childPosition.value ) } @Test @FlakyTest(bugId = 183713100) fun testModifiers_doNotCauseUnnecessaryRemeasure() { var first by mutableStateOf(true) var totalMeasures = 0 @Composable fun CountMeasures(modifier: Modifier) { Layout( content = {}, modifier = modifier, measurePolicy = { _, _ -> ++totalMeasures layout(0, 0) {} } ) } show { Box { if (first) Box {} else Row {} CountMeasures(Modifier.size(10.dp)) CountMeasures(Modifier.requiredSize(10.dp)) CountMeasures(Modifier.wrapContentSize(Alignment.BottomEnd)) CountMeasures(Modifier.fillMaxSize(0.8f)) CountMeasures(Modifier.defaultMinSize(10.dp, 20.dp)) } } val root = findComposeView() waitForDraw(root) activityTestRule.runOnUiThread { assertEquals(5, totalMeasures) first = false } activityTestRule.runOnUiThread { assertEquals(5, totalMeasures) } } @Test fun testModifiers_equals() { assertEquals(Modifier.size(10.dp, 20.dp), Modifier.size(10.dp, 20.dp)) assertEquals(Modifier.requiredSize(10.dp, 20.dp), Modifier.requiredSize(10.dp, 20.dp)) assertEquals( Modifier.wrapContentSize(Alignment.BottomEnd), Modifier.wrapContentSize(Alignment.BottomEnd) ) assertEquals(Modifier.fillMaxSize(0.8f), Modifier.fillMaxSize(0.8f)) assertEquals(Modifier.defaultMinSize(10.dp, 20.dp), Modifier.defaultMinSize(10.dp, 20.dp)) assertNotEquals(Modifier.size(10.dp, 20.dp), Modifier.size(20.dp, 10.dp)) assertNotEquals(Modifier.requiredSize(10.dp, 20.dp), Modifier.requiredSize(20.dp, 10.dp)) assertNotEquals( Modifier.wrapContentSize(Alignment.BottomEnd), Modifier.wrapContentSize(Alignment.BottomCenter) ) assertNotEquals(Modifier.fillMaxSize(0.8f), Modifier.fillMaxSize()) assertNotEquals( Modifier.defaultMinSize(10.dp, 20.dp), Modifier.defaultMinSize(20.dp, 10.dp) ) } @Test fun testIntrinsicMeasurements_notQueriedWhenConstraintsAreFixed() { @Composable fun ErrorIntrinsicsLayout(modifier: Modifier) { Layout( {}, modifier, object : MeasurePolicy { override fun MeasureScope.measure( measurables: List<Measurable>, constraints: Constraints ): MeasureResult { return layout(0, 0) {} } override fun IntrinsicMeasureScope.minIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ) = error("Error intrinsic") override fun IntrinsicMeasureScope.minIntrinsicHeight( measurables: List<IntrinsicMeasurable>, width: Int ) = error("Error intrinsic") override fun IntrinsicMeasureScope.maxIntrinsicWidth( measurables: List<IntrinsicMeasurable>, height: Int ) = error("Error intrinsic") override fun IntrinsicMeasureScope.maxIntrinsicHeight( measurables: List<IntrinsicMeasurable>, width: Int ) = error("Error intrinsic") } ) } show { Box(Modifier.width(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) } Box(Modifier.width(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) } Box(Modifier.width(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) } Box(Modifier.width(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) } Box(Modifier.requiredWidth(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) } Box(Modifier.requiredWidth(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) } Box(Modifier.requiredWidth(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) } Box(Modifier.requiredWidth(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.width(1.dp)) } Box(Modifier.height(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) } Box(Modifier.height(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) } Box(Modifier.height(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) } Box(Modifier.height(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) } Box(Modifier.requiredHeight(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) } Box(Modifier.requiredHeight(IntrinsicSize.Min)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) } Box(Modifier.requiredHeight(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) } Box(Modifier.requiredHeight(IntrinsicSize.Max)) { ErrorIntrinsicsLayout(Modifier.height(1.dp)) } } // The test tests that the measure pass should not crash. val root = findComposeView() waitForDraw(root) } @Test fun sizeModifiers_doNotCauseCrashesWhenCreatingConstraints() { show { Box(Modifier.sizeIn(minWidth = -1.dp)) Box(Modifier.sizeIn(minWidth = 10.dp, maxWidth = 5.dp)) Box(Modifier.sizeIn(minHeight = -1.dp)) Box(Modifier.sizeIn(minHeight = 10.dp, maxHeight = 5.dp)) Box( Modifier.sizeIn( minWidth = Dp.Infinity, maxWidth = Dp.Infinity, minHeight = Dp.Infinity, maxHeight = Dp.Infinity ) ) Box(Modifier.defaultMinSize(minWidth = -1.dp, minHeight = -1.dp)) } val root = findComposeView() waitForDraw(root) } }
apache-2.0
48eef42d5286eda17af6e3b1435ec83d
38.351621
100
0.54656
5.518184
false
true
false
false
androidx/androidx
camera/integration-tests/viewtestapp/src/main/java/androidx/camera/integration/view/ToneMappingSurfaceProcessor.kt
3
5599
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.camera.integration.view import android.graphics.SurfaceTexture import android.graphics.SurfaceTexture.OnFrameAvailableListener import android.os.Handler import android.os.Looper import android.view.Surface import androidx.annotation.VisibleForTesting import androidx.camera.core.SurfaceOutput import androidx.camera.core.SurfaceProcessor import androidx.camera.core.SurfaceRequest import androidx.camera.core.impl.utils.Threads.checkMainThread import androidx.camera.core.impl.utils.executor.CameraXExecutors.mainThreadExecutor import androidx.camera.core.processing.OpenGlRenderer import androidx.camera.core.processing.ShaderProvider /** * A processor that applies tone mapping on camera output. * * <p>The thread safety is guaranteed by using the main thread. */ class ToneMappingSurfaceProcessor : SurfaceProcessor, OnFrameAvailableListener { companion object { // A fragment shader that applies a yellow hue. private val TONE_MAPPING_SHADER_PROVIDER = object : ShaderProvider { override fun createFragmentShader(sampler: String, fragCoords: String): String { return """ #extension GL_OES_EGL_image_external : require precision mediump float; uniform samplerExternalOES $sampler; varying vec2 $fragCoords; void main() { vec4 sampleColor = texture2D($sampler, $fragCoords); gl_FragColor = vec4( sampleColor.r * 0.5 + sampleColor.g * 0.8 + sampleColor.b * 0.3, sampleColor.r * 0.4 + sampleColor.g * 0.7 + sampleColor.b * 0.2, sampleColor.r * 0.3 + sampleColor.g * 0.5 + sampleColor.b * 0.1, 1.0); } """ } } } private val mainThreadHandler: Handler = Handler(Looper.getMainLooper()) private val glRenderer: OpenGlRenderer = OpenGlRenderer() private val outputSurfaces: MutableMap<SurfaceOutput, Surface> = mutableMapOf() private val textureTransform: FloatArray = FloatArray(16) private val surfaceTransform: FloatArray = FloatArray(16) private var isReleased = false // For testing. private var surfaceRequested = false // For testing. private var outputSurfaceProvided = false init { mainThreadExecutor().execute { glRenderer.init(TONE_MAPPING_SHADER_PROVIDER) } } override fun onInputSurface(surfaceRequest: SurfaceRequest) { checkMainThread() if (isReleased) { surfaceRequest.willNotProvideSurface() return } surfaceRequested = true val surfaceTexture = SurfaceTexture(glRenderer.textureName) surfaceTexture.setDefaultBufferSize( surfaceRequest.resolution.width, surfaceRequest.resolution.height ) val surface = Surface(surfaceTexture) surfaceRequest.provideSurface(surface, mainThreadExecutor()) { surfaceTexture.setOnFrameAvailableListener(null) surfaceTexture.release() surface.release() } surfaceTexture.setOnFrameAvailableListener(this, mainThreadHandler) } override fun onOutputSurface(surfaceOutput: SurfaceOutput) { checkMainThread() outputSurfaceProvided = true if (isReleased) { surfaceOutput.close() return } val surface = surfaceOutput.getSurface(mainThreadExecutor()) { surfaceOutput.close() outputSurfaces.remove(surfaceOutput)?.let { removedSurface -> glRenderer.unregisterOutputSurface(removedSurface) } } glRenderer.registerOutputSurface(surface) outputSurfaces[surfaceOutput] = surface } @VisibleForTesting fun isSurfaceRequestedAndProvided(): Boolean { return surfaceRequested && outputSurfaceProvided } fun release() { checkMainThread() if (isReleased) { return } // Once release is called, we can stop sending frame to output surfaces. for (surfaceOutput in outputSurfaces.keys) { surfaceOutput.close() } outputSurfaces.clear() glRenderer.release() isReleased = true } override fun onFrameAvailable(surfaceTexture: SurfaceTexture) { checkMainThread() if (isReleased) { return } surfaceTexture.updateTexImage() surfaceTexture.getTransformMatrix(textureTransform) for (entry in outputSurfaces.entries.iterator()) { val surface = entry.value val surfaceOutput = entry.key surfaceOutput.updateTransformMatrix(surfaceTransform, textureTransform) glRenderer.render(surfaceTexture.timestamp, surfaceTransform, surface) } } }
apache-2.0
ba81f215310c72895289aacca89ee0d9
35.842105
92
0.65851
5.282075
false
false
false
false
lytefast/flex-input
flexinput/src/main/java/com/lytefast/flexinput/model/Photo.kt
1
2123
package com.lytefast.flexinput.model import android.content.ContentResolver import android.content.ContentUris import android.net.Uri import android.os.AsyncTask import android.os.Parcel import android.os.Parcelable import android.provider.MediaStore import android.util.Log /** * Represents a photo obtained from the [MediaStore.Images.Media.EXTERNAL_CONTENT_URI] store. * * @author Sam Shih */ class Photo : Attachment<String> { constructor(id: Long, uri: Uri, displayName: String, photoDataLocation: String?) : super(id, uri, displayName, photoDataLocation) constructor(parcelIn: Parcel) : super(parcelIn) fun getThumbnailUri(contentResolver: ContentResolver): Uri? { val cursor = contentResolver.query( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, arrayOf(MediaStore.Images.Thumbnails._ID), "${MediaStore.Images.Thumbnails.IMAGE_ID} = ? AND KIND = ?", arrayOf(id.toString(), Integer.toString(MediaStore.Images.Thumbnails.MINI_KIND)), null) if (cursor == null || !cursor.moveToFirst()) { asyncGenerateThumbnail(contentResolver) cursor?.close() return uri // Slow due to photo size and manipulation but better than nothing } cursor.use { val thumbId = it.getLong(0) return ContentUris.withAppendedId( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, thumbId) } } /** * Generate thumbnail for next time. */ private fun asyncGenerateThumbnail(contentResolver: ContentResolver) { AsyncTask.execute { try { MediaStore.Images.Thumbnails.getThumbnail( contentResolver, id, MediaStore.Images.Thumbnails.MINI_KIND, null) } catch (e: Exception) { Log.v(Photo::class.java.name, "Error generating thumbnail for photo $id.") } } } companion object { @Suppress("unused") // Used as part of Parcellable @JvmField val CREATOR = object : Parcelable.Creator<Photo> { override fun createFromParcel(parcel: Parcel): Photo = Photo(parcel) override fun newArray(size: Int): Array<Photo?> = arrayOfNulls(size) } } }
mit
bbd12194e807ce22e1ec931caa490135
31.166667
95
0.700895
4.246
false
false
false
false
jean79/yested
src/main/kotlin/net/yested/utils/jquery.kt
2
2003
package net.yested.utils import jquery.JQuery import org.w3c.dom.Element import org.w3c.dom.HTMLElement import org.w3c.dom.Window class Position(val top:Int, val left:Int) class JSArray(val length:Int) @Suppress("NOTHING_TO_INLINE") inline fun JQuery.sortable(options: dynamic):Unit = asDynamic().sortable(options) @Suppress("NOTHING_TO_INLINE") inline fun JQuery.each(noinline func:(index:Int, element:HTMLElement)->Unit):Unit = asDynamic().each(func) @Suppress("NOTHING_TO_INLINE") inline fun JQuery.disableSelection():Unit = asDynamic().disableSelection() @Suppress("NOTHING_TO_INLINE") inline fun JQuery.on(event:String, noinline handler:(dynamic)->Unit): Unit = asDynamic().on(event, handler) @Suppress("NOTHING_TO_INLINE") inline fun JQuery.off(event:String): Unit = asDynamic().off(event) @Suppress("NOTHING_TO_INLINE") inline fun JQuery.keypress(noinline handler: (event:dynamic) -> Unit): Unit = asDynamic().keypress(handler) @Suppress("NOTHING_TO_INLINE") inline fun JQuery.css(property:String):String = asDynamic().css(property) @Suppress("NOTHING_TO_INLINE") inline fun JQuery.css(property:String, value:String):String = asDynamic().css(property, value) @Suppress("NOTHING_TO_INLINE") inline fun JQuery.offset():Position = asDynamic().offset() @Suppress("NOTHING_TO_INLINE") inline fun JQuery.scrollLeft():Int = asDynamic().scrollLeft() @Suppress("NOTHING_TO_INLINE") inline fun JQuery.scrollTop():Int = asDynamic().scrollTop() @Suppress("NOTHING_TO_INLINE") inline fun JQuery.closest(element: Element):JSArray = asDynamic().closest(element) @JsName("$") external fun jq(window: Window): JQuery = definedExternally external interface JQStatic { //throttle: https://github.com/cowboy/jquery-throttle-debounce fun <EVENT> throttle(duration:Int, handler:(event:EVENT) -> Unit): Function1<EVENT, Unit> } @JsName("$") external var jqStatic: JQStatic fun <M> throttle(duration:Int, handler:(event:M) -> Unit): Function1<M, Unit> = jqStatic.throttle(duration, handler)
mit
de233b586d37ccc59afb81995f3c7780
32.966102
117
0.752371
3.507881
false
false
false
false
j-selby/EscapistsRuntime
core/src/main/java/net/jselby/escapists/data/chunks/Globals.kt
1
1322
package net.jselby.escapists.data.chunks import net.jselby.escapists.data.Chunk import net.jselby.escapists.util.ByteReader class GlobalStrings : Chunk() { lateinit var data: Array<String?> override fun init(buffer: ByteReader, length: Int) { val l = buffer.unsignedInt.toInt() data = arrayOfNulls<String>(l) for (i in 0..l - 1) { data[i] = buffer.string } } } class GlobalValues : Chunk() { lateinit var values: Array<Number?> override fun init(buffer: ByteReader, length: Int) { val numberOfItems = buffer.unsignedShort val tempList = arrayOfNulls<ByteReader?>(numberOfItems); for (i in 0..numberOfItems - 1) { tempList[i] = ByteReader(buffer.getBytes(4)); } values = arrayOfNulls<Number?>(numberOfItems) for (i in 0..numberOfItems - 1) { val reader = tempList[i]!!; val value : Number; val type = buffer.unsignedByte.toInt() if (type == 2) { // Float/Double value = reader.float } else if (type == 0) { // Int value = reader.int } else { throw IllegalArgumentException("Invalid GlobalValue type $type."); } values[i] = value } } }
mit
e21ddf211e9cb4d104c4f9316b62d4f7
28.377778
82
0.566566
4.237179
false
false
false
false
goldmansachs/obevo
obevo-db/src/main/java/com/gs/obevo/db/impl/core/changeauditdao/SameSchemaChangeAuditDao.kt
1
21749
/** * Copyright 2017 Goldman Sachs. * 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.gs.obevo.db.impl.core.changeauditdao import com.gs.obevo.api.appdata.Change import com.gs.obevo.api.appdata.ChangeIncremental import com.gs.obevo.api.appdata.ChangeKey import com.gs.obevo.api.appdata.ChangeRerunnable import com.gs.obevo.api.appdata.DeployExecution import com.gs.obevo.api.appdata.DeployExecutionImpl import com.gs.obevo.api.appdata.DeployExecutionStatus import com.gs.obevo.api.appdata.PhysicalSchema import com.gs.obevo.api.platform.AuditLock import com.gs.obevo.api.platform.ChangeAuditDao import com.gs.obevo.api.platform.ChangeType import com.gs.obevo.db.api.appdata.DbEnvironment import com.gs.obevo.db.api.appdata.Grant import com.gs.obevo.db.api.appdata.GrantTargetType import com.gs.obevo.db.api.appdata.Permission import com.gs.obevo.db.api.platform.DbChangeTypeBehavior import com.gs.obevo.db.api.platform.SqlExecutor import com.gs.obevo.dbmetadata.api.DaSchemaInfoLevel import com.gs.obevo.dbmetadata.api.DaTable import com.gs.obevo.dbmetadata.api.DbMetadataManager import com.gs.obevo.impl.ChangeTypeBehaviorRegistry import com.gs.obevo.util.VisibleForTesting import com.gs.obevo.util.knex.InternMap import org.apache.commons.dbutils.handlers.MapListHandler import org.eclipse.collections.api.list.ImmutableList import org.eclipse.collections.impl.block.function.checked.ThrowingFunction import org.eclipse.collections.impl.factory.Lists import org.eclipse.collections.impl.factory.Multimaps import org.eclipse.collections.impl.factory.Sets import org.joda.time.DateTime import org.joda.time.format.DateTimeFormat import org.slf4j.LoggerFactory import java.sql.Connection import java.sql.Timestamp /** * AuditDao that will write the audit to the same db schema as the Change audit */ class SameSchemaChangeAuditDao(private val env: DbEnvironment, private val sqlExecutor: SqlExecutor, private val dbMetadataManager: DbMetadataManager, private val deployUserId: String, private val deployExecutionDao: SameSchemaDeployExecutionDao, private val changeTypeBehaviorRegistry: ChangeTypeBehaviorRegistry) : ChangeAuditDao { private val dbChangeTable: String private val changeNameColumn: String private val changeTypeColumn: String private val deployUserIdColumn: String private val timeInsertedColumn: String private val timeUpdatedColumn: String private val rollbackContentColumn: String private val insertDeployExecutionIdColumn: String private val updateDeployExecutionIdColumn: String private val currentTimestamp: Timestamp get() = Timestamp(DateTime().millis) init { val convertDbObjectName = env.platform.convertDbObjectName() this.dbChangeTable = convertDbObjectName.valueOf(ChangeAuditDao.CHANGE_AUDIT_TABLE_NAME) // for backwards-compatibility, the dbChange table is named "ARTIFACTDEPLOYMENT". We hope to migrate existing tables eventually this.changeNameColumn = convertDbObjectName.valueOf("ARTIFACTPATH") // for backwards-compatibility, the changeName column is named "ArtifactPath". We hope to migrate existing tables eventually this.changeTypeColumn = convertDbObjectName.valueOf("CHANGETYPE") this.deployUserIdColumn = convertDbObjectName.valueOf("DEPLOY_USER_ID") this.timeInsertedColumn = convertDbObjectName.valueOf("TIME_INSERTED") this.timeUpdatedColumn = convertDbObjectName.valueOf("TIME_UPDATED") this.rollbackContentColumn = convertDbObjectName.valueOf("ROLLBACKCONTENT") this.insertDeployExecutionIdColumn = convertDbObjectName.valueOf("INSERTDEPLOYID") this.updateDeployExecutionIdColumn = convertDbObjectName.valueOf("UPDATEDEPLOYID") } override fun getAuditContainerName(): String { return dbChangeTable } override fun init() { for (schema in env.schemaNames) { val physicalSchema = env.getPhysicalSchema(schema) sqlExecutor.executeWithinContext(physicalSchema) { conn -> init(conn, schema) } } } private fun init(conn: Connection, schema: String) { val physicalSchema = env.getPhysicalSchema(schema) val artifactTable = queryAuditTable(physicalSchema) val jdbc = sqlExecutor.jdbcTemplate if (artifactTable == null) { val auditTableSql = get5_1Sql(physicalSchema) jdbc.execute(conn, auditTableSql) // We only grant SELECT access to PUBLIC so that folks can read the audit table without DBO permission // (we don't grant R/W access, as we assume whatever login that executes deployments already has DBO access, // and so can modify this table) val tableChangeType = changeTypeBehaviorRegistry.getChangeTypeBehavior(ChangeType.TABLE_STR) as DbChangeTypeBehavior if (env.platform.isPublicSchemaSupported) { tableChangeType.applyGrants(conn, physicalSchema, dbChangeTable, Lists.immutable.with(Permission("artifacTable", Lists.immutable.with(Grant(Lists.immutable.with("SELECT"), Multimaps.immutable.list.with(GrantTargetType.PUBLIC, "PUBLIC")))))) } } else { // We will still grant this here to make up for the existing DBs that did not have the grants given val tableChangeType = changeTypeBehaviorRegistry.getChangeTypeBehavior(ChangeType.TABLE_STR) as DbChangeTypeBehavior val schemaPlusTable = env.platform.getSubschemaPrefix(physicalSchema) + dbChangeTable // Here, we detect if we are on an older version of the table due to missing columns (added for version // 3.9.0). If we find the // columns are missing, we will add them and backfill if (artifactTable.getColumn(deployUserIdColumn) == null) { jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable, deployUserIdColumn, "VARCHAR(32)", env.platform.nullMarkerForCreateTable)) jdbc.execute(conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, deployUserIdColumn, "'backfill'")) } if (artifactTable.getColumn(timeUpdatedColumn) == null) { jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable, timeUpdatedColumn, env.platform.timestampType, env.platform .nullMarkerForCreateTable)) jdbc.execute( conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, timeUpdatedColumn, "'" + TIMESTAMP_FORMAT.print(DateTime()) + "'")) } if (artifactTable.getColumn(timeInsertedColumn) == null) { jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable, timeInsertedColumn, env.platform.timestampType, env.platform .nullMarkerForCreateTable)) jdbc.execute(conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, timeInsertedColumn, timeUpdatedColumn)) } if (artifactTable.getColumn(rollbackContentColumn) == null) { jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable, rollbackContentColumn, env.platform.textType, env.platform.nullMarkerForCreateTable)) // for the 3.12.0 release, we will also update the METADATA changeType value to STATICDATA jdbc.execute(conn, String.format("UPDATE %1\$s SET %2\$s='%3\$s' WHERE %2\$s='%4\$s'", schemaPlusTable, changeTypeColumn, ChangeType.STATICDATA_STR, OLD_STATICDATA_CHANGETYPE)) } if (artifactTable.getColumn(insertDeployExecutionIdColumn) == null) { jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable, insertDeployExecutionIdColumn, env.platform.bigIntType, env.platform.nullMarkerForCreateTable)) // If this column doesn't exist, it means we've just moved to the version w/ the DeployExecution table. // Let's add a row here to backfill the data. val deployExecution = DeployExecutionImpl("backfill", "backfill", schema, "0.0.0", currentTimestamp, false, false, null, "backfill", Sets.immutable.empty()) deployExecution.status = DeployExecutionStatus.SUCCEEDED deployExecutionDao.persistNewSameContext(conn, deployExecution, physicalSchema) jdbc.execute(conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, insertDeployExecutionIdColumn, deployExecution.id)) } if (artifactTable.getColumn(updateDeployExecutionIdColumn) == null) { jdbc.execute(conn, String.format("alter table %s ADD %s %s %s", schemaPlusTable, updateDeployExecutionIdColumn, env.platform.bigIntType, env.platform.nullMarkerForCreateTable)) jdbc.execute(conn, String.format("UPDATE %s SET %s = %s", schemaPlusTable, updateDeployExecutionIdColumn, insertDeployExecutionIdColumn)) } } } private fun queryAuditTable(physicalSchema: PhysicalSchema): DaTable? { return this.dbMetadataManager.getTableInfo(physicalSchema, dbChangeTable, DaSchemaInfoLevel().setRetrieveTableColumns(true)) } /** * SQL for the 5.0.x upgrade. * We keep in separate methods to allow for easy testing of the upgrades in SameSchemaChangeAuditDaoTest for different DBMSs */ @VisibleForTesting fun get5_0Sql(physicalSchema: PhysicalSchema): String { return if (env.auditTableSql != null) env.auditTableSql else String.format("CREATE TABLE " + env.platform.getSchemaPrefix(physicalSchema) + dbChangeTable + " ( \n" + " ARTFTYPE \tVARCHAR(31) NOT NULL,\n" + " " + changeNameColumn + "\tVARCHAR(255) NOT NULL,\n" + " OBJECTNAME \tVARCHAR(255) NOT NULL,\n" + " ACTIVE \tINTEGER %1\$s,\n" + " " + changeTypeColumn + " \tVARCHAR(255) %1\$s,\n" + " CONTENTHASH \tVARCHAR(255) %1\$s,\n" + " DBSCHEMA \tVARCHAR(255) %1\$s,\n" + " " + deployUserIdColumn + " \tVARCHAR(32) %1\$s,\n" + " " + timeInsertedColumn + " \t" + env.platform.timestampType + " %1\$s,\n" + " " + timeUpdatedColumn + " \t" + env.platform.timestampType + " %1\$s,\n" + " " + rollbackContentColumn + "\t" + env.platform.textType + " %1\$s,\n" + " CONSTRAINT ARTDEFPK PRIMARY KEY(" + changeNameColumn + ",OBJECTNAME)\n" + ") %2\$s\n", env.platform.nullMarkerForCreateTable, env.platform.getTableSuffixSql(env)) } /** * SQL for the 5.1.x upgrade. * We keep in separate methods to allow for easy testing of the upgrades in SameSchemaChangeAuditDaoTest for different DBMSs */ @VisibleForTesting fun get5_1Sql(physicalSchema: PhysicalSchema): String { return if (env.auditTableSql != null) env.auditTableSql else String.format("CREATE TABLE " + env.platform.getSchemaPrefix(physicalSchema) + dbChangeTable + " ( \n" + " ARTFTYPE \tVARCHAR(31) NOT NULL,\n" + " " + changeNameColumn + "\tVARCHAR(255) NOT NULL,\n" + " OBJECTNAME \tVARCHAR(255) NOT NULL,\n" + " ACTIVE \tINTEGER %1\$s,\n" + " " + changeTypeColumn + " \tVARCHAR(255) %1\$s,\n" + " CONTENTHASH \tVARCHAR(255) %1\$s,\n" + " DBSCHEMA \tVARCHAR(255) %1\$s,\n" + " " + deployUserIdColumn + " \tVARCHAR(32) %1\$s,\n" + " " + timeInsertedColumn + " \t" + env.platform.timestampType + " %1\$s,\n" + " " + timeUpdatedColumn + " \t" + env.platform.timestampType + " %1\$s,\n" + " " + rollbackContentColumn + "\t" + env.platform.textType + " %1\$s,\n" + " " + insertDeployExecutionIdColumn + "\t" + env.platform.bigIntType + " %1\$s,\n" + " " + updateDeployExecutionIdColumn + "\t" + env.platform.bigIntType + " %1\$s,\n" + " CONSTRAINT ARTDEFPK PRIMARY KEY(" + changeNameColumn + ",OBJECTNAME)\n" + ") %2\$s\n", env.platform.nullMarkerForCreateTable, env.platform.getTableSuffixSql(env)) } override fun insertNewChange(change: Change, deployExecution: DeployExecution) { sqlExecutor.executeWithinContext(change.getPhysicalSchema(env)) { conn -> insertNewChangeInternal(conn, change, deployExecution) } } private fun insertNewChangeInternal(conn: Connection, change: Change, deployExecution: DeployExecution) { val jdbcTemplate = sqlExecutor.jdbcTemplate val currentTimestamp = currentTimestamp jdbcTemplate.update( conn, "INSERT INTO " + env.platform.getSchemaPrefix(change.getPhysicalSchema(env)) + dbChangeTable + " (ARTFTYPE, DBSCHEMA, ACTIVE, CHANGETYPE, CONTENTHASH, " + changeNameColumn + ", OBJECTNAME, " + rollbackContentColumn + ", " + deployUserIdColumn + ", " + timeInsertedColumn + ", " + timeUpdatedColumn + ", " + insertDeployExecutionIdColumn + ", " + updateDeployExecutionIdColumn + ") " + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", if (change is ChangeIncremental) "I" else "R", change.schema, if (change.isActive) 1 else 0, change.changeType.name, change.contentHash, change.changeName, change.objectName, change.rollbackContent, deployUserId, currentTimestamp, currentTimestamp, deployExecution.id, deployExecution.id ) } override fun updateOrInsertChange(change: Change, deployExecution: DeployExecution) { sqlExecutor.executeWithinContext(change.getPhysicalSchema(env)) { conn -> val numRowsUpdated = updateInternal(conn, change, deployExecution) if (numRowsUpdated == 0) { insertNewChangeInternal(conn, change, deployExecution) } } } override fun getDeployedChanges(): ImmutableList<Change> { val convertDbObjectName = env.platform.convertDbObjectName() val artfs = env.schemaNames.flatMap { schema -> val deployExecutionsById = deployExecutionDao.getDeployExecutions(schema).associateBy(DeployExecution::getId) val physicalSchema = env.getPhysicalSchema(schema) sqlExecutor.executeWithinContext(physicalSchema, ThrowingFunction<Connection, List<Change>> { conn -> val jdbcTemplate = sqlExecutor.jdbcTemplate val artifactTable = queryAuditTable(physicalSchema) ?: return@ThrowingFunction emptyList() // If the artifact tables does not exist, then return empty list for that schema return@ThrowingFunction jdbcTemplate.query( conn, "SELECT * FROM " + env.platform.getSchemaPrefix(physicalSchema) + dbChangeTable + " WHERE DBSCHEMA = '" + schema + "'", MapListHandler()).map { resultSet -> val artfType = resultSet[convertDbObjectName.valueOf("ARTFTYPE")] as String val artf: Change if (artfType == "I") { artf = ChangeIncremental() } else if (artfType == "R") { artf = ChangeRerunnable() } else { throw IllegalArgumentException("This type does not exist $artfType") } var changeType = resultSet[changeTypeColumn] as String changeType = if (changeType == OLD_STATICDATA_CHANGETYPE) ChangeType.STATICDATA_STR else changeType artf.changeKey = ChangeKey( InternMap.instance().intern(resultSet[convertDbObjectName.valueOf("DBSCHEMA")] as String), env.platform.getChangeType(changeType), InternMap.instance().intern(resultSet[convertDbObjectName.valueOf("OBJECTNAME")] as String), resultSet[convertDbObjectName.valueOf(changeNameColumn)] as String ) artf.isActive = env.platform.getIntegerValue(resultSet[convertDbObjectName.valueOf("ACTIVE")]) == 1 // change METADATA to STATICDATA for backward compatability artf.contentHash = resultSet[convertDbObjectName.valueOf("CONTENTHASH")] as String? // these are repeated often artf.timeInserted = env.platform.getTimestampValue(resultSet[convertDbObjectName.valueOf(timeInsertedColumn)]) artf.timeUpdated = env.platform.getTimestampValue(resultSet[convertDbObjectName.valueOf(timeUpdatedColumn)]) artf.deployExecution = deployExecutionsById[env.platform.getLongValue(resultSet[updateDeployExecutionIdColumn])] // for backward compatibility, make sure the ROLLBACKCONTENT column exists if (artifactTable.getColumn(rollbackContentColumn) != null) { artf.rollbackContent = resultSet[rollbackContentColumn] as String? } artf } }) } // This block is to aim to backfill the "orderWithinObject" field, since we don't persist it in the database val incrementalChanges = artfs.filterNot { it.changeType.isRerunnable } val incrementalChangeMap = incrementalChanges.groupBy(Change::getObjectKey) incrementalChangeMap.values.forEach { objectChanges -> val sortedObjectChanges = objectChanges.sortedBy(Change::getTimeInserted) sortedObjectChanges.forEachIndexed { index, each -> each.orderWithinObject = 5000 + index } } return Lists.immutable.ofAll(artfs.toSet().toList().filter { env.schemaNames.contains(it.schema) }) } override fun deleteChange(change: Change) { sqlExecutor.executeWithinContext(change.getPhysicalSchema(env)) { conn -> sqlExecutor.jdbcTemplate.update( conn, "DELETE FROM " + env.platform.getSchemaPrefix(change.getPhysicalSchema(env)) + dbChangeTable + " WHERE " + changeNameColumn + " = ? AND OBJECTNAME = ?", change.changeName, change.objectName) } } override fun deleteObjectChanges(change: Change) { sqlExecutor.executeWithinContext(change.getPhysicalSchema(env)) { conn -> sqlExecutor.jdbcTemplate.update( conn, "DELETE FROM " + env.platform.getSchemaPrefix(change.getPhysicalSchema(env)) + dbChangeTable + " WHERE OBJECTNAME = ? AND CHANGETYPE = ?", change.objectName, change.changeType.name ) // TODO delete this eventually sqlExecutor.jdbcTemplate.update( conn, "DELETE FROM " + env.platform.getSchemaPrefix(change.getPhysicalSchema(env)) + dbChangeTable + " WHERE OBJECTNAME = ? AND CHANGETYPE = ?", change.objectName, "GRANT" ) } } private fun updateInternal(conn: Connection, artifact: Change, deployExecution: DeployExecution): Int { return sqlExecutor.jdbcTemplate.update( conn, "UPDATE " + env.platform.getSchemaPrefix(artifact.getPhysicalSchema(env)) + dbChangeTable + " SET " + "ARTFTYPE = ?, " + "DBSCHEMA = ?, " + "ACTIVE = ?, " + "CHANGETYPE = ?, " + "CONTENTHASH = ?, " + rollbackContentColumn + " = ?, " + deployUserIdColumn + " = ?, " + timeUpdatedColumn + " = ?, " + updateDeployExecutionIdColumn + " = ? " + "WHERE " + changeNameColumn + " = ? AND OBJECTNAME = ?", if (artifact is ChangeIncremental) "I" else "R", artifact.schema, if (artifact.isActive) 1 else 0, artifact.changeType.name, artifact.contentHash, artifact.rollbackContent, deployUserId, currentTimestamp, deployExecution.id, artifact.changeName, artifact.objectName ) } override fun acquireLock(): AuditLock { return sqlExecutor.executeWithinContext(env.physicalSchemas.first, ThrowingFunction { sqlExecutor.lock(it) }) } companion object { private val LOG = LoggerFactory.getLogger(SameSchemaChangeAuditDao::class.java) private val TIMESTAMP_FORMAT = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSS") // older version of static data private val OLD_STATICDATA_CHANGETYPE = "METADATA" } }
apache-2.0
6498fd0d1fdabdecf115db2ebc54989e
57.781081
353
0.643248
4.926161
false
false
false
false
Omico/CurrentActivity
core/common/src/main/kotlin/me/omico/currentactivity/utility/PackageManager.kt
1
1327
/* * This file is part of CurrentActivity. * * Copyright (C) 2022 Omico * * CurrentActivity 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. * * CurrentActivity 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 CurrentActivity. If not, see <https://www.gnu.org/licenses/>. */ package me.omico.currentactivity.utility import android.content.Context import android.content.pm.PackageInfo import android.content.pm.PackageManager import android.os.Build val Context.installedPackages: List<PackageInfo> get() = when { Build.VERSION.SDK_INT >= 33 -> packageManager.getInstalledPackages(PackageManager.PackageInfoFlags.of(0L)) else -> @Suppress("DEPRECATION") packageManager.getInstalledPackages(0) } fun Context.isPackageInstalled(packageName: String): Boolean = installedPackages.find { it.packageName == packageName } != null
gpl-3.0
7474311c1bd2b4760c8c8c9353f25ec4
38.029412
87
0.751319
4.336601
false
false
false
false
oleksiyp/mockk
mockk/common/src/test/kotlin/io/mockk/it/AnswersTest.kt
1
2658
package io.mockk.it import io.mockk.* import kotlin.test.Test import kotlin.test.assertEquals class AnswersTest { class MockCls { fun op(a: Int, b: Int, c: Int = 10, d: Int = 25) = a + b + c + d fun lambdaOp(a: Int, b: () -> Int) = a + b() } val spy = spyk(MockCls()) @Test fun answerFirstArg() { every { spy.op(any(), 5) } answers { if (firstArg<Int>() == 1) 1 else 2 } assertEquals(1, spy.op(1, 5)) assertEquals(2, spy.op(2, 5)) } @Test fun answerSecondArg() { every { spy.op(6, any()) } answers { if (secondArg<Int>() == 2) 3 else 4 } assertEquals(3, spy.op(6, 2)) assertEquals(4, spy.op(6, 3)) } @Test fun answerThirdArg() { every { spy.op(any(), 7, any()) } answers { if (thirdArg<Int>() == 9) 5 else 6 } assertEquals(5, spy.op(2, 7, 9)) assertEquals(6, spy.op(3, 7, 10)) } @Test fun answerLastArg() { every { spy.op(any(), 7, d = any()) } answers { if (lastArg<Int>() == 11) 7 else 8 } assertEquals(7, spy.op(2, 7, d = 11)) assertEquals(8, spy.op(3, 7, d = 12)) } @Test fun answerNArgs() { every { spy.op(any(), 1) } answers { nArgs } assertEquals(4, spy.op(2, 1)) } @Test fun answerParamTypesCount() { every { spy.op(any(), 2) } answers { method.paramTypes.size } assertEquals(4, spy.op(2, 2)) } @Test fun answerCaptureList() { val lstNonNull = mutableListOf<Int>() every { spy.op(1, 2, d = capture(lstNonNull)) } answers { lstNonNull.captured() } assertEquals(22, spy.op(1, 2, d = 22)) } @Test fun answerCaptureListNullable() { val lst = mutableListOf<Int?>() every { spy.op(3, 4, d = captureNullable(lst)) } answers { lst.captured()!! } assertEquals(33, spy.op(3, 4, d = 33)) } @Test fun answerCaptureSlot() { val slot = slot<Int>() every { spy.op(3, 4, d = capture(slot)) } answers { slot.captured } assertEquals(44, spy.op(3, 4, d = 44)) } @Test fun answerCaptureLambda() { val slot = slot<() -> Int>() every { spy.lambdaOp(1, capture(slot)) } answers { 2 + slot.invoke() } assertEquals(5, spy.lambdaOp(1, { 3 })) verify { spy.lambdaOp(1, any()) } } @Test fun answersNthArg() { every { spy.lambdaOp(any(), any()) } returnsArgument 0 assertEquals(1, spy.lambdaOp(1) { 3 }) assertEquals(2, spy.lambdaOp(2) { 3 }) assertEquals(5, spy.lambdaOp(5) { 3 }) verify { spy.lambdaOp(1, any()) } } }
apache-2.0
11e96598e00f71e2b336fd89f2940a9f
24.084906
92
0.528217
3.277435
false
true
false
false
noemus/kotlin-eclipse
kotlin-eclipse-ui-test/src/org/jetbrains/kotlin/ui/tests/editors/completion/KotlinFunctionParameterInfoTestCase.kt
1
2993
package org.jetbrains.kotlin.ui.tests.editors.completion import org.jetbrains.kotlin.testframework.editor.KotlinProjectTestCase import org.junit.Before import org.jetbrains.kotlin.testframework.utils.KotlinTestUtils import org.jetbrains.kotlin.ui.editors.KotlinFileEditor import org.jetbrains.kotlin.ui.editors.codeassist.KotlinCompletionProcessor import org.jetbrains.kotlin.core.builder.KotlinPsiManager import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.testframework.editor.TextEditorTest import org.junit.Assert open public class KotlinFunctionParameterInfoTestCase : KotlinProjectTestCase() { @Before fun before() { configureProject() } protected fun doTest(testPath: String) { val fileText = KotlinTestUtils.getText(testPath) val testEditor = configureEditor(KotlinTestUtils.getNameByPath(testPath), fileText) val actualResult = getContextInformation(testEditor.getEditor() as KotlinFileEditor) val expectedResult = getExpectedResult(testEditor) val agreement = actualResult.size == expectedResult.size && actualResult.all { actualResult -> expectedResult.any { expectedResult -> actualResult == expectedResult } } Assert.assertTrue("$expectedResult are not equals to $actualResult", agreement) } private fun getExpectedResult(testEditor: TextEditorTest): List<String> { val jetFile = KotlinPsiManager.getParsedFile(testEditor.getEditingFile()) val lastChild = jetFile.getLastChild() val expectedText = if (lastChild.getNode().getElementType() == KtTokens.BLOCK_COMMENT) { val lastChildText = lastChild.getText() lastChildText.substring(2, lastChildText.length - 2).trim() } else { // EOL_COMMENT lastChild.getText().substring(2).trim() } val regex = "\\((.*)\\)".toRegex() val beginHighlightRegex = "<highlight>".toRegex() val endHighlightRegex = "</highlight>".toRegex() val noParametersRegex = "<no parameters>".toRegex() return expectedText.split("\n") .map { line -> val match = regex.find(line) val displayString = match!!.groups[1]!!.value displayString .replace(beginHighlightRegex, "") .replace(endHighlightRegex, "") .replace(noParametersRegex, "") } .filter { it.isNotBlank() } } private fun getContextInformation(editor: KotlinFileEditor): List<String> { val completionProcessor = KotlinCompletionProcessor(editor) val contextInformation = completionProcessor.computeContextInformation(editor.getViewer(), KotlinTestUtils.getCaret(editor)) return contextInformation.map { it.getInformationDisplayString() } } }
apache-2.0
b9524863699ef25e590f1357a1293ac5
43.029412
99
0.659873
5.306738
false
true
false
false
klazuka/intellij-elm
src/main/kotlin/org/elm/utils/Timings.kt
1
3236
/* The MIT License (MIT) Derived from intellij-rust Copyright (c) 2015 Aleksey Kladov, Evgeny Kurbatsky, Alexey Kudinkin and contributors Copyright (c) 2016 JetBrains Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package org.elm.utils import kotlin.system.measureTimeMillis class Timings( private val valuesTotal: LinkedHashMap<String, Long> = LinkedHashMap(), private val invokes: MutableMap<String, Long> = mutableMapOf() ) { fun <T> measure(name: String, f: () -> T): T { check(name !in valuesTotal) return measureInternal(name, f) } fun <T> measureAverage(name: String, f: () -> T): T = measureInternal(name, f) fun merge(other: Timings): Timings { val values = values() val otherValues = other.values() check(values.isEmpty() || otherValues.isEmpty() || values.size == otherValues.size) val result = Timings() for (k in values.keys.union(otherValues.keys)) { result.valuesTotal[k] = // https://www.youtube.com/watch?v=vrfYLlR8X8k&feature=youtu.be&t=25m17s minOf(values.getOrDefault(k, Long.MAX_VALUE), otherValues.getOrDefault(k, Long.MAX_VALUE)) result.invokes[k] = 1 } return result } fun report() { val values = values() if (values.isEmpty()) { println("No metrics recorder") return } val width = values.keys.map { it.length }.maxByOrNull { i: Int -> i }!! for ((k, v) in values) { println("${k.padEnd(width)}: $v ms") } val total = values.values.sum() println("$total ms total.") println() } private fun <T> measureInternal(name: String, f: () -> T): T { var result: T? = null val time = measureTimeMillis { result = f() } valuesTotal.merge(name, time, Long::plus) invokes.merge(name, 1, Long::plus) @Suppress("UNCHECKED_CAST") return result as T } private fun values(): Map<String, Long> { val result = LinkedHashMap<String, Long>() for ((k, sum) in valuesTotal) { result[k] = (sum.toDouble() / invokes[k]!!).toLong() } return result } }
mit
89dc99e0204e10fff0cfc864fdb8fbb0
35.772727
110
0.650803
4.117048
false
false
false
false
ligee/kotlin-jupyter
src/main/kotlin/org/jetbrains/kotlinx/jupyter/util.kt
1
6013
package org.jetbrains.kotlinx.jupyter import org.jetbrains.kotlinx.jupyter.api.arrayRenderer import org.jetbrains.kotlinx.jupyter.api.bufferedImageRenderer import org.jetbrains.kotlinx.jupyter.codegen.ResultsRenderersProcessor import org.jetbrains.kotlinx.jupyter.compiler.util.CodeInterval import org.jetbrains.kotlinx.jupyter.compiler.util.SourceCodeImpl import org.jetbrains.kotlinx.jupyter.config.catchAll import org.jetbrains.kotlinx.jupyter.libraries.KERNEL_LIBRARIES import org.jetbrains.kotlinx.jupyter.libraries.parseLibraryDescriptor import java.io.File import java.util.Optional import java.util.concurrent.ConcurrentHashMap import kotlin.script.experimental.api.ScriptDiagnostic import kotlin.script.experimental.api.SourceCode import kotlin.script.experimental.jvm.util.determineSep import kotlin.script.experimental.jvm.util.toSourceCodePosition fun List<String>.joinToLines() = joinToString("\n") fun generateDiagnostic(fromLine: Int, fromCol: Int, toLine: Int, toCol: Int, message: String, severity: String) = ScriptDiagnostic( ScriptDiagnostic.unspecifiedError, message, ScriptDiagnostic.Severity.valueOf(severity), null, SourceCode.Location(SourceCode.Position(fromLine, fromCol), SourceCode.Position(toLine, toCol)) ) fun generateDiagnosticFromAbsolute(code: String, from: Int, to: Int, message: String, severity: ScriptDiagnostic.Severity): ScriptDiagnostic { val snippet = SourceCodeImpl(0, code) return ScriptDiagnostic( ScriptDiagnostic.unspecifiedError, message, severity, null, SourceCode.Location(from.toSourceCodePosition(snippet), to.toSourceCodePosition(snippet)) ) } fun CodeInterval.diagnostic(code: String, message: String, severity: ScriptDiagnostic.Severity = ScriptDiagnostic.Severity.ERROR): ScriptDiagnostic { return generateDiagnosticFromAbsolute(code, from, to, message, severity) } fun generateDiagnosticFromAbsolute(code: String, from: Int, to: Int, message: String, severity: String): ScriptDiagnostic { return generateDiagnosticFromAbsolute(code, from, to, message, ScriptDiagnostic.Severity.valueOf(severity)) } fun withPath(path: String?, diagnostics: List<ScriptDiagnostic>): List<ScriptDiagnostic> = diagnostics.map { it.copy(sourcePath = path) } fun String.findNthSubstring(s: String, n: Int, start: Int = 0): Int { if (n < 1 || start == -1) return -1 var i = start for (k in 1..n) { i = indexOf(s, i) if (i == -1) return -1 i += s.length } return i - s.length } fun SourceCode.Position.withNewAbsolute(code: SourceCode, newCode: SourceCode): SourceCode.Position? { val sep = code.text.determineSep() val absLineStart = if (line == 1) 0 else newCode.text.findNthSubstring(sep, line - 1) + sep.length var nextNewLinePos = newCode.text.indexOf(sep, absLineStart) if (nextNewLinePos == -1) nextNewLinePos = newCode.text.length val abs = absLineStart + col - 1 if (abs > nextNewLinePos) { return null } return SourceCode.Position(line, col, abs) } fun Int.toSourceCodePositionWithNewAbsolute(code: SourceCode, newCode: SourceCode): SourceCode.Position? { return toSourceCodePosition(code).withNewAbsolute(code, newCode) } fun ResultsRenderersProcessor.registerDefaultRenderers() { register(bufferedImageRenderer) register(arrayRenderer) } /** * Stores info about where a variable Y was declared and info about what are they at the address X. * K: key, stands for a way of addressing variables, e.g. address. * V: value, from Variable, choose any suitable type for your variable reference. * Default: T=Int, V=String */ class VariablesUsagesPerCellWatcher<K : Any, V : Any> { val cellVariables = mutableMapOf<K, MutableSet<V>>() /** * Tells in which cell a variable was declared */ private val variablesDeclarationInfo: MutableMap<V, K> = mutableMapOf() fun addDeclaration(address: K, variableRef: V) { ensureStorageCreation(address) // redeclaration of any type if (variablesDeclarationInfo.containsKey(variableRef)) { val oldCellId = variablesDeclarationInfo[variableRef] if (oldCellId != address) { cellVariables[oldCellId]?.remove(variableRef) } } variablesDeclarationInfo[variableRef] = address cellVariables[address]?.add(variableRef) } fun addUsage(address: K, variableRef: V) = cellVariables[address]?.add(variableRef) fun removeOldUsages(newAddress: K) { // remove known modifying usages in this cell cellVariables[newAddress]?.removeIf { variablesDeclarationInfo[it] != newAddress } } fun ensureStorageCreation(address: K) = cellVariables.putIfAbsent(address, mutableSetOf()) } fun <A, V> createCachedFun(calculate: (A) -> V): (A) -> V { return createCachedFun({ it }, calculate) } fun <A, K, V> createCachedFun(calculateKey: (A) -> K, calculate: (A) -> V): (A) -> V { val cache = ConcurrentHashMap<K, Optional<V>>() return { argument -> val key = calculateKey(argument) cache.getOrPut(key) { when (val value = calculate(argument)) { null -> Optional.empty<V>() else -> Optional.of(value) } as Optional<V> }.orElse(null) } } val libraryDescriptors = createCachedFun(calculateKey = { file: File -> file.absolutePath }) { homeDir -> val libraryFiles = KERNEL_LIBRARIES .homeLibrariesDir(homeDir) .listFiles(KERNEL_LIBRARIES::isLibraryDescriptor) .orEmpty() libraryFiles.toList().mapNotNull { file -> val libraryName = file.nameWithoutExtension log.info("Parsing descriptor for library '$libraryName'") log.catchAll(msg = "Parsing descriptor for library '$libraryName' failed") { libraryName to parseLibraryDescriptor(file.readText()) } }.toMap() }
apache-2.0
7cfe8ceabe4cd4cc31e15074b4ecbc09
36.347826
149
0.705139
4.316583
false
false
false
false
PassionateWsj/YH-Android
app/src/main/java/com/intfocus/template/subject/nine/collectionlist/adapter/CollectionListAdapter.kt
1
1937
package com.intfocus.template.subject.nine.collectionlist.adapter import android.widget.Toast import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.intfocus.template.R import com.intfocus.template.model.entity.Collection import com.intfocus.template.util.TimeUtils /** * **************************************************** * author jameswong * created on: 17/12/29 下午0:01 * e-mail: [email protected] * name: * desc: * **************************************************** */ class CollectionListAdapter : BaseQuickAdapter<Collection, BaseViewHolder>(R.layout.item_collection_list) { override fun convert(helper: BaseViewHolder, item: Collection) { val status = when { item.status == 1 -> "" item.status == 0 -> "上传中" else -> "草稿" } helper.setText(R.id.tv_item_collection_list_status, status) .setText(R.id.tv_item_collection_list_title, item.h1 ?: "") .setText(R.id.tv_item_collection_list_content, item.h2 ?: "") .setText(R.id.tv_item_collection_list_title_label, item.h3 ?: "") .setGone(R.id.right_menu_sync, item.status != 1) .setOnClickListener(R.id.rl_item_collection_list_container, { view -> Toast.makeText(mContext, "onItemClick" + data.indexOf(item), Toast.LENGTH_SHORT).show() }) .setOnClickListener(R.id.right_menu_delete, { view -> remove(data.indexOf(item)) }) .setOnClickListener(R.id.right_menu_sync, { view -> Toast.makeText(mContext, "onItemClick" + data.indexOf(item), Toast.LENGTH_SHORT).show() }) item.updated_at?.let { helper.setText(R.id.tv_item_collection_list_time, TimeUtils.getStandardDate(it)) } } }
gpl-3.0
906fc84dcbe5df4b1e757ee7d4a78bc5
42.727273
107
0.583983
4.023013
false
false
false
false
HabitRPG/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/ui/viewHolders/PetViewHolder.kt
1
6317
package com.habitrpg.android.habitica.ui.viewHolders import android.graphics.PorterDuff import android.graphics.drawable.BitmapDrawable import android.view.View import android.view.ViewGroup import androidx.core.graphics.drawable.toBitmap import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.databinding.PetDetailItemBinding import com.habitrpg.android.habitica.extensions.inflate import com.habitrpg.android.habitica.models.inventory.Animal import com.habitrpg.android.habitica.models.inventory.Egg import com.habitrpg.android.habitica.models.inventory.Food import com.habitrpg.android.habitica.models.inventory.HatchingPotion import com.habitrpg.android.habitica.models.inventory.Pet import com.habitrpg.common.habitica.extensions.DataBindingUtils import com.habitrpg.android.habitica.ui.menu.BottomSheetMenu import com.habitrpg.android.habitica.ui.menu.BottomSheetMenuItem import com.habitrpg.android.habitica.ui.views.dialogs.PetSuggestHatchDialog import io.reactivex.rxjava3.subjects.PublishSubject class PetViewHolder( parent: ViewGroup, private val equipEvents: PublishSubject<String>, private val feedEvents: PublishSubject<Pair<Pet, Food?>>, private val ingredientsReceiver: ((Animal, ((Pair<Egg?, HatchingPotion?>) -> Unit)) -> Unit)? ) : androidx.recyclerview.widget.RecyclerView.ViewHolder(parent.inflate(R.layout.pet_detail_item)), View.OnClickListener { private var hasMount: Boolean = false private var hasUnlockedPotion: Boolean = false private var hasUnlockedEgg: Boolean = false private var eggCount: Int = 0 private var potionCount: Int = 0 private var ownsSaddles = false private var animal: Pet? = null private var currentPet: String? = null private var binding: PetDetailItemBinding = PetDetailItemBinding.bind(itemView) private var isOwned: Boolean = false private var canRaiseToMount: Boolean = false init { itemView.setOnClickListener(this) } fun bind( item: Pet, trained: Int, eggCount: Int, potionCount: Int, canRaiseToMount: Boolean, ownsSaddles: Boolean, hasUnlockedEgg: Boolean, hasUnlockedPotion: Boolean, hasMount: Boolean, currentPet: String? ) { this.animal = item isOwned = trained > 0 binding.imageView.alpha = 1.0f this.canRaiseToMount = canRaiseToMount this.eggCount = eggCount this.potionCount = potionCount this.ownsSaddles = ownsSaddles this.hasUnlockedEgg = hasUnlockedEgg this.hasUnlockedPotion = hasUnlockedPotion this.hasMount = hasMount this.currentPet = currentPet binding.imageView.visibility = View.VISIBLE binding.itemWrapper.visibility = View.GONE binding.checkmarkView.visibility = View.GONE binding.titleTextView.visibility = View.GONE binding.root.contentDescription = item.text val imageName = "stable_Pet-${item.animal}-${item.color}" if (trained > 0) { if (this.canRaiseToMount) { binding.trainedProgressBar.visibility = View.VISIBLE binding.trainedProgressBar.progress = trained } else { binding.trainedProgressBar.visibility = View.GONE } } else { binding.trainedProgressBar.visibility = View.GONE binding.imageView.alpha = 0.2f } if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.LOLLIPOP_MR1) { binding.trainedProgressBar.progressBackgroundTintMode = PorterDuff.Mode.SRC_OVER } binding.imageView.background = null binding.activeIndicator.visibility = if (currentPet.equals(animal?.key)) View.VISIBLE else View.GONE binding.imageView.tag = imageName DataBindingUtils.loadImage(itemView.context, imageName) { val resources = itemView.context.resources ?: return@loadImage val drawable = if (trained == 0) BitmapDrawable(resources, it.toBitmap().extractAlpha()) else it if (binding.imageView.tag == imageName) { binding.imageView.bitmap = drawable.toBitmap() } } } override fun onClick(v: View) { if (!isOwned) { showRequirementsDialog() return } val context = itemView.context val menu = BottomSheetMenu(context) menu.setTitle(animal?.text) menu.setImage("stable_Pet-${animal?.animal}-${animal?.color}") val hasCurrentPet = currentPet.equals(animal?.key) val labelId = if (hasCurrentPet) R.string.unequip else R.string.equip menu.addMenuItem(BottomSheetMenuItem(itemView.resources.getString(labelId))) if (canRaiseToMount) { menu.addMenuItem(BottomSheetMenuItem(itemView.resources.getString(R.string.feed))) if (ownsSaddles) { menu.addMenuItem(BottomSheetMenuItem(itemView.resources.getString(R.string.use_saddle))) } } menu.setSelectionRunnable { index -> val pet = animal ?: return@setSelectionRunnable when (index) { 0 -> { animal?.let { equipEvents.onNext(it.key ?: "") } } 1 -> { feedEvents.onNext(Pair(pet, null)) } 2 -> { val saddle = Food() saddle.key = "Saddle" feedEvents.onNext(Pair(pet, saddle)) } } } menu.show() } private fun showRequirementsDialog() { val context = itemView.context val dialog = PetSuggestHatchDialog(context) animal?.let { ingredientsReceiver?.invoke(it) { ingredients -> dialog.configure( it, ingredients.first, ingredients.second, eggCount, potionCount, hasUnlockedEgg, hasUnlockedPotion, hasMount ) dialog.show() } } } }
gpl-3.0
e973d6eb34614aa615fa064deffb6be8
36.60119
104
0.630046
4.859231
false
false
false
false
WangDaYeeeeee/GeometricWeather
app/src/main/java/wangdaye/com/geometricweather/common/basic/models/ChineseCity.kt
1
850
package wangdaye.com.geometricweather.common.basic.models import wangdaye.com.geometricweather.common.basic.models.options.provider.WeatherSource import java.util.* data class ChineseCity( val cityId: String, val province: String, val city: String, val district: String, val latitude: String, val longitude: String ) { fun toLocation() = Location( cityId = cityId, latitude = latitude.toFloat(), longitude = longitude.toFloat(), timeZone = TimeZone.getTimeZone("Asia/Shanghai"), country = "中国", province = province, city = city, district = if (district == "无") "" else district, weather = null, weatherSource = WeatherSource.CAIYUN, isCurrentPosition = false, isResidentPosition = false, isChina = true ) }
lgpl-3.0
324e2327e4ecc78429dffc7528141b99
28.137931
87
0.643365
4.328205
false
false
false
false
hitoshura25/Media-Player-Omega-Android
login_presentation/src/main/java/com/vmenon/mpo/login/presentation/RegistrationFormValidator.kt
1
3723
package com.vmenon.mpo.login.presentation import android.util.Patterns import androidx.databinding.Observable import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import com.vmenon.mpo.login.presentation.BR import com.vmenon.mpo.login.presentation.R import com.vmenon.mpo.login.presentation.model.RegistrationObservable import com.vmenon.mpo.login.presentation.model.RegistrationValid class RegistrationFormValidator : Observable.OnPropertyChangedCallback() { private val registrationValid = MutableLiveData(INITIAL_VALID_STATE) fun registrationValid(): LiveData<RegistrationValid> = registrationValid override fun onPropertyChanged(sender: Observable?, propertyId: Int) { if (sender !is RegistrationObservable) return when (propertyId) { BR.firstName -> { val firstNameError = if (sender.getFirstName().isNotBlank()) null else R.string.first_name_invalid registrationValid.postValue( registrationValid.value?.copy( firstNameValid = firstNameError == null, firstNameError = firstNameError ) ?: INITIAL_VALID_STATE ) } BR.lastName -> { val lastNameError = if (sender.getLastName().isNotBlank()) null else R.string.last_name_invalid registrationValid.postValue( registrationValid.value?.copy( lastNameValid = lastNameError == null, lastNameError = lastNameError ) ?: INITIAL_VALID_STATE ) } BR.email -> { val emailError = if (sender.getEmail().isNotBlank() && Patterns.EMAIL_ADDRESS.matcher( sender.getEmail() ).matches() ) null else R.string.email_invalid registrationValid.postValue( registrationValid.value?.copy( emailValid = emailError == null, emailError = emailError ) ?: INITIAL_VALID_STATE ) } BR.password -> { val passwordError = if (sender.getPassword().isNotBlank()) null else R.string.password_invalid registrationValid.postValue( registrationValid.value?.copy( passwordValid = passwordError == null, passwordError = passwordError ) ?: INITIAL_VALID_STATE ) } BR.confirmPassword -> { val confirmPasswordError = if (sender.getConfirmPassword().isNotBlank()) { if (sender.getConfirmPassword() == sender.getPassword() ) { null } else { R.string.confirm_password_does_not_match } } else { R.string.confirm_password_invalid } registrationValid.postValue( registrationValid.value?.copy( confirmPasswordValid = confirmPasswordError == null, confirmPasswordError = confirmPasswordError ) ?: INITIAL_VALID_STATE ) } } } companion object { private val INITIAL_VALID_STATE = RegistrationValid() } }
apache-2.0
abdd2aa3ed1404767d3df17f02299d24
40.377778
97
0.518399
6.174129
false
false
false
false
google/filament
android/filament-utils-android/src/main/java/com/google/android/filament/utils/TextureLoader.kt
1
3466
/* * 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 com.google.android.filament.textured import android.content.res.Resources import android.graphics.Bitmap import android.graphics.BitmapFactory import com.google.android.filament.Engine import com.google.android.filament.Texture import com.google.android.filament.android.TextureHelper import java.lang.IllegalArgumentException import java.nio.ByteBuffer const val SKIP_BITMAP_COPY = true enum class TextureType { COLOR, NORMAL, DATA } fun loadTexture(engine: Engine, resources: Resources, resourceId: Int, type: TextureType): Texture { val options = BitmapFactory.Options() // Color is the only type of texture we want to pre-multiply with the alpha channel // Pre-multiplication is the default behavior, so we need to turn it off here options.inPremultiplied = type == TextureType.COLOR val bitmap = BitmapFactory.decodeResource(resources, resourceId, options) val texture = Texture.Builder() .width(bitmap.width) .height(bitmap.height) .sampler(Texture.Sampler.SAMPLER_2D) .format(internalFormat(type)) // This tells Filament to figure out the number of mip levels .levels(0xff) .build(engine) // TextureHelper offers a method that skips the copy of the bitmap into a ByteBuffer if (SKIP_BITMAP_COPY) { TextureHelper.setBitmap(engine, texture, 0, bitmap) } else { val buffer = ByteBuffer.allocateDirect(bitmap.byteCount) bitmap.copyPixelsToBuffer(buffer) // Do not forget to rewind the buffer! buffer.flip() val descriptor = Texture.PixelBufferDescriptor( buffer, format(bitmap), type(bitmap)) texture.setImage(engine, 0, descriptor) } texture.generateMipmaps(engine) return texture } private fun internalFormat(type: TextureType) = when (type) { TextureType.COLOR -> Texture.InternalFormat.SRGB8_A8 TextureType.NORMAL -> Texture.InternalFormat.RGBA8 TextureType.DATA -> Texture.InternalFormat.RGBA8 } // Not required when SKIP_BITMAP_COPY is true // Use String representation for compatibility across API levels private fun format(bitmap: Bitmap) = when (bitmap.config.name) { "ALPHA_8" -> Texture.Format.ALPHA "RGB_565" -> Texture.Format.RGB "ARGB_8888" -> Texture.Format.RGBA "RGBA_F16" -> Texture.Format.RGBA else -> throw IllegalArgumentException("Unknown bitmap configuration") } // Not required when SKIP_BITMAP_COPY is true private fun type(bitmap: Bitmap) = when (bitmap.config.name) { "ALPHA_8" -> Texture.Type.USHORT "RGB_565" -> Texture.Type.USHORT_565 "ARGB_8888" -> Texture.Type.UBYTE "RGBA_F16" -> Texture.Type.HALF else -> throw IllegalArgumentException("Unsupported bitmap configuration") }
apache-2.0
3383c566f607812be7dd968cf60d2196
34.367347
100
0.705713
4.226829
false
false
false
false
apollostack/apollo-android
apollo-compiler/src/main/kotlin/com/apollographql/apollo3/compiler/TypesToGenerate.kt
1
2206
package com.apollographql.apollo3.compiler import com.apollographql.apollo3.graphql.ast.GQLDocument import com.apollographql.apollo3.graphql.ast.GQLEnumTypeDefinition import com.apollographql.apollo3.graphql.ast.GQLInputObjectTypeDefinition import com.apollographql.apollo3.graphql.ast.GQLScalarTypeDefinition import com.apollographql.apollo3.graphql.ast.Schema import com.apollographql.apollo3.graphql.ast.usedTypeNames internal class TypesToGenerate( /** * The enums to generate */ val generateScalarMapping: Boolean, /** * The enums to generate */ val enumsToGenerate: Set<String>, /** * The enums to generate */ val inputObjectsToGenerate: Set<String>, ) internal fun computeTypesToGenerate( documents: List<GQLDocument>, schema: Schema, metadataEnums: Set<String>, metadataInputObjects: Set<String>, metadataCustomScalars: Boolean, alwaysGenerateTypesMatching: Set<String> ): TypesToGenerate { val regexes = alwaysGenerateTypesMatching.map { Regex(it) } val extraTypes = schema.typeDefinitions.values.filter { typeDefinition -> (typeDefinition is GQLInputObjectTypeDefinition || typeDefinition is GQLEnumTypeDefinition) && regexes.indexOfFirst { it.matches(typeDefinition.name) } >= 0 }.map { it.name } .toSet() val incomingTypes = metadataEnums.plus(metadataInputObjects) val usedTypes = ((documents.flatMap { it.definitions }.usedTypeNames(schema)) + extraTypes).map { schema.typeDefinitions[it]!! }.filter { when (it) { is GQLEnumTypeDefinition, is GQLInputObjectTypeDefinition, is GQLScalarTypeDefinition -> true else -> false } } val enumsToGenerate = usedTypes.filterIsInstance<GQLEnumTypeDefinition>() .map { it.name } .filter { !incomingTypes.contains(it) } val inputObjectsToGenerate = usedTypes.filterIsInstance<GQLInputObjectTypeDefinition>() .map { it.name } .filter { !incomingTypes.contains(it) } return TypesToGenerate( enumsToGenerate = enumsToGenerate.toSet(), inputObjectsToGenerate = inputObjectsToGenerate.toSet(), generateScalarMapping = !metadataCustomScalars, ) }
mit
728df43a2a500ba506a39960784767e1
30.070423
99
0.731188
4.456566
false
false
false
false
exponentjs/exponent
packages/expo/android/src/test/java/expo/modules/ReactActivityDelegateWrapperTest.kt
2
3970
package expo.modules import android.content.Context import android.content.Intent import com.facebook.react.ReactActivity import com.facebook.react.ReactActivityDelegate import com.google.common.truth.Truth.assertThat import expo.modules.core.interfaces.Package import expo.modules.core.interfaces.ReactActivityHandler import expo.modules.core.interfaces.ReactActivityLifecycleListener import io.mockk.MockKAnnotations import io.mockk.every import io.mockk.impl.annotations.RelaxedMockK import io.mockk.mockk import io.mockk.mockkObject import io.mockk.unmockkAll import io.mockk.verify import org.junit.After import org.junit.Before import org.junit.Test internal class ReactActivityDelegateWrapperTest { lateinit var mockPackage0: MockPackage lateinit var mockPackage1: MockPackage @RelaxedMockK lateinit var activity: ReactActivity @RelaxedMockK lateinit var delegate: ReactActivityDelegate @Before fun setUp() { mockPackage0 = MockPackage() mockPackage1 = MockPackage() MockKAnnotations.init(this) mockkObject(ExpoModulesPackage.Companion) every { ExpoModulesPackage.Companion.packageList } returns listOf(mockPackage0, mockPackage1) } @After fun tearDown() { unmockkAll() } @Test fun `onBackPressed should call each handler's callback just once`() { val delegateWrapper = ReactActivityDelegateWrapper(activity, delegate) every { mockPackage0.reactActivityLifecycleListener.onBackPressed() } returns true delegateWrapper.onBackPressed() verify(exactly = 1) { mockPackage0.reactActivityLifecycleListener.onBackPressed() } verify(exactly = 1) { mockPackage1.reactActivityLifecycleListener.onBackPressed() } verify(exactly = 1) { delegate.onBackPressed() } } @Test fun `onBackPressed should return true if someone returns true`() { val delegateWrapper = ReactActivityDelegateWrapper(activity, delegate) every { mockPackage0.reactActivityLifecycleListener.onBackPressed() } returns false every { mockPackage1.reactActivityLifecycleListener.onBackPressed() } returns true every { delegate.onBackPressed() } returns false val result = delegateWrapper.onBackPressed() assertThat(result).isTrue() } @Test fun `onNewIntent should call each handler's callback just once`() { val intent = mockk<Intent>() val delegateWrapper = ReactActivityDelegateWrapper(activity, delegate) every { mockPackage0.reactActivityLifecycleListener.onNewIntent(intent) } returns false every { mockPackage1.reactActivityLifecycleListener.onNewIntent(intent) } returns true every { delegate.onNewIntent(intent) } returns false delegateWrapper.onNewIntent(intent) verify(exactly = 1) { mockPackage0.reactActivityLifecycleListener.onNewIntent(any()) } verify(exactly = 1) { mockPackage1.reactActivityLifecycleListener.onNewIntent(any()) } verify(exactly = 1) { delegate.onNewIntent(any()) } } @Test fun `onNewIntent should return true if someone returns true`() { val intent = mockk<Intent>() val delegateWrapper = ReactActivityDelegateWrapper(activity, delegate) every { mockPackage0.reactActivityLifecycleListener.onNewIntent(intent) } returns false every { mockPackage1.reactActivityLifecycleListener.onNewIntent(intent) } returns true every { delegate.onNewIntent(intent) } returns false val result = delegateWrapper.onNewIntent(intent) assertThat(result).isTrue() } } internal class MockPackage : Package { val reactActivityLifecycleListener = mockk<ReactActivityLifecycleListener>(relaxed = true) val reactActivityHandler = mockk<ReactActivityHandler>(relaxed = true) override fun createReactActivityLifecycleListeners(activityContext: Context?): List<ReactActivityLifecycleListener> { return listOf(reactActivityLifecycleListener) } override fun createReactActivityHandlers(activityContext: Context?): List<ReactActivityHandler> { return listOf(reactActivityHandler) } }
bsd-3-clause
666d89c5a48e8a4fb83906aaa1c68966
35.422018
119
0.785139
5.189542
false
true
false
false
Heiner1/AndroidAPS
core/src/main/java/info/nightscout/androidaps/activities/ErrorHelperActivity.kt
1
1997
package info.nightscout.androidaps.activities import android.content.Context import android.content.Intent import android.os.Bundle import androidx.annotation.RawRes import info.nightscout.androidaps.core.R import info.nightscout.androidaps.database.AppRepository import info.nightscout.androidaps.database.transactions.InsertTherapyEventAnnouncementTransaction import info.nightscout.androidaps.dialogs.ErrorDialog import info.nightscout.shared.sharedPreferences.SP import io.reactivex.rxjava3.disposables.CompositeDisposable import io.reactivex.rxjava3.kotlin.plusAssign import javax.inject.Inject class ErrorHelperActivity : DialogAppCompatActivity() { @Inject lateinit var sp: SP @Inject lateinit var repository: AppRepository private val disposable = CompositeDisposable() @Override override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val errorDialog = ErrorDialog() errorDialog.helperActivity = this errorDialog.status = intent.getStringExtra(STATUS) ?: "" errorDialog.sound = intent.getIntExtra(SOUND_ID, R.raw.error) errorDialog.title = intent.getStringExtra(TITLE)?: "" errorDialog.show(supportFragmentManager, "Error") if (sp.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) disposable += repository.runTransaction(InsertTherapyEventAnnouncementTransaction(intent.getStringExtra(STATUS) ?: "")).subscribe() } companion object { const val SOUND_ID = "soundId" const val STATUS = "status" const val TITLE = "title" fun runAlarm(ctx: Context, status: String, title: String, @RawRes soundId: Int = 0) { val i = Intent(ctx, ErrorHelperActivity::class.java) i.putExtra(SOUND_ID, soundId) i.putExtra(STATUS, status) i.putExtra(TITLE, title) i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ctx.startActivity(i) } } }
agpl-3.0
342b0f7896ad7bab3d16e735d601bab0
37.403846
143
0.726089
4.698824
false
false
false
false
pambrose/prometheus-proxy
src/main/kotlin/io/prometheus/common/ScrapeResults.kt
1
1312
/* * Copyright © 2020 Paul Ambrose ([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("UndocumentedPublicClass", "UndocumentedPublicFunction") package io.prometheus.common import com.github.pambrose.common.util.EMPTY_BYTE_ARRAY import io.ktor.http.* internal class ScrapeResults( val agentId: String, val scrapeId: Long, var validResponse: Boolean = false, var statusCode: Int = HttpStatusCode.NotFound.value, var contentType: String = "", var zipped: Boolean = false, var contentAsText: String = "", var contentAsZipped: ByteArray = EMPTY_BYTE_ARRAY, var failureReason: String = "", var url: String = "" ) { fun setDebugInfo(url: String, failureReason: String = "") { this.url = url this.failureReason = failureReason } }
apache-2.0
eb8ec864f26274c83c603f71fd291976
31
75
0.726163
4.096875
false
false
false
false
esqr/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/modules/mainnavigation/MainNavigationActivity.kt
1
8024
package io.github.feelfreelinux.wykopmobilny.ui.modules.mainnavigation import android.content.Context import android.content.Intent import android.content.res.Configuration import android.os.Bundle import android.support.design.widget.NavigationView import android.support.v4.app.Fragment import android.support.v4.view.GravityCompat import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.widget.Toolbar import android.view.MenuItem import com.evernote.android.job.util.JobUtil import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.WykopApp import io.github.feelfreelinux.wykopmobilny.base.BaseActivity import io.github.feelfreelinux.wykopmobilny.base.BaseNavigationFragment import io.github.feelfreelinux.wykopmobilny.ui.dialogs.AppExitConfirmationDialog import io.github.feelfreelinux.wykopmobilny.ui.modules.NavigatorApi import io.github.feelfreelinux.wykopmobilny.ui.modules.settings.SettingsActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.loginscreen.LoginScreenActivity import io.github.feelfreelinux.wykopmobilny.ui.modules.mikroblog.feed.hot.HotFragment import io.github.feelfreelinux.wykopmobilny.ui.modules.notifications.notificationsservice.WykopNotificationsJob import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.hashtags.HashTagsNotificationsListFragment import io.github.feelfreelinux.wykopmobilny.ui.modules.notificationslist.notification.NotificationsListFragment import io.github.feelfreelinux.wykopmobilny.ui.modules.pm.conversationslist.ConversationsListFragment import io.github.feelfreelinux.wykopmobilny.utils.SettingsPreferencesApi import io.github.feelfreelinux.wykopmobilny.utils.isVisible import kotlinx.android.synthetic.main.activity_navigation.* import kotlinx.android.synthetic.main.drawer_header_view_layout.view.* import kotlinx.android.synthetic.main.navigation_header.view.* import kotlinx.android.synthetic.main.toolbar.* import javax.inject.Inject fun Context.launchNavigationActivity(targetFragment : String? = null) { val intent = Intent(this, NavigationActivity::class.java) targetFragment?.let { intent.putExtra(NavigationActivity.TARGET_FRAGMENT_KEY, targetFragment) } startActivity(intent) } interface MainNavigationInterface { val activityToolbar : Toolbar fun openFragment(fragment: Fragment) fun showErrorDialog(e: Throwable) } class NavigationActivity : BaseActivity(), MainNavigationView, NavigationView.OnNavigationItemSelectedListener, MainNavigationInterface { override val activityToolbar: Toolbar get() = toolbar companion object { val LOGIN_REQUEST_CODE = 142 val TARGET_FRAGMENT_KEY = "TARGET_FRAGMENT" val TARGET_NOTIFICATIONS = "TARGET_NOTIFICATIONS" fun getIntent(context: Context, targetFragment: String? = null): Intent { val intent = Intent(context, NavigationActivity::class.java) targetFragment?.let { intent.putExtra(NavigationActivity.TARGET_FRAGMENT_KEY, targetFragment) } return intent } } override fun onNavigationItemSelected(item: MenuItem): Boolean { when (item.itemId) { R.id.nav_mikroblog -> openFragment(HotFragment.newInstance()) R.id.login -> { navigator.openLoginScreen(this, LOGIN_REQUEST_CODE) } R.id.messages -> { openFragment(ConversationsListFragment.newInstance()) } R.id.nav_settings -> { navigator.openSettingsActivity(this) } else -> presenter.navigationItemClicked(item.itemId) } item.isChecked = true drawer_layout.closeDrawers() return true } @Inject lateinit var presenter : MainNavigationPresenter @Inject lateinit var settingsApi : SettingsPreferencesApi @Inject lateinit var navigator : NavigatorApi private val navHeader by lazy { navigationView.getHeaderView(0) } private val actionBarToggle by lazy { ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.nav_drawer_open, R.string.nav_drawer_closed) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_navigation) setSupportActionBar(toolbar) WykopApp.uiInjector.inject(this) JobUtil.hasBootPermission(this) // Schedules notification service WykopNotificationsJob.shedule(settingsApi) toolbar.tag = toolbar.overflowIcon // We want to save original overflow icon drawable into memory. setupNavigation() if (savedInstanceState == null) { if (intent.hasExtra(TARGET_FRAGMENT_KEY)) { when (intent.getStringExtra(TARGET_FRAGMENT_KEY)) { TARGET_NOTIFICATIONS -> openFragment(NotificationsListFragment.newInstance()) } } else openMainFragment() } } override fun onPostCreate(savedInstanceState: Bundle?) { super.onPostCreate(savedInstanceState) actionBarToggle.syncState() } override fun onConfigurationChanged(newConfig: Configuration?) { super.onConfigurationChanged(newConfig) actionBarToggle.onConfigurationChanged(newConfig) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { if (actionBarToggle.onOptionsItemSelected(item)) return true return super.onOptionsItemSelected(item) } override fun onDestroy() { super.onDestroy() presenter.unsubscribe() } private fun setupNavigation() { drawer_layout.addDrawerListener(actionBarToggle) navigationView.setNavigationItemSelectedListener(this) presenter.subscribe(this) } override fun showUsersMenu(value : Boolean) { navigationView.menu.apply { findItem(R.id.nav_user).isVisible = value findItem(R.id.nav_mojwykop).isVisible = value findItem(R.id.login).isVisible = !value findItem(R.id.logout).isVisible = value } navHeader.view_container.apply { checkIsUserLoggedIn() nav_notifications_tag.setOnClickListener { openFragment(HashTagsNotificationsListFragment.newInstance()) deselectItems() } nav_notifications.setOnClickListener { openFragment(NotificationsListFragment.newInstance()) deselectItems() } } } fun openMainFragment() { // @TODO Handle settings here openFragment(HotFragment()) } override fun openFragment(fragment: Fragment) { fab.isVisible = false fab.setOnClickListener(null) if (fragment is BaseNavigationFragment) fragment.fab = fab supportFragmentManager.beginTransaction().replace(R.id.contentView, fragment).commit() closeDrawer() } fun closeDrawer() = drawer_layout.closeDrawers() fun deselectItems() { val menu = navigationView.menu for (i in 0 until menu.size()) { menu.getItem(i).isChecked = false } } override fun onBackPressed() { if(drawer_layout.isDrawerOpen(GravityCompat.START)) closeDrawer() else AppExitConfirmationDialog(this, { finish() }).show() } override fun restartActivity() { navigator.openMainActivity(this) finish() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { when (requestCode) { LOGIN_REQUEST_CODE -> { if (resultCode == LoginScreenActivity.USER_LOGGED_IN) { restartActivity() } } else -> { if (resultCode == SettingsActivity.THEME_CHANGED_RESULT) { restartActivity() } } } } }
mit
6ac207cf3aa9b8bf2748d98e34f656ca
35.981567
137
0.694666
5.130435
false
false
false
false
sjnyag/stamp
app/src/main/java/com/sjn/stamp/ui/fragment/media/MediaBrowserListFragment.kt
1
6390
package com.sjn.stamp.ui.fragment.media import android.content.Context import android.os.Bundle import android.support.v4.media.MediaBrowserCompat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.sjn.stamp.R import com.sjn.stamp.ui.MediaBrowsable import com.sjn.stamp.ui.observer.MediaBrowserObserver import com.sjn.stamp.utils.LogHelper import com.sjn.stamp.utils.MediaIDHelper abstract class MediaBrowserListFragment : ListFragment(), MediaBrowserObserver.Listener { var mediaBrowsable: MediaBrowsable? = null var mediaId: String? get() { return arguments?.getString(ARG_MEDIA_ID) } set(mediaId) { arguments = Bundle(1).apply { putString(MediaBrowserListFragment.ARG_MEDIA_ID, mediaId) } } private val subscriptionCallback: MediaBrowserCompat.SubscriptionCallback = object : MediaBrowserCompat.SubscriptionCallback() { override fun onChildrenLoaded(parentId: String, children: List<MediaBrowserCompat.MediaItem>) { LogHelper.d(TAG, "onChildrenLoaded START") LogHelper.d(TAG, "onChildrenLoaded parentId: $parentId") LogHelper.d(TAG, "onChildrenLoaded children: " + children.size) onMediaBrowserChildrenLoaded(parentId, children) LogHelper.d(TAG, "onChildrenLoaded END") } override fun onError(id: String) { LogHelper.d(TAG, "onError START") onMediaBrowserError(id) LogHelper.d(TAG, "onError END") } } internal abstract fun onMediaBrowserChildrenLoaded(parentId: String, children: List<MediaBrowserCompat.MediaItem>) internal abstract fun onMediaBrowserError(parentId: String) override fun onAttach(context: Context?) { LogHelper.d(TAG, "onAttach START") super.onAttach(context) if (context is MediaBrowsable) { mediaBrowsable = context } LogHelper.d(TAG, "fragment.onAttach, mediaId=", mediaId) if (mediaBrowsable?.mediaBrowser?.isConnected == true) { onMediaBrowserConnected() } LogHelper.d(TAG, "onAttach END") } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { LogHelper.d(TAG, "onCreateView START") val view = super.onCreateView(inflater, container, savedInstanceState) LogHelper.d(TAG, "onCreateView END") return view } override fun onStart() { LogHelper.d(TAG, "onStart START") super.onStart() updateTitle() MediaBrowserObserver.addListener(this) LogHelper.d(TAG, "onStart END") } override fun onResume() { LogHelper.d(TAG, "onResume START") super.onResume() LogHelper.d(TAG, "onResume END") } override fun onPause() { LogHelper.d(TAG, "onPause START") super.onPause() LogHelper.d(TAG, "onPause END") } override fun onStop() { LogHelper.d(TAG, "onStop START") super.onStop() MediaBrowserObserver.removeListener(this) LogHelper.d(TAG, "onStop END") } override fun onDetach() { LogHelper.d(TAG, "onDetach START") super.onDetach() if (mediaBrowsable?.mediaBrowser?.isConnected == true) { mediaId?.let { mediaBrowsable?.mediaBrowser?.unsubscribe(it) } } mediaBrowsable = null LogHelper.d(TAG, "onDetach END") } // Called when the MediaBrowser is connected. This method is either called by the // fragment.onStart() or explicitly by the activity in the case where the connection // completes after the onStart() override fun onMediaBrowserConnected() { LogHelper.d(TAG, "onMediaControllerConnected START") if (isDetached || mediaBrowsable == null) { LogHelper.d(TAG, "onMediaControllerConnected SKIP") return } LogHelper.d(TAG, "onMediaControllerConnected mediaId: " + mediaId) // Unsubscribing before subscribing is required if this mediaId already has a subscriber // on this MediaBrowser instance. Subscribing to an already subscribed mediaId will replace // the callback, but won't trigger the initial callback.onChildrenLoaded. // // This is temporary: A bug is being fixed that will make subscribe // consistently call onChildrenLoaded initially, no matter if it is replacing an existing // subscriber or not. Currently this only happens if the mediaID has no previous // subscriber or if the media content changes on the service side, so we need to // unsubscribe first. mediaId?.let { mediaBrowsable?.mediaBrowser?.unsubscribe(it) mediaBrowsable?.mediaBrowser?.subscribe(it, subscriptionCallback) } // Add MediaController callback so we can redraw the list when metadata changes: // MediaControllerObserver.getInstance().addListener(this); LogHelper.d(TAG, "onMediaControllerConnected END") } protected fun reloadList() { LogHelper.d(TAG, "reloadList START") mediaId?.let { mediaBrowsable?.mediaBrowser?.unsubscribe(it) mediaBrowsable?.mediaBrowser?.subscribe(it, subscriptionCallback) } LogHelper.d(TAG, "reloadList END") } private fun updateTitle() { LogHelper.d(TAG, "updateTitle START") mediaId?.let { mediaBrowsable?.mediaBrowser?.getItem(it, object : MediaBrowserCompat.ItemCallback() { override fun onItemLoaded(item: MediaBrowserCompat.MediaItem?) { item?.description?.title?.let { listener?.setToolbarTitle(it) } } override fun onError(itemId: String) { val title = MediaIDHelper.extractBrowseCategoryValueFromMediaID(it) ?: context?.getString(R.string.app_name) listener?.setToolbarTitle(title) } }) } LogHelper.d(TAG, "updateTitle END") } companion object { private val TAG = LogHelper.makeLogTag(MediaBrowserListFragment::class.java) private const val ARG_MEDIA_ID = "media_id" } }
apache-2.0
1a84556df369b179d8c419646364dadf
37.263473
132
0.646009
4.976636
false
false
false
false
PolymerLabs/arcs
java/arcs/tools/PlanGenerator.kt
1
6773
package arcs.tools import arcs.core.data.CountType import arcs.core.data.CreatableStorageKey import arcs.core.data.EntityType import arcs.core.data.FieldName import arcs.core.data.FieldType import arcs.core.data.Plan import arcs.core.data.Recipe import arcs.core.data.Schema import arcs.core.data.SchemaFields import arcs.core.data.SchemaName import arcs.core.data.TupleType import arcs.core.data.TypeVariable import arcs.core.storage.StorageKeyManager import arcs.core.type.Type import com.squareup.kotlinpoet.CodeBlock import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.PropertySpec import com.squareup.kotlinpoet.buildCodeBlock /** * Adds a code-generated [Plan] to a [FileSpec]. * * Will also add code-generated [Plan.Handle] properties to the file. * * @param recipe [Recipe] source for [Plan] conversion. * @return self, with code-generated [Plan] and [Plan.Handle]s. */ fun FileSpec.Builder.addRecipe(recipe: Recipe): FileSpec.Builder { val handles = recipe.handles.values.map { PropertySpec.builder("${recipe.name}_${it.name}", Plan.Handle::class) .initializer(buildHandleBlock(it)) .build() } val ctx = mapOf( "plan" to Plan::class, "handles" to buildCollectionBlock(handles, "%N"), // TODO(161940699) Generate particles "particles" to buildCollectionBlock(listOf<Recipe.Particle>()), // TODO(161940729) Generate Annotations "annotations" to buildCollectionBlock(listOf<Annotation>()) ) val plan = PropertySpec.builder("${recipe.name}Plan", Plan::class) .initializer( buildCodeBlock { addNamed( """ %plan:T( particles = %particles:L, handles = %handles:L, annotations = %annotations:L ) """.trimIndent(), ctx ) } ) .build() handles.forEach { this.addProperty(it) } this.addProperty(plan) return this } /** * Adds a code-generated [Plan.Handle] to a [CodeBlock]. * * @param handle a source [Recipe.Handle] for conversion. * @return self, with a code-generated [Plan.Handle] instance. */ fun CodeBlock.Builder.addHandle(handle: Recipe.Handle): CodeBlock.Builder = with(handle) { val ctx = mapOf( "handle" to Plan.Handle::class, // TODO(161941222) verify join handles work "storageKeyManager" to StorageKeyManager::class, "key" to storageKey, "type" to buildTypeBlock(type), "annotations" to buildCollectionBlock(emptyList<Annotation>()), "creatable" to CreatableStorageKey::class, "name" to name ) val storageKeyTemplate = storageKey ?.let { "storageKey = %storageKeyManager:T.GLOBAL_INSTANCE.parse(%key:S)," } ?: "storageKey = %creatable:T(%name:S)," [email protected]( """ %handle:T( $storageKeyTemplate type = %type:L, annotations = %annotations:L ) """.trimIndent(), ctx ) } /** Shorthand for building a [CodeBlock] with a code-generated [Plan.Handle]. */ fun buildHandleBlock(handle: Recipe.Handle): CodeBlock = buildCodeBlock { addHandle(handle) } /** Code-generates a [Type] within a [CodeBlock]. */ fun CodeBlock.Builder.addType(type: Type): CodeBlock.Builder = when (type) { is EntityType -> add("%T(%L)", EntityType::class, buildSchemaBlock(type.entitySchema)) is Type.TypeContainer<*> -> add("%T(%L)", type::class, buildTypeBlock(type.containedType)) is CountType -> add("%T()", CountType::class) is TupleType -> add( "%T(%L)", TupleType::class, buildCollectionBlock(type.elementTypes) { builder, item -> builder.add(buildTypeBlock(item)) } ) is TypeVariable -> add( "%T(%S, %L, %L)", TypeVariable::class, type.name, type.constraint?.let { buildTypeBlock(it) }, type.maxAccess ) else -> throw IllegalArgumentException("[Type] $type is not supported.") } /** Shorthand for building a [CodeBlock] with a code-generated [Type]. */ fun buildTypeBlock(type: Type): CodeBlock = buildCodeBlock { addType(type) } /** Code-generates a [Schema] within a [CodeBlock]. */ fun CodeBlock.Builder.addSchema(schema: Schema): CodeBlock.Builder { if (Schema.EMPTY == schema) { add("%T.EMPTY", Schema::class) return this } val ctx = mapOf( "schema" to Schema::class, "names" to buildCollectionBlock(schema.names) { builder, item -> builder.add("%T(%S)", SchemaName::class, item.name) }, "fields" to buildSchemaFieldsBlock(schema.fields), "hash" to schema.hash ) addNamed( """ %schema:T( names = %names:L, fields = %fields:L, hash = %hash:S ) """.trimIndent(), ctx ) return this } /** Shorthand for building a [CodeBlock] with a code-generated [Schema]. */ fun buildSchemaBlock(schema: Schema): CodeBlock = buildCodeBlock { addSchema(schema) } /** Code-generates [SchemaFields] within a [CodeBlock]. */ fun CodeBlock.Builder.addSchemaFields(fields: SchemaFields): CodeBlock.Builder { val toSchemaField = { builder: CodeBlock.Builder, entry: Map.Entry<FieldName, FieldType> -> builder.add("%S to %L", entry.key, buildFieldTypeBlock(entry.value)) Unit } val ctx = mapOf( "fields" to SchemaFields::class, "singletons" to buildCollectionBlock(fields.singletons, toSchemaField), "collections" to buildCollectionBlock(fields.collections, toSchemaField) ) addNamed( """ %fields:T( singletons = %singletons:L, collections = %collections:L ) """.trimIndent(), ctx ) return this } /** Shorthand for building a [CodeBlock] with code-generated [SchemaFields]. */ fun buildSchemaFieldsBlock(schemaFields: SchemaFields): CodeBlock = buildCodeBlock { addSchemaFields(schemaFields) } /** Code-generates [FieldType] within a [CodeBlock]. */ fun CodeBlock.Builder.addFieldType(field: FieldType): CodeBlock.Builder = when (field) { is FieldType.Primitive -> add("%T.%L", FieldType::class, field.primitiveType) is FieldType.EntityRef -> add("%T(%S)", field::class, field.schemaHash) is FieldType.InlineEntity -> add("%T(%S)", field::class, field.schemaHash) is FieldType.Tuple -> add( "%T(%L)", FieldType.Tuple::class, buildCollectionBlock(field.types) { builder, item -> builder.addFieldType(item) } ) is FieldType.ListOf -> add( "%T(%L)", FieldType.ListOf::class, buildFieldTypeBlock(field.primitiveType) ) is FieldType.NullableOf -> add( "%T(%L)", FieldType.NullableOf::class, buildFieldTypeBlock(field.innerType) ) } /** Shorthand for building a [CodeBlock] with a code-generated [FieldType]. */ fun buildFieldTypeBlock(field: FieldType): CodeBlock = buildCodeBlock { addFieldType(field) }
bsd-3-clause
39a052a1d8fd73d05c40b8a4223e04e3
31.406699
93
0.671194
3.963136
false
false
false
false
Maccimo/intellij-community
plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/core/overrideImplement/KtOverrideMembersHandler.kt
2
5721
// 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.core.overrideImplement import org.jetbrains.kotlin.analysis.api.KtAllowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.KtAnalysisSession import org.jetbrains.kotlin.analysis.api.analyze import org.jetbrains.kotlin.analysis.api.lifetime.allowAnalysisOnEdt import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol import org.jetbrains.kotlin.analysis.api.symbols.KtClassKind import org.jetbrains.kotlin.analysis.api.symbols.KtClassOrObjectSymbol import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithModality import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.idea.KtIconProvider.getIcon import org.jetbrains.kotlin.idea.core.util.KotlinIdeaCoreBundle import org.jetbrains.kotlin.name.StandardClassIds import org.jetbrains.kotlin.psi.KtClassOrObject internal open class KtOverrideMembersHandler : KtGenerateMembersHandler(false) { @OptIn(KtAllowAnalysisOnEdt::class) override fun collectMembersToGenerate(classOrObject: KtClassOrObject): Collection<KtClassMember> { return allowAnalysisOnEdt { analyze(classOrObject) { collectMembers(classOrObject) } } } fun KtAnalysisSession.collectMembers(classOrObject: KtClassOrObject): List<KtClassMember> { val classOrObjectSymbol = classOrObject.getClassOrObjectSymbol() return getOverridableMembers(classOrObjectSymbol).map { (symbol, bodyType, containingSymbol) -> KtClassMember( KtClassMemberInfo( symbol, symbol.render(renderOption), getIcon(symbol), containingSymbol?.classIdIfNonLocal?.asSingleFqName()?.toString() ?: containingSymbol?.name?.asString(), containingSymbol?.let { getIcon(it) } ), bodyType, preferConstructorParameter = false ) } } @OptIn(ExperimentalStdlibApi::class) private fun KtAnalysisSession.getOverridableMembers(classOrObjectSymbol: KtClassOrObjectSymbol): List<OverrideMember> { return buildList { classOrObjectSymbol.getMemberScope().getCallableSymbols().forEach { symbol -> if (!symbol.isVisibleInClass(classOrObjectSymbol)) return@forEach val implementationStatus = symbol.getImplementationStatus(classOrObjectSymbol) ?: return@forEach if (!implementationStatus.isOverridable) return@forEach val intersectionSymbols = symbol.getIntersectionOverriddenSymbols() val symbolsToProcess = if (intersectionSymbols.size <= 1) { listOf(symbol) } else { val nonAbstractMembers = intersectionSymbols.filter { (it as? KtSymbolWithModality)?.modality != Modality.ABSTRACT } // If there are non-abstract members, we only want to show override for these non-abstract members. Otherwise, show any // abstract member to override. nonAbstractMembers.ifEmpty { listOf(intersectionSymbols.first()) } } val hasNoSuperTypesExceptAny = classOrObjectSymbol.superTypes.singleOrNull()?.isAny == true for (symbolToProcess in symbolsToProcess) { val originalOverriddenSymbol = symbolToProcess.originalOverriddenSymbol val containingSymbol = originalOverriddenSymbol?.originalContainingClassForOverride val bodyType = when { classOrObjectSymbol.classKind == KtClassKind.INTERFACE && containingSymbol?.classIdIfNonLocal == StandardClassIds.Any -> { if (hasNoSuperTypesExceptAny) { // If an interface does not extends any other interfaces, FE1.0 simply skips members of `Any`. So we mimic // the same behavior. See idea/testData/codeInsight/overrideImplement/noAnyMembersInInterface.kt continue } else { BodyType.NO_BODY } } (originalOverriddenSymbol as? KtSymbolWithModality)?.modality == Modality.ABSTRACT -> BodyType.FROM_TEMPLATE symbolsToProcess.size > 1 -> BodyType.QUALIFIED_SUPER else -> BodyType.SUPER } // Ideally, we should simply create `KtClassMember` here and remove the intermediate `OverrideMember` data class. But // that doesn't work because this callback function is holding a read lock and `symbol.render(renderOption)` requires // the write lock. // Hence, we store the data in an intermediate `OverrideMember` data class and do the rendering later in the `map` call. add(OverrideMember(symbolToProcess, bodyType, containingSymbol)) } } } } private data class OverrideMember(val symbol: KtCallableSymbol, val bodyType: BodyType, val containingSymbol: KtClassOrObjectSymbol?) override fun getChooserTitle() = KotlinIdeaCoreBundle.message("override.members.handler.title") override fun getNoMembersFoundHint() = KotlinIdeaCoreBundle.message("override.members.handler.no.members.hint") }
apache-2.0
cb1990490c9a3526695c9399d0dd7f48
54.553398
146
0.644992
6.073248
false
false
false
false
edwardharks/Aircraft-Recognition
recognition/src/test/kotlin/com/edwardharker/aircraftrecognition/search/SearchStoreTest.kt
1
2270
package com.edwardharker.aircraftrecognition.search import org.junit.Test import org.mockito.Mockito import rx.Observable import rx.observers.TestSubscriber class SearchStoreTest { private val testSubscriber = TestSubscriber<SearchState>() private val actionSubject = rx.subjects.PublishSubject.create<SearchAction>() @Test fun usesSearchFunctionForQueryChangedActions() { val mockedSearchUseCase = Mockito.mock(MockSearchUseCase::class.java) val store = SearchStore(mockedSearchUseCase::search, noOpReducer) store.dispatch(actionSubject) store.subscribe().subscribe(testSubscriber) actionSubject.onNext(queryChangedAction) Mockito.verify(mockedSearchUseCase).search(queryChangedAction) } @Test fun startsWithEmptyState() { val expected = SearchState.empty() val store = SearchStore(noOpSearchUseCase, noOpReducer) store.dispatch(actionSubject) store.subscribe().subscribe(testSubscriber) actionSubject.onNext(SearchResultsAction(emptyList())) testSubscriber.assertValues(expected) } @Test fun returnsOutputOfReducer() { val expected = SearchState.error() val fakeReducer = fun(_: SearchState, _: SearchAction): SearchState = expected val fakeSearchUseCase = fun(_: QueryChangedAction): Observable<SearchAction> = Observable.just(SearchResultsAction(emptyList())) val store = SearchStore(fakeSearchUseCase, fakeReducer) store.dispatch(actionSubject) store.subscribe().subscribe(testSubscriber) actionSubject.onNext(queryChangedAction) testSubscriber.assertValues(SearchState.empty(), expected) } private interface MockSearchUseCase { fun search(action: QueryChangedAction): Observable<SearchAction> } private companion object { private val queryChangedAction = QueryChangedAction("query") private val noOpReducer = fun(oldState: SearchState, _: SearchAction): SearchState { return oldState } private val noOpSearchUseCase = fun(_: QueryChangedAction): Observable<SearchAction> { return Observable.never() } } }
gpl-3.0
82e5a46995ae76ff74235322211067b2
31.913043
86
0.696916
5.509709
false
true
false
false
wordpress-mobile/WordPress-Android
WordPress/src/main/java/org/wordpress/android/localcontentmigration/LocalMigrationContentProvider.kt
1
3529
package org.wordpress.android.localcontentmigration import android.database.Cursor import android.net.Uri import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.components.SingletonComponent import org.wordpress.android.localcontentmigration.LocalContentEntity.AccessToken import org.wordpress.android.localcontentmigration.LocalContentEntity.BloggingReminders import org.wordpress.android.localcontentmigration.LocalContentEntity.EligibilityStatus import org.wordpress.android.localcontentmigration.LocalContentEntity.Post import org.wordpress.android.localcontentmigration.LocalContentEntity.ReaderPosts import org.wordpress.android.localcontentmigration.LocalContentEntity.Sites import org.wordpress.android.localcontentmigration.LocalContentEntity.UserFlags import org.wordpress.android.provider.query.QueryResult import java.lang.Integer.parseInt class LocalMigrationContentProvider: TrustedQueryContentProvider() { @EntryPoint @InstallIn(SingletonComponent::class) interface LocalMigrationContentProviderEntryPoint { fun queryResult(): QueryResult fun localSiteProviderHelper(): LocalSiteProviderHelper fun localPostProviderHelper(): LocalPostProviderHelper fun localEligibilityStatusProviderHelper(): LocalEligibilityStatusProviderHelper fun localAccessTokenProviderHelper(): LocalAccessTokenProviderHelper fun userFlagsProviderHelper(): UserFlagsProviderHelper fun readeSavedPostsProviderHelper(): ReaderSavedPostsProviderHelper fun bloggingRemindersProviderHelper(): BloggingRemindersProviderHelper } override fun query(uri: Uri): Cursor { val path = checkNotNull(uri.path) { "This provider does not support queries without a path." } // Find the matching entity and its captured groups val (entity, groups) = LocalContentEntity.values().firstNotNullOf { entity -> entity.contentIdCapturePattern.find(path)?.let { match -> return@firstNotNullOf Pair(entity, match.groups) } } val localEntityId = extractEntityId(groups) return query(entity, localEntityId) } // The first group is the entire match, so we drop that and parse the next captured group as an integer private fun extractEntityId(groups: MatchGroupCollection) = groups.drop(1).firstOrNull()?.let { parseInt(it.value) } private fun query(entity: LocalContentEntity, localEntityId: Int?): Cursor { val context = checkNotNull(context) { "Cannot find context from the provider." } with(EntryPointAccessors.fromApplication(context.applicationContext, LocalMigrationContentProviderEntryPoint::class.java)) { val response = when (entity) { EligibilityStatus -> localEligibilityStatusProviderHelper().getData() AccessToken -> localAccessTokenProviderHelper().getData() UserFlags -> userFlagsProviderHelper().getData() ReaderPosts -> readeSavedPostsProviderHelper().getData() BloggingReminders -> bloggingRemindersProviderHelper().getData() Sites -> localSiteProviderHelper().getData() Post -> localPostProviderHelper().getData(localEntityId) } return queryResult().createCursor(response) } } } interface LocalDataProviderHelper { fun getData(localEntityId: Int? = null): LocalContentEntityData }
gpl-2.0
2e35bb0a5347418804619388dc23f464
49.414286
107
0.750071
5.59271
false
false
false
false
ingokegel/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/move/moveFilesOrDirectories/KotlinMoveDirectoryWithClassesHelper.kt
2
5810
// Copyright 2000-2022 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.refactoring.move.moveFilesOrDirectories import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.project.Project import com.intellij.psi.PsiDirectory import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.refactoring.listeners.RefactoringElementListener import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesHelper import com.intellij.refactoring.move.moveFilesOrDirectories.MoveFilesOrDirectoriesUtil import com.intellij.usageView.UsageInfo import com.intellij.util.Function import com.intellij.util.containers.MultiMap import org.jetbrains.kotlin.idea.base.util.quoteIfNeeded import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.core.getFqNameWithImplicitPrefix import org.jetbrains.kotlin.idea.core.getPackage import org.jetbrains.kotlin.idea.refactoring.invokeOnceOnCommandFinish import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.KotlinDirectoryMoveTarget import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.MoveKotlinDeclarationsProcessor import org.jetbrains.kotlin.idea.refactoring.move.moveDeclarations.analyzeConflictsInFile import org.jetbrains.kotlin.idea.util.application.runReadAction import org.jetbrains.kotlin.name.FqName import org.jetbrains.kotlin.psi.KtFile class KotlinMoveDirectoryWithClassesHelper : MoveDirectoryWithClassesHelper() { private data class FileUsagesWrapper( val psiFile: KtFile, val usages: List<UsageInfo>, val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor? ) : UsageInfo(psiFile) private class MoveContext( val newParent: PsiDirectory, val moveDeclarationsProcessor: MoveKotlinDeclarationsProcessor? ) private val fileHandler = MoveKotlinFileHandler() private var fileToMoveContext: MutableMap<PsiFile, MoveContext>? = null private fun getOrCreateMoveContextMap(): MutableMap<PsiFile, MoveContext> { return fileToMoveContext ?: HashMap<PsiFile, MoveContext>().apply { fileToMoveContext = this invokeOnceOnCommandFinish { fileToMoveContext = null } } } override fun findUsages( filesToMove: MutableCollection<PsiFile>, directoriesToMove: Array<out PsiDirectory>, result: MutableCollection<UsageInfo>, searchInComments: Boolean, searchInNonJavaFiles: Boolean, project: Project ) { filesToMove .filterIsInstance<KtFile>() .mapTo(result) { FileUsagesWrapper(it, fileHandler.findUsages(it, null, false), null) } } override fun preprocessUsages( project: Project, files: MutableSet<PsiFile>, infos: Array<UsageInfo>, directory: PsiDirectory?, conflicts: MultiMap<PsiElement, String> ) { val psiPackage = directory?.getPackage() ?: return val moveTarget = KotlinDirectoryMoveTarget(FqName(psiPackage.qualifiedName), directory.virtualFile) for ((index, usageInfo) in infos.withIndex()) { if (usageInfo !is FileUsagesWrapper) continue ProgressManager.getInstance().progressIndicator?.text2 = KotlinBundle.message("text.processing.file.0", usageInfo.psiFile.name) runReadAction { analyzeConflictsInFile(usageInfo.psiFile, usageInfo.usages, moveTarget, files, conflicts) { infos[index] = usageInfo.copy(usages = it) } } } } override fun beforeMove(psiFile: PsiFile) { } // Actual move logic is implemented in postProcessUsages since usages are not available here override fun move( file: PsiFile, moveDestination: PsiDirectory, oldToNewElementsMapping: MutableMap<PsiElement, PsiElement>, movedFiles: MutableList<PsiFile>, listener: RefactoringElementListener? ): Boolean { if (file !is KtFile) return false val moveDeclarationsProcessor = fileHandler.initMoveProcessor(file, moveDestination, false) val moveContextMap = getOrCreateMoveContextMap() moveContextMap[file] = MoveContext(moveDestination, moveDeclarationsProcessor) if (moveDeclarationsProcessor != null) { moveDestination.getFqNameWithImplicitPrefix()?.quoteIfNeeded()?.let { file.packageDirective?.fqName = it } } return true } override fun afterMove(newElement: PsiElement) { } override fun postProcessUsages(usages: Array<out UsageInfo>, newDirMapper: Function<in PsiDirectory, out PsiDirectory>) { val fileToMoveContext = fileToMoveContext ?: return try { val usagesToProcess = ArrayList<FileUsagesWrapper>() usages .filterIsInstance<FileUsagesWrapper>() .forEach body@{ val file = it.psiFile val moveContext = fileToMoveContext[file] ?: return@body MoveFilesOrDirectoriesUtil.doMoveFile(file, moveContext.newParent) val moveDeclarationsProcessor = moveContext.moveDeclarationsProcessor ?: return@body val movedFile = moveContext.newParent.findFile(file.name) ?: return@body usagesToProcess += FileUsagesWrapper(movedFile as KtFile, it.usages, moveDeclarationsProcessor) } usagesToProcess.forEach { fileHandler.retargetUsages(it.usages, it.moveDeclarationsProcessor!!) } } finally { this.fileToMoveContext = null } } }
apache-2.0
bbaa0c6541d29db872b68b1af8588451
41.416058
158
0.714286
5.528069
false
false
false
false
Anizoptera/BacKT_WebServer
src/main/kotlin/azadev/backt/webserver/utils/text.kt
1
477
package azadev.backt.webserver.utils private val REX_HTML_TAGS = "</?[a-z][^<]*?>".toRegex(RegexOption.IGNORE_CASE) fun String.removeHtmlTags() = replace(REX_HTML_TAGS, "") private val REX_HTML_BR = "<br/?>".toRegex(RegexOption.IGNORE_CASE) fun String.replaceBrWithNl() = replace(REX_HTML_BR, "\n") private val REX_WS = "[\\s\\p{Z}]+".toRegex() fun String.splitByWhitespaces() = split(REX_WS) fun String.collapseWs(collapseTo: String = " ") = replace(REX_WS, collapseTo)
mit
3cd74beceae1376797ac4c4f87a24263
33.071429
78
0.698113
3.038217
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/application/options/editor/EditorTabsOptionsModel.kt
4
2504
// 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.application.options.editor import com.intellij.ide.ui.UISettings import com.intellij.ide.ui.UISettingsState import com.intellij.openapi.application.ApplicationBundle.message import com.intellij.ui.ExperimentalUI import com.intellij.ui.layout.* internal const val EDITOR_TABS_OPTIONS_ID = "editor.preferences.tabs" private val ui: UISettingsState get() = UISettings.getInstance().state internal val showDirectoryForNonUniqueFilenames get() = CheckboxDescriptor(message("checkbox.show.directory.for.non.unique.files"), ui::showDirectoryForNonUniqueFilenames) internal val markModifiedTabsWithAsterisk: CheckboxDescriptor get() { val text = if (ExperimentalUI.isNewUI()) { message("checkbox.mark.modified.tabs") } else message("checkbox.mark.modified.tabs.with.asterisk") return CheckboxDescriptor(text, ui::markModifiedTabsWithAsterisk) } internal val showTabsTooltips get() = CheckboxDescriptor(message("checkbox.show.tabs.tooltips"), ui::showTabsTooltips) internal val showFileIcon get() = CheckboxDescriptor(message("checkbox.show.file.icon.in.editor.tabs"), ui::showFileIconInTabs) internal val showFileExtension get() = CheckboxDescriptor(message("checkbox.show.file.extension.in.editor.tabs"), PropertyBinding({ !ui.hideKnownExtensionInTabs }, { ui.hideKnownExtensionInTabs = !it })) internal val hideTabsIfNeeded get() = CheckboxDescriptor(message("checkbox.editor.scroll.if.need"), ui::hideTabsIfNeeded) internal val showPinnedTabsInASeparateRow get() = CheckboxDescriptor(message("checkbox.show.pinned.tabs.in.a.separate.row"), ui::showPinnedTabsInASeparateRow) internal val sortTabsAlphabetically get() = CheckboxDescriptor(message("checkbox.sort.tabs.alphabetically"), ui::sortTabsAlphabetically) internal val openTabsAtTheEnd get() = CheckboxDescriptor(message("checkbox.open.new.tabs.at.the.end"), ui::openTabsAtTheEnd) internal val showTabsInOneRow get() = CheckboxDescriptor(message("checkbox.editor.tabs.in.single.row"), ui::scrollTabLayoutInEditor) internal val openInPreviewTabIfPossible get() = CheckboxDescriptor(message("checkbox.smart.tab.preview"), ui::openInPreviewTabIfPossible, message("checkbox.smart.tab.preview.inline.help")) internal val useSmallFont get() = CheckboxDescriptor(message("checkbox.use.small.font.for.labels"), ui::useSmallLabelsOnTabs)
apache-2.0
1d9594e7057d3fba4a66eda2797ee501
54.644444
174
0.791534
4.439716
false
false
false
false
GunoH/intellij-community
plugins/kotlin/base/fe10/analysis/src/org/jetbrains/kotlin/idea/caches/project/multiplatformUtil.kt
4
6357
// Copyright 2000-2022 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.caches.project import com.intellij.openapi.module.Module import com.intellij.psi.PsiElement import org.jetbrains.kotlin.analyzer.ModuleInfo import org.jetbrains.kotlin.caches.resolve.KotlinCacheService import org.jetbrains.kotlin.config.KotlinSourceRootType import org.jetbrains.kotlin.config.SourceKotlinRootType import org.jetbrains.kotlin.config.TestSourceKotlinRootType import org.jetbrains.kotlin.descriptors.ModuleDescriptor import org.jetbrains.kotlin.idea.base.facet.implementingModules import org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule import org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule import org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.kotlinSourceRootType import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.PlatformModuleInfo import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull import org.jetbrains.kotlin.idea.base.projectStructure.productionSourceInfo import org.jetbrains.kotlin.idea.base.projectStructure.testSourceInfo import org.jetbrains.kotlin.idea.base.facet.implementingModules as implementingModulesNew import org.jetbrains.kotlin.platform.TargetPlatform import org.jetbrains.kotlin.platform.isCommon import org.jetbrains.kotlin.types.typeUtil.closure @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.isNewMultiPlatformModule' instead.", ReplaceWith("this.isNewMultiPlatformModule", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.isNewMPPModule: Boolean get() = isNewMultiPlatformModule @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.kotlinSourceRootType' instead.", ReplaceWith("sourceType", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.sourceType: SourceType? get() = when (kotlinSourceRootType) { TestSourceKotlinRootType -> @Suppress("DEPRECATION") SourceType.TEST SourceKotlinRootType -> @Suppress("DEPRECATION") SourceType.PRODUCTION else -> null } @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.isMultiPlatformModule' instead.", ReplaceWith("isMultiPlatformModule", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.isMPPModule: Boolean get() = isMultiPlatformModule @Deprecated( "Use 'org.jetbrains.kotlin.idea.base.facet.implementingModules' instead.", ReplaceWith("implementingModules", imports = ["org.jetbrains.kotlin.idea.base.facet"]), level = DeprecationLevel.ERROR ) @Suppress("unused") val Module.implementingModules: List<Module> get() = implementingModulesNew val ModuleDescriptor.implementingDescriptors: List<ModuleDescriptor> get() { val moduleInfo = getCapability(ModuleInfo.Capability) if (moduleInfo is PlatformModuleInfo) { return listOf(this) } val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList() val implementingModuleInfos = moduleSourceInfo.module.implementingModules .mapNotNull { module -> val sourceRootType = moduleSourceInfo.kotlinSourceRootType ?: return@mapNotNull null module.getModuleInfo(sourceRootType) } return implementingModuleInfos.mapNotNull { it.toDescriptor() } } val ModuleDescriptor.allImplementingDescriptors: Collection<ModuleDescriptor> get() = implementingDescriptors.closure(preserveOrder = true) { it.implementingDescriptors } fun Module.getModuleInfo(sourceRootType: KotlinSourceRootType): ModuleSourceInfo? { return when (sourceRootType) { SourceKotlinRootType -> productionSourceInfo TestSourceKotlinRootType -> testSourceInfo } } /** * This function returns immediate parents in dependsOn graph */ val ModuleDescriptor.implementedDescriptors: List<ModuleDescriptor> get() { val moduleInfo = getCapability(ModuleInfo.Capability) if (moduleInfo is PlatformModuleInfo) return listOf(this) val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList() return moduleSourceInfo.expectedBy.mapNotNull { it.toDescriptor() } } fun Module.toDescriptor() = (productionSourceInfo ?: testSourceInfo)?.toDescriptor() fun ModuleSourceInfo.toDescriptor() = KotlinCacheService.getInstance(module.project) .getResolutionFacadeByModuleInfo(this, platform)?.moduleDescriptor fun PsiElement.getPlatformModuleInfo(desiredPlatform: TargetPlatform): PlatformModuleInfo? { assert(!desiredPlatform.isCommon()) { "Platform module cannot have Common platform" } val moduleInfo = this.moduleInfoOrNull as? ModuleSourceInfo ?: return null return doGetPlatformModuleInfo(moduleInfo, desiredPlatform) } fun getPlatformModuleInfo(moduleInfo: ModuleSourceInfo, desiredPlatform: TargetPlatform): PlatformModuleInfo? { assert(!desiredPlatform.isCommon()) { "Platform module cannot have Common platform" } return doGetPlatformModuleInfo(moduleInfo, desiredPlatform) } private fun doGetPlatformModuleInfo(moduleInfo: ModuleSourceInfo, desiredPlatform: TargetPlatform): PlatformModuleInfo? { val platform = moduleInfo.platform return when { platform.isCommon() -> { val correspondingImplementingModule = moduleInfo.module.implementingModules .map { module -> val sourceRootType = moduleInfo.kotlinSourceRootType ?: return@map null module.getModuleInfo(sourceRootType) } .firstOrNull { it?.platform == desiredPlatform } ?: return null PlatformModuleInfo(correspondingImplementingModule, correspondingImplementingModule.expectedBy) } platform == desiredPlatform -> { val expectedBy = moduleInfo.expectedBy.takeIf { it.isNotEmpty() } ?: return null PlatformModuleInfo(moduleInfo, expectedBy) } else -> null } }
apache-2.0
5c989f549bb53791b981eb1d8bffc5c9
43.461538
158
0.762624
5.266777
false
false
false
false
GunoH/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/slicer/KotlinSliceAnalysisMode.kt
4
2546
// Copyright 2000-2022 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.slicer import com.intellij.slicer.SliceUsage import com.intellij.util.Processor import org.jetbrains.kotlin.psi.KtElement import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer data class KotlinSliceAnalysisMode(val behaviourStack: List<Behaviour>, val inlineCallStack: List<InlineFunctionCall>) { fun withBehaviour(behaviour: Behaviour) = copy(behaviourStack = behaviourStack + behaviour) fun withInlineFunctionCall( callElement: KtElement, function: KtNamedFunction ) = copy(inlineCallStack = inlineCallStack + InlineFunctionCall(callElement, function)) fun dropBehaviour(): KotlinSliceAnalysisMode { check(behaviourStack.isNotEmpty()) return copy(behaviourStack = behaviourStack.dropLast(1)) } fun popInlineFunctionCall(function: KtNamedFunction): Pair<KotlinSliceAnalysisMode?, KtElement?> { val last = inlineCallStack.lastOrNull() if (last?.function != function) return null to null val newMode = copy(inlineCallStack = inlineCallStack.dropLast(1)) return newMode to last.callElement } val currentBehaviour: Behaviour? get() = behaviourStack.lastOrNull() interface Behaviour { fun processUsages( element: KtElement, parent: KotlinSliceUsage, uniqueProcessor: Processor<in SliceUsage> ) val slicePresentationPrefix: String val testPresentationPrefix: String override fun equals(other: Any?): Boolean override fun hashCode(): Int } class InlineFunctionCall(callElement: KtElement, function: KtNamedFunction) { private val callElementPointer = callElement.createSmartPointer() private val functionPointer = function.createSmartPointer() val callElement: KtElement? get() = callElementPointer.element val function: KtNamedFunction? get() = functionPointer.element override fun equals(other: Any?): Boolean { if (this === other) return true return other is InlineFunctionCall && other.callElement == callElement && other.function == function } override fun hashCode() = 0 } companion object { val Default = KotlinSliceAnalysisMode(emptyList(), emptyList()) } }
apache-2.0
0a0b6b820ad514fa7640d33d8e50b672
35.898551
158
0.703849
5.260331
false
false
false
false
GunoH/intellij-community
plugins/full-line/python/test/org/jetbrains/completion/full/line/python/features/TransformedSuggestions.kt
2
2457
package org.jetbrains.completion.full.line.python.features import org.jetbrains.completion.full.line.platform.FullLineLookupElement import org.jetbrains.completion.full.line.python.tests.FullLinePythonCompletionTestCase class TransformedSuggestions : FullLinePythonCompletionTestCase() { private val context = "\n<caret>" fun `test empty lookup shown`() { myFixture.configureByText("fragment.py", context) clearFLCompletionCache() myFixture.completeBasic() assertNotNull(myFixture.lookup) assertTrue(myFixture.fullLineElement().isEmpty()) } fun `test not showing BOS`() = doTestNotShowing("BOS", "<BOS", "<BOS>") fun `test not showing nonsense`() = doTestNotShowing("-+|", "():", "!", ".", "()") fun `test not showing empty`() = doTestNotShowing(" ", "\t\n", "") fun `test not showing repetition`() = doTestNotShowing( "model.model.model.", "varvarvarvar", "000", ) fun `test transformed uncompleted var`() = doTestTransform("not completed_one_", "not") fun `test transformed uncompleted fun`() = doTestTransform("a = my.func.not_completed_one_", "a = my.func.") // Test that check if suggestions are not filtered/transformed fun `test showing equations`() = doTestKeepShowing("1 + 2", "1+2", "1, 2", ", 1):") fun `test showing correct samples`() = doTestKeepShowing("a", "from i import j", "a = b", "def a(1, 2, 'str'):") private fun doTestTransform(initial: String, expected: String) { myFixture.configureByText("fragment.py", context) clearFLCompletionCache() myFixture.completeFullLine(initial) assertNotNull(myFixture.lookup) val elements = myFixture.lookupElements!!.filterIsInstance<FullLineLookupElement>().map { it.lookupString } assertContainsElements(elements, expected) assertDoesntContain(elements, initial) } private fun doTestNotShowing(vararg suggestions: String) = doTestFilter(emptyList(), *suggestions) private fun doTestKeepShowing(vararg suggestions: String) = doTestFilter(suggestions.toList(), *suggestions) private fun doTestFilter(expected: List<String>, vararg suggestions: String) { myFixture.configureByText("fragment.py", context) clearFLCompletionCache() myFixture.completeFullLine(*suggestions) assertNotNull(myFixture.lookup) assertEquals( expected.sorted(), myFixture.lookupElements!!.filterIsInstance<FullLineLookupElement>().map { it.lookupString }.sorted() ) } }
apache-2.0
6efc8865dcb5de8355c93065ff758485
34.608696
114
0.718763
4.403226
false
true
false
false
jk1/intellij-community
platform/lang-impl/src/com/intellij/execution/impl/BeforeRunTaskHelper.kt
2
1979
// 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.intellij.execution.impl import com.intellij.execution.BeforeRunTask import com.intellij.execution.BeforeRunTaskProvider import com.intellij.execution.configurations.ConfigurationFactory import com.intellij.execution.configurations.RunConfiguration import com.intellij.openapi.extensions.Extensions import com.intellij.util.SmartList import com.intellij.util.containers.filterSmartMutable import com.intellij.util.containers.mapSmartSet internal fun getEffectiveBeforeRunTaskList(ownTasks: List<BeforeRunTask<*>>, templateTasks: List<BeforeRunTask<*>>, ownIsOnlyEnabled: Boolean, isDisableTemplateTasks: Boolean): List<BeforeRunTask<*>> { val idToSet = ownTasks.mapSmartSet { it.providerId } val result = ownTasks.filterSmartMutable { !ownIsOnlyEnabled || it.isEnabled } var i = 0 for (templateTask in templateTasks) { if (templateTask.isEnabled && !idToSet.contains(templateTask.providerId)) { val effectiveTemplateTask = if (isDisableTemplateTasks) { val clone = templateTask.clone() clone.isEnabled = false clone } else { templateTask } result.add(i, effectiveTemplateTask) i++ } } return result } internal fun getHardcodedBeforeRunTasks(configuration: RunConfiguration, factory: ConfigurationFactory): List<BeforeRunTask<*>> { var result: MutableList<BeforeRunTask<*>>? = null for (provider in Extensions.getExtensions(BeforeRunTaskProvider.EXTENSION_POINT_NAME, configuration.project)) { val task = provider.createTask(configuration) ?: continue if (task.isEnabled) { factory.configureBeforeRunTaskDefaults(provider.id, task) if (task.isEnabled) { if (result == null) { result = SmartList<BeforeRunTask<*>>() } result.add(task) } } } return result.orEmpty() }
apache-2.0
7ff1ebfb8e69d0a3773feb0b15a3684d
39.408163
201
0.740778
4.602326
false
true
false
false
AoDevBlue/AnimeUltimeTv
app/src/main/java/blue/aodev/animeultimetv/data/converters/AnimeSummaryAdapter.kt
1
2695
package blue.aodev.animeultimetv.data.converters import blue.aodev.animeultimetv.domain.model.AnimeSummary import blue.aodev.animeultimetv.domain.model.AnimeType import org.jsoup.Jsoup import okhttp3.ResponseBody import org.jsoup.nodes.Element import retrofit2.Converter import retrofit2.Retrofit import java.lang.reflect.ParameterizedType import java.lang.reflect.Type internal class AnimeSummaryAdapter : Converter<ResponseBody, List<AnimeSummary>> { companion object { val FACTORY: Converter.Factory = object : Converter.Factory() { override fun responseBodyConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit): Converter<ResponseBody, *>? { if (type is ParameterizedType && getRawType(type) === List::class.java && getParameterUpperBound(0, type) === AnimeSummary::class.java) { return AnimeSummaryAdapter() } return null } } private val idRegex = Regex("""(?<=/)(.+?)(?=-)""") private val imageRegex = Regex("""[^=]+$""") } override fun convert(responseBody: ResponseBody): List<AnimeSummary> { val result = Jsoup.parse(responseBody.string()) .select(".jtable tr:not(:first-child)") .map { convertAnimeElement(it) } return result } private fun convertAnimeElement(animeElement: Element): AnimeSummary { val aImageElement = animeElement.child(0).child(0) val rawId = aImageElement.attr("href") val id = idRegex.find(rawId)?.value?.toInt() ?: -1 val imageElement = aImageElement.child(0) val title = imageElement.attr("title") val rawImageUrl = imageElement.attr("data-href") val imageUrl = imageRegex.find(rawImageUrl)?.value ?.let { "http://www.anime-ultime.net/" + it } val rawType = animeElement.child(2).text() val type = when (rawType) { "Episode" -> AnimeType.ANIME "OAV" -> AnimeType.OAV "Film" -> AnimeType.MOVIE else -> AnimeType.ANIME } val rawCount = animeElement.child(3).text() val splitCount = rawCount.split("/") val availableCount = splitCount.first().toDoubleOrNull()?.toInt() ?: 0 val totalCount = splitCount.last().toDoubleOrNull()?.toInt() ?: 0 val rawRating = animeElement.child(4).text() val rating = rawRating.split("/").firstOrNull()?.toFloatOrNull() ?: 0f return AnimeSummary(id, title, imageUrl, type, availableCount, totalCount, rating) } }
mit
4248ab421a17e96701ab7cfb2f1a0ca7
38.072464
97
0.614471
4.670711
false
false
false
false
code-disaster/lwjgl3
modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_multitexture.kt
4
8884
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package opengl.templates import org.lwjgl.generator.* import opengl.* val ARB_multitexture = "ARBMultitexture".nativeClassGL("ARB_multitexture", postfix = ARB) { documentation = """ Native bindings to the $registryLink extension. This extension allows application of multiple textures to a fragment in one rendering pass. ${GL13.promoted} """ IntConstant( "Accepted by the {@code texture} parameter of ActiveTexture and MultiTexCoord.", "TEXTURE0_ARB"..0x84C0, "TEXTURE1_ARB"..0x84C1, "TEXTURE2_ARB"..0x84C2, "TEXTURE3_ARB"..0x84C3, "TEXTURE4_ARB"..0x84C4, "TEXTURE5_ARB"..0x84C5, "TEXTURE6_ARB"..0x84C6, "TEXTURE7_ARB"..0x84C7, "TEXTURE8_ARB"..0x84C8, "TEXTURE9_ARB"..0x84C9, "TEXTURE10_ARB"..0x84CA, "TEXTURE11_ARB"..0x84CB, "TEXTURE12_ARB"..0x84CC, "TEXTURE13_ARB"..0x84CD, "TEXTURE14_ARB"..0x84CE, "TEXTURE15_ARB"..0x84CF, "TEXTURE16_ARB"..0x84D0, "TEXTURE17_ARB"..0x84D1, "TEXTURE18_ARB"..0x84D2, "TEXTURE19_ARB"..0x84D3, "TEXTURE20_ARB"..0x84D4, "TEXTURE21_ARB"..0x84D5, "TEXTURE22_ARB"..0x84D6, "TEXTURE23_ARB"..0x84D7, "TEXTURE24_ARB"..0x84D8, "TEXTURE25_ARB"..0x84D9, "TEXTURE26_ARB"..0x84DA, "TEXTURE27_ARB"..0x84DB, "TEXTURE28_ARB"..0x84DC, "TEXTURE29_ARB"..0x84DD, "TEXTURE30_ARB"..0x84DE, "TEXTURE31_ARB"..0x84DF ) IntConstant( "Accepted by the {@code pname} parameter of GetBooleanv, GetDoublev, GetIntegerv, and GetFloatv.", "ACTIVE_TEXTURE_ARB"..0x84E0, "CLIENT_ACTIVE_TEXTURE_ARB"..0x84E1, "MAX_TEXTURE_UNITS_ARB"..0x84E2 ) void( "ActiveTextureARB", """ Selects which texture unit subsequent texture state calls will affect. The number of texture units an implementation supports is implementation dependent. """, GLenum("texture", "which texture unit to make active", "#TEXTURE0_ARB GL_TEXTURE[1-31]") ) void( "ClientActiveTextureARB", """ Selects the vertex array client state parameters to be modified by the TexCoordPointer command and the array affected by EnableClientState and DisableClientState with parameter TEXTURE_COORD_ARRAY. """, GLenum("texture", "which texture coordinate array to make active", "#TEXTURE0_ARB GL_TEXTURE[1-31]") ) // MultiTexCoord functions javadoc val texCoordTex = "the coordinate set to be modified" val texCoordS = "the s component of the current texture coordinates" val texCoordT = "the t component of the current texture coordinates" val texCoordR = "the r component of the current texture coordinates" val texCoordQ = "the q component of the current texture coordinates" val texCoordBuffer = "the texture coordinate buffer" void( "MultiTexCoord1fARB", "Sets the current one-dimensional texture coordinate for the specified texture coordinate set. {@code t} and {@code r} are implicitly set to 0 and {@code q} to 1.", GLenum("texture", texCoordTex), GLfloat("s", texCoordS) ) void("MultiTexCoord1sARB", "Short version of #MultiTexCoord1fARB().", GLenum("texture", texCoordTex), GLshort("s", texCoordS)) void("MultiTexCoord1iARB", "Integer version of #MultiTexCoord1fARB().", GLenum("texture", texCoordTex), GLint("s", texCoordS)) void("MultiTexCoord1dARB", "Double version of #MultiTexCoord1fARB().", GLenum("texture", texCoordTex), GLdouble("s", texCoordS)) void("MultiTexCoord1fvARB", "Pointer version of #MultiTexCoord1fARB().", GLenum("texture", texCoordTex), Check(1)..GLfloat.const.p("v", texCoordBuffer)) void("MultiTexCoord1svARB", "Pointer version of #MultiTexCoord1sARB().", GLenum("texture", texCoordTex), Check(1)..GLshort.const.p("v", texCoordBuffer)) void("MultiTexCoord1ivARB", "Pointer version of #MultiTexCoord1iARB().", GLenum("texture", texCoordTex), Check(1)..GLint.const.p("v", texCoordBuffer)) void("MultiTexCoord1dvARB", "Pointer version of #MultiTexCoord1dARB().", GLenum("texture", texCoordTex), Check(1)..GLdouble.const.p("v", texCoordBuffer)) void( "MultiTexCoord2fARB", "Sets the current two-dimensional texture coordinate for the specified texture coordinate set. {@code r} is implicitly set to 0 and {@code q} to 1.", GLenum("texture", texCoordTex), GLfloat("s", texCoordS), GLfloat("t", texCoordT) ) void("MultiTexCoord2sARB", "Short version of #MultiTexCoord2fARB().", GLenum("texture", texCoordTex), GLshort("s", texCoordS), GLshort("t", texCoordT)) void("MultiTexCoord2iARB", "Integer version of #MultiTexCoord2fARB().", GLenum("texture", texCoordTex), GLint("s", texCoordS), GLint("t", texCoordT)) void("MultiTexCoord2dARB", "Double version of #MultiTexCoord2fARB().", GLenum("texture", texCoordTex), GLdouble("s", texCoordS), GLdouble("t", texCoordT)) void("MultiTexCoord2fvARB", "Pointer version of #MultiTexCoord2fARB().", GLenum("texture", texCoordTex), Check(2)..GLfloat.const.p("v", texCoordBuffer)) void("MultiTexCoord2svARB", "Pointer version of #MultiTexCoord2sARB().", GLenum("texture", texCoordTex), Check(2)..GLshort.const.p("v", texCoordBuffer)) void("MultiTexCoord2ivARB", "Pointer version of #MultiTexCoord2iARB().", GLenum("texture", texCoordTex), Check(2)..GLint.const.p("v", texCoordBuffer)) void("MultiTexCoord2dvARB", "Pointer version of #MultiTexCoord2dARB().", GLenum("texture", texCoordTex), Check(2)..GLdouble.const.p("v", texCoordBuffer)) void( "MultiTexCoord3fARB", "Sets the current three-dimensional texture coordinate for the specified texture coordinate set. {@code q} is implicitly set to 1.", GLenum("texture", texCoordTex), GLfloat("s", texCoordS), GLfloat("t", texCoordT), GLfloat("r", texCoordR) ) void("MultiTexCoord3sARB", "Short version of #MultiTexCoord3fARB().", GLenum("texture", texCoordTex), GLshort("s", texCoordS), GLshort("t", texCoordT), GLshort("r", texCoordR)) void("MultiTexCoord3iARB", "Integer version of #MultiTexCoord3fARB().", GLenum("texture", texCoordTex), GLint("s", texCoordS), GLint("t", texCoordT), GLint("r", texCoordR)) void("MultiTexCoord3dARB", "Double version of #MultiTexCoord3fARB().", GLenum("texture", texCoordTex), GLdouble("s", texCoordS), GLdouble("t", texCoordT), GLdouble("r", texCoordR)) void("MultiTexCoord3fvARB", "Pointer version of #MultiTexCoord3fARB().", GLenum("texture", texCoordTex), Check(3)..GLfloat.const.p("v", texCoordBuffer)) void("MultiTexCoord3svARB", "Pointer version of #MultiTexCoord3sARB().", GLenum("texture", texCoordTex), Check(3)..GLshort.const.p("v", texCoordBuffer)) void("MultiTexCoord3ivARB", "Pointer version of #MultiTexCoord3iARB().", GLenum("texture", texCoordTex), Check(3)..GLint.const.p("v", texCoordBuffer)) void("MultiTexCoord3dvARB", "Pointer version of #MultiTexCoord3dARB().", GLenum("texture", texCoordTex), Check(3)..GLdouble.const.p("v", texCoordBuffer)) void( "MultiTexCoord4fARB", "Sets the current four-dimensional texture coordinate for the specified texture coordinate set.", GLenum("texture", texCoordTex), GLfloat("s", texCoordS), GLfloat("t", texCoordT), GLfloat("r", texCoordR), GLfloat("q", texCoordQ) ) void("MultiTexCoord4sARB", "Short version of #MultiTexCoord4fARB().", GLenum("texture", texCoordTex), GLshort("s", texCoordS), GLshort("t", texCoordT), GLshort("r", texCoordR), GLshort("q", texCoordQ)) void("MultiTexCoord4iARB", "Integer version of #MultiTexCoord4fARB().", GLenum("texture", texCoordTex), GLint("s", texCoordS), GLint("t", texCoordT), GLint("r", texCoordR), GLint("q", texCoordQ)) void("MultiTexCoord4dARB", "Double version of #MultiTexCoord4fARB().", GLenum("texture", texCoordTex), GLdouble("s", texCoordS), GLdouble("t", texCoordT), GLdouble("r", texCoordR), GLdouble("q", texCoordQ)) void("MultiTexCoord4fvARB", "Pointer version of #MultiTexCoord4fARB().", GLenum("texture", texCoordTex), Check(4)..GLfloat.const.p("v", texCoordBuffer)) void("MultiTexCoord4svARB", "Pointer version of #MultiTexCoord4sARB().", GLenum("texture", texCoordTex), Check(4)..GLshort.const.p("v", texCoordBuffer)) void("MultiTexCoord4ivARB", "Pointer version of #MultiTexCoord4iARB().", GLenum("texture", texCoordTex), Check(4)..GLint.const.p("v", texCoordBuffer)) void("MultiTexCoord4dvARB", "Pointer version of #MultiTexCoord4dARB().", GLenum("texture", texCoordTex), Check(4)..GLdouble.const.p("v", texCoordBuffer)) }
bsd-3-clause
fef9c299517cbfc7e6ff73bf43ada729
52.524096
210
0.677735
4.184644
false
false
false
false
andriydruk/R.tools
app/src/main/kotlin/com/druk/rtools/QualifierDetailActivity.kt
1
2685
/* * Copyright (C) 2015 Andriy Druk * * 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.druk.rtools import android.content.Intent import android.os.Bundle import android.support.v4.app.NavUtils import android.support.v7.app.AppCompatActivity import android.view.MenuItem import kotlinx.android.synthetic.main.activity_qualifier_detail.* /** * An activity representing a single Qualifier detail screen. This * activity is only used on handset devices. On tablet-size devices, * item details are presented side-by-side with a list of items * in a [MainActivity]. * * * This activity is mostly just a 'shell' activity containing nothing * more than a [QualifierDetailFragment]. */ class QualifierDetailActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_qualifier_detail) // Show the Up button in the action bar. setSupportActionBar(toolbar) supportActionBar!!.setDisplayHomeAsUpEnabled(true) val qualifier = Qualifier.getQualifier(intent.getIntExtra(QualifierDetailFragment.ARG_ITEM_ID, -1)) setTitle(qualifier.nameResource) if (savedInstanceState == null) { supportFragmentManager.beginTransaction().add(R.id.qualifier_detail_container, QualifierDetailFragment.newInstance(qualifier.ordinal)).commit() } } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (id == android.R.id.home) { // This ID represents the Home or Up button. In the case of this // activity, the Up button is shown. Use NavUtils to allow users // to navigate up one level in the application structure. For // more details, see the Navigation pattern on Android Design: // // http://developer.android.com/design/patterns/navigation.html#up-vs-back // NavUtils.navigateUpTo(this, Intent(this, MainActivity::class.java)) return true } return super.onOptionsItemSelected(item) } }
apache-2.0
c8dbbca334aa2d7499a1a61515bffd7e
37.357143
107
0.700931
4.574106
false
false
false
false
syrop/GPS-Texter
texter/src/main/kotlin/pl/org/seva/texter/stats/StatsFragment.kt
1
10370
/* * Copyright (C) 2017 Wiktor Nizio * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If you like this program, consider donating bitcoin: bc1qncxh5xs6erq6w4qz3a7xl7f50agrgn3w58dsfp */ package pl.org.seva.texter.stats import android.Manifest import android.annotation.SuppressLint import android.content.pm.PackageManager import android.os.Bundle import android.preference.PreferenceManager import androidx.fragment.app.Fragment import androidx.core.content.ContextCompat import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.android.gms.maps.* import com.google.android.gms.maps.model.BitmapDescriptorFactory import com.google.android.gms.maps.model.CameraPosition import com.google.android.gms.maps.model.LatLng import com.google.android.gms.maps.model.MarkerOptions import kotlinx.android.synthetic.main.fragment_stats.* import java.util.Calendar import pl.org.seva.texter.R import pl.org.seva.texter.main.Permissions import pl.org.seva.texter.data.SmsLocation import pl.org.seva.texter.main.permissions import pl.org.seva.texter.movement.activityRecognition import pl.org.seva.texter.movement.location import pl.org.seva.texter.sms.smsSender class StatsFragment : Fragment() { private var distance: Double = 0.0 private var speed: Double = 0.0 private var isStationary: Boolean = false private var mapFragment: SupportMapFragment? = null private var map: GoogleMap? = null private var locationPermissionGranted = false private var zoom = 0.0f override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) createSubscriptions() } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { distance = location.distance speed = location.speed zoom = PreferenceManager.getDefaultSharedPreferences(activity) .getFloat(ZOOM_PROPERTY_NAME, DEFAULT_ZOOM) homeString = getString(R.string.home) hourString = requireActivity().getString(R.string.hour) speedUnitStr = getString(R.string.speed_unit) return inflater.inflate(R.layout.fragment_stats, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) send_now_button.setOnClickListener { onSendNowClicked() } send_now_button.isEnabled = smsSender.isTextingEnabled && distance != 0.0 && distance != smsSender.lastSentDistance showStats() MapsInitializer.initialize(requireActivity().applicationContext) val mapFragment = childFragmentManager.findFragmentById(R.id.map) as SupportMapFragment mapFragment.getMapAsync { it.onReady() } } @SuppressLint("MissingPermission") private fun GoogleMap.onReady() { map = this processLocationPermission() val homeLatLng = location.homeLatLng updateHomeLocation(homeLatLng) val cameraPosition = CameraPosition.Builder() .target(homeLatLng).zoom(zoom).build() checkNotNull(map).moveCamera(CameraUpdateFactory.newCameraPosition(cameraPosition)) if (locationPermissionGranted) { checkNotNull(map).isMyLocationEnabled = true } checkNotNull(map).setOnCameraIdleListener { onCameraIdle() } } private fun onCameraIdle() { zoom = checkNotNull(map).cameraPosition.zoom PreferenceManager.getDefaultSharedPreferences(activity).edit().putFloat(ZOOM_PROPERTY_NAME, zoom).apply() } private fun updateHomeLocation(homeLocation: LatLng?) { if (map == null || homeLocation == null) { return } val marker = MarkerOptions().position(homeLocation).title(homeString) // Changing marker icon marker.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ROSE)) // adding marker checkNotNull(map).clear() checkNotNull(map).addMarker(marker) } @SuppressLint("CheckResult") private fun processLocationPermission() { if (ContextCompat.checkSelfPermission( requireContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { locationPermissionGranted = true map?.isMyLocationEnabled = true onLocationPermissionGranted() } else { permissions.permissionGrantedListener() .filter { it.first == Permissions.LOCATION_PERMISSION_REQUEST_ID } .filter { it.second == Manifest.permission.ACCESS_FINE_LOCATION } .subscribe { onLocationPermissionGranted() } } } @SuppressLint("MissingPermission") private fun onLocationPermissionGranted() { locationPermissionGranted = true map?.isMyLocationEnabled = true } private fun createSubscriptions() { location.addDistanceChangedListenerUi(lifecycle) { onDistanceChanged() } location.addHomeChangedListener(lifecycle) { onHomeChanged() } timer.addTimerListenerUi(lifecycle) { showStats() } smsSender.addSmsSendingListenerUi(lifecycle) { onSendingSms() } activityRecognition.addActivityRecognitionListener( lifecycle, stationary = ::onDeviceStationary, moving = ::onDeviceMoving) } override fun onSaveInstanceState(outState: Bundle) { deleteMapFragment() super.onSaveInstanceState(outState) } override fun onStop() { deleteMapFragment() super.onStop() } private fun deleteMapFragment() { mapFragment?.let { checkNotNull(fragmentManager).beginTransaction().remove(it).commitAllowingStateLoss() mapFragment = null } } private fun onDeviceStationary() { isStationary = true } private fun onDeviceMoving() { isStationary = false } private fun showStats() { distance_value.text = if (distance == 0.0) { "0 km" } else { formattedDistanceStr } stationary.visibility = if (isStationary) View.VISIBLE else View.INVISIBLE update_interval_value.text = formattedTimeStr if (speed == 0.0 || distance == 0.0) { speed_value.visibility = View.INVISIBLE } else { speed_value.visibility = View.VISIBLE speed_value.text = formattedSpeedStr } } private val formattedDistanceStr : String get() = String.format("%.3f km", distance) private val formattedSpeedStr: String get() { @SuppressLint("DefaultLocale") var result = String.format("%.1f", if (isStationary) 0.0 else speed) + " " + speedUnitStr if (result.contains(".0")) { result = result.replace(".0", "") } else if (result.contains(",0")) { result = result.replace(",0", "") } return result } private val formattedTimeStr: String get() { var seconds = (System.currentTimeMillis() - timer.resetTime).toInt() / 1000 var minutes = seconds / 60 seconds %= 60 val hours = minutes / 60 minutes %= 60 val timeStrBuilder = StringBuilder() if (hours > 0) { timeStrBuilder.append(hours).append(" ").append(hourString) if (minutes > 0 || seconds > 0) { timeStrBuilder.append(" ") } } if (minutes > 0) { timeStrBuilder.append(minutes).append(" m") if (seconds > 0) { timeStrBuilder.append(" ") } } if (seconds > 0) { timeStrBuilder.append(seconds).append(" s") } else if (minutes == 0 && hours == 0) { timeStrBuilder.setLength(0) timeStrBuilder.append("0 s") } return timeStrBuilder.toString() } private fun onDistanceChanged() { if (distance != smsSender.lastSentDistance) { send_now_button.isEnabled = smsSender.isTextingEnabled } val threeHoursPassed = System.currentTimeMillis() - timer.resetTime > 3 * 3600 * 1000 if (threeHoursPassed) { this.speed = 0.0 this.distance = 0.0 } else { this.distance = location.distance this.speed = location.speed } showStats() } @SuppressLint("WrongConstant") private fun onSendNowClicked() { send_now_button.isEnabled = false val calendar = Calendar.getInstance() calendar.timeInMillis = timer.resetTime val minutes = calendar.get(Calendar.HOUR_OF_DAY) * 60 + calendar.get(Calendar.MINUTE) val location = SmsLocation() location.distance = distance location.direction = 0 location.setTime(minutes) location.speed = speed smsSender.send(location) } private fun onSendingSms() { send_now_button.isEnabled = false } private fun onHomeChanged() { distance = location.distance showStats() } companion object { private const val ZOOM_PROPERTY_NAME = "stats_map_zoom" private const val DEFAULT_ZOOM = 7.5f var homeString: String? = null private lateinit var hourString: String private lateinit var speedUnitStr: String fun newInstance() = StatsFragment() } }
gpl-3.0
c172945d1b8b009699ca4a14ad701e5b
34.033784
113
0.641273
4.87312
false
false
false
false
dbrant/apps-android-wikipedia
app/src/main/java/org/wikipedia/views/WikitextKeyboardButtonView.kt
1
2867
package org.wikipedia.views import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.ViewGroup import android.widget.FrameLayout import androidx.appcompat.content.res.AppCompatResources import androidx.core.content.withStyledAttributes import org.wikipedia.R import org.wikipedia.databinding.ViewWikitextKeyboardButtonBinding import org.wikipedia.util.FeedbackUtil.setButtonLongPressToast import org.wikipedia.util.ResourceUtil.getThemedAttributeId import org.wikipedia.util.ResourceUtil.getThemedColor class WikitextKeyboardButtonView constructor(context: Context, attrs: AttributeSet?) : FrameLayout(context, attrs) { init { val binding = ViewWikitextKeyboardButtonBinding.inflate(LayoutInflater.from(context), this) layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) attrs?.let { context.withStyledAttributes(it, R.styleable.WikitextKeyboardButtonView) { val drawableId = getResourceId(R.styleable.WikitextKeyboardButtonView_buttonImage, 0) val buttonText = getString(R.styleable.WikitextKeyboardButtonView_buttonText) val buttonHint = getString(R.styleable.WikitextKeyboardButtonView_buttonHint) val buttonTextColor = getColor(R.styleable.WikitextKeyboardButtonView_buttonTextColor, getThemedColor(context, R.attr.material_theme_secondary_color)) if (drawableId != 0) { binding.wikitextButtonText.visibility = GONE binding.wikitextButtonHint.visibility = GONE binding.wikitextButtonImage.visibility = VISIBLE binding.wikitextButtonImage.setImageResource(drawableId) } else { binding.wikitextButtonText.visibility = VISIBLE binding.wikitextButtonHint.visibility = VISIBLE binding.wikitextButtonImage.visibility = GONE if (!buttonHint.isNullOrEmpty()) { binding.wikitextButtonText.text = buttonText } binding.wikitextButtonText.setTextColor(buttonTextColor) if (!buttonHint.isNullOrEmpty()) { binding.wikitextButtonHint.text = buttonHint } } if (!buttonHint.isNullOrEmpty()) { contentDescription = buttonHint setButtonLongPressToast(this@WikitextKeyboardButtonView) } } } isClickable = true isFocusable = true background = AppCompatResources.getDrawable(context, getThemedAttributeId(context, android.R.attr.selectableItemBackground)) } }
apache-2.0
019d9273dc2548e4f07e1eae322766aa
50.196429
119
0.673526
5.997908
false
false
false
false