repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
mrkirby153/KirBot
src/main/kotlin/me/mrkirby153/KirBot/command/executors/moderation/infraction/TempMute.kt
1
3602
package me.mrkirby153.KirBot.command.executors.moderation.infraction import me.mrkirby153.KirBot.command.CommandCategory import me.mrkirby153.KirBot.command.CommandException import me.mrkirby153.KirBot.command.annotations.Command import me.mrkirby153.KirBot.command.annotations.CommandDescription import me.mrkirby153.KirBot.command.annotations.IgnoreWhitelist import me.mrkirby153.KirBot.command.annotations.LogInModlogs import me.mrkirby153.KirBot.command.args.CommandContext import me.mrkirby153.KirBot.infraction.Infractions import me.mrkirby153.KirBot.user.CLEARANCE_MOD import me.mrkirby153.KirBot.utils.Context import me.mrkirby153.KirBot.utils.canInteractWith import me.mrkirby153.KirBot.utils.getMember import me.mrkirby153.KirBot.utils.nameAndDiscrim import me.mrkirby153.kcutils.Time import net.dv8tion.jda.api.Permission import net.dv8tion.jda.api.entities.TextChannel import net.dv8tion.jda.api.entities.User import java.util.concurrent.TimeUnit import javax.inject.Inject class TempMute @Inject constructor(private val infractions: Infractions) { @Command(name = "tempmute", arguments = ["<user:user>", "<time:string>", "[reason:string...]"], permissions = [Permission.MANAGE_ROLES], clearance = CLEARANCE_MOD, category = CommandCategory.MODERATION) @LogInModlogs @CommandDescription("Temporarily mute the given user") @IgnoreWhitelist fun execute(context: Context, cmdContext: CommandContext) { val user = cmdContext.get<User>("user")!! val member = user.getMember(context.guild) ?: throw CommandException( "This user isn't a part of the guild!") val time = cmdContext.get<String>("time")!! val reason = cmdContext.get<String>("reason") val timeParsed = Time.parse(time) if (timeParsed <= 0) { throw CommandException("Please provide a time greater than 0") } if (context.channel !is TextChannel) throw CommandException("This command won't work in PMs") if (!context.author.canInteractWith(context.guild, user)) throw CommandException("Missing permissions") val highest = context.guild.selfMember.roles.map { it.position }.max() ?: 0 val mutedRole = infractions.getMutedRole(context.guild) ?: throw CommandException( "could not get the muted role") if (mutedRole.position > highest) throw CommandException("cannot assign the muted role") infractions.tempMute(user.id, context.guild, context.author.id, timeParsed, TimeUnit.MILLISECONDS, reason).handle { result, t -> if (t != null || !result.successful) { context.send().error("Could not temp-mute ${user.nameAndDiscrim}: ${t ?: result.errorMessage}").queue() return@handle } context.send().success( "Muted ${user.nameAndDiscrim} for ${Time.format(1, timeParsed)}" + buildString { if (reason != null) { append(" (`$reason`)") } when (result.dmResult) { Infractions.DmResult.SENT -> append(" _Successfully messaged the user_") Infractions.DmResult.SEND_ERROR -> append(" _Could not send DM to user._") else -> { } } }, true).queue() } } }
mit
eeb3fa9b0e4a287c2bcb1d7df0df9856
42.409639
100
0.631871
4.536524
false
false
false
false
noties/Markwon
app-sample/src/main/java/io/noties/markwon/app/samples/ExcludeFromParsingSample.kt
1
2261
package io.noties.markwon.app.samples import android.text.SpannableStringBuilder import io.noties.debug.Debug import io.noties.markwon.Markwon import io.noties.markwon.app.sample.ui.MarkwonTextViewSample import io.noties.markwon.sample.annotations.MarkwonArtifact import io.noties.markwon.sample.annotations.MarkwonSampleInfo import io.noties.markwon.sample.annotations.Tag import java.util.regex.Pattern @MarkwonSampleInfo( id = "20201111221945", title = "Exclude part of input from parsing", description = "Exclude part of input from parsing by splitting input with delimiters", artifacts = [MarkwonArtifact.CORE], tags = [Tag.parsing] ) class ExcludeFromParsingSample : MarkwonTextViewSample() { override fun render() { // cannot have continuous markdown between parts (so a node started in one part and ended in other) // with this approach // also exclude will start a new block and won't seamlessly continue any existing markdown one (so // if started inside a blockquote, then blockquote would be closed) val md = """ # Hello we are **going** to exclude some parts of this input _from_ parsing $EXCLUDE_START what is **good** is that we > do not need to care about blocks or inlines * and * everything * else $EXCLUDE_END **then** markdown _again_ and empty exclude at end: $EXCLUDE_START$EXCLUDE_END """.trimIndent() val markwon = Markwon.create(context) val matcher = Pattern.compile(RE, Pattern.MULTILINE).matcher(md) val builder by lazy(LazyThreadSafetyMode.NONE) { SpannableStringBuilder() } var end: Int = 0 while (matcher.find()) { val start = matcher.start() Debug.i(end, start, md.substring(end, start)) builder.append(markwon.toMarkdown(md.substring(end, start))) builder.append(matcher.group(1)) end = matcher.end() } if (end != md.length) { builder.append(markwon.toMarkdown(md.substring(end))) } markwon.setParsedMarkdown(textView, builder) } private companion object { const val EXCLUDE_START = "##IGNORE##" const val EXCLUDE_END = "--IGNORE--" const val RE = "${EXCLUDE_START}([\\s\\S]*?)${EXCLUDE_END}" } }
apache-2.0
3a96bcfbbdc51c7b87b2ac827a6c0529
29.16
103
0.687749
4.148624
false
false
false
false
italoag/qksms
presentation/src/main/java/com/moez/QKSMS/common/MenuItemAdapter.kt
3
3748
/* * Copyright (C) 2017 Moez Bhatti <[email protected]> * * This file is part of QKSMS. * * QKSMS is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * QKSMS is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with QKSMS. If not, see <http://www.gnu.org/licenses/>. */ package com.moez.QKSMS.common import android.content.Context import android.content.res.ColorStateList import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.ArrayRes import androidx.recyclerview.widget.RecyclerView import com.moez.QKSMS.R import com.moez.QKSMS.common.base.QkAdapter import com.moez.QKSMS.common.base.QkViewHolder import com.moez.QKSMS.common.util.Colors import com.moez.QKSMS.common.util.extensions.resolveThemeColor import com.moez.QKSMS.common.util.extensions.setVisible import io.reactivex.disposables.CompositeDisposable import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.Subject import kotlinx.android.synthetic.main.menu_list_item.* import kotlinx.android.synthetic.main.menu_list_item.view.* import javax.inject.Inject data class MenuItem(val title: String, val actionId: Int) class MenuItemAdapter @Inject constructor(private val context: Context, private val colors: Colors) : QkAdapter<MenuItem>() { val menuItemClicks: Subject<Int> = PublishSubject.create() private val disposables = CompositeDisposable() var selectedItem: Int? = null set(value) { val old = data.map { it.actionId }.indexOfFirst { it == field } val new = data.map { it.actionId }.indexOfFirst { it == value } field = value old.let { notifyItemChanged(it) } new.let { notifyItemChanged(it) } } fun setData(@ArrayRes titles: Int, @ArrayRes values: Int = -1) { val valueInts = if (values != -1) context.resources.getIntArray(values) else null data = context.resources.getStringArray(titles) .mapIndexed { index, title -> MenuItem(title, valueInts?.getOrNull(index) ?: index) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QkViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val view = layoutInflater.inflate(R.layout.menu_list_item, parent, false) val states = arrayOf( intArrayOf(android.R.attr.state_activated), intArrayOf(-android.R.attr.state_activated)) val text = parent.context.resolveThemeColor(android.R.attr.textColorTertiary) view.check.imageTintList = ColorStateList(states, intArrayOf(colors.theme().theme, text)) return QkViewHolder(view).apply { view.setOnClickListener { val menuItem = getItem(adapterPosition) menuItemClicks.onNext(menuItem.actionId) } } } override fun onBindViewHolder(holder: QkViewHolder, position: Int) { val menuItem = getItem(position) holder.title.text = menuItem.title holder.check.isActivated = (menuItem.actionId == selectedItem) holder.check.setVisible(selectedItem != null) } override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) { super.onDetachedFromRecyclerView(recyclerView) disposables.clear() } }
gpl-3.0
a04dcb95990a1f82a2563b5b249e5a7d
37.255102
125
0.712113
4.399061
false
false
false
false
googlecodelabs/fido2-codelab
android/app/src/main/java/com/example/android/fido2/api/AuthApi.kt
1
20970
/* * Copyright 2019 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.fido2.api import android.util.JsonReader import android.util.JsonToken import android.util.JsonWriter import android.util.Log import com.example.android.fido2.BuildConfig import com.example.android.fido2.decodeBase64 import com.example.android.fido2.toBase64 import com.google.android.gms.fido.fido2.api.common.Attachment import com.google.android.gms.fido.fido2.api.common.AuthenticatorAssertionResponse import com.google.android.gms.fido.fido2.api.common.AuthenticatorAttestationResponse import com.google.android.gms.fido.fido2.api.common.AuthenticatorSelectionCriteria import com.google.android.gms.fido.fido2.api.common.PublicKeyCredential import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialCreationOptions import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialDescriptor import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialParameters import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialRequestOptions import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialRpEntity import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialType import com.google.android.gms.fido.fido2.api.common.PublicKeyCredentialUserEntity import okhttp3.MediaType.Companion.toMediaTypeOrNull import okhttp3.OkHttpClient import okhttp3.Request import okhttp3.RequestBody import okhttp3.RequestBody.Companion.toRequestBody import okhttp3.Response import okhttp3.ResponseBody import ru.gildor.coroutines.okhttp.await import java.io.StringReader import java.io.StringWriter import javax.inject.Inject /** * Interacts with the server API. */ class AuthApi @Inject constructor( private val client: OkHttpClient ) { companion object { private const val BASE_URL = BuildConfig.API_BASE_URL private val JSON = "application/json".toMediaTypeOrNull() private const val SessionIdKey = "connect.sid=" private const val TAG = "AuthApi" } /** * @param username The username to be used for sign-in. * @return The Session ID. */ suspend fun username(username: String): ApiResult<Unit> { val call = client.newCall( Request.Builder() .url("$BASE_URL/username") .method("POST", jsonRequestBody { name("username").value(username) }) .build() ) val response = call.await() return response.result("Error calling /username") { } } /** * @param sessionId The session ID received on `username()`. * @param password A password. * @return An [ApiResult]. */ suspend fun password(sessionId: String, password: String): ApiResult<Unit> { val call = client.newCall( Request.Builder() .url("$BASE_URL/password") .addHeader("Cookie", formatCookie(sessionId)) .method("POST", jsonRequestBody { name("password").value(password) }) .build() ) val response = call.await() return response.result("Error calling /password") { } } /** * @param sessionId The session ID. * @return A list of all the credentials registered on the server. */ suspend fun getKeys(sessionId: String): ApiResult<List<Credential>> { val call = client.newCall( Request.Builder() .url("$BASE_URL/getKeys") .addHeader("Cookie", formatCookie(sessionId)) .method("POST", jsonRequestBody {}) .build() ) val response = call.await() return response.result("Error calling /getKeys") { parseUserCredentials(body ?: throw ApiException("Empty response from /getKeys")) } } /** * @param sessionId The session ID. * @return A pair. The `first` element is an [PublicKeyCredentialCreationOptions] that can be * used for a subsequent FIDO2 API call. The `second` element is a challenge string that should * be sent back to the server in [registerResponse]. */ suspend fun registerRequest(sessionId: String): ApiResult<PublicKeyCredentialCreationOptions> { val call = client.newCall( Request.Builder() .url("$BASE_URL/registerRequest") .addHeader("Cookie", formatCookie(sessionId)) .method("POST", jsonRequestBody { name("attestation").value("none") name("authenticatorSelection").objectValue { name("authenticatorAttachment").value("platform") name("userVerification").value("required") } }) .build() ) val response = call.await() return response.result("Error calling /registerRequest") { parsePublicKeyCredentialCreationOptions( body ?: throw ApiException("Empty response from /registerRequest") ) } } /** * @param sessionId The session ID to be used for the sign-in. * @param credential The PublicKeyCredential object. * @return A list of all the credentials registered on the server, including the newly * registered one. */ suspend fun registerResponse( sessionId: String, credential: PublicKeyCredential ): ApiResult<List<Credential>> { val rawId = credential.rawId.toBase64() val response = credential.response as AuthenticatorAttestationResponse val call = client.newCall( Request.Builder() .url("$BASE_URL/registerResponse") .addHeader("Cookie", formatCookie(sessionId)) .method("POST", jsonRequestBody { name("id").value(rawId) name("type").value(PublicKeyCredentialType.PUBLIC_KEY.toString()) name("rawId").value(rawId) name("response").objectValue { name("clientDataJSON").value( response.clientDataJSON.toBase64() ) name("attestationObject").value( response.attestationObject.toBase64() ) } }) .build() ) val apiResponse = call.await() return apiResponse.result("Error calling /registerResponse") { parseUserCredentials( body ?: throw ApiException("Empty response from /registerResponse") ) } } /** * @param sessionId The session ID. * @param credentialId The credential ID to be removed. */ suspend fun removeKey(sessionId: String, credentialId: String): ApiResult<Unit> { val call = client.newCall( Request.Builder() .url("$BASE_URL/removeKey?credId=$credentialId") .addHeader("Cookie", formatCookie(sessionId)) .method("POST", jsonRequestBody {}) .build() ) val response = call.await() return response.result("Error calling /removeKey") { } } /** * @param sessionId The session ID to be used for the sign-in. * @param credentialId The credential ID of this device. * @return A pair. The `first` element is a [PublicKeyCredentialRequestOptions] that can be used * for a subsequent FIDO2 API call. The `second` element is a challenge string that should * be sent back to the server in [signinResponse]. */ suspend fun signinRequest( sessionId: String, credentialId: String? ): ApiResult<PublicKeyCredentialRequestOptions> { val call = client.newCall( Request.Builder() .url( buildString { append("$BASE_URL/signinRequest") if (credentialId != null) { append("?credId=$credentialId") } } ) .addHeader("Cookie", formatCookie(sessionId)) .method("POST", jsonRequestBody {}) .build() ) val response = call.await() return response.result("Error calling /signinRequest") { parsePublicKeyCredentialRequestOptions( body ?: throw ApiException("Empty response from /signinRequest") ) } } /** * @param sessionId The session ID to be used for the sign-in. * @param credential The PublicKeyCredential object. * @return A list of all the credentials registered on the server, including the newly * registered one. */ suspend fun signinResponse( sessionId: String, credential: PublicKeyCredential ): ApiResult<List<Credential>> { val rawId = credential.rawId.toBase64() val response = credential.response as AuthenticatorAssertionResponse val call = client.newCall( Request.Builder() .url("$BASE_URL/signinResponse") .addHeader("Cookie", formatCookie(sessionId)) .method("POST", jsonRequestBody { name("id").value(rawId) name("type").value(PublicKeyCredentialType.PUBLIC_KEY.toString()) name("rawId").value(rawId) name("response").objectValue { name("clientDataJSON").value( response.clientDataJSON.toBase64() ) name("authenticatorData").value( response.authenticatorData.toBase64() ) name("signature").value( response.signature.toBase64() ) name("userHandle").value( response.userHandle?.toBase64() ?: "" ) } }) .build() ) val apiResponse = call.await() return apiResponse.result("Error calling /signingResponse") { parseUserCredentials(body ?: throw ApiException("Empty response from /signinResponse")) } } private fun parsePublicKeyCredentialRequestOptions( body: ResponseBody ): PublicKeyCredentialRequestOptions { val builder = PublicKeyCredentialRequestOptions.Builder() JsonReader(body.byteStream().bufferedReader()).use { reader -> reader.beginObject() while (reader.hasNext()) { when (reader.nextName()) { "challenge" -> builder.setChallenge(reader.nextString().decodeBase64()) "userVerification" -> reader.skipValue() "allowCredentials" -> builder.setAllowList(parseCredentialDescriptors(reader)) "rpId" -> builder.setRpId(reader.nextString()) "timeout" -> builder.setTimeoutSeconds(reader.nextDouble()) else -> reader.skipValue() } } reader.endObject() } return builder.build() } private fun parsePublicKeyCredentialCreationOptions( body: ResponseBody ): PublicKeyCredentialCreationOptions { val builder = PublicKeyCredentialCreationOptions.Builder() JsonReader(body.byteStream().bufferedReader()).use { reader -> reader.beginObject() while (reader.hasNext()) { when (reader.nextName()) { "user" -> builder.setUser(parseUser(reader)) "challenge" -> builder.setChallenge(reader.nextString().decodeBase64()) "pubKeyCredParams" -> builder.setParameters(parseParameters(reader)) "timeout" -> builder.setTimeoutSeconds(reader.nextDouble()) "attestation" -> reader.skipValue() // Unused "excludeCredentials" -> builder.setExcludeList( parseCredentialDescriptors(reader) ) "authenticatorSelection" -> builder.setAuthenticatorSelection( parseSelection(reader) ) "rp" -> builder.setRp(parseRp(reader)) } } reader.endObject() } return builder.build() } private fun parseRp(reader: JsonReader): PublicKeyCredentialRpEntity { var id: String? = null var name: String? = null reader.beginObject() while (reader.hasNext()) { when (reader.nextName()) { "id" -> id = reader.nextString() "name" -> name = reader.nextString() else -> reader.skipValue() } } reader.endObject() return PublicKeyCredentialRpEntity(id!!, name!!, /* icon */ null) } private fun parseSelection(reader: JsonReader): AuthenticatorSelectionCriteria { val builder = AuthenticatorSelectionCriteria.Builder() reader.beginObject() while (reader.hasNext()) { when (reader.nextName()) { "authenticatorAttachment" -> builder.setAttachment( Attachment.fromString(reader.nextString()) ) "userVerification" -> reader.skipValue() else -> reader.skipValue() } } reader.endObject() return builder.build() } private fun parseCredentialDescriptors( reader: JsonReader ): List<PublicKeyCredentialDescriptor> { val list = mutableListOf<PublicKeyCredentialDescriptor>() reader.beginArray() while (reader.hasNext()) { var id: String? = null reader.beginObject() while (reader.hasNext()) { when (reader.nextName()) { "id" -> id = reader.nextString() "type" -> reader.skipValue() "transports" -> reader.skipValue() else -> reader.skipValue() } } reader.endObject() list.add( PublicKeyCredentialDescriptor( PublicKeyCredentialType.PUBLIC_KEY.toString(), id!!.decodeBase64(), /* transports */ null ) ) } reader.endArray() return list } private fun parseUser(reader: JsonReader): PublicKeyCredentialUserEntity { reader.beginObject() var id: String? = null var name: String? = null var displayName = "" while (reader.hasNext()) { when (reader.nextName()) { "id" -> id = reader.nextString() "name" -> name = reader.nextString() "displayName" -> displayName = reader.nextString() else -> reader.skipValue() } } reader.endObject() return PublicKeyCredentialUserEntity( id!!.decodeBase64(), name!!, null, // icon displayName ) } private fun parseParameters(reader: JsonReader): List<PublicKeyCredentialParameters> { val parameters = mutableListOf<PublicKeyCredentialParameters>() reader.beginArray() while (reader.hasNext()) { reader.beginObject() var type: String? = null var alg = 0 while (reader.hasNext()) { when (reader.nextName()) { "type" -> type = reader.nextString() "alg" -> alg = reader.nextInt() else -> reader.skipValue() } } reader.endObject() parameters.add(PublicKeyCredentialParameters(type!!, alg)) } reader.endArray() return parameters } private fun jsonRequestBody(body: JsonWriter.() -> Unit): RequestBody { val output = StringWriter() JsonWriter(output).use { writer -> writer.beginObject() writer.body() writer.endObject() } return output.toString().toRequestBody(JSON) } private fun parseUserCredentials(body: ResponseBody): List<Credential> { fun readCredentials(reader: JsonReader): List<Credential> { val credentials = mutableListOf<Credential>() reader.beginArray() while (reader.hasNext()) { reader.beginObject() var id: String? = null var publicKey: String? = null while (reader.hasNext()) { when (reader.nextName()) { "credId" -> id = reader.nextString() "publicKey" -> publicKey = reader.nextString() else -> reader.skipValue() } } reader.endObject() if (id != null && publicKey != null) { credentials.add(Credential(id, publicKey)) } } reader.endArray() return credentials } JsonReader(body.byteStream().bufferedReader()).use { reader -> reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() if (name == "credentials") { return readCredentials(reader) } else { reader.skipValue() } } reader.endObject() } throw ApiException("Cannot parse credentials") } private fun throwResponseError(response: Response, message: String): Nothing { val b = response.body if (b != null) { throw ApiException("$message; ${parseError(b)}") } else { throw ApiException(message) } } private fun parseError(body: ResponseBody): String { val errorString = body.string() try { JsonReader(StringReader(errorString)).use { reader -> reader.beginObject() while (reader.hasNext()) { val name = reader.nextName() if (name == "error") { val token = reader.peek() if (token == JsonToken.STRING) { return reader.nextString() } return "Unknown" } else { reader.skipValue() } } reader.endObject() } } catch (e: Exception) { Log.e(TAG, "Cannot parse the error: $errorString", e) // Don't throw; this method is called during throwing. } return "" } private fun JsonWriter.objectValue(body: JsonWriter.() -> Unit) { beginObject() body() endObject() } private fun <T> Response.result(errorMessage: String, data: Response.() -> T): ApiResult<T> { if (!isSuccessful) { if (code == 401) { // Unauthorized return ApiResult.SignedOutFromServer } // All other errors throw an exception. throwResponseError(this, errorMessage) } val cookie = headers("set-cookie").find { it.startsWith(SessionIdKey) } val sessionId = if (cookie != null) parseSessionId(cookie) else null return ApiResult.Success(sessionId, data()) } private fun parseSessionId(cookie: String): String { val start = cookie.indexOf(SessionIdKey) if (start < 0) { throw ApiException("Cannot find $SessionIdKey") } val semicolon = cookie.indexOf(";", start + SessionIdKey.length) val end = if (semicolon < 0) cookie.length else semicolon return cookie.substring(start + SessionIdKey.length, end) } private fun formatCookie(sessionId: String): String { return "$SessionIdKey$sessionId" } }
apache-2.0
34dc04d1d67a3d7f74194c16dbda31d9
37.477064
100
0.561993
5.179057
false
false
false
false
wenhuiyao/CoroutinesAdapter
coroutines-adapter/src/main/kotlin/com/wenhui/coroutines/WorkerCoroutines.kt
1
1789
package com.wenhui.coroutines import kotlinx.coroutines.experimental.Job import java.util.concurrent.ExecutionException /** * Utility method to create a new background work */ internal fun <T> newFutureWork(action: Action<T>): FutureWork<T> = FutureWorkImpl(action) interface FutureWork<T> : Work<T, Worker> { /** * Synchronous call to get the computation result, throw exception if there are errors * * NOTE: this will block the current thread to wait of the result * * @throws [ExecutionException] * @throws [CancellationException] */ fun get(): T } class ExecutionException(cause: Throwable) : Exception(cause) class CancellationException(message: String = "Execution cancelled") : Exception(message) /** * Represent a background work, which can be [cancel] when needed. */ interface Worker : Manageable<Worker> { /** * Returns `true` when this work has completed for any reason, included cancellation. */ val isCompleted: Boolean /** * Cancel this work. The result is `true` if this work was * cancelled as a result of this invocation and `false` otherwise */ fun cancel(): Boolean } internal class WorkerImpl(private val job: Job) : Worker { override val isCompleted: Boolean get() = job.isCompleted override fun cancel() = job.cancel() override fun manageBy(manager: WorkManager): Worker { manager.manageJob(job) return this } } private class FutureWorkImpl<T>(private val action: Action<T>) : FutureWork<T>, BaseWork<T, Worker>(action) { override fun <R> newWork(action: Action<R>): Work<R, Worker> = FutureWorkImpl(action) override fun start(): Worker = WorkerImpl(executeWork(CONTEXT_BG)) override fun get(): T = action.run() }
apache-2.0
d59b0eaf739bf8d31ac9992ea81fc621
25.701493
109
0.69033
4.13164
false
false
false
false
SerCeMan/intellij-community
platform/script-debugger/protocol/protocol-reader/src/Util.kt
36
1364
package org.jetbrains.protocolReader import java.lang.reflect.ParameterizedType import java.lang.reflect.Type import java.lang.reflect.WildcardType public val TYPE_FACTORY_NAME_PREFIX: Char = 'F' public val READER_NAME: String = "reader" public val PENDING_INPUT_READER_NAME: String = "inputReader" public val BASE_VALUE_PREFIX: String = "baseMessage" public val JSON_READER_CLASS_NAME: String = "org.jetbrains.io.JsonReaderEx" public val JSON_READER_PARAMETER_DEF: String = JSON_READER_CLASS_NAME + ' ' + READER_NAME /** * Generate Java type name of the passed type. Type may be parameterized. */ fun writeJavaTypeName(arg: Type, out: TextOutput) { if (arg is Class<*>) { out.append(arg.getCanonicalName()) } else if (arg is ParameterizedType) { writeJavaTypeName(arg.getRawType(), out) out.append('<') val params = arg.getActualTypeArguments() for (i in params.indices) { if (i != 0) { out.comma() } writeJavaTypeName(params[i], out) } out.append('>') } else if (arg is WildcardType) { val upperBounds = arg.getUpperBounds() if (upperBounds == null) { throw RuntimeException() } if (upperBounds.size() != 1) { throw RuntimeException() } out.append("? extends ") writeJavaTypeName(upperBounds[0], out) } else { out.append(arg.toString()) } }
apache-2.0
0cc7775989b6bd040867623ac4fe3dac
26.3
89
0.67522
3.820728
false
false
false
false
gmillz/SlimFileManager
manager/src/main/java/com/slim/slimfilemanager/FileManager.kt
1
24436
package com.slim.slimfilemanager import android.Manifest import android.app.Activity import android.app.Fragment import android.app.FragmentManager import android.content.Intent import android.content.SharedPreferences import android.content.pm.PackageManager import android.os.Bundle import android.os.Environment import android.support.design.widget.NavigationView import android.support.design.widget.Snackbar import android.support.v13.app.FragmentStatePagerAdapter import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v4.view.GravityCompat import android.support.v4.view.PagerAdapter import android.support.v4.view.ViewPager import android.support.v4.widget.DrawerLayout import android.support.v7.app.ActionBarDrawerToggle import android.support.v7.widget.Toolbar import android.text.TextUtils import android.util.Log import android.view.Menu import android.view.MenuItem import android.view.SubMenu import android.view.View import android.view.ViewGroup import android.widget.ImageView import com.getbase.floatingactionbutton.FloatingActionButton import com.getbase.floatingactionbutton.FloatingActionsMenu import com.slim.slimfilemanager.fragment.BaseBrowserFragment import com.slim.slimfilemanager.fragment.BrowserFragment import com.slim.slimfilemanager.settings.SettingsActivity import com.slim.slimfilemanager.settings.SettingsProvider import com.slim.slimfilemanager.utils.Bookmark import com.slim.slimfilemanager.utils.BookmarkHelper import com.slim.slimfilemanager.utils.FragmentLifecycle import com.slim.slimfilemanager.utils.IconCache import com.slim.slimfilemanager.utils.PasteTask import com.slim.slimfilemanager.utils.RootUtils import com.slim.slimfilemanager.utils.Utils import com.slim.slimfilemanager.widget.PageIndicator import com.slim.slimfilemanager.widget.TabItem import com.slim.slimfilemanager.widget.TabPageIndicator import com.slim.util.SDCardUtils import kotlinx.android.synthetic.main.file_manager.* import java.io.File import java.util.ArrayList class FileManager : ThemeActivity(), View.OnClickListener, NavigationView.OnNavigationItemSelectedListener { internal lateinit var mView: View internal lateinit var mToolbar: Toolbar internal var mDrawerLayout: DrawerLayout? = null internal lateinit var mNavView: NavigationView internal lateinit var mPasteButton: FloatingActionButton internal var mActionMenu: FloatingActionsMenu? = null internal var mCurrentPosition: Int = 0 internal var mMove: Boolean = false internal var mPicking: Boolean = false private val mBookmarks = ArrayList<Bookmark>() private var mBookmarkHelper: BookmarkHelper? = null private var mSectionsPagerAdapter: SectionsPagerAdapter? = null internal var mPreferenceListener: SharedPreferences.OnSharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key -> for (tabItem in mSectionsPagerAdapter!!.items) { tabItem.fragment!!.onPreferencesChanged() } if (key == SettingsProvider.SMALL_INDICATOR) { setupPageIndicators() } } private var mFragment: BaseBrowserFragment? = null private var mDrawerToggle: ActionBarDrawerToggle? = null private val mCallbacks = ArrayList<ActivityCallback>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) mBookmarkHelper = BookmarkHelper(this) SettingsProvider.get(this) .registerOnSharedPreferenceChangeListener(mPreferenceListener) val intent = intent checkPermissions() if (intent.action == Intent.ACTION_GET_CONTENT) { setContentView(R.layout.file_picker) mView = findViewById(R.id.base) showFragment(intent.type) mPicking = true } else { setContentView(R.layout.file_manager) mView = findViewById(R.id.base) setupNavigationDrawer() setupTabs() setupActionButtons() } setupToolbar() if (supportActionBar != null) { supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setHomeButtonEnabled(true) supportActionBar!!.setTitle(R.string.file_manager) } if (savedInstanceState == null) { if (mDrawerLayout != null && mDrawerToggle != null) { mDrawerLayout!!.openDrawer(GravityCompat.START) mDrawerToggle!!.syncState() } } } fun addActivityCallback(callback: ActivityCallback) { mCallbacks.add(callback) } fun removeActivityCallback(callback: ActivityCallback) { if (mCallbacks.contains(callback)) { mCallbacks.remove(callback) } } public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) for (callback in mCallbacks) { callback.onActivityResult(requestCode, resultCode, data) } } fun checkPermissions() { val permissions = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE) var granted = true for (perm in permissions) { if (ContextCompat.checkSelfPermission(this, perm) != PackageManager.PERMISSION_GRANTED) { granted = false } } if (granted) { return } ActivityCompat.requestPermissions(this, permissions, 1) } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == 1) { var denied = false for (i in permissions.indices) { if (grantResults[i] == PackageManager.PERMISSION_DENIED) { denied = true } } if (denied) { Snackbar.make(mView, "Unable to continue, Permissions Denied", Snackbar.LENGTH_SHORT).show() } else { for (tab in mSectionsPagerAdapter!!.items) { tab.fragment!!.filesChanged(tab.path) } } } } override fun onNavigationItemSelected(item: MenuItem): Boolean { val id = item.itemId var fragmentId = TabItem.TAB_BROWSER var path: String? = null if (id == ROOT_ID) { path = "/" } else if (id == SDCARD_ID) { path = Environment.getExternalStorageDirectory().absolutePath } else if (id == EXTERNALSD_ID) { path = SDCardUtils.instance()!!.directory } else { for (bookmark in mBookmarks) { if (bookmark.menuId == id) { path = bookmark.path fragmentId = bookmark.fragmentId break } } } if (!TextUtils.isEmpty(path)) { if (mSectionsPagerAdapter!!.containsTabId(fragmentId)) { mSectionsPagerAdapter!!.moveToTabId(fragmentId, path) } else { mSectionsPagerAdapter!!.addTabId(fragmentId, path!!) } } item.isEnabled = true mDrawerLayout!!.closeDrawers() return true } public override fun onStart() { super.onStart() if (mSectionsPagerAdapter != null && pager != null) { setCurrentlyDisplayedFragment(mSectionsPagerAdapter!!.getItem( pager.currentItem) as BaseBrowserFragment) } } private fun showFragment(type: String) { val fragment = BrowserFragment() findViewById<View>(R.id.content).visibility = View.VISIBLE fragmentManager.beginTransaction().add(R.id.content, fragment).commit() setCurrentlyDisplayedFragment(fragment) fragment.setPicking() fragment.setMimeType(type) } private fun setupToolbar() { mToolbar = findViewById<View>(R.id.toolbar) as Toolbar setSupportActionBar(mToolbar) mToolbar.setTitle(R.string.file_manager) } private fun setupNavigationDrawer() { mDrawerLayout = findViewById<View>(R.id.drawer_layout) as DrawerLayout mNavView = findViewById<View>(R.id.nav_view) as NavigationView mDrawerToggle = ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) mDrawerLayout!!.addDrawerListener(object : DrawerLayout.DrawerListener { override fun onDrawerSlide(drawerView: View, slideOffset: Float) { if (java.lang.Float.toString(slideOffset).contains("0.1")) { /*mDrawerAdapter.notifyDataSetChanged(); mDrawerAdapter.notifyDataSetInvalidated();*/ mDrawerLayout!!.invalidate() } mDrawerToggle!!.onDrawerSlide(drawerView, slideOffset) } override fun onDrawerOpened(drawerView: View) { mDrawerToggle!!.onDrawerOpened(drawerView) } override fun onDrawerClosed(drawerView: View) { mDrawerToggle!!.onDrawerClosed(drawerView) } override fun onDrawerStateChanged(newState: Int) { mDrawerToggle!!.onDrawerStateChanged(newState) } }) mDrawerToggle!!.syncState() recreateDrawerItems() mNavView.setNavigationItemSelectedListener(this) val header = mNavView.getHeaderView(0) header?.findViewById<View>(R.id.header_layout)?.setBackgroundColor(mPrimaryColor) } private fun recreateDrawerItems() { mNavView.menu.clear() addBaseItems() val bookmarks = mBookmarkHelper!!.bookmarks val bookmarkGroup = mNavView.menu.addSubMenu("Bookmarks") if (bookmarks.size == 0) { addDefaultBookmarks() } for (bookmark in bookmarks) { mBookmarks.add(bookmark) val view = ImageView(this) view.setImageResource(R.drawable.close) bookmarkGroup.add(0, bookmark.menuId, 0, bookmark.name).actionView = view } //SubMenu cloud = mNavView.getMenu().addSubMenu("Cloud Storage"); //cloud.add(0, DROPBOX_ID, 0, "Dropbox"); //cloud.add(0, DRIVE_ID, 0, "Drive"); } private fun addDefaultBookmarks() { var bookmark = Bookmark() bookmark.name = getString(R.string.downloads_title) bookmark.path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).absolutePath bookmark.fragmentId = TabItem.TAB_BROWSER bookmark.menuId = View.generateViewId() mBookmarkHelper!!.addBookmark(bookmark) bookmark = Bookmark() bookmark.name = getString(R.string.dcim_title) bookmark.path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DCIM).absolutePath bookmark.fragmentId = TabItem.TAB_BROWSER bookmark.menuId = View.generateViewId() mBookmarkHelper!!.addBookmark(bookmark) bookmark = Bookmark() bookmark.name = "Documents" bookmark.path = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOCUMENTS).absolutePath bookmark.fragmentId = TabItem.TAB_BROWSER bookmark.menuId = View.generateViewId() mBookmarkHelper!!.addBookmark(bookmark) } private fun addBaseItems() { mNavView.menu.add(0, ROOT_ID, 0, R.string.root_title) .isVisible = SettingsProvider.getBoolean(this, SettingsProvider.KEY_ENABLE_ROOT, false) && RootUtils.isRootAvailable mNavView.menu.add(0, SDCARD_ID, 0, R.string.sdcard_title) getExternalSDCard() } private fun addBookmark() { val file = File(mFragment!!.currentPath) val bookmark = Bookmark() bookmark.name = file.name bookmark.path = file.absolutePath bookmark.fragmentId = mSectionsPagerAdapter!!.currentTabId bookmark.menuId = View.generateViewId() mBookmarkHelper!!.addBookmark(bookmark) recreateDrawerItems() } private fun setupTabs() { mSectionsPagerAdapter = SectionsPagerAdapter(fragmentManager) pager.adapter = mSectionsPagerAdapter pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener { override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) { } override fun onPageSelected(position: Int) { val fragmentToShow = mSectionsPagerAdapter!!.getItem(position) as FragmentLifecycle? fragmentToShow!!.onResumeFragment() if (mActionMenu != null) { mActionMenu!!.collapse() } val fragmentToHide = mSectionsPagerAdapter!!.getItem(mCurrentPosition) as FragmentLifecycle? fragmentToHide?.onPauseFragment() mCurrentPosition = position saveTabs() } override fun onPageScrollStateChanged(state: Int) {} }) setupPageIndicators() pager.currentItem = SettingsProvider.getInt(this, "current_tab", 0) } private fun setupPageIndicators() { indicator.setViewPager(pager) tab_indicator.setViewPager(pager) indicator.setSelectedColor(mPrimaryColorDark) indicator.setUnselectedColor(mPrimaryColor) tab_indicator.setSelectedColor(mPrimaryColorDark) tab_indicator.setUnselectedColor(mPrimaryColor) if (SettingsProvider.getBoolean(this, SettingsProvider.SMALL_INDICATOR, false)) { tab_indicator.visibility = View.GONE indicator.visibility = View.VISIBLE } else { indicator.visibility = View.GONE tab_indicator.visibility = View.VISIBLE } } fun setTabTitle(fragment: BaseBrowserFragment, path: String) { if (mPicking) return runOnUiThread { val title = fragment.getTabTitle(path) for (item in mSectionsPagerAdapter!!.items) { if (item.fragment === fragment) { tab_indicator.setTabTitle( title, mSectionsPagerAdapter!!.items.indexOf(item)) break } } } } private fun setupActionButtons() { mActionMenu = findViewById<View>(R.id.float_button) as FloatingActionsMenu mPasteButton = findViewById<View>(R.id.paste) as FloatingActionButton buildActionButtons() mActionMenu!!.setColorNormal(ThemeActivity.getAccentColor(this)) mActionMenu!!.setColorPressed(Utils.darkenColor(ThemeActivity.getAccentColor(this))) mPasteButton.colorNormal = ThemeActivity.getAccentColor(this) mPasteButton.colorPressed = Utils.darkenColor(ThemeActivity.getAccentColor(this)) mPasteButton.setOnClickListener { PasteTask(this@FileManager, mMove, mFragment!!.currentPath, mFragment!!.pasteCallback) for (item in mSectionsPagerAdapter!!.items) { item.fragment!!.filesChanged(item.fragment!!.currentPath) } //mFragment.filesChanged(mFragment.getCurrentPath()); setMove(false) showPaste(false) } mPasteButton.setOnLongClickListener { PasteTask.SelectedFiles.clearAll() setMove(false) showPaste(false) true } } private fun buildActionButtons() { mActionMenu!!.addButton(getButton(R.drawable.add_folder, R.string.create_folder, BaseBrowserFragment.ACTION_ADD_FOLDER)) mActionMenu!!.addButton(getButton(R.drawable.add_file, R.string.create_file, BaseBrowserFragment.ACTION_ADD_FILE)) } private fun getButton(icon: Int, title: Int, tag: Int): FloatingActionButton { val button = FloatingActionButton(this) button.colorNormal = ThemeActivity.getAccentColor(this) button.colorPressed = Utils.darkenColor(ThemeActivity.getAccentColor(this)) button.setIcon(icon) button.title = getString(title) button.tag = tag button.setOnClickListener(this) return button } override fun onClick(v: View) { if (v.tag == BaseBrowserFragment.ACTION_ADD_FILE) { mActionMenu!!.collapse() val fragment = mSectionsPagerAdapter!!.getItem(mCurrentPosition) as BaseBrowserFragment? fragment!!.showDialog(BaseBrowserFragment.ACTION_ADD_FILE) } else if (v.tag == BaseBrowserFragment.ACTION_ADD_FOLDER) { mActionMenu!!.collapse() mFragment!!.showDialog(BaseBrowserFragment.ACTION_ADD_FOLDER) } } fun setMove(move: Boolean) { mMove = move } fun showPaste(show: Boolean) { if (show) { mPasteButton.visibility = View.VISIBLE mActionMenu!!.visibility = View.GONE } else { mActionMenu!!.visibility = View.VISIBLE mPasteButton.visibility = View.GONE } } fun getExternalSDCard() { SDCardUtils.initialize(this) val extSD = SDCardUtils.instance()!!.directory if (!TextUtils.isEmpty(extSD)) { mNavView.menu.add(0, EXTERNALSD_ID, 0, "External SD") } } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) if (mPicking) return true menuInflater.inflate(R.menu.menu_file_manager, menu) if (mSectionsPagerAdapter!!.count == 0) { for (i in 0 until menu.size()) { val item = menu.getItem(i) if (item.itemId == R.id.close_tab) { item.isVisible = false } } } return true } fun setCurrentlyDisplayedFragment(fragment: BaseBrowserFragment) { mFragment = fragment } fun closeDrawers() { mDrawerLayout!!.closeDrawers() } override fun onOptionsItemSelected(item: MenuItem): Boolean { val id = item.itemId if (mPicking && id == android.R.id.home) { setResult(Activity.RESULT_CANCELED) finish() return true } if (mDrawerToggle != null && mDrawerToggle!!.onOptionsItemSelected(item)) { return true } when (id) { R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)) return true } R.id.add_tab -> { mSectionsPagerAdapter!!.addTab(Environment.getExternalStorageDirectory().path) return true } R.id.close_tab -> { mSectionsPagerAdapter!!.removeCurrentTab() invalidateOptionsMenu() return true } R.id.add_bookmark -> { addBookmark() return true } else -> return super.onOptionsItemSelected(item) } } override fun onTrimMemory(level: Int) { if (level >= Activity.TRIM_MEMORY_MODERATE) { IconCache.clearCache() } } public override fun onDestroy() { super.onDestroy() SettingsProvider.get(this) .unregisterOnSharedPreferenceChangeListener(mPreferenceListener) } private fun saveTabs() { if (mSectionsPagerAdapter == null) return val arrayList = ArrayList<String>() for (item in mSectionsPagerAdapter!!.items) { val path = item.fragment!!.currentPath if (!TextUtils.isEmpty(path)) { arrayList.add(item.fragment!!.currentPath) } } if (!arrayList.isEmpty()) { SettingsProvider.putTabList(this, "tabs", mSectionsPagerAdapter!!.items) } SettingsProvider.putInt(this, "current_tab", pager.currentItem) } interface ActivityCallback { fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) } private inner class SectionsPagerAdapter internal constructor(fm: FragmentManager) : FragmentStatePagerAdapter(fm) { internal var items = ArrayList<TabItem>() internal val currentTabId: Int get() = items[pager.currentItem].id init { addDefault() items = SettingsProvider.getTabList(this@FileManager, "tabs", items) } internal fun addTab(path: String) { val tab = TabItem(path, TabItem.TAB_BROWSER) items.add(tab) notifyDataSetChanged() [email protected]_indicator.notifyDataSetChanged() pager.currentItem = count if (items.size == 1) { setCurrentlyDisplayedFragment(items[0].fragment!!) } } internal fun containsTabId(id: Int): Boolean { for (tab in items) { if (tab.id == id) { return true } } return false } @JvmOverloads internal fun moveToTabId(id: Int, path: String? = null) { for (tab in items) { if (tab.id == id) { pager.setCurrentItem(items.indexOf(tab), true) if (path != null) { tab.fragment!!.filesChanged(path) } return } } } @JvmOverloads internal fun addTabId(id: Int, path: String = "/") { val tab = TabItem(path, id) items.add(tab) notifyDataSetChanged() pager.setCurrentItem(items.indexOf(tab), true) [email protected]_indicator.notifyDataSetChanged() } internal fun removeCurrentTab() { val id = mCurrentPosition pager.setCurrentItem(id - 1, true) items[id].fragment!!.onDestroyView() items.remove(items[id]) notifyDataSetChanged() [email protected]_indicator.notifyDataSetChanged() } internal fun addDefault() { items.add(TabItem(Environment.getExternalStorageDirectory().absolutePath, TabItem.TAB_BROWSER)) if (RootUtils.isRootAvailable && SettingsProvider.getBoolean(this@FileManager, SettingsProvider.KEY_ENABLE_ROOT, false)) { items.add(TabItem("/", TabItem.TAB_BROWSER)) } else { items.add(TabItem(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOWNLOADS).path, TabItem.TAB_BROWSER)) } } override fun getItem(position: Int): Fragment? { return if (items.size == 0) null else items[position].fragment } override fun getCount(): Int { return items.size } override fun getPageTitle(position: Int): CharSequence? { return if (!TextUtils.isEmpty(items[position].path)) { items[position].fragment!!.getTabTitle( items[position].path) } else "" } override fun getItemPosition(`object`: Any): Int { return PagerAdapter.POSITION_NONE } override fun setPrimaryItem(container: ViewGroup, position: Int, `object`: Any) { if (`object` is BaseBrowserFragment) { setCurrentlyDisplayedFragment(`object`) } super.setPrimaryItem(container!!, position, `object`) } } companion object { private val EXTERNALSD_ID = 0x003 private val USB_OTG_ID = 0x004 private val ROOT_ID = 0x005 private val SDCARD_ID = 0x006 } }
gpl-3.0
88213bdd98c840e9b70cc7fe36442cdd
34.674453
100
0.616017
5.17164
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/Statistics.kt
1
22518
/**************************************************************************************** * Copyright (c) 2014 Michael Goldbach <[email protected]> * * Copyright (c) 2021 Mike Hardy <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki import android.content.Intent import android.graphics.Color import android.os.Bundle import android.view.LayoutInflater import android.view.Menu import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.view.ViewTreeObserver.OnGlobalLayoutListener import android.webkit.WebView import android.widget.ProgressBar import androidx.annotation.CheckResult import androidx.appcompat.app.AppCompatActivity import androidx.core.os.bundleOf import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.recyclerview.widget.RecyclerView.AdapterDataObserver import androidx.viewpager2.adapter.FragmentStateAdapter import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator import com.ichi2.anim.ActivityTransitionAnimation import com.ichi2.anki.dialogs.DeckSelectionDialog.DeckSelectionListener import com.ichi2.anki.dialogs.DeckSelectionDialog.SelectableDeck import com.ichi2.anki.stats.AnkiStatsTaskHandler import com.ichi2.anki.stats.AnkiStatsTaskHandler.Companion.getInstance import com.ichi2.anki.stats.ChartView import com.ichi2.anki.widgets.DeckDropDownAdapter.SubtitleListener import com.ichi2.libanki.Collection import com.ichi2.libanki.DeckId import com.ichi2.libanki.Decks import com.ichi2.libanki.stats.Stats import com.ichi2.libanki.stats.Stats.AxisType import com.ichi2.libanki.stats.Stats.ChartType import com.ichi2.ui.FixedTextView import kotlinx.coroutines.Job import net.ankiweb.rsdroid.RustCleanup import timber.log.Timber @RustCleanup("Remove this whole activity and use the new Anki page once the new backend is the default") class Statistics : NavigationDrawerActivity(), DeckSelectionListener, SubtitleListener { lateinit var viewPager: ViewPager2 private set lateinit var slidingTabLayout: TabLayout private set private lateinit var taskHandler: AnkiStatsTaskHandler private lateinit var mDeckSpinnerSelection: DeckSpinnerSelection private var mStatsDeckId: DeckId = 0 override fun onCreate(savedInstanceState: Bundle?) { if (showedActivityFailedScreen(savedInstanceState)) { return } Timber.d("onCreate()") sIsSubtitle = true super.onCreate(savedInstanceState) setContentView(R.layout.activity_anki_stats) initNavigationDrawer(findViewById(android.R.id.content)) slidingTabLayout = findViewById(R.id.sliding_tabs) startLoadingCollection() } override fun onCollectionLoaded(col: Collection) { Timber.d("onCollectionLoaded()") super.onCollectionLoaded(col) // Setup Task Handler taskHandler = getInstance(col) // Create the adapter that will return a fragment for each of the three // primary sections of the activity. // Set up the ViewPager with the sections adapter. viewPager = findViewById<ViewPager2?>(R.id.pager).apply { adapter = StatsPagerAdapter(this@Statistics) offscreenPageLimit = 8 } // Fixes #8984: scroll to position 0 in RTL layouts val tabObserver = slidingTabLayout.viewTreeObserver tabObserver.addOnGlobalLayoutListener(object : OnGlobalLayoutListener { // Note: we can't use a lambda as we use 'this' to refer to the class. override fun onGlobalLayout() { // we need this here: If we select tab 0 before in an RTL context the layout has been drawn, // then it doesn't perform a scroll animation and selects the wrong element slidingTabLayout.viewTreeObserver.removeOnGlobalLayoutListener(this) slidingTabLayout.selectTab(slidingTabLayout.getTabAt(0)) } }) // Dirty way to get text size from a TextView with current style, change if possible val size = FixedTextView(this).textSize taskHandler.standardTextSize = size // Prepare options menu only after loading everything invalidateOptionsMenu() // StatisticFragment.updateAllFragments(); when (val defaultDeck = AnkiDroidApp.getSharedPrefs(this).getString("stats_default_deck", "current")) { "current" -> mStatsDeckId = col.decks.selected() "all" -> mStatsDeckId = Stats.ALL_DECKS_ID else -> Timber.w("Unknown defaultDeck: %s", defaultDeck) } mDeckSpinnerSelection = DeckSpinnerSelection( this, col, findViewById(R.id.toolbar_spinner), showAllDecks = true, alwaysShowDefault = true, showFilteredDecks = true ) mDeckSpinnerSelection.initializeActionBarDeckSpinner(this.supportActionBar!!) mDeckSpinnerSelection.selectDeckById(mStatsDeckId, false) taskHandler.setDeckId(mStatsDeckId) viewPager.adapter!!.notifyDataSetChanged() } override fun onResume() { Timber.d("onResume()") selectNavigationItem(R.id.nav_stats) super.onResume() } override fun onCreateOptionsMenu(menu: Menu): Boolean { super.onCreateOptionsMenu(menu) // System.err.println("in onCreateOptionsMenu"); val inflater = menuInflater inflater.inflate(R.menu.anki_stats, menu) // exit if mTaskHandler not initialized yet if (this::taskHandler.isInitialized) { val menuItemToCheck = when (taskHandler.statType) { AxisType.TYPE_MONTH -> R.id.item_time_month AxisType.TYPE_YEAR -> R.id.item_time_year AxisType.TYPE_LIFE -> R.id.item_time_all } menu.findItem(menuItemToCheck).isChecked = true } return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { if (drawerToggle.onOptionsItemSelected(item)) { return true } when (item.itemId) { R.id.item_time_month -> { item.isChecked = !item.isChecked if (taskHandler.statType != AxisType.TYPE_MONTH) { taskHandler.statType = AxisType.TYPE_MONTH viewPager.adapter!!.notifyDataSetChanged() } return true } R.id.item_time_year -> { item.isChecked = !item.isChecked if (taskHandler.statType != AxisType.TYPE_YEAR) { taskHandler.statType = AxisType.TYPE_YEAR viewPager.adapter!!.notifyDataSetChanged() } return true } R.id.item_time_all -> { item.isChecked = !item.isChecked if (taskHandler.statType != AxisType.TYPE_LIFE) { taskHandler.statType = AxisType.TYPE_LIFE viewPager.adapter!!.notifyDataSetChanged() } return true } R.id.action_time_chooser -> { return true } else -> return super.onOptionsItemSelected(item) } } /** * @return text to be used in the subtitle of the drop-down deck selector */ override val subtitleText: String get() = resources.getString(R.string.statistics) override fun onDeckSelected(deck: SelectableDeck?) { if (deck == null) { return } mDeckSpinnerSelection.initializeActionBarDeckSpinner(this.supportActionBar!!) mStatsDeckId = deck.deckId mDeckSpinnerSelection.selectDeckById(mStatsDeckId, true) taskHandler.setDeckId(mStatsDeckId) viewPager.adapter!!.notifyDataSetChanged() } /** * A [FragmentStateAdapter] that returns a fragment corresponding to * one of the tabs. */ class StatsPagerAdapter(fragmentActivity: FragmentActivity) : FragmentStateAdapter(fragmentActivity) { override fun createFragment(position: Int): Fragment { val item = StatisticFragment.newInstance(position) item.checkAndUpdate() return item } override fun getItemCount(): Int { return 9 } } abstract class StatisticFragment : Fragment() { // track current settings for each individual fragment protected var deckId: DeckId = 0 protected lateinit var statisticsJob: Job private lateinit var statisticsOverviewJob: Job private lateinit var mActivityPager: ViewPager2 private lateinit var mTabLayoutMediator: TabLayoutMediator private val mDataObserver: AdapterDataObserver = object : AdapterDataObserver() { override fun onChanged() { checkAndUpdate() super.onChanged() } } override fun onResume() { checkAndUpdate() super.onResume() } override fun onDestroy() { cancelTasks() if (this::mActivityPager.isInitialized) { mActivityPager.adapter?.unregisterAdapterDataObserver(mDataObserver) } super.onDestroy() } protected fun cancelTasks() { Timber.w("canceling tasks") if (this::statisticsJob.isInitialized) { statisticsJob.cancel() } if (this::statisticsOverviewJob.isInitialized) { statisticsOverviewJob.cancel() } } private fun getTabTitle(position: Int): String { return when (position) { TODAYS_STATS_TAB_POSITION -> getString(R.string.stats_overview) FORECAST_TAB_POSITION -> getString(R.string.stats_forecast) REVIEW_COUNT_TAB_POSITION -> getString(R.string.stats_review_count) REVIEW_TIME_TAB_POSITION -> getString(R.string.stats_review_time) INTERVALS_TAB_POSITION -> getString(R.string.stats_review_intervals) HOURLY_BREAKDOWN_TAB_POSITION -> getString(R.string.stats_breakdown) WEEKLY_BREAKDOWN_TAB_POSITION -> getString(R.string.stats_weekly_breakdown) ANSWER_BUTTONS_TAB_POSITION -> getString(R.string.stats_answer_buttons) CARDS_TYPES_TAB_POSITION -> getString(R.string.title_activity_template_editor) else -> "" } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { mActivityPager = (requireActivity() as Statistics).viewPager if (mActivityPager.adapter != null) { mActivityPager.adapter!!.registerAdapterDataObserver(mDataObserver) } initTabLayoutMediator((requireActivity() as Statistics).slidingTabLayout) } private fun initTabLayoutMediator(slidingTabLayout: TabLayout) { if (this::mTabLayoutMediator.isInitialized) { mTabLayoutMediator.detach() } mTabLayoutMediator = TabLayoutMediator( slidingTabLayout, mActivityPager ) { tab: TabLayout.Tab, position: Int -> tab.text = getTabTitle(position) } mTabLayoutMediator.attach() } abstract fun checkAndUpdate() companion object { /** * The fragment argument representing the section number for this * fragment. */ const val ARG_SECTION_NUMBER = "section_number" /** * Returns a new instance of this fragment for the given section * number. */ @CheckResult fun newInstance(sectionNumber: Int): StatisticFragment { val fragment: StatisticFragment = when (sectionNumber) { FORECAST_TAB_POSITION, REVIEW_COUNT_TAB_POSITION, REVIEW_TIME_TAB_POSITION, INTERVALS_TAB_POSITION, HOURLY_BREAKDOWN_TAB_POSITION, WEEKLY_BREAKDOWN_TAB_POSITION, ANSWER_BUTTONS_TAB_POSITION, CARDS_TYPES_TAB_POSITION -> ChartFragment() TODAYS_STATS_TAB_POSITION -> OverviewStatisticsFragment() else -> throw IllegalArgumentException("Unknown section number: $sectionNumber") }.apply { arguments = bundleOf(ARG_SECTION_NUMBER to sectionNumber) } return fragment } } } /** * A chart fragment containing a ChartView. */ class ChartFragment : StatisticFragment() { private lateinit var mChart: ChartView private lateinit var mProgressBar: ProgressBar private var mHeight = 0 private var mWidth = 0 private var mSectionNumber = 0 private var mType = AxisType.TYPE_MONTH private var mIsCreated = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val bundle = arguments mSectionNumber = bundle!!.getInt(ARG_SECTION_NUMBER) // int sectionNumber = 0; // System.err.println("sectionNumber: " + mSectionNumber); val rootView = inflater.inflate(R.layout.fragment_anki_stats, container, false) mChart = rootView.findViewById(R.id.image_view_chart) // mChart.setLayerType(View.LAYER_TYPE_SOFTWARE, null); mProgressBar = rootView.findViewById(R.id.progress_bar_stats) mProgressBar.visibility = View.VISIBLE // mChart.setVisibility(View.GONE); // TODO: Implementing loader for Collection in Fragment itself would be a better solution. createChart() mHeight = mChart.measuredHeight mWidth = mChart.measuredWidth mChart.addFragment(this) mType = (requireActivity() as Statistics).taskHandler.statType mIsCreated = true deckId = (requireActivity() as Statistics).mStatsDeckId if (deckId != Stats.ALL_DECKS_ID) { val col = CollectionHelper.instance.getCol(requireActivity())!! val baseName = Decks.basename(col.decks.current().getString("name")) if (sIsSubtitle) { (requireActivity() as AppCompatActivity).supportActionBar!!.subtitle = baseName } else { requireActivity().title = baseName } } else { if (sIsSubtitle) { (requireActivity() as AppCompatActivity).supportActionBar!!.setSubtitle(R.string.stats_deck_collection) } else { requireActivity().title = resources.getString(R.string.stats_deck_collection) } } return rootView } private fun createChart() { val statisticsActivity = requireActivity() as Statistics val taskHandler = statisticsActivity.taskHandler statisticsJob = launchCatchingTask { taskHandler.createChart(getChartTypeFromPosition(mSectionNumber), mProgressBar, mChart) } } override fun checkAndUpdate() { if (!mIsCreated) { return } val height = mChart.measuredHeight val width = mChart.measuredWidth // are height and width checks still necessary without bitmaps? if (height != 0 && width != 0) { if (mHeight != height || mWidth != width || mType != (requireActivity() as Statistics).taskHandler.statType || deckId != (requireActivity() as Statistics).mStatsDeckId) { mHeight = height mWidth = width mType = (requireActivity() as Statistics).taskHandler.statType mProgressBar.visibility = View.VISIBLE mChart.visibility = View.GONE deckId = (requireActivity() as Statistics).mStatsDeckId cancelTasks() createChart() } } } } class OverviewStatisticsFragment : StatisticFragment() { private lateinit var mWebView: WebView private lateinit var mProgressBar: ProgressBar private var mType = AxisType.TYPE_MONTH private var mIsCreated = false override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val rootView = inflater.inflate(R.layout.fragment_anki_stats_overview, container, false) val handler = (requireActivity() as Statistics).taskHandler // Workaround for issue 2406 -- crash when resuming after app is purged from RAM // TODO: Implementing loader for Collection in Fragment itself would be a better solution. mWebView = rootView.findViewById(R.id.web_view_stats) // Set transparent color to prevent flashing white when night mode enabled mWebView.setBackgroundColor(Color.argb(1, 0, 0, 0)) mProgressBar = rootView.findViewById(R.id.progress_bar_stats_overview) mProgressBar.visibility = View.VISIBLE createStatisticOverview() mType = handler.statType mIsCreated = true val col = CollectionHelper.instance.getCol(requireActivity())!! deckId = (requireActivity() as Statistics).mStatsDeckId if (deckId != Stats.ALL_DECKS_ID) { val basename = Decks.basename(col.decks.current().getString("name")) if (sIsSubtitle) { (requireActivity() as AppCompatActivity).supportActionBar!!.subtitle = basename } else { requireActivity().title = basename } } else { if (sIsSubtitle) { (requireActivity() as AppCompatActivity).supportActionBar!!.setSubtitle(R.string.stats_deck_collection) } else { requireActivity().setTitle(R.string.stats_deck_collection) } } return rootView } private fun createStatisticOverview() { val handler = (requireActivity() as Statistics).taskHandler statisticsJob = launchCatchingTask("createStatisticOverview failed with error") { handler.createStatisticsOverview(mWebView, mProgressBar) } } override fun checkAndUpdate() { if (!mIsCreated) { return } if (mType != (requireActivity() as Statistics).taskHandler.statType || deckId != (requireActivity() as Statistics).mStatsDeckId ) { mType = (requireActivity() as Statistics).taskHandler.statType mProgressBar.visibility = View.VISIBLE mWebView.visibility = View.GONE deckId = (requireActivity() as Statistics).mStatsDeckId cancelTasks() createStatisticOverview() } } } override fun onBackPressed() { if (isDrawerOpen) { super.onBackPressed() } else { Timber.i("Back key pressed") val data = Intent() if (intent.hasExtra("selectedDeck")) { data.putExtra("originalDeck", intent.getLongExtra("selectedDeck", 0L)) } setResult(RESULT_CANCELED, data) finishWithAnimation(ActivityTransitionAnimation.Direction.END) } } fun getCurrentDeckId(): DeckId { return mStatsDeckId } companion object { const val TODAYS_STATS_TAB_POSITION = 0 const val FORECAST_TAB_POSITION = 1 const val REVIEW_COUNT_TAB_POSITION = 2 const val REVIEW_TIME_TAB_POSITION = 3 const val INTERVALS_TAB_POSITION = 4 const val HOURLY_BREAKDOWN_TAB_POSITION = 5 const val WEEKLY_BREAKDOWN_TAB_POSITION = 6 const val ANSWER_BUTTONS_TAB_POSITION = 7 const val CARDS_TYPES_TAB_POSITION = 8 private var sIsSubtitle = false fun getChartTypeFromPosition(position: Int): ChartType { return when (position) { FORECAST_TAB_POSITION -> ChartType.FORECAST REVIEW_COUNT_TAB_POSITION -> ChartType.REVIEW_COUNT REVIEW_TIME_TAB_POSITION -> ChartType.REVIEW_TIME INTERVALS_TAB_POSITION -> ChartType.INTERVALS HOURLY_BREAKDOWN_TAB_POSITION -> ChartType.HOURLY_BREAKDOWN WEEKLY_BREAKDOWN_TAB_POSITION -> ChartType.WEEKLY_BREAKDOWN ANSWER_BUTTONS_TAB_POSITION -> ChartType.ANSWER_BUTTONS CARDS_TYPES_TAB_POSITION -> ChartType.CARDS_TYPES else -> throw IllegalArgumentException("Unknown chart position: $position") } } } }
gpl-3.0
ee29c3cdf4d070f3b8c176686521f351
42.387283
254
0.606359
5.217331
false
false
false
false
ankidroid/Anki-Android
AnkiDroid/src/main/java/com/ichi2/anki/dialogs/InsertFieldDialog.kt
1
4442
/**************************************************************************************** * Copyright (c) 2021 Akshay Jadhav <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ package com.ichi2.anki.dialogs import android.os.Bundle import android.view.ViewGroup import android.widget.TextView import androidx.core.os.bundleOf import androidx.fragment.app.DialogFragment import androidx.recyclerview.widget.RecyclerView import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.list.customListAdapter import com.ichi2.anki.CardTemplateEditor import com.ichi2.anki.R import java.util.* /** * Dialog fragment used to show the fields that the user can insert in the card editor. This * fragment can notify other fragments from the same activity about an inserted field. * * @see [CardTemplateEditor.CardTemplateFragment] */ class InsertFieldDialog : DialogFragment() { private lateinit var mDialog: MaterialDialog private lateinit var mFieldList: List<String> /** * A dialog for inserting field in card template editor */ override fun onCreateDialog(savedInstanceState: Bundle?): MaterialDialog { super.onCreate(savedInstanceState) mFieldList = requireArguments().getStringArrayList(KEY_FIELD_ITEMS)!! val adapter: RecyclerView.Adapter<*> = object : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val root = layoutInflater.inflate(R.layout.material_dialog_list_item, parent, false) return object : RecyclerView.ViewHolder(root) {} } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { val textView = holder.itemView as TextView textView.text = mFieldList[position] textView.setOnClickListener { selectFieldAndClose(textView) } } override fun getItemCount(): Int { return mFieldList.size } } mDialog = MaterialDialog(requireContext()) .title(R.string.card_template_editor_select_field) .negativeButton(R.string.dialog_cancel) .customListAdapter(adapter) return mDialog } private fun selectFieldAndClose(textView: TextView) { parentFragmentManager.setFragmentResult( REQUEST_FIELD_INSERT, bundleOf(KEY_INSERTED_FIELD to textView.text.toString()) ) mDialog.dismiss() } companion object { /** * Other fragments sharing the activity can use this with * [androidx.fragment.app.FragmentManager.setFragmentResultListener] to get a result back. */ const val REQUEST_FIELD_INSERT = "request_field_insert" /** * This fragment requires that a list of fields names to be passed in. */ const val KEY_INSERTED_FIELD = "key_inserted_field" private const val KEY_FIELD_ITEMS = "key_field_items" fun newInstance(fieldItems: List<String>): InsertFieldDialog = InsertFieldDialog().apply { arguments = bundleOf(KEY_FIELD_ITEMS to ArrayList(fieldItems)) } } }
gpl-3.0
525222ad5e7c2796dd85a6cdd20202f7
45.757895
105
0.595452
5.345367
false
false
false
false
rock3r/detekt
detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/MemberNameEqualsClassName.kt
1
5038
package io.gitlab.arturbosch.detekt.rules.naming import io.gitlab.arturbosch.detekt.api.CodeSmell import io.gitlab.arturbosch.detekt.api.Config import io.gitlab.arturbosch.detekt.api.Debt import io.gitlab.arturbosch.detekt.api.Entity import io.gitlab.arturbosch.detekt.api.Issue import io.gitlab.arturbosch.detekt.api.Rule import io.gitlab.arturbosch.detekt.api.Severity import io.gitlab.arturbosch.detekt.rules.isOverride import org.jetbrains.kotlin.descriptors.DeclarationDescriptor import org.jetbrains.kotlin.descriptors.FunctionDescriptor import org.jetbrains.kotlin.psi.KtBlockExpression import org.jetbrains.kotlin.psi.KtClass import org.jetbrains.kotlin.psi.KtClassOrObject import org.jetbrains.kotlin.psi.KtDeclaration import org.jetbrains.kotlin.psi.KtNamedDeclaration import org.jetbrains.kotlin.psi.KtNamedFunction import org.jetbrains.kotlin.psi.KtObjectDeclaration import org.jetbrains.kotlin.resolve.BindingContext /** * This rule reports a member that has the same as the containing class or object. * This might result in confusion. * The member should either be renamed or changed to a constructor. * Factory functions that create an instance of the class are exempt from this rule. * * <noncompliant> * class MethodNameEqualsClassName { * * fun methodNameEqualsClassName() { } * } * * class PropertyNameEqualsClassName { * * val propertyEqualsClassName = 0 * } * </noncompliant> * * <compliant> * class Manager { * * companion object { * // factory functions can have the same name as the class * fun manager(): Manager { * return Manager() * } * } * } * </compliant> * * @configuration ignoreOverriddenFunction - if overridden functions and properties should be ignored (default: `true`) * (deprecated: "Use `ignoreOverridden` instead") * @configuration ignoreOverridden - if overridden functions and properties should be ignored (default: `true`) * * @active since v1.2.0 */ class MemberNameEqualsClassName(config: Config = Config.empty) : Rule(config) { override val issue = Issue(javaClass.simpleName, Severity.Style, "A member should not be given the same name as its parent class or object.", Debt.FIVE_MINS) private val classMessage = "A member is named after the class. This might result in confusion. " + "Either rename the member or change it to a constructor." private val objectMessage = "A member is named after the object. " + "This might result in confusion. Please rename the member." private val ignoreOverridden = valueOrDefault(IGNORE_OVERRIDDEN, valueOrDefault(IGNORE_OVERRIDDEN_FUNCTION, true)) override fun visitClass(klass: KtClass) { if (!klass.isInterface()) { (getMisnamedMembers(klass, klass.name) + getMisnamedCompanionObjectMembers(klass)) .forEach { report(CodeSmell(issue, Entity.from(it), classMessage)) } } super.visitClass(klass) } override fun visitObjectDeclaration(declaration: KtObjectDeclaration) { if (!declaration.isCompanion()) { getMisnamedMembers(declaration, declaration.name) .forEach { report(CodeSmell(issue, Entity.from(it), objectMessage)) } } super.visitObjectDeclaration(declaration) } private fun getMisnamedMembers(klassOrObject: KtClassOrObject, name: String?): Sequence<KtNamedDeclaration> { val body = klassOrObject.body ?: return emptySequence() return (body.functions.asSequence() as Sequence<KtNamedDeclaration> + body.properties) .filterNot { ignoreOverridden && it.isOverride() } .filter { it.name?.equals(name, ignoreCase = true) == true } } private fun getMisnamedCompanionObjectMembers(klass: KtClass): Sequence<KtNamedDeclaration> { return klass.companionObjects .asSequence() .flatMap { getMisnamedMembers(it, klass.name) } .filterNot { it is KtNamedFunction && isFactoryMethod(it, klass) } } private fun isFactoryMethod(function: KtNamedFunction, klass: KtClass): Boolean { val typeReference = function.typeReference return when { typeReference != null -> typeReference.text == klass.name function.bodyExpression !is KtBlockExpression -> { val functionDescriptor = function.descriptor() as? FunctionDescriptor functionDescriptor?.returnType?.constructor?.declarationDescriptor == klass.descriptor() } else -> false } } private fun KtDeclaration.descriptor(): DeclarationDescriptor? { return if (bindingContext == BindingContext.EMPTY) { null } else { bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, this] } } companion object { const val IGNORE_OVERRIDDEN_FUNCTION = "ignoreOverriddenFunction" const val IGNORE_OVERRIDDEN = "ignoreOverridden" } }
apache-2.0
46da8b949b1d562a6cea03ee95bb92c4
39.304
119
0.699881
4.704015
false
true
false
false
magnusja/libaums
libaums/src/main/java/me/jahnen/libaums/core/driver/file/FileBlockDeviceDriver.kt
2
2003
package me.jahnen.libaums.core.driver.file import me.jahnen.libaums.core.driver.BlockDeviceDriver import java.io.* import java.net.URL import java.nio.ByteBuffer import java.nio.channels.Channels /** * Created by magnusja on 01/08/17. */ class FileBlockDeviceDriver : BlockDeviceDriver { private var file: RandomAccessFile override var blockSize: Int = 0 private set private var byteOffset: Int = 0 override val blocks: Long get() = file.length() / blockSize @Throws(FileNotFoundException::class) @JvmOverloads constructor(file: File, byteOffset: Int = 0, blockSize: Int = 512) { this.file = RandomAccessFile(file, "rw") this.blockSize = blockSize this.byteOffset = byteOffset } @Throws(IOException::class) @JvmOverloads constructor(url: URL, byteOffset: Int = 0, blockSize: Int = 512) { this.byteOffset = byteOffset val rbc = Channels.newChannel(url.openStream()) val tempFile = File.createTempFile("libaums_file_blockdevice", ".bin") tempFile.deleteOnExit() val fos = FileOutputStream(tempFile) fos.channel.transferFrom(rbc, 0, java.lang.Long.MAX_VALUE) this.file = RandomAccessFile(tempFile, "rw") this.blockSize = blockSize } @Throws(IOException::class) override fun init() { } @Throws(IOException::class) override fun read(deviceOffset: Long, buffer: ByteBuffer) { file.seek(deviceOffset * blockSize + byteOffset) val read = file.read(buffer.array(), buffer.position(), buffer.remaining()) if (read == -1) { throw IOException("EOF") } buffer.position(buffer.position() + read) } @Throws(IOException::class) override fun write(deviceOffset: Long, buffer: ByteBuffer) { file.seek(deviceOffset * blockSize + byteOffset) file.write(buffer.array(), buffer.position(), buffer.remaining()) buffer.position(buffer.limit()) } }
apache-2.0
eb16ac14647d8323383267b2aa0eebae
28.895522
83
0.658512
4.129897
false
false
false
false
SergeySave/SpaceGame
desktop/src/com/sergey/spacegame/client/ecs/system/LineRenderSystem.kt
1
1505
package com.sergey.spacegame.client.ecs.system import com.badlogic.ashley.core.Engine import com.badlogic.ashley.core.Entity import com.badlogic.ashley.core.EntitySystem import com.badlogic.ashley.core.Family import com.badlogic.ashley.utils.ImmutableArray import com.sergey.spacegame.client.ecs.component.LineVisualComponent import com.sergey.spacegame.client.gl.DrawingBatch /** * Represents the system for lines such as weapon fire * * @author sergeys * * @constructor Creates a new LineRenderSystem * * @property batch - the batch that this system will draw to */ class LineRenderSystem(private val batch: DrawingBatch) : EntitySystem(2) { private var entities: ImmutableArray<Entity>? = null override fun addedToEngine(engine: Engine) { entities = engine.getEntitiesFor(Family.all(LineVisualComponent::class.java).get()) } override fun removedFromEngine(engine: Engine) { entities = null } override fun update(deltaTime: Float) { batch.enableBlending() var line: LineVisualComponent for (entity in entities!!) { line = LineVisualComponent.MAPPER.get(entity) batch.setLineWidth(line.thickness) batch.setForceColor(line.getColorWithOpacity()) batch.line(line.x, line.y, line.x2, line.y2) line.life -= deltaTime if (line.life < 0) engine.removeEntity(entity) } } }
mit
70c63dc6b4270384c75a6b6e5a689732
29.714286
91
0.671096
4.312321
false
false
false
false
ccomeaux/boardgamegeek4android
app/src/main/java/com/boardgamegeek/entities/GamePlayerPollResultsEntity.kt
1
1068
package com.boardgamegeek.entities data class GamePlayerPollResultsEntity( val totalVotes: Int = 0, val playerCount: String = "0", val bestVoteCount: Int = 0, val recommendedVoteCount: Int = 0, val notRecommendedVoteCount: Int = 0, private val recommendation: Int = UNKNOWN ) { val calculatedRecommendation by lazy { if (recommendation == UNKNOWN) { val halfTotalVoteCount = ((bestVoteCount + recommendedVoteCount + notRecommendedVoteCount) / 2) + 1 when { halfTotalVoteCount == 0 -> UNKNOWN bestVoteCount >= halfTotalVoteCount -> BEST bestVoteCount + recommendedVoteCount >= halfTotalVoteCount -> RECOMMENDED notRecommendedVoteCount >= halfTotalVoteCount -> NOT_RECOMMENDED else -> UNKNOWN } } else { recommendation } } companion object { const val BEST = 2 const val RECOMMENDED = 1 const val UNKNOWN = 0 const val NOT_RECOMMENDED = -1 } }
gpl-3.0
4c38829df905969f79107ca382c4e8bc
32.375
111
0.607678
5.061611
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/persistence/WCAndroidDatabase.kt
1
5735
package org.wordpress.android.fluxc.persistence import android.content.Context import androidx.room.AutoMigration import androidx.room.Database import androidx.room.Room import androidx.room.RoomDatabase import androidx.room.TypeConverters import androidx.room.withTransaction import org.wordpress.android.fluxc.model.OrderEntity import org.wordpress.android.fluxc.persistence.converters.BigDecimalConverter import org.wordpress.android.fluxc.persistence.converters.LocalIdConverter import org.wordpress.android.fluxc.persistence.converters.LongListConverter import org.wordpress.android.fluxc.persistence.converters.RemoteIdConverter import org.wordpress.android.fluxc.persistence.dao.AddonsDao import org.wordpress.android.fluxc.persistence.dao.CouponsDao import org.wordpress.android.fluxc.persistence.dao.InboxNotesDao import org.wordpress.android.fluxc.persistence.dao.OrderMetaDataDao import org.wordpress.android.fluxc.persistence.dao.OrderNotesDao import org.wordpress.android.fluxc.persistence.dao.OrdersDao import org.wordpress.android.fluxc.persistence.dao.TopPerformerProductsDao import org.wordpress.android.fluxc.persistence.entity.AddonEntity import org.wordpress.android.fluxc.persistence.entity.AddonOptionEntity import org.wordpress.android.fluxc.persistence.entity.CouponEmailEntity import org.wordpress.android.fluxc.persistence.entity.CouponEntity import org.wordpress.android.fluxc.persistence.entity.GlobalAddonGroupEntity import org.wordpress.android.fluxc.persistence.entity.InboxNoteActionEntity import org.wordpress.android.fluxc.persistence.entity.InboxNoteEntity import org.wordpress.android.fluxc.persistence.entity.OrderMetaDataEntity import org.wordpress.android.fluxc.persistence.entity.OrderNoteEntity import org.wordpress.android.fluxc.persistence.entity.TopPerformerProductEntity import org.wordpress.android.fluxc.persistence.migrations.AutoMigration13to14 import org.wordpress.android.fluxc.persistence.migrations.AutoMigration14to15 import org.wordpress.android.fluxc.persistence.migrations.AutoMigration16to17 import org.wordpress.android.fluxc.persistence.migrations.AutoMigration17to18 import org.wordpress.android.fluxc.persistence.migrations.AutoMigration18to19 import org.wordpress.android.fluxc.persistence.migrations.AutoMigration19to20 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_10_11 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_11_12 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_15_16 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_3_4 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_4_5 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_5_6 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_6_7 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_7_8 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_8_9 import org.wordpress.android.fluxc.persistence.migrations.MIGRATION_9_10 @Database( version = 20, entities = [ AddonEntity::class, AddonOptionEntity::class, CouponEntity::class, CouponEmailEntity::class, GlobalAddonGroupEntity::class, OrderNoteEntity::class, OrderEntity::class, OrderMetaDataEntity::class, InboxNoteEntity::class, InboxNoteActionEntity::class, TopPerformerProductEntity::class ], autoMigrations = [ AutoMigration(from = 12, to = 13), AutoMigration(from = 13, to = 14, spec = AutoMigration13to14::class), AutoMigration(from = 14, to = 15, spec = AutoMigration14to15::class), AutoMigration(from = 16, to = 17, spec = AutoMigration16to17::class), AutoMigration(from = 17, to = 18, spec = AutoMigration17to18::class), AutoMigration(from = 18, to = 19, spec = AutoMigration18to19::class), AutoMigration(from = 19, to = 20, spec = AutoMigration19to20::class) ] ) @TypeConverters( value = [ LocalIdConverter::class, LongListConverter::class, RemoteIdConverter::class, BigDecimalConverter::class ] ) abstract class WCAndroidDatabase : RoomDatabase(), TransactionExecutor { abstract val addonsDao: AddonsDao abstract val ordersDao: OrdersDao abstract val orderNotesDao: OrderNotesDao abstract val orderMetaDataDao: OrderMetaDataDao abstract val couponsDao: CouponsDao abstract val inboxNotesDao: InboxNotesDao abstract val topPerformerProductsDao: TopPerformerProductsDao companion object { fun buildDb(applicationContext: Context) = Room.databaseBuilder( applicationContext, WCAndroidDatabase::class.java, "wc-android-database" ).allowMainThreadQueries() .fallbackToDestructiveMigrationOnDowngrade() .fallbackToDestructiveMigrationFrom(1, 2) .addMigrations(MIGRATION_3_4) .addMigrations(MIGRATION_4_5) .addMigrations(MIGRATION_5_6) .addMigrations(MIGRATION_6_7) .addMigrations(MIGRATION_7_8) .addMigrations(MIGRATION_8_9) .addMigrations(MIGRATION_9_10) .addMigrations(MIGRATION_10_11) .addMigrations(MIGRATION_11_12) .addMigrations(MIGRATION_15_16) .build() } override suspend fun <R> executeInTransaction(block: suspend () -> R): R = withTransaction(block) override fun <R> runInTransaction(block: () -> R): R = runInTransaction(block) }
gpl-2.0
fb155726a15fc8913fcf4535aa777a61
48.439655
82
0.75048
4.519307
false
false
false
false
simo-andreev/Colourizmus
app/src/main/java/bg/o/sim/colourizmus/utils/Util.kt
1
2921
package bg.o.sim.colourizmus.utils import android.Manifest.permission.WRITE_EXTERNAL_STORAGE import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.content.pm.PackageManager.PERMISSION_GRANTED import android.media.Image import android.os.Build import androidx.core.app.ActivityCompat import androidx.core.content.ContextCompat import android.widget.Toast import java.io.File import java.io.FileOutputStream import java.io.IOException import java.text.SimpleDateFormat import java.util.* /** * Utility file for storing non-UI Strings, regexprs, numeric constants and * providing non-class-specific objects and utility methods. */ // String constants const val DB_NAME: String = "bg.o.sim.colourizmus.db" const val EXTRA_COLOUR: String = "EXTRA_COLOUR" const val EXTRA_PICTURE_URI: String = "EXTRA_PICTURE_URI" const val EXTRA_PICTURE_THUMB: String = "EXTRA_PICTURE_THUMB" // Numeric constants const val REQUEST_IMAGE_CAPTURE: Int = 0b0000_0000 const val REQUEST_PERMISSION_IMAGE_CAPTURE: Int = 0b0000_0010 const val REQUEST_IMAGE_PERMISSION: Int = 0b0000_1000 fun Context.toastShort(message: String) { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() } fun Context.toastLong(message: String) { Toast.makeText(this, message, Toast.LENGTH_LONG).show() } /** When you just *have* to call a [Toast] from a background [Thread]*/ fun Activity.toastOnUiThreadExplicit(message: String) { this.runOnUiThread { toastLong(message) } } @Throws(IOException::class) fun Activity.getImageFile(): File { requestStoragePermission(this) // rand locale for consistency val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.GERMANY).format(Date()) val imageFileName = "COLOURIZMUS_$timestamp" val storageDir: File = this.getExternalFilesDir(android.os.Environment.DIRECTORY_PICTURES)!! return File.createTempFile(imageFileName, ".jpg", storageDir) } fun Activity.havePermission(permission: String) = PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this, permission) fun requestStoragePermission(activity: Activity) { if (Build.VERSION.SDK_INT < 23) return //permission is automatically granted on sdk<23 upon installation if (ContextCompat.checkSelfPermission(activity, WRITE_EXTERNAL_STORAGE) == PERMISSION_GRANTED) ActivityCompat.requestPermissions(activity, arrayOf(WRITE_EXTERNAL_STORAGE), 1) } /** Saves a JPEG [Image] into the specified [File]. */ class ImageSaver(private val mImage: Image, private val mFile: File) : Runnable { override fun run() { val buffer = mImage.planes[0].buffer val bytes = ByteArray(buffer.remaining()) buffer.get(bytes) val output = FileOutputStream(mFile) try { output.write(bytes) } finally { mImage.close() output.close() } } }
apache-2.0
958eee4d97cf84bec3b4b035c200f4d8
32.574713
139
0.74495
4.062587
false
false
false
false
LanternPowered/LanternServer
src/main/kotlin/org/lanternpowered/server/profile/LanternProfileProperty.kt
1
2676
/* * Lantern * * Copyright (c) LanternPowered <https://www.lanternpowered.org> * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * This work is licensed under the terms of the MIT License (MIT). For * a copy, see 'LICENSE.txt' or <https://opensource.org/licenses/MIT>. */ package org.lanternpowered.server.profile import com.google.common.collect.LinkedHashMultimap import com.google.common.collect.Multimap import com.google.gson.JsonArray import com.google.gson.JsonObject import org.lanternpowered.api.util.optional.asOptional import org.spongepowered.api.data.persistence.DataContainer import org.spongepowered.api.profile.property.ProfileProperty import java.util.Optional data class LanternProfileProperty( private val name: String, private val value: String, private val signature: String? ) : ProfileProperty { override fun getName(): String = this.name override fun getValue(): String = this.value override fun getSignature(): Optional<String> = this.signature.asOptional() override fun getContentVersion(): Int = 1 override fun toContainer(): DataContainer { val dataContainer = DataContainer.createNew() .set(LanternGameProfile.NAME, this.name) .set(LanternGameProfile.VALUE, this.value) if (this.signature != null) dataContainer[LanternGameProfile.SIGNATURE] = this.signature return dataContainer } companion object { /** * Creates [LanternProfileProperty] from the specified [JsonObject]. * * @param jsonObject The json object * @return The profile property */ fun createFromJson(jsonObject: JsonObject): LanternProfileProperty { val name = jsonObject["name"].asString val value = jsonObject["value"].asString val signature = jsonObject["signature"]?.asString return LanternProfileProperty(name, value, signature) } /** * Creates a multimap with [LanternProfileProperty]s from the specified [JsonArray]. * * @param jsonArray The json array * @return The multimap */ fun createPropertiesMapFromJson(jsonArray: JsonArray): Multimap<String, ProfileProperty> { val properties = LinkedHashMultimap.create<String, ProfileProperty>() for (i in 0 until jsonArray.size()) { val profileProperty = this.createFromJson(jsonArray[i].asJsonObject) properties.put(profileProperty.name, profileProperty) } return properties } } }
mit
67a73d6b2cf2a463b69989d65903caa6
36.166667
98
0.672646
4.83906
false
false
false
false
ageery/kwicket
kwicket-sample/src/main/kotlin/org/kwicket/sample/BasePage.kt
1
2733
package org.kwicket.sample import de.agilecoders.wicket.core.markup.html.bootstrap.html.HtmlTag import de.agilecoders.wicket.core.markup.html.bootstrap.html.IeEdgeMetaTag import de.agilecoders.wicket.core.markup.html.bootstrap.html.MobileViewportMetaTag import de.agilecoders.wicket.core.markup.html.bootstrap.image.Icon import de.agilecoders.wicket.core.markup.html.bootstrap.navbar.Navbar import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeCssReference import de.agilecoders.wicket.extensions.markup.html.bootstrap.icon.FontAwesomeIconType import org.apache.wicket.Component import org.apache.wicket.ajax.IAjaxIndicatorAware import org.apache.wicket.event.IEvent import org.apache.wicket.markup.head.CssReferenceHeaderItem import org.apache.wicket.markup.head.IHeaderResponse import org.apache.wicket.markup.html.WebPage import org.apache.wicket.markup.html.basic.Label import org.apache.wicket.model.ResourceModel import org.apache.wicket.request.mapper.parameter.PageParameters import org.apache.wicket.request.resource.CssResourceReference import org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.common.KNotificationPanel import org.kwicket.agilecoders.wicket.core.ajax.markup.html.bootstrap.navbar.KNavbar import org.kwicket.component.q import org.kwicket.component.refresh abstract class BasePage(pageParameters: PageParameters? = null) : WebPage(pageParameters), IAjaxIndicatorAware { companion object { private val ajaxIndicatorId = "ajax" } private val feedback: Component init { q(HtmlTag("html")) q(Label("title", ResourceModel("page.title"))) q(MobileViewportMetaTag("viewport")) q(IeEdgeMetaTag("ie-edge")) q( KNavbar( id = "navbar", renderBodyOnly = false, brandName = ResourceModel("app.name"), inverted = true, position = Navbar.Position.TOP ) ) q(Icon("ajax-indicator", FontAwesomeIconType.spinner).setMarkupId(ajaxIndicatorId)) feedback = q(KNotificationPanel(id = "feedback", outputMarkupPlaceholderTag = true)) } override fun renderHead(response: IHeaderResponse) { super.renderHead(response) response.render(CssReferenceHeaderItem.forReference(FontAwesomeCssReference.instance())) response.render(CssReferenceHeaderItem.forReference(CssResourceReference(BasePage::class.java, "theme.css"))) } override fun getAjaxIndicatorMarkupId() = ajaxIndicatorId override fun onEvent(event: IEvent<*>) { val payload = event.payload when (payload) { is HasFeedbackEvent -> feedback.refresh() } } }
apache-2.0
9acedfd9aafe0df28e83eb45c772245d
40.409091
117
0.743139
4.185299
false
false
false
false
RoverPlatform/rover-android
experiences/src/main/kotlin/io/rover/sdk/experiences/ui/blocks/web/WebBlockView.kt
1
3520
package io.rover.sdk.experiences.ui.blocks.web import android.annotation.SuppressLint import android.content.Context import android.graphics.Canvas import android.os.Build import android.util.AttributeSet import android.view.MotionEvent import android.webkit.WebView import androidx.annotation.RequiresApi import io.rover.sdk.experiences.logging.log import io.rover.sdk.experiences.ui.blocks.concerns.ViewComposition import io.rover.sdk.experiences.ui.blocks.concerns.background.ViewBackground import io.rover.sdk.experiences.ui.blocks.concerns.border.ViewBorder import io.rover.sdk.experiences.ui.blocks.concerns.layout.LayoutableView import io.rover.sdk.experiences.ui.blocks.concerns.layout.ViewBlock import io.rover.sdk.experiences.ui.concerns.MeasuredBindableView import io.rover.sdk.experiences.ui.concerns.ViewModelBinding internal class WebBlockView : WebView, LayoutableView<WebViewBlockViewModelInterface> { constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) @RequiresApi(Build.VERSION_CODES.LOLLIPOP) constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) // mixins (TODO: injections) private val viewComposition = ViewComposition() private val viewBackground = ViewBackground(this) private val viewBorder = ViewBorder(this, viewComposition) private val viewBlock = ViewBlock(this) private val viewWeb = ViewWeb(this) override var viewModelBinding: MeasuredBindableView.Binding<WebViewBlockViewModelInterface>? by ViewModelBinding { binding, _ -> viewBorder.viewModelBinding = binding viewBlock.viewModelBinding = binding viewBackground.viewModelBinding = binding viewWeb.viewModelBinding = binding } override fun draw(canvas: Canvas) { viewComposition.beforeDraw(canvas) super.draw(canvas) viewComposition.afterDraw(canvas) } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) viewComposition.onSizeChanged(w, h, oldw, oldh) } @SuppressLint("MissingSuperCall") override fun requestLayout() { // log.v("Tried to invalidate layout. Inhibited.") } override fun forceLayout() { log.v("Tried to forcefully invalidate layout. Inhibited.") } /** * Overrides [onTouchEvent] in order to (optionally) prevent touch & drag scrolling of the * web view. We suppress the ClickableViewAccessibility warning because that warning * is intended for usage of onTouchEvent to detect clicks. There is no click equivalent of * touch & drag for scrolling. We also disable/enable the scroll bars as part of the same * policy separately in [ViewWeb]. */ @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { // TODO: sadly this cannot be delegated readily to ViewWeb because it requires using this // override, so we'll ask the view model from here. While I could teach ViewComposition // about TouchEvent, because handlers can consume events it is unclear requestDisallowInterceptTouchEvent((viewModelBinding?.viewModel?.scrollingEnabled) ?: true) return super.onTouchEvent(event) } }
apache-2.0
8f13d9664daff1072997c8e991ba572a
43.556962
143
0.75
4.472681
false
false
false
false
ziggy42/Blum
app/src/main/java/com/andreapivetta/blu/common/utils/Utils.kt
1
1911
package com.andreapivetta.blu.common.utils import android.content.Context import android.graphics.Bitmap import android.graphics.BitmapFactory import android.net.Uri import android.util.DisplayMetrics import timber.log.Timber import java.io.IOException import java.io.InputStream import java.net.URL import java.text.SimpleDateFormat import java.util.* import java.util.concurrent.TimeUnit object Utils { fun dpToPx(context: Context, dp: Int) = Math.round(dp * (context.resources.displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)) fun getBitmapFromURL(strURL: String): Bitmap? = try { val connection = URL(strURL).openConnection() connection.connect() BitmapFactory.decodeStream(connection.inputStream) } catch (e: IOException) { Timber.e(e) null } fun formatDate(timeStamp: Long): String? { val c = Calendar.getInstance() val c2 = Calendar.getInstance() c2.timeInMillis = timeStamp val diff = c.timeInMillis - timeStamp val seconds = TimeUnit.MILLISECONDS.toSeconds(diff) if (seconds > 60) { val minutes = TimeUnit.MILLISECONDS.toMinutes(diff) if (minutes > 60) { val hours = TimeUnit.MILLISECONDS.toHours(diff) if (hours > 24) { if (c.get(Calendar.YEAR) == c2.get(Calendar.YEAR)) return SimpleDateFormat("MMM dd", Locale.getDefault()).format(c2.time) else return SimpleDateFormat("MMM dd yyyy", Locale.getDefault()).format(c2.time) } else return "${hours}h" } else return "${minutes}m" } else return "${seconds}s" } fun inputStreamFromUri(context: Context, uri: Uri): InputStream = context.contentResolver.openInputStream(uri) }
apache-2.0
e8ba921a3eef0ab5e7dfdefae91ef110
32.526316
99
0.626897
4.539192
false
false
false
false
ykrank/S1-Next
app/src/main/java/me/ykrank/s1next/view/dialog/VoteDialogFragment.kt
1
6280
package me.ykrank.s1next.view.dialog import android.app.Dialog import android.os.Bundle import androidx.recyclerview.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.Window import com.github.ykrank.androidautodispose.AndroidRxDispose import com.github.ykrank.androidlifecycle.event.FragmentEvent import com.github.ykrank.androidtools.extension.toast import com.github.ykrank.androidtools.ui.adapter.simple.BindViewHolderCallback import com.github.ykrank.androidtools.ui.adapter.simple.SimpleRecycleViewAdapter import com.github.ykrank.androidtools.util.RxJavaUtil import io.reactivex.rxkotlin.Singles import me.ykrank.s1next.App import me.ykrank.s1next.R import me.ykrank.s1next.data.User import me.ykrank.s1next.data.api.ApiFlatTransformer import me.ykrank.s1next.data.api.S1Service import me.ykrank.s1next.data.api.app.AppService import me.ykrank.s1next.data.api.model.Vote import me.ykrank.s1next.databinding.ItemVoteBinding import me.ykrank.s1next.databinding.LayoutVoteBinding import me.ykrank.s1next.util.ErrorUtil import me.ykrank.s1next.viewmodel.ItemVoteViewModel import me.ykrank.s1next.viewmodel.VoteViewModel import javax.inject.Inject /** * A dialog lets the user vote thread. */ class VoteDialogFragment : BaseDialogFragment(), VoteViewModel.VoteVmAction { @Inject lateinit var appService: AppService @Inject lateinit var s1Service: S1Service @Inject lateinit var mUser: User private lateinit var tid: String private lateinit var mVote: Vote private lateinit var binding: LayoutVoteBinding private lateinit var adapter: SimpleRecycleViewAdapter private lateinit var data: List<ItemVoteViewModel> override fun onCreate(savedInstanceState: Bundle?) { App.appComponent.inject(this) super.onCreate(savedInstanceState) tid = arguments!!.getString(ARG_THREAD_ID)!! mVote = arguments!!.getParcelable(ARG_VOTE)!! adapter = SimpleRecycleViewAdapter(context!!, R.layout.item_vote, false, BindViewHolderCallback { position, itemBind -> itemBind as ItemVoteBinding itemBind.radio.setOnClickListener { refreshSelectedItem(position, itemBind) } itemBind.checkBox.setOnClickListener { refreshSelectedItem(position, itemBind) } }) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { binding = LayoutVoteBinding.inflate(inflater, container, false) val model = VoteViewModel(mVote, this) binding.model = model binding.recycleView.adapter = adapter binding.recycleView.layoutManager = androidx.recyclerview.widget.LinearLayoutManager(context) mVote.voteOptions?.let { data = it.values.map { ItemVoteViewModel(binding.model!!, it) } adapter.swapDataSet(data) } loadData() return binding.root } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val dialog = super.onCreateDialog(savedInstanceState) dialog.window?.requestFeature(Window.FEATURE_NO_TITLE) return dialog } override fun onStart() { super.onStart() dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) } private fun loadData() { Singles.zip(appService.getPollInfo(mUser.appSecureToken, tid), appService.getPollOptions(mUser.appSecureToken, tid)) .compose(ApiFlatTransformer.apiPairErrorTransformer()) .compose(RxJavaUtil.iOSingleTransformer()) .map { (a,b)-> a.data to b.data } .to(AndroidRxDispose.withSingle(this, FragmentEvent.DESTROY)) .subscribe({ (appVote, voteOptions)-> binding.model?.appVote?.set(appVote) voteOptions?.let { data.forEachIndexed { index, vm -> vm.option.mergeWithAppVoteOption(it[index], appVote?.voters ?: mVote.voteCount) } } adapter.notifyDataSetChanged() }, { val activity = activity ?: return@subscribe activity.toast(ErrorUtil.parse(activity, it)) }) } private fun refreshSelectedItem(position: Int, itemBind: ItemVoteBinding) { if (mVote.isMultiple) { itemBind.model?.let { if (it.selected.get()) { it.selected.set(false) } else { val selected = data.filter { it.selected.get() } if (selected.size < mVote.maxChoices) { it.selected.set(true) } } } } else { data.forEachIndexed { index, vm -> vm.selected.set(index == position) } } adapter.notifyDataSetChanged() } override fun onClickVote(view: View?) { val selected = data.filter { it.selected.get() }.map { it.option.optionId } s1Service.vote(tid, mUser.authenticityToken, selected) .compose(ApiFlatTransformer.apiErrorTransformer()) .compose(RxJavaUtil.iOSingleTransformer()) .to(AndroidRxDispose.withSingle(this, FragmentEvent.DESTROY)) .subscribe({ activity?.toast(R.string.vote_success) loadData() }, { val activity = activity ?: return@subscribe activity.toast(ErrorUtil.parse(activity, it)) }) } companion object { const val ARG_VOTE = "vote" const val ARG_THREAD_ID = "thread_id" val TAG: String = VoteDialogFragment::class.java.name fun newInstance(threadId: String, vote: Vote): VoteDialogFragment { val fragment = VoteDialogFragment() val bundle = Bundle() bundle.putString(ARG_THREAD_ID, threadId) bundle.putParcelable(ARG_VOTE, vote) fragment.arguments = bundle return fragment } } }
apache-2.0
567a94154fc7122f6f578d573755f045
37.060606
127
0.64793
4.554025
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/ui/fragments/favorites/FavoritesViewModel.kt
1
1736
package com.pr0gramm.app.ui.fragments.favorites import androidx.lifecycle.ViewModel import androidx.lifecycle.asFlow import androidx.lifecycle.viewModelScope import com.pr0gramm.app.services.CollectionsService import com.pr0gramm.app.services.PostCollection import com.pr0gramm.app.services.UserService import com.pr0gramm.app.ui.base.launchIgnoreErrors import com.pr0gramm.app.util.doInBackground import com.pr0gramm.app.util.equalsIgnoreCase import kotlinx.coroutines.flow.* class FavoritesViewModel( val user: String, private val userService: UserService, private val collectionsService: CollectionsService, ) : ViewModel() { private val mutableCollectionsState = MutableStateFlow<List<PostCollection>>(listOf()) val myView = userService.loginState.name.equalsIgnoreCase(user) val collectionsState: StateFlow<List<PostCollection>> = mutableCollectionsState init { val collections = when { myView -> { // observe our collections collectionsService.collections.asFlow() } else -> flow { // fetch collections once val info = userService.info(user) emit(PostCollection.fromApi(info)) } } viewModelScope.launchIgnoreErrors { observeCollections(collections) } if (myView) { // trigger an async refresh of my collections doInBackground { collectionsService.refresh() } } } private suspend fun observeCollections(collectionsToObserve: Flow<List<PostCollection>>) { collectionsToObserve.collect { collections -> mutableCollectionsState.value = collections } } }
mit
86fdacc732be993ae465a5935925b3b0
32.403846
94
0.690668
4.890141
false
false
false
false
lukashaertel/megal-vm
src/main/kotlin/org/softlang/util/Many.kt
1
1419
package org.softlang.util import kotlin.reflect.KMutableProperty1 import kotlin.reflect.KProperty class Many<S, P>( val to: KMutableProperty1<P, S?>, val listener: (List<P>, List<P>) -> Unit = { f, t -> }) { /** * Current value of the field */ private var current: List<P> = emptyList() private var recurrent = false private var issuing = false operator fun getValue(site: S, property: KProperty<*>): List<P> { return current } operator fun setValue(site: S, property: KProperty<*>, new: List<P>) { if (issuing) throw IllegalAccessException("Change to value while issuing delta.") if (recurrent) return try { recurrent = true // Store current value and stop if no real change val old = current if (old == new) return // Transfer new value current = new val minus = old - new val plus = new - old for (x in minus) to.set(x, null) for (x in plus) to.set(x, site) // Issue delta to listener try { issuing = true listener(minus, plus) } finally { issuing = false } } finally { recurrent = false } } }
mit
1b93c2a2e52c063e944ebc9d76a191f5
21.539683
80
0.496124
4.714286
false
false
false
false
QuickBlox/quickblox-android-sdk
sample-videochat-kotlin/app/src/main/java/com/quickblox/sample/videochat/kotlin/activities/PermissionsActivity.kt
1
4380
package com.quickblox.sample.videochat.kotlin.activities import android.app.Activity import android.content.Intent import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import androidx.core.app.ActivityCompat import com.quickblox.sample.videochat.kotlin.R import com.quickblox.sample.videochat.kotlin.utils.SharedPrefsHelper import com.quickblox.sample.videochat.kotlin.utils.longToast private const val PERMISSION_CODE = 0 private const val EXTRA_PERMISSIONS = "extra_permissions" private const val CHECK_ONLY_AUDIO = "check_only_audio" class PermissionsActivity : BaseActivity() { companion object { fun startForResult(activity: Activity, checkOnlyAudio: Boolean, permissions: Array<String>) { val intent = Intent(activity, PermissionsActivity::class.java) intent.putExtra(EXTRA_PERMISSIONS, permissions) intent.putExtra(CHECK_ONLY_AUDIO, checkOnlyAudio) activity.startActivityForResult(intent, PERMISSION_CODE) } } private enum class PermissionFeatures { CAMERA, MICROPHONE } private var requiresCheck: Boolean = false override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_permissions) supportActionBar?.hide() requiresCheck = true } override fun onResume() { super.onResume() if (intent == null || !intent.hasExtra(EXTRA_PERMISSIONS)) { throw RuntimeException("This Activity needs to be launched using the static startActivityForResult() method.") } if (requiresCheck) { checkPermissions() } else { requiresCheck = true } } private fun checkPermissions() { val permissions = intent.getStringArrayExtra(EXTRA_PERMISSIONS)!! val checkOnlyAudio = intent.getBooleanExtra(CHECK_ONLY_AUDIO, false) if (checkOnlyAudio) { checkPermissionAudio(permissions[1]) } else { checkPermissionAudioVideo(permissions) } } private fun checkPermissionAudio(audioPermission: String) { if (checkPermission(audioPermission)) { requestPermissions(audioPermission) } else { allPermissionsGranted() } } private fun checkPermissionAudioVideo(permissions: Array<String>) { if (checkPermissions(permissions)) { requestPermissions(*permissions) } else { allPermissionsGranted() } } private fun requestPermissions(vararg permissions: String) { ActivityCompat.requestPermissions(this, permissions, PERMISSION_CODE) } private fun allPermissionsGranted() { setResult(Activity.RESULT_OK) finish() } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { super.onRequestPermissionsResult(requestCode, permissions, grantResults) if (requestCode == PERMISSION_CODE && hasAllPermissionsGranted(grantResults)) { requiresCheck = true allPermissionsGranted() } else { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { for (permission in permissions) { if (!shouldShowRequestPermissionRationale(permission)) { SharedPrefsHelper.save(permission, false) } } } requiresCheck = false showDeniedResponse(grantResults) finish() } } private fun showDeniedResponse(grantResults: IntArray) { if (grantResults.size > 1) { for (index in grantResults.indices) { if (grantResults[index] != 0) { longToast(getString(R.string.permission_unavailable, PermissionFeatures.values()[index])) } } } else { longToast(getString(R.string.permission_unavailable, PermissionFeatures.MICROPHONE)) } } private fun hasAllPermissionsGranted(grantResults: IntArray): Boolean { for (grantResult in grantResults) { if (grantResult == PackageManager.PERMISSION_DENIED) { return false } } return true } }
bsd-3-clause
969ea50ad7438d9b60cfb360db34378e
32.442748
122
0.643607
5.277108
false
false
false
false
ademar111190/goodreads
app/src/test/java/ademar/goodreads/test/Fixture.kt
1
2912
package ademar.goodreads.test import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import okhttp3.mockwebserver.MockWebServer import retrofit2.Retrofit import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory import retrofit2.converter.simplexml.SimpleXmlConverterFactory // region Database val DATABASE_NAME = "goodreads" val DATABASE_VERSION = 1 // endregion // region Ext val ACTIVITY_DIMEN_ID = 123 val ACTIVITY_DIMEN_VALUE = 42.0f val ACTIVITY_VIEW_ID = 321 val EDIT_TEXT_TEXT = "Text" // endregion // region Model val AUTHOR_ID = 432L val AUTHOR_NAME = "Ayn Rand" val BEST_BOOK_ID = 662L val BEST_BOOK_IMAGE = "https://d.gr-assets.com/books/1405868167m/662.jpg" val BEST_BOOK_TITLE = "Atlas Shrugged" val SEARCH_END = 1 val SEARCH_QUERY = "Atlas Shrugged" val SEARCH_START = 1 val SEARCH_TOTAL = 1 val WORK_AVERAGE_RATING = 3.67 val WORK_BOOKS = 13 val WORK_ID = 817219L val WORK_PUBLICATION_DAY = 31 val WORK_PUBLICATION_MONTH = 12 val WORK_PUBLICATION_YEAR = 1957 val WORK_RATINGS = 268028 val WORK_REVIEWS = 13514 val XML_AUTHOR = """<author> <id type="integer">$AUTHOR_ID</id> <name>$AUTHOR_NAME</name> </author>""" val XML_BEST_BOOK = """<best_book type="Book"> <id type="integer">$BEST_BOOK_ID</id> <title>$BEST_BOOK_TITLE</title> $XML_AUTHOR <image_url>$BEST_BOOK_IMAGE</image_url> </best_book>""" val XML_WORK = """<work> <id type="integer">$WORK_ID</id> <books_count type="integer">$WORK_BOOKS</books_count> <ratings_count type="integer">$WORK_RATINGS</ratings_count> <text_reviews_count type="integer">$WORK_REVIEWS</text_reviews_count> <original_publication_year type="integer">$WORK_PUBLICATION_YEAR</original_publication_year> <original_publication_month type="integer">$WORK_PUBLICATION_MONTH</original_publication_month> <original_publication_day type="integer">$WORK_PUBLICATION_DAY</original_publication_day> <average_rating>$WORK_AVERAGE_RATING</average_rating> $XML_BEST_BOOK </work>""" val XML_SEARCH = """<search> <query><![CDATA[$SEARCH_QUERY]]></query> <results-start>$SEARCH_START</results-start> <results-end>$SEARCH_END</results-end> <total-results>$SEARCH_TOTAL</total-results> <results> $XML_WORK </results> </search>""" val XML_SEARCH_RESPONSE = """<?xml version="1.0" encoding="UTF-8"?> <GoodreadsResponse> $XML_SEARCH </GoodreadsResponse>""" // endregion fun buildRetrofit(server: MockWebServer): Retrofit { return Retrofit.Builder() .baseUrl(server.url("")) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(SimpleXmlConverterFactory.create()) .client(OkHttpClient.Builder() .addInterceptor(HttpLoggingInterceptor() .setLevel(HttpLoggingInterceptor.Level.BODY)) .build()) .build() }
mit
8cf60529e91b829df07cebe976810cb7
29.030928
99
0.695055
3.555556
false
false
false
false
cloose/luftbild4p3d
src/main/kotlin/org/luftbild4p3d/osm/Member.kt
1
349
package org.luftbild4p3d.osm import javax.xml.bind.annotation.XmlAttribute import javax.xml.bind.annotation.XmlElement class Member(@XmlAttribute val type: String = "", @XmlAttribute val ref: Long = 0, @XmlAttribute val role: String = "") { @XmlElement(name = "nd") val nodeReference: MutableCollection<NodeReference> = mutableListOf() }
gpl-3.0
4dfcef13bab7337b84415b87342cf927
30.818182
121
0.750716
3.877778
false
false
false
false
daugeldauge/NeePlayer
compose/src/main/java/com/neeplayer/compose/ThumbnailFetcher.kt
1
2029
package com.neeplayer.compose import android.content.ContentUris import android.content.Context import android.graphics.drawable.BitmapDrawable import android.net.Uri import android.os.CancellationSignal import android.provider.MediaStore import coil.bitmap.BitmapPool import coil.decode.DataSource import coil.decode.Options import coil.fetch.DrawableResult import coil.fetch.FetchResult import coil.fetch.Fetcher import coil.size.OriginalSize import coil.size.PixelSize import coil.size.Size import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.coroutines.withContext import kotlin.coroutines.resume class ThumbnailFetcher(private val context: Context) : Fetcher<Uri> { override suspend fun fetch(pool: BitmapPool, data: Uri, size: Size, options: Options): FetchResult { return withContext(Dispatchers.IO) { suspendCancellableCoroutine { continuation -> val cancellationSignal = CancellationSignal() continuation.invokeOnCancellation { cancellationSignal.cancel() } val albumId = requireNotNull(data.lastPathSegment?.toLongOrNull()) val uri = ContentUris.withAppendedId(MediaStore.Audio.Albums.EXTERNAL_CONTENT_URI, albumId) val androidSize = when (size) { OriginalSize -> android.util.Size(1000, 1000) is PixelSize -> android.util.Size(size.width, size.height) } val bitmap = context.contentResolver.loadThumbnail(uri, androidSize, cancellationSignal) continuation.resume( DrawableResult( drawable = BitmapDrawable(context.resources, bitmap), isSampled = false, dataSource = DataSource.DISK, ) ) } } } override fun key(data: Uri) = data.toString() override fun handles(data: Uri) = data.scheme == "neeplayer" }
mit
4d2d5c243cba04129701e957061f592c
35.890909
107
0.676195
5.16285
false
false
false
false
natanieljr/droidmate
project/pcComponents/exploration/src/main/kotlin/org/droidmate/exploration/modelFeatures/reporter/EffectiveActions2MF.kt
1
7946
// DroidMate, an automated execution generator for Android apps. // Copyright (C) 2012-2018. Saarland University // // 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/>. // // Current Maintainers: // Nataniel Borges Jr. <nataniel dot borges at cispa dot saarland> // Jenny Hotzkow <jenny dot hotzkow at cispa dot saarland> // // Former Maintainers: // Konrad Jamrozik <jamrozik at st dot cs dot uni-saarland dot de> // // web: www.droidmate.org package org.droidmate.exploration.modelFeatures.reporter import kotlinx.coroutines.CoroutineName import org.droidmate.deviceInterface.exploration.isClick import org.droidmate.exploration.ExplorationContext import org.droidmate.exploration.modelFeatures.ModelFeature import org.droidmate.explorationModel.interaction.Interaction import org.droidmate.explorationModel.interaction.State import org.droidmate.explorationModel.interaction.Widget import org.droidmate.exploration.modelFeatures.misc.plot import java.awt.Point import java.awt.image.BufferedImage import java.awt.image.Raster import java.io.ByteArrayInputStream import java.io.File import java.nio.file.Files import java.nio.file.Path import java.time.temporal.ChronoUnit import java.util.* import javax.imageio.ImageIO import kotlin.coroutines.CoroutineContext class EffectiveActions2MF(private val pixelDensity: Int = nexus5XPixelDensity, private val includePlots: Boolean = true) : ModelFeature() { companion object { /** * The conversion depends on the density of the device. * To get the density of the device: Resources.getSystem().getDisplayMetrics().density * Here we use by default the density of the Nexus 5X used in the experiments (https://material.io/devices/) * Density Nexus 5x = 2.6 * * @return */ private const val nexus5XPixelDensity: Int = (24 * 2.6).toInt() } override val coroutineContext: CoroutineContext = CoroutineName("EffectiveActionsMF") /** * Keep track of effective actions during exploration * This is not used to dump the report at the end */ private var totalActions = 0 private var effectiveActions = 0 override suspend fun onNewInteracted(traceId: UUID, targetWidgets: List<Widget>, prevState: State<*>, newState: State<*>) { totalActions++ if (prevState != newState) effectiveActions++ } fun getTotalActions(): Int { return totalActions } fun getEffectiveActions(): Int { return effectiveActions } override suspend fun onAppExplorationFinished(context: ExplorationContext<*, *, *>) { val sb = StringBuilder() val header = "Time_Seconds\tTotal_Actions\tTotal_Effective\n" sb.append(header) val reportData: HashMap<Long, Pair<Int, Int>> = HashMap() // Ignore app start val records = context.explorationTrace.P_getActions().drop(1) val nrActions = records.size val startTimeStamp = records.first().startTimestamp var totalActions = 1 var effectiveActions = 1 for (i in 1 until nrActions) { val prevAction = records[i - 1] val currAction = records[i] val currTimestamp = currAction.startTimestamp val currTimeDiff = ChronoUnit.SECONDS.between(startTimeStamp, currTimestamp) if (actionWasEffective(prevAction, currAction)) effectiveActions++ totalActions++ reportData[currTimeDiff] = Pair(totalActions, effectiveActions) if (i % 100 == 0) log.info("Processing $i") } reportData.keys.sorted().forEach { key -> val value = reportData[key]!! sb.appendln("$key\t${value.first}\t${value.second}") } val reportFile = context.model.config.baseDir.resolve("effective_actions.txt") Files.write(reportFile, sb.toString().toByteArray()) if (includePlots) { log.info("Writing out plot $") this.writeOutPlot(reportFile, context.model.config.baseDir) } } // Currently used in child projects @Suppress("MemberVisibilityCanBePrivate") fun actionWasEffective(prevAction: Interaction<*>, currAction: Interaction<*>): Boolean { return if ((!prevAction.actionType.isClick()) || (! currAction.actionType.isClick())) true else { currAction.prevState != currAction.resState } } private fun writeOutPlot(dataFile: Path, resourceDir: Path) { val fileName = dataFile.fileName.resolveSibling(File(dataFile.fileName.toString()).nameWithoutExtension + "." + "pdf") val outFile = dataFile.resolveSibling(fileName) plot(dataFile.toAbsolutePath().toString(), outFile.toAbsolutePath().toString(), resourceDir) } /** * Returns the percentage similarity between 2 image files */ private fun compareImage(screenshotA: ByteArray, screenshotB: ByteArray): Double { var percentage = 0.0 try { // take buffer data from both image files val biA = ImageIO.read(ByteArrayInputStream(screenshotA)) //Original code: val dbA = biA.data.dataBuffer val dbA = getDataWithoutStatusBar(biA).dataBuffer //Get screenshot without Status bar val sizeA = dbA.size val biB = ImageIO.read(ByteArrayInputStream(screenshotB)) //Original code: val dbB = biB.data.dataBuffer val dbB = getDataWithoutStatusBar(biB).dataBuffer //Get screenshot without Status bar val sizeB = dbB.size var count = 0 // compare data-buffer objects if (sizeA == sizeB) { (0 until sizeA) .filter { dbA.getElem(it) == dbB.getElem(it) } .forEach { count++ } percentage = (count * 100 / sizeA).toDouble() } else log.info("Both images have different size") } catch (e: Exception) { log.error("Failed to compare image files: $screenshotA and $screenshotB", e) } return percentage } /** * Returns a copy of the screenshot without status bar * @param bi */ private fun getDataWithoutStatusBar(bi: BufferedImage): Raster { val raster = bi.data val width = raster.width val height = raster.height val startX = raster.minX val statusBarHeight = getStatusBarHeightInPX() val wr = Raster.createWritableRaster(raster.sampleModel, Point(raster.sampleModelTranslateX, raster.sampleModelTranslateY)) var tData: Any? = null for (i in statusBarHeight until statusBarHeight + (height - statusBarHeight)) { tData = raster.getDataElements(startX, i, width, 1, tData) wr.setDataElements(startX, i, width, 1, tData) } return wr } /** * Returns the Status Bar height in pixels * The status bar height in Android is 24dp (https://material.io/guidelines/layout/structure.html#structure-app-bar) * We need to convert dp to px. * @return */ private fun getStatusBarHeightInPX(): Int { return 24 * pixelDensity } }
gpl-3.0
03f486d7d349c611c6a144b92d11993c
34.797297
127
0.656179
4.644068
false
false
false
false
renard314/textfairy
app/src/main/java/com/renard/ocr/documents/creation/crop/CropImageFragment.kt
1
6687
/* * Copyright (C) 2007 The Android Open Source Project * Copyright (C) 2012,2013,2014,2015 Renard Wellnitz * * 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.renard.ocr.documents.creation.crop import android.graphics.Bitmap import android.graphics.Rect import android.graphics.RectF import android.os.Bundle import android.view.View import androidx.appcompat.app.AlertDialog import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.commit import com.renard.ocr.MonitoredActivity import com.renard.ocr.R import com.renard.ocr.cropimage.image_processing.BlurDetectionResult.Blurriness.STRONG_BLUR import com.renard.ocr.databinding.ActivityCropimageBinding import com.renard.ocr.documents.creation.ocr.ImageLoadingViewModel import com.renard.ocr.documents.creation.ocr.ImageLoadingViewModel.ImageLoadStatus.PreparedForCrop import com.renard.ocr.util.PreferencesUtils import com.renard.ocr.util.afterMeasured /** * The activity can crop specific region of interest from an image. */ class CropImageFragment : Fragment(R.layout.activity_cropimage) { private var mRotation = 0 private var mCrop: CropHighlightView? = null private lateinit var binding: ActivityCropimageBinding override fun onViewCreated(view: View, savedInstanceState: Bundle?) { binding = ActivityCropimageBinding.bind(view) binding.itemRotateLeft.setOnClickListener { onRotateClicked(-1) } binding.itemRotateRight.setOnClickListener { onRotateClicked(1) } startCropping() } private fun showCropOnBoarding(blurDetectionResult: PreparedForCrop) { PreferencesUtils.setFirstScan(requireContext(), false) val builder = AlertDialog.Builder(requireContext()) builder.setTitle(R.string.crop_onboarding_title) builder.setMessage(R.string.crop_onboarding_message) builder.setPositiveButton(R.string.got_it) { dialog, _ -> dialog.dismiss() } builder.setOnDismissListener { handleBlurResult(blurDetectionResult) } builder.show() } private fun onRotateClicked(delta: Int) { val currentBitmap = binding.cropImageView.mBitmapDisplayed.bitmap ?: return mRotation += if (delta < 0) { -delta * 3 } else { delta } mRotation %= 4 binding.cropImageView.setImageBitmapResetBase(currentBitmap, false, mRotation * 90) showDefaultCroppingRectangle(currentBitmap) } private fun startCropping() { (requireActivity() as MonitoredActivity).setToolbarMessage(R.string.crop_title) val model by activityViewModels<ImageLoadingViewModel>() model.content.observe(viewLifecycleOwner) { status -> when (status) { is ImageLoadingViewModel.ImageLoadStatus.Loaded -> { binding.root.afterMeasured { val margin = resources.getDimension(R.dimen.crop_margin) val width = (binding.cropLayout.width - 2 * margin).toInt() val height = (binding.cropLayout.height - 2 * margin).toInt() status.prepareForCropping(width, height) } } is PreparedForCrop -> { analytics().sendBlurResult(status.blurDetectionResult) binding.cropLayout.displayedChild = 1 binding.root.afterMeasured { binding.cropImageView.setImageBitmapResetBase(status.bitmap, true, mRotation * 90) if (PreferencesUtils.isFirstScan(requireContext())) { showCropOnBoarding(status) } else { handleBlurResult(status) } binding.itemRotateLeft.isVisible = true binding.itemRotateRight.isVisible = true binding.itemSave.isVisible = true binding.itemSave.setOnClickListener { status.cropAndProject( mCrop!!.trapezoid, mCrop!!.perspectiveCorrectedBoundingRect, mRotation ) } } } else -> { /*ignored*/ } } } } private fun analytics() = (requireActivity() as MonitoredActivity).anaLytics private fun handleBlurResult(blurDetectionResult: PreparedForCrop) { analytics().sendScreenView(SCREEN_NAME) showDefaultCroppingRectangle(blurDetectionResult.bitmap) if (blurDetectionResult.blurDetectionResult.blurriness == STRONG_BLUR) { binding.cropImageView.zoomTo(1f, 500f); (requireActivity() as MonitoredActivity).setToolbarMessage(R.string.image_is_blurred) parentFragmentManager.commit(true) { add( BlurWarningDialog.newInstance(blurDetectionResult.blurDetectionResult.blurValue.toFloat()), BlurWarningDialog.TAG ) } } } private fun showDefaultCroppingRectangle(bitmap: Bitmap) { val width = bitmap.width val height = bitmap.height val imageRect = Rect(0, 0, width, height) // make the default size about 4/5 of the width or height val cropWidth = Math.min(width, height) * 4 / 5 val x = (width - cropWidth) / 2 val y = (height - cropWidth) / 2 val cropRect = RectF(x.toFloat(), y.toFloat(), (x + cropWidth).toFloat(), (y + cropWidth).toFloat()) val hv = CropHighlightView(binding.cropImageView, imageRect, cropRect) binding.cropImageView.resetMaxZoom() binding.cropImageView.add(hv) mCrop = hv mCrop!!.setFocus(true) binding.cropImageView.invalidate() } companion object { internal const val HINT_DIALOG_ID = 2 const val SCREEN_NAME = "Crop Image" } }
apache-2.0
a94a59cb590dbf00e9ca098179fe0d9f
40.283951
115
0.638403
4.739192
false
false
false
false
nickthecoder/paratask
paratask-app/src/main/kotlin/uk/co/nickthecoder/paratask/project/ParataskAction.kt
1
3248
/* ParaTask Copyright (C) 2017 Nick Robinson> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package uk.co.nickthecoder.paratask.project import javafx.event.EventHandler import javafx.scene.control.MenuItem import javafx.scene.control.SplitMenuButton import javafx.scene.image.Image import javafx.scene.image.ImageView import javafx.scene.input.KeyCode import uk.co.nickthecoder.paratask.* import uk.co.nickthecoder.paratask.gui.ApplicationAction import uk.co.nickthecoder.paratask.gui.ShortcutHelper import uk.co.nickthecoder.paratask.parameters.ShortcutParameter import uk.co.nickthecoder.paratask.tools.HomeTool class ParataskAction( name: String, keyCode: KeyCode?, shift: Boolean? = false, control: Boolean? = false, alt: Boolean? = false, meta: Boolean? = false, shortcut: Boolean? = false, tooltip: String? = null, label: String? = null) : ApplicationAction(name, keyCode, shift, control, alt, meta, shortcut, tooltip, label) { init { ParataskActions.add(this) } fun createToolButton(shortcuts: ShortcutHelper? = null, action: (Tool) -> Unit): ToolSplitMenuButton { shortcuts?.let { it.add(this) { action(HomeTool()) } } val split = ToolSplitMenuButton(label ?: "", image, action) split.tooltip = createTooltip() return split } fun editTask(): Task = EditShortcut(this) private class EditShortcut(val action: ParataskAction) : AbstractTask() { override val taskD = TaskDescription("editShortcut", description = "You will need to restart the application for new shortcuts to take effect. Sorry.") val shortcutP = ShortcutParameter("shortcut") init { shortcutP.keyCodeCombination = action.keyCodeCombination taskD.addParameters(shortcutP) } override fun run() { action.keyCodeCombination = shortcutP.keyCodeCombination ParataskActions.save() } } class ToolSplitMenuButton(label: String, icon: Image?, val action: (Tool) -> Unit) : SplitMenuButton() { init { text = label graphic = ImageView(icon) onAction = EventHandler { action(HomeTool()) } } init { TaskRegistry.home.listTasks().filterIsInstance<Tool>().forEach { tool -> val imageView = tool.icon?.let { ImageView(it) } val item = MenuItem(tool.shortTitle, imageView) item.onAction = EventHandler { action(tool) } items.add(item) } } } }
gpl-3.0
f3e3307d20a0bcbfa1192c4251214001
31.48
120
0.663177
4.523677
false
false
false
false
nemerosa/ontrack
ontrack-extension-casc/src/main/java/net/nemerosa/ontrack/extension/casc/schema/CascSchema.kt
1
5688
package net.nemerosa.ontrack.extension.casc.schema import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.extension.casc.CascContext import net.nemerosa.ontrack.model.annotations.APIDescription import net.nemerosa.ontrack.model.annotations.APIIgnore import net.nemerosa.ontrack.model.annotations.getPropertyName import java.time.Duration import kotlin.reflect.KClass import kotlin.reflect.KProperty import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.hasAnnotation import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.jvmErasure sealed class CascType( val description: String, ) { abstract val __type: String } class CascObject( val fields: List<CascField>, description: String, ) : CascType(description) { override val __type: String = "object" fun findFieldByName(name: String) = fields.find { it.name == name } } class CascArray( description: String, val type: CascType, ) : CascType(description) { override val __type: String = "array" } class CascField( val name: String, val type: CascType, val description: String, val required: Boolean, ) class CascJson : CascType("JSON type") { override val __type: String = "JSON" } class CascDuration: CascType("Duration") { override val __type: String = "Duration" } sealed class CascScalar( override val __type: String, description: String, ) : CascType(description) class CascString : CascScalar("string", "String type") class CascInt : CascScalar("int", "Int type") class CascLong : CascScalar("long", "Long type") class CascBoolean : CascScalar("boolean", "Boolean type") val cascString = CascString() val cascInt = CascInt() val cascLong = CascLong() val cascBoolean = CascBoolean() val cascJson = CascJson() val cascDuration = CascDuration() private val builtinTypes = listOf( cascString, cascInt, cascLong, cascBoolean, cascJson, ).associateBy { it.__type } // ==================================================================================== // ==================================================================================== // ==================================================================================== class DescribedCascType( val type: CascType, val description: String, val required: Boolean = false, ) { fun required() = DescribedCascType(type, description, required = true) } fun CascContext.with(description: String) = DescribedCascType(type, description) fun cascObject( description: String, vararg fields: CascField, ) = CascObject( fields.toList(), description ) fun cascObject( description: String, vararg fields: Pair<String, DescribedCascType>, ) = CascObject( description = description, fields = fields.map { (name, described) -> CascField( name = name, type = described.type, description = described.description, required = described.required, ) } ) fun cascArray( description: String, type: CascType, ) = CascArray( description, type ) fun cascField( name: String, type: CascType, description: String, required: Boolean, ) = CascField( name = name, type = type, description = description, required = required, ) // ==================================================================================== // ==================================================================================== // ==================================================================================== fun cascObject(type: KClass<*>): CascType { val description = type.findAnnotation<APIDescription>()?.value ?: type.java.simpleName return CascObject( type.memberProperties.mapNotNull { property -> if (!property.hasAnnotation<APIIgnore>()) { cascField(property) } else { null } }, description ) } fun cascField( property: KProperty<*>, type: CascType = cascFieldType(property), description: String? = null, required: Boolean? = null, ): CascField { val actualDescription = description ?: property.findAnnotation<APIDescription>()?.value ?: property.name return CascField( name = cascFieldName(property), type = type, description = actualDescription, required = required ?: !property.returnType.isMarkedNullable, ) } fun cascFieldName(property: KProperty<*>): String = getPropertyName(property) internal fun cascFieldType(property: KProperty<*>): CascType = when { property.hasAnnotation<CascPropertyType>() -> cascPropertyType(property) property.hasAnnotation<CascNested>() -> cascNestedType(property) else -> when (property.returnType.jvmErasure) { String::class -> cascString Boolean::class -> cascBoolean Int::class -> cascInt Long::class -> cascLong JsonNode::class -> cascJson Duration::class -> cascDuration else -> error("Cannot get CasC type for $property") } } private fun cascPropertyType(property: KProperty<*>): CascType { val propertyType = property.findAnnotation<CascPropertyType>() ?: error("CascPropertyType annotation is expected on $property.") val type = propertyType.type .takeIf { it.isNotBlank() } ?: propertyType.value return builtinTypes[type] ?: error("Cannot find built-in type [$type] required by $property.") } private fun cascNestedType(property: KProperty<*>): CascType = cascObject(property.returnType.jvmErasure)
mit
efb3bcbcc44ff0937766e38a5cef94d4
27.727273
98
0.613572
4.590799
false
false
false
false
Kerr1Gan/ShareBox
share/src/main/java/com/ethan/and/ui/fragment/SimpleDialogFragment.kt
1
1852
package com.ethan.and.ui.fragment import android.annotation.SuppressLint import android.app.Dialog import android.content.Intent import android.os.Bundle import android.support.v4.app.Fragment import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatDialogFragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup /** * Created by Ethan_Xiang on 2017/10/20. */ class SimpleDialogFragment : AppCompatDialogFragment { private var mDialog: Dialog? = null private var mReset = false constructor() : super() @SuppressLint("ValidFragment") constructor(dialog: Dialog) { mDialog = dialog if (mDialog is IActivityResult) { (mDialog as IActivityResult).setFragmentHost(this) } } override fun onCreateDialog(savedInstanceState: Bundle?): Dialog { val local = mDialog return if (local != null) { mReset = false local } else { mReset = true AlertDialog.Builder(context!!).create() } } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { if (mReset) { dismiss() } return super.onCreateView(inflater, container, savedInstanceState) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (mDialog is IActivityResult) { (mDialog as IActivityResult).onActivityResult(requestCode, resultCode, data) } } interface IActivityResult { fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) fun setFragmentHost(fragment: Fragment?) fun getFragmentHost(): Fragment? } }
apache-2.0
fb29213b7605c785e8b19b1fa3848adb
28.887097
116
0.675486
4.736573
false
false
false
false
marcelgross90/Cineaste
app/src/main/kotlin/de/cineaste/android/viewholder/series/SeriesSearchViewHolder.kt
1
1102
package de.cineaste.android.viewholder.series import android.content.Context import android.view.View import android.widget.TextView import de.cineaste.android.R import de.cineaste.android.entity.series.Series import de.cineaste.android.listener.ItemClickListener class SeriesSearchViewHolder( itemView: View, listener: ItemClickListener, context: Context ) : AbstractSeriesViewHolder(itemView, listener, context) { private val releaseDate: TextView = itemView.findViewById(R.id.releaseDate) override fun assignData(series: Series, position: Int) { setBaseInformation(series) val seriesReleaseDate = series.releaseDate if (seriesReleaseDate != null) { releaseDate.text = convertDate(seriesReleaseDate) } else { releaseDate.text = resources.getString(R.string.coming_soon) } listener?.let { view.setOnClickListener { view -> listener.onItemClickListener( series.id, arrayOf(view, poster) ) } } } }
gpl-3.0
bdec20ab94a156f0fabdc1427639bcd5
29.611111
79
0.662432
4.791304
false
false
false
false
vondear/RxTools
RxUI/src/main/java/com/tamsiree/rxui/view/loadingview/animation/interpolator/KeyFrameInterpolator.kt
1
1830
package com.tamsiree.rxui.view.loadingview.animation.interpolator import android.animation.TimeInterpolator import android.view.animation.Interpolator import com.tamsiree.rxui.view.loadingview.animation.interpolator.Ease.inOut /** * @author tamsiree */ class KeyFrameInterpolator(private val interpolator: TimeInterpolator, private vararg var fractions: Float) : Interpolator { fun setFractions(vararg fractions: Float) { this.fractions = fractions } @Synchronized override fun getInterpolation(input: Float): Float { var input = input if (fractions.size > 1) { for (i in 0 until fractions.size - 1) { val start = fractions[i] val end = fractions[i + 1] val duration = end - start if (input >= start && input <= end) { input = (input - start) / duration return start + (interpolator.getInterpolation(input) * duration) } } } return interpolator.getInterpolation(input) } companion object { @JvmStatic fun easeInOut(vararg fractions: Float): KeyFrameInterpolator { val interpolator = KeyFrameInterpolator(inOut()) interpolator.setFractions(*fractions) return interpolator } @JvmStatic fun pathInterpolator(controlX1: Float, controlY1: Float, controlX2: Float, controlY2: Float, vararg fractions: Float): KeyFrameInterpolator { val interpolator = KeyFrameInterpolator(PathInterpolatorCompat.create(controlX1, controlY1, controlX2, controlY2)) interpolator.setFractions(*fractions) return interpolator } } }
apache-2.0
3a0af98d4f8044c49106e84e7cd6d456
34.901961
126
0.608743
5.12605
false
false
false
false
Ribesg/anko
dsl/src/org/jetbrains/android/anko/annotations/AnnotationManager.kt
1
2265
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.annotations import org.jetbrains.android.anko.utils.getPackageName import org.w3c.dom.Document import org.xml.sax.InputSource import java.io.StringReader import javax.xml.parsers.DocumentBuilderFactory import kotlinx.dom.childElements class AnnotationManager(private val provider: AnnotationProvider) { fun findAnnotationsFor(q: String): Set<ExternalAnnotation> { var packageName = getPackageName(q.substringBefore(' ')) val annotations = provider.getExternalAnnotations(packageName) return annotations[q] ?: setOf() } } fun parseAnnotations(doc: Document): Map<String, Set<ExternalAnnotation>> { val map = hashMapOf<String, Set<ExternalAnnotation>>() for (element in doc.documentElement.childElements("item")) { val annotations = element.childElements("annotation") .map { parseAnnotation(it.getAttribute("name")) } .filterNotNull() .toSet() map.put(element.getAttribute("name"), annotations) } return map } private fun parseAnnotation(fqName: String): ExternalAnnotation? { return when (fqName) { "org.jetbrains.annotations.NotNull" -> ExternalAnnotation.NotNull "org.jetbrains.anko.GenerateLayout" -> ExternalAnnotation.GenerateLayout "org.jetbrains.anko.GenerateView" -> ExternalAnnotation.GenerateView else -> null } } internal fun parseXml(xmlText: String): Document { val factory = DocumentBuilderFactory.newInstance() val builder = factory.newDocumentBuilder() val inputSource = InputSource(StringReader(xmlText)) return builder.parse(inputSource) }
apache-2.0
718bf45d41912194060f9bae556c068c
34.968254
80
0.726269
4.502982
false
false
false
false
SapuSeven/BetterUntis
app/src/main/java/com/sapuseven/untis/activities/BaseActivity.kt
1
5225
package com.sapuseven.untis.activities import android.annotation.SuppressLint import android.content.Context import android.content.res.Configuration import android.graphics.Color import android.os.Bundle import android.util.Log import android.util.TypedValue import androidx.annotation.AttrRes import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.app.AppCompatDelegate import com.sapuseven.untis.R import com.sapuseven.untis.helpers.ErrorLogger import com.sapuseven.untis.helpers.config.PreferenceManager import com.sapuseven.untis.helpers.config.PreferenceUtils import java.io.File @SuppressLint("Registered") // This activity is not intended to be used directly open class BaseActivity : AppCompatActivity() { protected var currentTheme: String = "" private var currentDarkTheme: String = "" protected lateinit var preferences: PreferenceManager protected var hasOwnToolbar: Boolean = false private var themeId = -1 override fun onCreate(savedInstanceState: Bundle?) { ErrorLogger.initialize(this) Thread.setDefaultUncaughtExceptionHandler(CrashHandler(this, Thread.getDefaultUncaughtExceptionHandler())) if (!::preferences.isInitialized) preferences = PreferenceManager(this) currentTheme = PreferenceUtils.getPrefString(preferences, "preference_theme") currentDarkTheme = PreferenceUtils.getPrefString(preferences, "preference_dark_theme") setAppTheme(hasOwnToolbar) super.onCreate(savedInstanceState) } /** * Checks for saved crashes. Calls [onErrorLogFound] if logs are found. * * @return `true` if the logs contain a critical application crash, `false` otherwise */ protected fun checkForCrashes(): Boolean { val logFiles = File(filesDir, "logs").listFiles() if (logFiles?.isNotEmpty() == true) { onErrorLogFound() return logFiles.find { f -> f.name.startsWith("_") } != null } return false } /** * Gets called if any error logs are found. * * Override this function in your actual activity. */ open fun onErrorLogFound() { return } protected fun readCrashData(crashFile: File): String { val reader = crashFile.bufferedReader() val stackTrace = StringBuilder() val buffer = CharArray(1024) var length = reader.read(buffer) while (length != -1) { stackTrace.append(String(buffer, 0, length)) length = reader.read(buffer) } return stackTrace.toString() } override fun onStart() { super.onStart() setBlackBackground(PreferenceUtils.getPrefBool(preferences, "preference_dark_theme_oled")) } override fun onResume() { super.onResume() val theme = PreferenceUtils.getPrefString(preferences, "preference_theme") val darkTheme = PreferenceUtils.getPrefString(preferences, "preference_dark_theme") if (currentTheme != theme || currentDarkTheme != darkTheme) recreate() currentTheme = theme currentDarkTheme = darkTheme } override fun setTheme(resid: Int) { super.setTheme(resid) themeId = resid } private fun setAppTheme(hasOwnToolbar: Boolean) { when (currentTheme) { "untis" -> setTheme(if (hasOwnToolbar) R.style.AppTheme_ThemeUntis_NoActionBar else R.style.AppTheme_ThemeUntis) "blue" -> setTheme(if (hasOwnToolbar) R.style.AppTheme_ThemeBlue_NoActionBar else R.style.AppTheme_ThemeBlue) "green" -> setTheme(if (hasOwnToolbar) R.style.AppTheme_ThemeGreen_NoActionBar else R.style.AppTheme_ThemeGreen) "pink" -> setTheme(if (hasOwnToolbar) R.style.AppTheme_ThemePink_NoActionBar else R.style.AppTheme_ThemePink) "cyan" -> setTheme(if (hasOwnToolbar) R.style.AppTheme_ThemeCyan_NoActionBar else R.style.AppTheme_ThemeCyan) "pixel" -> setTheme(if (hasOwnToolbar) R.style.AppTheme_ThemePixel_NoActionBar else R.style.AppTheme_ThemePixel) else -> setTheme(if (hasOwnToolbar) R.style.AppTheme_NoActionBar else R.style.AppTheme) } delegate.localNightMode = when (PreferenceUtils.getPrefString(preferences, "preference_dark_theme", currentDarkTheme)) { "on" -> AppCompatDelegate.MODE_NIGHT_YES "auto" -> AppCompatDelegate.MODE_NIGHT_AUTO_BATTERY else -> AppCompatDelegate.MODE_NIGHT_NO } } private fun setBlackBackground(blackBackground: Boolean) { if (blackBackground && resources.configuration.uiMode.and(Configuration.UI_MODE_NIGHT_MASK) == Configuration.UI_MODE_NIGHT_YES) window.decorView.setBackgroundColor(Color.BLACK) else { val typedValue = TypedValue() theme.resolveAttribute(android.R.attr.windowBackground, typedValue, true) if (typedValue.type >= TypedValue.TYPE_FIRST_COLOR_INT && typedValue.type <= TypedValue.TYPE_LAST_COLOR_INT) window.decorView.setBackgroundColor(typedValue.data) } } protected fun getAttr(@AttrRes attr: Int): Int { val typedValue = TypedValue() theme.resolveAttribute(attr, typedValue, true) return typedValue.data } private class CrashHandler(val context: Context, private val defaultUncaughtExceptionHandler: Thread.UncaughtExceptionHandler?) : Thread.UncaughtExceptionHandler { override fun uncaughtException(t: Thread, e: Throwable) { Log.e("BetterUntis", "Application crashed!", e) saveCrash(e) defaultUncaughtExceptionHandler?.uncaughtException(t, e) } private fun saveCrash(e: Throwable) { ErrorLogger.instance?.logThrowable(e) } } }
gpl-3.0
ffefc879051513a23e57fcdabf18ac39
34.544218
164
0.765167
3.896346
false
false
false
false
stripe/stripe-android
payments-core/src/main/java/com/stripe/android/model/CreateFinancialConnectionsSessionParams.kt
1
800
package com.stripe.android.model internal data class CreateFinancialConnectionsSessionParams( val clientSecret: String, val customerName: String, val customerEmailAddress: String? ) { fun toMap(): Map<String, Any> { val paymentMethod = PaymentMethodCreateParams.createUSBankAccount( billingDetails = PaymentMethod.BillingDetails( name = customerName, email = customerEmailAddress ) ) return mapOf( PARAM_CLIENT_SECRET to clientSecret, PARAM_PAYMENT_METHOD_DATA to paymentMethod.toParamMap() ) } companion object { private const val PARAM_CLIENT_SECRET = "client_secret" private const val PARAM_PAYMENT_METHOD_DATA = "payment_method_data" } }
mit
2409690ef940c2e77c404aa20eb4d6d3
31
75
0.64875
5.031447
false
false
false
false
stripe/stripe-android
identity/src/main/java/com/stripe/android/identity/navigation/CouldNotCaptureFragment.kt
1
6012
package com.stripe.android.identity.navigation import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.IdRes import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.res.stringResource import androidx.core.os.bundleOf import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.stripe.android.identity.R import com.stripe.android.identity.analytics.IdentityAnalyticsRequestFactory.Companion.SCREEN_NAME_ERROR import com.stripe.android.identity.navigation.IdentityDocumentScanFragment.Companion.ARG_SHOULD_START_FROM_BACK import com.stripe.android.identity.states.IdentityScanState import com.stripe.android.identity.ui.ErrorScreen import com.stripe.android.identity.ui.ErrorScreenButton import com.stripe.android.identity.utils.navigateToUploadFragment /** * Fragment to indicate live capture failure. */ internal class CouldNotCaptureFragment( identityViewModelFactory: ViewModelProvider.Factory ) : BaseErrorFragment(identityViewModelFactory) { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = ComposeView(requireContext()).apply { val args = requireNotNull(arguments) { "Argument to CouldNotCaptureFragment is null" } val scanType = args[ARG_COULD_NOT_CAPTURE_SCAN_TYPE] as IdentityScanState.ScanType setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { ErrorScreen( title = stringResource(id = R.string.could_not_capture_title), message1 = stringResource(id = R.string.could_not_capture_body1), message2 = if (scanType == IdentityScanState.ScanType.SELFIE) { null } else { stringResource( R.string.could_not_capture_body2 ) }, topButton = if (scanType == IdentityScanState.ScanType.SELFIE) { null } else { ErrorScreenButton( buttonText = stringResource(id = R.string.file_upload), ) { identityViewModel.screenTracker.screenTransitionStart( SCREEN_NAME_ERROR ) navigateToUploadFragment( scanType.toUploadDestinationId(), shouldShowTakePhoto = true, shouldShowChoosePhoto = !args.getBoolean(ARG_REQUIRE_LIVE_CAPTURE) ) } }, bottomButton = ErrorScreenButton( buttonText = stringResource(id = R.string.try_again) ) { identityViewModel.screenTracker.screenTransitionStart( SCREEN_NAME_ERROR ) findNavController().navigate( scanType.toScanDestinationId(), bundleOf( ARG_SHOULD_START_FROM_BACK to scanType.toShouldStartFromBack() ) ) } ) } } internal companion object { const val ARG_COULD_NOT_CAPTURE_SCAN_TYPE = "scanType" const val ARG_REQUIRE_LIVE_CAPTURE = "requireLiveCapture" @IdRes private fun IdentityScanState.ScanType.toUploadDestinationId() = when (this) { IdentityScanState.ScanType.ID_FRONT -> R.id.action_couldNotCaptureFragment_to_IDUploadFragment IdentityScanState.ScanType.ID_BACK -> R.id.action_couldNotCaptureFragment_to_IDUploadFragment IdentityScanState.ScanType.DL_FRONT -> R.id.action_couldNotCaptureFragment_to_driverLicenseUploadFragment IdentityScanState.ScanType.DL_BACK -> R.id.action_couldNotCaptureFragment_to_driverLicenseUploadFragment IdentityScanState.ScanType.PASSPORT -> R.id.action_couldNotCaptureFragment_to_passportUploadFragment IdentityScanState.ScanType.SELFIE -> { throw IllegalArgumentException("SELFIE doesn't support upload") } } @IdRes private fun IdentityScanState.ScanType.toScanDestinationId() = when (this) { IdentityScanState.ScanType.ID_FRONT -> R.id.action_couldNotCaptureFragment_to_IDScanFragment IdentityScanState.ScanType.ID_BACK -> R.id.action_couldNotCaptureFragment_to_IDScanFragment IdentityScanState.ScanType.DL_FRONT -> R.id.action_couldNotCaptureFragment_to_driverLicenseScanFragment IdentityScanState.ScanType.DL_BACK -> R.id.action_couldNotCaptureFragment_to_driverLicenseScanFragment IdentityScanState.ScanType.PASSPORT -> R.id.action_couldNotCaptureFragment_to_passportScanFragment IdentityScanState.ScanType.SELFIE -> R.id.action_couldNotCaptureFragment_to_selfieFragment } private fun IdentityScanState.ScanType.toShouldStartFromBack() = when (this) { IdentityScanState.ScanType.ID_FRONT -> false IdentityScanState.ScanType.ID_BACK -> true IdentityScanState.ScanType.DL_FRONT -> false IdentityScanState.ScanType.DL_BACK -> true IdentityScanState.ScanType.PASSPORT -> false IdentityScanState.ScanType.SELFIE -> false } } }
mit
f70139f32643c03599489ab0f210b3dc
44.203008
111
0.610279
5.339254
false
false
false
false
AndroidX/androidx
compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/gestures/TransformableState.kt
3
9925
/* * 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.foundation.gestures import androidx.compose.animation.core.AnimationSpec import androidx.compose.animation.core.AnimationState import androidx.compose.animation.core.Spring import androidx.compose.animation.core.SpringSpec import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.animateTo import androidx.compose.foundation.MutatePriority import androidx.compose.foundation.MutatorMutex import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState import androidx.compose.ui.geometry.Offset import kotlinx.coroutines.coroutineScope import androidx.compose.foundation.internal.JvmDefaultWithCompatibility /** * State of [transformable]. Allows for a granular control of how different gesture * transformations are consumed by the user as well as to write custom transformation methods * using [transform] suspend function. */ @JvmDefaultWithCompatibility interface TransformableState { /** * Call this function to take control of transformations and gain the ability to send transform * events via [TransformScope.transformBy]. All actions that change zoom, pan or rotation * values must be performed within a [transform] block (even if they don't call any other * methods on this object) in order to guarantee that mutual exclusion is enforced. * * If [transform] is called from elsewhere with the [transformPriority] higher or equal to * ongoing transform, ongoing transform will be canceled. */ suspend fun transform( transformPriority: MutatePriority = MutatePriority.Default, block: suspend TransformScope.() -> Unit ) /** * Whether this [TransformableState] is currently transforming by gesture or programmatically or * not. */ val isTransformInProgress: Boolean } /** * Scope used for suspending transformation operations */ @JvmDefaultWithCompatibility interface TransformScope { /** * Attempts to transform by [zoomChange] in relative multiplied value, by [panChange] in * pixels and by [rotationChange] in degrees. * * @param zoomChange scale factor multiplier change for zoom * @param panChange panning offset change, in [Offset] pixels * @param rotationChange change of the rotation in degrees */ fun transformBy( zoomChange: Float = 1f, panChange: Offset = Offset.Zero, rotationChange: Float = 0f ) } /** * Default implementation of [TransformableState] interface that contains necessary information * about the ongoing transformations and provides smooth transformation capabilities. * * This is the simplest way to set up a [transformable] modifier. When constructing this * [TransformableState], you must provide a [onTransformation] lambda, which will be invoked * whenever pan, zoom or rotation happens (by gesture input or any [TransformableState.transform] * call) with the deltas from the previous event. * * @param onTransformation callback invoked when transformation occurs. The callback receives the * change from the previous event. It's relative scale multiplier for zoom, [Offset] in pixels * for pan and degrees for rotation. Callers should update their state in this lambda. */ fun TransformableState( onTransformation: (zoomChange: Float, panChange: Offset, rotationChange: Float) -> Unit ): TransformableState = DefaultTransformableState(onTransformation) /** * Create and remember default implementation of [TransformableState] interface that contains * necessary information about the ongoing transformations and provides smooth transformation * capabilities. * * This is the simplest way to set up a [transformable] modifier. When constructing this * [TransformableState], you must provide a [onTransformation] lambda, which will be invoked * whenever pan, zoom or rotation happens (by gesture input or any [TransformableState.transform] * call) with the deltas from the previous event. * * @param onTransformation callback invoked when transformation occurs. The callback receives the * change from the previous event. It's relative scale multiplier for zoom, [Offset] in pixels * for pan and degrees for rotation. Callers should update their state in this lambda. */ @Composable fun rememberTransformableState( onTransformation: (zoomChange: Float, panChange: Offset, rotationChange: Float) -> Unit ): TransformableState { val lambdaState = rememberUpdatedState(onTransformation) return remember { TransformableState { z, p, r -> lambdaState.value.invoke(z, p, r) } } } /** * Animate zoom by a ratio of [zoomFactor] over the current size and suspend until its finished. * * @param zoomFactor ratio over the current size by which to zoom. For example, if [zoomFactor] * is `3f`, zoom will be increased 3 fold from the current value. * @param animationSpec [AnimationSpec] to be used for animation */ suspend fun TransformableState.animateZoomBy( zoomFactor: Float, animationSpec: AnimationSpec<Float> = SpringSpec(stiffness = Spring.StiffnessLow) ) { require(zoomFactor > 0) { "zoom value should be greater than 0" } var previous = 1f transform { AnimationState(initialValue = previous).animateTo(zoomFactor, animationSpec) { val scaleFactor = if (previous == 0f) 1f else this.value / previous transformBy(zoomChange = scaleFactor) previous = this.value } } } /** * Animate rotate by a ratio of [degrees] clockwise and suspend until its finished. * * @param degrees ratio over the current size by which to rotate, in degrees * @param animationSpec [AnimationSpec] to be used for animation */ suspend fun TransformableState.animateRotateBy( degrees: Float, animationSpec: AnimationSpec<Float> = SpringSpec(stiffness = Spring.StiffnessLow) ) { var previous = 0f transform { AnimationState(initialValue = previous).animateTo(degrees, animationSpec) { val delta = this.value - previous transformBy(rotationChange = delta) previous = this.value } } } /** * Animate pan by [offset] Offset in pixels and suspend until its finished * * @param offset offset to pan, in pixels * @param animationSpec [AnimationSpec] to be used for pan animation */ suspend fun TransformableState.animatePanBy( offset: Offset, animationSpec: AnimationSpec<Offset> = SpringSpec(stiffness = Spring.StiffnessLow) ) { var previous = Offset.Zero transform { AnimationState( typeConverter = Offset.VectorConverter, initialValue = previous ) .animateTo(offset, animationSpec) { val delta = this.value - previous transformBy(panChange = delta) previous = this.value } } } /** * Zoom without animation by a ratio of [zoomFactor] over the current size and suspend until it's * set. * * @param zoomFactor ratio over the current size by which to zoom */ suspend fun TransformableState.zoomBy(zoomFactor: Float) = transform { transformBy(zoomFactor, Offset.Zero, 0f) } /** * Rotate without animation by a [degrees] degrees and suspend until it's set. * * @param degrees degrees by which to rotate */ suspend fun TransformableState.rotateBy(degrees: Float) = transform { transformBy(1f, Offset.Zero, degrees) } /** * Pan without animation by a [offset] Offset in pixels and suspend until it's set. * * @param offset offset in pixels by which to pan */ suspend fun TransformableState.panBy(offset: Offset) = transform { transformBy(1f, offset, 0f) } /** * Stop and suspend until any ongoing [TransformableState.transform] with priority * [terminationPriority] or lower is terminated. * * @param terminationPriority transformation that runs with this priority or lower will be stopped */ suspend fun TransformableState.stopTransformation( terminationPriority: MutatePriority = MutatePriority.Default ) { this.transform(terminationPriority) { // do nothing, just lock the mutex so other scroll actors are cancelled } } private class DefaultTransformableState( val onTransformation: (zoomChange: Float, panChange: Offset, rotationChange: Float) -> Unit ) : TransformableState { private val transformScope: TransformScope = object : TransformScope { override fun transformBy(zoomChange: Float, panChange: Offset, rotationChange: Float) = onTransformation(zoomChange, panChange, rotationChange) } private val transformMutex = MutatorMutex() private val isTransformingState = mutableStateOf(false) override suspend fun transform( transformPriority: MutatePriority, block: suspend TransformScope.() -> Unit ): Unit = coroutineScope { transformMutex.mutateWith(transformScope, transformPriority) { isTransformingState.value = true try { block() } finally { isTransformingState.value = false } } } override val isTransformInProgress: Boolean get() = isTransformingState.value }
apache-2.0
fdf58d5ea920d74aa2ef1012e99157b6
37.030651
100
0.730176
4.629198
false
false
false
false
AndroidX/androidx
glance/glance-appwidget/src/androidMain/kotlin/androidx/glance/appwidget/NormalizeCompositionTree.kt
3
11783
/* * 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.glance.appwidget import android.util.Log import androidx.compose.ui.unit.dp import androidx.glance.AndroidResourceImageProvider import androidx.glance.BackgroundModifier import androidx.glance.Emittable import androidx.glance.EmittableButton import androidx.glance.EmittableImage import androidx.glance.EmittableWithChildren import androidx.glance.GlanceModifier import androidx.glance.ImageProvider import androidx.glance.action.ActionModifier import androidx.glance.action.LambdaAction import androidx.glance.appwidget.lazy.EmittableLazyListItem import androidx.glance.background import androidx.glance.extractModifier import androidx.glance.findModifier import androidx.glance.layout.Alignment import androidx.glance.layout.ContentScale import androidx.glance.layout.EmittableBox import androidx.glance.layout.HeightModifier import androidx.glance.layout.WidthModifier import androidx.glance.layout.fillMaxHeight import androidx.glance.layout.fillMaxSize import androidx.glance.layout.fillMaxWidth import androidx.glance.layout.padding import androidx.glance.text.EmittableText import androidx.glance.toEmittableText import androidx.glance.unit.Dimension internal fun normalizeCompositionTree(root: RemoteViewsRoot) { coerceToOneChild(root) root.normalizeSizes() root.transformTree { view -> if (view is EmittableLazyListItem) normalizeLazyListItem(view) view.transformBackgroundImageAndActionRipple() } } /** * Ensure that [container] has only one direct child. * * If [container] has multiple children, wrap them in an [EmittableBox] and make that the only child * of container. If [container] contains only children of type [EmittableSizeBox], then we will make * sure each of the [EmittableSizeBox]es has one child by wrapping their children in an * [EmittableBox]. */ private fun coerceToOneChild(container: EmittableWithChildren) { if (container.children.isNotEmpty() && container.children.all { it is EmittableSizeBox }) { for (item in container.children) { item as EmittableSizeBox if (item.children.size == 1) continue val box = EmittableBox() box.children += item.children item.children.clear() item.children += box } return } else if (container.children.size == 1) { return } val box = EmittableBox() box.children += container.children container.children.clear() container.children += box } /** * Resolve mixing wrapToContent and fillMaxSize on containers. * * Make sure that if a node with wrapToContent has a child with fillMaxSize, then it becomes * fillMaxSize. Otherwise, the behavior depends on the version of Android. */ private fun EmittableWithChildren.normalizeSizes() { children.forEach { child -> if (child is EmittableWithChildren) { child.normalizeSizes() } } if ((modifier.findModifier<HeightModifier>()?.height ?: Dimension.Wrap) is Dimension.Wrap && children.any { child -> child.modifier.findModifier<HeightModifier>()?.height is Dimension.Fill } ) { modifier = modifier.fillMaxHeight() } if ((modifier.findModifier<WidthModifier>()?.width ?: Dimension.Wrap) is Dimension.Wrap && children.any { child -> child.modifier.findModifier<WidthModifier>()?.width is Dimension.Fill } ) { modifier = modifier.fillMaxWidth() } } /** Transform each node in the tree. */ private fun EmittableWithChildren.transformTree(block: (Emittable) -> Emittable) { children.forEachIndexed { index, child -> val newChild = block(child) children[index] = newChild if (newChild is EmittableWithChildren) newChild.transformTree(block) } } /** * Walks through the Emittable tree and updates the key for all LambdaActions. * * This function updates the key such that the final key is equal to the original key plus a string * indicating its index among its siblings. This is because sibling Composables will often have the * same key due to how [androidx.compose.runtime.currentCompositeKeyHash] works. Adding the index * makes sure that all of these keys are unique. * * Note that, because we run the same composition multiple times for different sizes in certain * modes (see [ForEachSize]), action keys in one SizeBox should mirror the action keys in other * SizeBoxes, so that if an action is triggered on the widget being displayed in one size, the state * will be updated for the composition in all sizes. This is why there can be multiple LambdaActions * for each key, even after de-duping. */ internal fun EmittableWithChildren.updateLambdaActionKeys(): Map<String, List<LambdaAction>> = children.foldIndexed( mutableMapOf<String, MutableList<LambdaAction>>() ) { index, actions, child -> val (actionMod, modifiers) = child.modifier.extractModifier<ActionModifier>() if (actionMod != null && actionMod.action is LambdaAction && child !is EmittableSizeBox && child !is EmittableLazyListItem) { val action = actionMod.action as LambdaAction val newKey = action.key + "+$index" val newAction = LambdaAction(newKey, action.block) actions.getOrPut(newKey) { mutableListOf() }.add(newAction) child.modifier = modifiers.then(ActionModifier(newAction)) } if (child is EmittableWithChildren) { child.updateLambdaActionKeys().forEach { (key, childActions) -> actions.getOrPut(key) { mutableListOf() }.addAll(childActions) } } actions } private fun normalizeLazyListItem(view: EmittableLazyListItem) { if (view.children.size == 1 && view.alignment == Alignment.CenterStart) return val box = EmittableBox() box.children += view.children box.contentAlignment = view.alignment box.modifier = view.modifier view.children.clear() view.children += box view.alignment = Alignment.CenterStart } /** * If this [Emittable] has a background image or a ripple, transform the emittable so that it is * wrapped in an [EmittableBox], with the background and ripple added as [ImageView]s in the * background and foreground. * * If this is an [EmittableButton], we additonally set a clip outline on the wrapper box, and * convert the target emittable to an [EmittableText] */ private fun Emittable.transformBackgroundImageAndActionRipple(): Emittable { // EmittableLazyListItem and EmittableSizeBox are wrappers for their immediate only child, // and do not get translated to their own element. We will transform their child instead. if (this is EmittableLazyListItem || this is EmittableSizeBox) return this var target = this // We only need to add a background image view if the background is a Bitmap, or a // drawable resource with non-default content scale. Otherwise, we can set the background // directly on the target element in ApplyModifiers.kt. val (bgModifier, notBgModifier) = target.modifier.extractModifier<BackgroundModifier>() val addBackground = bgModifier?.imageProvider != null && (bgModifier.imageProvider !is AndroidResourceImageProvider || bgModifier.contentScale != ContentScale.FillBounds) // Add a ripple for every element with an action that does not have already have a built in // ripple. notBgModifier.warnIfMultipleClickableActions() val (actionModifier, notBgOrActionModifier) = notBgModifier.extractModifier<ActionModifier>() val addRipple = actionModifier != null && !hasBuiltinRipple() val isButton = target is EmittableButton if (!addBackground && !addRipple && !isButton) return target // Hoist the size and action modifiers to the wrapping Box, then set the target element to fill // the given space. doNotUnsetAction() prevents the views within the Box from being made // clickable. val (sizeModifiers, nonSizeModifiers) = notBgOrActionModifier.extractSizeModifiers() val boxModifiers = mutableListOf<GlanceModifier?>(sizeModifiers, actionModifier) val targetModifiers = mutableListOf<GlanceModifier?>( nonSizeModifiers.fillMaxSize() ) // If we don't need to emulate the background, add the background modifier back to the target. if (!addBackground) { targetModifiers += bgModifier } // If this is a button, set the necessary modifiers on the wrapping Box. if (target is EmittableButton) { boxModifiers += GlanceModifier .clipToOutline(true) .enabled(target.enabled) .background(ImageProvider(R.drawable.glance_button_outline)) target = target.toEmittableText() targetModifiers += GlanceModifier.padding(horizontal = 16.dp, vertical = 8.dp) } return EmittableBox().apply { modifier = boxModifiers.collect() if (isButton) contentAlignment = Alignment.Center if (addBackground && bgModifier != null) { children += EmittableImage().apply { modifier = GlanceModifier.fillMaxSize() provider = bgModifier.imageProvider contentScale = bgModifier.contentScale } } children += target.apply { modifier = targetModifiers.collect() } if (addRipple) { children += EmittableImage().apply { modifier = GlanceModifier.fillMaxSize() provider = ImageProvider(R.drawable.glance_ripple) } } } } private fun Emittable.hasBuiltinRipple() = this is EmittableSwitch || this is EmittableRadioButton || this is EmittableCheckBox private data class ExtractedSizeModifiers( val sizeModifiers: GlanceModifier = GlanceModifier, val nonSizeModifiers: GlanceModifier = GlanceModifier, ) /** * Split the [GlanceModifier] into one that contains the [WidthModifier]s and [HeightModifier]s and * one that contains the rest. */ private fun GlanceModifier.extractSizeModifiers() = if (any { it is WidthModifier || it is HeightModifier }) { foldIn(ExtractedSizeModifiers()) { acc, modifier -> if (modifier is WidthModifier || modifier is HeightModifier) { acc.copy(sizeModifiers = acc.sizeModifiers.then(modifier)) } else { acc.copy(nonSizeModifiers = acc.nonSizeModifiers.then(modifier)) } } } else { ExtractedSizeModifiers(nonSizeModifiers = this) } private fun GlanceModifier.warnIfMultipleClickableActions() { val actionCount = foldIn(0) { count, modifier -> if (modifier is ActionModifier) count + 1 else count } if (actionCount > 1) { Log.w( GlanceAppWidgetTag, "More than one clickable defined on the same GlanceModifier, " + "only the last one will be used." ) } } private fun MutableList<GlanceModifier?>.collect(): GlanceModifier = fold(GlanceModifier) { acc: GlanceModifier, mod: GlanceModifier? -> mod?.let { acc.then(mod) } ?: acc }
apache-2.0
7b916455d857b867c4478675b348dc54
40.199301
100
0.706611
4.485344
false
false
false
false
riaektiv/fdp
fdp-common/src/test/java/com/riaektiv/fdp/common/messages/GsonMessageConverterTest.kt
1
1122
package com.riaektiv.fdp.common.messages import com.riaektiv.fdp.common.TestSupport import com.riaektiv.fdp.common.kafka.KafkaMessage import com.riaektiv.fdp.common.kafka.MessageProperties import org.junit.Assert.assertEquals import org.junit.Test /** * Created: 3/24/2018, 6:15 PM Eastern Time * * @author Sergey Chuykov */ class GsonMessageConverterTest : TestSupport() { val converter = GsonMessageConverter() private class Token(val value: String) @Test fun fromMessage() { val json = """{"value":"qwerty"}""" val props = MessageProperties() props.objectType = Token::class.java.name val obj = converter.fromMessage(KafkaMessage(json.asByteBuffer(), props)) assert(obj is Token) val token = obj as Token assertEquals("qwerty", token.value) } @Test fun toMessage() { val props = MessageProperties() val message = converter.toMessage(Token("qwerty"), props) assertEquals("""{"value":"qwerty"}""", message.body.asString()) assertEquals(Token::class.java.name, props.objectType) } }
apache-2.0
671d8fa0c0f108b0294a121e88d49a8d
22.395833
81
0.670232
4.218045
false
true
false
false
ajordens/orca
keiko-redis-spring/src/main/kotlin/com/netflix/spinnaker/config/RedisQueueConfiguration.kt
2
7100
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License") * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.config import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.module.kotlin.KotlinModule import com.netflix.spinnaker.q.metrics.EventPublisher import com.netflix.spinnaker.q.migration.SerializationMigrator import com.netflix.spinnaker.q.redis.RedisClusterDeadMessageHandler import com.netflix.spinnaker.q.redis.RedisClusterQueue import com.netflix.spinnaker.q.redis.RedisDeadMessageHandler import com.netflix.spinnaker.q.redis.RedisQueue import java.net.URI import java.time.Clock import java.time.Duration import java.util.Optional import org.apache.commons.pool2.impl.GenericObjectPoolConfig import org.springframework.beans.factory.annotation.Qualifier import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import redis.clients.jedis.HostAndPort import redis.clients.jedis.Jedis import redis.clients.jedis.JedisCluster import redis.clients.jedis.JedisPool import redis.clients.jedis.Protocol import redis.clients.jedis.util.Pool @Configuration @EnableConfigurationProperties(RedisQueueProperties::class) @ConditionalOnProperty( value = ["keiko.queue.redis.enabled"], havingValue = "true", matchIfMissing = true ) class RedisQueueConfiguration { @Bean @ConditionalOnMissingBean(GenericObjectPoolConfig::class) fun redisPoolConfig() = GenericObjectPoolConfig<Any>().apply { blockWhenExhausted = false maxWaitMillis = 2000 } @Bean @ConditionalOnMissingBean(name = ["queueRedisPool"]) @ConditionalOnProperty( value = ["redis.cluster-enabled"], havingValue = "false", matchIfMissing = true ) fun queueRedisPool( @Value("\${redis.connection:redis://localhost:6379}") connection: String, @Value("\${redis.timeout:2000}") timeout: Int, redisPoolConfig: GenericObjectPoolConfig<Any> ) = URI.create(connection).let { cx -> val port = if (cx.port == -1) Protocol.DEFAULT_PORT else cx.port val db = if (cx.path.isNullOrEmpty()) { Protocol.DEFAULT_DATABASE } else { cx.path.substringAfter("/").toInt() } val password = cx.userInfo?.substringAfter(":") val isSSL = cx.scheme == "rediss" JedisPool(redisPoolConfig, cx.host, port, timeout, password, db, isSSL) } @Bean @ConditionalOnMissingBean(name = ["queue"]) @ConditionalOnProperty( value = ["redis.cluster-enabled"], havingValue = "false", matchIfMissing = true ) fun queue( @Qualifier("queueRedisPool") redisPool: Pool<Jedis>, redisQueueProperties: RedisQueueProperties, clock: Clock, deadMessageHandler: RedisDeadMessageHandler, publisher: EventPublisher, redisQueueObjectMapper: ObjectMapper, serializationMigrator: Optional<SerializationMigrator> ) = RedisQueue( queueName = redisQueueProperties.queueName, pool = redisPool, clock = clock, mapper = redisQueueObjectMapper, deadMessageHandlers = listOf(deadMessageHandler), publisher = publisher, ackTimeout = Duration.ofSeconds(redisQueueProperties.ackTimeoutSeconds.toLong()), serializationMigrator = serializationMigrator ) @Bean @ConditionalOnMissingBean(name = ["redisDeadMessageHandler"]) @ConditionalOnProperty( value = ["redis.cluster-enabled"], havingValue = "false", matchIfMissing = true ) fun redisDeadMessageHandler( @Qualifier("queueRedisPool") redisPool: Pool<Jedis>, redisQueueProperties: RedisQueueProperties, clock: Clock ) = RedisDeadMessageHandler( deadLetterQueueName = redisQueueProperties.deadLetterQueueName, pool = redisPool, clock = clock ) @Bean @ConditionalOnMissingBean(name = ["queueRedisCluster"]) @ConditionalOnProperty(value = ["redis.cluster-enabled"]) fun queueRedisCluster( @Value("\${redis.connection:redis://localhost:6379}") connection: String, @Value("\${redis.timeout:2000}") timeout: Int, @Value("\${redis.maxattempts:4}") maxAttempts: Int, redisPoolConfig: GenericObjectPoolConfig<Any> ): JedisCluster { URI.create(connection).let { cx -> val port = if (cx.port == -1) Protocol.DEFAULT_PORT else cx.port val password = cx.userInfo?.substringAfter(":") return JedisCluster( HostAndPort(cx.host, port), timeout, timeout, maxAttempts, password, redisPoolConfig ) } } @Bean @ConditionalOnMissingBean(name = ["queue", "clusterQueue"]) @ConditionalOnProperty(value = ["redis.cluster-enabled"]) fun clusterQueue( @Qualifier("queueRedisCluster") cluster: JedisCluster, redisQueueProperties: RedisQueueProperties, clock: Clock, deadMessageHandler: RedisClusterDeadMessageHandler, publisher: EventPublisher, redisQueueObjectMapper: ObjectMapper, serializationMigrator: Optional<SerializationMigrator> ) = RedisClusterQueue( queueName = redisQueueProperties.queueName, jedisCluster = cluster, clock = clock, mapper = redisQueueObjectMapper, deadMessageHandlers = listOf(deadMessageHandler), publisher = publisher, ackTimeout = Duration.ofSeconds(redisQueueProperties.ackTimeoutSeconds.toLong()), serializationMigrator = serializationMigrator ) @Bean @ConditionalOnMissingBean(name = ["redisClusterDeadMessageHandler"]) @ConditionalOnProperty(value = ["redis.cluster-enabled"]) fun redisClusterDeadMessageHandler( @Qualifier("queueRedisCluster") cluster: JedisCluster, redisQueueProperties: RedisQueueProperties, clock: Clock ) = RedisClusterDeadMessageHandler( deadLetterQueueName = redisQueueProperties.deadLetterQueueName, jedisCluster = cluster, clock = clock ) @Bean @ConditionalOnMissingBean fun redisQueueObjectMapper(properties: Optional<ObjectMapperSubtypeProperties>): ObjectMapper = ObjectMapper().apply { registerModule(KotlinModule()) disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) SpringObjectMapperConfigurer( properties.orElse(ObjectMapperSubtypeProperties()) ).registerSubtypes(this) } }
apache-2.0
e9b2dea6dcbab6e9412203f0b6c26b0a
33.803922
97
0.74493
4.965035
false
true
false
false
inorichi/tachiyomi-extensions
src/id/mangaku/src/eu/kanade/tachiyomi/extension/id/mangaku/Mangaku.kt
1
6467
package eu.kanade.tachiyomi.extension.id.mangaku import android.annotation.SuppressLint import eu.kanade.tachiyomi.network.GET import eu.kanade.tachiyomi.source.model.FilterList import eu.kanade.tachiyomi.source.model.MangasPage import eu.kanade.tachiyomi.source.model.Page import eu.kanade.tachiyomi.source.model.SChapter import eu.kanade.tachiyomi.source.model.SManga import eu.kanade.tachiyomi.source.online.ParsedHttpSource import eu.kanade.tachiyomi.util.asJsoup import okhttp3.Headers import okhttp3.Request import okhttp3.Response import org.jsoup.nodes.Document import org.jsoup.nodes.Element class Mangaku : ParsedHttpSource() { override val name = "Mangaku" override val baseUrl = "https://mangaku.in/" override val lang = "id" override val supportsLatest = true private var searchQuery = "" override fun popularMangaRequest(page: Int): Request { return GET(baseUrl + "daftar-komik-bahasa-indonesia/", headers) } override fun latestUpdatesRequest(page: Int): Request { return GET(baseUrl, headers) } override fun searchMangaRequest(page: Int, query: String, filters: FilterList): Request { searchQuery = query return GET(baseUrl + "daftar-komik-bahasa-indonesia/", headers) } override fun popularMangaSelector() = "a.screenshot" override fun latestUpdatesSelector() = "div.kiri_anime div.utao" override fun searchMangaSelector() = popularMangaSelector() override fun popularMangaFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.attr("rel") manga.url = element.attr("href") manga.title = element.text() return manga } override fun latestUpdatesFromElement(element: Element): SManga { val manga = SManga.create() manga.thumbnail_url = element.select("div.uta div.imgu img").attr("src") val mangaUrl = element.select("div.uta div.luf a.series").attr("href").replace("hhtps", "http") manga.url = mangaUrl.replace("hhtps", "https") manga.title = element.select("div.uta div.luf a.series").text() return manga } override fun searchMangaFromElement(element: Element) = popularMangaFromElement(element) override fun mangaDetailsRequest(manga: SManga): Request { return GET(manga.url, headers) } @SuppressLint("DefaultLocale") override fun mangaDetailsParse(document: Document): SManga { val infoString = document.select("#abc > p > span > small").html().toString().split("<br> ") val manga = SManga.create() infoString.forEach { if (it.contains("</b>")) { val info = it.split("</b>") val key = info[0].replace(":", "").replace("<b>", "").trim().toLowerCase() val value = info[1].replace(":", "").trim() when (key) { "genre" -> manga.genre = value.replace("–", ", ").replace("-", ", ").trim() "author" -> manga.author = value "artist" -> manga.artist = value "sinopsis" -> manga.description = value } } } manga.status = SManga.UNKNOWN manga.thumbnail_url = document.select("#abc > div > span > small > a > img").attr("src") return manga } override fun chapterListRequest(manga: SManga): Request { return GET(manga.url, headers) } override fun chapterListSelector() = "div.entry > div > table > tbody > tr > td:nth-child(1) > small > div:nth-child(2) > a" override fun chapterFromElement(element: Element): SChapter { val chapter = SChapter.create() val chapterUrl = element.attr("href") chapter.url = chapterUrl chapter.name = element.text() if (chapter.name.contains("–")) chapter.name = chapter.name.split("–")[1].trim() return chapter } override fun prepareNewChapter(chapter: SChapter, manga: SManga) { val basic = Regex("""Chapter\s([0-9]+)""") when { basic.containsMatchIn(chapter.name) -> { basic.find(chapter.name)?.let { chapter.chapter_number = it.groups[1]?.value!!.toFloat() } } } } override fun pageListRequest(chapter: SChapter): Request { return GET(chapter.url, headers) } override fun pageListParse(document: Document): List<Page> { var pageList = document.select("div.entry img") if (pageList.isEmpty()) { pageList = document.select("div.entry-content img") } val pages = mutableListOf<Page>() var i = 0 pageList.forEach { element -> val imageUrl = element.attr("src") i++ if (imageUrl.isNotEmpty()) { pages.add(Page(i, "", imageUrl)) } } return pages } override fun imageUrlParse(document: Document) = "" override fun imageRequest(page: Page): Request { var mainUrl = baseUrl var imageUrl = page.imageUrl.toString() if (imageUrl.contains("mangaku.co")) { mainUrl = "https://mangaku.co" } if (imageUrl.startsWith("//")) { imageUrl = "https:$imageUrl" } else if (imageUrl.startsWith("/")) { imageUrl = mainUrl + imageUrl } val imgHeader = Headers.Builder().apply { add("user-agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36") add("referer", mainUrl) }.build() return GET(imageUrl, imgHeader) } override fun popularMangaNextPageSelector() = "next" override fun latestUpdatesNextPageSelector() = popularMangaNextPageSelector() override fun searchMangaNextPageSelector() = popularMangaNextPageSelector() @SuppressLint("DefaultLocale") override fun searchMangaParse(response: Response): MangasPage { val document = response.asJsoup() val mangas = arrayListOf<SManga>() document.select(searchMangaSelector()).forEach { element -> val manga = popularMangaFromElement(element) if (manga.title.toLowerCase().contains(searchQuery.toLowerCase())) { mangas.add(manga) } } return MangasPage(mangas, false) } }
apache-2.0
b9b56e1b5c0290e2569b4dae27529f54
36.563953
154
0.617397
4.449725
false
false
false
false
CoderLine/alphaTab
src.kotlin/alphaTab/alphaTab/src/commonMain/kotlin/alphaTab/collections/ObjectDoubleMap.kt
1
4049
package alphaTab.collections public open class ObjectDoubleMapEntry<TKey> { private var _key: TKey public var key: TKey get() = _key internal set(value) { _key = value } private var _value: Double public var value: Double get() = _value internal set(value) { _value = value } @Suppress("UNCHECKED_CAST") public constructor() { _key = null as TKey _value = 0.0 } public constructor(key: TKey, value: Double) { _key = key _value = value } } public class ObjectDoubleMapEntryInternal<TKey> : ObjectDoubleMapEntry<TKey>(), IMapEntryInternal { public override var hashCode: Int = 0 public override var next: Int = 0 @Suppress("UNCHECKED_CAST") override fun reset() { key = null as TKey value = 0.0 } } public class ObjectDoubleMap<TKey> : MapBase<ObjectDoubleMapEntry<TKey>, ObjectDoubleMapEntryInternal<TKey>> { public constructor() public constructor(iterable: Iterable<ObjectDoubleMapEntry<TKey>>) { for (it in iterable) { set(it.key, it.value) } } @Suppress("UNCHECKED_CAST") public fun has(key: TKey): Boolean { return findEntryInternal(key as Any, { entry, k -> entry.key == (k as TKey) }) >= 0 } @Suppress("UNCHECKED_CAST") public fun get(key: TKey): Double { val i = findEntryInternal(key as Any, { entry, k -> entry.key == (k as TKey) }) if (i >= 0) { return entries[i].value } throw KeyNotFoundException() } public fun set(key: TKey, value: Double) { insert(key, value) } @Suppress("UNCHECKED_CAST") private fun insert(key: TKey, value: Double) { insertInternal( key as Any, value, { entry, k -> entry.key = k as TKey }, { entry, v -> entry.value = v }, { entry, k -> entry.key == (k as TKey) } ) } public fun delete(key: TKey) { deleteInternal(key.hashCode()) } private var _values: ValueCollection<TKey>? = null public fun values(): IDoubleIterable { _values = _values ?: ValueCollection(this) return _values!! } private var _keys: KeyCollection<TKey>? = null public fun keys(): Iterable<TKey> { _keys = _keys ?: KeyCollection(this) return _keys!! } override fun createEntries(size: Int): Array<ObjectDoubleMapEntryInternal<TKey>> { return Array(size) { ObjectDoubleMapEntryInternal() } } override fun createEntries( size: Int, old: Array<ObjectDoubleMapEntryInternal<TKey>> ): Array<ObjectDoubleMapEntryInternal<TKey>> { return Array(size) { if (it < old.size) old[it] else ObjectDoubleMapEntryInternal() } } private class ValueCollection<TKey>(private val map: ObjectDoubleMap<TKey>) : IDoubleIterable { override fun iterator(): DoubleIterator { return ValueIterator(map.iterator()) } private class ValueIterator<TKey>(private val iterator: Iterator<ObjectDoubleMapEntry<TKey>>) : DoubleIterator() { override fun hasNext(): Boolean { return iterator.hasNext() } override fun nextDouble(): Double { return iterator.next().value } } } private class KeyCollection<TKey>(private val map: ObjectDoubleMap<TKey>) : Iterable<TKey> { override fun iterator(): Iterator<TKey> { return KeyIterator(map.iterator()) } private class KeyIterator<TKey>(private val iterator: Iterator<ObjectDoubleMapEntry<TKey>>) : Iterator<TKey> { override fun hasNext(): Boolean { return iterator.hasNext() } override fun next(): TKey { return iterator.next().key } } } }
mpl-2.0
2e3a559a245eeb92fb0a5613785adede
26.544218
103
0.569523
4.401087
false
false
false
false
xdtianyu/CallerInfo
app/src/main/java/org/xdty/callerinfo/model/database/DatabaseImpl.kt
1
11261
package org.xdty.callerinfo.model.database import android.annotation.SuppressLint import android.util.Log import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.schedulers.Schedulers import io.requery.Persistable import io.requery.sql.EntityDataStore import org.xdty.callerinfo.application.Application.Companion.appComponent import org.xdty.callerinfo.model.db.Caller import org.xdty.callerinfo.model.db.InCall import org.xdty.callerinfo.model.db.MarkedRecord import org.xdty.callerinfo.utils.Utils import org.xdty.phone.number.model.INumber import org.xdty.phone.number.model.Type import javax.inject.Inject @SuppressLint("CheckResult") class DatabaseImpl private constructor() : Database { @Inject internal lateinit var mDataStore: EntityDataStore<Persistable> init { appComponent.inject(this) } override fun fetchInCalls(): Observable<List<InCall>> { return Observable.fromCallable { mDataStore.select(InCall::class.java) .orderBy(InCall.TIME.desc()) .get() .toList() }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun fetchCallers(): Observable<List<Caller>> { return Observable.fromCallable { mDataStore.select(Caller::class.java).get().toList() } .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun clearAllInCalls(): Observable<Int> { return Observable.fromCallable { mDataStore.delete(InCall::class.java).get().value() } .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun clearAllInCallSync() { mDataStore.delete(InCall::class.java).get().value() } override fun removeInCall(inCall: InCall) { Observable.just(inCall).observeOn(Schedulers.io()).subscribe { try { mDataStore.delete(it) } catch (e: Exception) { e.printStackTrace() } } } override fun findCaller(number: String): Observable<Caller> { return Observable.fromCallable<Caller> { val callers = mDataStore.select(Caller::class.java) .where(Caller.NUMBER.eq(number)) .get() .toList() var caller: Caller? = null if (callers.size > 0) { caller = callers[0] } caller }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun findCallerSync(number: String): Caller? { val callers = mDataStore.select(Caller::class.java) .where(Caller.NUMBER.eq(number)) .get() .toList() var caller: Caller? = null if (callers.size > 0) { caller = callers[0] } return caller } override fun removeCaller(caller: Caller) { Observable.just(caller).observeOn(Schedulers.io()).subscribe { mDataStore.delete(it) } } override fun clearAllCallerSync(): Int { return mDataStore.delete(Caller::class.java).get().value() } override fun updateCaller(caller: Caller) { Observable.just(caller).observeOn(Schedulers.io()).subscribe { val c = mDataStore.select(Caller::class.java).where( Caller.NUMBER.eq(it.number)).get().firstOr(it) if (c !== it) { c.callerSource = it.callerSource c.callerType = it.callerType c.city = it.city c.name = it.name c.name = it.name c.setType(it.type.text) c.count = it.count c.province = it.province c.operators = it.operators c.lastUpdate = it.lastUpdate } mDataStore.upsert(c) } } override fun saveInCall(inCall: InCall) { Observable.just(inCall).observeOn(Schedulers.io()).subscribe { mDataStore.insert(it) } } override fun saveMarked(markedRecord: MarkedRecord) { updateMarked(markedRecord) } override fun updateMarked(markedRecord: MarkedRecord) { Observable.just(markedRecord) .observeOn(Schedulers.io()) .subscribe { val record = mDataStore.select(MarkedRecord::class.java) .where(MarkedRecord.NUMBER.eq(it.number)) .get() .firstOr(it) if (record !== it) { record.count = it.count record.isReported = false record.source = it.source record.time = it.time record.type = it.type record.typeName = it.typeName } mDataStore.upsert(record) } } override fun updateCaller(markedRecord: MarkedRecord) { Observable.just(markedRecord) .observeOn(Schedulers.io()) .subscribe { val caller = mDataStore.select(Caller::class.java) .where( Caller.NUMBER.eq(it.number)) .get() .firstOr(Caller()) caller.number = it.number caller.name = it.typeName caller.lastUpdate = it.time caller.setType("report") caller.isOffline = false mDataStore.upsert(caller) } } override fun fetchMarkedRecords(): Observable<List<MarkedRecord>> { return Observable.fromCallable { mDataStore.select(MarkedRecord::class.java).get().toList() } .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun findMarkedRecord(number: String): Observable<MarkedRecord> { return Observable.fromCallable<MarkedRecord> { val records = mDataStore.select(MarkedRecord::class.java) .where(MarkedRecord.NUMBER.eq(number)) .get() .toList() var record: MarkedRecord? = null if (records.size > 0) { record = records[0] } record }.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()) } override fun updateMarkedRecord(number: String) { Observable.just(number) .observeOn(Schedulers.io()) .subscribe { val records = mDataStore.select(MarkedRecord::class.java) .where(MarkedRecord.NUMBER.eq(it)) .get() .toList() var record: MarkedRecord? = null if (records.size > 0) { record = records[0] record.isReported = true mDataStore.update(record!!) } if (records.size > 1) { Log.e("DatabaseImpl", "updateMarkedRecord duplicate number: $it") } } } override fun fetchCallersSync(): List<Caller> { return mDataStore.select(Caller::class.java).get().toList() } override fun fetchInCallsSync(): List<InCall> { return mDataStore.select(InCall::class.java).orderBy(InCall.TIME.desc()).get().toList() } override fun fetchMarkedRecordsSync(): List<MarkedRecord> { return mDataStore.select(MarkedRecord::class.java).get().toList() } override fun addCallers(callers: List<Caller>) { Observable.fromIterable(callers) .observeOn(Schedulers.io()) .subscribeOn(Schedulers.io()) .flatMap { caller -> Observable.just(caller) } .subscribe { caller -> mDataStore.upsert(caller) } } override fun addInCallers(inCalls: List<InCall>) { Observable.fromIterable(inCalls) .observeOn(Schedulers.io()) .subscribeOn(Schedulers.io()) .flatMap { inCall -> Observable.just(inCall) } .subscribe { inCall -> mDataStore.insert(inCall) } } override fun addMarkedRecords(markedRecords: List<MarkedRecord>) { Observable.fromIterable(markedRecords) .observeOn(Schedulers.io()) .subscribeOn(Schedulers.io()) .flatMap { record -> Observable.just(record) } .subscribe { markedRecord -> val record = mDataStore.select(MarkedRecord::class.java) .where(MarkedRecord.NUMBER.eq(markedRecord.number)) .get() .firstOr(markedRecord) if (record !== markedRecord) { record.count = markedRecord.count record.isReported = false record.source = markedRecord.source record.time = markedRecord.time record.type = markedRecord.type record.typeName = markedRecord.typeName } mDataStore.upsert(record) } } override fun clearAllMarkedRecordSync() { mDataStore.delete(MarkedRecord::class.java).get().value() } override fun getInCallCount(number: String): Int { val time = System.currentTimeMillis() - 24 * 60 * 60 * 1000 return mDataStore.count(InCall::class.java) .where(InCall.NUMBER.eq(number)) .and(InCall.TIME.gt(time)) .get() .value() } override fun addInCallersSync(inCalls: List<InCall>) { for (inCall in inCalls) { mDataStore.insert(inCall) } } override fun saveMarkedRecord(number: INumber, uid: String) { if (number.type == Type.REPORT) { findMarkedRecord(number.number).subscribe { record -> if (record == null) { val type = Utils.typeFromString(number.name) if (type >= 0) { val markedRecord = MarkedRecord() markedRecord.number = number.number markedRecord.uid = uid markedRecord.source = number.apiId markedRecord.type = type markedRecord.count = number.count markedRecord.typeName = number.name saveMarked(markedRecord) } } } } } override fun removeRecord(record: MarkedRecord) { Observable.just(record).observeOn(Schedulers.io()).subscribe { mDataStore.delete(it) removeCaller(findCallerSync(it.number)!!) } } companion object { val instance = DatabaseImpl() } }
gpl-3.0
f5cb690aaddbe7fd5646c9945422f4dd
36.54
101
0.544623
4.893959
false
false
false
false
PoweRGbg/AndroidAPS
app/src/main/java/info/nightscout/androidaps/activities/ErrorHelperActivity.kt
3
946
package info.nightscout.androidaps.activities import android.os.Bundle import info.nightscout.androidaps.R import info.nightscout.androidaps.dialogs.ErrorDialog import info.nightscout.androidaps.plugins.general.nsclient.NSUpload import info.nightscout.androidaps.utils.SP class ErrorHelperActivity : DialogAppCompatActivity() { @Override override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val errorDialog = ErrorDialog() errorDialog.helperActivity = this errorDialog.status = intent.getStringExtra("status") errorDialog.sound = intent.getIntExtra("soundid", R.raw.error) errorDialog.title = intent.getStringExtra("title") errorDialog.show(supportFragmentManager, "Error") if (SP.getBoolean(R.string.key_ns_create_announcements_from_errors, true)) { NSUpload.uploadError(intent.getStringExtra("status")) } } }
agpl-3.0
1f1d431c0637fcf19aaddd4a8437b64a
36.84
84
0.739958
4.706468
false
false
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/view/course_content/ui/adapter/delegates/control_bar/CourseContentControlBarDelegate.kt
2
7658
package org.stepik.android.view.course_content.ui.adapter.delegates.control_bar import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import androidx.appcompat.widget.PopupMenu import androidx.collection.LongSparseArray import androidx.swiperefreshlayout.widget.CircularProgressDrawable import kotlinx.android.synthetic.main.view_course_content_control_bar.view.* import org.stepic.droid.R import org.stepic.droid.persistence.model.DownloadProgress import org.stepic.droid.ui.util.setHeight import org.stepic.droid.util.TextUtil import org.stepik.android.presentation.personal_deadlines.model.PersonalDeadlinesState import org.stepik.android.view.course_content.model.CourseContentItem import ru.nobird.android.ui.adapterdelegates.AdapterDelegate import ru.nobird.android.ui.adapterdelegates.DelegateViewHolder class CourseContentControlBarDelegate( private val controlBarClickListener: CourseContentControlBarClickListener, private val courseDownloadStatuses: LongSparseArray<DownloadProgress.Status> ) : AdapterDelegate<CourseContentItem, DelegateViewHolder<CourseContentItem>>() { companion object { private const val SMALLEST_FORMAT_UNIT = 1024 * 1024L // 1 mb } override fun onCreateViewHolder(parent: ViewGroup): ViewHolder = ViewHolder(createView(parent, R.layout.view_course_content_control_bar)) override fun isForViewType(position: Int, data: CourseContentItem): Boolean = data is CourseContentItem.ControlBar inner class ViewHolder(root: View) : DelegateViewHolder<CourseContentItem>(root) { private val controlBar = root.controlBar private lateinit var status: DownloadProgress.Status private lateinit var downloadControl: View private lateinit var downloadDrawable: ImageView private lateinit var downloadText: TextView private val progressDrawable = CircularProgressDrawable(context).apply { strokeWidth = 5f centerRadius = 20f setColorSchemeColors(0x535366) start() } private val controlBarHeight: Int init { controlBar.onClickListener = { id -> val data = (itemData as? CourseContentItem.ControlBar) if (data == null) { false } else { when (id) { R.id.course_control_schedule -> handleScheduleClick(data) R.id.course_control_download_all -> { if (data.course != null) { when (status) { is DownloadProgress.Status.NotCached -> controlBarClickListener.onDownloadAllClicked(data.course) is DownloadProgress.Status.Cached -> controlBarClickListener.onRemoveAllClicked(data.course) } } } } true } } val attrs = context.theme.obtainStyledAttributes(intArrayOf(android.R.attr.actionBarSize)) try { controlBarHeight = attrs.getDimension(0, 0F).toInt() } finally { attrs.recycle() } } override fun onBind(data: CourseContentItem) { data as CourseContentItem.ControlBar val isScheduleVisible = with(data.personalDeadlinesState) { this is PersonalDeadlinesState.EmptyDeadlines || this is PersonalDeadlinesState.Deadlines } || data.hasDates controlBar.changeItemVisibility(R.id.course_control_schedule, isScheduleVisible) controlBar.changeItemVisibility(R.id.course_control_download_all, data.course != null) controlBar.setHeight(if (data.isEnabled) controlBarHeight else 0) downloadControl = controlBar.findViewById<View>(R.id.course_control_download_all) downloadDrawable = downloadControl.findViewById(android.R.id.icon) downloadText = downloadControl.findViewById(android.R.id.text1) if (data.course != null) { status = courseDownloadStatuses[data.course.id] ?: DownloadProgress.Status.Pending downloadControl.isEnabled = status is DownloadProgress.Status.Cached || status is DownloadProgress.Status.NotCached when (status) { is DownloadProgress.Status.InProgress, DownloadProgress.Status.Pending -> { downloadText.text = context.resources.getString(R.string.course_control_processing) downloadDrawable.setImageDrawable(progressDrawable) } is DownloadProgress.Status.Cached -> { downloadText.text = TextUtil.formatBytes((status as DownloadProgress.Status.Cached).bytesTotal, SMALLEST_FORMAT_UNIT) downloadDrawable.setImageResource(R.drawable.ic_download_remove) } is DownloadProgress.Status.NotCached -> { downloadText.text = context.resources.getString(R.string.course_control_download_all) downloadDrawable.setImageResource(R.drawable.ic_download) } } } } private fun handleScheduleClick(data: CourseContentItem.ControlBar) { when (data.personalDeadlinesState) { PersonalDeadlinesState.EmptyDeadlines -> controlBarClickListener.onCreateScheduleClicked() is PersonalDeadlinesState.Deadlines -> { val record = data.personalDeadlinesState.record val anchorView = controlBar.findViewById<View>(R.id.course_control_schedule) val popupMenu = PopupMenu(context, anchorView) popupMenu.inflate(R.menu.course_content_control_bar_schedule_menu) popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.menu_item_deadlines_edit -> controlBarClickListener.onChangeScheduleClicked(record) R.id.menu_item_deadlines_remove -> controlBarClickListener.onRemoveScheduleClicked(record) R.id.menu_item_deadlines_sync -> controlBarClickListener.onExportScheduleClicked() } true } popupMenu.show() } is PersonalDeadlinesState.NoDeadlinesNeeded -> { val anchorView = controlBar.findViewById<View>(R.id.course_control_schedule) val popupMenu = PopupMenu(context, anchorView) popupMenu.inflate(R.menu.course_content_control_bar_schedule_menu_no_personal) popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.menu_item_deadlines_sync -> controlBarClickListener.onExportScheduleClicked() } true } popupMenu.show() } } } } }
apache-2.0
52e921b02ffdceab95565d7ae43049b7
45.98773
141
0.594542
5.533237
false
false
false
false
Bios-Marcel/ServerBrowser
src/main/kotlin/com/msc/serverbrowser/gui/components/SampServerTable.kt
1
12906
package com.msc.serverbrowser.gui.components import com.msc.serverbrowser.Client import com.msc.serverbrowser.data.FavouritesController import com.msc.serverbrowser.data.entites.SampServer import com.msc.serverbrowser.data.properties.ClientPropertiesController import com.msc.serverbrowser.data.properties.ConnectOnDoubleClickProperty import com.msc.serverbrowser.getWindow import com.msc.serverbrowser.util.samp.GTAController import com.msc.serverbrowser.util.windows.OSUtility import javafx.beans.property.ObjectProperty import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.collections.transformation.FilteredList import javafx.collections.transformation.SortedList import javafx.scene.control.* import javafx.scene.control.Alert.AlertType import javafx.scene.input.* import javafx.scene.text.Text import java.util.Optional import java.util.StringJoiner import java.util.function.Predicate import java.util.stream.Collectors import kotlin.collections.ArrayList import kotlin.collections.set /** * [TableView] that was made for the ServerList View, contains a special TableRowFactory and * allows filtering and sorting. * * @author Marcel * @since 23.09.2017 */ class SampServerTable(val client: Client) : TableView<SampServer>() { /** * @return [.tableMode] */ var tableMode = SampServerTableMode.FAVOURITES private set private val connectMenuItem = MenuItem(Client.getString("connectToServer")) private val connectWithPasswordMenuItem = MenuItem(Client.getString("connectToServerUsingPassword")) private val connectSeparator = SeparatorMenuItem() private val addToFavouritesMenuItem = MenuItem(Client.getString("addToFavourites")) private val removeFromFavouritesMenuItem = MenuItem(Client.getString("removeFromFavourites")) private val copyIpAddressAndPortMenuItem = MenuItem(Client.getString("copyIpAddressAndPort")) private val visitWebsiteMenuItem = MenuItem(Client.getString("visitWebsite")) private val tableContextMenu = ContextMenu(connectMenuItem, connectWithPasswordMenuItem, connectSeparator, addToFavouritesMenuItem, removeFromFavouritesMenuItem, copyIpAddressAndPortMenuItem, visitWebsiteMenuItem) /** * @return the [ObservableList] list that contains all data and is mutable */ val servers: ObservableList<SampServer> = FXCollections.observableArrayList<SampServer>() private val filteredServers = FilteredList(servers) private val sortedServers = SortedList(filteredServers) private val firstIfAnythingSelected: Optional<SampServer> get() { val selectedServers = selectionModel.selectedItems return if (selectedServers.isEmpty()) { Optional.empty() } else Optional.ofNullable(selectedServers[0]) } /** * Constructor; sets the TableRowFactory, the ContextMenu Actions and table settings. */ init { items = sortedServers selectionModel.selectionMode = SelectionMode.MULTIPLE setKeyActions() initTableRowFactory() setMenuItemDefaultActions() } private fun setKeyActions() { setOnKeyReleased { released -> if (tableMode == SampServerTableMode.FAVOURITES && released.code == KeyCode.DELETE) { deleteSelectedFavourites() } } } private fun setMenuItemDefaultActions() { connectMenuItem.setOnAction { _ -> firstIfAnythingSelected.ifPresent { server -> GTAController.tryToConnect(client, server.address, server.port, "") } } visitWebsiteMenuItem.setOnAction { _ -> firstIfAnythingSelected.ifPresent { server -> OSUtility.browse(server.website) } } connectWithPasswordMenuItem.setOnAction { _ -> GTAController.promptUserForServerPassword(client) .ifPresent { serverPassword -> firstIfAnythingSelected.ifPresent { server -> GTAController.tryToConnect(client, server.address, server.port, serverPassword) } } } addToFavouritesMenuItem.setOnAction { _ -> val serverList = selectionModel.selectedItems serverList.forEach { FavouritesController.addServerToFavourites(it) } } removeFromFavouritesMenuItem.setOnAction { _ -> deleteSelectedFavourites() } copyIpAddressAndPortMenuItem.setOnAction { _ -> val serverOptional = firstIfAnythingSelected serverOptional.ifPresent { server -> val content = ClipboardContent() content.putString(server.address + ":" + server.port) Clipboard.getSystemClipboard().setContent(content) } } } private fun deleteSelectedFavourites() { val alert = Alert(AlertType.CONFIRMATION, Client.getString("sureYouWantToDeleteFavourites"), ButtonType.YES, ButtonType.NO) alert.initOwner(getWindow()) alert.title = Client.getString("deleteFavourites") val result = alert.showAndWait() result.ifPresent { buttonType -> if (buttonType == ButtonType.YES) { val serverList = selectionModel.selectedItems serverList.forEach { FavouritesController.removeServerFromFavourites(it) } servers.removeAll(serverList) } } } private fun initTableRowFactory() { setRowFactory { _ -> val row = TableRow<SampServer>() row.setOnDragOver { event -> event.acceptTransferModes(TransferMode.MOVE) } row.setOnDragEntered { _ -> row.styleClass.add("overline") } row.setOnDragExited { _ -> row.styleClass.remove("overline") } row.setOnDragDetected { event -> onRowDragDetected(row, event) } row.setOnDragDropped { event -> onRowDragDropped(row, event) } row.setOnMouseClicked { clicked -> // A row has been clicked, so we want to hide the previous context menu tableContextMenu.hide() if (row.item != null) { // If there is an item in this row, we want to proceed further handleClick(row, clicked) } else { // Otherwise we clear the selection. selectionModel.clearSelection() } } row } } private fun onRowDragDropped(row: TableRow<SampServer>, event: DragEvent) { val dragBoard = event.dragboard val oldIndexes = dragBoard.getContent(OLD_INDEXES_LIST_DATA_FORMAT) as MutableList<Int> val newIndex = servers.indexOf(row.item) val newIndexCorrect = if (newIndex == -1) servers.size else newIndex if (oldIndexes.contains(newIndexCorrect)) { return } val firstOfOldIndexes = oldIndexes[0] if (newIndexCorrect != firstOfOldIndexes) { val draggedServer = ArrayList(selectionModel.selectedItems) val reverseAndAdd = { draggedServer.reverse() draggedServer.forEach { server -> servers.add(newIndexCorrect, server) } } val sortReverseAndRemove = { oldIndexes.sort() oldIndexes.reverse() oldIndexes.forEach { index -> servers.removeAt(index) } } if (oldIndexes[0] < newIndexCorrect) { reverseAndAdd() sortReverseAndRemove() } else { sortReverseAndRemove() reverseAndAdd() } } } private fun onRowDragDetected(row: TableRow<SampServer>, event: MouseEvent) { val selectedServers = selectionModel.selectedItems val rowServer = row.item if (servers.size <= 1 || selectedServers.isEmpty() || !selectedServers.contains(rowServer)) { return } val clipboardContent = ClipboardContent() val selectedServerIndices = selectionModel.selectedItems.stream() .map<Int> { servers.indexOf(it) } .collect(Collectors.toList()) clipboardContent[OLD_INDEXES_LIST_DATA_FORMAT] = selectedServerIndices val ghostString = StringJoiner(System.lineSeparator()) selectedServers.forEach { server -> ghostString.add(server.hostname + " - " + server.toString()) } val dragBoard = startDragAndDrop(TransferMode.MOVE) dragBoard.setDragView(Text(ghostString.toString()).snapshot(null, null), event.x, event.y) dragBoard.setContent(clipboardContent) } private fun handleClick(row: TableRow<SampServer>, clicked: MouseEvent) { if (clicked.button == MouseButton.PRIMARY) { handleLeftClick(row) } else if (clicked.button == MouseButton.SECONDARY) { handleRightClick(row, clicked) } } private fun handleRightClick(row: TableRow<SampServer>, clicked: MouseEvent) { val selectedServers = selectionModel.selectedItems if (selectionModel.selectedIndices.contains(row.index)) { // In case the current selection model contains the clicked row, we want to open the // context menu on the current selection mode displayMenu(selectedServers, clicked.screenX, clicked.screenY) } else { // Otherwise we will select the clicked item and open the context menu on it displayMenu(listOf<SampServer>(row.item), clicked.screenX, clicked.screenY) } } private fun handleLeftClick(row: TableRow<SampServer>) { val lastLeftClickTime = row.userData as Long? val wasDoubleClick = lastLeftClickTime != null && System.currentTimeMillis() - lastLeftClickTime < 300 val onlyOneSelectedItem = selectionModel.selectedItems.size == 1 if (wasDoubleClick && onlyOneSelectedItem) { if (ClientPropertiesController.getProperty(ConnectOnDoubleClickProperty)) { firstIfAnythingSelected.ifPresent { server -> GTAController.tryToConnect(client, server.address, server.port, "") } } } else { row.setUserData(java.lang.Long.valueOf(System.currentTimeMillis())) } } /** * Displays the context menu for server entries. * * @param serverList The list of servers that the context menu actions will affect * @param posX X coordinate * @param posY Y coordinate */ private fun displayMenu(serverList: List<SampServer>, posX: Double, posY: Double) { val sizeEqualsOne = serverList.size == 1 connectMenuItem.isVisible = sizeEqualsOne tableContextMenu.items[1].isVisible = sizeEqualsOne // Separator copyIpAddressAndPortMenuItem.isVisible = sizeEqualsOne visitWebsiteMenuItem.isVisible = sizeEqualsOne connectSeparator.isVisible = sizeEqualsOne val favouriteMode = tableMode == SampServerTableMode.FAVOURITES addToFavouritesMenuItem.isVisible = !favouriteMode removeFromFavouritesMenuItem.isVisible = favouriteMode tableContextMenu.show(this, posX, posY) } /** * Sets the mode, which decides how the table will behave. * * @param mode the mode that the [SampServerTable] will be used for. */ fun setServerTableMode(mode: SampServerTableMode) { tableMode = mode } /** * @return the comparator property that is used to sort the items */ fun sortedListComparatorProperty(): ObjectProperty<Comparator<in SampServer>> { return sortedServers.comparatorProperty() } /** * @return the predicate property that is used to filter the data */ fun predicateProperty(): ObjectProperty<Predicate<in SampServer>> { return filteredServers.predicateProperty() } /** * Returns true if this list contains the specified element * * @param server the server to search for * @return true if the data contains the server */ operator fun contains(server: SampServer): Boolean { return servers.contains(server) } /** * Deletes all currently contained servers. */ fun clear() { servers.clear() } /** * Adds a new [SampServer] to the data. * * @param newServer the server that will be added */ fun add(newServer: SampServer) { servers.add(newServer) } /** * Adds a collection of new [SampServer] to the data. * * @param newServers the servers that will be added */ fun addAll(newServers: Collection<SampServer>) { newServers.forEach { this.add(it) } } companion object { private val OLD_INDEXES_LIST_DATA_FORMAT = DataFormat("index") } }
mpl-2.0
777f27ff23bebb920b8428077acbb316
37.183432
217
0.658686
4.888636
false
false
false
false
grenzfrequence/showMyCar
app/src/main/java/com/grenzfrequence/showmycar/common/recycler_binding_adapter/RecyclerBindingAdapter.kt
1
3648
package com.grenzfrequence.showmycar.common.recycler_binding_adapter import android.support.annotation.LayoutRes import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View.* import android.view.ViewGroup import com.grenzfrequence.showmycar.car_types.ui.base.MvvmViewModelItem import java.util.* /** * Created by grenzfrequence on 19/03/17. */ class RecyclerBindingAdapter<ITEM, VIEWMODELITEM : MvvmViewModelItem<ITEM>>( @param:LayoutRes private val itemLayoutEven: Int, @param:LayoutRes private val itemLayoutOdd: Int, @param:LayoutRes private val progressBarLayout: Int, private val viewModelId: Int, private val createViewModel: () -> VIEWMODELITEM) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { companion object { private val TYPE_BINDING_VIEW_HOLDER_EVEN = 1 private val TYPE_BINDING_VIEW_HOLDER_ODD = 2 private val TYPE_PROGRESS_BAR_VIEW_HOLDER = 3 } private var listItems: List<ITEM> = ArrayList() private var showProgressBar = false init { setHasStableIds(true) } fun setListItems(listItems: List<ITEM>) { this.listItems = listItems showProgressBar = false notifyDataSetChanged() } fun showOnLoadMore(): Int { showProgressBar = true notifyDataSetChanged() return 0 } override fun getItemCount(): Int { return if (listItems.isEmpty()) 0 else listItems.size + 1 } override fun getItemViewType(position: Int): Int { return if (position != 0 && position == itemCount - 1) TYPE_PROGRESS_BAR_VIEW_HOLDER else if (position % 2 == 0) TYPE_BINDING_VIEW_HOLDER_ODD else TYPE_BINDING_VIEW_HOLDER_EVEN } override fun getItemId(position: Int): Long { return if (position != 0 && position == itemCount - 1) NO_ID.toLong() else listItems[position]?.hashCode()?.toLong() ?: NO_ID.toLong() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val layoutId = when (viewType) { TYPE_BINDING_VIEW_HOLDER_EVEN -> itemLayoutEven TYPE_BINDING_VIEW_HOLDER_ODD -> itemLayoutOdd else -> progressBarLayout } val view = LayoutInflater.from(parent.context).inflate(layoutId, parent, false) val viewHolder: RecyclerView.ViewHolder when (viewType) { TYPE_BINDING_VIEW_HOLDER_EVEN, TYPE_BINDING_VIEW_HOLDER_ODD -> viewHolder = BindingViewHolder(view, createViewModel(), viewModelId) TYPE_PROGRESS_BAR_VIEW_HOLDER -> viewHolder = ProgressBarViewHolder(view) else -> throw IllegalArgumentException("Invalid ViewType: " + viewType) } return viewHolder } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { if (holder is BindingViewHolder<*>) { val bindingViewHolder = holder as BindingViewHolder<VIEWMODELITEM> val modelData = listItems[position] bindingViewHolder.viewModel.modelData = modelData bindingViewHolder.executePendingBindings() } else if (holder is ProgressBarViewHolder) { val progressBarViewHolder = holder.progressBar if (showProgressBar) { progressBarViewHolder.isIndeterminate = true progressBarViewHolder.visibility = VISIBLE } else { progressBarViewHolder.visibility = GONE } } } }
mit
3d90560976c3105d2d7287df271f57ef
33.415094
96
0.650219
4.896644
false
false
false
false
da1z/intellij-community
platform/script-debugger/backend/src/debugger/values/ObjectValueBase.kt
6
3030
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.debugger.values import com.intellij.util.SmartList import org.jetbrains.concurrency.* import org.jetbrains.debugger.EvaluateContext import org.jetbrains.debugger.Variable import org.jetbrains.debugger.VariablesHost import java.util.* abstract class ObjectValueBase<VALUE_LOADER : ValueManager>(type: ValueType) : ValueBase(type), ObjectValue { protected abstract val childrenManager: VariablesHost<VALUE_LOADER> override val properties: Promise<List<Variable>> get() = childrenManager.get() internal abstract inner class MyObsolescentAsyncFunction<PARAM, RESULT>(private val obsolescent: Obsolescent) : ObsolescentFunction<PARAM, Promise<RESULT>> { override fun isObsolete() = obsolescent.isObsolete || childrenManager.valueManager.isObsolete } override fun getProperties(names: List<String>, evaluateContext: EvaluateContext, obsolescent: Obsolescent) = properties .thenAsync(object : MyObsolescentAsyncFunction<List<Variable>, List<Variable>>(obsolescent) { override fun `fun`(variables: List<Variable>) = getSpecifiedProperties(variables, names, evaluateContext) }) override val valueString: String? = null override fun getIndexedProperties(from: Int, to: Int, bucketThreshold: Int, consumer: IndexedVariablesConsumer, componentType: ValueType?): Promise<*> = rejectedPromise<Any?>() @Suppress("UNCHECKED_CAST") override val variablesHost: VariablesHost<ValueManager> get() = childrenManager as VariablesHost<ValueManager> } fun getSpecifiedProperties(variables: List<Variable>, names: List<String>, evaluateContext: EvaluateContext): Promise<List<Variable>> { val properties = SmartList<Variable>() var getterCount = 0 for (property in variables) { if (!property.isReadable || !names.contains(property.name)) { continue } if (!properties.isEmpty()) { Collections.sort(properties) { o1, o2 -> names.indexOf(o1.name) - names.indexOf(o2.name) } } properties.add(property) if (property.value == null) { getterCount++ } } if (getterCount == 0) { return resolvedPromise(properties) } else { val promises = SmartList<Promise<*>>() for (variable in properties) { if (variable.value == null) { val valueModifier = variable.valueModifier!! promises.add(valueModifier.evaluateGet(variable, evaluateContext)) } } return all(promises, properties) } }
apache-2.0
69ee0877147e7c3fd4c20caba98d928a
36.8875
178
0.738944
4.423358
false
false
false
false
esqr/WykopMobilny
app/src/main/kotlin/io/github/feelfreelinux/wykopmobilny/ui/adapters/EntryDetailAdapter.kt
1
1755
package io.github.feelfreelinux.wykopmobilny.ui.adapters import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.ViewGroup import io.github.feelfreelinux.wykopmobilny.R import io.github.feelfreelinux.wykopmobilny.models.dataclass.Author import io.github.feelfreelinux.wykopmobilny.models.dataclass.Entry import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.CommentViewHolder import io.github.feelfreelinux.wykopmobilny.ui.adapters.viewholders.EntryViewHolder class EntryDetailAdapter(val addReceiverListener : (Author) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { var entry : Entry? = null private val ENTRY_HOLDER = 0 private val COMMENT_HOLDER = 1 override fun onBindViewHolder(holder: RecyclerView.ViewHolder?, position: Int) { when (holder?.itemViewType) { ENTRY_HOLDER -> (holder as EntryViewHolder).bindView(entry!!) COMMENT_HOLDER -> (holder as CommentViewHolder).bindView(entry!!.comments[position - 1]) } } override fun getItemViewType(position: Int): Int { return if (position == 0) ENTRY_HOLDER else COMMENT_HOLDER } override fun getItemCount() : Int { entry?.comments?.let { return it.size + 1 } return 0 } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return when (viewType) { ENTRY_HOLDER -> EntryViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.entry_list_item, parent, false)) else -> CommentViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.comment_list_item, parent, false), addReceiverListener) } } }
mit
9053a2b715c93c34a7944d020679c6fe
39.813953
146
0.722507
4.606299
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/dialogs/CalibrationDialog.kt
1
4238
package info.nightscout.androidaps.dialogs import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner import dagger.android.HasAndroidInjector import info.nightscout.androidaps.R import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.databinding.DialogCalibrationBinding import info.nightscout.androidaps.interfaces.GlucoseUnit import info.nightscout.androidaps.interfaces.Profile import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.iob.iobCobCalculator.GlucoseStatusProvider import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.androidaps.utils.XDripBroadcast import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.interfaces.ResourceHelper import java.text.DecimalFormat import java.util.* import javax.inject.Inject class CalibrationDialog : DialogFragmentWithDate() { @Inject lateinit var injector: HasAndroidInjector @Inject lateinit var rh: ResourceHelper @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var xDripBroadcast: XDripBroadcast @Inject lateinit var uel: UserEntryLogger @Inject lateinit var glucoseStatusProvider: GlucoseStatusProvider private var _binding: DialogCalibrationBinding? = null // This property is only valid between onCreateView and // onDestroyView. private val binding get() = _binding!! override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("bg", binding.bg.value) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { onCreateViewGeneral() _binding = DialogCalibrationBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val units = profileFunction.getUnits() val bg = Profile.fromMgdlToUnits(glucoseStatusProvider.glucoseStatusData?.glucose ?: 0.0, units) if (units == GlucoseUnit.MMOL) binding.bg.setParams(savedInstanceState?.getDouble("bg") ?: bg, 2.0, 30.0, 0.1, DecimalFormat("0.0"), false, binding.okcancel.ok) else binding.bg.setParams(savedInstanceState?.getDouble("bg") ?: bg, 36.0, 500.0, 1.0, DecimalFormat("0"), false, binding.okcancel.ok) binding.units.text = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl) binding.bgLabel.labelFor = binding.bg.editTextId } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun submit(): Boolean { if (_binding == null) return false val units = profileFunction.getUnits() val unitLabel = if (units == GlucoseUnit.MMOL) rh.gs(R.string.mmol) else rh.gs(R.string.mgdl) val actions: LinkedList<String?> = LinkedList() val bg = binding.bg.value actions.add(rh.gs(R.string.treatments_wizard_bg_label) + ": " + Profile.toCurrentUnitsString(profileFunction, bg) + " " + unitLabel) if (bg > 0) { activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(R.string.overview_calibration), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { uel.log(Action.CALIBRATION, Sources.CalibrationDialog, ValueWithUnit.fromGlucoseUnit(bg, units.asText)) xDripBroadcast.sendCalibration(bg) }) } } else activity?.let { activity -> OKDialog.show(activity, rh.gs(R.string.overview_calibration), rh.gs(R.string.no_action_selected)) } return true } }
agpl-3.0
04110bb67ee6ddb8f3b248df09217573
43.610526
146
0.715432
4.503719
false
false
false
false
realm/realm-java
realm-transformer/src/main/kotlin/io/realm/transformer/build/BuildTemplate.kt
1
7781
/* * Copyright 2018 Realm 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 io.realm.transformer.build import com.android.build.api.transform.DirectoryInput import com.android.build.api.transform.Format import com.android.build.api.transform.JarInput import com.android.build.api.transform.Transform import com.android.build.api.transform.TransformInput import com.android.build.api.transform.TransformOutputProvider import com.google.common.io.Files import io.realm.transformer.* import javassist.ClassPool import javassist.CtClass import java.io.File import java.util.regex.Pattern public const val DOT_CLASS = ".class" public const val DOT_JAR = ".jar" /** * Abstract class defining the structure of doing different types of builds. * */ abstract class BuildTemplate(val metadata: ProjectMetaData, val outputProvider: TransformOutputProvider, val transform: Transform) { protected lateinit var inputs: MutableCollection<TransformInput> protected lateinit var classPool: ManagedClassPool protected val outputClassNames: MutableSet<String> = hashSetOf() protected val outputReferencedClassNames: MutableSet<String> = hashSetOf() protected val outputModelClasses: ArrayList<CtClass> = arrayListOf() /** * Find all the class names available for transforms as well as all referenced classes. */ abstract fun prepareOutputClasses(inputs: MutableCollection<TransformInput>) /** * Helper method for going through all `TransformInput` and sort classes into buckets of * source files in the current project or source files found in jar files. * * @param inputs set of input files * @param directoryFiles the set of files in directories getting compiled. These are potential * candidates for the transformer. * @param jaFiles the set of files found in jar files. These will never be transformed. This should * already be done when creating the jar file. */ protected abstract fun categorizeClassNames(inputs: Collection<TransformInput>, directoryFiles: MutableSet<String>, referencedFiles: MutableSet<String>) /** * Returns `true` if this build contains no relevant classes to transform. */ fun hasNoOutput(): Boolean { return outputClassNames.isEmpty() } fun prepareReferencedClasses(referencedInputs: Collection<TransformInput>) { categorizeClassNames(referencedInputs, outputReferencedClassNames, outputReferencedClassNames) // referenced files // Create and populate the Javassist class pool this.classPool = ManagedClassPool(inputs, referencedInputs) // Append android.jar to class pool. We don't need the class names of them but only the class in the pool for // javassist. See https://github.com/realm/realm-java/issues/2703. addBootClassesToClassPool(classPool) logger.debug("ClassPool contains Realm classes: ${classPool.getOrNull("io.realm.RealmList") != null}") filterForModelClasses(outputClassNames, outputReferencedClassNames) } protected abstract fun filterForModelClasses(outputClassNames: Set<String>, outputReferencedClassNames: Set<String>) fun markMediatorsAsTransformed() { val baseProxyMediator: CtClass = classPool.get("io.realm.internal.RealmProxyMediator") val mediatorPattern: Pattern = Pattern.compile("^io\\.realm\\.[^.]+Mediator$") val proxyMediatorClasses: Collection<CtClass> = outputClassNames .filter { mediatorPattern.matcher(it).find() } .map { classPool.getCtClass(it) } .filter { it.superclass.equals(baseProxyMediator) } logger.debug("Proxy Mediator Classes: ${proxyMediatorClasses.joinToString(",") { it.name }}") proxyMediatorClasses.forEach { BytecodeModifier.overrideTransformedMarker(it) } } fun transformModelClasses() { // Add accessors to the model classes in the target project outputModelClasses.forEach { logger.debug("Modify model class: ${it.name}") BytecodeModifier.addRealmAccessors(it) BytecodeModifier.addRealmProxyInterface(it, classPool) BytecodeModifier.callInjectObjectContextFromConstructors(it) } } abstract fun transformDirectAccessToModelFields() fun copyResourceFiles() { copyResourceFiles(inputs) classPool.close(); } private fun copyResourceFiles(inputs: MutableCollection<TransformInput>) { inputs.forEach { input: TransformInput -> input.directoryInputs.forEach { directory: DirectoryInput -> val dirPath: String = directory.file.absolutePath directory.file.walkTopDown().forEach { file: File -> if (file.isFile) { if (!file.absolutePath.endsWith(DOT_CLASS)) { logger.debug(" Copying resource file: $file") val dest = File(getOutputFile(outputProvider, Format.DIRECTORY), file.absolutePath.substring(dirPath.length)) dest.parentFile.mkdirs() Files.copy(file, dest) } } } } input.jarInputs.forEach { jar: JarInput -> logger.debug("Found JAR file: ${jar.file.absolutePath}") val dirPath: String = jar.file.absolutePath jar.file.walkTopDown().forEach { file: File -> if (file.isFile) { if (file.absolutePath.endsWith(DOT_JAR)) { logger.debug(" Copying jar file: $file") val dest = File(getOutputFile(outputProvider, Format.JAR), file.absolutePath.substring(dirPath.length)) dest.parentFile.mkdirs() Files.copy(file, dest) } } } } } } protected fun getOutputFile(outputProvider: TransformOutputProvider, format: Format): File { return outputProvider.getContentLocation("realm", transform.inputTypes, transform.scopes, format) } /** * There is no official way to get the path to android.jar for transform. * See https://code.google.com/p/android/issues/detail?id=209426 */ private fun addBootClassesToClassPool(classPool: ClassPool) { try { metadata.bootClassPath.forEach { val path: String = it.absolutePath logger.debug("Add boot class $path to class pool.") classPool.appendClassPath(path) } } catch (e: Exception) { // Just log it. It might not impact the transforming if the method which needs to be transformer doesn't // contain classes from android.jar. logger.debug("Cannot get bootClasspath caused by: ", e) } } fun getOutputModelClasses(): Set<CtClass> { return outputModelClasses.toSet() } protected abstract fun findModelClasses(classNames: Set<String>): Collection<CtClass> }
apache-2.0
ad45dc8f879abfb5643ee27a5e1d9669
41.98895
137
0.659555
4.909148
false
false
false
false
PolymerLabs/arcs
javatests/arcs/core/storage/testutil/RefModeStoreHelperTest.kt
1
4821
package arcs.core.storage.testutil import arcs.core.crdt.VersionMap import arcs.core.data.CollectionType import arcs.core.data.EntityType import arcs.core.data.RawEntity import arcs.core.entity.testutil.RestrictedDummyEntity import arcs.core.storage.ActiveStore import arcs.core.storage.ProxyMessage import arcs.core.storage.StoreOptions import arcs.core.storage.UntypedProxyMessage import arcs.core.storage.referencemode.RefModeStoreData import arcs.core.storage.referencemode.RefModeStoreOp import arcs.core.storage.referencemode.RefModeStoreOutput import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runBlockingTest import org.junit.Before import org.junit.Test private typealias ProxyMessageOperations = ProxyMessage.Operations<RefModeStoreData, RefModeStoreOp, RefModeStoreOutput> @Suppress("UNCHECKED_CAST") @OptIn(ExperimentalCoroutinesApi::class) class RefModeStoreHelperTest { private lateinit var capturedProxyMessages: MutableList<ProxyMessageOperations> private lateinit var fakeStore: ActiveStore<RefModeStoreData, RefModeStoreOp, RefModeStoreOutput> @Before fun setUp() { capturedProxyMessages = mutableListOf() val storeOptions = StoreOptions( DummyStorageKey("abc"), CollectionType(EntityType(RestrictedDummyEntity.SCHEMA)) ) fakeStore = object : NoopActiveStore(storeOptions) { override suspend fun onProxyMessage(message: UntypedProxyMessage) { capturedProxyMessages.add(message as ProxyMessageOperations) } } as ActiveStore<RefModeStoreData, RefModeStoreOp, RefModeStoreOutput> } @Test fun sendUpdateOp_incrementsVersionMap() = runBlockingTest { val helper = RefModeStoreHelper(ACTOR, fakeStore) helper.sendUpdateOp(DUMMY_ENTITY1) helper.sendUpdateOp(DUMMY_ENTITY2) assertProxyMessages( RefModeStoreOp.SingletonUpdate(ACTOR, VersionMap(ACTOR to 1), DUMMY_ENTITY1), RefModeStoreOp.SingletonUpdate(ACTOR, VersionMap(ACTOR to 2), DUMMY_ENTITY2) ) } @Test fun sendAddOp_incrementsVersionMap() = runBlockingTest { val helper = RefModeStoreHelper(ACTOR, fakeStore) helper.sendAddOp(DUMMY_ENTITY1) helper.sendAddOp(DUMMY_ENTITY2) assertProxyMessages( RefModeStoreOp.SetAdd(ACTOR, VersionMap(ACTOR to 1), DUMMY_ENTITY1), RefModeStoreOp.SetAdd(ACTOR, VersionMap(ACTOR to 2), DUMMY_ENTITY2) ) } @Test fun sendRemoveOp_doesNotIncrementVersionMap() = runBlockingTest { val helper = RefModeStoreHelper(ACTOR, fakeStore) helper.sendAddOp(DUMMY_ENTITY1) helper.sendRemoveOp(DUMMY_ENTITY1.id) assertProxyMessages( RefModeStoreOp.SetAdd(ACTOR, VersionMap(ACTOR to 1), DUMMY_ENTITY1), RefModeStoreOp.SetRemove(ACTOR, VersionMap(ACTOR to 1), DUMMY_ENTITY1.id) ) } @Test fun sendSingletonClearOp_doesNotIncrementVersionMap() = runBlockingTest { val helper = RefModeStoreHelper(ACTOR, fakeStore) helper.sendUpdateOp(DUMMY_ENTITY1) helper.sendSingletonClearOp() assertProxyMessages( RefModeStoreOp.SingletonUpdate(ACTOR, VersionMap(ACTOR to 1), DUMMY_ENTITY1), RefModeStoreOp.SingletonClear(ACTOR, VersionMap(ACTOR to 1)) ) } @Test fun sendCollectionClearOp_doesNotIncrementVersionMap() = runBlockingTest { val helper = RefModeStoreHelper(ACTOR, fakeStore) helper.sendAddOp(DUMMY_ENTITY1) helper.sendCollectionClearOp() assertProxyMessages( RefModeStoreOp.SetAdd(ACTOR, VersionMap(ACTOR to 1), DUMMY_ENTITY1), RefModeStoreOp.SetClear(ACTOR, VersionMap(ACTOR to 1)) ) } @Test fun sendOps_forwardsOpsToStoreUsingCallbackToken() = runBlockingTest { val helper = RefModeStoreHelper(ACTOR, fakeStore, callbackToken = 123) val ops = arrayOf( RefModeStoreOp.SetAdd("a", VersionMap("a" to 1), DUMMY_ENTITY1), RefModeStoreOp.SetAdd("b", VersionMap("b" to 1), DUMMY_ENTITY2) ) helper.sendOps(*ops) assertThat(capturedProxyMessages).containsExactly( ProxyMessageOperations(ops.toList(), id = 123) ) } /** Checks that the [ProxyMessageOperations] sent to the store match the given [ops], in order. */ private fun assertProxyMessages(vararg ops: RefModeStoreOp) { val expected = ops.map { ProxyMessageOperations(listOf(it), id = DEFAULT_CALLBACK_TOKEN) } assertThat(capturedProxyMessages).containsExactlyElementsIn(expected).inOrder() } private companion object { private const val ACTOR = "ACTOR" private const val DEFAULT_CALLBACK_TOKEN = 1 private val DUMMY_ENTITY1 = RawEntity( id = "id1", singletons = emptyMap(), collections = emptyMap() ) private val DUMMY_ENTITY2 = RawEntity( id = "id2", singletons = emptyMap(), collections = emptyMap() ) } }
bsd-3-clause
a8b8d6025dd2a9758039096ea5bb514f
32.248276
100
0.753578
4.170415
false
true
false
false
Tiofx/semester_6
IAD/IAD_lab_2/src/main/kotlin/util/baseParse.kt
1
1391
package util import java.io.File fun String.getFromResources(): File = File(Thread.currentThread().contextClassLoader.getResource(this).file) fun String.getShortCountryName() = this.substringBefore('(').trim() fun File.parseCountrySet() = this.readLines() .map { it.replace(Regex("\\d+."), "") } .map(String::trim) .filter(String::isNotEmpty) .toSet() fun File.parseArea() = this.readLines() .map(String::trim) .map { it.replace(",", ".") } .filter(String::isNotEmpty) .asSequence() .batch(3) .map { Area(it[1], it[2].replace(" ", "").toDouble()) } .toList() fun File.parseGdp() = this.readLines() .map(String::trim) .map { it.replace(",", ".") } .filter(String::isNotEmpty) .asSequence() .batch(2) .map { val list = it[0].split(Regex("[ \t\n]+")) Gdp(list[1], it[1].replace(" ", "").toDouble()) } .toList() fun File.parsePopulation() = this.readLines() .map(String::trim) .map { it.replace(",", ".") } .filter(String::isNotEmpty) .asSequence() .batch(4) .map { Population( it[1], it[2].replace(" ", "").toInt(), it[3].replace("%", "").toDouble() ) } .toList()
gpl-3.0
cefadef5caad2f0f908e244c9c895d61
27.408163
108
0.493889
3.874652
false
false
false
false
Hexworks/zircon
zircon.core/src/jvmTest/kotlin/org/hexworks/zircon/internal/behavior/impl/DefaultScrollable3DTest.kt
1
6047
package org.hexworks.zircon.internal.behavior.impl import org.assertj.core.api.Assertions.assertThat import org.hexworks.zircon.api.data.Position3D import org.hexworks.zircon.api.data.Size3D import org.junit.Before import org.junit.Test class DefaultScrollable3DTest { lateinit var target: DefaultScrollable3D @Before fun setUp() { target = DefaultScrollable3D( initialVisibleSize = VISIBLE_SPACE_SIZE, initialActualSize = VIRTUAL_SPACE_SIZE ) } @Test fun shouldProperlyReportVirtualSpaceSize() { assertThat(target.actualSize) .isEqualTo(VIRTUAL_SPACE_SIZE) } @Test fun shouldProperlyScrollOneRightWhenCanScroll() { target.scrollOneRight() assertThat(target.visibleOffset) .isEqualTo(Position3D.create(1, 0, 0)) } @Test fun shouldProperlyScrollOneLeftWhenCanScroll() { target.scrollOneRight() target.scrollOneRight() target.scrollOneLeft() assertThat(target.visibleOffset) .isEqualTo(Position3D.create(1, 0, 0)) } @Test fun shouldProperlyScrollOneForwardWhenCanScroll() { target.scrollOneForward() assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 1, 0)) } @Test fun shouldProperlyScrollOneBackwardWhenCanScroll() { target.scrollOneForward() target.scrollOneForward() target.scrollOneBackward() assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 1, 0)) } @Test fun shouldProperlyScrollOneUpWhenCanScroll() { target.scrollOneUp() assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 0, 1)) } @Test fun shouldProperlyScrollOneDownWhenCanScroll() { target.scrollOneUp() target.scrollOneUp() target.scrollOneDown() assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 0, 1)) } @Test fun shouldProperlyScrollRightWhenCanScroll() { target.scrollRightBy(5) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(5, 0, 0)) } @Test fun shouldProperlyScrollLeftWhenCanScroll() { target.scrollRightBy(5) target.scrollLeftBy(3) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(2, 0, 0)) } @Test fun shouldProperlyScrollForwardWhenCanScroll() { target.scrollForwardBy(5) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 5, 0)) } @Test fun shouldProperlyScrollBackwardWhenCanScroll() { target.scrollForwardBy(5) target.scrollBackwardBy(3) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 2, 0)) } @Test fun shouldProperlyScrollUpWhenCanScroll() { target.scrollUpBy(5) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 0, 5)) } @Test fun shouldProperlyScrollDownWhenCanScroll() { target.scrollUpBy(5) target.scrollDownBy(3) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 0, 2)) } @Test fun shouldProperlyScrollRightToMaxWhenScrollingTooMuch() { target.scrollRightBy(Int.MAX_VALUE) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(5, 0, 0)) } @Test fun shouldProperlyScrollLeftToMaxWhenScrollingTooMuch() { target.scrollRightBy(5) target.scrollLeftBy(Int.MAX_VALUE) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 0, 0)) } @Test fun shouldProperlyScrollForwardToMaxWhenScrollingTooMuch() { target.scrollForwardBy(Int.MAX_VALUE) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 5, 0)) } @Test fun shouldProperlyScrollBackwardToMaxWhenScrollingTooMuch() { target.scrollForwardBy(5) target.scrollBackwardBy(Int.MAX_VALUE) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 0, 0)) } @Test fun shouldProperlyScrollDownToMaxWhenScrollingTooMuch() { target.scrollUpBy(5) target.scrollDownBy(Int.MAX_VALUE) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 0, 0)) } @Test fun shouldProperlyScrollUpToMaxWhenScrollingTooMuch() { target.scrollUpBy(Int.MAX_VALUE) assertThat(target.visibleOffset) .isEqualTo(Position3D.create(0, 0, 5)) } @Test fun shouldProperlyScrollToProvided3dPosition() { val newPosition = Position3D.create(5, 5, 0) target.scrollTo(newPosition) assertThat(target.visibleOffset) .isEqualTo(newPosition) } @Test(expected = IllegalArgumentException::class) fun shouldThrowExceptionWhenTryingToScrollRightByNegativeAmount() { target.scrollRightBy(-1) } @Test(expected = IllegalArgumentException::class) fun shouldThrowExceptionWhenTryingToScrollLeftByNegativeAmount() { target.scrollLeftBy(-1) } @Test(expected = IllegalArgumentException::class) fun shouldThrowExceptionWhenTryingToScrollUpByNegativeAmount() { target.scrollUpBy(-1) } @Test(expected = IllegalArgumentException::class) fun shouldThrowExceptionWhenTryingToScrollDownByNegativeAmount() { target.scrollDownBy(-1) } @Test(expected = IllegalArgumentException::class) fun shouldThrowExceptionWhenTryingToScrollOutsideOfTheActualSize() { target.scrollTo(Position3D.create(15, 0, 0)) } companion object { val VIRTUAL_SPACE_SIZE = Size3D.create( xLength = 10, yLength = 10, zLength = 10 ) val VISIBLE_SPACE_SIZE = Size3D.create( xLength = 5, yLength = 5, zLength = 5 ) } }
apache-2.0
7da1e6049214c9278b5c58bb7e7ff0be
25.406114
72
0.653051
4.14462
false
true
false
false
edwardharks/Aircraft-Recognition
androidcommon/src/test/kotlin/com/edwardharker/aircraftrecognition/analytics/EventsTest.kt
1
2772
package com.edwardharker.aircraftrecognition.analytics import com.edwardharker.aircraftrecognition.analytics.EventType.IMAGE_LOAD_ERROR import com.edwardharker.aircraftrecognition.analytics.EventType.SELECT_CONTENT import com.edwardharker.aircraftrecognition.analytics.EventType.SELECT_FILTER_OPTION import com.edwardharker.aircraftrecognition.analytics.Events.aircraftDetailEvent import com.edwardharker.aircraftrecognition.analytics.Events.imageErrorEvent import com.edwardharker.aircraftrecognition.analytics.Events.selectFilterOptionEvent import com.edwardharker.aircraftrecognition.analytics.Events.similarAircraftClickEvent import com.edwardharker.aircraftrecognition.analytics.Events.youtubeVideoClickEvent import org.hamcrest.CoreMatchers.equalTo import org.junit.Assert.assertThat import org.junit.Test class EventsTest { @Test fun `creates aircraft detail event`() { val expected = Event( eventType = SELECT_CONTENT, itemId = AIRCRAFT_ID, content = AIRCRAFT_ID ) assertThat(aircraftDetailEvent(AIRCRAFT_ID), equalTo(expected)) } @Test fun `creates image error event`() { val expected = Event( eventType = IMAGE_LOAD_ERROR, itemName = IMAGE_URL, content = REASON ) assertThat(imageErrorEvent(IMAGE_URL, REASON), equalTo(expected)) } @Test fun `creates similar aircraft click event`() { val expected = Event( eventType = SELECT_CONTENT, itemId = AIRCRAFT_ID, content = AIRCRAFT_ID, origin = "similaraircraft" ) assertThat(similarAircraftClickEvent(AIRCRAFT_ID), equalTo(expected)) } @Test fun `creates youtube video click event`() { val expected = Event( eventType = SELECT_CONTENT, itemId = VIDEO_ID, content = VIDEO_ID, origin = AIRCRAFT_ID ) assertThat(youtubeVideoClickEvent(VIDEO_ID, AIRCRAFT_ID), equalTo(expected)) } @Test fun `creates select filter option event`() { val expected = Event( eventType = SELECT_FILTER_OPTION, content = "$FILTER:$FILTER_OPTION" ) val actual = selectFilterOptionEvent( filter = FILTER, filterOption = FILTER_OPTION ) assertThat(actual, equalTo(expected)) } private companion object { private const val AIRCRAFT_ID = "an_aircraft_id" private const val VIDEO_ID = "a_video_id" private const val IMAGE_URL = "image://url" private const val REASON = "a_reason" private const val FILTER = "filter" private const val FILTER_OPTION = "filter_option" } }
gpl-3.0
c1fe16d791e3c331202add33dabb4a11
31.623529
86
0.665945
4.706282
false
true
false
false
kevinmost/extensions-kotlin
core/src/main/java/com/kevinmost/koolbelt/extension/URIUtil.kt
2
882
package com.kevinmost.koolbelt.extension import java.io.IOException import java.io.InputStream import java.net.URI fun URI.readToByteArray(estimatedSizeInBytes: Int = DEFAULT_BUFFER_SIZE): ReadURIResult { try { return ReadURIResult.Success(toURL().openStream().readToByteArray(estimatedSizeInBytes), this) } catch(e: IOException) { return ReadURIResult.Failure(e, this) } } private fun InputStream.readToByteArray(estimatedSizeInBytes: Int): ByteArray { return use { readBytes(estimatedSizeInBytes) } } sealed class ReadURIResult(val uri: URI) { class Success(val bytes: ByteArray, uri: URI) : ReadURIResult(uri) { operator fun component1() = bytes } class Failure(val err: IOException, uri: URI) : ReadURIResult(uri) { operator fun component1() = err } operator fun component2() = uri fun getIfSuccessful(): Success? = this as? Success }
apache-2.0
c466e94cf8ab3de152e84d796fd07a8a
27.451613
98
0.743764
3.834783
false
false
false
false
DanielGrech/anko
dsl/static/src/Logger.kt
3
4011
/* * Copyright 2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.anko import android.content.Context import android.app.Fragment import android.util.Log public interface AnkoLogger { public val loggerTag: String get() { val tag = javaClass.getSimpleName() return if (tag.length() <= 23) { tag } else { tag.substring(0, 23) } } protected final fun verbose(message: Any?, thr: Throwable? = null) { val tag = loggerTag if (Log.isLoggable(tag, Log.VERBOSE)) { if (thr != null) Log.v(tag, message?.toString() ?: "null", thr) else Log.v(tag, message?.toString() ?: "null") } } protected final fun debug(message: Any?, thr: Throwable? = null) { val tag = loggerTag if (Log.isLoggable(tag, Log.DEBUG)) { if (thr != null) Log.d(tag, message?.toString() ?: "null", thr) else Log.d(tag, message?.toString() ?: "null") } } protected final fun info(message: Any?, thr: Throwable? = null) { val tag = loggerTag if (Log.isLoggable(tag, Log.INFO)) { if (thr != null) Log.i(tag, message?.toString() ?: "null", thr) else Log.i(tag, message?.toString() ?: "null") } } protected final fun warn(message: Any?, thr: Throwable? = null) { val tag = loggerTag if (Log.isLoggable(tag, Log.WARN)) { if (thr != null) Log.w(tag, message?.toString() ?: "null", thr) else Log.w(tag, message?.toString() ?: "null") } } protected final fun error(message: Any?, thr: Throwable? = null) { val tag = loggerTag if (Log.isLoggable(tag, Log.ERROR)) { if (thr != null) Log.e(tag, message?.toString() ?: "null", thr) else Log.e(tag, message?.toString() ?: "null") } } protected final fun wtf(message: Any?, thr: Throwable? = null) { if (thr != null) Log.wtf(loggerTag, message?.toString() ?: "null", thr) else Log.wtf(loggerTag, message?.toString() ?: "null") } /* lazy */ protected final inline fun verbose(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.VERBOSE)) Log.v(tag, message()?.toString() ?: "null") } protected final inline fun debug(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.DEBUG)) Log.d(tag, message()?.toString() ?: "null") } protected final inline fun info(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.INFO)) Log.i(tag, message()?.toString() ?: "null") } protected final inline fun warn(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.WARN)) Log.w(tag, message()?.toString() ?: "null") } protected final inline fun error(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.ERROR)) Log.e(tag, message()?.toString() ?: "null") } protected final inline fun wtf(message: () -> Any?) { Log.v(loggerTag, message()?.toString() ?: "null") } } public fun Throwable.getStackTraceString(): String = Log.getStackTraceString(this)
apache-2.0
8843d95fc11eb9be62e7b8c9cf288c51
31.354839
89
0.557716
3.979167
false
false
false
false
bertilxi/DC-Android
app/src/main/java/utnfrsf/dondecurso/common/Util.kt
1
5629
package utnfrsf.dondecurso.common import com.google.gson.internal.LinkedTreeMap import org.jsoup.Jsoup import org.jsoup.nodes.Element import utnfrsf.dondecurso.domain.* import utnfrsf.dondecurso.service.Api import java.util.* import kotlin.collections.ArrayList object Util { fun fromJson(objects: LinkedTreeMap<String, Any>): ArrayList<Materia> { val mMaterias: ArrayList<Materia> = ArrayList() for (key in objects.keys) { objects[key] val materiaNode: LinkedTreeMap<String, Any> = objects.getValue(key) as LinkedTreeMap<String, Any> val id: Double = materiaNode.getValue("id") as Double val idCarrera: Double = materiaNode.getValue("id_carrera") as Double val comisionesMap: LinkedTreeMap<String, Double> = materiaNode.getValue("comisiones") as LinkedTreeMap<String, Double> val nombre: Any = materiaNode.getValue("nombre") val nivel: Double = materiaNode.getValue("nivel") as Double val materia = Materia() materia.nombre = nombre.toString() materia.id = Math.round(id).toInt() materia.idCarrera = Math.round(idCarrera).toInt() materia.nivel = Math.round(nivel).toInt() materia.comisiones = ArrayList<Comision>() for (comKey in comisionesMap.keys) { val comisionNode: LinkedTreeMap<String, Any> = comisionesMap.getValue(comKey) as LinkedTreeMap<String, Any> val comID: Double = comisionNode.getValue("id") as Double val comNombre: Any = comisionNode.getValue("nombre") val comision: Comision = Comision() comision.id = Math.round(comID).toInt() comision.nombre = comNombre.toString() materia.comisiones!!.add(comision) } mMaterias.add(materia) } return mMaterias } fun fromJson(objects: String): ArrayList<Reserva> { val mReservas: ArrayList<Reserva> = ArrayList() val doc = Jsoup.parse(objects) if (doc.getElementsByClass("bloque").isEmpty()) { val tablas = doc.getElementsByTag("table") if (tablas.isNotEmpty()) { val tablaReservas = tablas[0] val filas = tablaReservas.getElementsByTag("tr") filas.removeAt(0) for (f in filas) { val columnas = f.getElementsByTag("td") val mReserva = Reserva() mReserva.comision = columnas[0].text() mReserva.horario = columnas[1].text() mReserva.nombre = columnas[2].text() mReserva.aula = columnas[3].text() mReservas.add(mReserva) } } } return mReservas } fun fromJsonReservasEspeciales(objects: String): ArrayList<ReservaEspecial> { val mReservas: ArrayList<ReservaEspecial> = ArrayList() val doc = Jsoup.parse(objects) val tablas = doc.getElementsByTag("table") if (tablas.isNotEmpty()) { var tablaReservasEspeciales: Element? = null if (doc.getElementsByClass("bloque").isEmpty()) { if (tablas.size >= 2) { tablaReservasEspeciales = tablas[1] } } else { tablaReservasEspeciales = tablas[0] } if (tablaReservasEspeciales != null) { val filas = tablaReservasEspeciales.getElementsByTag("tr") filas?.removeAt(0) for (f in filas!!) { val columnas = f.getElementsByTag("td") val mReserva = ReservaEspecial() val s = columnas[0].text() val split = s.split("Carrera: ", "Materia: ", "- ") if (split.size >= 2) { mReserva.carrera = split[1] } if (split.size >= 3) { mReserva.materia = split[2] } for (i in 4..split.size) { mReserva.descripcion += split[i - 1] + '\n' } mReserva.horario = columnas[1].text() + " a " + columnas[2].text() mReserva.aula = columnas[3].text() mReservas.add(mReserva) } } } return mReservas } fun getWeek(favoritos: ArrayList<Favorito>): ArrayList<Reserva> { val reservas: ArrayList<Reserva> = ArrayList() val reservasFiltered: ArrayList<Reserva> = ArrayList() val c = Calendar.getInstance() c.time = Date() val rangoSemana = IntRange(Calendar.MONDAY, Calendar.FRIDAY) val diaDeHoy = c.get(Calendar.DAY_OF_WEEK) val fechaDeHoy = c.get(Calendar.DATE) if (!rangoSemana.contains(diaDeHoy)) return reservas val api = Api.service val carrera = favoritos[0].carrera rangoSemana.forEach { if (diaDeHoy >= it) { val fecha = "" val request = api.requestDistribution(fecha, carrera.id.toString(), null, null, null) val mReservasStr = request.execute().body() val mReservas = fromJson(mReservasStr) reservas.addAll(mReservas) } } favoritos.forEach { (carrera1) -> reservasFiltered.addAll(reservas.filter { it.nombre == carrera1.nombre }) } return reservasFiltered } }
mit
5fb95e5fc3b0a892e0af7ec68fdbc709
37.033784
130
0.551252
4.020714
false
false
false
false
SimpleMobileTools/Simple-Music-Player
app/src/main/kotlin/com/simplemobiletools/musicplayer/activities/EqualizerActivity.kt
1
8271
package com.simplemobiletools.musicplayer.activities import android.annotation.SuppressLint import android.media.MediaPlayer import android.media.audiofx.Equalizer import android.os.Bundle import android.widget.SeekBar import com.google.gson.Gson import com.google.gson.reflect.TypeToken import com.simplemobiletools.commons.dialogs.RadioGroupDialog import com.simplemobiletools.commons.extensions.* import com.simplemobiletools.commons.helpers.DARK_GREY import com.simplemobiletools.commons.helpers.NavigationIcon import com.simplemobiletools.commons.models.RadioItem import com.simplemobiletools.commons.views.MySeekBar import com.simplemobiletools.musicplayer.R import com.simplemobiletools.musicplayer.extensions.config import com.simplemobiletools.musicplayer.helpers.EQUALIZER_PRESET_CUSTOM import com.simplemobiletools.musicplayer.services.MusicService import kotlinx.android.synthetic.main.activity_equalizer.* import kotlinx.android.synthetic.main.equalizer_band.view.* import java.text.DecimalFormat class EqualizerActivity : SimpleActivity() { private var bands = HashMap<Short, Int>() private var bandSeekBars = ArrayList<MySeekBar>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_equalizer) initMediaPlayer() } override fun onResume() { super.onResume() setupToolbar(equalizer_toolbar, NavigationIcon.Arrow) } @SuppressLint("SetTextI18n") private fun initMediaPlayer() { val player = MusicService.mPlayer ?: MediaPlayer() val equalizer = MusicService.mEqualizer ?: Equalizer(0, player.audioSessionId) try { if (!equalizer.enabled) { equalizer.enabled = true } } catch (e: IllegalStateException) { } setupBands(equalizer) setupPresets(equalizer) updateTextColors(equalizer_holder) val presetTextColor = if (isWhiteTheme()) { DARK_GREY } else { getProperPrimaryColor().getContrastColor() } equalizer_preset.setTextColor(presetTextColor) } private fun setupBands(equalizer: Equalizer) { val minValue = equalizer.bandLevelRange[0] val maxValue = equalizer.bandLevelRange[1] equalizer_label_right.text = "+${maxValue / 100}" equalizer_label_left.text = "${minValue / 100}" equalizer_label_0.text = (minValue + maxValue).toString() bandSeekBars.clear() equalizer_bands_holder.removeAllViews() val bandType = object : TypeToken<HashMap<Short, Int>>() {}.type bands = Gson().fromJson<HashMap<Short, Int>>(config.equalizerBands, bandType) ?: HashMap() for (band in 0 until equalizer.numberOfBands) { val frequency = equalizer.getCenterFreq(band.toShort()) / 1000 val formatted = formatFrequency(frequency) layoutInflater.inflate(R.layout.equalizer_band, equalizer_bands_holder, false).apply { equalizer_bands_holder.addView(this) bandSeekBars.add(this.equalizer_band_seek_bar) this.equalizer_band_label.text = formatted this.equalizer_band_label.setTextColor(getProperTextColor()) this.equalizer_band_seek_bar.max = maxValue - minValue this.equalizer_band_seek_bar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener { override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) { if (fromUser) { val newProgress = Math.round(progress / 100.0) * 100 [email protected]_band_seek_bar.progress = newProgress.toInt() val newValue = newProgress + minValue try { if ((MusicService.mEqualizer ?: equalizer).getBandLevel(band.toShort()) != newValue.toShort()) { (MusicService.mEqualizer ?: equalizer).setBandLevel(band.toShort(), newValue.toShort()) bands[band.toShort()] = newValue.toInt() } } catch (e: Exception) { } } } override fun onStartTrackingTouch(seekBar: SeekBar) { draggingStarted(equalizer) } override fun onStopTrackingTouch(seekBar: SeekBar) { bands[band.toShort()] = [email protected]_band_seek_bar.progress config.equalizerBands = Gson().toJson(bands) } }) } } } private fun draggingStarted(equalizer: Equalizer) { equalizer_preset.text = getString(R.string.custom) config.equalizerPreset = EQUALIZER_PRESET_CUSTOM for (band in 0 until equalizer.numberOfBands) { bands[band.toShort()] = bandSeekBars[band].progress } } private fun setupPresets(equalizer: Equalizer) { try { presetChanged(config.equalizerPreset, equalizer) } catch (e: Exception) { showErrorToast(e) config.equalizerPreset = EQUALIZER_PRESET_CUSTOM } equalizer_preset.setOnClickListener { val items = arrayListOf<RadioItem>() (0 until equalizer.numberOfPresets).mapTo(items) { RadioItem(it, equalizer.getPresetName(it.toShort())) } items.add(RadioItem(EQUALIZER_PRESET_CUSTOM, getString(R.string.custom))) RadioGroupDialog(this, items, config.equalizerPreset) { presetId -> try { config.equalizerPreset = presetId as Int presetChanged(presetId, equalizer) } catch (e: Exception) { showErrorToast(e) config.equalizerPreset = EQUALIZER_PRESET_CUSTOM } } } } private fun presetChanged(presetId: Int, equalizer: Equalizer) { if (presetId == EQUALIZER_PRESET_CUSTOM) { equalizer_preset.text = getString(R.string.custom) for (band in 0 until equalizer.numberOfBands) { val minValue = equalizer.bandLevelRange[0] val progress = if (bands.containsKey(band.toShort())) { bands[band.toShort()] } else { val maxValue = equalizer.bandLevelRange[1] (maxValue - minValue) / 2 } bandSeekBars[band].progress = progress!!.toInt() val newValue = progress + minValue (MusicService.mEqualizer ?: equalizer).setBandLevel(band.toShort(), newValue.toShort()) } } else { val presetName = (MusicService.mEqualizer ?: equalizer).getPresetName(presetId.toShort()) if (presetName.isEmpty()) { config.equalizerPreset = EQUALIZER_PRESET_CUSTOM equalizer_preset.text = getString(R.string.custom) } else { equalizer_preset.text = presetName } (MusicService.mEqualizer ?: equalizer).usePreset(presetId.toShort()) val lowestBandLevel = (MusicService.mEqualizer ?: equalizer).bandLevelRange?.get(0) for (band in 0 until (MusicService.mEqualizer ?: equalizer).numberOfBands) { val level = (MusicService.mEqualizer ?: equalizer).getBandLevel(band.toShort()).minus(lowestBandLevel!!) bandSeekBars[band].progress = level } } } // copypasted from the file size formatter, should be simplified private fun formatFrequency(value: Int): String { if (value <= 0) { return "0 Hz" } val units = arrayOf("Hz", "kHz", "gHz") val digitGroups = (Math.log10(value.toDouble()) / Math.log10(1000.0)).toInt() return "${DecimalFormat("#,##0.#").format(value / Math.pow(1000.0, digitGroups.toDouble()))} ${units[digitGroups]}" } }
gpl-3.0
3be505263999e0a1cc4ba884859ec9b3
40.984772
128
0.607424
4.908605
false
true
false
false
hzsweers/CatchUp
services/designernews/src/main/kotlin/io/sweers/catchup/service/designernews/model/Comment.kt
1
1357
/* * Copyright (C) 2019. Zac Sweers * * 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 io.sweers.catchup.service.designernews.model import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import kotlinx.datetime.Instant /** * Models a comment on a designer news story. */ @JsonClass(generateAdapter = true) internal data class Comment( val body: String, @Json(name = "body_html") val bodyHtml: String, val comments: List<Comment>, @Json(name = "created_at") val createdAt: Instant, val depth: Int, val id: Long, val upvoted: Boolean, @Json(name = "user_display_name") val userDisplayName: String, @Json(name = "user_id") val userId: Long, @Json(name = "user_job") val userJob: String?, @Json(name = "user_portrait_url") val userPortraitUrl: String?, @Json(name = "vote_count") val voteCount: Int )
apache-2.0
72649e43c88ddbc69514234a4ca48b66
33.794872
75
0.722918
3.667568
false
false
false
false
siarhei-luskanau/android-iot-doorbell
data/dataDoorbellApiStub/src/main/kotlin/siarhei/luskanau/iot/doorbell/data/repository/StubDoorbellRepository.kt
1
5526
package siarhei.luskanau.iot.doorbell.data.repository import kotlinx.coroutines.delay import siarhei.luskanau.iot.doorbell.data.model.CameraData import siarhei.luskanau.iot.doorbell.data.model.DoorbellData import siarhei.luskanau.iot.doorbell.data.model.ImageData import java.io.IOException import java.io.InputStream import kotlin.math.max import kotlin.math.min import kotlin.random.Random @Suppress("TooManyFunctions") class StubDoorbellRepository : DoorbellRepository { override suspend fun getDoorbellsList( size: Int, startAt: String?, orderAsc: Boolean ): List<DoorbellData> { delay() if (startAt != null && Random.nextInt(PERCENT_FULL) > PERCENT_ERROR) { throw IOException("test") } val fromToPair = getFromToRange( size = size, startAt = startAt?.toInt(), orderAsc = orderAsc, minCount = MIN_COUNT, maxCount = DOORBELL_MAX_COUNT ) val list = mutableListOf<DoorbellData>() fromToPair?.let { for (i in fromToPair.first..fromToPair.second) { list.add( DoorbellData( doorbellId = "$i", name = "doorbell_$i" ) ) } } return list } override suspend fun getDoorbell(doorbellId: String): DoorbellData { delay() return DoorbellData( doorbellId = doorbellId, name = "doorbell_$doorbellId" ) } override suspend fun getCamerasList(doorbellId: String): List<CameraData> { delay() return listOf( CameraData( cameraId = "0", name = "camera0" ), CameraData( cameraId = "1", name = "camera1" ), CameraData( cameraId = "2", name = "camera2" ) ) } override suspend fun sendDoorbellData(doorbellData: DoorbellData) { delay() } override suspend fun sendCamerasList(doorbellId: String, list: List<CameraData>) { delay() } override suspend fun sendCameraImageRequest( doorbellId: String, cameraId: String, isRequested: Boolean ) { delay() } override suspend fun getCameraImageRequest(doorbellId: String): Map<String, Boolean> { delay() return emptyMap() } override suspend fun sendImage( doorbellId: String, cameraId: String, imageInputStream: InputStream ) { delay() } override suspend fun getImage( doorbellId: String, imageId: String ): ImageData { delay() return ImageData( imageId = imageId, imageUri = imageUriList[imageId.toInt() % imageUriList.size] ) } override suspend fun getImagesList( doorbellId: String, size: Int, imageIdAt: String?, orderAsc: Boolean ): List<ImageData> { delay() if (imageIdAt != null && Random.nextInt(PERCENT_FULL) > PERCENT_ERROR) { throw IOException("test") } val fromToPair = getFromToRange( size = size, startAt = imageIdAt?.toInt(), orderAsc = orderAsc, minCount = MIN_COUNT, maxCount = IMAGE_MAX_COUNT ) val list = mutableListOf<ImageData>() fromToPair?.let { for (i in fromToPair.first..fromToPair.second) { list.add( ImageData( imageId = "$i", imageUri = imageUriList[i % imageUriList.size], timestampString = "timestampString_$i" ) ) } } return list } @Suppress("ComplexMethod", "ReturnCount") fun getFromToRange( size: Int, startAt: Int?, orderAsc: Boolean, minCount: Int, maxCount: Int ): Pair<Int, Int>? { startAt?.let { startAtInt -> if (orderAsc && startAtInt >= maxCount - 1) { return null } if (orderAsc.not() && startAtInt <= minCount) { return null } } val from: Int = if (orderAsc) { startAt?.let { it + 1 } ?: 0 } else { startAt?.let { it - 1 } ?: (size - 1) } val to: Int = if (orderAsc) { min(maxCount - 1, startAt?.let { it + size } ?: (size - 1)) } else { max(0, startAt?.let { max((it - size), minCount) } ?: 0) } return Pair(from, to) } private suspend fun delay() { delay(Random.nextLong(from = DELAY_MIN, until = DELAY_MAX)) } companion object { private const val DELAY_MIN = 1_000L private const val DELAY_MAX = 2_000L private const val MIN_COUNT = 0 private const val DOORBELL_MAX_COUNT = 50 private const val IMAGE_MAX_COUNT = 150 private const val PERCENT_FULL = 100 private const val PERCENT_ERROR = 90 private val imageUriList = (1..10).map { "https://github.com/google-developer-training/" + "android-basics-kotlin-affirmations-app-solution/" + "raw/main/app/src/main/res/drawable/image$it.jpg" } } }
mit
616681661bb98a7f31e1b2ce2b4c149f
27.484536
90
0.527868
4.616541
false
false
false
false
iPoli/iPoli-android
app/src/main/java/io/ipoli/android/quest/schedule/summary/ScheduleSummaryViewController.kt
1
7100
package io.ipoli.android.quest.schedule.summary import android.os.Build import android.os.Bundle import android.view.* import com.haibin.calendarview.Calendar import com.haibin.calendarview.CalendarView import io.ipoli.android.MainActivity import io.ipoli.android.R import io.ipoli.android.common.datetime.DateUtils import io.ipoli.android.common.redux.android.ReduxViewController import io.ipoli.android.common.view.* import io.ipoli.android.habit.show.HabitViewController import io.ipoli.android.quest.schedule.summary.ScheduleSummaryViewState.StateType.* import io.ipoli.android.quest.schedule.summary.usecase.CreateScheduleSummaryItemsUseCase import kotlinx.android.synthetic.main.controller_schedule_summary.view.* import org.json.JSONArray import org.json.JSONObject import org.threeten.bp.DayOfWeek import org.threeten.bp.LocalDate import org.threeten.bp.Month import org.threeten.bp.YearMonth import org.threeten.bp.format.TextStyle import java.util.* /** * Created by Venelin Valkov <[email protected]> * on 07/03/2018. */ class ScheduleSummaryViewController(args: Bundle? = null) : ReduxViewController<ScheduleSummaryAction, ScheduleSummaryViewState, ScheduleSummaryReducer>( args ) { override val reducer = ScheduleSummaryReducer override fun onCreateView( inflater: LayoutInflater, container: ViewGroup, savedViewState: Bundle? ): View { val view = container.inflate(R.layout.controller_schedule_summary) setToolbar(view.toolbar) activity?.let { (it as MainActivity).supportActionBar?.setHomeAsUpIndicator(R.drawable.ic_close_text_secondary_24dp) } setHasOptionsMenu(true) when (DateUtils.firstDayOfWeek) { DayOfWeek.SATURDAY -> view.calendarView.setWeekStarWithSat() DayOfWeek.SUNDAY -> view.calendarView.setWeekStarWithSun() else -> view.calendarView.setWeekStarWithMon() } view.calendarView.setOnMonthChangeListener(HabitViewController.SkipFirstChangeMonthListener { year, month -> dispatch(ScheduleSummaryAction.ChangeMonth(YearMonth.of(year, month))) }) view.calendarView.setOnCalendarSelectListener(SkipFirstChangeDateListener { calendar, isClicked -> val newDate = LocalDate.of(calendar.year, calendar.month, calendar.day) if (isClicked) { dispatch(ScheduleSummaryAction.ChangeDate(newDate)) } }) return view } private fun renderToolbarDate(view: View, month: Int, year: Int) { view.currentMonth.text = Month.of(month).getDisplayName(TextStyle.FULL, Locale.getDefault()) view.currentYear.text = "$year" } override fun onCreateLoadAction() = ScheduleSummaryAction.Load override fun colorStatusBars() { activity?.let { it.window.statusBarColor = colorRes(attrResourceId(android.R.attr.colorBackground)) it.window.navigationBarColor = colorRes(attrResourceId(android.R.attr.colorBackground)) if (it.isDarkTheme) return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { it.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR or View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { it.window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR } } } override fun onAttach(view: View) { super.onAttach(view) showBackButton() view.toolbar.onDebounceMenuClick({ item -> if (item.itemId == R.id.actionGoToToday) { view.calendarView.scrollToCurrent(true) dispatch(ScheduleSummaryAction.GoToToday) } }, { _ -> router.handleBack() }) } override fun onDetach(view: View) { resetDecorView() view.toolbar.clearDebounceListeners() super.onDetach(view) } private fun resetDecorView() { activity?.let { it.window.decorView.systemUiVisibility = 0 } } override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) { super.onCreateOptionsMenu(menu, inflater) inflater.inflate(R.menu.month_preview_menu, menu) } override fun render(state: ScheduleSummaryViewState, view: View) { when (state.type) { DATE_DATA_CHANGED -> { val currentDate = state.currentDate view.calendarView.scrollToCalendar( currentDate.year, currentDate.monthValue, currentDate.dayOfMonth ) renderToolbarDate(view, currentDate.monthValue, currentDate.year) } MONTH_CHANGED -> { renderToolbarDate(view, state.currentDate.monthValue, state.currentDate.year) } SCHEDULE_SUMMARY_DATA_CHANGED -> { view.calendarView.setSchemeDate(state.calendars.map { it.toString() to it }.toMap()) } DATE_SELECTED -> { router.handleBack() } else -> { } } } private val ScheduleSummaryViewState.calendars: List<Calendar> get() = items.map { val itemDate = it.date val items = it.items.map { sc -> val json = JSONObject() when (sc) { is CreateScheduleSummaryItemsUseCase.Schedule.Item.Quest -> { json.put("type", "quest") json.put("name", sc.name) json.put("isCompleted", sc.isCompleted) json.put("color", sc.color.name) } is CreateScheduleSummaryItemsUseCase.Schedule.Item.Event -> { json.put("type", "event") json.put("name", sc.name) json.put("color", sc.color) } } json } Calendar().apply { day = itemDate.dayOfMonth month = itemDate.monthValue year = itemDate.year isCurrentDay = itemDate == currentDate isCurrentMonth = itemDate.month == currentDate.month isLeapYear = itemDate.isLeapYear scheme = JSONArray(items).toString() } } class SkipFirstChangeDateListener(private inline val onChange: (Calendar, Boolean) -> Unit) : CalendarView.OnCalendarSelectListener { override fun onCalendarSelect(calendar: Calendar, isClick: Boolean) { if (isFirstChange) { isFirstChange = false return } onChange(calendar, isClick) } override fun onCalendarOutOfRange(calendar: Calendar) { } private var isFirstChange = true } }
gpl-3.0
059513391361268e29865a425995926c
33.808824
116
0.613662
4.777927
false
false
false
false
pdvrieze/kotlinsql
sql/src/main/kotlin/io/github/pdvrieze/kotlinsql/ddl/columns/impl/CountColumn.kt
1
2683
/* * Copyright (c) 2021. * * This file is part of kotlinsql. * * This file is licenced to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You should have received a copy of the license with the source distribution. * Alternatively, 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 io.github.pdvrieze.kotlinsql.ddl.columns.impl import io.github.pdvrieze.kotlinsql.ddl.columns.* import io.github.pdvrieze.kotlinsql.ddl.* import io.github.pdvrieze.kotlinsql.metadata.ColumnsResults class CountColumn(private val colRef: ColumnRef<*, *, *>) : NumericColumn<Int, NumericColumnType.INT_T> { override val table: TableRef get() = colRef.table override val name: String get() = "COUNT( ${colRef.name} )" override val type: NumericColumnType.INT_T get() = NumericColumnType.INT_T override val notnull: Boolean? get() = null override val unique: Boolean get() = false override val autoincrement: Boolean get() = false override val default: Int? get() = null override val comment: String? get() = null override val columnFormat: ColumnConfiguration.ColumnFormat? get() = null override val storageFormat: ColumnConfiguration.StorageFormat? get() = null override val references: ColsetRef? get() = null override val unsigned: Boolean get() = true override val zerofill: Boolean get() = false override val displayLength: Int get() = 11 override fun copyConfiguration( newName: String?, owner: Table, ): NumberColumnConfiguration<Int, NumericColumnType.INT_T> { throw UnsupportedOperationException() } override fun ref(): ColumnRef<Int, NumericColumnType.INT_T, NumericColumn<Int, NumericColumnType.INT_T>> { throw UnsupportedOperationException() } override fun toDDL(): CharSequence { throw UnsupportedOperationException("A table column cannot be a pure function.") } override fun matches( typeName: String, size: Int, notNull: Boolean?, autoincrement: Boolean?, default: String?, comment: String?, ): Boolean { return false } override fun matches(columnData: ColumnsResults.Data): Boolean = false }
apache-2.0
c306257b7e306eff024f8f35504b5cb7
35.767123
110
0.700335
4.376835
false
true
false
false
ktorio/ktor
ktor-utils/jvm/src/io/ktor/util/date/DateJvm.kt
1
2161
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.date import io.ktor.util.* import java.util.* private val GMT_TIMEZONE = TimeZone.getTimeZone("GMT") /** * Create new gmt date from the [timestamp]. * @param timestamp is a number of epoch milliseconds (it is `now` by default). */ @Suppress("FunctionName") public actual fun GMTDate(timestamp: Long?): GMTDate = Calendar.getInstance(GMT_TIMEZONE, Locale.ROOT)!!.toDate(timestamp) /** * Create an instance of [GMTDate] from the specified date/time components */ @Suppress("FunctionName") public actual fun GMTDate( seconds: Int, minutes: Int, hours: Int, dayOfMonth: Int, month: Month, year: Int ): GMTDate = (Calendar.getInstance(GMT_TIMEZONE, Locale.ROOT)!!).apply { set(Calendar.YEAR, year) set(Calendar.MONTH, month.ordinal) set(Calendar.DAY_OF_MONTH, dayOfMonth) set(Calendar.HOUR_OF_DAY, hours) set(Calendar.MINUTE, minutes) set(Calendar.SECOND, seconds) set(Calendar.MILLISECOND, 0) }.toDate(timestamp = null) public fun Calendar.toDate(timestamp: Long?): GMTDate { timestamp?.let { timeInMillis = it } val seconds = get(Calendar.SECOND) val minutes = get(Calendar.MINUTE) val hours = get(Calendar.HOUR_OF_DAY) /** * from (SUN 1) (MON 2) .. (SAT 7) to (SUN 6) (MON 0) .. (SAT 5) */ val numberOfDay = (get(Calendar.DAY_OF_WEEK) + 7 - 2) % 7 val dayOfWeek = WeekDay.from(numberOfDay) val dayOfMonth = get(Calendar.DAY_OF_MONTH) val dayOfYear = get(Calendar.DAY_OF_YEAR) val month = Month.from(get(Calendar.MONTH)) val year = get(Calendar.YEAR) return GMTDate( seconds, minutes, hours, dayOfWeek, dayOfMonth, dayOfYear, month, year, timeInMillis ) } /** * Convert to [Date] */ public fun GMTDate.toJvmDate(): Date = Date(timestamp) /** * Gets current system time in milliseconds since certain moment in the past, only delta between two subsequent calls makes sense. */ public actual fun getTimeMillis(): Long = System.currentTimeMillis()
apache-2.0
9feef1820dfa2a366657c4ae710d9376
27.434211
130
0.679315
3.713058
false
false
false
false
airbnb/lottie-android
sample-compose/src/main/java/com/airbnb/lottie/sample/compose/examples/ExamplesPage.kt
1
3551
package com.airbnb.lottie.sample.compose.examples import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.ListItem import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.navigation.NavController import com.airbnb.lottie.sample.compose.R import com.airbnb.lottie.sample.compose.Route import com.airbnb.lottie.sample.compose.composables.Marquee import com.airbnb.lottie.sample.compose.navigate @Composable fun ExamplesPage(navController: NavController) { Column( modifier = Modifier .verticalScroll(rememberScrollState()) ) { Marquee(stringResource(R.string.examples_title)) ListItem( text = { Text("Basic Usage") }, secondaryText = { Text("Various example of simple Lottie usage") }, modifier = Modifier .clickable { navController.navigate(Route.BasicUsageExamples) } ) ListItem( text = { Text("Animatable Usage") }, secondaryText = { Text("Usage of LottieAnimatable") }, modifier = Modifier .clickable { navController.navigate(Route.AnimatableUsageExamples) } ) ListItem( text = { Text("Transitions") }, secondaryText = { Text("Sequencing segments of an animation based on state") }, modifier = Modifier .clickable { navController.navigate(Route.TransitionsExamples) } ) ListItem( text = { Text("View Pager") }, secondaryText = { Text("Syncing a Lottie animation with a view pager") }, modifier = Modifier .clickable { navController.navigate(Route.ViewPagerExample) } ) ListItem( text = { Text("Network Animations") }, secondaryText = { Text("Loading animations from a url") }, modifier = Modifier .clickable { navController.navigate(Route.NetworkExamples) } ) ListItem( text = { Text("Dynamic Properties") }, secondaryText = { Text("Setting dynamic properties") }, modifier = Modifier .clickable { navController.navigate(Route.DynamicPropertiesExamples) } ) ListItem( text = { Text("Images") }, secondaryText = { Text("Using animations with images") }, modifier = Modifier .clickable { navController.navigate(Route.ImagesExamples) } ) ListItem( text = { Text("Text") }, secondaryText = { Text("Using animations with text") }, modifier = Modifier .clickable { navController.navigate(Route.TextExamples) } ) ListItem( text = { Text("ContentScale and Alignment") }, secondaryText = { Text("Changing an animation's ContentScale and Alignment") }, modifier = Modifier .clickable { navController.navigate(Route.ContentScaleExamples) } ) ListItem( text = { Text("Caching") }, secondaryText = { Text("Interacting with Lottie's composition cache") }, modifier = Modifier .clickable { navController.navigate(Route.CachingExamples) } ) } }
apache-2.0
981f4b38f7bbc9f8f4f5467de777ca08
40.302326
91
0.62067
5.252959
false
false
false
false
Tickaroo/tikxml
annotationprocessortesting-kt/src/main/java/com/tickaroo/tikxml/regressiontests/Team.kt
1
2662
package com.tickaroo.tikxml.regressiontests import com.tickaroo.tikxml.annotation.Attribute import com.tickaroo.tikxml.annotation.Xml /** * A Element that skips some inner elements * * @author Hannes Dorfmann */ @Xml class Team { @Attribute var id: Int = 0 @Attribute var countryId: String? = null @Attribute var shortName: String? = null @Attribute var longName: String? = null @Attribute var token: String? = null @Attribute var iconSmall: String? = null @Attribute var iconBig: String? = null @Attribute var defaultLeagueId: Int = 0 @Attribute var lat: Double = 0.toDouble() @Attribute var lng: Double = 0.toDouble() override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is Team) return false val team = other as Team? if (id != team!!.id) return false if (defaultLeagueId != team.defaultLeagueId) return false if (java.lang.Double.compare(team.lat, lat) != 0) return false if (java.lang.Double.compare(team.lng, lng) != 0) return false if (if (countryId != null) countryId != team.countryId else team.countryId != null) return false if (if (shortName != null) shortName != team.shortName else team.shortName != null) return false if (if (longName != null) longName != team.longName else team.longName != null) return false if (if (token != null) token != team.token else team.token != null) return false if (if (iconSmall != null) iconSmall != team.iconSmall else team.iconSmall != null) return false return if (iconBig != null) iconBig == team.iconBig else team.iconBig == null } override fun hashCode(): Int { var result: Int var temp: Long result = id result = 31 * result + if (countryId != null) countryId!!.hashCode() else 0 result = 31 * result + if (shortName != null) shortName!!.hashCode() else 0 result = 31 * result + if (longName != null) longName!!.hashCode() else 0 result = 31 * result + if (token != null) token!!.hashCode() else 0 result = 31 * result + if (iconSmall != null) iconSmall!!.hashCode() else 0 result = 31 * result + if (iconBig != null) iconBig!!.hashCode() else 0 result = 31 * result + defaultLeagueId temp = java.lang.Double.doubleToLongBits(lat) result = 31 * result + (temp xor temp.ushr(32)).toInt() temp = java.lang.Double.doubleToLongBits(lng) result = 31 * result + (temp xor temp.ushr(32)).toInt() return result } }
apache-2.0
566d9826961934d04661c052250f78da
35.465753
100
0.618708
4.045593
false
false
false
false
McMoonLakeDev/MoonLake
API/src/main/kotlin/com/mcmoonlake/api/util/ConvertedCollection.kt
1
3026
/* * ProtocolLib - Bukkit server library that allows access to the Minecraft protocol. * Copyright (C) 2012 Kristian S. Stangeland * * 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., 59 Temple Place, Suite 330, Boston, MA * 02111-1307 USA */ /* * Copyright (C) 2016-Present The MoonLake ([email protected]) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mcmoonlake.api.util abstract class ConvertedCollection<VI, VO>( private val inner: MutableCollection<VI> ) : ConvertedAbstract<VI, VO>(), MutableCollection<VO> { override fun add(element: VO): Boolean = inner.add(toIn(element)) override fun addAll(elements: Collection<VO>): Boolean { var modified = false elements.forEach { modified = modified or add(it) } return modified } override fun clear() = inner.clear() override fun contains(element: VO): Boolean = inner.contains(toIn(element)) override fun containsAll(elements: Collection<VO>): Boolean = elements.any { it -> contains(it) } override fun isEmpty(): Boolean = inner.isEmpty() override fun iterator(): MutableIterator<VO> = TransformedIterator.of(inner.iterator(), getOutConverter()) override fun remove(element: VO): Boolean = inner.remove(toIn(element)) override fun removeAll(elements: Collection<VO>): Boolean { var modified = false elements.forEach { modified = modified or remove(it) } return modified } override fun retainAll(elements: Collection<VO>): Boolean { val copy: MutableList<VI> = ArrayList() elements.forEach { copy.add(toIn(it)) } return inner.retainAll(copy) } override val size: Int get() = inner.size }
gpl-3.0
b3f42355a571c8c93af8a09325f852ce
35.457831
98
0.689028
4.379161
false
false
false
false
mdanielwork/intellij-community
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/patterns/groovyPatterns.kt
3
2030
// 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 org.jetbrains.plugins.groovy.lang.psi.patterns import com.intellij.openapi.util.Key import com.intellij.patterns.PatternCondition import com.intellij.patterns.PsiMethodPattern import com.intellij.util.ProcessingContext import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.GrListOrMap import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationMemberValue import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression val closureCallKey: Key<GrCall> = Key.create<GrCall>("groovy.pattern.closure.call") inline fun <reified T : GroovyPsiElement> groovyElement(): GroovyElementPattern.Capture<T> = GroovyElementPattern.Capture(T::class.java) inline fun <reified T : GrExpression> groovyExpression(): GroovyExpressionPattern.Capture<T> = GroovyExpressionPattern.Capture(T::class.java) fun groovyList(): GroovyExpressionPattern.Capture<GrListOrMap> = groovyExpression<GrListOrMap>().with(object : PatternCondition<GrListOrMap>("isList") { override fun accepts(t: GrListOrMap, context: ProcessingContext?) = !t.isMap }) fun psiMethod(containingClass: String, vararg name: String): PsiMethodPattern = GroovyPatterns.psiMethod().withName(*name).definedInClass(containingClass) fun groovyClosure(): GroovyClosurePattern = GroovyClosurePattern() val groovyAnnotationArgumentValue: GroovyElementPattern.Capture<GrAnnotationMemberValue> = groovyElement() val groovyAnnotationArgument: GroovyAnnotationArgumentPattern.Capture = GroovyAnnotationArgumentPattern.Capture() val groovyAnnotationArgumentList: GroovyElementPattern.Capture<GrAnnotationArgumentList> = groovyElement()
apache-2.0
c137ef9e441bf537ac08fb66a6e75ea8
64.483871
154
0.838424
4.471366
false
false
false
false
dhis2/dhis2-android-sdk
core/src/main/java/org/hisp/dhis/android/core/trackedentity/internal/TrackedEntityInstanceImportHandler.kt
1
9925
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.android.core.trackedentity.internal import dagger.Reusable import java.util.* import javax.inject.Inject import org.hisp.dhis.android.core.arch.db.stores.internal.StoreUtils.getSyncState import org.hisp.dhis.android.core.arch.handlers.internal.HandleAction import org.hisp.dhis.android.core.common.State import org.hisp.dhis.android.core.common.internal.DataStatePropagator import org.hisp.dhis.android.core.enrollment.Enrollment import org.hisp.dhis.android.core.enrollment.internal.EnrollmentImportHandler import org.hisp.dhis.android.core.imports.TrackerImportConflict import org.hisp.dhis.android.core.imports.internal.TEIImportSummary import org.hisp.dhis.android.core.imports.internal.TEIWebResponseHandlerSummary import org.hisp.dhis.android.core.imports.internal.TrackerImportConflictParser import org.hisp.dhis.android.core.imports.internal.TrackerImportConflictStore import org.hisp.dhis.android.core.relationship.RelationshipCollectionRepository import org.hisp.dhis.android.core.relationship.RelationshipHelper import org.hisp.dhis.android.core.relationship.internal.RelationshipDHISVersionManager import org.hisp.dhis.android.core.relationship.internal.RelationshipStore import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstance import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceInternalAccessor import org.hisp.dhis.android.core.trackedentity.TrackedEntityInstanceTableInfo @Reusable internal class TrackedEntityInstanceImportHandler @Inject internal constructor( private val trackedEntityInstanceStore: TrackedEntityInstanceStore, private val enrollmentImportHandler: EnrollmentImportHandler, private val trackerImportConflictStore: TrackerImportConflictStore, private val trackerImportConflictParser: TrackerImportConflictParser, private val relationshipStore: RelationshipStore, private val dataStatePropagator: DataStatePropagator, private val relationshipDHISVersionManager: RelationshipDHISVersionManager, private val relationshipRepository: RelationshipCollectionRepository, private val trackedEntityAttributeValueStore: TrackedEntityAttributeValueStore ) { private val alreadyDeletedInServerRegex = Regex("Tracked entity instance (\\w{11}) cannot be deleted as it is not present in the system") @Suppress("NestedBlockDepth") fun handleTrackedEntityInstanceImportSummaries( teiImportSummaries: List<TEIImportSummary?>?, instances: List<TrackedEntityInstance> ): TEIWebResponseHandlerSummary { val summary = TEIWebResponseHandlerSummary() val processedTeis = mutableListOf<String>() teiImportSummaries?.filterNotNull()?.forEach { teiImportSummary -> val teiUid = teiImportSummary.reference() ?: checkAlreadyDeletedInServer(teiImportSummary) if (teiUid != null) { processedTeis.add(teiUid) val instance = instances.find { it.uid() == teiUid } val state = getSyncState(teiImportSummary.status()) trackerImportConflictStore.deleteTrackedEntityConflicts(teiUid) val handleAction = trackedEntityInstanceStore.setSyncStateOrDelete(teiUid, state) if (state == State.ERROR || state == State.WARNING) { resetNestedDataStates(instance) instance?.let { summary.teis.error.add(it) } } else { setRelationshipsState(teiUid, State.SYNCED) instance?.let { summary.teis.success.add(it) } } if (handleAction !== HandleAction.Delete) { storeTEIImportConflicts(teiImportSummary) val enSummary = handleEnrollmentImportSummaries(teiImportSummary, instances, state) summary.add(enSummary) dataStatePropagator.refreshTrackedEntityInstanceAggregatedSyncState(teiUid) } if (state == State.SYNCED && (handleAction == HandleAction.Update || handleAction == HandleAction.Insert) ) { trackedEntityAttributeValueStore.removeDeletedAttributeValuesByInstance(teiUid) } } } val ignoredTeis = processIgnoredTEIs(processedTeis, instances) summary.teis.ignored.addAll(ignoredTeis) return summary } private fun handleEnrollmentImportSummaries( teiImportSummary: TEIImportSummary, instances: List<TrackedEntityInstance>, teiState: State ): TEIWebResponseHandlerSummary { return teiImportSummary.enrollments()?.importSummaries()?.let { importSummaries -> val teiUid = teiImportSummary.reference() enrollmentImportHandler.handleEnrollmentImportSummary( importSummaries, getEnrollments(teiUid, instances), teiState ) } ?: TEIWebResponseHandlerSummary() } private fun storeTEIImportConflicts(teiImportSummary: TEIImportSummary) { val trackerImportConflicts: MutableList<TrackerImportConflict> = ArrayList() if (teiImportSummary.description() != null) { trackerImportConflicts.add( getConflictBuilder(teiImportSummary) .conflict(teiImportSummary.description()) .displayDescription(teiImportSummary.description()) .value(teiImportSummary.reference()) .build() ) } teiImportSummary.conflicts()?.forEach { importConflict -> trackerImportConflicts.add( trackerImportConflictParser .getTrackedEntityInstanceConflict(importConflict, getConflictBuilder(teiImportSummary)) ) } trackerImportConflicts.forEach { trackerImportConflictStore.insert(it) } } // Legacy code for <= 2.29 private fun setRelationshipsState(trackedEntityInstanceUid: String?, state: State) { val dbRelationships = relationshipRepository.getByItem(RelationshipHelper.teiItem(trackedEntityInstanceUid), true, false) val ownedRelationships = relationshipDHISVersionManager .getOwnedRelationships(dbRelationships, trackedEntityInstanceUid) for (relationship in ownedRelationships) { relationshipStore.setSyncStateOrDelete(relationship.uid()!!, state) } } private fun processIgnoredTEIs( processedTEIs: List<String>, instances: List<TrackedEntityInstance> ): List<TrackedEntityInstance> { return instances.filterNot { processedTEIs.contains(it.uid()) }.onEach { instance -> trackerImportConflictStore.deleteTrackedEntityConflicts(instance.uid()) trackedEntityInstanceStore.setSyncStateOrDelete(instance.uid(), State.TO_UPDATE) resetNestedDataStates(instance) } } private fun resetNestedDataStates(instance: TrackedEntityInstance?) { instance?.let { dataStatePropagator.resetUploadingEnrollmentAndEventStates(instance.uid()) setRelationshipsState(instance.uid(), State.TO_UPDATE) } } private fun getEnrollments( trackedEntityInstanceUid: String?, instances: List<TrackedEntityInstance> ): List<Enrollment> { return instances.find { it.uid() == trackedEntityInstanceUid }?.let { TrackedEntityInstanceInternalAccessor.accessEnrollments(it) } ?: listOf() } private fun checkAlreadyDeletedInServer(summary: TEIImportSummary): String? { val teiUid = summary.description()?.let { alreadyDeletedInServerRegex.find(it)?.groupValues?.get(1) } return if (teiUid != null && trackedEntityInstanceStore.selectByUid(teiUid)?.deleted() == true) { teiUid } else { null } } private fun getConflictBuilder(teiImportSummary: TEIImportSummary): TrackerImportConflict.Builder { return TrackerImportConflict.builder() .trackedEntityInstance(teiImportSummary.reference()) .tableReference(TrackedEntityInstanceTableInfo.TABLE_INFO.name()) .status(teiImportSummary.status()) .created(Date()) } }
bsd-3-clause
df8d8e0b61bbc1262e3c16fa8c30bb46
46.037915
111
0.712645
5.081925
false
false
false
false
mdanielwork/intellij-community
platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.kt
1
38205
// 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.ProjectTopics import com.intellij.configurationStore.* import com.intellij.execution.* import com.intellij.execution.configuration.ConfigurationFactoryEx import com.intellij.execution.configurations.* import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionUtil import com.intellij.ide.util.PropertiesComponent import com.intellij.openapi.Disposable import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.* import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.diagnostic.runAndLogException import com.intellij.openapi.extensions.ProjectExtensionPointName import com.intellij.openapi.options.SchemeManager import com.intellij.openapi.options.SchemeManagerFactory import com.intellij.openapi.project.IndexNotReadyException import com.intellij.openapi.project.Project import com.intellij.openapi.roots.ModuleRootEvent import com.intellij.openapi.roots.ModuleRootListener import com.intellij.openapi.updateSettings.impl.pluginsAdvertisement.UnknownFeaturesCollector import com.intellij.openapi.util.ClearableLazyValue import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.project.isDirectoryBased import com.intellij.util.* import com.intellij.util.containers.* import com.intellij.util.text.UniqueNameGenerator import gnu.trove.THashMap import org.jdom.Element import org.jetbrains.annotations.TestOnly import java.util.* import java.util.concurrent.ConcurrentMap import java.util.concurrent.atomic.AtomicBoolean import java.util.concurrent.atomic.AtomicReference import java.util.concurrent.locks.ReentrantReadWriteLock import javax.swing.Icon import kotlin.concurrent.read import kotlin.concurrent.write private const val SELECTED_ATTR = "selected" internal const val METHOD = "method" private const val OPTION = "option" private const val RECENT = "recent_temporary" private val RUN_CONFIGURATION_TEMPLATE_PROVIDER_EP = ProjectExtensionPointName<RunConfigurationTemplateProvider>("com.intellij.runConfigurationTemplateProvider") interface RunConfigurationTemplateProvider { fun getRunConfigurationTemplate(factory: ConfigurationFactory, runManager: RunManagerImpl): RunnerAndConfigurationSettingsImpl? } // open for Upsource (UpsourceRunManager overrides to disable loadState (empty impl)) @State(name = "RunManager", storages = [(Storage(value = StoragePathMacros.WORKSPACE_FILE, useSaveThreshold = ThreeState.NO))]) open class RunManagerImpl @JvmOverloads constructor(val project: Project, sharedStreamProvider: StreamProvider? = null) : RunManagerEx(), PersistentStateComponent<Element>, Disposable { companion object { const val CONFIGURATION = "configuration" const val NAME_ATTR = "name" internal val LOG = logger<RunManagerImpl>() @JvmStatic fun getInstanceImpl(project: Project) = RunManager.getInstance(project) as RunManagerImpl @JvmStatic fun canRunConfiguration(environment: ExecutionEnvironment): Boolean { return environment.runnerAndConfigurationSettings?.let { canRunConfiguration(it, environment.executor) } ?: false } @JvmStatic fun canRunConfiguration(configuration: RunnerAndConfigurationSettings, executor: Executor): Boolean { try { configuration.checkSettings(executor) } catch (ignored: IndexNotReadyException) { return false } catch (ignored: RuntimeConfigurationError) { return false } catch (ignored: RuntimeConfigurationException) { } return true } } private val lock = ReentrantReadWriteLock() private val idToType = object { private var cachedValue: Map<String, ConfigurationType>? = null val value: Map<String, ConfigurationType> get() { var result = cachedValue if (result == null) { result = compute() cachedValue = result } return result } fun drop() { cachedValue = null } fun resolve(value: Map<String, ConfigurationType>) { cachedValue = value } private fun compute(): Map<String, ConfigurationType> { return buildConfigurationTypeMap(ConfigurationType.CONFIGURATION_TYPE_EP.extensionList) } } @Suppress("LeakingThis") private val listManager = RunConfigurationListManagerHelper(this) private val templateIdToConfiguration = THashMap<String, RunnerAndConfigurationSettingsImpl>() // template configurations are not included here private val idToSettings: LinkedHashMap<String, RunnerAndConfigurationSettings> get() = listManager.idToSettings // When readExternal not all configuration may be loaded, so we need to remember the selected configuration // so that when it is eventually loaded, we can mark is as a selected. private var selectedConfigurationId: String? = null private val iconCache = TimedIconCache() private val recentlyUsedTemporaries = ArrayList<RunnerAndConfigurationSettings>() // templates should be first because to migrate old before run list to effective, we need to get template before run task private val workspaceSchemeManagerProvider = SchemeManagerIprProvider("configuration", Comparator { n1, n2 -> val w1 = getNameWeight(n1) val w2 = getNameWeight(n2) if (w1 == w2) { n1.compareTo(n2) } else { w1 - w2 } }) internal val schemeManagerIprProvider = if (project.isDirectoryBased || sharedStreamProvider != null) null else SchemeManagerIprProvider("configuration") @Suppress("LeakingThis") private val templateDifferenceHelper = TemplateDifferenceHelper(this) @Suppress("LeakingThis") private val workspaceSchemeManager = SchemeManagerFactory.getInstance(project).create("workspace", RunConfigurationSchemeManager(this, templateDifferenceHelper, isShared = false, isWrapSchemeIntoComponentElement = false), streamProvider = workspaceSchemeManagerProvider, isAutoSave = false) @Suppress("LeakingThis") private var projectSchemeManager = SchemeManagerFactory.getInstance(project).create("runConfigurations", RunConfigurationSchemeManager(this, templateDifferenceHelper, isShared = true, isWrapSchemeIntoComponentElement = schemeManagerIprProvider == null), schemeNameToFileName = OLD_NAME_CONVERTER, streamProvider = sharedStreamProvider ?: schemeManagerIprProvider) private val isFirstLoadState = AtomicBoolean(true) private val stringIdToBeforeRunProvider = object : ClearableLazyValue<ConcurrentMap<String, BeforeRunTaskProvider<*>>>() { override fun compute(): ConcurrentMap<String, BeforeRunTaskProvider<*>> { val result = ContainerUtil.newConcurrentMap<String, BeforeRunTaskProvider<*>>() for (provider in BeforeRunTaskProvider.EXTENSION_POINT_NAME.getExtensionList(project)) { result.put(provider.id.toString(), provider) } return result } } internal val eventPublisher: RunManagerListener get() = project.messageBus.syncPublisher(RunManagerListener.TOPIC) init { if (!ApplicationManager.getApplication().isUnitTestMode) { project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener { override fun rootsChanged(event: ModuleRootEvent) { selectedConfiguration?.let { iconCache.remove(it.uniqueID) } } }) } } @TestOnly fun initializeConfigurationTypes(factories: List<ConfigurationType>) { idToType.resolve(buildConfigurationTypeMap(factories)) } private fun buildConfigurationTypeMap(factories: List<ConfigurationType>): Map<String, ConfigurationType> { val types = factories.toMutableList() types.add(UnknownConfigurationType.getInstance()) val map = THashMap<String, ConfigurationType>() for (type in types) { map.put(type.id, type) } return map } override fun createConfiguration(name: String, factory: ConfigurationFactory): RunnerAndConfigurationSettings { val template = getConfigurationTemplate(factory) return createConfiguration(factory.createConfiguration(name, template.configuration), template) } override fun createConfiguration(runConfiguration: RunConfiguration, factory: ConfigurationFactory): RunnerAndConfigurationSettings { return createConfiguration(runConfiguration, getConfigurationTemplate(factory)) } private fun createConfiguration(configuration: RunConfiguration, template: RunnerAndConfigurationSettingsImpl): RunnerAndConfigurationSettings { val settings = RunnerAndConfigurationSettingsImpl(this, configuration) settings.importRunnerAndConfigurationSettings(template) if (!settings.isShared) { shareConfiguration(settings, template.isShared) } configuration.beforeRunTasks = template.configuration.beforeRunTasks return settings } override fun dispose() { lock.write { iconCache.clear() templateIdToConfiguration.clear() } } open val config by lazy { RunManagerConfig(PropertiesComponent.getInstance(project)) } /** * Template configuration is not included */ override fun getConfigurationsList(type: ConfigurationType): List<RunConfiguration> { var result: MutableList<RunConfiguration>? = null for (settings in allSettings) { val configuration = settings.configuration if (type.id == configuration.type.id) { if (result == null) { result = SmartList<RunConfiguration>() } result.add(configuration) } } return result ?: emptyList() } override val allConfigurationsList: List<RunConfiguration> get() = allSettings.mapSmart { it.configuration } fun getSettings(configuration: RunConfiguration) = allSettings.firstOrNull { it.configuration === configuration } as? RunnerAndConfigurationSettingsImpl override fun getConfigurationSettingsList(type: ConfigurationType) = allSettings.filterSmart { it.type === type } fun getConfigurationsGroupedByTypeAndFolder(isIncludeUnknown: Boolean): Map<ConfigurationType, Map<String?, List<RunnerAndConfigurationSettings>>> { val result = LinkedHashMap<ConfigurationType, MutableMap<String?, MutableList<RunnerAndConfigurationSettings>>>() // use allSettings to return sorted result for (setting in allSettings) { val type = setting.type if (!isIncludeUnknown && type === UnknownConfigurationType.getInstance()) { continue } val folderToConfigurations = result.getOrPut(type) { LinkedHashMap() } folderToConfigurations.getOrPut(setting.folderName) { SmartList() }.add(setting) } return result } override fun getConfigurationTemplate(factory: ConfigurationFactory): RunnerAndConfigurationSettingsImpl { for (provider in RUN_CONFIGURATION_TEMPLATE_PROVIDER_EP.getExtensions(project)) { provider.getRunConfigurationTemplate(factory, this)?.let { return it } } val key = getFactoryKey(factory) return lock.read { templateIdToConfiguration.get(key) } ?: lock.write { templateIdToConfiguration.getOrPut(key) { val template = createTemplateSettings(factory) workspaceSchemeManager.addScheme(template) template } } } internal fun createTemplateSettings(factory: ConfigurationFactory): RunnerAndConfigurationSettingsImpl { val configuration = factory.createTemplateConfiguration(project, this) configuration.isAllowRunningInParallel = factory.singletonPolicy.isAllowRunningInParallel val template = RunnerAndConfigurationSettingsImpl(this, configuration, isTemplate = true) if (configuration is UnknownRunConfiguration) { configuration.isDoNotStore = true } configuration.beforeRunTasks = getHardcodedBeforeRunTasks(configuration, factory) return template } override fun addConfiguration(settings: RunnerAndConfigurationSettings) { doAddConfiguration(settings, isCheckRecentsLimit = true) } private fun doAddConfiguration(settings: RunnerAndConfigurationSettings, isCheckRecentsLimit: Boolean) { val newId = settings.uniqueID var existingId: String? = null lock.write { listManager.immutableSortedSettingsList = null // https://youtrack.jetbrains.com/issue/IDEA-112821 // we should check by instance, not by id (todo is it still relevant?) existingId = if (idToSettings.get(newId) === settings) newId else findExistingConfigurationId(settings) existingId?.let { if (newId != it) { idToSettings.remove(it) if (selectedConfigurationId == it) { selectedConfigurationId = newId } } } idToSettings.put(newId, settings) if (existingId == null) { refreshUsagesList(settings) } else { (if (settings.isShared) workspaceSchemeManager else projectSchemeManager).removeScheme( settings as RunnerAndConfigurationSettingsImpl) } // scheme level can be changed (workspace -> project), so, ensure that scheme is added to corresponding scheme manager (if exists, doesn't harm) settings.schemeManager?.addScheme(settings as RunnerAndConfigurationSettingsImpl) } if (existingId == null) { if (isCheckRecentsLimit && settings.isTemporary) { checkRecentsLimit() } eventPublisher.runConfigurationAdded(settings) } else { eventPublisher.runConfigurationChanged(settings, existingId) } } private val RunnerAndConfigurationSettings.schemeManager: SchemeManager<RunnerAndConfigurationSettingsImpl>? get() = if (isShared) projectSchemeManager else workspaceSchemeManager override fun refreshUsagesList(profile: RunProfile) { if (profile !is RunConfiguration) { return } getSettings(profile)?.let { refreshUsagesList(it) } } private fun refreshUsagesList(settings: RunnerAndConfigurationSettings) { if (settings.isTemporary) { lock.write { recentlyUsedTemporaries.remove(settings) recentlyUsedTemporaries.add(0, settings) trimUsagesListToLimit() } } } // call only under write lock private fun trimUsagesListToLimit() { while (recentlyUsedTemporaries.size > config.recentsLimit) { recentlyUsedTemporaries.removeAt(recentlyUsedTemporaries.size - 1) } } fun checkRecentsLimit() { var removed: MutableList<RunnerAndConfigurationSettings>? = null lock.write { trimUsagesListToLimit() var excess = idToSettings.values.count { it.isTemporary } - config.recentsLimit if (excess <= 0) { return } for (settings in idToSettings.values) { if (settings.isTemporary && !recentlyUsedTemporaries.contains(settings)) { if (removed == null) { removed = SmartList<RunnerAndConfigurationSettings>() } removed!!.add(settings) if (--excess <= 0) { break } } } } removed?.let { removeConfigurations(it) } } @JvmOverloads fun setOrder(comparator: Comparator<RunnerAndConfigurationSettings>, isApplyAdditionalSortByTypeAndGroup: Boolean = true) { lock.write { listManager.setOrder(comparator, isApplyAdditionalSortByTypeAndGroup) } } override var selectedConfiguration: RunnerAndConfigurationSettings? get() { return lock.read { selectedConfigurationId?.let { idToSettings.get(it) } } } set(value) { fun isTheSame() = value?.uniqueID == selectedConfigurationId lock.read { if (isTheSame()) { return } } lock.write { if (isTheSame()) { return } val id = value?.uniqueID if (id != null && !idToSettings.containsKey(id)) { LOG.error("$id must be added before selecting") } selectedConfigurationId = id } eventPublisher.runConfigurationSelected(value) } fun requestSort() { lock.write { listManager.requestSort() } } override val allSettings: List<RunnerAndConfigurationSettings> get() { listManager.immutableSortedSettingsList?.let { return it } lock.write { return listManager.buildImmutableSortedSettingsList() } } override fun getState(): Element { if (!isFirstLoadState.get()) { lock.read { val list = idToSettings.values.toList() list.forEachManaged { listManager.checkIfDependenciesAreStable(it.configuration, list) } } } val element = Element("state") workspaceSchemeManager.save() lock.read { workspaceSchemeManagerProvider.writeState(element) if (idToSettings.size > 1) { selectedConfiguration?.let { element.setAttribute(SELECTED_ATTR, it.uniqueID) } listManager.writeOrder(element) } val recentList = SmartList<String>() recentlyUsedTemporaries.forEachManaged { recentList.add(it.uniqueID) } if (!recentList.isEmpty()) { val recent = Element(RECENT) element.addContent(recent) val listElement = Element("list") recent.addContent(listElement) for (id in recentList) { listElement.addContent(Element("item").setAttribute("itemvalue", id)) } } } return element } fun writeContext(element: Element) { for (setting in allSettings) { if (setting.isTemporary) { element.addContent((setting as RunnerAndConfigurationSettingsImpl).writeScheme()) } } selectedConfiguration?.let { element.setAttribute(SELECTED_ATTR, it.uniqueID) } } fun writeConfigurations(parentNode: Element, settings: Collection<RunnerAndConfigurationSettings>) { settings.forEach { parentNode.addContent((it as RunnerAndConfigurationSettingsImpl).writeScheme()) } } internal fun writeBeforeRunTasks(configuration: RunConfiguration): Element? { val tasks = configuration.beforeRunTasks val methodElement = Element(METHOD) methodElement.attribute("v", "2") for (task in tasks) { val child = Element(OPTION) child.setAttribute(NAME_ATTR, task.providerId.toString()) if (task is PersistentStateComponent<*>) { if (!task.isEnabled) { child.setAttribute("enabled", "false") } serializeStateInto(task, child) } else { @Suppress("DEPRECATION") task.writeExternal(child) } methodElement.addContent(child) } return methodElement } @Suppress("unused") /** * used by MPS. Do not use if not approved. */ fun reloadSchemes() { lock.write { // not really required, but hot swap friendly - 1) factory is used a key, 2) developer can change some defaults. templateDifferenceHelper.clearCache() templateIdToConfiguration.clear() listManager.idToSettings.clear() recentlyUsedTemporaries.clear() stringIdToBeforeRunProvider.drop() } workspaceSchemeManager.reload() projectSchemeManager.reload() } override fun noStateLoaded() { isFirstLoadState.set(false) loadSharedRunConfigurations() runConfigurationFirstLoaded() eventPublisher.stateLoaded(this, true) } override fun loadState(parentNode: Element) { val oldSelectedConfigurationId: String? val isFirstLoadState = isFirstLoadState.compareAndSet(true, false) if (isFirstLoadState) { oldSelectedConfigurationId = null } else { oldSelectedConfigurationId = selectedConfigurationId clear(false) } val nameGenerator = UniqueNameGenerator() workspaceSchemeManagerProvider.load(parentNode) { element -> var schemeKey: String? = element.getAttributeValue("name") if (schemeKey == "<template>" || schemeKey == null) { // scheme name must be unique element.getAttributeValue("type")?.let { if (schemeKey == null) { schemeKey = "<template>" } schemeKey += ", type: ${it}" } } else if (schemeKey != null) { val typeId = element.getAttributeValue("type") if (typeId == null) { LOG.warn("typeId is null for '${schemeKey}'") } schemeKey = "${typeId ?: "unknown"}-${schemeKey}" } // in case if broken configuration, do not fail, just generate name if (schemeKey == null) { schemeKey = nameGenerator.generateUniqueName("Unnamed") } else { schemeKey = "${schemeKey!!}, factoryName: ${element.getAttributeValue("factoryName", "")}" nameGenerator.addExistingName(schemeKey!!) } schemeKey!! } workspaceSchemeManager.reload() lock.write { recentlyUsedTemporaries.clear() val recentListElement = parentNode.getChild(RECENT)?.getChild("list") if (recentListElement != null) { for (id in recentListElement.getChildren("item").mapNotNull { it.getAttributeValue("itemvalue") }) { idToSettings.get(id)?.let { recentlyUsedTemporaries.add(it) } } } selectedConfigurationId = parentNode.getAttributeValue(SELECTED_ATTR) } if (isFirstLoadState) { loadSharedRunConfigurations() } // apply order after loading shared RC lock.write { listManager.readCustomOrder(parentNode) } runConfigurationFirstLoaded() fireBeforeRunTasksUpdated() if (!isFirstLoadState && oldSelectedConfigurationId != null && oldSelectedConfigurationId != selectedConfigurationId) { eventPublisher.runConfigurationSelected(selectedConfiguration) } eventPublisher.stateLoaded(this, isFirstLoadState) } private fun loadSharedRunConfigurations() { if (schemeManagerIprProvider == null) { projectSchemeManager.loadSchemes() } else { project.service<IprRunManagerImpl>().lastLoadedState.getAndSet(null)?.let { data -> schemeManagerIprProvider.load(data) projectSchemeManager.reload() } } } private fun runConfigurationFirstLoaded() { if (selectedConfiguration == null) { selectedConfiguration = allSettings.firstOrNull { it.type.isManaged } } } fun readContext(parentNode: Element) { var selectedConfigurationId = parentNode.getAttributeValue(SELECTED_ATTR) for (element in parentNode.children) { val config = loadConfiguration(element, false) if (selectedConfigurationId == null && element.getAttributeBooleanValue(SELECTED_ATTR)) { selectedConfigurationId = config.uniqueID } } this.selectedConfigurationId = selectedConfigurationId eventPublisher.runConfigurationSelected(selectedConfiguration) } override fun hasSettings(settings: RunnerAndConfigurationSettings) = lock.read { idToSettings.get(settings.uniqueID) == settings } private fun findExistingConfigurationId(settings: RunnerAndConfigurationSettings): String? { for ((key, value) in idToSettings) { if (value === settings) { return key } } return null } // used by MPS, don't delete fun clearAll() { clear(true) idToType.drop() } private fun clear(allConfigurations: Boolean) { val removedConfigurations = lock.write { listManager.immutableSortedSettingsList = null val configurations = if (allConfigurations) { val configurations = idToSettings.values.toList() idToSettings.clear() selectedConfigurationId = null configurations } else { val configurations = SmartList<RunnerAndConfigurationSettings>() val iterator = idToSettings.values.iterator() for (configuration in iterator) { if (configuration.isTemporary || !configuration.isShared) { iterator.remove() configurations.add(configuration) } } selectedConfigurationId?.let { if (idToSettings.containsKey(it)) { selectedConfigurationId = null } } configurations } templateIdToConfiguration.clear() recentlyUsedTemporaries.clear() configurations } iconCache.clear() val eventPublisher = eventPublisher removedConfigurations.forEach { eventPublisher.runConfigurationRemoved(it) } } fun loadConfiguration(element: Element, isShared: Boolean): RunnerAndConfigurationSettings { val settings = RunnerAndConfigurationSettingsImpl(this) LOG.runAndLogException { settings.readExternal(element, isShared) } addConfiguration(element, settings) return settings } internal fun addConfiguration(element: Element, settings: RunnerAndConfigurationSettingsImpl, isCheckRecentsLimit: Boolean = true) { if (settings.isTemplate) { val factory = settings.factory // do not register unknown RC type templates (it is saved in any case in the scheme manager, so, not lost on save) if (factory !== UnknownConfigurationType.getInstance()) { val key = getFactoryKey(factory) lock.write { val old = templateIdToConfiguration.put(key, settings) if (old != null) { LOG.error("Template $key already registered, old: $old, new: $settings") } } } } else { doAddConfiguration(settings, isCheckRecentsLimit) if (element.getAttributeBooleanValue(SELECTED_ATTR)) { // to support old style selectedConfiguration = settings } } } internal fun readBeforeRunTasks(element: Element?, settings: RunnerAndConfigurationSettings, configuration: RunConfiguration) { var result: MutableList<BeforeRunTask<*>>? = null if (element != null) { for (methodElement in element.getChildren(OPTION)) { val key = methodElement.getAttributeValue(NAME_ATTR) val provider = stringIdToBeforeRunProvider.value.getOrPut(key) { UnknownBeforeRunTaskProvider(key) } val beforeRunTask = provider.createTask(configuration) ?: continue if (beforeRunTask is PersistentStateComponent<*>) { // for PersistentStateComponent we don't write default value for enabled, so, set it to true explicitly beforeRunTask.isEnabled = true deserializeAndLoadState(beforeRunTask, methodElement) } else { @Suppress("DEPRECATION") beforeRunTask.readExternal(methodElement) } if (result == null) { result = SmartList() } result.add(beforeRunTask) } } if (element?.getAttributeValue("v") == null) { if (settings.isTemplate) { if (result.isNullOrEmpty()) { configuration.beforeRunTasks = getHardcodedBeforeRunTasks(configuration, configuration.factory!!) return } } else { configuration.beforeRunTasks = getEffectiveBeforeRunTaskList(result ?: emptyList(), getConfigurationTemplate(configuration.factory!!).configuration.beforeRunTasks, true, false) return } } configuration.beforeRunTasks = result ?: emptyList() } @JvmOverloads fun getFactory(typeId: String?, factoryId: String?, checkUnknown: Boolean = false): ConfigurationFactory? { val type = idToType.value.get(typeId) if (type == null) { if (checkUnknown && typeId != null) { UnknownFeaturesCollector.getInstance(project).registerUnknownRunConfiguration(typeId, factoryId) } return UnknownConfigurationType.getInstance() } return getFactory(type, factoryId) } fun getFactory(type: ConfigurationType, factoryId: String?): ConfigurationFactory? { return when (type) { is UnknownConfigurationType -> type.configurationFactories.firstOrNull() is SimpleConfigurationType -> type else -> type.configurationFactories.firstOrNull { factoryId == null || it.id == factoryId } } } override fun setTemporaryConfiguration(tempConfiguration: RunnerAndConfigurationSettings?) { if (tempConfiguration == null) { return } tempConfiguration.isTemporary = true addConfiguration(tempConfiguration) if (Registry.`is`("select.run.configuration.from.context")) { selectedConfiguration = tempConfiguration } } override val tempConfigurationsList: List<RunnerAndConfigurationSettings> get() = allSettings.filterSmart { it.isTemporary } override fun makeStable(settings: RunnerAndConfigurationSettings) { settings.isTemporary = false doMakeStable(settings) fireRunConfigurationChanged(settings) } private fun doMakeStable(settings: RunnerAndConfigurationSettings) { lock.write { recentlyUsedTemporaries.remove(settings) listManager.afterMakeStable() } } override fun <T : BeforeRunTask<*>> getBeforeRunTasks(taskProviderId: Key<T>): List<T> { val tasks = SmartList<T>() val checkedTemplates = SmartList<RunnerAndConfigurationSettings>() lock.read { for (settings in allSettings) { val configuration = settings.configuration for (task in getBeforeRunTasks(configuration)) { if (task.isEnabled && task.providerId === taskProviderId) { @Suppress("UNCHECKED_CAST") tasks.add(task as T) } else { val template = getConfigurationTemplate(configuration.factory!!) if (!checkedTemplates.contains(template)) { checkedTemplates.add(template) for (templateTask in getBeforeRunTasks(template.configuration)) { if (templateTask.isEnabled && templateTask.providerId === taskProviderId) { @Suppress("UNCHECKED_CAST") tasks.add(templateTask as T) } } } } } } } return tasks } override fun getConfigurationIcon(settings: RunnerAndConfigurationSettings, withLiveIndicator: Boolean): Icon { val uniqueId = settings.uniqueID if (selectedConfiguration?.uniqueID == uniqueId) { iconCache.checkValidity(uniqueId) } var icon = iconCache.get(uniqueId, settings, project) if (withLiveIndicator) { val runningDescriptors = ExecutionManagerImpl.getInstance(project).getRunningDescriptors { it === settings } when { runningDescriptors.size == 1 -> icon = ExecutionUtil.getLiveIndicator(icon) runningDescriptors.size > 1 -> icon = IconUtil.addText(icon, runningDescriptors.size.toString()) } } return icon } fun isInvalidInCache(configuration: RunConfiguration): Boolean { findSettings(configuration)?.let { return iconCache.isInvalid(it.uniqueID) } return false } fun getConfigurationById(id: String): RunnerAndConfigurationSettings? = lock.read { idToSettings.get(id) } override fun findConfigurationByName(name: String?): RunnerAndConfigurationSettings? { if (name == null) { return null } return allSettings.firstOrNull { it.name == name } } override fun findSettings(configuration: RunConfiguration): RunnerAndConfigurationSettings? { val id = RunnerAndConfigurationSettingsImpl.getUniqueIdFor(configuration) lock.read { return idToSettings.get(id) } } override fun isTemplate(configuration: RunConfiguration): Boolean { lock.read { return templateIdToConfiguration.values.any { it.configuration === configuration } } } override fun <T : BeforeRunTask<*>> getBeforeRunTasks(settings: RunConfiguration, taskProviderId: Key<T>): List<T> { if (settings is WrappingRunConfiguration<*>) { return getBeforeRunTasks(settings.peer, taskProviderId) } var result: MutableList<T>? = null for (task in getBeforeRunTasks(settings)) { if (task.providerId === taskProviderId) { if (result == null) { result = SmartList<T>() } @Suppress("UNCHECKED_CAST") result.add(task as T) } } return result ?: emptyList() } override fun getBeforeRunTasks(configuration: RunConfiguration) = doGetBeforeRunTasks(configuration) fun shareConfiguration(settings: RunnerAndConfigurationSettings, value: Boolean) { if (settings.isShared == value) { return } if (value && settings.isTemporary) { doMakeStable(settings) } settings.isShared = value fireRunConfigurationChanged(settings) } override fun setBeforeRunTasks(configuration: RunConfiguration, tasks: List<BeforeRunTask<*>>) { if (!configuration.type.isManaged) { return } configuration.beforeRunTasks = tasks fireBeforeRunTasksUpdated() } fun fireBeginUpdate() { eventPublisher.beginUpdate() } fun fireEndUpdate() { eventPublisher.endUpdate() } fun fireRunConfigurationChanged(settings: RunnerAndConfigurationSettings) { eventPublisher.runConfigurationChanged(settings, null) } @Suppress("OverridingDeprecatedMember") override fun addRunManagerListener(listener: RunManagerListener) { project.messageBus.connect().subscribe(RunManagerListener.TOPIC, listener) } fun fireBeforeRunTasksUpdated() { eventPublisher.beforeRunTasksChanged() } override fun removeConfiguration(settings: RunnerAndConfigurationSettings?) { if (settings != null) { removeConfigurations(listOf(settings)) } } fun removeConfigurations(toRemove: Collection<RunnerAndConfigurationSettings>) { if (toRemove.isEmpty()) { return } val changedSettings = SmartList<RunnerAndConfigurationSettings>() val removed = SmartList<RunnerAndConfigurationSettings>() var selectedConfigurationWasRemoved = false lock.write { listManager.immutableSortedSettingsList = null val iterator = idToSettings.values.iterator() for (settings in iterator) { if (toRemove.contains(settings)) { if (selectedConfigurationId == settings.uniqueID) { selectedConfigurationWasRemoved = true } iterator.remove() settings.schemeManager?.removeScheme(settings as RunnerAndConfigurationSettingsImpl) recentlyUsedTemporaries.remove(settings) removed.add(settings) iconCache.remove(settings.uniqueID) } else { var isChanged = false val otherConfiguration = settings.configuration val newList = otherConfiguration.beforeRunTasks.nullize()?.toMutableSmartList() ?: continue val beforeRunTaskIterator = newList.iterator() for (task in beforeRunTaskIterator) { if (task is RunConfigurationBeforeRunProvider.RunConfigurableBeforeRunTask && toRemove.firstOrNull { task.isMySettings(it) } != null) { beforeRunTaskIterator.remove() isChanged = true changedSettings.add(settings) } } if (isChanged) { otherConfiguration.beforeRunTasks = newList } } } } if (selectedConfigurationWasRemoved) { selectedConfiguration = null } removed.forEach { eventPublisher.runConfigurationRemoved(it) } changedSettings.forEach { eventPublisher.runConfigurationChanged(it, null) } } @TestOnly fun getTemplateIdToConfiguration(): Map<String, RunnerAndConfigurationSettingsImpl> { if (!ApplicationManager.getApplication().isUnitTestMode) { throw IllegalStateException("test only") } return templateIdToConfiguration } } @State(name = "ProjectRunConfigurationManager") internal class IprRunManagerImpl(private val project: Project) : PersistentStateComponent<Element> { val lastLoadedState = AtomicReference<Element>() override fun getState(): Element? { val iprProvider = RunManagerImpl.getInstanceImpl(project).schemeManagerIprProvider ?: return null val result = Element("state") iprProvider.writeState(result) return result } override fun loadState(state: Element) { lastLoadedState.set(state) } } private fun getNameWeight(n1: String) = if (n1.startsWith("<template> of ") || n1.startsWith("_template__ ")) 0 else 1 internal fun doGetBeforeRunTasks(configuration: RunConfiguration): List<BeforeRunTask<*>> { return when (configuration) { is WrappingRunConfiguration<*> -> doGetBeforeRunTasks(configuration.peer) else -> configuration.beforeRunTasks } } internal fun RunConfiguration.cloneBeforeRunTasks() { beforeRunTasks = doGetBeforeRunTasks(this).mapSmart { it.clone() } } fun callNewConfigurationCreated(factory: ConfigurationFactory, configuration: RunConfiguration) { @Suppress("UNCHECKED_CAST", "DEPRECATION") (factory as? ConfigurationFactoryEx<RunConfiguration>)?.onNewConfigurationCreated(configuration) (configuration as? ConfigurationCreationListener)?.onNewConfigurationCreated() } private fun getFactoryKey(factory: ConfigurationFactory): String { return when { factory.type is SimpleConfigurationType -> factory.type.id else -> "${factory.type.id}.${factory.id}" } }
apache-2.0
2dbc3e7c3dbb65cb5087f9d1fc7f560c
33.731818
185
0.685931
5.483709
false
true
false
false
theapache64/Mock-API
src/com/theah64/mock_api/servlets/GetResponseServlet.kt
1
2122
package com.theah64.mock_api.servlets import com.theah64.mock_api.database.Responses import com.theah64.mock_api.database.Routes import com.theah64.mock_api.utils.APIResponse import com.theah64.webengine.database.querybuilders.QueryBuilderException import com.theah64.webengine.utils.PathInfo import com.theah64.webengine.utils.Request import org.json.JSONException import org.json.JSONObject import javax.servlet.annotation.WebServlet import java.io.IOException import java.sql.SQLException @WebServlet(urlPatterns = ["/v1/get_response"]) class GetResponseServlet : AdvancedBaseServlet() { override val isSecureServlet: Boolean get() = true override val requiredParameters: Array<String>? get() = arrayOf(Responses.COLUMN_ID, KEY_ROUTE_NAME, KEY_PROJECT_NAME) @Throws(Request.RequestException::class, IOException::class, JSONException::class, SQLException::class, Request.RequestException::class, PathInfo.PathInfoException::class, QueryBuilderException::class) override fun doAdvancedPost() { val responseId = getStringParameter(Responses.COLUMN_ID)!! val resp: String? if (responseId == Routes.COLUMN_DEFAULT_RESPONSE) { val routeName = getStringParameter(KEY_ROUTE_NAME)!! val projectName = getStringParameter(KEY_PROJECT_NAME)!! resp = Routes.instance.get(projectName, routeName)!!.defaultResponse } else { resp = Responses.instance.get( Responses.COLUMN_ID, responseId, Responses.COLUMN_RESPONSE, false ) } if (resp != null) { val joData = JSONObject() joData.put(Responses.COLUMN_ID, responseId) joData.put(Responses.COLUMN_RESPONSE, resp) writer!!.write(APIResponse("OK", joData).response) } else { writer!!.write(APIResponse("Invalid response id").response) } } companion object { private val KEY_ROUTE_NAME = "route_name" private val KEY_PROJECT_NAME = "project_name" } }
apache-2.0
5c3b8f39859aef34ca3a28c66d18a505
32.15625
205
0.672008
4.384298
false
false
false
false
spotify/heroic
heroic-component/src/main/java/com/spotify/heroic/metric/ResultGroup.kt
1
2495
/* * Copyright (c) 2019 Spotify AB. * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"): you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package com.spotify.heroic.metric import com.spotify.heroic.cluster.ClusterShard import com.spotify.heroic.common.Histogram import com.spotify.heroic.common.Series import java.util.* data class ResultGroup( // key-value pairs that act as a lookup key, identifying this result group val key: Map<String, String>, val series: Set<Series>, val group: MetricCollection, /** * The interval in milliseconds for which a sample can be expected. A cadence of 0 indicates * that this value is unknown. */ val cadence: Long ) { companion object { @JvmStatic fun toShardedResultGroup(shard: ClusterShard): (ResultGroup) -> ShardedResultGroup { return { ShardedResultGroup(shard.shard, it.key, it.series, it.group, it.cadence) } } @JvmStatic fun summarize(resultGroups: List<ResultGroup>): MultiSummary { val keySize = Histogram.Builder() val seriesSummarizer = SeriesSetsSummarizer() val dataSize = Histogram.Builder() var cadence = Optional.empty<Long>() resultGroups.forEach { keySize.add(it.key.size.toLong()) seriesSummarizer.add(it.series) dataSize.add(it.group.size().toLong()) cadence = Optional.of(it.cadence) } return MultiSummary(keySize.build(), seriesSummarizer.end(), dataSize.build(), cadence) } } data class MultiSummary( val keySize: Histogram, val series: SeriesSetsSummarizer.Summary, val dataSize: Histogram, val cadence: Optional<Long> ) }
apache-2.0
1123b5d6c8aaa8b5de06c61dff52877a
34.642857
99
0.674148
4.235993
false
false
false
false
dahlstrom-g/intellij-community
plugins/settings-repository/src/actions/SyncAction.kt
1
2240
// 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.settingsRepository.actions import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.project.DumbAwareAction import com.intellij.openapi.project.Project import kotlinx.coroutines.runBlocking import org.jetbrains.settingsRepository.LOG import org.jetbrains.settingsRepository.SyncType import org.jetbrains.settingsRepository.icsManager import org.jetbrains.settingsRepository.icsMessage internal val NOTIFICATION_GROUP = NotificationGroupManager.getInstance().getNotificationGroup("Settings Repository") internal abstract class SyncAction(private val syncType: SyncType) : DumbAwareAction() { override fun update(e: AnActionEvent) { if (ApplicationManager.getApplication().isUnitTestMode) { return } val repositoryManager = icsManager.repositoryManager e.presentation.isEnabledAndVisible = (repositoryManager.isRepositoryExists() && repositoryManager.hasUpstream()) || (syncType == SyncType.MERGE && icsManager.readOnlySourcesManager.repositories.isNotEmpty()) } override fun actionPerformed(event: AnActionEvent) { runBlocking { syncAndNotify(syncType, event.project) } } } private suspend fun syncAndNotify(syncType: SyncType, project: Project?) { try { val message = if (icsManager.syncManager.sync(syncType, project)) { icsMessage("sync.done.message") } else { icsMessage("sync.up.to.date.message") } NOTIFICATION_GROUP.createNotification(message, NotificationType.INFORMATION).notify(project) } catch (e: Exception) { LOG.warn(e) NOTIFICATION_GROUP.createNotification(icsMessage("sync.rejected.title"), e.message ?: icsMessage("sync.internal.error"), NotificationType.ERROR).notify(project) } } internal class MergeAction : SyncAction(SyncType.MERGE) internal class ResetToTheirsAction : SyncAction(SyncType.OVERWRITE_LOCAL) internal class ResetToMyAction : SyncAction(SyncType.OVERWRITE_REMOTE)
apache-2.0
93263ef6aa397e273a9cec9b4eb27872
40.481481
164
0.791964
4.859002
false
false
false
false
securityfirst/Umbrella_android
app/src/main/java/org/secfirst/umbrella/feature/checklist/view/adapter/PathwaysAdapter.kt
1
2473
package org.secfirst.umbrella.feature.checklist.view.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import kotlinx.android.synthetic.main.pathways_item.view.* import org.secfirst.umbrella.R import org.secfirst.umbrella.data.database.checklist.Checklist import org.secfirst.umbrella.data.database.checklist.Dashboard import org.secfirst.umbrella.misc.ITEM_VIEW_TYPE_ITEM class PathwaysAdapter(private val dashboardItems: MutableList<Dashboard.Item>, private val onDashboardItemClicked: (Checklist) -> Unit, private val onChecklistStarClick: (Checklist, Int) -> Unit) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { override fun getItemCount() = dashboardItems.size fun removeAt(position: Int) { dashboardItems.removeAt(position) notifyItemRemoved(position) notifyDataSetChanged() } fun getPathways(position: Int) = dashboardItems[position].checklist override fun getItemViewType(position: Int) = ITEM_VIEW_TYPE_ITEM override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.pathways_item, parent, false) return PathwaysHolder(view) } override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) { holder as PathwaysHolder holder.bind(dashboardItems[position], clickListener = { onDashboardItemClicked(dashboardItems[position].checklist!!) }, starListener = { onChecklistStarClick(dashboardItems[position].checklist!!, position) }) } class PathwaysHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { fun bind(dashboardItem: Dashboard.Item, clickListener: (PathwaysHolder) -> Unit, starListener: (PathwaysHolder) -> Unit) { with(dashboardItem) { if (dashboardItem.checklist!!.favorite) itemView.star.setImageResource(R.drawable.ic_star_selected) else itemView.star.setImageResource(R.drawable.ic_star_border) itemView.pathwaysLabel.text = label itemView.setOnClickListener { clickListener(this@PathwaysHolder) } itemView.pathwaysStar.setOnClickListener { starListener(this@PathwaysHolder) } } } } }
gpl-3.0
07fa539860837e8f90cc56d2fdaf796c
42.403509
133
0.706834
4.710476
false
false
false
false
subhalaxmin/Programming-Kotlin
Chapter07/src/main/kotlin/com/packt/chapter2/smartcasts.kt
4
569
package com.packt.chapter2 fun printStringLength(any: Any) { if (any is String) { println(any.length) } } fun isString(any: Any): Boolean { return if (any is String) true else false } fun isEmptyString(any: Any): Boolean { return any is String && any.length == 0 } fun isNotStringOrEmpty(any: Any): Boolean { return any !is String || any.length == 0 } fun length(any: Any): Int { val string = any as String return string.length } fun safeCast() { val any = "/home/users" val string: String? = any as String val file: File? = any as File }
mit
1ce271abc9ef7d9d837310a3cdb3f5c3
17.387097
43
0.666081
3.232955
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/sns/src/main/kotlin/com/kotlin/sns/SubscribeEmail.kt
1
1929
// snippet-sourcedescription:[SubscribeEmail.kt demonstrates how to subscribe to an Amazon Simple Notification Service (Amazon SNS) email endpoint.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-keyword:[Amazon Simple Notification Service] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.kotlin.sns // snippet-start:[sns.kotlin.SubscribeEmail.import] import aws.sdk.kotlin.services.sns.SnsClient import aws.sdk.kotlin.services.sns.model.SubscribeRequest import kotlin.system.exitProcess // snippet-end:[sns.kotlin.SubscribeEmail.import] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html */ suspend fun main(args: Array<String>) { val usage = """ Usage: SubscribeEmail <topicArn> <email> Where: topicArn - The ARN of the topic to subscribe. email - The email address to use. """ if (args.size != 2) { println(usage) exitProcess(0) } val topicArn = args[0] val email = args[1] val subscriptionArn = subEmail(topicArn, email) println("Subscription ARN is $subscriptionArn") } // snippet-start:[sns.kotlin.SubscribeEmail.main] suspend fun subEmail(topicArnVal: String, email: String): String { val request = SubscribeRequest { protocol = "email" endpoint = email returnSubscriptionArn = true topicArn = topicArnVal } SnsClient { region = "us-east-1" }.use { snsClient -> val result = snsClient.subscribe(request) return result.subscriptionArn.toString() } } // snippet-end:[sns.kotlin.SubscribeEmail.main]
apache-2.0
b09c8644cae9625c7eb1b71fb816c329
29.112903
148
0.673924
4.02714
false
false
false
false
MGaetan89/ShowsRage
app/src/test/kotlin/com/mgaetan89/showsrage/fragment/AddShowOptionsFragment_GetStatusTest.kt
1
2211
package com.mgaetan89.showsrage.fragment import android.content.res.Resources import android.support.v4.app.Fragment import android.support.v4.app.FragmentActivity import android.widget.Spinner import com.mgaetan89.showsrage.EmptyFragmentHostCallback import com.mgaetan89.showsrage.R import org.assertj.core.api.Assertions.assertThat import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import org.mockito.Mockito.`when` import org.mockito.Mockito.mock import org.mockito.Mockito.spy @RunWith(Parameterized::class) class AddShowOptionsFragment_GetStatusTest(val spinner: Spinner?, val status: String?) { private lateinit var fragment: AddShowOptionsFragment @Before fun before() { val resources = mock(Resources::class.java) `when`(resources.getStringArray(R.array.status_keys)).thenReturn(arrayOf("wanted", "skipped", "archived", "ignored")) val activity = mock(FragmentActivity::class.java) `when`(activity.resources).thenReturn(resources) this.fragment = spy(AddShowOptionsFragment()) try { val fragmentHostField = Fragment::class.java.getDeclaredField("mHost") fragmentHostField.isAccessible = true fragmentHostField.set(this.fragment, EmptyFragmentHostCallback(activity)) } catch (ignored: IllegalAccessException) { } catch (ignored: NoSuchFieldException) { } `when`(this.fragment.resources).thenReturn(resources) } @Test fun getStatus() { assertThat(this.fragment.getStatus(this.spinner)).isEqualTo(this.status) } companion object { @JvmStatic @Parameterized.Parameters fun data(): Collection<Array<Any?>> { return listOf( arrayOf<Any?>(null, "wanted"), arrayOf<Any?>(getMockedSpinner(-1), null), arrayOf<Any?>(getMockedSpinner(0), "wanted"), arrayOf<Any?>(getMockedSpinner(1), "skipped"), arrayOf<Any?>(getMockedSpinner(2), "archived"), arrayOf<Any?>(getMockedSpinner(3), "ignored"), arrayOf<Any?>(getMockedSpinner(4), null) ) } private fun getMockedSpinner(selectedItemPosition: Int): Spinner { val spinner = mock(Spinner::class.java) `when`(spinner.selectedItemPosition).thenReturn(selectedItemPosition) return spinner } } }
apache-2.0
682bb7ac5a8a25ab5df43808cad8c1a4
30.585714
119
0.75848
3.741117
false
false
false
false
google/intellij-community
plugins/kotlin/completion/impl-k1/src/org/jetbrains/kotlin/idea/completion/CompletionSession.kt
2
21372
// 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.completion import com.intellij.codeInsight.completion.CompletionParameters import com.intellij.codeInsight.completion.CompletionResultSet import com.intellij.codeInsight.completion.CompletionSorter import com.intellij.codeInsight.completion.CompletionUtil import com.intellij.codeInsight.completion.impl.CamelHumpMatcher import com.intellij.codeInsight.completion.impl.RealPrefixMatchingWeigher import com.intellij.codeInsight.lookup.LookupElement import com.intellij.openapi.progress.ProcessCanceledException import com.intellij.patterns.PatternCondition import com.intellij.patterns.StandardPatterns import com.intellij.psi.search.GlobalSearchScope import com.intellij.util.ProcessingContext import org.jetbrains.kotlin.base.analysis.isExcludedFromAutoImport import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.ModuleOrigin import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfo.OriginCapability import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade import org.jetbrains.kotlin.idea.caches.resolve.util.getResolveScope import org.jetbrains.kotlin.idea.codeInsight.ReferenceVariantsHelper import org.jetbrains.kotlin.idea.core.* import org.jetbrains.kotlin.idea.core.util.CodeFragmentUtils import org.jetbrains.kotlin.idea.imports.importableFqName import org.jetbrains.kotlin.idea.references.mainReference import org.jetbrains.kotlin.idea.util.* import org.jetbrains.kotlin.platform.isMultiPlatform import org.jetbrains.kotlin.platform.jvm.isJvm import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.ImportPath import org.jetbrains.kotlin.resolve.descriptorUtil.module import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker import org.jetbrains.kotlin.types.typeUtil.isUnit import org.jetbrains.kotlin.types.typeUtil.makeNotNullable class CompletionSessionConfiguration( val useBetterPrefixMatcherForNonImportedClasses: Boolean, val nonAccessibleDeclarations: Boolean, val javaGettersAndSetters: Boolean, val javaClassesNotToBeUsed: Boolean, val staticMembers: Boolean, val dataClassComponentFunctions: Boolean ) fun CompletionSessionConfiguration(parameters: CompletionParameters) = CompletionSessionConfiguration( useBetterPrefixMatcherForNonImportedClasses = parameters.invocationCount < 2, nonAccessibleDeclarations = parameters.invocationCount >= 2, javaGettersAndSetters = parameters.invocationCount >= 2, javaClassesNotToBeUsed = parameters.invocationCount >= 2, staticMembers = parameters.invocationCount >= 2, dataClassComponentFunctions = parameters.invocationCount >= 2 ) abstract class CompletionSession( protected val configuration: CompletionSessionConfiguration, originalParameters: CompletionParameters, resultSet: CompletionResultSet ) { init { CompletionBenchmarkSink.instance.onCompletionStarted(this) } protected val parameters = run { val fixedPosition = addParamTypesIfNeeded(originalParameters.position) originalParameters.withPosition(fixedPosition, fixedPosition.textOffset) } protected val toFromOriginalFileMapper = ToFromOriginalFileMapper.create(this.parameters) protected val position = this.parameters.position protected val file = position.containingFile as KtFile protected val resolutionFacade = file.getResolutionFacade() protected val moduleDescriptor = resolutionFacade.moduleDescriptor protected val project = position.project protected val isJvmModule = moduleDescriptor.platform.isJvm() protected val allowExpectedDeclarations = moduleDescriptor.platform.isMultiPlatform() protected val isDebuggerContext = file is KtCodeFragment protected val nameExpression: KtSimpleNameExpression? protected val expression: KtExpression? init { val reference = (position.parent as? KtSimpleNameExpression)?.mainReference if (reference != null) { if (reference.expression is KtLabelReferenceExpression) { this.nameExpression = null this.expression = reference.expression.parent.parent as? KtExpressionWithLabel } else { this.nameExpression = reference.expression this.expression = nameExpression } } else { this.nameExpression = null this.expression = null } } protected val bindingContext = CompletionBindingContextProvider.getInstance(project).getBindingContext(position, resolutionFacade) protected val inDescriptor = position.getResolutionScope(bindingContext, resolutionFacade).ownerDescriptor private val kotlinIdentifierStartPattern = StandardPatterns.character().javaIdentifierStart().andNot(singleCharPattern('$')) private val kotlinIdentifierPartPattern = StandardPatterns.character().javaIdentifierPart().andNot(singleCharPattern('$')) protected val prefix = CompletionUtil.findIdentifierPrefix( originalParameters.position.containingFile, originalParameters.offset, kotlinIdentifierPartPattern or singleCharPattern('@'), kotlinIdentifierStartPattern ) protected val prefixMatcher = CamelHumpMatcher(prefix) protected val descriptorNameFilter: (String) -> Boolean = prefixMatcher.asStringNameFilter() protected val isVisibleFilter: (DeclarationDescriptor) -> Boolean = { isVisibleDescriptor(it, completeNonAccessible = configuration.nonAccessibleDeclarations) } protected val isVisibleFilterCheckAlways: (DeclarationDescriptor) -> Boolean = { isVisibleDescriptor(it, completeNonAccessible = false) } protected val referenceVariantsHelper = ReferenceVariantsHelper( bindingContext, resolutionFacade, moduleDescriptor, isVisibleFilter, NotPropertiesService.getNotProperties(position) ) protected val shadowedFilter: ((Collection<DeclarationDescriptor>) -> Collection<DeclarationDescriptor>)? by lazy { ShadowedDeclarationsFilter.create( bindingContext = bindingContext, resolutionFacade = resolutionFacade, context = nameExpression!!, callTypeAndReceiver = callTypeAndReceiver, )?.createNonImportedDeclarationsFilter( importedDeclarations = referenceVariantsCollector!!.allCollected.imported, allowExpectedDeclarations = allowExpectedDeclarations, ) } protected inline fun <reified T : DeclarationDescriptor> processWithShadowedFilter(descriptor: T, processor: (T) -> Unit) { val shadowedFilter = shadowedFilter val element = if (shadowedFilter != null) { shadowedFilter(listOf(descriptor)).singleOrNull()?.let { it as T } } else { descriptor } element?.let(processor) } protected val callTypeAndReceiver = if (nameExpression == null) CallTypeAndReceiver.UNKNOWN else CallTypeAndReceiver.detect(nameExpression) protected val receiverTypes = nameExpression?.let { detectReceiverTypes(bindingContext, nameExpression, callTypeAndReceiver) } protected val basicLookupElementFactory = BasicLookupElementFactory(project, InsertHandlerProvider(callTypeAndReceiver.callType, parameters.editor) { expectedInfos }) // LookupElementsCollector instantiation is deferred because virtual call to createSorter uses data from derived classes protected val collector: LookupElementsCollector by lazy(LazyThreadSafetyMode.NONE) { LookupElementsCollector( { CompletionBenchmarkSink.instance.onFlush(this) }, prefixMatcher, originalParameters, resultSet, createSorter(), (file as? KtCodeFragment)?.extraCompletionFilter, allowExpectedDeclarations, ) } protected val searchScope: GlobalSearchScope = getResolveScope(originalParameters.originalFile as KtFile) protected fun indicesHelper(mayIncludeInaccessible: Boolean): KotlinIndicesHelper { val filter = if (mayIncludeInaccessible) isVisibleFilter else isVisibleFilterCheckAlways return KotlinIndicesHelper( resolutionFacade, searchScope, filter, filterOutPrivate = !mayIncludeInaccessible, declarationTranslator = { toFromOriginalFileMapper.toSyntheticFile(it) }, file = file ) } private fun isVisibleDescriptor(descriptor: DeclarationDescriptor, completeNonAccessible: Boolean): Boolean { if (!configuration.javaClassesNotToBeUsed && descriptor is ClassDescriptor) { if (descriptor.importableFqName?.isJavaClassNotToBeUsedInKotlin() == true) return false } if (descriptor is TypeParameterDescriptor && !isTypeParameterVisible(descriptor)) return false if (descriptor is DeclarationDescriptorWithVisibility) { val visible = descriptor.isVisible(position, callTypeAndReceiver.receiver as? KtExpression, bindingContext, resolutionFacade) if (visible) return true return completeNonAccessible && (!descriptor.isFromLibrary() || isDebuggerContext) } val fqName = descriptor.importableFqName if (fqName != null && fqName.isExcludedFromAutoImport(project, file)) return false return true } private fun DeclarationDescriptor.isFromLibrary(): Boolean { if (module.getCapability(OriginCapability) == ModuleOrigin.LIBRARY) return true if (this is CallableMemberDescriptor && kind == CallableMemberDescriptor.Kind.FAKE_OVERRIDE) { return overriddenDescriptors.all { it.isFromLibrary() } } return false } private fun isTypeParameterVisible(typeParameter: TypeParameterDescriptor): Boolean { val owner = typeParameter.containingDeclaration var parent: DeclarationDescriptor? = inDescriptor while (parent != null) { if (parent == owner) return true if (parent is ClassDescriptor && !parent.isInner) return false parent = parent.containingDeclaration } return true } protected fun flushToResultSet() { collector.flushToResultSet() } fun complete(): Boolean { return try { _complete().also { CompletionBenchmarkSink.instance.onCompletionEnded(this, false) } } catch (pce: ProcessCanceledException) { CompletionBenchmarkSink.instance.onCompletionEnded(this, true) throw pce } } private fun _complete(): Boolean { // we restart completion when prefix becomes "get" or "set" to ensure that properties get lower priority comparing to get/set functions (see KT-12299) val prefixPattern = StandardPatterns.string().with(object : PatternCondition<String>("get or set prefix") { override fun accepts(prefix: String, context: ProcessingContext?) = prefix == "get" || prefix == "set" }) collector.restartCompletionOnPrefixChange(prefixPattern) val statisticsContext = calcContextForStatisticsInfo() if (statisticsContext != null) { collector.addLookupElementPostProcessor { lookupElement -> // we should put data into the original element because of DecoratorCompletionStatistician lookupElement.putUserDataDeep(STATISTICS_INFO_CONTEXT_KEY, statisticsContext) lookupElement } } doComplete() flushToResultSet() return !collector.isResultEmpty } fun addLookupElementPostProcessor(processor: (LookupElement) -> LookupElement) { collector.addLookupElementPostProcessor(processor) } protected abstract fun doComplete() protected abstract val descriptorKindFilter: DescriptorKindFilter? protected abstract val expectedInfos: Collection<ExpectedInfo> protected val importableFqNameClassifier = ImportableFqNameClassifier(file) { ImportInsertHelper.getInstance(file.project).isImportedWithDefault(ImportPath(it, false), file) } protected open fun createSorter(): CompletionSorter { var sorter = CompletionSorter.defaultSorter(parameters, prefixMatcher)!! sorter = sorter.weighBefore( "stats", DeprecatedWeigher, PriorityWeigher, PreferGetSetMethodsToPropertyWeigher, NotImportedWeigher(importableFqNameClassifier), NotImportedStaticMemberWeigher(importableFqNameClassifier), KindWeigher, CallableWeigher ) sorter = sorter.weighAfter("stats", VariableOrFunctionWeigher, ImportedWeigher(importableFqNameClassifier)) val preferContextElementsWeigher = PreferContextElementsWeigher(inDescriptor) sorter = if (callTypeAndReceiver is CallTypeAndReceiver.SUPER_MEMBERS) { // for completion after "super." strictly prefer the current member sorter.weighBefore("kotlin.deprecated", preferContextElementsWeigher) } else { sorter.weighBefore("kotlin.proximity", preferContextElementsWeigher) } sorter = sorter.weighBefore("middleMatching", PreferMatchingItemWeigher) // we insert one more RealPrefixMatchingWeigher because one inserted in default sorter is placed in a bad position (after "stats") sorter = sorter.weighAfter("lift.shorter", RealPrefixMatchingWeigher()) sorter = sorter.weighAfter("kotlin.proximity", ByNameAlphabeticalWeigher, PreferLessParametersWeigher) sorter = sorter.weighBefore("prefix", KotlinUnwantedLookupElementWeigher) sorter = if (expectedInfos.all { it.fuzzyType?.type?.isUnit() == true }) { sorter.weighBefore("prefix", PreferDslMembers) } else { sorter.weighAfter("kotlin.preferContextElements", PreferDslMembers) } return sorter } protected fun calcContextForStatisticsInfo(): String? { if (expectedInfos.isEmpty()) return null var context = expectedInfos .mapNotNull { it.fuzzyType?.type?.constructor?.declarationDescriptor?.importableFqName } .distinct() .singleOrNull() ?.let { "expectedType=$it" } if (context == null) { context = expectedInfos .mapNotNull { it.expectedName } .distinct() .singleOrNull() ?.let { "expectedName=$it" } } return context } protected val referenceVariantsCollector = if (nameExpression != null) { ReferenceVariantsCollector( referenceVariantsHelper = referenceVariantsHelper, indicesHelper = indicesHelper(true), prefixMatcher = prefixMatcher, nameExpression = nameExpression, callTypeAndReceiver = callTypeAndReceiver, resolutionFacade = resolutionFacade, bindingContext = bindingContext, importableFqNameClassifier = importableFqNameClassifier, configuration = configuration, allowExpectedDeclarations = allowExpectedDeclarations, ) } else { null } protected fun ReferenceVariants.excludeNonInitializedVariable(): ReferenceVariants { return ReferenceVariants(referenceVariantsHelper.excludeNonInitializedVariable(imported, position), notImportedExtensions) } protected fun referenceVariantsWithSingleFunctionTypeParameter(): ReferenceVariants? { val variants = referenceVariantsCollector?.allCollected ?: return null val filter = { descriptor: DeclarationDescriptor -> descriptor is FunctionDescriptor && LookupElementFactory.hasSingleFunctionTypeParameter(descriptor) } return ReferenceVariants(variants.imported.filter(filter), variants.notImportedExtensions.filter(filter)) } protected fun getRuntimeReceiverTypeReferenceVariants(lookupElementFactory: LookupElementFactory): Pair<ReferenceVariants, LookupElementFactory>? { val evaluator = file.getCopyableUserData(CodeFragmentUtils.RUNTIME_TYPE_EVALUATOR) ?: return null val referenceVariants = referenceVariantsCollector?.allCollected ?: return null val explicitReceiver = callTypeAndReceiver.receiver as? KtExpression ?: return null val type = bindingContext.getType(explicitReceiver) ?: return null if (!TypeUtils.canHaveSubtypes(KotlinTypeChecker.DEFAULT, type)) return null val runtimeType = evaluator(explicitReceiver) if (runtimeType == null || runtimeType == type) return null val expressionReceiver = ExpressionReceiver.create(explicitReceiver, runtimeType, bindingContext) val (variants, notImportedExtensions) = ReferenceVariantsCollector( referenceVariantsHelper = referenceVariantsHelper, indicesHelper = indicesHelper(true), prefixMatcher = prefixMatcher, nameExpression = nameExpression!!, callTypeAndReceiver = callTypeAndReceiver, resolutionFacade = resolutionFacade, bindingContext = bindingContext, importableFqNameClassifier = importableFqNameClassifier, configuration = configuration, allowExpectedDeclarations = allowExpectedDeclarations, runtimeReceiver = expressionReceiver, ).collectReferenceVariants(descriptorKindFilter!!) val filteredVariants = filterVariantsForRuntimeReceiverType(variants, referenceVariants.imported) val filteredNotImportedExtensions = filterVariantsForRuntimeReceiverType(notImportedExtensions, referenceVariants.notImportedExtensions) val runtimeVariants = ReferenceVariants(filteredVariants, filteredNotImportedExtensions) return Pair(runtimeVariants, lookupElementFactory.copy(receiverTypes = listOf(ReceiverType(runtimeType, 0)))) } private fun <TDescriptor : DeclarationDescriptor> filterVariantsForRuntimeReceiverType( runtimeVariants: Collection<TDescriptor>, baseVariants: Collection<TDescriptor> ): Collection<TDescriptor> { val baseVariantsByName = baseVariants.groupBy { it.name } val result = ArrayList<TDescriptor>() for (variant in runtimeVariants) { val candidates = baseVariantsByName[variant.name] if (candidates == null || candidates.none { compareDescriptors(project, variant, it) }) { result.add(variant) } } return result } protected open fun shouldCompleteTopLevelCallablesFromIndex(): Boolean { if (nameExpression == null) return false if ((descriptorKindFilter?.kindMask ?: 0).and(DescriptorKindFilter.CALLABLES_MASK) == 0) return false if (callTypeAndReceiver is CallTypeAndReceiver.IMPORT_DIRECTIVE) return false return callTypeAndReceiver.receiver == null } protected fun processTopLevelCallables(processor: (DeclarationDescriptor) -> Unit) { indicesHelper(true).processTopLevelCallables({ prefixMatcher.prefixMatches(it) }) { processWithShadowedFilter(it, processor) } } protected fun withCollectRequiredContextVariableTypes(action: (LookupElementFactory) -> Unit): Collection<FuzzyType> { val provider = CollectRequiredTypesContextVariablesProvider() val lookupElementFactory = createLookupElementFactory(provider) action(lookupElementFactory) return provider.requiredTypes } protected fun withContextVariablesProvider(contextVariablesProvider: ContextVariablesProvider, action: (LookupElementFactory) -> Unit) { val lookupElementFactory = createLookupElementFactory(contextVariablesProvider) action(lookupElementFactory) } protected open fun createLookupElementFactory(contextVariablesProvider: ContextVariablesProvider): LookupElementFactory { return LookupElementFactory( basicLookupElementFactory, parameters.editor, receiverTypes, callTypeAndReceiver.callType, inDescriptor, contextVariablesProvider ) } protected fun detectReceiverTypes( bindingContext: BindingContext, nameExpression: KtSimpleNameExpression, callTypeAndReceiver: CallTypeAndReceiver<*, *> ): List<ReceiverType>? { var receiverTypes = callTypeAndReceiver.receiverTypesWithIndex( bindingContext, nameExpression, moduleDescriptor, resolutionFacade, stableSmartCastsOnly = true, /* we don't include smart cast receiver types for "unstable" receiver value to mark members grayed */ withImplicitReceiversWhenExplicitPresent = true ) if (callTypeAndReceiver is CallTypeAndReceiver.SAFE || isDebuggerContext) { receiverTypes = receiverTypes?.map { ReceiverType(it.type.makeNotNullable(), it.receiverIndex) } } return receiverTypes } }
apache-2.0
13287f78b367d949d29661be42e5798d
44.96129
158
0.729178
6.040701
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/EvaluateCompileTimeExpressionIntention.kt
1
3302
// 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.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.util.text.StringUtil import org.jetbrains.kotlin.KtNodeTypes import org.jetbrains.kotlin.idea.base.resources.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingOffsetIndependentIntention import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.kotlin.resolve.calls.util.getType import org.jetbrains.kotlin.resolve.constants.evaluate.ConstantExpressionEvaluator import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode class EvaluateCompileTimeExpressionIntention : SelfTargetingOffsetIndependentIntention<KtBinaryExpression>( KtBinaryExpression::class.java, KotlinBundle.lazyMessage("evaluate.compile.time.expression") ) { companion object { val constantNodeTypes = listOf(KtNodeTypes.FLOAT_CONSTANT, KtNodeTypes.CHARACTER_CONSTANT, KtNodeTypes.INTEGER_CONSTANT) } override fun isApplicableTo(element: KtBinaryExpression): Boolean { if (element.getStrictParentOfType<KtBinaryExpression>() != null || !element.isConstantExpression()) return false val constantValue = element.getConstantValue() ?: return false setTextGetter { KotlinBundle.message("replace.with.0", constantValue) } return true } override fun applyTo(element: KtBinaryExpression, editor: Editor?) { val constantValue = element.getConstantValue() ?: return element.replace(KtPsiFactory(element.project).createExpression(constantValue)) } private fun KtExpression?.isConstantExpression(): Boolean { return when (val expression = KtPsiUtil.deparenthesize(this)) { is KtConstantExpression -> expression.elementType in constantNodeTypes is KtPrefixExpression -> expression.baseExpression.isConstantExpression() is KtBinaryExpression -> expression.left.isConstantExpression() && expression.right.isConstantExpression() else -> false } } private fun KtBinaryExpression.getConstantValue(): String? { val context = analyze(BodyResolveMode.PARTIAL) val type = getType(context) ?: return null val constantValue = ConstantExpressionEvaluator.getConstant(this, context)?.toConstantValue(type) ?: return null return when (val value = constantValue.value) { is Char -> "'${StringUtil.escapeStringCharacters(value.toString())}'" is Long -> "${value}L" is Float -> when { value.isNaN() -> "Float.NaN" value.isInfinite() -> if (value > 0.0f) "Float.POSITIVE_INFINITY" else "Float.NEGATIVE_INFINITY" else -> "${value}f" } is Double -> when { value.isNaN() -> "Double.NaN" value.isInfinite() -> if (value > 0.0) "Double.POSITIVE_INFINITY" else "Double.NEGATIVE_INFINITY" else -> value.toString() } else -> value.toString() } } }
apache-2.0
a38c6f56ed6167eecf18aebe8f8543eb
49.030303
158
0.709267
5.103555
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/idea/tests/testData/inspections/dfa/Suppressions.kt
1
2682
// WITH_STDLIB fun returnInReturn(a: Boolean, b: Boolean): Boolean { // KTIJ-23768 return a || return b } fun assertCall(x: Int, b: Boolean, c: Boolean) { if (x < 0) return if (Math.random() > 0.5) { assert(x >= 0) } if (Math.random() > 0.5) { assert(b && x >= 0) } if (Math.random() > 0.5) { assert(b || x >= 0) } if (Math.random() > 0.5) { assert(<warning descr="Condition 'c && !(b || x >= 0)' is always false">c && <warning descr="Condition '!(b || x >= 0)' is always false when reached">!(b || <warning descr="Condition 'x >= 0' is always true when reached">x >= 0</warning>)</warning></warning>) } if (Math.random() > 0.5) { assert(c && !(b || x < 0)) } if (Math.random() > 0.5) { assert(<warning descr="Condition 'x < 0' is always false">x < 0</warning>) } } fun requireCall(x: Int) { if (x < 0) return require(x >= 0) require(<warning descr="Condition 'x < 0' is always false">x < 0</warning>) } fun compilerWarningSuppression() { val x: Int = 1 @Suppress("SENSELESS_COMPARISON") if (x == null) {} } fun compilerWarningDuplicate(x : Int) { // Reported as a compiler warning: suppress if (<warning descr="[SENSELESS_COMPARISON] Condition 'x != null' is always 'true'">x != null</warning>) { } } fun compilerWarningDuplicateWhen(x : X) { // Reported as a compiler warning: suppress when (x) { <warning descr="[USELESS_IS_CHECK] Check for instance is always 'true'">is X</warning> -> {} } } fun nothingOrNull(s: String?): String? { return s?.let { if (it.isEmpty()) return null return s } } fun nothingOrNullToElvis(s: String?): Boolean { return s?.let { if (it.isEmpty()) return false return s.hashCode() < 0 } ?: false } // f.get() always returns null but it's inevitable: we cannot return anything else, hence suppress the warning fun alwaysNull(f : MyFuture<Void>) = f.get() fun unusedResult(x: Int) { // Whole condition is always true but reporting it is not very useful x > 0 || return } interface MyFuture<T> { fun get():T? } class X fun updateChain(b: Boolean, c: Boolean): Int { var x = 0 if (b) x = x or 1 if (c) x = x or 2 return x } fun updateChainBoolean(b: Boolean, c: Boolean): Boolean { var x = false x = x || b x = x || c return x } fun updateChainInterrupted(b: Boolean, c: Boolean): Int { var x = 0 x++ <warning descr="Value of 'x--' is always zero">x--</warning> if (b) x = <weak_warning descr="Value of 'x' is always zero">x</weak_warning> or 1 if (c) x = x or 2 return x }
apache-2.0
7f44615dafbbcaed05629765973e3329
28.472527
267
0.579791
3.278729
false
false
false
false
java-graphics/assimp
src/main/kotlin/assimp/format/blender/BlenderModifier.kt
2
8005
/* Open Asset Import Library (assimp) ---------------------------------------------------------------------- Copyright (c) 2006-2018, assimp team All rights reserved. Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the assimp team, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission of the assimp team. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ---------------------------------------------------------------------- */ package assimp.format.blender import assimp.AiNode // ------------------------------------------------------------------------------------------- /** Dummy base class for all blender modifiers. Modifiers are reused between imports, so * they should be stateless and not try to cache model data. */ // ------------------------------------------------------------------------------------------- // class BlenderModifier // { // public: // virtual ~BlenderModifier() { // // empty // } // // public: // // // -------------------- // /** Check if *this* modifier is active, given a ModifierData& block.*/ // virtual bool IsActive( const ModifierData& /*modin*/) { // return false; // } // // // -------------------- // /** Apply the modifier to a given output node. The original data used // * to construct the node is given as well. Not called unless IsActive() // * was called and gave positive response. */ // virtual void DoIt(aiNode& /*out*/, // ConversionData& /*conv_data*/, // const ElemBase& orig_modifier, // const Scene& /*in*/, // const Object& /*orig_object*/ // ) { // DefaultLogger::get()->warn((Formatter::format("This modifier is not supported, skipping: "),orig_modifier.dna_type)); // return; // } // }; class SharedModifierData : ElemBase() { var modifier = ModifierData() } /** Manage all known modifiers and instance and apply them if necessary */ class BlenderModifierShowcase { /** Apply all requested modifiers provided we support them. */ fun applyModifiers(out: AiNode, convData: ConversionData, in_: Scene , origObject: Object) { var cnt = 0L var ful = 0L /* NOTE: this cast is potentially unsafe by design, so we need to perform type checks before we're allowed to dereference the pointers without risking to crash. We might still be invoking UB btw - we're assuming that the ModifierData member of the respective modifier structures is at offset sizeof(vftable) with no padding. */ var cur = origObject.modifiers?.first as? SharedModifierData var begin = true while(cur != null) { if(!begin) { cur = cur.modifier.next as? SharedModifierData ++ful } begin = false assert(cur!!.dnaType.isNotEmpty()) // TODO("apply Modifiers") // val s = convData.db.dna.Get( cur->dna_type ) // if (!s) { // ASSIMP_LOG_WARN_F("BlendModifier: could not resolve DNA name: ",cur->dna_type) // continue // } // // // this is a common trait of all XXXMirrorData structures in BlenderDNA // const Field* f = s->Get("modifier") // if (!f || f->offset != 0) { // ASSIMP_LOG_WARN("BlendModifier: expected a `modifier` member at offset 0") // continue // } // // s = conv_data.db.dna.Get( f->type ) // if (!s || s->name != "ModifierData") { // ASSIMP_LOG_WARN("BlendModifier: expected a ModifierData structure as first member") // continue // } // // // now, we can be sure that we should be fine to dereference *cur* as // // ModifierData (with the above note). // const ModifierData& dat = cur->modifier // // const fpCreateModifier* curgod = creators // std::vector< BlenderModifier* >::iterator curmod = cached_modifiers->begin(), endmod = cached_modifiers->end() // // for (;*curgod;++curgod,++curmod) { // allocate modifiers on the fly // if (curmod == endmod) { // cached_modifiers->pushBack((*curgod)()) // // endmod = cached_modifiers->end() // curmod = endmod-1 // } // // BlenderModifier* const modifier = *curmod // if(modifier->IsActive(dat)) { // modifier->DoIt(out,conv_data,*static_cast<const ElemBase *>(cur),in,orig_object) // cnt++ // // curgod = NULL // break // } // } // if (curgod) { // ASSIMP_LOG_WARN_F("Couldn't find a handler for modifier: ",dat.name) // } // } // // // Even though we managed to resolve some or all of the modifiers on this // // object, we still can't say whether our modifier implementations were // // able to fully do their job. // if (ful) { // ASSIMP_LOG_DEBUG_F("BlendModifier: found handlers for ",cnt," of ",ful," modifiers on `",orig_object.id.name, // "`, check log messages above for errors") } } // TempArray< std::vector,BlenderModifier > cached_modifiers } // MODIFIERS // ------------------------------------------------------------------------------------------- /** Mirror modifier. Status: implemented. */ // ------------------------------------------------------------------------------------------- //class BlenderModifier_Mirror : public BlenderModifier //{ // public: // // // -------------------- // virtual bool IsActive(const ModifierData & modin); // // // -------------------- // virtual void DoIt(aiNode& out, // ConversionData& conv_data, // const ElemBase & orig_modifier, // const Scene & in, // const Object & orig_object // ); //}; // //// ------------------------------------------------------------------------------------------- ///** Subdivision modifier. Status: dummy. */ //// ------------------------------------------------------------------------------------------- //class BlenderModifier_Subdivision : public BlenderModifier //{ // public: // // // -------------------- // virtual bool IsActive(const ModifierData & modin); // // // -------------------- // virtual void DoIt(aiNode& out, // ConversionData& conv_data, // const ElemBase & orig_modifier, // const Scene & in, // const Object & orig_object // ); //};
bsd-3-clause
ced4bd72624e4b6bb755a90361d4dcf6
36.764151
131
0.539788
4.512401
false
false
false
false
apollographql/apollo-android
tests/models-response-based/src/commonTest/kotlin/test/TestBuildersTest.kt
1
7017
package test import codegen.models.AllPlanetsQuery import codegen.models.BirthdateQuery import codegen.models.EpisodeQuery import codegen.models.HeroAndFriendsWithTypenameQuery import codegen.models.MergedFieldWithSameShapeQuery import codegen.models.test.AllPlanetsQuery_TestBuilder.Data import codegen.models.test.BirthdateQuery_TestBuilder.Data import codegen.models.test.EpisodeQuery_TestBuilder.Data import codegen.models.test.HeroAndFriendsWithTypenameQuery_TestBuilder.Data import codegen.models.test.MergedFieldWithSameShapeQuery_TestBuilder.Data import codegen.models.type.Date import codegen.models.type.Episode import com.apollographql.apollo3.api.Adapter import com.apollographql.apollo3.annotations.ApolloExperimental import com.apollographql.apollo3.api.CompiledListType import com.apollographql.apollo3.api.CompiledNamedType import com.apollographql.apollo3.api.CompiledNotNullType import com.apollographql.apollo3.api.CompiledType import com.apollographql.apollo3.api.CustomScalarAdapters import com.apollographql.apollo3.api.json.JsonReader import com.apollographql.apollo3.api.json.JsonWriter import com.apollographql.apollo3.api.test.DefaultTestResolver import com.apollographql.apollo3.api.test.TestResolver import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertNull import kotlin.test.fail @OptIn(ApolloExperimental::class) class TestBuildersTest { @Test fun allPlanets() { val data = AllPlanetsQuery.Data { allPlanets = allPlanets { planets = listOf( planet { name = "Tatoine" } ) } } assertEquals("Tatoine", data.allPlanets?.planets?.get(0)?.name) } @Test fun nullIsWorking() { val data = AllPlanetsQuery.Data { allPlanets = null } assertNull(data.allPlanets) } @Test fun typenameMustBeSet() { try { HeroAndFriendsWithTypenameQuery.Data {} fail("An exception was expected") } catch (e: IllegalStateException) { assertEquals("__typename is not known at compile-time for this type. Please specify it explicitely", e.message) } } @Test fun polymorphic() { val data = MergedFieldWithSameShapeQuery.Data { hero = humanHero { property = "Earth" } } val hero = data.hero assertIs<MergedFieldWithSameShapeQuery.Data.HumanHero>(hero) assertEquals("Earth", hero.property) } @Test fun customScalar() { /** * A very simple adapter that simply converts to Long in order to avoid pulling kotlinx.datetime in the classpath */ val adapter = object : Adapter<Long> { override fun fromJson(reader: JsonReader, customScalarAdapters: CustomScalarAdapters): Long { return reader.nextString()!!.toLong() } override fun toJson(writer: JsonWriter, customScalarAdapters: CustomScalarAdapters, value: Long) { TODO("Not yet implemented") } } val data = BirthdateQuery.Data(customScalarAdapters = CustomScalarAdapters.Builder().add(Date.type, adapter).build()) { hero = hero { birthDate = "12345" } } assertEquals(12345L, data.hero?.birthDate) } @Test fun customDefaultTestResolver() { val defaultString = "default" val defaultInt = 5 val defaultFloat = 7.0 val myTestResolver = object : DefaultTestResolver() { override fun resolveListSize(path: List<Any>): Int { return 1 } override fun resolveInt(path: List<Any>): Int { return defaultInt } override fun resolveString(path: List<Any>): String { return defaultString } override fun resolveFloat(path: List<Any>): Double { return defaultFloat } override fun resolveComposite(path: List<Any>, ctors: Array<out () -> Map<String, Any?>>): Map<String, Any?> { return ctors[0]() } } val data = AllPlanetsQuery.Data(testResolver = myTestResolver) {} val expected = AllPlanetsQuery.Data( allPlanets = AllPlanetsQuery.Data.AllPlanets( planets = listOf( AllPlanetsQuery.Data.AllPlanets.Planet( __typename = "Planet", name = defaultString, climates = listOf(defaultString), surfaceWater = defaultFloat, filmConnection = AllPlanetsQuery.Data.AllPlanets.Planet.FilmConnection( totalCount = defaultInt, films = listOf( AllPlanetsQuery.Data.AllPlanets.Planet.FilmConnection.Film( __typename = "Film", title = defaultString, producers = listOf(defaultString) ) ) ) ) ) ) ) assertEquals(expected, data) } @Test fun customTestResolver() { val defaultString = "default" val defaultInt = 5 val defaultFloat = 7.0 val myTestResolver = object : TestResolver { override fun <T> resolve(responseName: String, compiledType: CompiledType, ctors: Array<out () -> Map<String, Any?>>?): T { return when (compiledType) { is CompiledNotNullType -> resolve(responseName, compiledType.ofType, ctors) is CompiledListType -> listOf(resolve<Any>(responseName, compiledType.ofType, ctors)) is CompiledNamedType -> { when (compiledType.name) { "Int" -> defaultInt "Float" -> defaultFloat "String" -> defaultString else -> ctors!![0]() } } } as T } } val data = AllPlanetsQuery.Data(testResolver = myTestResolver) {} val expected = AllPlanetsQuery.Data( allPlanets = AllPlanetsQuery.Data.AllPlanets( planets = listOf( AllPlanetsQuery.Data.AllPlanets.Planet( __typename = "Planet", name = defaultString, climates = listOf(defaultString), surfaceWater = defaultFloat, filmConnection = AllPlanetsQuery.Data.AllPlanets.Planet.FilmConnection( totalCount = defaultInt, films = listOf( AllPlanetsQuery.Data.AllPlanets.Planet.FilmConnection.Film( __typename = "Film", title = defaultString, producers = listOf(defaultString) ) ) ) ) ) ) ) assertEquals(expected, data) } @Test fun enum() { val data = EpisodeQuery.Data { hero = hero { appearsIn = listOf(Episode.JEDI.rawValue) } } assertEquals(Episode.JEDI, data.hero?.appearsIn?.single()) } }
mit
a6243555af1b889975ececc407bb7652
30.751131
129
0.61807
4.562419
false
true
false
false
Kotlin/kotlinx.coroutines
kotlinx-coroutines-core/jvm/src/channels/Actor.kt
1
7435
/* * Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license. */ package kotlinx.coroutines.channels import kotlinx.coroutines.* import kotlinx.coroutines.intrinsics.* import kotlinx.coroutines.selects.* import kotlin.coroutines.* import kotlin.coroutines.intrinsics.* /** * Scope for [actor][GlobalScope.actor] coroutine builder. * * **Note: This API will become obsolete in future updates with introduction of complex actors.** * See [issue #87](https://github.com/Kotlin/kotlinx.coroutines/issues/87). */ @ObsoleteCoroutinesApi public interface ActorScope<E> : CoroutineScope, ReceiveChannel<E> { /** * A reference to the mailbox channel that this coroutine [receives][receive] messages from. * It is provided for convenience, so that the code in the coroutine can refer * to the channel as `channel` as apposed to `this`. * All the [ReceiveChannel] functions on this interface delegate to * the channel instance returned by this function. */ public val channel: Channel<E> } /** * Launches new coroutine that is receiving messages from its mailbox channel * and returns a reference to its mailbox channel as a [SendChannel]. The resulting * object can be used to [send][SendChannel.send] messages to this coroutine. * * The scope of the coroutine contains [ActorScope] interface, which implements * both [CoroutineScope] and [ReceiveChannel], so that coroutine can invoke * [receive][ReceiveChannel.receive] directly. The channel is [closed][SendChannel.close] * when the coroutine completes. * * Coroutine context is inherited from a [CoroutineScope], additional context elements can be specified with [context] argument. * If the context does not have any dispatcher nor any other [ContinuationInterceptor], then [Dispatchers.Default] is used. * The parent job is inherited from a [CoroutineScope] as well, but it can also be overridden * with corresponding [context] element. * * By default, the coroutine is immediately scheduled for execution. * Other options can be specified via `start` parameter. See [CoroutineStart] for details. * An optional [start] parameter can be set to [CoroutineStart.LAZY] to start coroutine _lazily_. In this case, * it will be started implicitly on the first message * [sent][SendChannel.send] to this actors's mailbox channel. * * Uncaught exceptions in this coroutine close the channel with this exception as a cause and * the resulting channel becomes _failed_, so that any attempt to send to such a channel throws exception. * * The kind of the resulting channel depends on the specified [capacity] parameter. * See [Channel] interface documentation for details. * * See [newCoroutineContext][CoroutineScope.newCoroutineContext] for a description of debugging facilities that are available for newly created coroutine. * * ### Using actors * * A typical usage of the actor builder looks like this: * * ``` * val c = actor { * // initialize actor's state * for (msg in channel) { * // process message here * } * } * // send messages to the actor * c.send(...) * ... * // stop the actor when it is no longer needed * c.close() * ``` * * ### Stopping and cancelling actors * * When the inbox channel of the actor is [closed][SendChannel.close] it sends a special "close token" to the actor. * The actor still processes all the messages that were already sent and then "`for (msg in channel)`" loop terminates * and the actor completes. * * If the actor needs to be aborted without processing all the messages that were already sent to it, then * it shall be created with a parent job: * * ``` * val job = Job() * val c = actor(context = job) { ... } * ... * // abort the actor * job.cancel() * ``` * * When actor's parent job is [cancelled][Job.cancel], then actor's job becomes cancelled. It means that * "`for (msg in channel)`" and other cancellable suspending functions throw [CancellationException] and actor * completes without processing remaining messages. * * **Note: This API will become obsolete in future updates with introduction of complex actors.** * See [issue #87](https://github.com/Kotlin/kotlinx.coroutines/issues/87). * * @param context additional to [CoroutineScope.coroutineContext] context of the coroutine. * @param capacity capacity of the channel's buffer (no buffer by default). * @param start coroutine start option. The default value is [CoroutineStart.DEFAULT]. * @param onCompletion optional completion handler for the actor coroutine (see [Job.invokeOnCompletion]) * @param block the coroutine code. */ @ObsoleteCoroutinesApi public fun <E> CoroutineScope.actor( context: CoroutineContext = EmptyCoroutineContext, capacity: Int = 0, // todo: Maybe Channel.DEFAULT here? start: CoroutineStart = CoroutineStart.DEFAULT, onCompletion: CompletionHandler? = null, block: suspend ActorScope<E>.() -> Unit ): SendChannel<E> { val newContext = newCoroutineContext(context) val channel = Channel<E>(capacity) val coroutine = if (start.isLazy) LazyActorCoroutine(newContext, channel, block) else ActorCoroutine(newContext, channel, active = true) if (onCompletion != null) coroutine.invokeOnCompletion(handler = onCompletion) coroutine.start(start, coroutine, block) return coroutine } private open class ActorCoroutine<E>( parentContext: CoroutineContext, channel: Channel<E>, active: Boolean ) : ChannelCoroutine<E>(parentContext, channel, initParentJob = false, active = active), ActorScope<E> { init { initParentJob(parentContext[Job]) } override fun onCancelling(cause: Throwable?) { _channel.cancel(cause?.let { it as? CancellationException ?: CancellationException("$classSimpleName was cancelled", it) }) } override fun handleJobException(exception: Throwable): Boolean { handleCoroutineException(context, exception) return true } } private class LazyActorCoroutine<E>( parentContext: CoroutineContext, channel: Channel<E>, block: suspend ActorScope<E>.() -> Unit ) : ActorCoroutine<E>(parentContext, channel, active = false), SelectClause2<E, SendChannel<E>> { private var continuation = block.createCoroutineUnintercepted(this, this) override fun onStart() { continuation.startCoroutineCancellable(this) } override suspend fun send(element: E) { start() return super.send(element) } @Suppress("DEPRECATION", "DEPRECATION_ERROR") override fun offer(element: E): Boolean { start() return super.offer(element) } override fun trySend(element: E): ChannelResult<Unit> { start() return super.trySend(element) } override fun close(cause: Throwable?): Boolean { // close the channel _first_ val closed = super.close(cause) // then start the coroutine (it will promptly fail if it was not started yet) start() return closed } override val onSend: SelectClause2<E, SendChannel<E>> get() = this // registerSelectSend override fun <R> registerSelectClause2(select: SelectInstance<R>, param: E, block: suspend (SendChannel<E>) -> R) { start() super.onSend.registerSelectClause2(select, param, block) } }
apache-2.0
170be0209128176a7e5635f1d535b7b5
37.523316
154
0.708944
4.409846
false
false
false
false
fboldog/anko
anko/library/static/sqlite/src/sqlTypes.kt
2
2246
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:Suppress("unused") package org.jetbrains.anko.db interface SqlType { val name: String fun render(): String operator fun plus(m: SqlTypeModifier): SqlType companion object { fun create(name: String): SqlType = SqlTypeImpl(name) } } interface SqlTypeModifier { val modifier: String companion object { fun create(modifier: String): SqlTypeModifier = SqlTypeModifierImpl(modifier) } } val NULL: SqlType = SqlTypeImpl("NULL") val INTEGER: SqlType = SqlTypeImpl("INTEGER") val REAL: SqlType = SqlTypeImpl("REAL") val TEXT: SqlType = SqlTypeImpl("TEXT") val BLOB: SqlType = SqlTypeImpl("BLOB") fun FOREIGN_KEY(columnName: String, referenceTable: String, referenceColumn: String): Pair<String, SqlType> { return "" to SqlTypeImpl("FOREIGN KEY($columnName) REFERENCES $referenceTable($referenceColumn)") } val PRIMARY_KEY: SqlTypeModifier = SqlTypeModifierImpl("PRIMARY KEY") val NOT_NULL: SqlTypeModifier = SqlTypeModifierImpl("NOT NULL") val AUTOINCREMENT: SqlTypeModifier = SqlTypeModifierImpl("AUTOINCREMENT") val UNIQUE: SqlTypeModifier = SqlTypeModifierImpl("UNIQUE") fun DEFAULT(value: String): SqlTypeModifier = SqlTypeModifierImpl("DEFAULT $value") private open class SqlTypeImpl(override val name: String, val modifiers: String? = null) : SqlType { override fun render() = if (modifiers == null) name else "$name $modifiers" override fun plus(m: SqlTypeModifier): SqlType { return SqlTypeImpl(name, if (modifiers == null) m.modifier else "$modifiers ${m.modifier}") } } private open class SqlTypeModifierImpl(override val modifier: String) : SqlTypeModifier
apache-2.0
54e4cd116091cbe1acb4691f50408964
34.09375
109
0.737311
3.93345
false
false
false
false
leafclick/intellij-community
platform/statistics/devkit/src/com/intellij/internal/statistic/actions/StatisticsEventLogToolWindow.kt
1
7343
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.internal.statistic.actions import com.intellij.diagnostic.logging.LogConsoleBase import com.intellij.diagnostic.logging.LogFilter import com.intellij.diagnostic.logging.LogFilterListener import com.intellij.diagnostic.logging.LogFilterModel import com.intellij.execution.process.ProcessOutputType import com.intellij.internal.statistic.StatisticsBundle import com.intellij.internal.statistic.actions.StatisticsEventLogToolWindow.Companion.rejectedValidationTypes import com.intellij.internal.statistic.eventLog.EventLogNotificationService import com.intellij.internal.statistic.eventLog.LogEvent import com.intellij.internal.statistic.eventLog.validator.ValidationResultType.* import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.ActionManager import com.intellij.openapi.actionSystem.DefaultActionGroup import com.intellij.openapi.progress.ProgressIndicator import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.progress.Task import com.intellij.openapi.project.Project import com.intellij.openapi.ui.SimpleToolWindowPanel import com.intellij.openapi.util.Disposer import com.intellij.openapi.wm.ToolWindowManager import com.intellij.ui.FilterComponent import com.intellij.ui.JBColor import com.intellij.util.containers.ContainerUtil import com.intellij.util.text.DateFormatUtil import java.awt.BorderLayout import java.awt.FlowLayout import javax.swing.BorderFactory import javax.swing.JComponent import javax.swing.JPanel const val eventLogToolWindowsId = "Statistics Event Log" class StatisticsEventLogToolWindow(project: Project, private val recorderId: String) : SimpleToolWindowPanel(false, true), Disposable { private val consoleLog = StatisticsEventLogConsole(project, StatisticsLogFilterModel()) private val eventLogListener: (LogEvent) -> Unit = { logEvent -> consoleLog.addLogLine(buildLogMessage(logEvent)) } init { val topPanel = JPanel(FlowLayout(FlowLayout.LEFT)) topPanel.add(consoleLog.filter) topPanel.add(createActionToolbar()) topPanel.border = BorderFactory.createMatteBorder(0, 0, 1, 0, JBColor.border()) add(topPanel, BorderLayout.NORTH) setContent(consoleLog.component) toolbar = ActionManager.getInstance().createActionToolbar("FusEventLogToolWindow", consoleLog.orCreateActions, false).component Disposer.register(this, consoleLog) EventLogNotificationService.subscribe(eventLogListener, recorderId) } private fun createActionToolbar(): JComponent { val topToolbarActions = DefaultActionGroup() topToolbarActions.add(RecordStateStatisticsEventLogAction(false)) topToolbarActions.add(OpenEventLogFileAction(recorderId)) topToolbarActions.addSeparator(StatisticsBundle.message("stats.whitelist")) topToolbarActions.add(ConfigureWhitelistAction(recorderId)) topToolbarActions.add(UpdateWhitelistAction(recorderId)) topToolbarActions.add(OpenWhitelistFileAction(recorderId)) topToolbarActions.addSeparator(StatisticsBundle.message("stats.local.whitelist")) topToolbarActions.add(AddTestGroupToLocalWhitelistAction()) topToolbarActions.add(CleanupLocalWhitelistAction()) topToolbarActions.add(OpenLocalWhitelistFileAction(recorderId)) val toolbar = ActionManager.getInstance().createActionToolbar("FusEventLogToolWindow", topToolbarActions, true) toolbar.setShowSeparatorTitles(true) return toolbar.component } override fun dispose() { EventLogNotificationService.unsubscribe(eventLogListener, recorderId) } companion object { private val systemFields = setOf("last", "created") private const val projectIdPrefixSize = 8 private const val projectIdSuffixSize = 2 private const val maxProjectIdSize = projectIdPrefixSize + projectIdSuffixSize val rejectedValidationTypes = setOf(REJECTED, INCORRECT_RULE, UNDEFINED_RULE, UNREACHABLE_WHITELIST, PERFORMANCE_ISSUE) fun buildLogMessage(logEvent: LogEvent): String { return buildString { append(DateFormatUtil.formatTimeWithSeconds(logEvent.time)) append(" - ['${logEvent.group.id}', v${logEvent.group.version}]: '${logEvent.event.id}' ") append("{") append(buildEventDataMessages(logEvent)) append("}") } } private fun buildEventDataMessages(logEvent: LogEvent): String { return logEvent.event.data .filter { (key, _) -> !systemFields.contains(key) } .map { (key, value) -> var valueAsString = value.toString() if (key == "project") { valueAsString = shortenProjectId(valueAsString) } "\"$key\":\"$valueAsString\"" } .joinToString(", ") } private fun shortenProjectId(projectId: String): String { val length = projectId.length val isRejected = rejectedValidationTypes.any { it.description == projectId } if (!isRejected && projectId.isNotBlank() && length > maxProjectIdSize) { return "${projectId.substring(0, projectIdPrefixSize)}...${projectId.substring(length - projectIdSuffixSize, length)}" } else { return projectId } } } } private class StatisticsEventLogConsole(val project: Project, val model: LogFilterModel) : LogConsoleBase(project, null, eventLogToolWindowsId, false, model) { val filter = object : FilterComponent("STATISTICS_EVENT_LOG_FILTER_HISTORY", 5) { override fun filter() { val task = object : Task.Backgroundable(project, APPLYING_FILTER_TITLE) { override fun run(indicator: ProgressIndicator) { model.updateCustomFilter(filter) } } ProgressManager.getInstance().run(task) } } override fun isActive(): Boolean { return ToolWindowManager.getInstance(project).getToolWindow(eventLogToolWindowsId)?.isVisible ?: false } fun addLogLine(line: String) { super.addMessage(line) } } class StatisticsLogFilterModel : LogFilterModel() { private val listeners = ContainerUtil.createLockFreeCopyOnWriteList<LogFilterListener>() private var customFilter: String? = null override fun getCustomFilter(): String? = customFilter override fun addFilterListener(listener: LogFilterListener?) { listeners.add(listener) } override fun removeFilterListener(listener: LogFilterListener?) { listeners.remove(listener) } override fun getLogFilters(): List<LogFilter> = emptyList() override fun isFilterSelected(filter: LogFilter?): Boolean = false override fun selectFilter(filter: LogFilter?) {} override fun updateCustomFilter(filter: String) { super.updateCustomFilter(filter) customFilter = filter for (listener in listeners) { listener.onTextFilterChange() } } override fun processLine(line: String): MyProcessingResult { val contentType = defineContentType(line) val applicable = isApplicable(line) return MyProcessingResult(contentType, applicable, null) } private fun defineContentType(line: String): ProcessOutputType { return when { rejectedValidationTypes.any { line.contains(it.description) } -> ProcessOutputType.STDERR else -> ProcessOutputType.STDOUT } } }
apache-2.0
9a6848dcb26da5408894380515fbf1c1
38.913043
140
0.758273
4.731314
false
false
false
false
leafclick/intellij-community
plugins/github/src/org/jetbrains/plugins/github/pullrequest/comment/viewer/GHPRSimpleOnesideDiffViewerReviewThreadsHandler.kt
1
2168
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.pullrequest.comment.viewer import com.intellij.diff.tools.simple.SimpleOnesideDiffViewer import com.intellij.diff.util.LineRange import com.intellij.diff.util.Range import com.intellij.openapi.editor.impl.EditorImpl import org.jetbrains.plugins.github.pullrequest.comment.GHPRCommentsUtil import org.jetbrains.plugins.github.pullrequest.comment.GHPRDiffReviewThreadMapping import org.jetbrains.plugins.github.pullrequest.comment.ui.* import org.jetbrains.plugins.github.ui.util.SingleValueModel class GHPRSimpleOnesideDiffViewerReviewThreadsHandler(commentableRangesModel: SingleValueModel<List<Range>?>, reviewThreadsModel: SingleValueModel<List<GHPRDiffReviewThreadMapping>?>, viewer: SimpleOnesideDiffViewer, componentsFactory: GHPRDiffEditorReviewComponentsFactory) : GHPRDiffViewerBaseReviewThreadsHandler<SimpleOnesideDiffViewer>(commentableRangesModel, reviewThreadsModel, viewer) { private val commentableRanges = SingleValueModel<List<LineRange>>(emptyList()) private val editorThreads = GHPREditorReviewThreadsModel() override val viewerReady: Boolean = true init { val inlaysManager = EditorComponentInlaysManager(viewer.editor as EditorImpl) GHPREditorCommentableRangesController(commentableRanges, componentsFactory, inlaysManager) { viewer.side to it } GHPREditorReviewThreadsController(editorThreads, componentsFactory, inlaysManager) } override fun markCommentableRanges(ranges: List<Range>?) { commentableRanges.value = ranges?.let { GHPRCommentsUtil.getLineRanges(it, viewer.side) }.orEmpty() } override fun showThreads(threads: List<GHPRDiffReviewThreadMapping>?) { editorThreads.update(threads ?.filter { it.diffSide == viewer.side } ?.groupBy({ it.fileLineIndex }, { it.thread }).orEmpty()) } }
apache-2.0
8ae76041880e88a5c417721c18871db0
50.619048
140
0.736162
5.199041
false
false
false
false
crispab/codekvast
product/server/intake/src/main/kotlin/io/codekvast/intake/file_import/FileImportTask.kt
1
4673
/* * Copyright (c) 2015-2022 Hallin Information Technology AB * * 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 io.codekvast.intake.file_import import io.codekvast.common.lock.Lock import io.codekvast.common.lock.LockTemplate import io.codekvast.common.logging.LoggerDelegate import io.codekvast.common.logging.LoggingUtils import io.codekvast.common.thread.NamedThreadTemplate import io.codekvast.intake.bootstrap.CodekvastIntakeSettings import io.codekvast.intake.metrics.IntakeMetricsService import lombok.RequiredArgsConstructor import lombok.extern.slf4j.Slf4j import org.springframework.scheduling.annotation.Scheduled import org.springframework.stereotype.Component import java.io.File import java.nio.file.Files import java.nio.file.Path import java.time.Instant import java.util.stream.Collectors import javax.annotation.PostConstruct /** * Scans a certain directory for files produced by the Codekvast agents and imports them to the * database. * * @author [email protected] */ @Component @Slf4j @RequiredArgsConstructor class FileImportTask( private val settings: CodekvastIntakeSettings, private val publicationImporter: PublicationImporter, private val metricsService: IntakeMetricsService, private val lockTemplate: LockTemplate ) { private val logger by LoggerDelegate() @PostConstruct fun postConstruct() { logger.info( "Looking for files in {} every {} seconds", settings.fileImportQueuePath, settings.fileImportIntervalSeconds ) } @Scheduled( initialDelayString = "\${codekvast.intake.fileImportInitialDelaySeconds:5}000", fixedRateString = "\${codekvast.intake.fileImportIntervalSeconds}000" ) fun importPublicationFiles() { NamedThreadTemplate().doInNamedThread("import", this::processQueue) } private fun processQueue() { lockTemplate.doWithLock(Lock.forTask("fileImport", 120), this::doProcessQueue) } private fun doProcessQueue() { val queue: List<File> = collectFilesInQueue(); val queueLength = queue.size if (queueLength > 0) { logger.info("Importing {} new publication files", queueLength) val startedAt = Instant.now() queue.forEach(this::doProcessFile) logger.info( "Imported {} new publications files in {}", queueLength, LoggingUtils.humanReadableDuration(startedAt, Instant.now()) ) } } private fun collectFilesInQueue(): List<File> { val queuePath = settings.fileImportQueuePath if (queuePath.mkdirs()) { logger.info("Created {}", queuePath.absolutePath) } Files.list(queuePath.toPath()).use { val result = it .peek { p -> logger.debug("Found {}", p) } .map(Path::toFile) .filter { file -> file.name.endsWith(".ser") } .collect(Collectors.toList()) metricsService.gaugePublicationQueueLength(result.size) return result } } private fun doProcessFile(file: File) { val handled = publicationImporter.importPublicationFile(file) if (handled && settings.deleteImportedFiles) { deleteFile(file) } } private fun deleteFile(file: File) { val deleted = file.delete() if (deleted) { logger.debug("Deleted {}", file) } else { logger.warn("Could not delete {}", file) } } }
mit
2daa41c3476b91eb39b9d7142948fc10
35.224806
95
0.679221
4.590373
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/meta/ModelTests.kt
1
5806
package test.meta import org.junit.Assert import org.junit.Test import slatekit.common.DateTime import slatekit.common.data.DataType import slatekit.common.ids.UPID import slatekit.meta.Reflector import slatekit.meta.models.FieldCategory import slatekit.meta.models.Model import test.setup.* import java.util.* import kotlin.reflect.KClass import kotlin.reflect.full.createType class ModelTests { @Test fun can_build_simple_model_from_reflection(){ val model = Model.load(AuthorR::class, AuthorR::id.name) ensureAuthorModel(model) } @Test fun can_build_simple_model_from_schema(){ val model = loadSchemaSpecification() ensureAuthorModel(model) } @Test fun can_build_complex_model_from_schema(){ val model = Model.load(UserWithAddress::class, UserWithAddress::id.name) val addrProp = model.fields.find { it.name == "addr" } Assert.assertTrue( addrProp != null) Assert.assertTrue( addrProp!!.model != null) Assert.assertTrue( addrProp!!.model?.dataType == Address::class) } @Test fun can_build_simple_model_with_nullable(){ val model = Model.load(AuthorRNull::class, AuthorRNull::id.name) Assert.assertTrue(model.hasId) Assert.assertTrue(model.any) ensureField(model, "id" , false, Long::class ) ensureField(model, "email" , false, String::class ) ensureField(model, "isActive" , false, Boolean::class ) ensureField(model, "age" , false, Int::class ) ensureField(model, "status" , false, StatusEnum::class ) ensureField(model, "salary" , false, Double::class ) ensureField(model, "createdAt" , false, DateTime::class ) } @Test fun can_build_simple_with_sub_objects(){ val model = Model.load(SampleEntityImmutable::class, SampleEntityImmutable::id.name) Assert.assertTrue(model.hasId) Assert.assertTrue(model.any) fun ensure(name:String, storedAs:String, type:DataType, model: Model){ Assert.assertTrue(model.lookup[name] != null) Assert.assertEquals(storedAs, model.lookup[name]?.storedName) Assert.assertEquals(type, model.lookup[name]?.dataTpe) } ensure("test_object", "test_object", DataType.DTObject, model) ensure("test_object_state", "test_object_state", DataType.DTString, model) ensure("test_object_country", "test_object_country", DataType.DTInt, model) ensure("test_object_isPOBox", "test_object_isPOBox", DataType.DTBool, model) } @Test fun can_load_nullable(){ data class Test(val str1:String, val str2:String? = null) val a1Type = Test::str1.returnType val a1Cls = Test::str1.returnType.classifier as KClass<*> val a1Type2 = Test::str1.returnType val a1Type3 =(Test::str1.returnType.classifier as KClass<*>).createType() val a2Type = Test::str2.returnType val a2Cls = Test::str2.returnType.classifier as KClass<*> val a2Type2 = Test::str2.returnType val a2Type3 =(Test::str2.returnType.classifier as KClass<*>).createType() val props = Reflector.getProperties(Test::class) val prop1 = props.get(0) val prop1Type = prop1.returnType val prop2 = props.get(1) val prop2Type = prop2.returnType Assert.assertEquals(a1Type, a1Type2) Assert.assertEquals(a1Type, a1Type3) Assert.assertEquals(a1Type, prop1Type) Assert.assertEquals(a1Type.isMarkedNullable, a1Type3.isMarkedNullable) Assert.assertEquals(a1Type.isMarkedNullable, prop1Type.isMarkedNullable) Assert.assertEquals(a2Type, a2Type2) Assert.assertEquals(a2Type, prop2Type) //Assert.assertEquals(a2Type, a2Type3) Assert.assertEquals(a2Type.isMarkedNullable, prop2Type.isMarkedNullable) } fun ensureField(model: Model, name:String, required:Boolean, tpe: KClass<*>):Unit { val field = model.fields.find { it.name == name } Assert.assertTrue(field != null) Assert.assertTrue(field!!.isRequired == required) Assert.assertTrue(field!!.dataCls == tpe) } private fun ensureAuthorModel(model: Model) { Assert.assertTrue(model.hasId) Assert.assertTrue(model.any) Assert.assertTrue(model.idField!!.name == "id") ensureField(model, "id" , true, Long::class ) ensureField(model, "createdAt" , true, DateTime::class ) ensureField(model, "createdBy" , true, Long::class ) ensureField(model, "updatedAt" , true, DateTime::class ) ensureField(model, "updatedBy" , true, Long::class ) ensureField(model, "uuid" , true, String::class ) ensureField(model, "email" , true, String::class ) ensureField(model, "isActive" , true, Boolean::class ) ensureField(model, "age" , true, Int::class ) ensureField(model, "salary" , true, Double::class ) ensureField(model, "uid" , true, UUID::class ) ensureField(model, "shardId" , true, UPID::class ) } private fun loadSchemaSpecification(): Model { val model = Model.of<Long, AuthorR>(Long::class, AuthorR::class) { field(AuthorR::id, category = FieldCategory.Id) field(AuthorR::createdAt) field(AuthorR::createdBy) field(AuthorR::updatedAt) field(AuthorR::updatedBy) field(AuthorR::uuid) field(AuthorR::email) field(AuthorR::isActive) field(AuthorR::age) field(AuthorR::salary) field(AuthorR::uid) field(AuthorR::shardId) } return model } }
apache-2.0
13d775ad113e5a479b1af7adfb7aebd8
37.450331
92
0.637961
3.850133
false
true
false
false
faceofcat/Tesla-Core-Lib
src/main/kotlin/net/ndrei/teslacorelib/inventory/IRedstoneControlledMachine.kt
1
821
package net.ndrei.teslacorelib.inventory /** * Created by CF on 2017-06-29. */ interface IRedstoneControlledMachine { val allowRedstoneControl: Boolean val redstoneControl: RedstoneControl fun toggleRedstoneControl() enum class RedstoneControl { AlwaysActive { override fun getNext() = RedstoneOn override fun canRun(getter: () -> Int) = true }, RedstoneOn { override fun getNext() = RedstoneOff override fun canRun(getter: () -> Int) = (getter() > 0) }, RedstoneOff { override fun getNext() = AlwaysActive override fun canRun(getter: () -> Int) = (getter() == 0) }; abstract fun getNext(): RedstoneControl abstract fun canRun(getter: () -> Int): Boolean } }
mit
1284b037400b23378ab6c6c3f03e6ca9
27.310345
68
0.590743
4.535912
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/reflection/properties/getDelegate/topLevelProperty.kt
2
651
// IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT import kotlin.reflect.KProperty import kotlin.reflect.jvm.isAccessible import kotlin.test.* object Delegate { var storage = "" operator fun getValue(instance: Any?, property: KProperty<*>) = storage operator fun setValue(instance: Any?, property: KProperty<*>, value: String) { storage = value } } var result: String by Delegate fun box(): String { result = "Fail" val p = (::result).apply { isAccessible = true } val d = p.getDelegate() as Delegate result = "OK" assertEquals(d, (::result).apply { isAccessible = true }.getDelegate()) return d.getValue(null, p) }
apache-2.0
d14a71e6da58893b7a9193363128f68d
27.304348
100
0.677419
3.969512
false
false
false
false
Triple-T/gradle-play-publisher
play/plugin/src/main/kotlin/com/github/triplet/gradle/play/tasks/internal/PlayApiService.kt
1
4952
package com.github.triplet.gradle.play.tasks.internal import com.github.triplet.gradle.androidpublisher.CommitResponse import com.github.triplet.gradle.androidpublisher.EditManager import com.github.triplet.gradle.androidpublisher.EditResponse import com.github.triplet.gradle.androidpublisher.PlayPublisher import com.github.triplet.gradle.common.utils.marked import com.github.triplet.gradle.common.utils.nullOrFull import com.github.triplet.gradle.common.utils.orNull import com.github.triplet.gradle.common.utils.safeCreateNewFile import org.gradle.api.file.FileSystemOperations import org.gradle.api.file.RegularFileProperty import org.gradle.api.logging.Logging import org.gradle.api.provider.Property import org.gradle.api.services.BuildService import org.gradle.api.services.BuildServiceParameters import java.io.ByteArrayInputStream import java.io.InputStream import javax.inject.Inject internal abstract class PlayApiService @Inject constructor( private val fileOps: FileSystemOperations, ) : BuildService<PlayApiService.Params> { val publisher by lazy { credentialStream().use { PlayPublisher(it, parameters.appId.get()) } } val edits by lazy { val editId = getOrCreateEditId() editIdFile.safeCreateNewFile().writeText(editId) EditManager(publisher, editId) } private val editId get() = editIdFile.readText() private val editIdFile = parameters.editIdFile.get().asFile private val editIdFileAndFriends get() = listOf(editIdFile, editIdFile.marked("commit"), editIdFile.marked("skipped")) fun scheduleCommit() { editIdFile.marked("commit").safeCreateNewFile() } fun shouldCommit(): Boolean = editIdFile.marked("commit").exists() fun commit() { val response = publisher.commitEdit(editId) if (response is CommitResponse.Failure) { if (response.failedToSendForReview()) { val retryResponse = publisher.commitEdit(editId, sendChangesForReview = false) (retryResponse as? CommitResponse.Failure)?.rethrow(response) } else { response.rethrow() } } } fun skipCommit() { editIdFile.marked("skipped").safeCreateNewFile() } fun shouldSkip(): Boolean = editIdFile.marked("skipped").exists() fun validate() { publisher.validateEdit(editId) } fun cleanup() { fileOps.delete { delete(editIdFileAndFriends) } } private fun getOrCreateEditId(): String { val editId = editIdFile.orNull()?.readText().nullOrFull()?.takeIf { editIdFile.marked("skipped").exists() } cleanup() val response = if (editId == null) { publisher.insertEdit() } else { editIdFile.marked("skipped").safeCreateNewFile() publisher.getEdit(editId) } return when (response) { is EditResponse.Success -> response.id is EditResponse.Failure -> handleFailure(response) } } private fun handleFailure(response: EditResponse.Failure): String { val appId = parameters.appId if (response.isNewApp()) { // Rethrow for clarity response.rethrow(""" |No application found for the package name '$appId'. The first version of your |app must be uploaded via the Play Console. """.trimMargin()) } else if (response.isInvalidEdit()) { Logging.getLogger(PlayApiService::class.java) .error("Failed to retrieve saved edit, regenerating.") return getOrCreateEditId() } else if (response.isUnauthorized()) { response.rethrow(""" |Service account not authenticated. See the README for instructions: |https://github.com/Triple-T/gradle-play-publisher#service-account """.trimMargin()) } else { response.rethrow() } } private fun credentialStream(): InputStream { val credsFile = parameters.credentials.asFile.orNull if (credsFile != null) { return credsFile.inputStream() } val credsString = System.getenv(PlayPublisher.CREDENTIAL_ENV_VAR) if (credsString != null) { return ByteArrayInputStream(credsString.toByteArray()) } error(""" |No credentials specified. Please read our docs for more details: |https://github.com/Triple-T/gradle-play-publisher#authenticating-gradle-play-publisher """.trimMargin()) } interface Params : BuildServiceParameters { val appId: Property<String> val credentials: RegularFileProperty val editIdFile: RegularFileProperty @Suppress("PropertyName") // Don't use this val _extensionPriority: Property<Int> } }
mit
714c9dbc0e764885aadf404dfe55eb6b
34.884058
99
0.653069
4.826511
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/dataClasses/equals/alreadyDeclaredWrongSignature.kt
2
984
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_RUNTIME data class B(val x: Int) { fun equals(other: B): Boolean = false } data class C(val x: Int) { fun equals(): Boolean = false } data class D(val x: Int) { fun equals(other: Any?, another: String): Boolean = false } data class E(val x: Int) { fun equals(x: E): Boolean = false override fun equals(x: Any?): Boolean = false } fun box(): String { B::class.java.getDeclaredMethod("equals", Any::class.java) B::class.java.getDeclaredMethod("equals", B::class.java) C::class.java.getDeclaredMethod("equals", Any::class.java) C::class.java.getDeclaredMethod("equals") D::class.java.getDeclaredMethod("equals", Any::class.java) D::class.java.getDeclaredMethod("equals", Any::class.java, String::class.java) E::class.java.getDeclaredMethod("equals", Any::class.java) E::class.java.getDeclaredMethod("equals", E::class.java) return "OK" }
apache-2.0
d60227c0a93023d98d8bcd38477ea878
25.594595
80
0.692073
3.358362
false
false
false
false
smmribeiro/intellij-community
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packagedetails/PackageDetailsPanel.kt
2
4361
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packagedetails import com.intellij.openapi.application.EDT import com.intellij.openapi.project.Project import com.intellij.ui.components.JBScrollPane import com.intellij.util.ui.UIUtil import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle import com.jetbrains.packagesearch.intellij.plugin.ui.PackageSearchUI import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.KnownRepositories import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.OperationExecutor import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.UiPackageModel import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase import com.jetbrains.packagesearch.intellij.plugin.ui.util.emptyBorder import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import java.awt.CardLayout import java.awt.Point import javax.swing.JPanel import javax.swing.JViewport import javax.swing.SwingConstants internal class PackageDetailsPanel( project: Project, operationExecutor: OperationExecutor ) : PackageSearchPanelBase(PackageSearchBundle.message("packagesearch.ui.toolwindow.tab.packages.selectedPackage")) { private var currentPanelName = EMPTY_STATE private val cardPanel = PackageSearchUI.cardPanel { border = emptyBorder() } private val headerPanel = PackageDetailsHeaderPanel(project, operationExecutor) private val infoPanel = PackageDetailsInfoPanel() private val scrollPanel = PackageSearchUI.verticalScrollPane(infoPanel).apply { viewport.scrollMode = JViewport.SIMPLE_SCROLL_MODE // https://stackoverflow.com/a/54550638/95901 UIUtil.putClientProperty(verticalScrollBar, JBScrollPane.IGNORE_SCROLLBAR_IN_INSETS, true) } private val emptyStatePanel = PackageSearchUI.borderPanel { border = emptyBorder(12) addToCenter( PackageSearchUI.createLabel().apply { text = PackageSearchBundle.message("packagesearch.ui.toolwindow.packages.details.emptyState") horizontalAlignment = SwingConstants.CENTER foreground = PackageSearchUI.getTextColorSecondary(false) } ) } init { cardPanel.add(emptyStatePanel, EMPTY_STATE) val contentPanel = PackageSearchUI.borderPanel { border = emptyBorder() addToTop(headerPanel) addToCenter(scrollPanel) } cardPanel.add(contentPanel, CONTENT_PANEL) showPanel(EMPTY_STATE) } internal data class ViewModel( val selectedPackageModel: UiPackageModel<*>?, val knownRepositoriesInTargetModules: KnownRepositories.InTargetModules, val targetModules: TargetModules, val onlyStable: Boolean, val invokeLaterScope: CoroutineScope ) fun display(viewModel: ViewModel) { if (viewModel.selectedPackageModel == null) { showPanel(EMPTY_STATE) return } headerPanel.display( PackageDetailsHeaderPanel.ViewModel( viewModel.selectedPackageModel, viewModel.knownRepositoriesInTargetModules, viewModel.targetModules, viewModel.onlyStable ) ) infoPanel.display( PackageDetailsInfoPanel.ViewModel( viewModel.selectedPackageModel.packageModel, viewModel.selectedPackageModel.selectedVersion.originalVersion, viewModel.knownRepositoriesInTargetModules.allKnownRepositories ) ) showPanel(CONTENT_PANEL) viewModel.invokeLaterScope.launch(Dispatchers.EDT) { scrollPanel.viewport.viewPosition = Point(0, 0) } } private fun showPanel(panelName: String) { if (currentPanelName == panelName) return (cardPanel.layout as CardLayout).show(cardPanel, panelName) currentPanelName = panelName } override fun build(): JPanel = cardPanel companion object { private const val EMPTY_STATE = "empty_state" private const val CONTENT_PANEL = "content_panel" } }
apache-2.0
555e58089c52da738e6457d3d38b705c
36.594828
117
0.725522
5.185493
false
false
false
false
smmribeiro/intellij-community
platform/execution-impl/src/com/intellij/execution/ui/RunContentManagerImpl.kt
1
28456
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.ui import com.intellij.execution.ExecutionBundle import com.intellij.execution.Executor import com.intellij.execution.KillableProcess import com.intellij.execution.RunnerAndConfigurationSettings import com.intellij.execution.configurations.RunConfiguration import com.intellij.execution.dashboard.RunDashboardManager import com.intellij.execution.executors.DefaultRunExecutor import com.intellij.execution.process.ProcessAdapter import com.intellij.execution.process.ProcessEvent import com.intellij.execution.process.ProcessHandler import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.execution.runners.ExecutionUtil import com.intellij.execution.ui.layout.impl.DockableGridContainerFactory import com.intellij.ide.impl.ContentManagerWatcher import com.intellij.ide.plugins.DynamicPluginListener import com.intellij.ide.plugins.IdeaPluginDescriptor import com.intellij.openapi.Disposable import com.intellij.openapi.actionSystem.DataProvider import com.intellij.openapi.actionSystem.PlatformCoreDataKeys import com.intellij.openapi.application.AppUIExecutor import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.serviceIfCreated import com.intellij.openapi.project.Project import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.IconLoader import com.intellij.openapi.util.Key import com.intellij.openapi.util.registry.Registry import com.intellij.openapi.wm.RegisterToolWindowTask import com.intellij.openapi.wm.ToolWindow import com.intellij.openapi.wm.ToolWindowManager import com.intellij.openapi.wm.ex.ToolWindowManagerListener import com.intellij.openapi.wm.impl.content.ToolWindowContentUi import com.intellij.ui.AppUIUtil import com.intellij.ui.content.* import com.intellij.ui.content.Content.CLOSE_LISTENER_KEY import com.intellij.ui.content.impl.ContentManagerImpl import com.intellij.ui.docking.DockManager import com.intellij.util.ObjectUtils import com.intellij.util.SmartList import com.intellij.util.ui.EmptyIcon import com.intellij.util.ui.UIUtil import org.jetbrains.annotations.ApiStatus import java.util.concurrent.ConcurrentLinkedDeque import java.util.function.Predicate import javax.swing.Icon private val EXECUTOR_KEY: Key<Executor> = Key.create("Executor") class RunContentManagerImpl(private val project: Project) : RunContentManager { private val toolWindowIdToBaseIcon: MutableMap<String, Icon> = HashMap() private val toolWindowIdZBuffer = ConcurrentLinkedDeque<String>() init { val containerFactory = DockableGridContainerFactory() DockManager.getInstance(project).register(DockableGridContainerFactory.TYPE, containerFactory, project) AppUIExecutor.onUiThread().expireWith(project).submit { init() } } companion object { @JvmField val ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY = Key.create<Boolean>("ALWAYS_USE_DEFAULT_STOPPING_BEHAVIOUR_KEY") @ApiStatus.Internal @JvmField val TEMPORARY_CONFIGURATION_KEY = Key.create<RunnerAndConfigurationSettings>("TemporaryConfiguration") @JvmStatic fun copyContentAndBehavior(descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) { if (contentToReuse != null) { val attachedContent = contentToReuse.attachedContent if (attachedContent != null && attachedContent.isValid) { descriptor.setAttachedContent(attachedContent) } if (contentToReuse.isReuseToolWindowActivation) { descriptor.isActivateToolWindowWhenAdded = contentToReuse.isActivateToolWindowWhenAdded } if (descriptor.processHandler?.getUserData(RunContentDescriptor.CONTENT_TOOL_WINDOW_ID_KEY) == null) { descriptor.contentToolWindowId = contentToReuse.contentToolWindowId } descriptor.isSelectContentWhenAdded = contentToReuse.isSelectContentWhenAdded } } @JvmStatic fun isTerminated(content: Content): Boolean { val processHandler = getRunContentDescriptorByContent(content)?.processHandler ?: return true return processHandler.isProcessTerminated } @JvmStatic fun getRunContentDescriptorByContent(content: Content): RunContentDescriptor? { return content.getUserData(RunContentDescriptor.DESCRIPTOR_KEY) } @JvmStatic fun getExecutorByContent(content: Content): Executor? = content.getUserData(EXECUTOR_KEY) } // must be called on EDT private fun init() { val messageBusConnection = project.messageBus.connect() messageBusConnection.subscribe(ToolWindowManagerListener.TOPIC, object : ToolWindowManagerListener { override fun stateChanged(toolWindowManager: ToolWindowManager) { toolWindowIdZBuffer.retainAll(toolWindowManager.toolWindowIdSet) val activeToolWindowId = toolWindowManager.activeToolWindowId if (activeToolWindowId != null && toolWindowIdZBuffer.remove(activeToolWindowId)) { toolWindowIdZBuffer.addFirst(activeToolWindowId) } } }) messageBusConnection.subscribe(DynamicPluginListener.TOPIC, object : DynamicPluginListener { override fun beforePluginUnload(pluginDescriptor: IdeaPluginDescriptor, isUpdate: Boolean) { processToolWindowContentManagers { _, contentManager -> val contents = contentManager.contents for (content in contents) { val runContentDescriptor = getRunContentDescriptorByContent(content) ?: continue if (runContentDescriptor.processHandler?.isProcessTerminated == true) { contentManager.removeContent(content, true) } } } } }) } @ApiStatus.Internal fun registerToolWindow(executor: Executor): ContentManager { val toolWindowManager = getToolWindowManager() val toolWindowId = executor.toolWindowId var toolWindow = toolWindowManager.getToolWindow(toolWindowId) if (toolWindow != null) { return toolWindow.contentManager } toolWindow = toolWindowManager.registerToolWindow(RegisterToolWindowTask( id = toolWindowId, icon = executor.toolWindowIcon, stripeTitle = executor::getActionName)) if (DefaultRunExecutor.EXECUTOR_ID == executor.id) { UIUtil.putClientProperty(toolWindow.component, ToolWindowContentUi.ALLOW_DND_FOR_TABS, true) } val contentManager = toolWindow.contentManager contentManager.addDataProvider(object : DataProvider { override fun getData(dataId: String): Any? { if (PlatformCoreDataKeys.HELP_ID.`is`(dataId)) return executor.helpId return null } }) ContentManagerWatcher.watchContentManager(toolWindow, contentManager) initToolWindow(executor, toolWindowId, executor.toolWindowIcon, contentManager) return contentManager } private fun initToolWindow(executor: Executor?, toolWindowId: String, toolWindowIcon: Icon, contentManager: ContentManager) { toolWindowIdToBaseIcon.put(toolWindowId, toolWindowIcon) contentManager.addContentManagerListener(object : ContentManagerListener { override fun selectionChanged(event: ContentManagerEvent) { if (event.operation != ContentManagerEvent.ContentOperation.add) { return } val content = event.content // Content manager contains contents related with different executors. // Try to get executor from content. // Must contain this user data since all content is added by this class. val contentExecutor = executor ?: getExecutorByContent(content)!! syncPublisher.contentSelected(getRunContentDescriptorByContent(content), contentExecutor) content.helpId = contentExecutor.helpId } }) Disposer.register(contentManager, Disposable { contentManager.removeAllContents(true) toolWindowIdZBuffer.remove(toolWindowId) toolWindowIdToBaseIcon.remove(toolWindowId) }) toolWindowIdZBuffer.addLast(toolWindowId) } private val syncPublisher: RunContentWithExecutorListener get() = project.messageBus.syncPublisher(RunContentManager.TOPIC) override fun toFrontRunContent(requestor: Executor, handler: ProcessHandler) { val descriptor = getDescriptorBy(handler, requestor) ?: return toFrontRunContent(requestor, descriptor) } override fun toFrontRunContent(requestor: Executor, descriptor: RunContentDescriptor) { ApplicationManager.getApplication().invokeLater(Runnable { val contentManager = getContentManagerForRunner(requestor, descriptor) val content = getRunContentByDescriptor(contentManager, descriptor) if (content != null) { contentManager.setSelectedContent(content) getToolWindowManager().getToolWindow(getToolWindowIdForRunner(requestor, descriptor))!!.show(null) } }, project.disposed) } override fun hideRunContent(executor: Executor, descriptor: RunContentDescriptor) { ApplicationManager.getApplication().invokeLater(Runnable { val toolWindow = getToolWindowManager().getToolWindow(getToolWindowIdForRunner(executor, descriptor)) toolWindow?.hide(null) }, project.disposed) } override fun getSelectedContent(): RunContentDescriptor? { for (activeWindow in toolWindowIdZBuffer) { val contentManager = getContentManagerByToolWindowId(activeWindow) ?: continue val selectedContent = contentManager.selectedContent ?: if (contentManager.contentCount == 0) { // continue to the next window if the content manager is empty continue } else { // stop iteration over windows because there is some content in the window and the window is the last used one break } // here we have selected content return getRunContentDescriptorByContent(selectedContent) } return null } override fun removeRunContent(executor: Executor, descriptor: RunContentDescriptor): Boolean { val contentManager = getContentManagerForRunner(executor, descriptor) val content = getRunContentByDescriptor(contentManager, descriptor) return content != null && contentManager.removeContent(content, true) } override fun showRunContent(executor: Executor, descriptor: RunContentDescriptor) { showRunContent(executor, descriptor, descriptor.executionId) } private fun showRunContent(executor: Executor, descriptor: RunContentDescriptor, executionId: Long) { if (ApplicationManager.getApplication().isUnitTestMode) { return } val contentManager = getContentManagerForRunner(executor, descriptor) val toolWindowId = getToolWindowIdForRunner(executor, descriptor) val oldDescriptor = chooseReuseContentForDescriptor(contentManager, descriptor, executionId, descriptor.displayName, getReuseCondition(toolWindowId)) val content: Content? if (oldDescriptor == null) { content = createNewContent(descriptor, executor) } else { content = oldDescriptor.attachedContent!! syncPublisher.contentRemoved(oldDescriptor, executor) Disposer.dispose(oldDescriptor) // is of the same category, can be reused } content.executionId = executionId content.component = descriptor.component content.setPreferredFocusedComponent(descriptor.preferredFocusComputable) content.putUserData(RunContentDescriptor.DESCRIPTOR_KEY, descriptor) content.putUserData(EXECUTOR_KEY, executor) content.displayName = descriptor.displayName descriptor.setAttachedContent(content) val toolWindow = getToolWindowManager().getToolWindow(toolWindowId) val processHandler = descriptor.processHandler if (processHandler != null) { val processAdapter = object : ProcessAdapter() { override fun startNotified(event: ProcessEvent) { UIUtil.invokeLaterIfNeeded { content.icon = ExecutionUtil.getLiveIndicator(descriptor.icon) toolWindow!!.setIcon(ExecutionUtil.getLiveIndicator(toolWindowIdToBaseIcon[toolWindowId])) } } override fun processTerminated(event: ProcessEvent) { AppUIUtil.invokeLaterIfProjectAlive(project) { val manager = getContentManagerByToolWindowId(toolWindowId) ?: return@invokeLaterIfProjectAlive val alive = isAlive(manager) setToolWindowIcon(alive, toolWindow!!) val icon = descriptor.icon content.icon = if (icon == null) executor.disabledIcon else IconLoader.getTransparentIcon(icon) } } } processHandler.addProcessListener(processAdapter) val disposer = content.disposer if (disposer != null) { Disposer.register(disposer, Disposable { processHandler.removeProcessListener(processAdapter) }) } } if (oldDescriptor == null) { contentManager.addContent(content) content.putUserData(CLOSE_LISTENER_KEY, CloseListener(content, executor)) } if (descriptor.isSelectContentWhenAdded /* also update selection when reused content is already selected */ || oldDescriptor != null && content.manager!!.isSelected(content)) { content.manager!!.setSelectedContent(content) } if (!descriptor.isActivateToolWindowWhenAdded) { return } ApplicationManager.getApplication().invokeLater(Runnable { // let's activate tool window, but don't move focus // // window.show() isn't valid here, because it will not // mark the window as "last activated" windows and thus // some action like navigation up/down in stacktrace wont // work correctly getToolWindowManager().getToolWindow(toolWindowId)!!.activate( descriptor.activationCallback, descriptor.isAutoFocusContent, descriptor.isAutoFocusContent) }, project.disposed) } private fun getContentManagerByToolWindowId(toolWindowId: String): ContentManager? { project.serviceIfCreated<RunDashboardManager>()?.let { if (it.toolWindowId == toolWindowId) { return if (toolWindowIdToBaseIcon.contains(toolWindowId)) it.dashboardContentManager else null } } return getToolWindowManager().getToolWindow(toolWindowId)?.contentManagerIfCreated } override fun getReuseContent(executionEnvironment: ExecutionEnvironment): RunContentDescriptor? { if (ApplicationManager.getApplication().isUnitTestMode) { return null } val contentToReuse = executionEnvironment.contentToReuse if (contentToReuse != null) { return contentToReuse } val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment) val reuseCondition: Predicate<Content>? val contentManager: ContentManager if (toolWindowId == null) { contentManager = getContentManagerForRunner(executionEnvironment.executor, null) reuseCondition = null } else { contentManager = getOrCreateContentManagerForToolWindow(toolWindowId, executionEnvironment.executor) reuseCondition = getReuseCondition(toolWindowId) } return chooseReuseContentForDescriptor(contentManager, null, executionEnvironment.executionId, executionEnvironment.toString(), reuseCondition) } private fun getReuseCondition(toolWindowId: String): Predicate<Content>? { val runDashboardManager = RunDashboardManager.getInstance(project) return if (runDashboardManager.toolWindowId == toolWindowId) runDashboardManager.reuseCondition else null } override fun findContentDescriptor(requestor: Executor, handler: ProcessHandler): RunContentDescriptor? { return getDescriptorBy(handler, requestor) } override fun showRunContent(info: Executor, descriptor: RunContentDescriptor, contentToReuse: RunContentDescriptor?) { copyContentAndBehavior(descriptor, contentToReuse) showRunContent(info, descriptor, descriptor.executionId) } private fun getContentManagerForRunner(executor: Executor, descriptor: RunContentDescriptor?): ContentManager { return descriptor?.attachedContent?.manager ?: getOrCreateContentManagerForToolWindow(getToolWindowIdForRunner(executor, descriptor), executor) } private fun getOrCreateContentManagerForToolWindow(id: String, executor: Executor): ContentManager { val contentManager = getContentManagerByToolWindowId(id) if (contentManager != null) { updateToolWindowDecoration(id, executor) return contentManager } val dashboardManager = RunDashboardManager.getInstance(project) if (dashboardManager.toolWindowId == id) { initToolWindow(null, dashboardManager.toolWindowId, dashboardManager.toolWindowIcon, dashboardManager.dashboardContentManager) return dashboardManager.dashboardContentManager } else { return registerToolWindow(executor) } } override fun getToolWindowByDescriptor(descriptor: RunContentDescriptor): ToolWindow? { descriptor.contentToolWindowId?.let { return getToolWindowManager().getToolWindow(it) } processToolWindowContentManagers { toolWindow, contentManager -> if (getRunContentByDescriptor(contentManager, descriptor) != null) { return toolWindow } } return null } private fun updateToolWindowDecoration(id: String, executor: Executor) { if (project.serviceIfCreated<RunDashboardManager>()?.toolWindowId == id) { return } getToolWindowManager().getToolWindow(id)?.apply { stripeTitle = executor.actionName setIcon(executor.icon) toolWindowIdToBaseIcon[id] = executor.icon } } private inline fun processToolWindowContentManagers(processor: (ToolWindow, ContentManager) -> Unit) { val toolWindowManager = getToolWindowManager() for (executor in Executor.EXECUTOR_EXTENSION_NAME.extensionList) { val toolWindow = toolWindowManager.getToolWindow(executor.id) ?: continue processor(toolWindow, toolWindow.contentManagerIfCreated ?: continue) } project.serviceIfCreated<RunDashboardManager>()?.let { val toolWindowId = it.toolWindowId if (toolWindowIdToBaseIcon.contains(toolWindowId)) { processor(toolWindowManager.getToolWindow(toolWindowId) ?: return, it.dashboardContentManager) } } } override fun getAllDescriptors(): List<RunContentDescriptor> { val descriptors: MutableList<RunContentDescriptor> = SmartList() processToolWindowContentManagers { _, contentManager -> for (content in contentManager.contents) { getRunContentDescriptorByContent(content)?.let { descriptors.add(it) } } } return descriptors } override fun selectRunContent(descriptor: RunContentDescriptor) { processToolWindowContentManagers { _, contentManager -> val content = getRunContentByDescriptor(contentManager, descriptor) ?: return@processToolWindowContentManagers contentManager.setSelectedContent(content) return } } private fun getToolWindowManager() = ToolWindowManager.getInstance(project) override fun getContentDescriptorToolWindowId(configuration: RunConfiguration?): String? { if (configuration != null) { val runDashboardManager = RunDashboardManager.getInstance(project) if (runDashboardManager.isShowInDashboard(configuration)) { return runDashboardManager.toolWindowId } } return null } override fun getToolWindowIdByEnvironment(executionEnvironment: ExecutionEnvironment): String { // Also there are some places where ToolWindowId.RUN or ToolWindowId.DEBUG are used directly. // For example, HotSwapProgressImpl.NOTIFICATION_GROUP. All notifications for this group is shown in Debug tool window, // however such notifications should be shown in Run Dashboard tool window, if run content is redirected to Run Dashboard tool window. val toolWindowId = getContentDescriptorToolWindowId(executionEnvironment) return toolWindowId ?: executionEnvironment.executor.toolWindowId } private fun getDescriptorBy(handler: ProcessHandler, runnerInfo: Executor): RunContentDescriptor? { fun find(manager: ContentManager?): RunContentDescriptor? { if (manager == null) return null val contents = if (manager is ContentManagerImpl) { manager.contentsRecursively } else { manager.contents.toList() } for (content in contents) { val runContentDescriptor = getRunContentDescriptorByContent(content) if (runContentDescriptor?.processHandler === handler) { return runContentDescriptor } } return null } find(getContentManagerForRunner(runnerInfo, null))?.let { return it } find(getContentManagerByToolWindowId(project.serviceIfCreated<RunDashboardManager>()?.toolWindowId ?: return null) ?: return null)?.let { return it } return null } fun moveContent(executor: Executor, descriptor: RunContentDescriptor) { val content = descriptor.attachedContent ?: return val oldContentManager = content.manager val newContentManager = getOrCreateContentManagerForToolWindow(getToolWindowIdForRunner(executor, descriptor), executor) if (oldContentManager == null || oldContentManager === newContentManager) return val listener = content.getUserData(CLOSE_LISTENER_KEY) if (listener != null) { oldContentManager.removeContentManagerListener(listener) } oldContentManager.removeContent(content, false) if (isAlive(descriptor)) { if (!isAlive(oldContentManager)) { updateToolWindowIcon(oldContentManager, false) } if (!isAlive(newContentManager)) { updateToolWindowIcon(newContentManager, true) } } newContentManager.addContent(content) // Close listener is added to new content manager by propertyChangeListener in BaseContentCloseListener. } private fun updateToolWindowIcon(contentManagerToUpdate: ContentManager, alive: Boolean) { processToolWindowContentManagers { toolWindow, contentManager -> if (contentManagerToUpdate == contentManager) { setToolWindowIcon(alive, toolWindow) return } } } private fun setToolWindowIcon(alive: Boolean, toolWindow: ToolWindow) { val base = toolWindowIdToBaseIcon.get(toolWindow.id) toolWindow.setIcon(if (alive) ExecutionUtil.getLiveIndicator(base) else ObjectUtils.notNull(base, EmptyIcon.ICON_13)) } private inner class CloseListener(content: Content, private val myExecutor: Executor) : BaseContentCloseListener(content, project) { override fun disposeContent(content: Content) { try { val descriptor = getRunContentDescriptorByContent(content) syncPublisher.contentRemoved(descriptor, myExecutor) if (descriptor != null) { Disposer.dispose(descriptor) } } finally { content.release() } } override fun closeQuery(content: Content, projectClosing: Boolean): Boolean { val descriptor = getRunContentDescriptorByContent(content) ?: return true if (Content.TEMPORARY_REMOVED_KEY.get(content, false)) return true val processHandler = descriptor.processHandler if (processHandler == null || processHandler.isProcessTerminated) { return true } val sessionName = descriptor.displayName val killable = processHandler is KillableProcess && (processHandler as KillableProcess).canKillProcess() val task = object : WaitForProcessTask(processHandler, sessionName, projectClosing, project) { override fun onCancel() { if (killable && !processHandler.isProcessTerminated) { (processHandler as KillableProcess).killProcess() } } } if (killable) { val cancelText = ExecutionBundle.message("terminating.process.progress.kill") task.cancelText = cancelText task.cancelTooltipText = cancelText } return askUserAndWait(processHandler, sessionName, task) } } } private fun chooseReuseContentForDescriptor(contentManager: ContentManager, descriptor: RunContentDescriptor?, executionId: Long, preferredName: String?, reuseCondition: Predicate<in Content>?): RunContentDescriptor? { var content: Content? = null if (descriptor != null) { //Stage one: some specific descriptors (like AnalyzeStacktrace) cannot be reused at all if (descriptor.isContentReuseProhibited) { return null } // stage two: try to get content from descriptor itself val attachedContent = descriptor.attachedContent if (attachedContent != null && attachedContent.isValid && (descriptor.displayName == attachedContent.displayName || !attachedContent.isPinned)) { val contents = if (contentManager is ContentManagerImpl) { contentManager.contentsRecursively } else { contentManager.contents.toList() } if (contents.contains(attachedContent)) { content = attachedContent } } } // stage three: choose the content with name we prefer if (content == null) { content = getContentFromManager(contentManager, preferredName, executionId, reuseCondition) } if (content == null || !RunContentManagerImpl.isTerminated(content) || content.executionId == executionId && executionId != 0L) { return null } val oldDescriptor = RunContentManagerImpl.getRunContentDescriptorByContent(content) ?: return null if (oldDescriptor.isContentReuseProhibited) { return null } if (descriptor == null || oldDescriptor.reusePolicy.canBeReusedBy(descriptor)) { return oldDescriptor } return null } private fun getContentFromManager(contentManager: ContentManager, preferredName: String?, executionId: Long, reuseCondition: Predicate<in Content>?): Content? { val contents = if (contentManager is ContentManagerImpl) { contentManager.contentsRecursively } else { contentManager.contents.toMutableList() } val first = contentManager.selectedContent if (first != null && contents.remove(first)) { //selected content should be checked first contents.add(0, first) } if (preferredName != null) { // try to match content with specified preferred name for (c in contents) { if (canReuseContent(c, executionId) && preferredName == c.displayName) { return c } } } // return first "good" content return contents.firstOrNull { canReuseContent(it, executionId) && (reuseCondition == null || reuseCondition.test(it)) } } private fun canReuseContent(c: Content, executionId: Long): Boolean { return !c.isPinned && RunContentManagerImpl.isTerminated(c) && !(c.executionId == executionId && executionId != 0L) } private fun getToolWindowIdForRunner(executor: Executor, descriptor: RunContentDescriptor?): String { return descriptor?.contentToolWindowId ?: executor.toolWindowId } private fun createNewContent(descriptor: RunContentDescriptor, executor: Executor): Content { val content = ContentFactory.SERVICE.getInstance().createContent(descriptor.component, descriptor.displayName, true) content.putUserData(ToolWindow.SHOW_CONTENT_ICON, java.lang.Boolean.TRUE) if (Registry.`is`("start.run.configurations.pinned", false)) content.isPinned = true content.icon = descriptor.icon ?: executor.toolWindowIcon return content } private fun getRunContentByDescriptor(contentManager: ContentManager, descriptor: RunContentDescriptor): Content? { return contentManager.contents.firstOrNull { descriptor == RunContentManagerImpl.getRunContentDescriptorByContent(it) } } private fun isAlive(contentManager: ContentManager): Boolean { return contentManager.contents.any { val descriptor = RunContentManagerImpl.getRunContentDescriptorByContent(it) descriptor != null && isAlive(descriptor) } } private fun isAlive(descriptor: RunContentDescriptor): Boolean { val handler = descriptor.processHandler return handler != null && !handler.isProcessTerminated }
apache-2.0
49334ada89172606e167f747b4d67e01
41.346726
153
0.735592
5.337835
false
false
false
false
smmribeiro/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/lang/formatter/settings/MarkdownCodeStyleSettingsProvider.kt
2
7123
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.lang.formatter.settings import com.intellij.application.options.IndentOptionsEditor import com.intellij.application.options.SmartIndentOptionsEditor import com.intellij.lang.Language import com.intellij.psi.codeStyle.* import org.intellij.plugins.markdown.MarkdownBundle import org.intellij.plugins.markdown.lang.MarkdownLanguage internal class MarkdownCodeStyleSettingsProvider : LanguageCodeStyleSettingsProvider() { override fun getLanguage(): Language = MarkdownLanguage.INSTANCE override fun createConfigurable(baseSettings: CodeStyleSettings, modelSettings: CodeStyleSettings): CodeStyleConfigurable { return MarkdownCodeStyleConfigurable(baseSettings, modelSettings) } override fun getConfigurableDisplayName() = MarkdownBundle.message("markdown.settings.name") override fun customizeSettings(consumer: CodeStyleSettingsCustomizable, settingsType: SettingsType) { @Suppress("NON_EXHAUSTIVE_WHEN") when (settingsType) { SettingsType.WRAPPING_AND_BRACES_SETTINGS -> { consumer.showStandardOptions("RIGHT_MARGIN", "WRAP_ON_TYPING") consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::WRAP_TEXT_IF_LONG.name, MarkdownBundle.message("markdown.style.settings.text.wrapping"), null, CodeStyleSettingsCustomizable.OptionAnchor.AFTER, "WRAP_ON_TYPING" ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::WRAP_TEXT_INSIDE_BLOCKQUOTES.name, MarkdownBundle.message("markdown.style.settings.text.wrapping.inside.blockquotes"), null, CodeStyleSettingsCustomizable.OptionAnchor.AFTER, "WRAP_ON_TYPING" ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::KEEP_LINE_BREAKS_INSIDE_TEXT_BLOCKS.name, MarkdownBundle.message("markdown.style.settings.line.breaks.inside.text.blocks"), MarkdownBundle.message("markdown.style.settings.group.when.reformatting") ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::INSERT_QUOTE_ARROWS_ON_WRAP.name, MarkdownBundle.message("markdown.style.settings.insert.quote.arrows"), MarkdownBundle.message("markdown.style.settings.group.when.reformatting") ) } SettingsType.BLANK_LINES_SETTINGS -> { consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::MAX_LINES_AROUND_HEADER.name, MarkdownBundle.message("markdown.style.settings.blank.lines.around.header"), CodeStyleSettingsCustomizableOptions.getInstance().BLANK_LINES ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::MAX_LINES_AROUND_BLOCK_ELEMENTS.name, MarkdownBundle.message("markdown.style.settings.blank.lines.around.block.elements"), CodeStyleSettingsCustomizableOptions.getInstance().BLANK_LINES ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::MAX_LINES_BETWEEN_PARAGRAPHS.name, MarkdownBundle.message("markdown.style.settings.blank.lines.between.paragraphs"), CodeStyleSettingsCustomizableOptions.getInstance().BLANK_LINES ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::MIN_LINES_AROUND_HEADER.name, MarkdownBundle.message("markdown.style.settings.blank.lines.around.header"), CodeStyleSettingsCustomizableOptions.getInstance().BLANK_LINES_KEEP ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::MIN_LINES_AROUND_BLOCK_ELEMENTS.name, MarkdownBundle.message("markdown.style.settings.blank.lines.around.block.elements"), CodeStyleSettingsCustomizableOptions.getInstance().BLANK_LINES_KEEP ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::MIN_LINES_BETWEEN_PARAGRAPHS.name, MarkdownBundle.message("markdown.style.settings.blank.lines.between.paragraphs"), CodeStyleSettingsCustomizableOptions.getInstance().BLANK_LINES_KEEP ) } SettingsType.SPACING_SETTINGS -> { consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::FORCE_ONE_SPACE_BETWEEN_WORDS.name, MarkdownBundle.message("markdown.style.settings.spacing.between.words"), MarkdownBundle.message("markdown.style.settings.spacing.force.one.space") ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::FORCE_ONE_SPACE_AFTER_HEADER_SYMBOL.name, MarkdownBundle.message("markdown.style.settings.spacing.after.header.symbol"), MarkdownBundle.message("markdown.style.settings.spacing.force.one.space") ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::FORCE_ONE_SPACE_AFTER_LIST_BULLET.name, MarkdownBundle.message("markdown.style.settings.spacing.after.list.marker"), MarkdownBundle.message("markdown.style.settings.spacing.force.one.space") ) consumer.showCustomOption( MarkdownCustomCodeStyleSettings::class.java, MarkdownCustomCodeStyleSettings::FORCE_ONE_SPACE_AFTER_BLOCKQUOTE_SYMBOL.name, MarkdownBundle.message("markdown.style.settings.spacing.after.blockquote.marker"), MarkdownBundle.message("markdown.style.settings.spacing.force.one.space") ) } } } override fun createCustomSettings(settings: CodeStyleSettings): CustomCodeStyleSettings { return MarkdownCustomCodeStyleSettings(settings) } override fun getIndentOptionsEditor(): IndentOptionsEditor = SmartIndentOptionsEditor() @org.intellij.lang.annotations.Language("Markdown") override fun getCodeSample(settingsType: SettingsType): String { val sampleName = when (settingsType) { SettingsType.INDENT_SETTINGS -> "indent_settings.md" SettingsType.BLANK_LINES_SETTINGS -> "blank_lines_settings.md" SettingsType.SPACING_SETTINGS -> "spacing_settings.md" else -> "default.md" } val codeSample = this::class.java.getResourceAsStream(sampleName)?.bufferedReader()?.use { it.readText() } return codeSample ?: "Failed to get predefined code sample" } }
apache-2.0
95d3a24a831fd47aaac5f7b2a17bba93
47.787671
158
0.732135
5.13925
false
false
false
false
smmribeiro/intellij-community
plugins/kotlin/idea/tests/testData/refactoring/changeSignature/GenericConstructorBefore.kt
13
357
open class C0<X>(val x: X) {} open class C1<T: Any> protected (val x1: T? = null, var x2: Double, x3: ((Int) -> Int)?) : C0<((Int) -> Int)?>(x3){ fun bar() { val y1 = x1; val y2 = x2; } } class C2 : C1<Int>(1, 2.5, null<caret>) { fun foo() { var c = C1(2, 3.5, null); c = C1(x1 = 2, x2 = 3.5, x3 = null); } }
apache-2.0
cfad2f7df83e11e9a5eea257f5affc58
24.571429
115
0.445378
2.288462
false
false
false
false
Flank/flank
test_runner/src/main/kotlin/ftl/args/ArgsFileVisitor.kt
1
2258
package ftl.args import ftl.run.exception.FlankGeneralError import java.io.IOException import java.nio.file.FileSystems import java.nio.file.FileVisitOption import java.nio.file.FileVisitResult import java.nio.file.Files import java.nio.file.LinkOption import java.nio.file.Path import java.nio.file.Paths import java.nio.file.SimpleFileVisitor import java.nio.file.attribute.BasicFileAttributes import java.util.EnumSet class ArgsFileVisitor(glob: String) : SimpleFileVisitor<Path>() { private val pathMatcher = FileSystems.getDefault().getPathMatcher(glob) private val result: MutableList<Path> = mutableListOf() @Throws(IOException::class) override fun visitFile(path: Path, attrs: BasicFileAttributes): FileVisitResult { if (pathMatcher.matches(path)) { result.add(path) } return FileVisitResult.CONTINUE } override fun visitFileFailed(file: Path?, exc: IOException?): FileVisitResult { // java.nio.file.AccessDeniedException: /tmp/systemd-private-2bc4cd4c824142ab95fb18cbb14165f5-systemd-timesyncd.service-epYUoK System.err.println("Failed to visit $file ${exc?.message}") return FileVisitResult.CONTINUE } companion object { private const val RECURSE = "/**" private const val SINGLE_GLOB = "/*" } @Throws(java.nio.file.NoSuchFileException::class) fun walk(searchPath: Path): List<Path> { val searchString = searchPath.toString() // /Users/tmp/code/flank/test_projects/android/** => /Users/tmp/code/flank/test_projects/android/ // /Users/tmp/code/* => /Users/tmp/code/ val beforeGlob = Paths.get(searchString.substringBefore(SINGLE_GLOB)) // must not follow links when resolving paths or /tmp turns into /private/tmp val realPath = try { beforeGlob.toRealPath(LinkOption.NOFOLLOW_LINKS) } catch (e: java.nio.file.NoSuchFileException) { throw FlankGeneralError("Failed to resolve path $searchPath") } val searchDepth = if (searchString.contains(RECURSE)) Integer.MAX_VALUE else 1 Files.walkFileTree(realPath, EnumSet.of(FileVisitOption.FOLLOW_LINKS), searchDepth, this) return this.result } }
apache-2.0
24459cfc9fcb82c580ec1d68efc621bd
38.614035
134
0.704606
4.143119
false
false
false
false
fabmax/kool
kool-core/src/commonMain/kotlin/de/fabmax/kool/modules/ksl/KslShader.kt
1
30912
package de.fabmax.kool.modules.ksl import de.fabmax.kool.KoolContext import de.fabmax.kool.math.* import de.fabmax.kool.modules.ksl.lang.* import de.fabmax.kool.pipeline.* import de.fabmax.kool.scene.Mesh import kotlin.reflect.KProperty open class KslShader(val program: KslProgram, val pipelineConfig: PipelineConfig) : Shader() { val uniforms = mutableMapOf<String, Uniform<*>>() val texSamplers1d = mutableMapOf<String, TextureSampler1d>() val texSamplers2d = mutableMapOf<String, TextureSampler2d>() val texSamplers3d = mutableMapOf<String, TextureSampler3d>() val texSamplersCube = mutableMapOf<String, TextureSamplerCube>() private val connectUniformListeners = mutableListOf<ConnectUniformListener>() override fun onPipelineSetup(builder: Pipeline.Builder, mesh: Mesh, ctx: KoolContext) { // prepare shader model for generating source code, also updates program dependencies (e.g. which // uniform is used by which shader stage) program.prepareGenerate() if (program.dumpCode) { program.vertexStage.hierarchy.printHierarchy() } setupAttributes(mesh, builder) setupUniforms(builder) builder.blendMode = pipelineConfig.blendMode builder.cullMethod = pipelineConfig.cullMethod builder.depthTest = pipelineConfig.depthTest builder.isWriteDepth = pipelineConfig.isWriteDepth builder.lineWidth = pipelineConfig.lineWidth builder.name = program.name builder.shaderCodeGenerator = { ctx.generateKslShader(this, it) } super.onPipelineSetup(builder, mesh, ctx) } override fun onPipelineCreated(pipeline: Pipeline, mesh: Mesh, ctx: KoolContext) { pipeline.layout.descriptorSets.forEach { descSet -> descSet.descriptors.forEach { desc -> when (desc) { is UniformBuffer -> desc.uniforms.forEach { uniforms[it.name] = it } is TextureSampler1d -> texSamplers1d[desc.name] = desc is TextureSampler2d -> texSamplers2d[desc.name] = desc is TextureSampler3d -> texSamplers3d[desc.name] = desc is TextureSamplerCube -> texSamplersCube[desc.name] = desc } } } pipeline.onUpdate += { cmd -> for (i in program.shaderListeners.indices) { program.shaderListeners[i].onUpdate(cmd) } } program.shaderListeners.forEach { it.onShaderCreated(this, pipeline, ctx) } // it can happen that onPipelineCreated is called repeatedly, in that case the connect-method of // most uniform listeners would overwrite the current uniform value with the initial default value // -> only connect listeners if not already connected // fixme: check if repeated onPipelineCreated() calls have other negative effects (at least performance is not // optimal...) connectUniformListeners.forEach { it.connect() } super.onPipelineCreated(pipeline, mesh, ctx) } private fun setupUniforms(builder: Pipeline.Builder) { val descBuilder = DescriptorSetLayout.Builder() builder.descriptorSetLayouts += descBuilder program.uniformBuffers.filter { it.uniforms.isNotEmpty() }.forEach { kslUbo -> val ubo = UniformBuffer.Builder() descBuilder.descriptors += ubo ubo.name = kslUbo.name if (kslUbo.uniforms.values.any { u -> u.value in program.vertexStage.main.dependencies.keys }) { ubo.stages += ShaderStage.VERTEX_SHADER } if (kslUbo.uniforms.values.any { u -> u.value in program.fragmentStage.main.dependencies.keys }) { ubo.stages += ShaderStage.FRAGMENT_SHADER } kslUbo.uniforms.values.forEach { uniform -> // make sure to reuse the existing Uniform<*> object in case multiple pipeline instances are // created from this KslShader instance val createdUniform: Uniform<*> = uniforms[uniform.name] ?: when(val type = uniform.value.expressionType) { is KslTypeFloat1 -> { Uniform1f(uniform.name) } is KslTypeFloat2 -> { Uniform2f(uniform.name) } is KslTypeFloat3 -> { Uniform3f(uniform.name) } is KslTypeFloat4 -> { Uniform4f(uniform.name) } is KslTypeInt1 -> { Uniform1i(uniform.name) } is KslTypeInt2 -> { Uniform2i(uniform.name) } is KslTypeInt3 -> { Uniform3i(uniform.name) } is KslTypeInt4 -> { Uniform4i(uniform.name) } //is KslTypeMat2 -> { UniformMat2f(uniform.name) } is KslTypeMat3 -> { UniformMat3f(uniform.name) } is KslTypeMat4 -> { UniformMat4f(uniform.name) } is KslTypeArray<*> -> { when (type.elemType) { is KslTypeFloat1 -> { Uniform1fv(uniform.name, uniform.arraySize) } is KslTypeFloat2 -> { Uniform2fv(uniform.name, uniform.arraySize) } is KslTypeFloat3 -> { Uniform3fv(uniform.name, uniform.arraySize) } is KslTypeFloat4 -> { Uniform4fv(uniform.name, uniform.arraySize) } is KslTypeInt1 -> { Uniform1iv(uniform.name, uniform.arraySize) } is KslTypeInt2 -> { Uniform2iv(uniform.name, uniform.arraySize) } is KslTypeInt3 -> { Uniform3iv(uniform.name, uniform.arraySize) } is KslTypeInt4 -> { Uniform4iv(uniform.name, uniform.arraySize) } is KslTypeMat3 -> { UniformMat3fv(uniform.name, uniform.arraySize) } is KslTypeMat4 -> { UniformMat4fv(uniform.name, uniform.arraySize) } else -> throw IllegalStateException("Unsupported uniform array type: ${type.elemType.typeName}") } } else -> throw IllegalStateException("Unsupported uniform type: ${type.typeName}") } ubo.uniforms += { createdUniform } } } if (program.uniformSamplers.isNotEmpty()) { program.uniformSamplers.values.forEach { sampler -> val desc = when(val type = sampler.value.expressionType) { is KslTypeDepthSampler2d -> TextureSampler2d.Builder().apply { isDepthSampler = true } is KslTypeDepthSamplerCube -> TextureSamplerCube.Builder().apply { isDepthSampler = true } is KslTypeColorSampler1d -> TextureSampler1d.Builder() is KslTypeColorSampler2d -> TextureSampler2d.Builder() is KslTypeColorSampler3d -> TextureSampler3d.Builder() is KslTypeColorSamplerCube -> TextureSamplerCube.Builder() is KslTypeArray<*> -> { when (type.elemType) { is KslTypeDepthSampler2d -> TextureSampler2d.Builder().apply { isDepthSampler = true arraySize = sampler.arraySize } is KslTypeDepthSamplerCube -> TextureSamplerCube.Builder().apply { isDepthSampler = true arraySize = sampler.arraySize } is KslTypeColorSampler1d -> TextureSampler1d.Builder().apply { arraySize = sampler.arraySize } is KslTypeColorSampler2d -> TextureSampler2d.Builder().apply { arraySize = sampler.arraySize } is KslTypeColorSampler3d -> TextureSampler3d.Builder().apply { arraySize = sampler.arraySize } is KslTypeColorSamplerCube -> TextureSamplerCube.Builder().apply { arraySize = sampler.arraySize } else -> throw IllegalStateException("Unsupported sampler array type: ${type.elemType.typeName}") } } else -> throw IllegalStateException("Unsupported sampler uniform type: ${type.typeName}") } desc.name = sampler.name if (sampler.value in program.vertexStage.main.dependencies.keys) { desc.stages += ShaderStage.VERTEX_SHADER } if (sampler.value in program.fragmentStage.main.dependencies.keys) { desc.stages += ShaderStage.FRAGMENT_SHADER } descBuilder.descriptors += desc } } // todo: push constants (is there such thing in webgpu? otherwise only relevant for vulkan...) } private fun setupAttributes(mesh: Mesh, builder: Pipeline.Builder) { var attribLocation = 0 val verts = mesh.geometry val vertLayoutAttribs = mutableListOf<VertexLayout.VertexAttribute>() val vertLayoutAttribsI = mutableListOf<VertexLayout.VertexAttribute>() var iBinding = 0 program.vertexStage.attributes.values.asSequence().filter { it.inputRate == KslInputRate.Vertex }.forEach { vertexAttrib -> val attrib = verts.attributeByteOffsets.keys.find { it.name == vertexAttrib.name } ?: throw NoSuchElementException("Mesh does not include required vertex attribute: ${vertexAttrib.name}") val off = verts.attributeByteOffsets[attrib]!! if (attrib.type.isInt) { vertLayoutAttribsI += VertexLayout.VertexAttribute(attribLocation, off, attrib) } else { vertLayoutAttribs += VertexLayout.VertexAttribute(attribLocation, off, attrib) } vertexAttrib.location = attribLocation attribLocation += attrib.props.nSlots } builder.vertexLayout.bindings += VertexLayout.Binding( iBinding++, InputRate.VERTEX, vertLayoutAttribs, verts.byteStrideF ) if (vertLayoutAttribsI.isNotEmpty()) { builder.vertexLayout.bindings += VertexLayout.Binding( iBinding++, InputRate.VERTEX, vertLayoutAttribsI, verts.byteStrideI ) } val instanceAttribs = program.vertexStage.attributes.values.filter { it.inputRate == KslInputRate.Instance } val insts = mesh.instances if (insts != null) { val instLayoutAttribs = mutableListOf<VertexLayout.VertexAttribute>() instanceAttribs.forEach { instanceAttrib -> val attrib = insts.attributeOffsets.keys.find { it.name == instanceAttrib.name } ?: throw NoSuchElementException("Mesh does not include required instance attribute: ${instanceAttrib.name}") val off = insts.attributeOffsets[attrib]!! instLayoutAttribs += VertexLayout.VertexAttribute(attribLocation, off, attrib) instanceAttrib.location = attribLocation attribLocation += attrib.props.nSlots } builder.vertexLayout.bindings += VertexLayout.Binding( iBinding, InputRate.INSTANCE, instLayoutAttribs, insts.strideBytesF ) } else if (instanceAttribs.isNotEmpty()) { throw IllegalStateException("Shader model requires instance attributes, but mesh doesn't provide any") } } class PipelineConfig { var blendMode = BlendMode.BLEND_MULTIPLY_ALPHA var cullMethod = CullMethod.CULL_BACK_FACES var depthTest = DepthCompareOp.LESS_EQUAL var isWriteDepth = true var lineWidth = 1f } protected interface ConnectUniformListener { val isConnected: Boolean? fun connect() } protected fun uniform1f(uniformName: String?, defaultVal: Float? = null): UniformInput1f = UniformInput1f(uniformName, defaultVal ?: 0f).also { connectUniformListeners += it } protected fun uniform2f(uniformName: String?, defaultVal: Vec2f? = null): UniformInput2f = UniformInput2f(uniformName, defaultVal ?: Vec2f.ZERO).also { connectUniformListeners += it } protected fun uniform3f(uniformName: String?, defaultVal: Vec3f? = null): UniformInput3f = UniformInput3f(uniformName, defaultVal ?: Vec3f.ZERO).also { connectUniformListeners += it } protected fun uniform4f(uniformName: String?, defaultVal: Vec4f? = null): UniformInput4f = UniformInput4f(uniformName, defaultVal ?: Vec4f.ZERO).also { connectUniformListeners += it } protected fun uniform1i(uniformName: String?, defaultVal: Int? = null): UniformInput1i = UniformInput1i(uniformName, defaultVal ?: 0).also { connectUniformListeners += it } protected fun uniform2i(uniformName: String?, defaultVal: Vec2i? = null): UniformInput2i = UniformInput2i(uniformName, defaultVal ?: Vec2i.ZERO).also { connectUniformListeners += it } protected fun uniform3i(uniformName: String?, defaultVal: Vec3i? = null): UniformInput3i = UniformInput3i(uniformName, defaultVal ?: Vec3i.ZERO).also { connectUniformListeners += it } protected fun uniform4i(uniformName: String?, defaultVal: Vec4i? = null): UniformInput4i = UniformInput4i(uniformName, defaultVal ?: Vec4i.ZERO).also { connectUniformListeners += it } protected fun uniformMat3f(uniformName: String?, defaultVal: Mat3f? = null): UniformInputMat3f = UniformInputMat3f(uniformName, defaultVal).also { connectUniformListeners += it } protected fun uniformMat4f(uniformName: String?, defaultVal: Mat4f? = null): UniformInputMat4f = UniformInputMat4f(uniformName, defaultVal).also { connectUniformListeners += it } protected fun texture1d(uniformName: String?, defaultVal: Texture1d? = null): UniformInputTexture1d = UniformInputTexture1d(uniformName, defaultVal).also { connectUniformListeners += it } protected fun texture2d(uniformName: String?, defaultVal: Texture2d? = null): UniformInputTexture2d = UniformInputTexture2d(uniformName, defaultVal).also { connectUniformListeners += it } protected fun texture3d(uniformName: String?, defaultVal: Texture3d? = null): UniformInputTexture3d = UniformInputTexture3d(uniformName, defaultVal).also { connectUniformListeners += it } protected fun textureCube(uniformName: String?, defaultVal: TextureCube? = null): UniformInputTextureCube = UniformInputTextureCube(uniformName, defaultVal).also { connectUniformListeners += it } protected fun uniform1fv(uniformName: String?, arraySize: Int): UniformInput1fv = UniformInput1fv(uniformName, arraySize).also { connectUniformListeners += it } protected fun uniform2fv(uniformName: String?, arraySize: Int): UniformInput2fv = UniformInput2fv(uniformName, arraySize).also { connectUniformListeners += it } protected fun uniform3fv(uniformName: String?, arraySize: Int): UniformInput3fv = UniformInput3fv(uniformName, arraySize).also { connectUniformListeners += it } protected fun uniform4fv(uniformName: String?, arraySize: Int): UniformInput4fv = UniformInput4fv(uniformName, arraySize).also { connectUniformListeners += it } protected fun texture1dArray(uniformName: String?, arraySize: Int): UniformInputTextureArray1d = UniformInputTextureArray1d(uniformName, arraySize).also { connectUniformListeners += it } protected fun texture2dArray(uniformName: String?, arraySize: Int): UniformInputTextureArray2d = UniformInputTextureArray2d(uniformName, arraySize).also { connectUniformListeners += it } protected fun texture3dArray(uniformName: String?, arraySize: Int): UniformInputTextureArray3d = UniformInputTextureArray3d(uniformName, arraySize).also { connectUniformListeners += it } protected fun textureCubeArray(uniformName: String?, arraySize: Int): UniformInputTextureArrayCube = UniformInputTextureArrayCube(uniformName, arraySize).also { connectUniformListeners += it } protected inner class UniformInput1f(val uniformName: String?, defaultVal: Float) : ConnectUniformListener { private var uniform: Uniform1f? = null private var buffer = defaultVal override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform1f)?.apply { value = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Float = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Float) { uniform?.let { it.value = value } ?: run { buffer = value } } } protected inner class UniformInput2f(val uniformName: String?, defaultVal: Vec2f) : ConnectUniformListener { private var uniform: Uniform2f? = null private val buffer = MutableVec2f(defaultVal) override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform2f)?.apply { value.set(buffer) } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Vec2f = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Vec2f) = (uniform?.value ?: buffer).set(value) } protected inner class UniformInput3f(val uniformName: String?, defaultVal: Vec3f) : ConnectUniformListener { private var uniform: Uniform3f? = null private val buffer = MutableVec3f(defaultVal) override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform3f)?.apply { value.set(buffer) } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Vec3f = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Vec3f) = (uniform?.value ?: buffer).set(value) } protected inner class UniformInput4f(val uniformName: String?, defaultVal: Vec4f) : ConnectUniformListener { private var uniform: Uniform4f? = null private val buffer = MutableVec4f(defaultVal) override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform4f)?.apply { value.set(buffer) } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Vec4f = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Vec4f) = (uniform?.value ?: buffer).set(value) } protected inner class UniformInput1i(val uniformName: String?, defaultVal: Int) : ConnectUniformListener { private var uniform: Uniform1i? = null private var buffer = defaultVal override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform1i)?.apply { value = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Int = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Int) { uniform?.let { it.value = value } ?: run { buffer = value } } } protected inner class UniformInput2i(val uniformName: String?, defaultVal: Vec2i) : ConnectUniformListener { private var uniform: Uniform2i? = null private val buffer = MutableVec2i(defaultVal) override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform2i)?.apply { value.set(buffer) } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Vec2i = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Vec2i) = (uniform?.value ?: buffer).set(value) } protected inner class UniformInput3i(val uniformName: String?, defaultVal: Vec3i) : ConnectUniformListener { private var uniform: Uniform3i? = null private val buffer = MutableVec3i(defaultVal) override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform3i)?.apply { value.set(buffer) } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Vec3i = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Vec3i) = (uniform?.value ?: buffer).set(value) } protected inner class UniformInput4i(val uniformName: String?, defaultVal: Vec4i) : ConnectUniformListener { private var uniform: Uniform4i? = null private val buffer = MutableVec4i(defaultVal) override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform4i)?.apply { value.set(buffer) } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Vec4i = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Vec4i) = (uniform?.value ?: buffer).set(value) } protected inner class UniformInputMat3f(val uniformName: String?, defaultVal: Mat3f?) : ConnectUniformListener { var uniform: UniformMat3f? = null private val buffer = Mat3f().apply { defaultVal?.let { set(it) } } override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? UniformMat3f)?.apply { value.set(buffer) } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Mat3f = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Mat3f) = (uniform?.value ?: buffer).set(value) } protected inner class UniformInputMat4f(val uniformName: String?, defaultVal: Mat4f?) : ConnectUniformListener { var uniform: UniformMat4f? = null private val buffer = Mat4f().apply { defaultVal?.let { set(it) } } override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? UniformMat4f)?.apply { value.set(buffer) } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Mat4f = uniform?.value ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Mat4f) = (uniform?.value ?: buffer).set(value) } protected inner class UniformInputTexture1d(val uniformName: String?, defaultVal: Texture1d?) : ConnectUniformListener { var uniform: TextureSampler1d? = null private var buffer: Texture1d? = defaultVal override val isConnected: Boolean = uniform != null override fun connect() { uniform = texSamplers1d[uniformName]?.apply { texture = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Texture1d? = uniform?.texture ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Texture1d?) { uniform?.let { it.texture = value } ?: run { buffer = value } } } protected inner class UniformInputTexture2d(val uniformName: String?, defaultVal: Texture2d?) : ConnectUniformListener { var uniform: TextureSampler2d? = null private var buffer: Texture2d? = defaultVal override val isConnected: Boolean = uniform != null override fun connect() { uniform = texSamplers2d[uniformName]?.apply { texture = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Texture2d? = uniform?.texture ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Texture2d?) { uniform?.let { it.texture = value } ?: run { buffer = value } } } protected inner class UniformInputTexture3d(val uniformName: String?, defaultVal: Texture3d?) : ConnectUniformListener { var uniform: TextureSampler3d? = null private var buffer: Texture3d? = defaultVal override val isConnected: Boolean = uniform != null override fun connect() { uniform = texSamplers3d[uniformName]?.apply { texture = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Texture3d? = uniform?.texture ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: Texture3d?) { uniform?.let { it.texture = value } ?: run { buffer = value } } } protected inner class UniformInputTextureCube(val uniformName: String?, defaultVal: TextureCube?) : ConnectUniformListener { var uniform: TextureSamplerCube? = null private var buffer: TextureCube? = defaultVal override val isConnected: Boolean = uniform != null override fun connect() { uniform = texSamplersCube[uniformName]?.apply { texture = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): TextureCube? = uniform?.texture ?: buffer operator fun setValue(thisRef: Any?, property: KProperty<*>, value: TextureCube?) { uniform?.let { it.texture = value } ?: run { buffer = value } } } protected inner class UniformInput1fv(val uniformName: String?, val arraySize: Int) : ConnectUniformListener { private var uniform: Uniform1fv? = null private val buffer = FloatArray(arraySize) override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform1fv)?.apply { check(length == arraySize) { "Mismatching uniform array size: $length != $arraySize" } value = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): FloatArray = uniform?.value ?: buffer } protected inner class UniformInput2fv(val uniformName: String?, val arraySize: Int) : ConnectUniformListener { private var uniform: Uniform2fv? = null private val buffer = Array(arraySize) { MutableVec2f(Vec2f.ZERO) } override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform2fv)?.apply { check(length == arraySize) { "Mismatching uniform array size: $length != $arraySize" } value = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Array<MutableVec2f> = uniform?.value ?: buffer } protected inner class UniformInput3fv(val uniformName: String?, val arraySize: Int) : ConnectUniformListener { private var uniform: Uniform3fv? = null private val buffer = Array(arraySize) { MutableVec3f(Vec3f.ZERO) } override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform3fv)?.apply { check(length == arraySize) { "Mismatching uniform array size: $length != $arraySize" } value = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Array<MutableVec3f> = uniform?.value ?: buffer } protected inner class UniformInput4fv(val uniformName: String?, val arraySize: Int) : ConnectUniformListener { private var uniform: Uniform4fv? = null private val buffer = Array(arraySize) { MutableVec4f(Vec4f.ZERO) } override val isConnected: Boolean = uniform != null override fun connect() { uniform = (uniforms[uniformName] as? Uniform4fv)?.apply { check(length == arraySize) { "Mismatching uniform array size: $length != $arraySize" } value = buffer } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Array<MutableVec4f> = uniform?.value ?: buffer } protected inner class UniformInputTextureArray1d(val uniformName: String?, val arrSize: Int) : ConnectUniformListener { var uniform: TextureSampler1d? = null private val buffer = Array<Texture1d?>(arrSize) { null } override val isConnected: Boolean = uniform != null override fun connect() { uniform = texSamplers1d[uniformName]?.apply { check(arraySize == arrSize) { "Mismatching texture array size: $arraySize != $arrSize" } for (i in textures.indices) { textures[i] = buffer[i] } } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Array<Texture1d?> = uniform?.textures ?: buffer } protected inner class UniformInputTextureArray2d(val uniformName: String?, val arrSize: Int) : ConnectUniformListener { var uniform: TextureSampler2d? = null private val buffer = Array<Texture2d?>(arrSize) { null } override val isConnected: Boolean = uniform != null override fun connect() { uniform = texSamplers2d[uniformName]?.apply { check(arraySize == arrSize) { "Mismatching texture array size: $arraySize != $arrSize" } for (i in textures.indices) { textures[i] = buffer[i] } } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Array<Texture2d?> = uniform?.textures ?: buffer } protected inner class UniformInputTextureArray3d(val uniformName: String?, val arrSize: Int) : ConnectUniformListener { var uniform: TextureSampler3d? = null private val buffer = Array<Texture3d?>(arrSize) { null } override val isConnected: Boolean = uniform != null override fun connect() { uniform = texSamplers3d[uniformName]?.apply { check(arraySize == arrSize) { "Mismatching texture array size: $arraySize != $arrSize" } for (i in textures.indices) { textures[i] = buffer[i] } } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Array<Texture3d?> = uniform?.textures ?: buffer } protected inner class UniformInputTextureArrayCube(val uniformName: String?, val arrSize: Int) : ConnectUniformListener { var uniform: TextureSamplerCube? = null private val buffer = Array<TextureCube?>(arrSize) { null } override val isConnected: Boolean = uniform != null override fun connect() { uniform = texSamplersCube[uniformName]?.apply { check(arraySize == arrSize) { "Mismatching texture array size: $arraySize != $arrSize" } for (i in textures.indices) { textures[i] = buffer[i] } } } operator fun getValue(thisRef: Any?, property: KProperty<*>): Array<TextureCube?> = uniform?.textures ?: buffer } }
apache-2.0
545b9f1744eb78d1ae208cac921ac941
56.781308
131
0.645089
4.690032
false
false
false
false
anitawoodruff/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/widget/AddTaskWidgetProvider.kt
1
2724
package com.habitrpg.android.habitica.widget import android.appwidget.AppWidgetManager import android.content.ComponentName import android.content.Context import android.widget.RemoteViews import androidx.preference.PreferenceManager import com.habitrpg.android.habitica.R import com.habitrpg.android.habitica.models.tasks.Task class AddTaskWidgetProvider : BaseWidgetProvider() { override fun layoutResourceId(): Int { return R.layout.widget_add_task } override fun onUpdate(context: Context, appWidgetManager: AppWidgetManager, appWidgetIds: IntArray) { super.onUpdate(context, appWidgetManager, appWidgetIds) // Get all ids val thisWidget = ComponentName(context, AddTaskWidgetProvider::class.java) val allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget) for (widgetId in allWidgetIds) { val options = appWidgetManager.getAppWidgetOptions(widgetId) appWidgetManager.partiallyUpdateAppWidget(widgetId, sizeRemoteViews(context, options, widgetId)) } } override fun configureRemoteViews(remoteViews: RemoteViews, widgetId: Int, columns: Int, rows: Int): RemoteViews { val selectedTaskType = getSelectedTaskType(widgetId) var addText: String? = "" var backgroundResource = R.drawable.widget_add_habit_background when (selectedTaskType) { Task.TYPE_HABIT -> { addText = context?.resources?.getString(R.string.add_habit) backgroundResource = R.drawable.widget_add_habit_background } Task.TYPE_DAILY -> { addText = context?.resources?.getString(R.string.add_daily) backgroundResource = R.drawable.widget_add_daily_background } Task.TYPE_TODO -> { addText = context?.resources?.getString(R.string.add_todo) backgroundResource = R.drawable.widget_add_todo_background } Task.TYPE_REWARD -> { addText = context?.resources?.getString(R.string.add_reward) backgroundResource = R.drawable.widget_add_reward_background } } remoteViews.setTextViewText(R.id.add_task_text, addText) remoteViews.setInt(R.id.add_task_icon, "setBackgroundResource", backgroundResource) return remoteViews } private fun getSelectedTaskType(widgetId: Int): String { val preferences = PreferenceManager.getDefaultSharedPreferences(this.context) return preferences.getString("add_task_widget_$widgetId", Task.TYPE_HABIT) ?: "" } }
gpl-3.0
2340ce10d975fdfbc72f863e495ae67a
41.238095
118
0.658223
5.03512
false
false
false
false